Home > OS >  Git merge untracked files
Git merge untracked files

Time:11-24

When doing a git-merge or git-pull with local untracked files that have been added remotely, the following error appears

error: The following untracked working tree files would be overwritten by merge:

Many questions have been asked about this, but all that I found wanted to overwrite the local files. However, I want to get a diff, i.e. merge the files to make sure nothing gets lost.

How could I achieve that automatically, without processing the files one by one?

CodePudding user response:

A merge, in Git, needs three—not just two—files:

  • There is a "base file": this is what you and they, whoever they may be, started with.
  • There is your file: whatever is different between the base and your file, those are your changes.
  • There is their file: whatever is different between the base and their file, those are their changes.

If you have an untracked file in your working tree, and they have a file of the same name in their commit, that's your file and their file. Where is the base file?

The git merge command won't make one up, but you can do the following:

  1. save your version of the file somewhere (perhaps outside the working tree, or rename your file from foo to foo.ours);
  2. let git merge run and produce a new merge commit (resolving conflicts if needed); then
  3. come up with a base version of your and their files.

You now have three files:

  • foo.base: you just came up with this yourself.
  • foo: this is their version of the file.
  • foo.ours: this is the one you had before you started the git merge that you have now finished.

You can now:

  1. copy foo to foo.theirs;
  2. copy foo.ours to foo;
  3. run git merge-file foo foo.base foo.theirs

This git merge-file uses the same algorithm as git merge, but takes the three files directly. The ours version is the one you name first: foo here. The merge result is written back to this file, so it's a good idea to use a copy, in case Git makes a mess of it and you decide you would rather start over.

Note that you may, if you wish, use an empty file as the merge base. If you do this, though, the result is usually not very helpful. If you decide to do that anyway, you can simply add and commit your file before merging: git merge will see the two copies of foo as both added, i.e., an add/add conflict, and do the same thing that all this fussing-about with git merge-file would have done.

CodePudding user response:

I see two options for you:

commit untracked files

  • commit the untracked files
  • git merge
  • handle the conflicts if any

move untracked files aside

  • move untracked files aside (rename them or move them somewhere else)
  • git merge will put the new files in place.
  • move the files you moved aside back to their original location.
  • git diff will show you now the differences between your version and the version you just merged in.
  • Related