Search code examples
gitgit-cherry-pick

Git cherry-pick commit that adds the same file


Consider the situation created by the following commands:

git init
git commit --allow-empty -m "Initial commit"
git branch first
git branch second
git checkout first
echo 1 > file
echo 2 >> file
echo 3 >> file
echo 4 >> file
git add file
git commit -m "Commit file 1 to 4"
git checkout second
echo 1 > file
echo 2 >> file
echo 3 >> file
echo 4 >> file
echo 5 >> file
echo 6 >> file
git add file
git commit -m "Commit file 1 to 6"
git checkout first
git cherry-pick second

The file on branch first contains numbers from 1 to 4 (each in its own line). The same file on the branch second contains numbers from 1 to 6. The file has been added in both branches as a new one.

Now, if I try to cherry-pick one branch onto another, my dreamed result would be (the file contents):

1
2
3
4
5
6

An acceptable result would be

1
2
3
4
<<<<<<< HEAD
=======
5
6
>>>>>>> 5c9d53e... Commit file 1 to 6

However, git always gives me:

<<<<<<< HEAD
1
2
3
4
=======
1
2
3
4
5
6
>>>>>>> 5c9d53e... Commit file 1 to 6

And I have to do all of the conflict resolution myself.

How to cherry-pick two commits that add the same file (with possibly similar content) on each other? How to make git try to analyze their contents and run into conflict only if it needs to?

Now it behaves like Hey! These commits add the same file so I will throw a whole file conflict here! I'm too lazy to look inside them.


Solution

  • After the cherry-pick one needs to run

    git checkout --conflict=merge file
    

    in order to get the acceptable content of the file, i.e.:

    1
    2
    3
    4
    <<<<<<< ours
    =======
    5
    6
    >>>>>>> theirs
    

    Neither --strategy resolve nor the Git 2.9 solved the problem for me, as suggested by @BryceDrew and @torek respectively.