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-branchThese markers help you identify the conflicting sections:
<<<<<<< HEAD: Indicates the start of the changes from your current branch (usuallymainormasterif 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:
- Identify Conflicted Files: Git will tell you which files have conflicts. You can also run
git statusto see them listed under 'Unmerged paths'.
git status- Open Conflicted Files: Open each file listed by
git statusin your code editor.