Git Reference / Rewriting history
12Rewriting history
Interactive rebase turns a messy series of commits into a clean story before you share it.
$ git rebase -i HEAD~4 pick a1b2c3d Add user model # reword = change message · squash = meld into previous · fixup = meld, drop message fixup e4f5a6b oops, typo reword 7c8d9e0 add API endpoint edit 1f2a3b4 Big commit to split drop 5c6d7e8 debug logging
Common recipes
Autosquash fixups
Mark a fix for an earlier commit; Git places it for you.
git commit --fixup=a1b2c3d git rebase -i --autosquash main
Split a commit
Mark it edit in the rebase, then:
git reset HEAD~1 git add -p && git commit -m "Part 1" git add -p && git commit -m "Part 2" git rebase --continue
Run tests on every commit
Rebase stops at the first failure.
git rebase -i --exec "npm test" main
Purge a file from all history
Use git-filter-repo (the recommended replacement for filter-branch).
pip install git-filter-repo git filter-repo --path secrets.env --invert-paths git filter-repo --replace-text expressions.txt
Leaked a secret?Rewriting history isn’t enough — anyone may have cloned it. Rotate the credential first, then clean the history.