Resolving Merge Conflicts
Merge conflicts happen when Git cannot automatically combine changes made to the same lines of a file on different branches, or when a file is deleted on one branch but modified on another. Git pauses the merge and lets you decide which changes to keep.
Follow these steps to identify, resolve, and complete a merge safely.
Step 1: Identify the Conflicts
When a merge encounters conflicts, run the following command to identify the affected files:
git status
Look under Unmerged paths to find the files that require conflict resolution.
Step 2: Understand the Conflict Markers
Open a conflicted file in your code editor, such as Visual Studio Code. Git marks the competing changes with special lines.
<<<<<<< HEAD
This is the code currently on your active branch (e.g., main).
=======
This is the incoming code from the branch you are merging.
>>>>>>> feature-login
-
<<<<<<< HEAD: Marks the beginning of the current branch's changes. -
=======: Separates the two competing versions. -
>>>>>>> feature-login: Marks the end of the incoming branch's changes.
HEAD
represents the version from your currently checked-out
branch, while the incoming section contains the
changes being merged.
Step 3: Resolve the Code
Edit the conflicted file to create the final version you want to keep.
- Review both blocks of code and choose the correct version, or combine the changes if both are needed.
-
Remove the conflict-marker lines:
<<<<<<<,=======, and>>>>>>>. - Save the file after resolving the conflict.
Step 4: Finalize the Merge
1. Stage the Resolved Files
git add <filename>
Replace <filename> with the name
of the resolved file. If you have resolved all
relevant files, you can stage them together:
git add .
2. Verify the Status
git status
Confirm that there are no remaining unmerged paths and that the resolved files are staged.
3. Complete the Merge Commit
git commit -m "Merge branch 'feature-login' and resolve conflicts"
This completes the merge when Git requires a merge commit. If Git has already completed the merge automatically, a separate merge commit may not be needed.
The Panic Button: Abort the Merge
If you are not ready to resolve the conflicts or want to abandon the current merge attempt, you can try:
git merge --abort
This attempts to return the repository to its pre-merge state. If you had uncommitted changes before starting the merge, the recovery may not be perfect, so use caution.
git merge --abort carefully.