As git users, we know that we should “commit early, commit often.” While this is a wonderful thing to do, it does mean that from time to time we make a mistake and need to fix a commit. Maybe we forget to git add
a new file, or missed a typo. So we go ahead and git commit --amend
. Problem solved. Great.
But personally, I hate it.
For one thing, amending commits hides history. Once you amend, that past state is gone before you can properly test the new one. True, you can also restore it via git reflog
, but no-one really likes using that. It should be a last resort.
For another thing, amending is very limited. Say I am writing some C code. I write my first module, add it and commit.
|
|
I write my second module, and add it as well.
|
|
And now, after adding that second commit, I realize that I forgot to commit FirstModule.c
. git commit --amend
to the rescue? Not really. I now have to resort to the black, frightening voodoo magic called git rebase
.
First, we commit the forgotten module
|
|
And then rebase - git rebase -i HEAD~3
|
|
Change to
|
|
Save & Quit, and we’re done.
|
|
Not that hard, is it?
But still, moving between amending and rebasing can be cumbersome. Especially as most of the time there is no real need to rebase and it’s easy to forget the process. Enter git commit --fixup
(or --squash
) and git rebase -i --autosquash
.
These commands save us the work of reordering the commits and changing from pick
to fixup
or squash
. Making our rebasing work a lot easier.
I like defining the following aliases:
|
|
Using those aliases, the rebasing we did earlier would work as follows:
|
|
We’d get the following rebase automatically
|
|
Exit the editor, and be done with it.
We can use fix
as many times as we want (just go ahead and git fix HEAD -a
) before the rebase. Our log may look funny
|
|
But the rebase doesn’t care
|
|
Conclusion
Stop using git commit --amend
and start using git fix
(git commit --fixup
) instead. It is a no-fear, low-overhead alternative, and it far more flexible.
Here are the aliases again, in case you want them:
|
|