Master the art of combining branches and resolving conflicts in Git
Master Git merge operations, including fast-forward and three-way merges, and handling merge conflicts.
Git uses different merge strategies depending on the branch history. The two main types of merges are fast-forward and three-way merges.
Occurs when there is a direct linear path from the source branch to the target branch. No additional commit is created.
Creates a new merge commit when the branches have diverged. Combines the histories of both branches.
Here are the essential commands you'll use when merging branches:
Git offers several merge strategies to handle different scenarios:
- •
recursive:
Default strategy for branches with one merge base
- •
ours:
Resolves conflicts by keeping the current branch version
- •
theirs:
Resolves conflicts by keeping the merged branch version
Merge conflicts occur when Git can't automatically resolve differences between branches. Here's how to handle them:
- 1.
Identify conflicted files using
git status
- 2.
Open conflicted files and look for conflict markers
(<<<<<<<, =======, >>>>>>>)
- 3.
Edit files to resolve conflicts, removing conflict markers
- 4.
Stage resolved files and complete the merge with a commit
- Update before merging:
Always pull the latest changes from the target branch before merging
- Test before merging:
Ensure all tests pass in your feature branch before merging
- Review changes:
Double-check the changes being merged using git diff
- Clean history:
Consider using --squash for feature branches to maintain a clean history
Now that you understand merging, in the next lesson you'll learn about:
- Working with remote repositories
- Setting up remote connections