When multiple developers are collaborating and working on the same codebase, Git is one of the most widely used platforms for this purpose.But if multiple developers are making changes to the same file at the same time, Git cannot automatically merge the changes from the different branches in some cases, which leads to merge conflicts. If merge conflicts are not resolved correctly, it could lead to problems with development and stability in the project. In this article, we will explain what merge conflicts are and how to detect and resolve them using Git commands.
Table of Contents:
What is Git?
Git is a version control system that allows developers to engage in parallel coding. Parallel coding enables multiple developers to work on the same project simultaneously. GitHub is a web-based hosting service for Git repositories with a user-friendly interface that allows developers to push, pull, and merge code into the repository. Large codebases can be accessed and changed without breaking the system and order. Git allows developers to push, pull, and merge code into the repository, improving collaboration. This increases the efficiency and saves time for software developers.
What is Git Merge?
Git Merge is a feature of Git that allows users to integrate changes made to the code in their branch with the main repository.
A repository is a directory or a storage space that contains the main project on which everyone is working.
Technically, a branch is a lightweight, movable pointer to a commit. It can be thought of as a subfolder that contains a copy of the main project.
In a development environment, you work on a copy (branch) instead of the main project (repository). This is a prevention measure to avoid any incorrect changes made to the main project that hinder the working of the system.
Git merge performs two types of merges: a fast-forward merge and a no-fast-forward merge. We will also discuss git rebase, which is an alternative to git merge.
Master Merge Conflicts with Expert DevOps Courses
Learn to resolve code conflicts efficiently and streamline your DevOps workflows with our specialized courses.
1. Fast-forward Merge
A fast-forward merge happens when the main branch stays as it was when the target branch was created. This means that the main and the target branches must not diverge. This is because in this type of merge, git moves the branch pointer forward to the latest commit. It does not perform any complex merging operations.
2. No-fast-forward Merge
When multiple changes are made to the same file, Git can’t decide which changes to merge and which to discard. Instead, Git creates a special commit that joins both sets the changes. This is known as the merge commit. Here, Git can’t simply move forward. It has to combine changes from all the paths.
Alternative to Git Merge: Git Rebase
Git rebase is a command that moves the commits from one branch and re-applies them on top of another branch. Another branch could be the main branch as well. Unlike a traditional merge, rebase rewrites history to make it look like the work was done in a straight line. This helps keep the project history clean and easy to follow. Rebase creates new versions of your commits with the same content but different commit IDs, because they now follow a new base.
What are Merge Conflicts in Git?
Git allows a team to work together on the same project. When working in a team, a situation might arise when two people are making changes to the same code file. They might be making changes to the same line of code. In this scenario, it becomes difficult for git to choose whose changes to keep in the original file. Because of this, a merge conflict is detected. In Git, conflicts may arise when you attempt to perform one of the following operations: pull, merge, rebase, cherry-pick, undo stash changes, or apply a patch.
Types of Merge Conflicts
A merge conflict can arise at two points: one is when Git starts the merge request, and the other is during the merge process. Let us understand how these conflicts can arise and what happens in each of these conflicts.
1. Before Starting the Merge Process
Before starting a merge, Git first checks your file to see if there are any unsaved changes in your project (working directory or staging area). These are uncommitted changes. Git will stop the merge and display an error message that explains the merge conflict.
For a merge conflict in the working directory, it will display:
error: Entry 'filename.ext' not up-to-date. Cannot merge.
For a merge conflict in the staging area, Git will display:
error: Entry 'filename.ext' would be overwritten by merge. Cannot merge.
Git stops to prevent overwriting the pending changes by the new commits that are being merged.
2. During the Merge Process
This type of merge conflict occurs when the changes you have committed to a file are in conflict with somebody else’s committed changes to the file. It is also known as the content conflict.
Git throws the following error message to alert the user:
CONFLICT (content): Merge conflict in filename.ext
Automatic merge failed; fix conflicts and then commit the result.
Identifying a Merge Conflict
To resolve a merge conflict, we first have to learn how to identify these conflicts. There are a few ways you can identify a merge conflict:
1. Git output
If a merge conflict occurs, Git will display a clear message to alert the user about it and urge them to resolve it.
The message could be something like
error: Entry ‘filename.ext’ would be overwritten by merge. Cannot merge.
Or,
CONFLICT (content): Merge conflict in filename.ext
Automatic merge failed; fix conflicts and then commit the result.
2. Files marked unmerged
Once you become aware that there are merge conflicts in some files in your directory, you can gain further knowledge and analyze the situation with the help of the git status command. The git status command will output something like this for the merge conflict files.
$ git status
On branch main
You have unmerged paths.
(fix conflicts and run "git commit")
(use "git merge --abort" to abort the merge)
Unmerged paths:
(use "git add …" to mark resolution)
both modified: filename.ext
3. Conflict Markers in the File
Git assists you in resolving the merge conflict by highlighting the lines that are causing the issue with the help of markers. You can use the cat command to open the file on the command line.
There are three types of markers used to highlight the lines that are causing the conflict.
- <<<<<<< HEAD: This marker marks the start of the content where you have made changes in your branch to be merged with the main branch.
- ======= : This line is the “centre” of the conflict. All the content between <<<<<<< HEAD and ======= is your branch’s modifications.
- >>>>>>> new_branch_to_merge_later: From the ======= till >>>>>>> new_branch_to_merge_later lies all the modification content that is present in some other branch, wanting to be merged with the main branch.
Together, it looks something like this:
<<<<<<< HEAD
Your branch’s changes
=======
Incoming changes from the other branch
>>>>>>> new_branch_to_merge_later
Get 100% Hike!
Master Most in Demand Skills Now!
Creating a Merge Conflict
Before we learn how to resolve merge conflicts, we will have to simulate a merge conflict. We can create a mock-up merge conflict to learn and hone our skills. You can do this in the following steps:
Step 1: Make a Directory
- Create a directory on your local system via the mkdir command and move into it using the cd command.
Step 2: Initialize it as a Git Repository
- Initialize that directory as a Git repository using git init and create a new file using the touch command. The name of the file can be anything.
Step 3: Add some content
- Add some content to the file using the echo command and then commit it to the repository.
Step 4: Create a new branch
- We will use this branch to introduce merge conflicts. We will learn to resolve them in the later section.
- You can create a new branch using the git checkout -b <branchname> command. Git will automatically switch to the newly created branch.
- Now make some changes in the main_file.txt and commit it to the repository.
Step 5: Merge Conflict
- Now, again, switch to the main branch. You can do this using git checkout main.
- Append some text to the file through this branch. Commit these changes to the repo and merge the new branch.
- We have successfully created a merge conflict.
Resolving Merge Conflicts in Git
Now that we have successfully created a merge conflict. We will learn to resolve merge conflicts through this simulation. There are various ways to deal with merge conflicts based on your situation.
This method works when you are using git bash or a terminal-only interface to make changes or merge.
Step 1: Git status
- The git status command will give you further insights on the conflict that has occurred.
Step 2: Open the file.
- You can use the cat command to open the file and find out the exact line that is causing the conflict using markers.
- You should use the nano command to open the file in edit mode.
Step 3: Resolve Manually
- Once you have opened the file, keep only the relevant lines that are correct or useful in the future. Remember to remove the ======= as well.
- Save the file once the changes are complete. Use the commands Ctrl + X, Y and then Enter.
Step 4: Commit the changes
If the merge conflicts are too messy for you or missing proper context for you to understand, you can just abort the merge. This can be done using the following command.
git merge --abort
Abort option will exit the merge process and return the branch to the state before the merge began.
Essential Git Commands for Handling Merge Conflicts
There are some general Git commands that can help you resolve merge conflicts. These are:
1. git status
This command is used to display the current status of the working directory or the staging area.
2. git log –merge
This shows the list of commits that are causing conflicts between two branches involved in a merge.
3. git diff
This command helps you identify what has changed between two branches, or the current file and the committed files, or the current file and the staged file.
4. git checkout
This command can be used to switch between the branches and also for undoing changes in a file.
5. git reset –mixed
This command is used to undo commits and unstage changes without deleting any actual file content from your working directory.
Command |
Description |
git status |
Show current state and files with conflicts |
git log –merge |
View conflicting commits |
git diff |
Compare changes across commits or stages |
git checkout |
Switch branches or discard changes in files |
git reset –mixed |
Unstage changes while keeping file content intact |
Master Essential DevOps Concepts at No Cost
Take Advantage of Our Free DevOps Course
Conclusion
Merge conflicts are an unavoidable aspect when working in collaboration, but they shouldn’t scare you. If you have an understanding of how those conflicts can happen and are skilled with the basic commands and methods to solve a merge conflict, you can get rid of these conflicts with confidence. Always be sure to communicate with your team, review the conflicting changes, and thoroughly test afterwards. If you take these best practices into account, you will be able to better deal with Git merge conflicts and keep your workflow efficient and error-free.
If you are new to Git and want to learn it from scratch, including how to install Git in your local system, check out this training course. If you are preparing for a software developer interview, check out these Git interview questions and ace your interview.
Resolving Merge Conflicts in Git – FAQs
Q1. What is the Git tool to resolve merge conflicts?
You can use Git CLI with manual editing to resolve conflicts or tools like VS Code Merge Editor, GitKraken, or Sourcetree
Q2. How to resolve merge conflicts faster?
You can resolve merge conflicts faster by using a visual merge tool.
Q3. How do I resolve conflicts in the merge editor?
You can use the merge editor to compare changes side-by-side, select or edit conflicting lines, and then save and commit the resolved file.
Q4. How to resolve merge conflicts in Git interview questions?
You can explain using git status, identifying conflict markers, editing files, running git add, then committing to finish the merge.
Q5. How to explain Git in interview?
Ygives the besou can say Git is a version control system that tracks code changes, supports collaboration, and allows branching, merging, and rollback of code versions efficiently.