Getting Started with GitHub: A Beginner's Guide to Version Control and Collaboration

Resolving Merge Conflicts

Section 5

Branching and Merging: Working on Features Independently

Getting Started with GitHub: A Beginner's Guide to Version Control and CollaborationBranching and Merging: Working on Features Independently

Even with the best planning, sometimes your independent work on a branch might clash with changes made elsewhere. When you try to merge a branch and Git can't automatically figure out how to combine the changes, you've encountered a merge conflict. This is a common part of working collaboratively, and understanding how to resolve them is crucial. Think of it as Git saying, 'I'm not sure which version of this code you want to keep, so I need your help!'

When a merge conflict occurs, Git will pause the merge process and mark the files with conflicts. You'll see special markers within the affected files that look like this:

<<<<<<< HEAD
// Code from your current branch (HEAD)
console.log('Hello from main!');
=======
// Code from the branch you are merging in
console.log('Hello from feature-branch!');
>>>>>>> feature-branch

These markers help you identify the conflicting sections:

  • <<<<<<< HEAD: Indicates the start of the changes from your current branch (usually main or master if you're merging into it).
  • =======: Separates the changes from your current branch and the changes from the branch you are merging.
  • >>>>>>> [branch-name]: Indicates the end of the changes from the branch you are merging in.

To resolve a merge conflict, you need to manually edit the conflicted files. Your goal is to decide which code to keep, or to combine parts of both. You will remove the conflict markers (<<<<<<<, =======, >>>>>>>) and leave only the desired code.

Here's a typical workflow for resolving conflicts:

  1. Identify Conflicted Files: Git will tell you which files have conflicts. You can also run git status to see them listed under 'Unmerged paths'.
git status
チャプターへ戻る