Master: git merge
In this video we'll learn how to handle merge conflicts and understand merge commits.
In init: git merge we merged two branches that shared a common history.
In addition, the changes we made were only on the new-branch. So they didn't overlap with any changes on the master branch.
As such, we didn't have any conflicts during our merge.
On active projects there will be times where a merge is not so clean and will require you to manually resolve the conflicts.
Let's set up this scenario by making a change to File 1 on a new branch and changing the same file on the master branch.
So I'll create and checkout a new branch called add-timestamp by running:
git checkout -b add-timestamp
Then I'll append a timestamp to File 1 and commit that change.
I'll switch back to the master branch by running
git checkout master
And make the same change to File 1 then commit it.
We can see these branches have diverged by running:
git log --oneline --decorate --graph --all
In this case, the master branch is one commit ahead of the add-timestamp branch and the add-timestamp branch has a commit that master does not.
So let's see how to Git handles merging these two branches by running:
git merge add-timestamp
From the output we see that Git tried to merge these two branches and failed.
My command also shows that we are in a MERGING state.
We can get more information by running get status
.
The output lists File 1 as both modified. This means the file was modified on both of the branches and Git could not reliably merge them.
In this case, because we made the same change to the same line of the same file.
So Git needs us to resolve the conflict. We can do so by simply editing the file.
When I open File 1 in a text editor, I see Git has marked the sections of the file that conflict by fencing them in with several repeated characters.
By default, they are in two sections. In the case, the top section is what's on master and the bottom section is what's on add-timestamp.
I'll resolve the conflict by removing the markers and manually updating the timestamp.
I'll save the file and follow the suggestion from git status
.
So I'll add the file.
When I run git status
again I see File 1 is now listed as modified, and Git suggests to run git commit
to complete the merge.
Whenever you have a merge conflict, Git creates what's called a merge commit.
Its message is auto-generated so I'll just save it as is.
This completes the merge and if I run git log
again, we'll see the divergence has been resolved with the merge commit.
If you are the only one making changes, you may not encounter merge conflicts. If several people are making changes, they're going to happen from time to time.
While I'll discuss strategies to avoid them in future videos, you shouldn't fear them.
Often it's just a matter of reviewing the conflicts and determining which change to keep. You can always use git log
to determine the other authors and involve them in the process.