Handling merge conflicts in Git is a crucial skill for any DevOps Engineer. Here’s a step-by-step guide on how to resolve merge conflicts.
1. Identify the conflict:
First, try merging the branches using ‘git merge‘:
git checkout main
git merge featureBranch
If there is a conflict, Git will output a message like:
Auto-merging myfile.txt
CONFLICT (content): Merge conflict in myfile.txt
Automatic merge failed; fix conflicts and then commit the result.
2. Examine the conflicting changes:
Check the status of the repository using ‘git status‘:
git status
You’ll see something like:
On branch main
You have unmerged paths.
(fix conflicts and run "git commit")
(use "git merge --abort" to abort the merge)
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: myfile.txt
The conflicting file (in this case ‘myfile.txt‘) will be marked as "both modified".
3. Resolve the conflict:
Open the conflicting file with your editor of choice, and you’ll see conflict markers indicating the conflicting changes:
<<<<<<< HEAD
This is the version in your current branch (main branch)
=======
This is the version in the merging branch (featureBranch)
>>>>>>> featureBranch
Edit the file to manually resolve the conflict, and remove the conflict markers. The final content might look like:
This is the merged version of this file.
4. Stage and commit the resolved changes:
After resolving the conflict, stage the changes using ‘git add‘:
git add myfile.txt
Then, commit the merge using ‘git commit‘. Git will automatically insert a commit message indicating that a merge is happening. You can use that message or modify it as needed:
git commit
This results in a merge commit, which you can verify with ‘git log –graph –oneline‘:
* 54a72bc (HEAD -> main) Merge branch 'featureBranch'
|
| * b984738 (featureBranch) Change in the featureBranch
* | 0e56c1e Change in the main branch
|/
* 8a9f199 Initial commit
5. (Optional) Use a merge tool:
If you prefer a more visual way to deal with conflicts, you can use a merge tool like KDiff3, Meld, or P4Merge. Configure the merge tool in your ‘.gitconfig‘ file and then use ‘git mergetool‘ during the conflict resolution step.
After resolving the conflicts and completing the merge, your branches will be synchronized, and the conflicts will be resolved.
Remember, merge conflicts are common in collaborative development environments, and learning how to address them efficiently is essential for DevOps Engineers.