Conflict resolution
In relation to Git control, a conflict (called a merge conflict) occurs
when two edits overlap between branches Common examples:
- Two lines are edited differently
- One branch deletes a file while the other modifies it
- A file is renamed in one branch but not in another
Use Cases:
- Working on the same file across multiple branches
- Collaborating with teammates on shared code
- Merging feature branches into main/master
- Resolving conflicting changes before deployment
Examples:
Creating a merge conflict step-by-step:
- Create a new folder anywhere on your computer called "conflicts"
- Right click the folder and open it in VS Code
- In the VS Code terminal, type:
- This initializes a new Git repository on the master branch
- Create a new file called favouritefruit.txt
- Paste the following text into the file:
- Save the file
- Stage the file:
- Commit the change:
- Create and switch to a new branch called oranges:
- Replace the contents of favouritefruit.txt with:
- Save the file
- Stage and commit the change:
- Switch back to the master branch:
- Add a new line (line 2) to favouritefruit.txt:
- Stage and commit this change:
- Attempt to merge the oranges branch into master:
- If done correctly, you should now see a merge conflict. Congratulations!
git init
My favourite fruit are apples! Apples are the best!
git add favouritefruit.txt
git commit -m "add my favourite fruit"
git checkout -b oranges
My favourite fruit are oranges! Oranges are the best!
git add favouritefruit.txt
git commit -m "add my superior favourite fruit"
git commit -m "add my superior favourite fruit"
git checkout master
Oranges SUCK
git add favouritefruit.txt
git commit -m "add information about oranges"
git commit -m "add information about oranges"
git merge oranges
Resolving a merge conflict:
- Open favouritefruit.txt in VS Code.
-
Notice that there are lines in the file that you didn’t add:
- <<<<<< HEAD
- =======
- >>>>>>> oranges
at the topin the middleat the bottom - All content between "<<<<<< HEAD" and ""======="" is the content from the current branch (master).
- All content between "======="" and ">>>>>>> oranges" is the incoming change from the oranges branch.
-
VS Code makes resolving conflicts easy. At the top of the file,
you will see options such as:
- Accept Current Change
- Accept Incoming Change
- For this demonstration, choose Accept Incoming Change. This will remove the current change and keep the oranges branch change.
- Once selected, the file will return to normal and the conflict markers will disappear.
- Now stage the resolved file:
- Commit the resolution:
- You have successfully resolved the merge conflict and merged the oranges branch into master!
git add favouritefruit.txt
git commit -m "resolved conflict"