24. Creating a merge conflict

Goals

  • Create a conflicting change in the main branch.

When you merge two branches, Git tries to move the changes from one branch to the other. If the same part of the file was changed in both branches, Git may not be able to combine the changes automatically. In this case, Git will report a conflict and ask you to resolve it manually. In this lesson, we will simulate a conflict and later learn how to resolve it.

In real life merge conflicts happen regularly when working in the team. For example, you and your colleague started working on two different features, affecting the same files. Your colleague finished his work first and merged his changes to the main branch. Now you want to merge your own changes to the main branch as well. But the main branch is now different from the one you started working on—there is new code, submitted by your colleague. Most likely, Git will not be able to merge your changes automatically and will ask for human assistance.

01 Switch back to the main and create conflict

Remember, in our main branch, the page is still called hello.html? Switch back to the main branch and make the following changes:

git switch main

File: hello.html

<!-- Author: Alexander Shvets (alex@githowto.com) -->
<html>
  <head>
    <title>Hello World Page</title>
  </head>
  <body>
    <h1>Hello, World!</h1>
    <p>Let's learn Git together.</p>
  </body>
</html>

Run

git add hello.html
git commit -m "Added meta title"

02 View branches

Run

git log --all --graph

Result

$ git log --all --graph
* 85c14e9 2023-11-28 | Added meta title (HEAD -> main) [Alexander Shvets]
| *   a33deed 2023-11-28 | Merge branch 'main' into style (style) [Alexander Shvets]
| |\  
| |/  
|/|   
* | ee16740 2023-11-28 | Added README [Alexander Shvets]
| * 0ee0113 2023-11-28 | Renamed hello.html; moved style.css [Alexander Shvets]
| * 903eb1d 2023-11-28 | Included stylesheet into hello.html [Alexander Shvets]
| * 555372e 2023-11-28 | Added css stylesheet [Alexander Shvets]
|/  
* 9288a33 2023-11-28 | Added copyright statement with email [Alexander Shvets]
* b7614c1 2023-11-28 | Added HTML header (tag: v1) [Alexander Shvets]
* 46afaff 2023-11-28 | Added standard HTML page tags (tag: v1-beta) [Alexander Shvets]
* 78433de 2023-11-28 | Added h1 tag [Alexander Shvets]
* 5836970 2023-11-28 | Initial commit [Alexander Shvets]

After the "Added README" commit, the main branch has been merged with the style branch, but there is an additional main commit, which was not merged back to the style branch.

03 Next

The last change in main conflicts with some changes in the style branch. In the next step we will solve this conflict.