Branching, Merging & Conflict Resolution

25 minLesson 2 of 4

Learning Objectives

  • Create and switch between branches
  • Merge branches and understand fast-forward vs merge commits
  • Resolve merge conflicts manually
  • Use git diff, blame, revert, and reset
  • Tag commits for release versioning

Why Branches?

Branches let you develop features in isolation without affecting stable code. The main branch stays clean while you experiment on feature branches.

Branch Commands

# Create a branch
git branch feature-auth
 
# Switch to it
git switch feature-auth
# or (legacy): git checkout feature-auth
 
# Create and switch in one command
git switch -c feature-auth
 
# List branches (* = current)
git branch
 
# Delete a branch (after merging)
git branch -d feature-auth

Merging

When your feature is ready, merge it into main:

# Switch to main
git switch main
 
# Merge feature branch
git merge feature-auth
 
# Delete the merged branch
git branch -d feature-auth

Resolving Conflicts

Conflicts occur when two branches modify the same lines:

git merge feature-branch
# Auto-merging file.txt
# CONFLICT (content): Merge conflict in file.txt

The file will contain conflict markers:

<<<<<<< HEAD
Content from current branch
=======
Content from incoming branch
>>>>>>> feature-branch

Resolution:

  1. Open the file and choose which content to keep
  2. Remove the conflict markers (<<<<<<<, =======, >>>>>>>)
  3. Stage and commit:
git add file.txt
git commit -m "Resolve merge conflict in file.txt"

Comparing Changes

# Differences in working directory
git diff
 
# Between branches
git diff main feature-auth
 
# Between commits
git diff abc123 def456

Viewing File History

# Who changed each line
git blame filename.txt
 
# History of a specific file
git log --follow filename.txt

Undoing Changes

Revert (Safe — creates new commit)

git revert HEAD        # Undo last commit
git revert abc123      # Undo specific commit

Reset (Destructive — removes commits)

git reset --soft HEAD~1   # Undo commit, keep changes staged
git reset --hard HEAD~1   # Undo commit AND discard changes
⚠️

git reset --hard permanently deletes changes. Never use it on commits already pushed to a shared repository.

Tags

Tags mark specific commits (usually releases):

git tag v1.0.0
git tag -a v1.0.0 -m "First stable release"
git tag              # List tags
git push origin v1.0.0  # Push tag to remote

Summary

  • Branches isolate work; git switch -c name creates and switches
  • git merge combines branches; conflicts require manual resolution
  • git revert safely undoes commits; git reset rewrites history
  • git diff shows changes; git blame shows line-by-line authorship
  • Tags mark releases: git tag v1.0.0

Next Steps

Next, we'll connect to GitHub — clone repos, push/pull, and collaborate with pull requests.