Snowball Snowball - 2 months ago 17
Git Question

How merge branch with specific commit

I thought I created a new branch for a specific commit, but actually I left it on the master branch and made my latest commits on the new branch instead.

So now I want to remove the last commit on the master branch and merge my new commits with the master branch before that specific commit.

Probabbly easier to understand with an image:

enter image description here

Answer

In order to merge the branch "before" a commit on an existing branch a few things need to be done.

In Git every commit contains the hash of it's parent in it's own hash to ensure integrity. This means that the last commit you want to merge something in between you will have to rename everything else.

Idea

The idea is to store the current "master" away as a branch called "old-master". We know set master to the desired commit and do the merge. We can then decide to recover the commits that are on old master but not on the new master (the f0c5f03 in your case) or just leave it.

Solution

$ git checkout master
$ git branch old-master   # let's call our current master in additon "old-master"
$ git reset f2097eb       # reset master (currently checked out) to this commit. See [git reset][1].

Your graph now looks like

  o old-master
/ ^ this is commit f0c5f03
o master
 \
  o - o .... o 12columns

Lets do the merge:

$ git merge 12columns

In your case this is a fast forward. So no actual merge is performed. Our graph is now:

  o old-master
 /
o - ...... o # master

Deletion

We can now decide. Do you want to throw away the old-master or put it on top:

$ git branch -D old-master   # Remove the old commit f0c5f03

Recovering

or checkout the old master and rebase it on top

$ git checkout old-master
$ git rebase master

This results in:

o - o ...... o - o # master
^ f2097eb        ^ Commit f0c5f03 but now with new commit hash.
Comments