How to merge branches with conflicts

GitGitBeginner
Practice Now

Introduction

Navigating branch conflicts is a crucial skill for developers using Git version control. This comprehensive tutorial will guide you through understanding, resolving, and preventing merge conflicts, empowering you to manage complex collaborative coding projects effectively.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL git(("`Git`")) -.-> git/BranchManagementGroup(["`Branch Management`"]) git(("`Git`")) -.-> git/BasicOperationsGroup(["`Basic Operations`"]) git(("`Git`")) -.-> git/DataManagementGroup(["`Data Management`"]) git/BranchManagementGroup -.-> git/branch("`Handle Branches`") git/BranchManagementGroup -.-> git/checkout("`Switch Branches`") git/BranchManagementGroup -.-> git/merge("`Merge Histories`") git/BranchManagementGroup -.-> git/log("`Show Commits`") git/BasicOperationsGroup -.-> git/diff("`Compare Changes`") git/DataManagementGroup -.-> git/reset("`Undo Changes`") git/BranchManagementGroup -.-> git/rebase("`Reapply Commits`") subgraph Lab Skills git/branch -.-> lab-418648{{"`How to merge branches with conflicts`"}} git/checkout -.-> lab-418648{{"`How to merge branches with conflicts`"}} git/merge -.-> lab-418648{{"`How to merge branches with conflicts`"}} git/log -.-> lab-418648{{"`How to merge branches with conflicts`"}} git/diff -.-> lab-418648{{"`How to merge branches with conflicts`"}} git/reset -.-> lab-418648{{"`How to merge branches with conflicts`"}} git/rebase -.-> lab-418648{{"`How to merge branches with conflicts`"}} end

Git Merge Basics

Understanding Git Merge

Git merge is a fundamental operation that allows you to combine multiple development lines into a single branch. When working on collaborative projects, merging becomes crucial for integrating changes from different branches.

Types of Merges

Fast-Forward Merge

A fast-forward merge occurs when the target branch has no additional commits since the source branch was created.

gitGraph commit branch feature checkout feature commit checkout main merge feature

Three-Way Merge

When branches have diverged, Git performs a three-way merge using a common ancestor commit.

gitGraph commit branch feature checkout feature commit checkout main commit merge feature

Basic Merge Commands

Command Description
git merge <branch-name> Merge specified branch into current branch
git merge --no-ff <branch-name> Force create a merge commit
git merge --abort Cancel ongoing merge

Practical Example

Let's demonstrate a merge on Ubuntu 22.04:

## Create and switch to main branch
git checkout main

## Create and switch to feature branch
git checkout -b feature-branch

## Make some changes
echo "New feature" > feature.txt
git add feature.txt
git commit -m "Add new feature"

## Switch back to main branch
git checkout main

## Merge feature branch
git merge feature-branch

Best Practices

  • Always ensure your working directory is clean before merging
  • Communicate with team members about branch merges
  • Use descriptive commit messages
  • Regularly pull changes to minimize merge conflicts

LabEx recommends practicing merge scenarios to build confidence in Git workflow management.

Resolving Merge Conflicts

What are Merge Conflicts?

Merge conflicts occur when Git cannot automatically resolve differences in code between two commits. This typically happens when the same part of a file has been modified differently in two branches.

Identifying Merge Conflicts

When a merge conflict happens, Git marks the problematic areas in the files:

<<<<<<< HEAD
Current branch changes
=======
Incoming branch changes
>>>>>>> branch-name

Conflict Resolution Workflow

1. Detect Conflicts

## Attempt to merge branches
git merge feature-branch

## Check conflict status
git status

2. Open Conflict Files

Conflicts are marked with special Git markers:

<<<<<<< HEAD
Current branch content
=======
Incoming branch content
>>>>>>> feature-branch

3. Manual Resolution Strategies

Strategy Description
Keep Current Use current branch's changes
Keep Incoming Use feature branch's changes
Combine Manually Manually edit to incorporate both changes

4. Resolve Conflicts Manually

## Edit file to remove Git markers
## Decide which changes to keep or combine
nano conflicted-file.txt

## Stage the resolved file
git add conflicted-file.txt

## Complete the merge
git commit -m "Resolve merge conflicts"

Conflict Resolution Tools

Visual Tools

  • VSCode
  • GitKraken
  • SourceTree

Command-line Tools

  • git mergetool
  • vimdiff

Conflict Prevention Workflow

flowchart TD A[Pull Latest Changes] --> B[Create Feature Branch] B --> C[Regular Commits] C --> D[Pull Main Branch] D --> E[Resolve Small Conflicts Early] E --> F[Merge to Main Branch]

Advanced Conflict Resolution

Aborting Merge

## Cancel ongoing merge
git merge --abort

Resolving Complex Conflicts

  • Break down large merges
  • Communicate with team
  • Use feature flags

LabEx recommends practicing conflict resolution in a safe environment to build confidence and skills.

Conflict Prevention Tips

Proactive Merge Conflict Management

1. Regular Branch Synchronization

## Frequently update main branch
git checkout main
git pull origin main

## Rebase feature branch
git checkout feature-branch
git rebase main

2. Branching Strategy

gitGraph commit branch feature checkout feature commit commit checkout main commit merge feature
Strategy Description Conflict Risk
Feature Branches Isolate development Low
Short-lived Branches Frequent merges Very Low
Long-running Branches Infrequent merges High

3. Commit Smaller, More Focused Changes

## Good: Small, focused commits
git add specific_file.py
git commit -m "Fix login validation"

## Avoid: Large, complex commits
git add .
git commit -m "Multiple changes"

Advanced Prevention Techniques

Code Review Practices

flowchart TD A[Create Pull Request] --> B[Team Code Review] B --> C[Address Review Comments] C --> D[Resolve Potential Conflicts] D --> E[Merge to Main Branch]

Configuration Best Practices

## Configure merge strategy
git config --global merge.conflictstyle diff3

## Enable merge backup
git config --global merge.keepBackup true

Tooling and Automation

Continuous Integration

Tool Conflict Detection Automated Merge
Jenkins Yes Partial
GitHub Actions Yes Limited
GitLab CI Yes Limited

Pre-merge Checks

#!/bin/bash
## Pre-merge validation script
git diff main...feature-branch
  1. Create feature branches
  2. Pull main branch regularly
  3. Rebase feature branches
  4. Use pull requests
  5. Conduct code reviews

Key Preventive Commands

## Check divergence between branches
git log --graph --oneline main..feature-branch

## Show merge preview
git merge-base main feature-branch

Common Conflict Scenarios

  • Simultaneous file edits
  • Refactoring shared code
  • Dependency updates
  • Configuration changes

LabEx emphasizes that preventing conflicts is easier than resolving them.

Summary

Mastering Git merge techniques is essential for seamless code integration. By understanding conflict resolution strategies, implementing preventive practices, and using Git's powerful tools, developers can maintain a clean and efficient version control workflow, ensuring smooth collaboration and code quality.

Other Git Tutorials you may like