Close

March 18, 2019

Git rebase and autosquash

This may not be new to you, but I recently discovered another cool feature of Git. Rebasing with the autosquash option allows me to keep a clean log with minimal effort. I’ve written about interactive rebasing before. This makes it even easier.

Interactive Rebasing

You want to do an interactive rebase when you have a series of commits that need be squashed together or when you want to change the order.

Let’s say you have the following commits:

1cd67b5 2019-02-25 Add a logo to the login page
d43eeb2 2019-02-24 Add the login page

But then you realize you forgot to add the login button to the login page and that there are more images to add to the login page. You could just add a new commit. There’s nothing wrong with that, but for the sake of this post, you want to add the button in the first commit and the other images in the second.

Assuming you’re working on a branch off master, create two new commits and then do:

git rebase -i master

In the editor that is opened, you will see something like this:

pick d43eeb2 Add the login page
pick 1cd67b5 Add a logo to the login page
pick 99e85fc Add missing button to login page
pick 89805a1 Add missing images

If you change that to (notice how the order has changed):

pick d43eeb2 Add the login page
f 99e85fc Add missing button to login page
pick 1cd67b5 Add a logo to the login page
s 89805a1 Add missing images

Then Git will squash the two first commits into one and use the commit message of the first one (“Add the login page”). This is a fixup. Next, Git will squash the last commit into the third and allow you to change the commit message. In this example, you might want to change the message to “Add images to login page.”

Autosquash

This process can be automated a bit further. Let’s go back to our initial situation:

1cd67b5 2019-02-25 Add a logo to the login page
d43eeb2 2019-02-24 Add the login page

Create your next two commits like this:

git commit --fixup 1cd67b5

and

git commit --squash d43eeb2

Git will now create commit messages for you that it recognizes when use use autosquash:

git rebase -i master --autosquash

Git now automatically orders the commits in the editor, and selects the correct options:

pick d43eeb2 Add the login page
f 99e85fc Add missing button to login page
pick 1cd67b5 Add a logo to the login page
s 89805a1 Add missing images

Just double check the results, save it and Git will do the rest!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.