fracz
fracz

Reputation: 21258

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.

Upvotes: 3

Views: 387

Answers (2)

fracz
fracz

Reputation: 21258

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.

Upvotes: 2

Bryce Drew
Bryce Drew

Reputation: 6729

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

#Here is where I did edits:

git cherry-pick --strategy resolve second
git diff HEAD..second
git add file
git commit -C second

You are using the default merge strategy: recursive. The resolve merge strategy will produce the conflict in the state you might want.

$ git diff HEAD..second
diff --git a/file b/file
index 94ebaf9..b414108 100644
--- a/file
+++ b/file
@@ -2,3 +2,5 @@
 2
 3
 4
+5
+6

$ cat file
1
2
3
4
5
6

Upvotes: 2

Related Questions