Git Merge Conflict Resolution
#
WhyWe teach conflict resolution in git because sometimes merging won’t be so simple. This is especially true when we start collaborating with others, whether in the community or in the workplace. Knowing how to resolve merge conflicts and utilizing the full power of git will give you a great advantage in the workplace and will allow your workflow to achieve new heights.
#
What#
Merge ConflictA conflict occurs when there are two changes in the same line or set of lines in two different commits. It’s important to note that git doesn’t know how to code in C#. Git doesn’t know what to do when you have two edits of the same line, so git will mark the conflict and allow the user to decide which edit to pick or what changes to make.
In the situation below, there are two branches: a "bugfix" branch with a few commits coming off the "master" branch.
In this case, merging "bugfix" back into "master" is not much of an issue. That's because the state of "master" has not changed since "bugfix" was created. Git will merge this by moving the "master" position to the latest position of "bugfix". This merge is called a "fast-forward" since the possibility of a conflict cannot exist.
In the example below, however, "master" has been updated several times since "bugfix" was branched out. The changes from "bugfix" and "master" need to be combined when a merge is executed on these two branches.
For this sort of merge, a "merge commit" will be created, and the "master" position will be updated to the newly created merge commit.
#
Resolve Merge ConflictsAbort - stop the process
Resolve the conflict manually - go through the code and making edits
or
- Take out the git markers and choose what changes we want.
DONE
#
HowUsually, a merge conflict can arise when the master has been updated since you created your new branch (based on master). Maybe someone edited the same lines you were intending to edit without your knowledge. You don’t have to throw all of your work away! We can simply resolve the conflict points and get your work into the master branch!
We’ll show this merge conflict from this git repository: Github - mvdoyle/MergeConflictExercise
#
Resolving a conflict manuallyInspect the newBranch
Switch to master branch
Merge newBranch into master
Resolve the merge conflict (choose which changes to keep)
- Remove
>>>>>>>
and==========
from your code along with the changes you want removed (current or incoming)
- Remove
After we have taken out the git markers and chosen what we want, we need to stage and commit:
CONFLICT RESOLVED
#
AdditionalThese are bonus commands to show more information about the commit history and helps you to better visualize the changes that are present (NOT NECESSARY)
--OR--
#
Takeaways- Conflicts can arise when you attempt to merge commits that have different histories
- Visual Studio and Visual Studio Code have interfaces for resolving merge conflicts
git merge --abort
to undo a merge and fix any conflicts