What is merge conflict? How is it resolved?
Shruthi Rajkumar
Cloud Engineering Manager | Multi-cloud SME - 1xAWS/ 1xGCP / 1xAzure | Passionate about GenAI, Automation and DevOps | Managing projects on Business transformation and Cloud Adoption
What is merge conflict?
A merge conflict is?an event that occurs when Git is unable to automatically resolve differences in code between two commits. When all the changes in the code occur on different lines or in different files, Git will successfully merge commits without raising merge conflict. But when the changes in the code occur on same lines in same file, that is when merge conflict occurs.
Let us see this with an example. Consider there is a repository on github.com named demo_merge_conflict. This repo has a file called 'demo_file" hosted on main branch. Please find below the contents of the file:
Notice that line number 3 outputs "text"
Let us assume 2 developers - Developer A and Developer B are working on this code simultaneously.
Developer A, created a feature branch - 'Developer A' and edits the file with the output "I am a tech enthusiast, but I don't follow Shruthi". He commits the file and merges this branch with main.
So the 'demo_file" hosted on main branch looks like below:
领英推荐
At the same time developer B is working on the same demo_file and makes changes in a new feature branch 'DeveloperB'. The demo_file in feature branch 'DeveloperB' looks like below:
Now since both developers A and B have made changes to same line '3' on same file 'demo_file', this will lead to a merge conflict when B tries to merge his branch 'DeveloperB'. This can be seen in the picture below:
Notice that the 'merge pull request' button is greyed out. You will not be able to merge until the conflict is resolved. You can use the 'resolve conflicts' button to edit code and resolve the conflict.
How to resolve merge conflict?
In order to resolve the conflict both developers A and B sit together and after discussing they come to a common ground and decide on what code should go into line 3 and then use the resolve conflict button to update the decided code. Later this can be committed and merged.
In our example, developer A and B decide to put code 'System.out.println("I am a tech enthusiast. I follow Shruthi on LinkedIn and I have also subscribed to TechBytes")' on line 3. So now the same is updated in the code line 3 by clicking on resolve conflict. Later this is committed and DeveloperB branch is merged successfully with main. Now the code on main looks like below image: