Git Branch Management and Interactive Rebasing
This guide covers how to reorganize, group, and clean up your Git commit history using interactive rebase.
Viewing Branch Commits
To view all commits in your current branch since its creation:
# If you know the base branch (e.g., main)
git log main..HEAD
# To see the exact branching point
git log $(git merge-base main HEAD)..HEAD
# For a more compact view
git log --oneline main..HEAD
# With a graphical representation
git log --graph --oneline main..HEAD
Grouping Commits by Theme
Interactive rebase allows you to reorganize commits into logical groups:
- Start an interactive rebase:
git rebase -i <commit-hash-before-your-branch>
# Or to rebase the last n commits
git rebase -i HEAD~n
- In the editor that opens, mark commits for regrouping:
pick(orp): Keep the commit as issquash(ors): Merge with the previous commit but keep its messagefixup(orf): Merge with the previous commit and discard its messagereword(orr): Keep the commit but edit its message
Example:
pick abc1234 Theme 1: First change
squash def5678 More changes for Theme 1
squash ghi9101 Another Theme 1 change
pick jkl1121 Theme 2: First change
squash mno1415 More Theme 2 changes
- Save and close the editor. Git will open another editor for each combined commit message.
Editing Commit Messages
To fix typos or improve commit messages during rebasing:
- In the interactive rebase editor, mark the commit with
reword:
pick abcd123 First commit
reword efgh456 Fix typo in documntation
pick ijkl789 Last commit
- Save and close. Git will open an editor for each
rewordcommit. - Edit the message, save, and close.
Handling Merge Conflicts
When conflicts occur during rebasing:
- Git will pause the rebase and show the conflicting files
- Open each conflicting file and look for conflict markers:
<<<<<<< HEAD
Current code
=======
Incoming code from the commit
>>>>>>> commit-hash commit message - Edit the files to resolve conflicts, removing the conflict markers
- For deleted files that conflict with modifications, decide whether to:
- Keep:
git add <file> - Remove:
git rm <file>
- Keep:
- Mark resolved files:
git add <resolved-file> - Continue the rebase:
git rebase --continue - Or abort if needed:
git rebase --abort
Pushing Rebased Changes
After rebasing, you'll need to force-push to update the remote:
# Safer force-push that checks for remote changes first
git push --force-with-lease origin branch-name
# Traditional force-push (use with caution)
git push --force origin branch-name
Best Practices
- Back up your branch before rebasing
- Avoid rebasing shared branches
- Group related commits together
- Write clear, descriptive commit messages
- Resolve conflicts carefully, preserving important changes