Ch 03Branching Workflows & Resolving Merge Conflicts
Chapter 03 of 05·25 min

Branching Workflows & Resolving Merge Conflicts

In professional engineering teams, developers never commit directly to the primary production branch (`main`). Instead, each new feature, bug fix, or data experiment is isolated on an independent **feature branch**. In this chapter, you will master Git's lightweight branching mechanism, execute smooth merges, demystify what causes merge conflicts, and resolve conflicts step-by-step like a senior engineer.

Learning objectives
  • 01Understand Git branches as lightweight 41-byte movable pointers to specific commits rather than duplicate folder copies
  • 02Create and switch between branches using the modern git switch -c and legacy git checkout -b commands
  • 03Execute fast-forward merges when histories have not diverged and three-way merges when parallel work has occurred
  • 04Identify the exact anatomy of merge conflict markers (<<<<<<< HEAD, =======, >>>>>>> branch)
  • 05Resolve merge conflicts cleanly using both terminal commands and graphical editor diff tools in VS Code
  • 06Clean up stale feature branches safely using git branch -d and force delete with -D

3.1 What is a Branch? Lightweight Movable Pointers

In older version control systems, creating a branch required copying the entire folder of files, which was slow and consumed disk space. In Git, **a branch is simply a tiny text file containing a 40-character SHA-1 commit hash** (just 41 bytes on disk). When you create a branch, Git creates a pointer pointing to the current commit. As you make new commits on that branch, the pointer automatically moves forward to each new commit snapshot. The special pointer called `HEAD` indicates which branch and commit your working directory currently reflects.
Branch Early and Often
Because Git branches are virtually instantaneous and take near-zero disk space, you should create a fresh branch for every self-contained task or experiment.

3.2 Branch Operations: `git branch`, `git checkout` vs Modern `git switch`

Branching is Git's superpower. Managing branches involves three core commands: ### 1. Inspecting & Managing Branches (`git branch`) • `git branch`: Lists all local branches on your computer. An asterisk `*` indicates your currently active branch. • `git branch -a`: Lists all local branches AND remote tracking branches (e.g. `remotes/origin/main`). • `git branch <new-name>`: Creates a new branch pointer without immediately switching to it. • `git branch -m <old-name> <new-name>`: Renames a branch (or `git branch -m <new-name>` to rename the current branch). • `git branch -d <name>`: Safely deletes a branch after verifying its commits have been merged. • `git branch -D <name>`: Force-deletes a branch even if it contains unmerged experimental commits. ### 2. Navigating Branches: Classic `checkout` vs Modern `switch` Historically, `git checkout` handled both switching branches and discarding file modifications. To remove ambiguity, modern Git (v2.23+) split these into `git switch` (for branches) and `git restore` (for working tree files): • **Classic Syntax**: `git checkout -b feature-a` (create & switch) or `git checkout feature-a` (switch). • **Modern Syntax**: `git switch -c feature-a` (create & switch) or `git switch feature-a` (switch). • **Quick Toggle**: `git switch -` immediately returns you to the branch you were previously on! ### 3. The 'Detached HEAD' State If you run `git checkout <commit-hash>`, you are checking out a specific historical commit rather than a branch name. Git enters a **Detached HEAD** state: any new commits you make are orphaned and will be lost when you switch away! To safely return to your primary branch, simply run `git switch main`.
Terminal Command 1: Branch Management, Navigation & Checkouts

List branches, create with switch -c and checkout -b, inspect with branch -v, and delete merged branches.

# List all local branches with their latest commit SHA and message
git branch -v

# Method A (Modern): Create and switch to a new branch with git switch
git switch -c feature/email-heuristics

# Method B (Classic): Create and switch using git checkout
# git checkout -b feature/email-heuristics

# Make changes and commit on the branch
echo "RISK_WEIGHT_URGENT = 25" > heuristics.py
git add heuristics.py
git commit -m "feat: define initial urgency scoring heuristic"

# Switch back to the main branch
git switch main

# Inspect all local branches (feature branch is visible)
git branch -a
Execution walkthrough
  1. 1.git branch -v lists branches and shows the latest commit message for each.
  2. 2.git switch -c creates and immediately checks out the new branch.
  3. 3.Commit files on the feature branch.
  4. 4.git switch main brings your working directory back to the clean main branch snapshot.
  5. 5.git branch -a confirms both branches exist safely in your repository.
Expected output
Switched to a new branch 'feature/email-heuristics'
[feature/email-heuristics a1b2c3d] feat: define initial urgency scoring heuristic
 1 file changed, 1 insertion(+)
 create mode 100644 heuristics.py
Switched to branch 'main'
Edge cases

• If you have uncommitted changes in your working directory that conflict with files on the target branch, Git prevents switching: 'error: Your local changes to the following files would be overwritten by checkout'. You must either commit or stash (`git stash`) your changes first.

