A merge conflict occurs when changes from different branches clash and Git cannot merge them automatically. Common scenarios include:
- Two contributors editing the same line in a file.
- One contributor deletes a file that another has modified.
- Simultaneous renaming of a file to different names in separate branches.
In such cases, Git will pause the merge process and mark the conflicting files for manual resolution. There are tools that helps users resolve these conflicts but in this guide, we will be focusing on the git command line tool.
- Identify Conflicted Files After attempting a merge, Git will notify you of conflicts. Use the following command to list them:
git statusLook for files listed under "Unmerged paths."
- Open and Examine Conflicted Files Open each conflicted file in your preferred text editor. Git sets boundaries for conflicts using the following markers:
<<<<<<< HEAD
Your changes
=======
Incoming changes
>>>>>>> branch-name
-
<<<<<<< HEADrepresents your current branch's changes. -
=======separates the conflicting changes. -
>>>>>>> branch-nameshows the incoming changes from the other branch.
- Resolve the Conflicts
Decide how to integrate the changes:
- Keep your changes.
- Accept the incoming changes.
- Combine both changes in a coherent manner.
After making the necessary edits, remove the conflict markers (<<<<<<<, =======, >>>>>>>)
- Mark Conflicts as Resolved Once you've resolved the conflicts in a file:
git add <filename>Repeat this for each conflicted file.
- Commit the Merge After staging all resolved files:
git commit -m "Resolved merge conflicts"🎉This finalizes the merge process.🎉
- Git Merge Tool: Launches a visual merge tool to help resolve conflicts.
git mergetoolNote: Ensure you have a merge tool installed (e.g., Meld, KDiff3, Beyond Compare).
- Abort a Merge: If you wish to cancel the merge process:
git merge --abortPull Regularly: Frequently pull changes from the main branch to stay updated.
git pull origin mainWork on Feature Branches: Create separate branches for each feature or fix.
git checkout -b feature-branchBy following this guide, you'll be well-equipped to handle merge conflicts confidently, ensuring a smoother contribution process to any open source project!