We have had a small problem in our team. One dev had to include some changes in our development branch. Before doing so, he accidentally merged a feature branch (which shouldn't be merged then) and kept on working over those changes, generating a couple of commits after the merge.
Now we want to keep those changes, but apply them to the commit before the merge was done. To keep it clear:
A (+b, +a)
|
B (+a)
|
C (merge commit)
|\
D \
| E (feature branch)
| /
|/
F
What we want to have his changes (+a,+b) applied over commit D . The equivalent to:
C (+a,+b)
|
D
| E (feature branch)
| /
|/
F
How can we commit a change to dismiss a previous merge keeping local changes?
How to Undo a Merge Commit in Git. You can use the Git reset command to undo a merge. Firstly, you need to check for the commit hash (or id) so you can use it to go back to the previous commit. To check for the hash, run git log or git reflog .
Do git rebase -i <sha before the branches diverged> this will allow you to remove the merge commit and the log will be one single line as you wanted. You can also delete any commits that you do not want any more.
Use git-reset or git merge --abort to cancel a merge that had conflicts. Please note that all the changes will be reset, and this operation cannot be reverted, so make sure to commit or git-stash all your changes before you start a merge.
This is a job for git rebase -i
. Run:
git rebase -i F
You'll be presented with a list of commits in ${EDITOR}
, like so:
pick 334ad92 D
pick fb54c42 E
pick 6901e51 B
pick 6c61a52 A
# Rebase eea2847..6c61a52 onto eea2847
#
# (more instructions here)
Delete the pick fb54c42 E
line to remove that commit. (Also, if you want A
and B
to be combined into a single commit, you can change the pick
command to squash
-- squash 6c61a52 A
). Save and close the file and your branches will be in the state you wish.
Note that this will change history. This means that you'll need to do a git push -f
if you've already pushed the branch anywhere, and it'll mess with anyone else who's been collaborating on this branch. If that's an issue, you can git revert
the merge commit instead:
git revert -m 1 C
The -m 1
argument tells git to revert against the first parent of the commit, which is the side that was merged into (D
, in your diagram).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With