refactor: we're breaking out merge-conflicts

This commit is contained in:
Bjarke Sporring
2026-01-15 12:51:43 +01:00
parent ea5cbccc75
commit 7b638d27de
29 changed files with 1385 additions and 1310 deletions

View File

@@ -0,0 +1,487 @@
# Module 04: Merge Conflicts
## Learning Objectives
By the end of this module, you will:
- Understand what merge conflicts are and why they occur
- Use `git diff` to discover changes between branches
- Identify merge conflicts in your repository
- Read and interpret conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`)
- Resolve merge conflicts manually
- Complete a merge after resolving conflicts
## Setup
Create the challenge environment:
```bash
.\setup.ps1
```
This creates a repository with two feature branches that have conflicting changes.
## Overview
A **merge conflict** occurs when Git cannot automatically combine changes because both branches modified the same part of the same file in different ways.
**When do conflicts happen?**
- ✅ Two branches modify the same lines in a file
- ✅ One branch deletes a file that another branch modifies
- ✅ Complex changes Git can't merge automatically
- ❌ Different files are changed (no conflict!)
- ❌ Different parts of the same file are changed (no conflict!)
**Don't fear conflicts!** They're a normal part of collaborative development. Git just needs your help to decide what the final code should look like.
## Your Task
### Part 1: Discover the Changes
Before merging, it's good practice to see what each branch changed:
```bash
cd challenge
# Check which branch you're on
git branch
# View all branches
git branch --all
```
You'll see three branches: `main`, `add-timeout`, and `add-debug`.
**Discover what each branch changed:**
```bash
# Compare main with add-timeout
git diff main add-timeout
# Compare main with add-debug
git diff main add-debug
# Compare the two feature branches directly
git diff add-timeout add-debug
```
**What did you discover?**
- Both branches modified `config.json`
- They both added a line in the same location (after `"port": 3000`)
- One adds `"timeout": 5000`
- The other adds `"debug": true`
This is a recipe for a conflict!
### Part 2: Merge the First Branch (No Conflict)
Let's merge `add-timeout` first:
```bash
# Make sure you're on main
git switch main
# Merge the first branch
git merge add-timeout
```
**Success!** This merge works because main hasn't changed since add-timeout was created.
```bash
# View the updated config
cat config.json
# Check the history
git log --oneline --graph --all
```
### Part 3: Try to Merge the Second Branch (Conflict!)
Now let's try to merge `add-debug`:
```bash
# Still on main
git merge add-debug
```
💥 **Boom!** You'll see:
```
Auto-merging config.json
CONFLICT (content): Merge conflict in config.json
Automatic merge failed; fix conflicts and then commit the result.
```
**Don't panic!** This is expected. Git is asking for your help.
### Part 4: Check the Status
```bash
git status
```
You'll see:
```
On branch main
You have unmerged paths.
(fix conflicts and run "git commit")
(use "git merge --abort" to abort the merge)
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: config.json
```
This tells you that `config.json` needs your attention!
### Part 5: Open and Examine the Conflicted File
Open `config.json` in your text editor:
```bash
# On Windows
notepad config.json
# Or use VS Code
code config.json
```
You'll see special **conflict markers**:
```json
{
"app": {
"name": "MyApp",
"version": "1.0.0",
"port": 3000,
<<<<<<< HEAD
"timeout": 5000
=======
"debug": true
>>>>>>> add-debug
}
}
```
### Part 6: Understand the Conflict Markers
Let's break down what you're seeing:
```
<<<<<<< HEAD
"timeout": 5000 ← Your current branch (main, which has add-timeout merged)
=======
"debug": true ← The branch you're merging (add-debug)
>>>>>>> add-debug
```
**What each marker means:**
- `<<<<<<< HEAD` - Start of your changes (current branch)
- `=======` - Separator between the two versions
- `>>>>>>> add-debug` - End of their changes (branch being merged)
### Part 7: Resolve the Conflict
You have three options:
**Option 1: Keep ONLY your changes (timeout)**
```json
"timeout": 5000
```
**Option 2: Keep ONLY their changes (debug)**
```json
"debug": true
```
**Option 3: Keep BOTH changes****Do this!**
```json
"timeout": 5000,
"debug": true
```
### Part 8: Edit the File
For this challenge, we want **both settings**, so:
1. Delete ALL the conflict markers:
- Remove `<<<<<<< HEAD`
- Remove `=======`
- Remove `>>>>>>> add-debug`
2. Keep both settings:
**Before (with conflict markers):**
```json
{
"app": {
"name": "MyApp",
"version": "1.0.0",
"port": 3000,
<<<<<<< HEAD
"timeout": 5000
=======
"debug": true
>>>>>>> add-debug
}
}
```
**After (resolved):**
```json
{
"app": {
"name": "MyApp",
"version": "1.0.0",
"port": 3000,
"timeout": 5000,
"debug": true
}
}
```
**Important:**
- Remove ALL markers
- Add a comma after `"timeout": 5000` (for valid JSON)
- Ensure the file is valid JSON
3. Save the file
### Part 9: Mark the Conflict as Resolved
Tell Git you've resolved the conflict:
```bash
# Stage the resolved file
git add config.json
# Check status
git status
```
You should see:
```
On branch main
All conflicts fixed but you are still merging.
(use "git commit" to conclude merge)
```
Perfect! Git confirms the conflict is resolved.
### Part 10: Complete the Merge
Commit the merge:
```bash
git commit
```
Git will open an editor with a default merge message. You can accept it or customize it, then save and close.
**Done!** Your merge is complete!
```bash
# View the final result
cat config.json
# View the history
git log --oneline --graph --all
```
You should see both `timeout` and `debug` in the config!
### Part 11: Verify Your Solution
From the module directory (not inside challenge/):
```bash
.\verify.ps1
```
## Understanding Conflict Markers
### Anatomy of a Conflict
```
<<<<<<< HEAD ← Marker: Start of your version
Your changes here
======= ← Marker: Separator
Their changes here
>>>>>>> branch-name ← Marker: End of their version
```
### Common Conflict Patterns
**Simple conflict:**
```
<<<<<<< HEAD
print("Hello")
=======
print("Hi")
>>>>>>> feature
```
Decision: Which greeting do you want?
**Both are needed:**
```
<<<<<<< HEAD
timeout: 5000
=======
debug: true
>>>>>>> feature
```
Decision: Keep both (add comma)!
**Deletion conflict:**
```
<<<<<<< HEAD
# Function deleted on your branch
=======
def old_function():
pass
>>>>>>> feature
```
Decision: Delete or keep the function?
## Common Mistakes to Avoid
**Forgetting to remove conflict markers**
```json
<<<<<<< HEAD Don't leave these in!
"timeout": 5000,
"debug": true
>>>>>>> add-debug Don't leave these in!
```
This breaks your code! Always remove ALL markers.
**Committing without staging**
```bash
git commit # Error! You didn't add the file
```
Always `git add` the resolved file first!
**Keeping only one side when both are needed**
If you delete one setting, you lose that work!
**Breaking syntax**
```json
"timeout": 5000 Missing comma!
"debug": true
```
Always verify your file is valid after resolving!
**Not testing the result**
Always check that your resolved code works!
## Aborting a Merge
Changed your mind? You can abort the merge anytime before committing:
```bash
git merge --abort
```
This returns your repository to the state before you started the merge. No harm done!
## Key Commands
```bash
# Discover changes before merging
git diff branch1 branch2
# Attempt a merge
git merge <branch-name>
# Check which files have conflicts
git status
# Abort the merge and start over
git merge --abort
# After resolving conflicts:
git add <resolved-file>
git commit
# View conflicts in a different style
git diff --ours # Your changes
git diff --theirs # Their changes
git diff --base # Original version
```
## Pro Tips
💡 **Use `git diff` first**
Always compare branches before merging:
```bash
git diff main..feature-branch
```
💡 **Prevent conflicts**
- Pull changes frequently
- Communicate with your team about who's working on what
- Keep branches short-lived and merge often
💡 **Make conflicts easier**
- Work on different files when possible
- Make small, focused commits
- If editing the same file, coordinate with teammates
💡 **When stuck**
- Read the conflict markers carefully
- Look at `git log` to understand what each side changed
- Use `git diff` to see the changes
- Ask a teammate to review your resolution
- Use a merge tool: `git mergetool`
## Merge Tools
Git supports visual merge tools that make resolving conflicts easier:
```bash
# Configure a merge tool (one-time setup)
git config --global merge.tool vscode # or meld, kdiff3, etc.
# Use the merge tool during a conflict
git mergetool
```
This opens a visual interface showing both versions side-by-side.
## Real-World Scenario
This exercise simulates a common real-world situation:
**Scenario:** Two developers working on the same file
- Alice adds a timeout configuration
- Bob adds debug mode configuration
- Both push their changes
- When Bob tries to merge, he gets a conflict
- Bob resolves it by keeping both changes
- Everyone's work is preserved!
This happens all the time in team development. Conflicts are normal!
## What You've Learned
After completing this module, you understand:
- ✅ Merge conflicts happen when the same lines are changed differently
-`git diff` helps you discover changes before merging
- ✅ Conflict markers show both versions
- ✅ You decide what the final code should look like
- ✅ Remove all markers before committing
- ✅ Test your resolution to ensure it works
- ✅ Conflicts are normal and easy to resolve with practice
## Next Steps
Ready to continue? The next module covers **cherry-picking** - selectively applying specific commits from one branch to another.
To start over:
```bash
.\reset.ps1
.\setup.ps1
```
**Need help?** Review the steps above, or run `git status` to see what Git suggests!

Submodule 01-essentials/04-merge-conflict/challenge added at 676b08e650

View File

@@ -0,0 +1,23 @@
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Resets the Module 04 challenge environment.
.DESCRIPTION
This script removes the challenge directory, allowing you to start fresh.
Run setup.ps1 again after resetting to recreate the environment.
#>
Write-Host "`n=== Resetting Module 04 Challenge ===" -ForegroundColor Cyan
if (Test-Path "challenge") {
Write-Host "Removing challenge directory..." -ForegroundColor Yellow
Remove-Item -Recurse -Force "challenge"
Write-Host "`n[SUCCESS] Challenge environment reset complete!" -ForegroundColor Green
Write-Host "`nRun .\setup.ps1 to create a fresh challenge environment." -ForegroundColor Cyan
Write-Host ""
} else {
Write-Host "`n[INFO] No challenge directory found. Nothing to reset." -ForegroundColor Yellow
Write-Host "Run .\setup.ps1 to create the challenge environment." -ForegroundColor Cyan
Write-Host ""
}

