How to Automate Amending to Older Commits

Mark McDonald
In the weeds
Published in
2 min readFeb 21, 2019
Tools of the Trade for Mending

I like to maintain a clean git history — it helps code reviewers go step by step, and it isolates changes for the poor future souls spelunking through the code base.

Often times I make a long string of small commits, then make a small change related back to an old commit. It’s easy to squash this small change into the last commit with git commit --amend, but it’s trickier to squash into an older commit.

I follow the flow outlined by George Brocklehurst in Auto-squashing Git Commits:

  1. Find the old commit’s SHA that I want to amend to
  2. Create a ‘fixup’ commit referencing that sha: git commit --fixup $SHA
  3. Perform an interactive rebase with autosquash: git rebase --autosquash --interactive $SHA^

Autosquash is great because it sets up the ‘fixup’ commit to be squashed into the commit it references when rebasing, but it will only do this when rebasing interactively. This forces us to confirm the autosquash looks good every time using an editor.

I realized I was typing the same set of lines over and over again and always accepting the confirmation screen, so I created a small bash function:

The neat trick here is that using “cat” as our editor skips the “interactive” part of the rebase.

So now I can update an old commit without thinking about the fixup and rebase flow I need to perform. It’s as simple as git add . && amend-ng 18740ae.

--

--