After committing, I always like to go through the diff before pushing the changes upstream. Just to make sure that everything is as it should be. Well, quite often I still spot some typos, commented out code that I was supposed to remove or some other minor things that need to be fixed. So I ended up running the same exact commands time and time again. First new commit for the fixes and then interactive rebase to squash the changes to the previous commit. Perfect opportunity to make an alias to save those precious keystrokes.
fixlast = !git commit -a --fixup=HEAD && GIT_EDITOR=true git rebase -i --autosquash HEAD~2
You can add the aliases to, for instance, your ~/.gitconfig file. With this alias you can easily autosquash changes to the previous commit by running git fixlast.
So let’s break it down quickly. To easily run multiple commands I’ve used ! to run shell commands instead of only git sub-commands. The first part takes all changes and creates a fixup commit for the previous commit, HEAD. The fixup argument adds fixup! prefix to the commit message which will be recognized by the autosquash later.
The second part starts interactive rebase and tells git to process all fixup and squash commits (–autosquash argument). The HEAD~2 takes two topmost commits to the rebase.
Normally, the interactive rebase opens an editor, but in this case we really just want to accept the autosquash without any manual selections. To do so GIT_EDITOR environment variable is set to true (i.e. /bin/true application). So when git wants to open the rebase editor, it just receives success return code immediately and carries on with the rebase. That’s all there is to it.
EDIT: From the comments I’ve received, there is also a more simple command for this particular case, which uses amend and reuse commit message, to accomplish the same outcome:
fixlast = commit -a --amend -C HEAD
You can also streamline working with git by having shell auto-completion and prompt that shows the current branch. Here’s how to set them up.
4 thoughts on “Git: easily auto-squash changes to previous commit”
How complicated. To modify the last commit, simply add your change in the index and call git commit –amend.
LikeLiked by 1 person
You are correct. I like to use rebase alot, so it seems that I have missed the simplest solution. Thanks for pointing it out.
You could still set the GIT_EDITOR to avoid amend editor pop up.
What about Github’s Atom project?
This post describes how to auto-squash changes to the previous commit from command line. I’m not very familiar with Atom editor, but it seems to have built-in Git integration so most likely this sort of alias commands could be added to it and used directly from the editor.