Git: Rewriting History with Rebase

Marcos Cannabrava
3 min readJun 3, 2020

--

No bloat, unsplash images, funny gifs. This concise post covers how to rewrite git history keeping commits and branches clean and descriptive.

# This post revolves around --rebase-merges flag which became available in git version 2.18.2. Update your git CLI if necessary.
  1. Git history full of partial-work commits and bad messages. 👎
  2. Git history with one or few commits per branch. 👍

One way to clean git history keeping the branches and rewriting commit messages is to use the git rebase interactive tool.

First use git log to find the first commit in your history then use git rebase to start rewriting history as shown below.

Step 1: git rebase -i — rebase-merges [first-commit]

The gist of this post is running rebase with interactive and rebase-merges flags from the first commit (08f64b9 in the example above). This command will open the following file on your IDE.

Step 2: editing git-rebase-todo file

Notice how you can see both Feat B and Feat A branch and all of its commits. Also several comments explain you how to edit the commits.

Step 2: r is for rewriting commit msg, s is for squashing (“deleting”)

In the image above all partial-work commits are squashed into one commit with a Good Commit Msg (please Google how to write one). The commits from other theoretical branches are kept since it’s not what the developer wanted to change in this example.

Check with your team how and if you should use git rebase in your git workflow.

Rewriting the history of your branch to push work with clear commits is ok.

Rewriting other developers’ history is not ok.

After closing the git-rebase-todo the rebase process continues and you’ll probably see screens like the ones below.

Just close it.
Delete the commit msgs you don’t want and keep the one you do want or rewrite with a Good Commit Msg!

Problems will show up. The way git rebase works is that it basically retraces the steps you took from that “first-commit” you put in the git rebase -i cmd.

When we reach a point in the code history when we had a conflict we’ll need to solve it again. (there could be a workaround and I just never bothered to look so if anyone knows please share on the comments)

Step 3: Fix conflicts…
gst = git status -> shows the files with conflicts.

You shouldn’t be having conflicts in rebase when dealing with production code. If you are, there’s some git history you probably shouldn’t be messing with.

# after resolving a conflict run:
git rebase --continue
More conflicts. Fix them. Continue. Success!
Final commit history

--

--