Fork me on GitHub

Git branch design lesson: Git rebase and commit squashing exercise

Overview

Teaching: 0 min
Exercises: 15 min
Questions
  • How can we commit often and still arrive at an understandable history?
Objectives
  • Learn how to clean up branches.

Git rebase and commit squashing exercise

Objective

In this exercise we will practice how to squash incomplete commits into one nice commit and replay it on top of the master branch.

Motivation

This technique is useful in situations where you need to make changes to a pull request before it can be integrated.

Exercise

Start the exercise by forking and cloning this repository.

The haiku branch represents a feature branch that is to be rebased (moved) and squashed.

On the haiku branch you find a script that prints a haiku:

$ git checkout haiku
$ python main.py

This is our haiku:

On a branch ...
                  by Kobayashi Issa

              On a branch
              floating downriver
              a cricket, singing.

The haiku is great but the commit history on the haiku branch is not (for the purpose of this exercise):

$ git log --oneline

65870f9 fix a copy-paste error
47a007d completed the haiku
a3278e3 another incomplete commit
54fba21 startign to work on it (commit with a typo)
3ff39a1 forgot to add a file
7e1f903 starting working on the haiku
c50a463 initial commit

Your task is to rebase the haiku branch on top of master and squash the several small “incomplete” commits into one single self-contained cherry-pickable commit.

In other words instead of this history:

We wish to first rebase the commits:

And in a second step squash the commits into one:

Verify the steps and the result with git status and git log. Verify the history and also that the script still works after the operation.

Hints

$ git rebase master         # moves current branch commits behind master
$ git reset --soft abc123   # move current branch pointer back to commit abc123
                            # and stage all modifications that came after abc123

Bonus exercise

Try redoing the exercise with an interactive rebase instead of a soft reset. Note that you first have to undo what you did in the previous exercise, and do a git pull to retrieve the original commits on the haiku branch.

Hints

$ git reset --hard abc123   # move current branch pointer back to commit abc123
      	    	   	    # and *throw away* all modifications
$ git rebase -i master	    # interactive rebase

Bonus question

  • Imagine that the haiku repository was a real project that you were going to contribute to.
  • By rebasing and squashing commits, were you doing “the right thing”?