Codingdomain.com

Git: Merging things together, revisited

Rebasing branches

As seen previously, branches can be merged together:

The result of a merge

For local commits, Git offers a better strategy: it can move the branch forward to a new starting point.

The rebase command

Before merging things, the branch can be rebased:

Moving a branch forward:
git checkout iss53
git rebase master

The result looks like this:

Effect of rebasing the iss53 branch

Git hides the old commits, and recreates them all at the end of the specified branch.

Merging it

Next, a standard merge can be done:

Merging the rebased branch:
git checkout master
git merge iss53

Now, Git mentions it does a fast-forward merge: it only has to move the master branch label forward to the newer commit of the chain.

Effects of rebase

With rebased branches, the commit log will be very clean. First you'll see all commits of one feature, followed by all commits of the next feature. This is easier to manage in the future as well.

Just to let you know...
The rebase command rewrites history. When working together with other developers, only rebase the commits you haven't shared yet.

Undoing a merge or rebase

As long as the merge or rebase exists in your own repository only, it can be immediately undone by running:

Directly undo a local git merge or rebase:
git reset --hard ORIG_HEAD

The ORIG_HEAD points to the last value of HEAD before a command like rebase, merge or reset was run.

Git keeps old commits of a rebase in the repository for a period of 30 days, so they can be recovered as well.

Coming up next

Ready for advanced work? Start to share changes with others.

blog comments powered by Disqus

Footnotes

The figures are based on the Pro Git book, chapter 3.6, which explains rebase in more detail.