discarding commits after a successful merge, while keeping the code of the merge commit intact

102 Views Asked by At

There are two branches that branched from master : develop, and foo. Both develop and foo diverged from master by several commits.

foo has been merged unto develop. Now foo and develop points to the same merge commit, i.e two "streams" of commits meet into this merge commit (apologies for approximate vocabulary).

The code in this merge commit is exactly as it should be. There is nothing that should be undone.

Now let's say that nobody will ever want to checkout any of the previous commit of foo. So, we would like to "delete" these commits (i.e. not undo the modification these commit brought, just not having them in the history. In fact, looking at the history, it would look as if foo never existed, and the merge commit is no longer the meeting points of two "streams of commit").

Certainly it would have been better if foo had been squashed before merged into develop, but this did not happen.

Attempting to rebase/squash foo after the merge required to solve some conflicts. Since the code is exactly as it should be in the merge commit, solving conflicts should not be required (disclaimer: may be that this rebase was not attempted in the proper way).

Is there a way to do this ?

2

There are 2 best solutions below

0
LeGEC On

To rewrite the head commit of develop :

$ git checkout develop

# move back one commit, keep all differences in the index
#  (as if you had already 'git added' them) :
$ git reset --soft HEAD^

# commit this as a simple commit :
$ git commit
0
CleanCoder265 On

Perform interactive rebase of develop branch. Doing this would allow you to squash commits into already existing commits. Since you are rewriting history, you get to choose which commits you want to remove from history

If you are using older version than git 2.23:

git checkout develop
git rebase --interactive SHA_of_last_good_commit

If you are using git 2.23 or newer version:

git switch develop
git rebase --interactive SHA_of_last_good_commit

Run rebase with -i/--interactive parameter, with SHA1 of the last “good” commit (i.e. the parent commit of the one we want to modify). This opens interactive window, where you can see all commit from last “good” commit to the top of the current branch, listed chronologically (older commits are on top of the file