Clean Commit History with Interactive Rebase
Squash, reorder, reword, and edit commits using interactive rebase to craft a clear, logical commit history before merging.
Prerequisites
- -Git installed
- -A feature branch with multiple commits
- -Understanding of commit history and HEAD references
Steps
Review recent commit history
Visualize the last 15 commits with a graph to understand the current history and decide how many commits to rebase.
Use --author to filter commits if working on a shared branch.
Start interactive rebase
Opens your editor with the last 5 commits. Each line starts with 'pick'. Change the action word to squash, reword, edit, drop, or fixup.
Never rebase commits that have already been pushed to a shared branch unless you coordinate with your team.
Squash fixup commits into their parent
Fixup merges a commit into the one above it and discards the fixup commit message. Squash does the same but lets you edit the combined message.
Use 'git commit --fixup=<hash>' while working to pre-mark commits for auto-squashing with 'git rebase -i --autosquash'.
Reorder commits for logical grouping
Move lines up or down to reorder commits. Git will replay them in the new order. Conflicts may arise if commits depend on each other.
Resolve any conflicts during rebase
If Git encounters conflicts while replaying commits, fix them, stage the resolutions, and continue the rebase.
Use 'git rebase --abort' at any point to cancel and return to the original state.
Force push the cleaned branch
Push the rewritten history. The --force-with-lease flag prevents overwriting commits pushed by others since your last fetch.
Always use --force-with-lease instead of --force. It is a safety net against accidentally overwriting a collaborator's work.
Full Script
FAQ
Discussion
Loading comments...