Git Branching & Merging
Master Git branching strategies: pointers, Fast-Forward vs 3-Way merges, rebasing, resolving merge conflicts, and Gitflow vs Trunk-Based.
In older version control systems, creating a branch was a slow, heavy operation. The system made a complete copy of your entire project directory on the server, consuming disk space and taking noticeable time. Because of this, developers rarely branched, which meant everyone worked on the same shared code and constantly conflicted with one another. Git changed this completely. In Git, a branch is not a copy of your files; it is simply a small text file containing a 40-character commit hash. Creating, switching between, or deleting branches takes only a couple of milliseconds, regardless of how large your project is. This lightweight branching model allows developers to create dedicated branches for every feature, bug fix, or experiment without worrying about slowing down teammates or bloating storage.
Definition
Git Branching is the practice of diverging from the main line of development to work on changes in isolation, using lightweight pointers to commits that can later be combined back into the main codebase through merging or rebasing.
Why It Matters
Without branches, multiple engineers working on the same project at the same time would constantly overwrite each other's work in progress, breaking the build for everyone. Branching allows work to happen in parallel: one engineer can spend a week building a new payment feature on a dedicated branch, while another engineer quickly fixes an urgent bug on the main branch. Once the feature is complete and verified by automated tests, it is merged cleanly back into the main branch.
How It Works
Git branching and merging work through commit pointers: 1. Branch Pointers and HEAD: A branch is simply a named pointer to a specific commit. HEAD is a special pointer that tracks which branch or commit you are currently looking at. When you make a new commit, Git creates the new commit with the current commit as its parent, and automatically moves your active branch pointer forward to the new commit. 2. Fast-Forward Merge vs 3-Way Merge: • Fast-Forward Merge: Occurs when the main branch has had no new commits since your feature branch started. Git simply slides the main branch pointer forward to match your feature branch. No extra merge commit is created. • 3-Way Merge: Occurs when both the main branch and your feature branch have new commits. Git finds their common ancestor, compares changes from both sides, and creates a new 'Merge Commit' with two parent commits. 3. Git Merge vs Git Rebase: • `git merge`: Combines branches while preserving the exact timeline of events, including the merge commit. It is safe and does not modify existing commit history. • `git rebase`: Moves the starting point of your feature branch to the latest commit on main, applying your changes one by one on top. This creates a clean, linear history, but changes commit hashes. • The Golden Rule of Rebasing: Never rebase a public branch that other team members are actively using or pulling from. 4. How Merge Conflicts Happen: A merge conflict occurs when two branches change the exact same line of code in different ways. Git pauses the merge and adds conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`), asking you to choose which code to keep.
Git Branching: Fast-Forward, 3-Way Merge, and Rebase
Key Points
- A branch in Git is just a lightweight pointer file holding a commit hash.
- HEAD points to your currently active branch or commit.
- Fast-Forward merges happen when no divergence has occurred; 3-way merges create a dedicated merge commit.
- Rebasing creates a clean, linear history by replaying commits, but rewrites commit hashes.
- The `git reflog` command is your safety net: it logs every time HEAD moves, letting you recover accidentally deleted commits.
Steps
Create and Switch to a Feature Branch
Create a new branch and switch to it using `git switch -c feat/user-auth` (or `git checkout -b feat/user-auth`).
Make Regular, Small Commits
Work on your feature in isolation, making clear, focused commits as you go.
Fetch Recent Changes from the Team
Before merging, get the latest updates from the remote repository using `git fetch origin`.
Update Your Branch with Main
Rebase or merge your branch with `origin/main` to resolve any conflicts locally before opening a pull request.
Merge and Clean Up the Branch
Once tests pass and the pull request is approved, merge the branch and delete the feature branch with `git branch -d feat/user-auth`.
Examples
The Parallel Timelines Analogy
Think of branching like a parallel timeline in science fiction. The main branch is the main timeline. When you branch off to build a feature, you enter an alternate reality where you can experiment freely. Once your invention works, you merge your timeline back into the main reality so everyone benefits.
Real-World Examples
Trunk-Based Development at Scale
Many high-performing engineering teams avoid long-lived branches. Developers work on short-lived branches that last only a few hours before merging into the main branch. Any incomplete features are hidden behind runtime Feature Flags, preventing massive, painful merge conflicts.
Technical Examples
# ─── Rebasing a Feature Branch onto Main and Handling Conflicts ───
# 1. Fetch latest changes from the remote
git fetch origin
# 2. Switch to your feature branch and start the rebase
git switch feat/payment-api
git rebase origin/main
# ─── If Git detects a conflict in src/payment.ts: ──────────────────
# CONFLICT (content): Merge conflict in src/payment.ts
# 3. Check which files need attention
git status
# 4. Open src/payment.ts and look for conflict markers:
# <<<<<<< HEAD (incoming code from main)
# const TIMEOUT_MS = 5000;
# =======
# const TIMEOUT_MS = 8000; // Updated for payment gateway
# >>>>>>> feat/payment-api (your change)
# 5. Edit the file to keep the correct logic, remove the markers, and stage:
git add src/payment.ts
# 6. Continue the rebase (do NOT run git commit here):
git rebase --continue
# Note: If you ever want to cancel the rebase and go back, run:
# git rebase --abortGit Merge (`git merge`) vs Git Rebase (`git rebase`)
| Aspect | Git Merge (`git merge`) | Git Rebase (`git rebase`) |
|---|---|---|
| History Appearance | Branches diverge and join back with merge commits | Linear, single straight line of commits |
| Commit Hashes | Preserved exactly as originally recorded | Rewritten with new commit hashes |
| Merge Commits | Creates a merge commit when branches diverge | Does not create a merge commit |
| Shared Public Branches | Safe to use on shared branches | Avoid on shared branches to prevent duplicate commits |
| Chronological Order | Reflects the exact chronological order of work | Reorders commits as if written on top of latest main |
Recovering Commits with Git Reflog
Advantages
- Lightweight: Creating, switching, and deleting branches happens almost instantly.
- Safe Isolation: Features and experiments do not interfere with working production code.
- Organized History: Rebasing and squashing allow teams to maintain readable, clean commit logs.
- Simple Experimentation: You can try risky ideas on a temporary branch and discard them easily if they fail.
Limitations
- Rebase Risks: Rebasing a shared public branch can confuse teammates by altering shared commit history.
- Conflict Accumulation: Branches left unmerged for too long accumulate large, complex merge conflicts.
Interview Questions
Explain the difference between `git merge` and `git rebase`. When should each be used?
`git merge` combines two divergent branches by creating a new merge commit that links both histories together, preserving the exact chronological sequence. `git rebase` rewrites history by moving the base of your branch to the tip of another branch and replaying your commits on top, creating a linear history. A common best practice is to rebase your local feature branch against main to keep your changes up to date, and use merge when integrating into shared branches.
Practice Questions
- Create a test repository, make conflicting edits on two branches, and practice resolving the conflict markers manually.
- Run `git reflog` in a repository to see how Git records your recent pointer movements.
