Can You Resolve Merge Conflicts Before They Happen?
Solving merge conflicts is fun! - said no one ever. Nobody likes them, but it doesn’t change the fact that they are, well, part of the job. In this short post, I would like to briefly explain where they come from, show how to solve them and as an added bonus, suggest a solution to potentially avoid them in the first place!
Merge conflicts - what are they?
A merge conflict is an event that occurs when Git is unable to automatically resolve differences in code between two commits. They can happen as a result of merging branches, during a rebase or when you’re cherry-picking in Git.
The good news is that Git is quite good at figuring out how to integrate changes, so most of the time you’re safe. The hard part begins when the exact same line has been modified and Git can’t decide which version is correct. It will notify you about it in the terminal and hold you responsible for fixing it.
Solving merge conflicts the normal way
Ok, so how do we resolve conflicts? We can either solve them manually or use a Git GUI such as the ones built into VS Code or Jetbrains IDEs or a separate desktop application like Tower or Sourcetree.
Let’s look at solving conflicts manually.
The conflicting changes are easy to spot as they will be marked in a file by <<<<<<<
and >>>>>>>
. The part before =======
is your version of the conflicting lines and the part after is their version. Delete the lines you don’t want (including the conflict markers) and keep those that are correct.
Early merge conflict detection
Merging conflicts are not as scary as they seem, but the truth is that solving them can be a long and tedious process, especially on big projects.
That is where GitLive comes in handy - a powerful tool that will warn you inside your IDE the moment you make a change in the editor that conflicts with a change on any other branch. The warnings show you potential conflicts and give you the chance to solve them before the merge conflict occurs.
Starting with GitLive
Install the latest GitLive VS Code extension or JetBrains plugin to get started.
When you open a file you’ll see the change indicators in the gutter of your editor that shows you where your teammates have made changes compared to your version of the file. These update in real-time as you and your teammates are editing.
If you've made a conflicting change you will see the bright red conflict indicator. These conflicts can be uncommitted local changes you have not pushed yet or existing changes on your branch that conflict with your teammates’ changes.
In JetBrains click on the author’s avatar (or you can rollover the affected lines in VS Code) to inspect a change and see the diff, what branch they're from and even cherry-pick changes straight into your local file.
That’s it, hope you’ll find my mini-guide on how to deal with merge conflicts useful and next time you encounter a merge conflict you won’t panic. Let me know what you think in the comments!