Resolving Git Merge Conflict
Understanding Merge Conflict
A merge conflict occurs when Git cannot automatically merge two changesets. This usually happens when two developers change the same lines of code in a file and try to push the changes to GitHub.
Step 1 — Let’s clone the repo
We need to use the command to download the repository from GitHub locally. To download the repository named Test, which I prepared in advance, we click the Code button on the right side and copy the URL.
We open the terminal and write git clone https://github.com/kazimovzaman2/Test.git
and download it locally. Before we do that, it’s best to use cd Desktop
and navigate to the Desktop folder.
In general, the following output will be returned:
Now we can open it in VSCode.
Step 2 — Let’s make a change
We can also modify the code we write on GitHub. Select the file we want to change, click on the pencil icon in the right corner, and make our changes.
I added the sentence Second change to the h1 tag.
Click the Commit Changes… button
And our code is currently changed on GitHub. However, these changes did not occur in our local file.
Suppose another developer cloned the repository to his computer and made the following changes. And wants to upload it to GitHub.
git add .
git commit -m “Commits”
git push
As you can see in the picture, we get an error. To solve this we need to use the pull
command.
We use the command git pull origin main
in the terminal, and pull the changes to our local repo.
The lines between “<<<<<<< HEAD (Current Change)” and “=======” indicate changes made in the local repo, “=======” and “>>>>>>>23428e731b33ea5add289578faf0701a39b8b6a1 ” represents the changes in the remote repo. To resolve the conflict, decide on the desired outcome and edit the file accordingly.
This is how I made the changes in my file. Finally, after making all the changes, we can upload the files to GitHub using the following commands.
git add .
git commit -m “Fix merge conflict”
git push
In conclusion, merge conflicts are a natural part of teamwork in Git, but they can be resolved with a systematic approach. By following these simple steps and communicating effectively with your team, you can overcome merge conflicts and achieve a successful outcome for your project.