View File

@@ -0,0 +1,125 @@
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Sets up the Module 04 challenge environment for merge conflicts.
.DESCRIPTION
This script creates a challenge directory with a Git repository containing
two feature branches that have conflicting changes to the same file.
Students will learn to identify, understand, and resolve merge conflicts.
#>
Write-Host "`n=== Setting up Module 04: Merge Conflicts ===" -ForegroundColor Cyan
# Remove existing challenge directory if it exists
if (Test-Path "challenge") {
Write-Host "Removing existing challenge directory..." -ForegroundColor Yellow
Remove-Item -Recurse -Force "challenge"
}
# Create fresh challenge directory
Write-Host "Creating challenge directory..." -ForegroundColor Green
New-Item -ItemType Directory -Path "challenge" | Out-Null
Set-Location "challenge"
# Initialize Git repository
Write-Host "Initializing Git repository..." -ForegroundColor Green
git init | Out-Null
# Configure git for this repository
git config user.name "Workshop Student"
git config user.email "student@example.com"
# ============================================================================
# Create base project
# ============================================================================
Write-Host "Creating base project..." -ForegroundColor Cyan
# Initial commit with config file
$configContent = @"
{
"app": {
"name": "MyApp",
"version": "1.0.0",
"port": 3000
}
}
"@
Set-Content -Path "config.json" -Value $configContent
git add .
git commit -m "Initial commit with config" | Out-Null
# Add README
$readmeContent = @"
# My Application
A simple application for learning merge conflicts.
## Configuration
Edit `config.json` to configure the application.
"@
Set-Content -Path "README.md" -Value $readmeContent
git add .
git commit -m "Add README" | Out-Null
# ============================================================================
# Branch 1: add-timeout (adds timeout setting)
# ============================================================================
Write-Host "Creating add-timeout branch..." -ForegroundColor Cyan
git switch -c add-timeout | Out-Null
$timeoutConfig = @"
{
"app": {
"name": "MyApp",
"version": "1.0.0",
"port": 3000,
"timeout": 5000
}
}
"@
Set-Content -Path "config.json" -Value $timeoutConfig
git add .
git commit -m "Add timeout configuration" | Out-Null
# ============================================================================
# Branch 2: add-debug (adds debug setting - CONFLICTS with timeout!)
# ============================================================================
Write-Host "Creating add-debug branch..." -ForegroundColor Cyan
git switch main | Out-Null
git switch -c add-debug | Out-Null
$debugConfig = @"
{
"app": {
"name": "MyApp",
"version": "1.0.0",
"port": 3000,
"debug": true
}
}
"@
Set-Content -Path "config.json" -Value $debugConfig
git add .
git commit -m "Add debug mode configuration" | Out-Null
# Switch back to main
git switch main | Out-Null
# Return to module directory
Set-Location ..
Write-Host "`n=== Setup Complete! ===" -ForegroundColor Green
Write-Host "`nYour challenge environment is ready in the 'challenge/' directory." -ForegroundColor Cyan
Write-Host "`nThe repository contains:" -ForegroundColor Yellow
Write-Host " - main branch: base configuration" -ForegroundColor White
Write-Host " - add-timeout branch: adds timeout setting" -ForegroundColor White
Write-Host " - add-debug branch: adds debug setting" -ForegroundColor White
Write-Host "`nBoth branches modify the same part of config.json!" -ForegroundColor Red
Write-Host "This will cause a merge conflict when you try to merge both." -ForegroundColor Red
Write-Host "`nNext steps:" -ForegroundColor Cyan
Write-Host " 1. Read the README.md for detailed instructions" -ForegroundColor White
Write-Host " 2. cd challenge" -ForegroundColor White
Write-Host " 3. Follow the guide to discover and resolve the conflict" -ForegroundColor White
Write-Host ""

