dave
dave

Reputation: 64727

Get changes from specific commit without changes from parent

Say I have a text file with the contents

A

I commit the file (commit febcdb0). Then I make another change and now the file contains:

A
B

And it is committed (commit 0d03344). Then I make another change:

A
B
C

And it is also committed (4077fb8). Is there a way to remove the second commit, so I end up with:

A
C

without ending up with a conflict like this:

A
<<<<<<< HEAD
B
C
======
>>>>>>> parent of 0d03344... B

That is - I specifically want the changes introduced with the last commit, but I want to discard changes from the previous commit?

I've tried interactive rebase and cherry-picking, but nothing seems to work.

So if I do:

git checkout fedcbd0
git checkout -b test
git cherry-pick 4077fb8

I get as a response:

Automatic cherry-pick failed.  After resolving the conflicts,
mark the corrected paths with 'git add <paths>' or 'git rm <paths>'
and commit the result with:

    git commit -c 4077fb8

With the contents of the file being the conflict above.

Upvotes: 1

Views: 2636

Answers (2)

Greg Hewgill
Greg Hewgill

Reputation: 994669

There's not really a good way to do this without causing a merge conflict. In commit 4077fb8, the line C is added after the line B and before the end of the file. If you try to directly apply that change to febcdb0, Git will not be able to accurately insert the new line C between B and end-of-file, because there is no line B. Because this change is not far enough away from the previous commit 0d03344, Git errs on the side of caution here and generates a merge conflict that you must resolve.

Upvotes: 1

iberbeu
iberbeu

Reputation: 16235

with git cherry-pick you can apply the changes introduced by some existing commits. In your case you can go back to the first commit and create a new branch, then use cherry-pick to apply there the last commit so that at the end you will remove the second commit

git checkout -b new_branch febcdb0

git cherry-pick 4077fb8

Upvotes: 2

Related Questions