6. Merge Conflicts

Git merge conflicts arise when you try to merge changes from two branches, but Git can’t automatically determine how to combine modifications made to the same file in both branches. This typically happens when different developers edit the same lines of code or content within a file.

  • Causes:
    • Editing the same lines of code: If two developers work on the same section of code in separate branches and both make changes, Git won’t know how to combine those edits.
    • Deleting and modifying a file: If one developer deletes a file in one branch while another modifies the same file in another branch, Git can’t automatically decide what to do.
  • Identifying Conflicts: When a merge conflict occurs, Git will halt the merge process and provide information about the conflicted files. You’ll typically see error messages or markers within the affected files highlighting the conflicting changes.
  • Resolving Conflicts: To complete the merge, you’ll need to manually edit the conflicted files. Here’s the general workflow:
    1. Identify the conflict markers within the file. Git usually uses markers like <<<<<<<, =======, and >>>>>>> to distinguish the different versions of the conflicting code sections from each branch (yours, the other developer’s, and the common ancestor).
    2. Analyze the changes and decide how to integrate them. You can choose to keep your changes, the other developer’s changes, or merge them together.
    3. Edit the file to remove the conflict markers and create the desired merged version.
    4. Once you’ve resolved all conflicts in all affected files, you can use git add to stage the resolved files and then git commit to complete the merge.
  • Resources for Help: There are many resources available to help you with resolving merge conflicts, including tutorials, cheat sheets, and visual guides. You can search online for “git merge conflict resolution” or refer to the Git documentation for specific instructions https://docs.github.com/articles/resolving-a-merge-conflict-on-github.

Git have support for many tools that help manual merge, but you can also use a simple text editor.

Example

$ git merge b3
Auto-merging file_1.txt
CONFLICT (content): Merge conflict in file_1.txt
Automatic merge failed; fix conflicts and then commit the result.
$