Skip to main content

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:

  1. Start an interactive rebase:
git rebase -i <commit-hash-before-your-branch>
# Or to rebase the last n commits
git rebase -i HEAD~n
  1. In the editor that opens, mark commits for regrouping:
    • pick (or p): Keep the commit as is
    • squash (or s): Merge with the previous commit but keep its message
    • fixup (or f): Merge with the previous commit and discard its message
    • reword (or r): 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
  1. 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:

  1. In the interactive rebase editor, mark the commit with reword:
pick abcd123 First commit
reword efgh456 Fix typo in documntation
pick ijkl789 Last commit
  1. Save and close. Git will open an editor for each reword commit.
  2. Edit the message, save, and close.

Handling Merge Conflicts

When conflicts occur during rebasing:

  1. Git will pause the rebase and show the conflicting files
  2. Open each conflicting file and look for conflict markers:
    <<<<<<< HEAD
    Current code
    =======
    Incoming code from the commit
    >>>>>>> commit-hash commit message
  3. Edit the files to resolve conflicts, removing the conflict markers
  4. For deleted files that conflict with modifications, decide whether to:
    • Keep: git add <file>
    • Remove: git rm <file>
  5. Mark resolved files:
    git add <resolved-file>
  6. Continue the rebase:
    git rebase --continue
  7. 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