373

I have conflicting branches, branch2 branched from branch1.

Let's say when rebasing branch2 on current branch1, while resolving conflicts, I decide to take some (not all) of "their" (i.e. branch1) files as-is. How do I do that?

I tried:

git checkout branch1:foo/bar.java
fatal: reference is not a tree: TS-modules-tmp:foo/bar.java

git checkout refs/heads/branch1:foo/bar.java
fatal: reference is not a tree: refs/heads/TS-modules-tmp:foo/bar.java
Ondra Žižka
  • 36,997
  • 35
  • 184
  • 250
  • 44
    Note: if you're rebasing branch2 onto branch1, the replaying happens relative to branch1, so "theirs" is actually branch2 and "ours" is branch1. http://git.661346.n2.nabble.com/Counter-intuitive-results-for-git-show-and-git-checkout-during-rebase-with-conflict-td2370354.html – Mr Fooz May 29 '12 at 22:20
  • 2
    See also https://github.com/git/git/commit/f30301657b68561392d910f6196380dd3976549e – VonC Aug 16 '15 at 21:01
  • 2
    This just cost me about 20 hours of diligent work. I honestly thought "ours" would always be the working copy. – Theodore R. Smith Feb 19 '20 at 17:57

2 Answers2

539

You want to use:

git checkout --ours foo/bar.java
git add foo/bar.java

If you rebase a branch feature_x against main (i.e. running git rebase main while on branch feature_x), during rebasing ours refers to main and theirs to feature_x.

As pointed out in the git-rebase docs:

Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.

For further details read this thread.

iGEL
  • 13,729
  • 9
  • 53
  • 65
  • 7
    I'm sure there's a good reason why merge and rebase have opposite meaning for "ours" and "theirs", but consistency would have been so much better. – laurent Jul 23 '20 at 15:32
  • So `their` in OPs question corresponds to `--ours` in the actual command. – Siddhartha Feb 18 '21 at 22:19
  • Note that `--ours` also corresponds (more intuitively) to the 'Current Changes' in your IDE when resolving conflicts, whereas `--theirs` corresponds to 'Incoming Changes' – ut9081 Mar 02 '21 at 11:50
2

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

Adrian Cornish
  • 20,973
  • 11
  • 50
  • 74
  • 37
    This would probably be a bad idea in the middle of a rebase as it would pull the file from the head of that branch not at the detached head point you would be at in a conflicted rebase state – Clintm Sep 19 '13 at 21:39
  • @Clintm, on the other hand it is a generic answer that you can pull the file from wherever you want. `branch1` would not be a particularly good idea as noted. But one can use a desired commit id. – akostadinov Nov 28 '20 at 16:08