Sobes.tech
Junior

How to resolve conflicts in Git?

sobes.tech AI

Answer from AI

Conflicts in Git occur when two participants modify the same part of a file or one deletes a file while another modifies it.

To resolve conflicts, the following steps are usually performed:

  1. Update your local repository: Make sure you have the most recent version of the code from the remote repository.

    // Get the latest changes from the remote repository
    git pull origin <branch-name>
    
  2. Identify conflicting files: Git will inform you which files have conflicts.

    // Show repository status and conflicting files
    git status
    

    In the files, you will see conflict markers, for example:

    <<<<<<< HEAD
    // Your local changes
    =======
    // Incoming changes from the remote branch
    >>>>>>> <commit-hash>
    
    • <<<<<<< HEAD: start of your local changes.
    • =======: separator between your changes and incoming changes.
    • >>>>>>> <commit-hash>: end of incoming changes with commit hash.
  3. Manual editing of files: Open the conflicting file in a text editor and manually remove conflict markers, leaving only the needed code. You need to decide which version of the code to keep or merge both.

  4. Add resolved files: After resolving the conflict in a file, add it to the index.

    // Add the resolved file to the index
    git add <conflicted-file>
    

    Repeat this step for all conflicting files.

  5. Create a conflict resolution commit: After adding all resolved files, create a commit. Git will automatically suggest a commit message indicating conflict resolution.

    // Create a conflict resolution commit
    git commit
    

    You can edit this message before saving.

  6. Push changes: Push the resolved changes to the remote repository.

    // Push changes to the remote repository
    git push origin <branch-name>
    

Tools for conflict resolution:

For convenience, you can use graphical merge tools such as:

  • Kdiff3
  • Meld
  • VS Code Merge Editor
  • IDEs (IntelliJ IDEA, PyCharm, etc.) with built-in tools

To configure an external tool for conflict resolution:

// Configure external merge tool (example for opendiff)
git config --global merge.tool opendiff
// Run the tool
git mergetool

It is important to remember that timely fetching of changes from the remote repository (git pull) helps minimize conflicts.