Resolving conflicts when merging branches
Merge conflicts occur when git is unable to automatically merge changes from different branches. This happens when there are conflicting changes in the same places in the repository.
The causes of conflicts may include:
- Multiple users editing the same files at once.
- Pulling remote repository changes (
git pull) that conflict with your local edits. - Merging branches (
git merge) with conflicting changes made to the same lines of code. - Pushing changes (
git push) to the remote repository that has commits conflicting with your local edits.
Types of conflicts:
- Line update conflicts are the most common type of conflict, which occurs when the same file line is updated differently in different branches.
- File structure conflicts occur when one user updates a file and another user deletes it.
What conflicts look like in files
When git detects a conflict, it marks the problematic sections with special markers:
Common part of the text before the conflict
<<<<<<< HEAD
Changes in the current branch
=======
Changes in the incomning branch
>>>>>>> branch-name
Where:
<<<<<<< HEADmarks the beginning of changes in the current branch.=======is the separator between versions.>>>>>>> branch-namemarks the end of changes in the incoming branch.
Resolving conflicts from the command line
To resolve a conflict using the command line:
-
Identify the files with conflicts by executing this command:
git statusFiles with conflicts will be displayed marked with
both modified. -
Open the file with the conflict in the text editor.
-
Locate the conflict markers (
<<<<<<<,=======,>>>>>>>). -
Choose the conflict resolution option:
- Delete the version you do not need.
- Create new code to merge both versions.
After the changes are introduced, remove all conflict markers.
-
Save the file.
-
Add the updated file into the index:
git add <file_name> -
Finish the merge:
git commit -m "Resolve merge conflict" -
Push the changes:
git push
File structure conflicts
To resolve a conflict when a file was updated in one branch and deleted in another:
-
Check the conflict status:
git status -
Choose the next action with the file:
-
To keep the file, run this command:
git add <file_name> -
To delete the file, run this command:
git rm <file_name>
-
-
Finish the merge:
git commit -m "Resolve file deletion conflict"
Using merge tools
You can use graphical tools for convenient conflict resolution.
To start the configured merge tool, such as VS Code, Sublime Merge, or others, run this command:
git mergetool
Aborting the merge
To abort the merge and revert to the state before the operation started, run this command:
git merge --abort