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:
-
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> -
Identify conflicting files: Git will inform you which files have conflicts.
// Show repository status and conflicting files git statusIn 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.
-
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.
-
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.
-
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 commitYou can edit this message before saving.
-
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.