Git Merge, Rebase, and Squash: Key Differences and Best Practices

Jun 22, 2024

Git Merge, Rebase, and Squash: Key Differences and Best Practices

Introduction

  • Common issue: Deciding whether to use git merge, git rebase, or squash commits
  • Objective: Breakdown the key differences and when to use each command in a workflow

Main Content

Scenario Setup

  • *Feature branch vs. Main branch:
    • Created new feature branch from main
    • Feature branch commits: A, B, C
    • Main branch commits: D, E
  • Visual analogy: Two branches of a tree growing in different directions
  • Goal: Keep feature branch up to date with main using git merge or git rebase

Git Merge

  • Description: Pulls in latest changes from main into the feature branch, creating a new "merge commit"
  • Analogy: Tying two branches together with a knot
  • Result: Complete picture of commit history but can become messy with many merge commits

Git Rebase

  • Description: Changes the base of the feature branch to the latest commit on main and replays changes from there
  • Result: Clean, straightforward commit history

Getting Feature Branch Back to Main

  • Options:
    • Git Merge: Creates a new "merge commit" that ties histories of both branches
      • Analogy: Knot in the rope showing where branches joined
      • Note: Can result in messy history with multiple merge commits
    • Git Rebase and Fast-Forward Merge: Moves feature branch's changes to the tip of main; then fast-forward merge
      • Analogy: Straightening out the rope for a linear history
    • Squash Commits: Combines all feature branch commits into a single commit
      • Result: Linear history in main, loss of detailed commit history
      • Popularity: Common on platforms like GitHub for tidy main branch history
      • Hybrid approach: Preserves detailed commit history in the feature branch

Summary

  • Git Merge: Provides a complete picture of commit history and branch evolution
  • Git Rebase: Tidies up history by moving commits to the main branch tip
  • Squashing: Consolidates commits for clean, linear main branch history at the cost of detailed history

Considerations

  • Team Values: Clean history vs detailed commit history
  • Choosing strategy: No one-size-fits-all; evaluate pros and cons based on team needs

Call to Action

  • Discussion: Have you used these strategies? Which one do you prefer and why?
  • Newsletter: Subscribe to the system design newsletter at blog.bytebytego.com, trusted by 450,000 readers