DEV Community

Cover image for Unmerging a git branch, keeping post-merge commits
sahilthakare
sahilthakare

Posted on

Unmerging a git branch, keeping post-merge commits

push your code Everyday to git?

After several commits on the merged master, the client wants the work done on the commit removed, but not the commits done after the merge.
Alt Text

Say there are three branches master, branch-A and branch-B.

I work on branch-A, a friend on branch-B. Once things are finalized, we merge branch-A and branch-B with the master.

After several commits on the merged master, the client wants the work done on branch-B removed, but NOT the commits done By branch-A after the merge.

How can we do it?

Basically, you git unmerge the commits :

Checkout to the master branch

git checkout origin master
Enter fullscreen mode Exit fullscreen mode

View the commit history

git log
Enter fullscreen mode Exit fullscreen mode
$ git log
commit ca82a6dff817ec66f44342007202690a93763949
Author: Sahil <sahil@gee-mail.com>
Date:   Mon Mar 17 21:52:11 2021 -0700

    Commit by Branch-A

commit 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7
Author: Sahil <sahil@gee-mail.com>
Date:   Sat Mar 15 16:40:33 2021 -0700

    Commit by Brach-B

commit a11bef06a3f659402fe7563abf99ad00de2209e6
Author: Sahil <sahil@gee-mail.com>
Date:   Sat Mar 15 10:31:28 2021 -0700

    Initial commit
Enter fullscreen mode Exit fullscreen mode

The commit we need to unmerge is
commit 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7

git revert <hashOfMergeCommit>
Enter fullscreen mode Exit fullscreen mode

in our case

git revert 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7
Enter fullscreen mode Exit fullscreen mode

If you need to reference numerous commits in the revert command, eg:

git revert <hashOfMergeCommit1> <hashOfMergeCommit2> <hashOfMergeCommit3>...
Enter fullscreen mode Exit fullscreen mode

Congratulations!

You've segregated the code you need, but don't stop there. Continue exploring and see what you can commit.

Top comments (0)