Why it happens: Git swaps files in your filesystem instantaneously because it only has to update references and stream cached objects from the local .git database.

3.3 Merging Branches: Fast-Forward vs Three-Way Merge

Once your feature branch work is tested and complete, you merge it back into `main`. ### Fast-Forward Merge If `main` has not had any new commits since you branched off, Git simply moves the `main` pointer forward to match your feature branch commit. No new merge commit is required. ### Three-Way (Recursive) Merge If other developers have added new commits to `main` while you were working on your feature branch, the histories have diverged. Git performs a 3-way merge using three snapshots: the common ancestor commit, the tip of `main`, and the tip of your feature branch, creating a new **merge commit** with two parent pointers.
Terminal Command 2: Merge Feature Branch into Main

Perform a fast-forward merge of feature-scanner into main and inspect the unified history.

# Ensure you are on the target branch (main)
git switch main

# Merge the feature branch into main
git merge feature-scanner

# Inspect the updated commit log
git log --oneline --graph
Execution walkthrough
  1. 1.Always verify you are on the destination branch before running git merge.
  2. 2.git merge feature-scanner merges the commits.
  3. 3.Inspect git log: both HEAD -> main and feature-scanner now point to the same latest commit.
Expected output
Updating b4c5d6e..c3d4e5f
Fast-forward
 scanner.py | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 scanner.py

Why it happens: Because main had not moved since feature-scanner was created, Git used a fast-forward update.

3.4 Demystifying Merge Conflicts: Anatomy & Resolution

A **merge conflict** occurs when two branches modify the **exact same lines of the same file** in different ways, or one branch deletes a file that the other branch modified. Git cannot guess which version is correct, so it halts the merge and asks you (the developer) to choose. When a conflict occurs, Git writes **conflict markers** directly into the affected file: ```text <<<<<<< HEAD threshold = 0.75 # from your current branch (main) ======= threshold = 0.90 # from the incoming branch (feature) >>>>>>> feature-threshold ``` ### Resolution Steps: 1. Open the conflicted file in VS Code or any text editor. 2. Decide which code to keep (Current, Incoming, or a combined synthesis). 3. Delete all marker lines (`<<<<<<<`, `=======`, `>>>>>>>`). 4. Save the file, stage it (`git add <file>`), and complete the merge with `git commit`.
Terminal Command 3: Complete a Conflict Resolution

Stage the resolved conflict file and record the final merge commit.

# After manually editing the conflicted file in your editor:
git status

# Stage the resolved file
git add scanner.py

# Finalize the merge commit
git commit -m "merge: resolve threshold conflict between main and feature-threshold"

# Delete the merged feature branch safely
git branch -d feature-threshold
Execution walkthrough
  1. 1.git status lists conflicted files under 'Unmerged paths'.
  2. 2.git add tells Git the conflict in that file is resolved.
  3. 3.git commit creates the merge commit.
  4. 4.git branch -d cleans up the branch pointer.
Expected output
[main d4e5f6a] merge: resolve threshold conflict between main and feature-threshold
Deleted branch feature-threshold (was c3d4e5f).
Edge cases

• If you want to abort an in-progress merge and return your repository to the state before running git merge, run: git merge --abort.

Why it happens: git branch -d checks if the branch is fully merged into HEAD before deleting, protecting you from losing unmerged work.

Practice exercise

Work through the exercise before starting the chapter assignment

Exercise 3: Create, Switch, and Delete a Branch

intermediate

In your local terminal, create a branch named 'test-experiment', switch to it, make a commit, switch back to 'main', and verify that your main branch remains on its previous commit.

Chapter summary

Key concepts and syntax cards for review

Key concepts
  • 01A Git branch is a lightweight 41-byte pointer referencing a commit; HEAD points to the currently active branch
  • 02git switch -c <branch> creates and switches to a new branch cleanly
  • 03Fast-forward merges occur when no divergent commits exist on the destination branch
  • 04Merge conflicts occur when conflicting changes happen on the same lines of the same file
  • 05Git conflict markers (<<<<<<<, =======, >>>>>>>) clearly delimit opposing edits for manual resolution
  • 06git merge --abort safely cancels an active merge conflict and restores previous repository state
Syntax reference
git branchLists all local branches, marking the currently checked-out branch with an asterisk (*)
git switch -c <name>Creates a new branch named <name> and immediately checks it out
git checkout -b <name>Classic Git command to create and switch to a new branch in one step
git branch -aLists all local and remote tracking branches in the repository
git switch <name>Switches the working directory to the existing branch <name>
git merge <branch>Merges commits from <branch> into the current active branch
git merge --abortAborts an in-progress merge conflict and resets files to pre-merge status
git branch -d <name>Safely deletes branch <name> if it has already been merged into HEAD

Knowledge check

Verify your grasp of the chapter concepts

What happens during a 'fast-forward' merge in Git?

Which command cancels an in-progress merge conflict and returns your files to clean pre-merge status?