How Does Git Resolve Merge Conflicts?
When using Git for version control, merge conflicts are a common issue, especially in collaborative projects. When two branches modify the same section of the same file, and one branch attempts to merge into another, merge conflicts occur. Git cannot automatically determine which changes to accept, so manual intervention is required to resolve these conflicts. Here are the steps to resolve merge conflicts along with relevant examples:
1. Detecting Conflicts
When executing git merge or git rebase commands, Git will prompt that a conflict has occurred, typically displaying a message like CONFLICT (content): Merge conflict in [filename].
2. Locating Conflicts
Use git status to identify which files contain conflicts.
3. Manually Resolving Conflicts
Open the file containing the conflict. Git marks the conflicting regions in the file with <<<<<<<, ======, and >>>>>>>. For example:
plaintext<<<<<<< HEAD This is the content from the current branch ======= This is the content from the branch being merged >>>>>>> feature-branch
You need to decide which changes to retain or combine both changes. Edit the file, remove the Git markers, and ensure the code logic remains correct.
4. Marking Conflicts as Resolved
After resolving all conflicts, use git add [filename] to mark the conflicts as resolved.
5. Completing the Merge
Once all conflicts are resolved, for a merge operation, complete the merge with git commit. Git typically provides a default merge commit message.
6. Testing to Ensure Code Works Correctly
Before committing the merged result, run tests to verify that the new merge does not break existing functionality.
Real-World Example:
Suppose you and your colleague both added installation instructions to the README.md file in the master branch, but in different sections. When you attempt to merge your colleague's branch, Git prompts a conflict. You open README.md and see the following conflict markers:
plaintext<<<<<<< HEAD # Installation Guide Ensure all dependencies are installed first. ======= # Installation Guide Follow these steps. >>>>>>> feature-branch
You decide to combine both sections, resulting in:
plaintext# Installation Guide Ensure all dependencies are installed first. Follow these steps.
Then use git add README.md and git commit to complete the merge.
By following these steps, you can effectively resolve Git merge conflicts, ensuring team collaboration is not disrupted by technical issues.