Merge Changes
Continuing with the previous example, you have finished the "Dark Mode" on your isolated branch feature-dark-mode. Everything works perfectly and now you need to bring that new code to the main branch (main).
This is called a merge.
Steps to do a local Merge
Doing a merge requires moving to the receiving branch first and then "calling" the branch with the changes.
- Move to the main branch (the one that will receive the changes):
git switch main - Verify that your other branches are up to date and clean of unsaved changes:
git status - Execute the merge specifying the branch you want to merge TOWARDS YOU:
git merge feature-dark-mode
If no one else modified the same files as you in the main branch while you were working, Git will do an automatic process called Fast-forward and that's it, your code is now joined into the official branch.
💥 Merge Conflicts
Sometimes, Git cannot do the "merge" automatically. This happens if:
- You and a colleague modified exactly the same line of a file.
- Someone deleted a file that you were modifying.
When this occurs, executing git merge will make Git stop the process and throw a huge warning message saying "CONFLICT (content): Merge conflict in...".
Don't panic. Git is simply asking for human help because it doesn't know which of the two versions of that line is the right one.
How to resolve a conflict
- Open your code editor (e.g. VS Code). The editor will visually highlight in colors the files where the collision occurred.
- Git will inject some special markers into your code. They look like this:
<<<<<<< HEAD (Current Change - What was in main)
<h1>Welcome to the main project</h1>
=======
<h1>Welcome in your dark mode version!</h1>
>>>>>>> feature-dark-mode (Incoming Change - What you are trying to bring in)
- Delete the Git markers. Manually delete the
<<<<<<<, the====, and the>>>>>>>. - Leave the code as you want it to look in its final version. It could be accepting the top version, the bottom one, or re-writing a third line that combines the best of both.
- Save the file.
Finish the Manual Merge
Once you have cleaned all the conflicts in all the files, you need to tell Git that you have already resolved the clash. This is done by creating a new final commit:
git add .
git commit -m "Merge feature-dark-mode resolving the conflict in index.html"
VS Code Tip: Modern editors like VS Code or extensions like GitLens have quick buttons above the conflicts that say "Accept current change", "Accept incoming change" or "Accept both" to make this deletion process easier.