Mastering ‘git’ with ‘git rebase’

Keywords: #git

Introduction

Recently, I started a new job. I sat down, checked out some repos, and cracked on with some work. When I was ready to commit my first changes, I typed git log to see how my new colleagues like to format their commits… No merge commits. A handful of devs all working on one branch simultaneously? What kind of elegant version control choreography had to be involved? I knew something was up…
What I was used to (a typical git-tree using `git merge`)

Figure 1: What I was used to (a typical git-tree using git merge)

What I saw (the same git-tree using `git rebase`)

Figure 2: What I saw (the same git-tree using git rebase)

The answer? One command: git rebase.

What does ‘git rebase’ actually do?

If we imagine the scenario below:

  1. Starting on grey-branch and running git checkout -b blue-branch creates the new branch blue-branch.
  2. Commit two sets of changes with git commit
  3. Then, a teammate pushes a couple of commits to grey-branch while your changes are still in review or you haven’t had time to merge.
  4. We switch back to grey-branch and pull the changes our teammate added.
On the blue branch before ‘git rebase’

Figure 3: On the blue branch before ‘git rebase’

At this point, I was used to using git merge where I would solve any conflicts and create a merge commit, making the tree look like this:

Merging the two sets of changes with a merge

Figure 4: Merging the two sets of changes with a merge

However, instead of using git merge , this is where git rebase comes in. If I am on blue-branch in figure 3 and I use git rebase grey-branch, magic happens:

Merging the two sets of changes with `git rebase grey-branch`

Figure 5: Merging the two sets of changes with git rebase grey-branch

Isn’t that so amazing? My commits have now been ‘rebased’ on top of the commits in grey-branch .

But the magic doesn’t end there. Once I use git push blue-branch:grey-branch I get this beauty:
git elegance

Figure 6: git elegance

So satisfying… All the changes with their relevant commit info but discarding branch history and those (now) pointless merge commits!


I hope you enjoyed reading this blog post! Sign up to my newsletter here: