Git: Fixup Your Commit
Quite often, I make a pull request with a few commits and then someone leaves a comment like: "There was a typo in your first commit". I can create another commit to fix the typo, but would rather have that fix included in the original commit. How can I do that?
Fixup Commit
Let's assume I have two commits in my branch aerabi/test
. Let's see them by doing a git log:
git log --oneline
The output is the following:
3963089 (HEAD -> aerabi/test) Add Test2.md
56b4c6d Add Test.md
And then I want to fix a typo in the file Test.md
. The way it works is as follows. I make my change in the file Test.md
and then stage it:
git add Test.md
Then I do a "fixup" commit, fixing up the first commit with the hash 56b4c6d
:
git commit --fixup 56b4c6d
A new commit is created. But since we didn't specify the commit message, let's do another log to see it:
5607ce2 (HEAD -> aerabi/test) fixup! Add Test.md
3963089 Add Test2.md
56b4c6d Add Test.md
The message is fixup! Add Test.md
. So, the same commit message as the one we are trying to fix, just with a fixup!
as the prefix.
Now we don't want this commit to lie around like this, so we do a rebase:
git rebase -i --autosquash HEAD~3
An editor opens up with the following content:
pick 56b4c6d Add Test.md
fixup 5607ce2 fixup! Add Test.md
pick 3963089 Add Test2.md
Observe that the last commit was moved and is placed right after the commit it's fixing up. And that the todo verb is already set to fixup
. Save the file and close it without modifying it. The final result is this:
b8158e4 (HEAD -> aerabi/test) Add Test2.md
487cddb Add Test.md
The last commit is merged into the first one, and its hash is changed because of that. Now we push it for further review:
git push --force-with-lease
Notes
In the rebasing context, fixup is similar to squash, only that its commit message is discarded. In the case of squash, git will ask you to merge the commit messages.
Note that we have passed the flag --autosquash
to the rebase command. We can make it default by setting the git config:
git config rebase.autosquash true
This command and more on squashing were discussed in:
Also, we had to push with --force-with-lease
because we have changed history by doing a rebase. More on differences between force and force with lease on this article:
Last Words
I write a blog post on git every week.
- Subscribe to my Medium publishes to get notified when a new Git Weekly issue is published.
- Follow me on Twitter for more updates and articles published on other platforms.