How to Rewrite Git History Correctly
Have you ever wanted to fix a problem with a git commit that wasn’t the last one you wrote? Perhaps a colleague made a typo in a ticket reference, or a spelling error, or you simply want to re-word an old commit.
If it’s the last commit, this is really easy
- In your terminal or command prompt type
git commit --amend
- Change the message to what you want
- Save the file and close the editor
If the commit was further back in the history, you previously had a big problem, and would have to rebase iteractively. This worked, but all the subsequent commits would be remade and it would look like all the commits in between had been changed too.
Your first thought might be to use git filter-branch but it’s complicated and can produce unreliable results, and it my use it still remade all of the commits in between, and it didn’t even do the rename properly, so I would rule this out.
A better solution exists in the form of git filter-repo, a fantastic addition to git that allows you to rewrite the commit without changing the rest of the commit history.
Here’s an example to change the commit message in a repo
git filter-repo --commit-callback '
msg = commit.message.decode(\"utf-8\")
newmsg = msg.replace(\"old string\", \"new string\")
commit.message = newmsg.encode(\"utf-8\")
This will replace any occurances of the “old string” with “new string”, making it really easy to make corrections. Be careful with what string you are picking, as you might get more matches than you were expecting.
I hope this helps you, and if it does, please follow me on twitter
«« Back to Articles