Resolving Merge Conflicts
Understanding Merge Conflicts
In Git, merge conflicts occur when two or more developers make changes to the same line of code in a file or when a developer deletes a file while another developer is modifying it. Git cannot automatically determine what is correct. Conflicts only affect the developer performing the merge, the Git repository's history remains clean.
How to Spot Merge Conflicts
During a merge or pull, you might see a message like this:
Auto-merging file.txt
CONFLICT (content): Merge conflict in file.txt
Automatic merge failed; fix conflicts and then commit the result.
This indicates a merge conflict in file.txt
.
Inspecting the Conflict
Open the file and look for the conflict markers. The conflict area will look something like this:
<<<<<<< HEAD
This is text from our current branch
=======
This is text from the branch we’re merging in
>>>>>>> branch-name
The part between <<<<<<< HEAD
and =======
is the version of the current branch. The part between =======
and >>>>>>> branch-name
is the version of the branch you're merging in.
Resolving the Conflict
To resolve the conflict, choose one side's changes or make a brand new change. For example, you might decide to keep the version from the branch you're merging in:
This is text from the branch we’re merging in
Or, you might decide to keep the version from your current branch:
This is text from our current branch
Or, you might decide to make an entirely new change:
This is a new change that combines both versions
Once you've resolved all conflicts in a file, git add the file.
Committing the Merge
After you've resolved the conflict and staged the changes with git add
, you can commit the merge with git commit
.
Conclusion
Resolving merge conflicts is a normal part of working with Git and working on a team. The key is to communicate with your team members and understand the changes they're making.