Resolving Git Merge Conflicts
Step-by-step guide to resolving merge conflicts: conflict markers (<<<<<<<, =======, >>>>>>>), 3-way merge tools, and preventing conflicts.
Resolving Git Merge Conflicts
A merge conflict occurs when two branches modify the exact same lines of code in different ways, and Git cannot automatically determine which version to keep.
1. Anatomy of a Merge Conflict
When a conflict occurs, Git pauses the merge and inserts visual conflict markers into the affected files:
<<<<<<< HEAD (Current Branch: e.g. main)
const API_URL = "https://api.prod.example.com";
=======
const API_URL = "https://api.staging.example.com";
>>>>>>> feature/new-api (Incoming Branch)<<<<<<< HEAD: Start of the conflict. Contains code from your currently checked-out branch.=======: The divider between conflicting versions.>>>>>>> <branch>: End of the conflict. Contains code from the branch being merged in.
2. Step-by-Step Resolution Process
- Locate Conflicted Files:
git status # Look for files listed under "Unmerged paths" (Both modified) - Open and Edit: Open the file in your code editor (e.g. VS Code with built-in conflict resolver buttons). Delete the conflict markers (
<<<<<<<,=======,>>>>>>>) and combine the code properly. - Stage the Resolved Files:
git add src/config.ts - Complete the Merge Commit:
git commit -m "merge: resolve API URL configuration conflict"
3. Aborting a Merge
If a conflict is too tangled and you want to safely abort and return to your original state before running git merge:
git merge --abortRelated Topics
Configuring .gitignore
How .gitignore works: glob patterns, ignoring node_modules and .env secrets, untracking previously committed files, and global gitignore.
Undoing Mistakes in Git
Comprehensive emergency guide for undoing Git mistakes: uncommitted edits, accidental commits, wrong branch commits, and recovering deleted files.