Fixing a commit with fixup and autosquash

Purpose

I sometimes run into a issue where I see a mistake I made in a prior commit. Rather than adding an additional commit that just fixes the issue, with a few git commands we can add a fix for that mistake right into the existing commit and keep our commit log clean.

How it works

Let's say you have the following git history:

$ git log --oneline --abbrev-commit
4624e09 (HEAD -> main) Commit 2 - Add feature 2
83abe29 Commit 1 - Add feature 1
bd762a2 Initial commit

You realize you made a mistake with feature 1, and you need to tweak the code a bit, but you don't want to introduce an additional commit. Here's the steps:

  1. Make the required changes
  2. Stage the changes with git add
  3. git commit --fixup $commitToFix
  4. git rebase --autosquash --interactive $commitToFix

In our example, we'd run these:

  1. git add .
  2. git commit --fixup 83abe29
  3. git rebase --autosquash --interactive 83abe29
  4. In the interactive rebate, set your fixup! commit to squash
85d9d40 (HEAD -> main) Commit 2 - Add feature 2
83abe29 Commit 1 - Add feature 1
bd762a2 Initial commit

Note that the commit hash for Commit 2 is different. Since we rebased with 83abe29 as the base, further commits will have different hashes since they're based on different commits.