Git Rebase

Modifying history

I find the man page of git rebase rather confusing.

I often use git rebase -i some-ancestor to reorder, reword, fixup or squash commits.

Every now and then, I have the special case where a branch topic shall be put directly ontop of the branch it branched off (e.g. master). I.e. we want to transform the left layout to the one shown on the right.

   o---o---o---o  master             o---o---o---o  master
        \                    --->                 \
         o---o---o  topic                          o'--o'--o'  topic

This is done by executing git rebase master topic when topic is checked out.

But only rarely do I need to put a distinct series of commits from one branch onto another branch, so I haven’t memorized the command yet.

Understanding the command is difficult though. The man page is great in that it has many examples, but it covers the commands very generically.

One can resort to cherry-pick the commits in order, but that doesn’t scale well.

So below is my try to rebase (i.e. reorder, reword, fixup, and a lot of drop) the man page to make sense for the specific use case described above.

git rebase [-i | --interactive] [--onto <newbase>] [<upstream> [<branch>]]

Lets you put a series of commits (between upstream and branch) onto newbase

Here is how you would transplant a topic branch based on one branch to another, to pretend that you forked the topic branch from the latter branch, using rebase –onto.

First let’s assume your topic is based on branch next. For example, a feature developed in topic depends on some functionality which is found in next.

   o---o---o---o---o  master
        \
         o---o---o---o---o  next
                          \
                           o---o---o  topic

We want to make topic forked from branch master; for example, because the functionality on which topic depends was merged into the more stable master branch. We want our tree to look like this:

   o---o---o---o---o  master
       |            \
       |             o'--o'--o'  topic
        \
         o---o---o---o---o  next

We can get this using the following command format:

 git rebase --onto <newbase> <upstream> <branch>

The command with the branch names of the example is then:

 git rebase --onto  master     next      topic

Bonus Tip

Joseph Wynn wrote a great under-the-hood description of git.



Home