Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Resolving Merge Conflicts

Introduction

Merge conflicts occur when multiple branches have changes to the same lines in a file or when one branch deletes a file that another branch has modified. Resolving these conflicts is crucial to maintaining the integrity of your codebase. This tutorial will guide you through the process of identifying, understanding, and resolving merge conflicts using the command line.

Identifying Merge Conflicts

Merge conflicts usually occur during the merge process. When you attempt to merge two branches, Git will automatically try to combine them. If it can't do this cleanly, it will notify you of a conflict.

Example Command:

git merge feature-branch

If there are conflicts, Git will output messages indicating which files are conflicted:

Auto-merging file.txt
CONFLICT (content): Merge conflict in file.txt
Automatic merge failed; fix conflicts and then commit the result.

Viewing Merge Conflicts

To see which files have conflicts, use the git status command. This will show you all the files that need attention.

Example Command:

git status
On branch main
You have unmerged paths.
(fix conflicts and run "git commit")

Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: file.txt

Understanding Conflict Markers

Open the conflicted file in your text editor. You will see conflict markers that look like this:

<<<<<<< HEAD
Your changes
=======
Changes from the feature-branch
>>>>>>> feature-branch

The text between <<<<<<< HEAD and ======= is what is currently in your branch. The text between ======= and >>>>>>> feature-branch is the conflicting change from the branch you are trying to merge.

Resolving the Conflict

To resolve the conflict, you need to decide which changes to keep. You can choose one side, the other, or combine the changes. Edit the file to reflect your choice and remove the conflict markers.

Resolved Conflict:

Your combined changes

Marking the Conflict as Resolved

Once you have resolved all conflicts in a file, you need to mark it as resolved using the git add command:

Example Command:

git add file.txt

Committing the Resolved Merge

After you have resolved all conflicts and marked them as resolved, you can commit the merge:

Example Command:

git commit

Git will use the default merge commit message, or you can provide a custom message.

Conclusion

Resolving merge conflicts can be challenging, but with practice, you'll become more comfortable with the process. Remember to communicate with your team to understand the context of conflicting changes and make informed decisions on how to resolve them.