Remove a merge/commit in git
Using git I merged a branch to master and now after a few weeks and many commits I'd like to remove that feature/branch. How do I do it? it doesn't seem trivial
If you want to completely remove it from you history, you could do the following:
git rebase -i <commit to remove>^
This will open your default editor (usually vi) with a list of commits, with the one you want to remove first. Remove it from the list, save, and quit. This should no rebase your branch without the commit you want to remove.
A "safer" approach is to leave the history in tact, so you can show that this feature used to exist, and was purposely removed. Just use git revert <commit to remove>
. This will create an additional patch that undoes the commit you want to get rid of. The main advantage is that you can edit the commit message, and explain why this feature is being removed.
If you want to revert a merge
commit, here is what you have to do.
- First, check the
git log
to find your merge commit's id. You'll also find multiple parent ids associated with the merge (see image below).
Note down the merge commit id shown in yellow.
The parent IDs are the ones written in the next line as Merge: parent1 parent2
. Now...
Short Story:
- Switch to branch on which the merge was made. Then Just do the
git revert <merge commit id> -m 1
which will open avi
console for entering commit message. Write, save, exit, done!
Long story:
Switch to branch on which the merge was made. In my case, it is the
test
branch and I'm trying to remove thefeature/analytics-v3
branch from it.git revert
is the command which reverts any commit. But there is a nasty trick when reverting amerge
commit. You need to enter the-m
flag otherwise it will fail. From here on, you need to decide whether you want to revert your branch and make it look like exactly it was onparent1
orparent2
via:
git revert <merge commit id> -m 1
(reverts to parent2
)
git revert <merge commit id> -m 2
(reverts to parent1
)
You can git log these parents to figure out which way you want to go and that's the root of all the confusion.