Conflictive merges
In the previous section we have seen an “automatic” merge, i.e., Git has been able to merge both histories. Why? Because of the previously mentioned common ancestor. That is, the branch is returning to the point it started from.
But, when the branch another branch borns from suffers changes, problems appear.
To understand this, let’s construct a new history, which will have the following graph:
With the following commands:
echo 'one' >>
file.txt
git add file.txt
git commit -m 'first'
echo 'two' >>
file.txt
git add file.txt
git commit -m 'second'
git checkout -b
second-branch
echo 'three (from
second-branch)' >> file.txt
git add file.txt
git commit -m 'third from
second branch'
git checkout master
echo 'three' >>
file.txt
git add file.txt
git commit -m 'third'
|
What will happen if we try
to merge second-branch to master?
git checkout master
git merge second-branch
|
Git won’t be able to do it:
1
2
|
CONFLICT (content): Merge
conflict in file.txt
Automatic merge failed;
fix conflicts and then commit the result.
|
Git doesn’t know how to do
it, because the changes made in second-branch are not directly
applicable to master, since it has changed from this first branch
inception. What Git has done is to indicate in which parts exists these
incompatibilities.
Note that we haven’t used
the --no-ff flag, since we now in advance that the fast-forward won’t
be possible.
If we check the status,
we will see the following:
On branch master
You have unmerged paths.
(fix conflicts
and run "git commit")
Unmerged paths:
(use "git
add <file>..." to mark resolution)
both
modified: file.txt
|
Showing the conflictive
files. If we open it, we will see that Git has added some strange lines:
one
two
<<<<<<<
HEAD
three
=======
three (from second-branch)
>>>>>>>
second-branch
|
Git has indicated which are
the incompatible changes. And how does it know? The incompatible changes
are those that have been introduced into the “to” merging branch (master) since
the creation of the “from” merging branch (second-branch).
Now, we have to decide how
to combine the changes. On the one hand, the changes introduced to the
current HEAD are shown (between <<<<<<<
HEAD and =======), and, on the other, the branch we are trying to
merge (between ======= and >>>>>>>
second-branch). To solve the conflict, there are three options:
Use HEAD version.
Use second-branch version.
A combination of two
versions.
Regardless the option, the
file should end without any of the meta characters that Git has added to
identify the conflicts.
Once the conflicts have been
resolved, we have to add the file to the index and continue with the merge,
with commit command:
git add file.txt
git commit
|
Once saved the commit, the
merge will be done, having Git created a third commit for this merge, as with
when we used the --no-ff in the previous section.
No comments:
Post a Comment