View File

@@ -0,0 +1,208 @@
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Verifies the Module 04 challenge solution.
.DESCRIPTION
This script checks that you've successfully resolved the merge conflict by:
- Merging both branches into main
- Resolving the conflict in config.json
- Keeping both timeout and debug settings
- Ensuring valid JSON syntax
#>
$script:allChecksPassed = $true
# ============================================================================
# Helper Functions
# ============================================================================
function Write-Pass {
param([string]$Message)
Write-Host "[PASS] $Message" -ForegroundColor Green
}
function Write-Fail {
param([string]$Message)
Write-Host "[FAIL] $Message" -ForegroundColor Red
$script:allChecksPassed = $false
}
function Write-Hint {
param([string]$Message)
Write-Host "[HINT] $Message" -ForegroundColor Yellow
}
function Write-Info {
param([string]$Message)
Write-Host "[INFO] $Message" -ForegroundColor Cyan
}
# ============================================================================
# Check challenge directory exists
# ============================================================================
if (-not (Test-Path "challenge")) {
Write-Host "[ERROR] Challenge directory not found." -ForegroundColor Red
Write-Host "Run .\setup.ps1 first to create the challenge environment." -ForegroundColor Yellow
exit 1
}
Push-Location "challenge"
if (-not (Test-Path ".git")) {
Write-Host "[ERROR] Not a git repository." -ForegroundColor Red
Write-Host "Run ..\setup.ps1 first to create the challenge environment." -ForegroundColor Yellow
Pop-Location
exit 1
}
Write-Host "`n=== Verifying Module 04: Merge Conflicts ===" -ForegroundColor Cyan
# ============================================================================
# Check current branch
# ============================================================================
$currentBranch = git branch --show-current 2>$null
if ($currentBranch -eq "main") {
Write-Pass "Currently on main branch"
} else {
Write-Fail "Should be on main branch (currently on: $currentBranch)"
Write-Hint "Switch to main with: git switch main"
}
# ============================================================================
# Check that merge is not in progress
# ============================================================================
if (Test-Path ".git/MERGE_HEAD") {
Write-Fail "Merge is still in progress (conflicts not resolved)"
Write-Hint "Resolve conflicts in config.json, then: git add config.json && git commit"
Pop-Location
exit 1
} else {
Write-Pass "No merge in progress (conflicts resolved)"
}
# ============================================================================
# Check if config.json exists
# ============================================================================
if (-not (Test-Path "config.json")) {
Write-Fail "File 'config.json' not found"
Write-Hint "The config.json file should exist"
Pop-Location
exit 1
}
# ============================================================================
# Verify config.json is valid JSON
# ============================================================================
try {
$configContent = Get-Content "config.json" -Raw
$config = $configContent | ConvertFrom-Json -ErrorAction Stop
Write-Pass "File 'config.json' is valid JSON"
} catch {
Write-Fail "File 'config.json' is not valid JSON"
Write-Hint "Make sure you removed all conflict markers (<<<<<<<, =======, >>>>>>>)"
Write-Hint "Check for missing commas or brackets"
Pop-Location
exit 1
}
# ============================================================================
# Check for conflict markers
# ============================================================================
if ($configContent -match '<<<<<<<|=======|>>>>>>>') {
Write-Fail "Conflict markers still present in config.json"
Write-Hint "Remove all conflict markers (<<<<<<<, =======, >>>>>>>)"
Pop-Location
exit 1
} else {
Write-Pass "No conflict markers in config.json"
}
# ============================================================================
# Verify both settings are present (timeout and debug)
# ============================================================================
if ($config.app.timeout -eq 5000) {
Write-Pass "Timeout setting preserved (5000)"
} else {
Write-Fail "Timeout setting missing or incorrect"
Write-Hint "Keep the timeout: 5000 setting from add-timeout branch"
}
if ($config.app.debug -eq $true) {
Write-Pass "Debug setting preserved (true)"
} else {
Write-Fail "Debug setting missing or incorrect"
Write-Hint "Keep the debug: true setting from add-debug branch"
}
# ============================================================================
# Verify both branches were merged
# ============================================================================
$addTimeoutMerged = git log --oneline --grep="add-timeout" 2>$null | Select-String "Merge"
$addDebugMerged = git log --oneline --grep="add-debug" 2>$null | Select-String "Merge"
if ($addTimeoutMerged) {
Write-Pass "add-timeout branch has been merged"
} else {
# Check if it was a fast-forward merge (commits exist but no merge commit)
$timeoutCommit = git log --oneline --grep="Add timeout configuration" 2>$null
if ($timeoutCommit) {
Write-Pass "add-timeout branch changes are in main"
} else {
Write-Fail "add-timeout branch not merged"
Write-Hint "Merge with: git merge add-timeout"
}
}
if ($addDebugMerged) {
Write-Pass "add-debug branch has been merged"
} else {
Write-Fail "add-debug branch not merged"
Write-Hint "Merge with: git merge add-debug"
}
# ============================================================================
# Check commit count (should have both merges)
# ============================================================================
$totalCommits = [int](git rev-list --count HEAD 2>$null)
if ($totalCommits -ge 5) {
Write-Pass "Repository has $totalCommits commits (all merges complete)"
} else {
Write-Info "Repository has $totalCommits commits"
Write-Hint "Make sure both branches are merged"
}
Pop-Location
# ============================================================================
# Final summary
# ============================================================================
Write-Host ""
if ($script:allChecksPassed) {
Write-Host "=========================================" -ForegroundColor Green
Write-Host " CONGRATULATIONS! CHALLENGE PASSED!" -ForegroundColor Green
Write-Host "=========================================" -ForegroundColor Green
Write-Host "`nYou've successfully:" -ForegroundColor Cyan
Write-Host " ✓ Discovered changes using git diff" -ForegroundColor White
Write-Host " ✓ Merged the first branch" -ForegroundColor White
Write-Host " ✓ Encountered a merge conflict" -ForegroundColor White
Write-Host " ✓ Resolved the conflict by keeping both changes" -ForegroundColor White
Write-Host " ✓ Completed the merge" -ForegroundColor White
Write-Host "`nYou're now ready to handle merge conflicts in real projects!" -ForegroundColor Green
Write-Host ""
exit 0
} else {
Write-Host "[SUMMARY] Some checks failed. Review the hints above." -ForegroundColor Red
Write-Host ""
Write-Host "Quick guide:" -ForegroundColor Cyan
Write-Host " 1. Make sure you're on main: git switch main" -ForegroundColor White
Write-Host " 2. Merge first branch: git merge add-timeout" -ForegroundColor White
Write-Host " 3. Merge second branch: git merge add-debug" -ForegroundColor White
Write-Host " 4. Resolve conflict: edit config.json, remove markers, keep both settings" -ForegroundColor White
Write-Host " 5. Stage resolved file: git add config.json" -ForegroundColor White
Write-Host " 6. Complete merge: git commit" -ForegroundColor White
Write-Host " 7. Run this verify script again" -ForegroundColor White
Write-Host ""
exit 1
}