How to deal with conflicts in Git?

Git is an excellent version control system that allows multiple people to work on a project simultaneously. But with multiple contributors, inevitably, changes can overlap and conflict. When Git cannot automatically resolve these differences, a merge conflict occurs. Let’s go through some steps to resolve these conflicts.

Step 1: Identify the Conflict

When you try to merge branches and encounter a conflict, Git will output a message like this:

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

This message tells you that a conflict has occurred in file.txt.

Step 2: Examine the Conflict

Next, open the file with the conflict. Git will mark the conflicted area like this:

<<<<<<< HEAD
This is some content from the current branch.
=======
This is some different content from the branch you're trying to merge.
>>>>>>> feature_branch

The content between <<<<<<< HEAD and ======= is your current branch’s content. The content between ======= and >>>>>>> feature_branch is the content from the branch you’re trying to merge.

Step 3: Resolve the Conflict

At this point, it’s your job to reconcile the differences. Maybe you keep your branch’s content, or the other branch’s content, or create a mix of the two, or something else entirely. It’s completely up to you.

Once you’ve made your changes, it might look something like this:

This is the reconciled content that takes the best of both worlds.

Step 4: Mark the Conflict as Resolved

After you’ve fixed the conflict, you need to add the resolved file to the staging area:

$ git add file.txt

This tells Git that you’ve resolved the conflict.

Step 5: Commit the Resolution

Finally, you can commit your resolution like this:

$ git commit -m "Resolved merge conflict in file.txt"

Git will automatically create a new commit that includes the conflict resolution. The commit will be a merge commit if the conflict arose from a merge, or a regular commit if it arose from a rebase.

Best Practices:

  • Before merging branches, always make sure you have the latest version of the codebase. Use git pull to fetch and merge any changes that have been pushed since your last pull.
  • If a conflict seems too complex to resolve, don’t panic! Git doesn’t throw away any changes, so you can always abort the merge and get help. To abort the merge, use git merge --abort.
  • Regularly pull and merge the main development branch into your feature branch. This can help you identify and resolve conflicts gradually, rather than all at once when you’re ready to merge your feature into the main codebase.

Remember, dealing with merge conflicts is a common part of working with Git. With time and practice, you’ll become comfortable resolving them.