Encountering Git merge conflicts is very common, especially in projects with multiple contributors. The basic steps to resolve merge conflicts include the following:
-
Identify the location of the conflict:
- When executing the
git mergecommand orgit pull(which essentially performs afetchfollowed by amerge), Git will indicate the file where the conflict occurs. For example, it will display 'CONFLICT (content): Merge conflict in filename'.
- When executing the
-
Inspect and edit the conflict file:
- Open the conflicted file; Git will mark the conflict locations, typically using
<<<<<<< HEAD,=======, and>>>>>>> [other_branch_name]to identify them. HEADrefers to the current branch's content, while the other part represents the content from the branch you are merging.- You need to carefully compare both parts to decide which to keep or whether to combine them for modification.
- Open the conflicted file; Git will mark the conflict locations, typically using
-
Save and commit the resolved file:
- After resolving all conflicts, save the file.
- Use the
git add <file>command to mark the resolved file as resolved.
-
Complete the merge:
- Execute
git committo complete the merge. Typically, Git provides a default merge commit message, which can be edited as needed.
- Execute
-
Test and verify:
- Before the final commit, it is crucial to run the project's tests (if available) to ensure the merge did not break any functionality.
- This helps avoid introducing new issues due to conflict resolution.
Example:
Suppose you and your colleague are working on the same file example.py; you added some features on your branch, while your colleague modified the same section on his branch. When you attempt to merge his branch into yours, a conflict occurs.
You open the example.py file and find content similar to the following:
python<<<<<<< HEAD # Your version of the function def my_function(): print("Hello from your branch!") ======= # Your colleague's version of the function def my_function(): print("Hello from colleague's branch!") >>>>>>> colleague_branch
In this case, you can decide to keep only one version or discuss with your colleague how to combine the advantages of both versions. After resolving, you save the file and use git add example.py and git commit to complete the merge.
This is the process of resolving merge conflicts using Git. This skill is essential in team collaboration to ensure smooth project progress.