Hands-On: Clean Up a Messy History
Hands-On: Clean Up a Messy History
Make three noisy commits on a feature branch, then squash them into one conventional commit with interactive rebase.
before after fixup + amend
A ← wip ← more ← typo A ← docs: mention a future health endpoint
feat/health-header feat/health-header
Setup
cd ~/desk/desk-api
git switch main
git switch -c feat/health-headerThree messy commits
echo "# health" >> README.md
git add README.md
git commit -m "wip"
echo "Health endpoint later." >> README.md
git add README.md
git commit -m "more"
echo "See src/ping.py for now." >> README.md
git add README.md
git commit -m "typo fix later"git log --oneline -5Squash with GNU sed (Linux)
Keep the first of the three; fixup the rest:
GIT_SEQUENCE_EDITOR="sed -i '2,\$s/^pick /fixup /'" git rebase -i HEAD~3
git log --oneline -5One commit remains, message still wip. Retitle:
git commit --amend -m "docs: mention a future health endpoint"
git log --oneline -3Optional: rebase onto main
If main moved, replay this one commit:
git rebase main
git log --oneline --graph --decorate -8Cleanup
git switch main
git merge --ff-only feat/health-header
git branch -d feat/health-headerIf --ff-only refuses, main moved; rebase the feature first or merge.
Done when
git logonmainshows onedocs:commit for this work, not threewipsgit statusis clean- The feature branch is deleted
Next chapter: copy a single commit onto another branch (cherry-pick) and undo a published commit (revert).