Files
git-workshop/01_essentials/06-reset/README.md

718 lines
18 KiB
Markdown

# Module 06: Git Reset - Dangerous History Rewriting
## ⚠️ CRITICAL SAFETY WARNING ⚠️
**Git reset is DESTRUCTIVE and DANGEROUS when misused!**
Before using `git reset`, always ask yourself:
```
Have I pushed these commits to a remote repository?
├─ YES → ❌ DO NOT USE RESET!
│ Use git revert instead (Module 05)
│ Rewriting pushed history breaks collaboration!
└─ NO → ✅ Proceed with reset (local cleanup only)
Choose your mode carefully:
--soft (safest), --mixed (moderate), --hard (DANGEROUS)
```
**The Golden Rule:** NEVER reset commits that have been pushed/shared.
## About This Module
Welcome to Module 06, where you'll learn the powerful but dangerous `git reset` command. Unlike `git revert` (Module 05) which safely creates new commits, **reset erases commits from history**.
**Why reset exists:**
- ✅ Clean up messy local commit history before pushing
- ✅ Undo commits you haven't shared yet
- ✅ Unstage files from the staging area
- ✅ Recover from mistakes (with reflog)
**Why reset is dangerous:**
- ⚠️ Erases commits permanently (without reflog)
- ⚠️ Breaks repositories if used on pushed commits
- ⚠️ Can lose work if used incorrectly
- ⚠️ Confuses teammates if they have your commits
**Key principle:** Reset is for polishing LOCAL history before sharing.
## Learning Objectives
By completing this module, you will:
1. Understand the three reset modes: --soft, --mixed, --hard
2. Reset commits while keeping changes staged (--soft)
3. Reset commits and unstage changes (--mixed)
4. Reset commits and discard everything (--hard)
5. Know when reset is appropriate (local only!)
6. Understand when to use revert instead
7. Use reflog to recover from mistakes
## Prerequisites
Before starting this module, you should:
- Be comfortable with commits and staging (`git add`, `git commit`)
- Understand `git revert` from Module 05
- **Know the difference between local and pushed commits!**
## Setup
Run the setup script to create the challenge environment:
```powershell
./setup.ps1
```
This creates a `challenge/` directory with three branches demonstrating different reset modes:
- `soft-reset` - Reset with --soft (keep changes staged)
- `mixed-reset` - Reset with --mixed (unstage changes)
- `hard-reset` - Reset with --hard (discard everything)
**Remember:** These are all LOCAL commits that have NEVER been pushed!
## Understanding Reset Modes
Git reset has three modes that control what happens to your changes:
| Mode | Commits | Staging Area | Working Directory |
|------|---------|--------------|-------------------|
| **--soft** | ✂️ Removed | ✅ Kept (staged) | ✅ Kept |
| **--mixed** (default) | ✂️ Removed | ✂️ Cleared | ✅ Kept (unstaged) |
| **--hard** | ✂️ Removed | ✂️ Cleared | ✂️ **LOST!** |
**Visual explanation:**
```
Before reset (3 commits):
A → B → C → HEAD
After git reset --soft HEAD~1:
A → B → HEAD
C's changes are staged
After git reset --mixed HEAD~1 (or just git reset HEAD~1):
A → B → HEAD
C's changes are unstaged (in working directory)
After git reset --hard HEAD~1:
A → B → HEAD
C's changes are GONE (discarded completely!)
```
## Challenge 1: Soft Reset (Safest)
### Scenario
You committed "feature C" but immediately realized the implementation is wrong. You want to undo the commit but keep the changes staged so you can edit and re-commit them properly.
**Use case:** Fixing the last commit's message or contents.
### Your Task
1. Navigate to the challenge directory:
```bash
cd challenge
```
2. You should be on the `soft-reset` branch. View the commits:
```bash
git log --oneline
```
You should see:
- "Add feature C - needs better implementation!"
- "Add feature B"
- "Add feature A"
- "Initial project setup"
3. View the current state:
```bash
git status
# Should be clean
```
4. Reset the last commit with --soft:
```bash
git reset --soft HEAD~1
```
5. Check what happened:
```bash
# Commit is gone
git log --oneline
# Should only show 3 commits now (feature C commit removed)
# Changes are still staged
git status
# Should show "Changes to be committed"
# View the staged changes
git diff --cached
# Should show feature C code ready to be re-committed
```
### What to Observe
After `--soft` reset:
- ✅ Commit removed from history
- ✅ Changes remain in staging area
- ✅ Working directory unchanged
- ✅ Ready to edit and re-commit
**When to use --soft:**
- Fix the last commit message (though `commit --amend` is simpler)
- Combine multiple commits into one
- Re-do a commit with better changes
## Challenge 2: Mixed Reset (Default, Moderate)
### Scenario
You committed two experimental features that aren't ready. You want to remove both commits and have the changes back in your working directory (unstaged) so you can review and selectively re-commit them.
**Use case:** Undoing commits and starting over with more careful staging.
### Your Task
1. Switch to the mixed-reset branch:
```bash
git switch mixed-reset
```
2. View the commits:
```bash
git log --oneline
```
You should see:
- "Add debug mode - REMOVE THIS TOO!"
- "Add experimental feature X - REMOVE THIS!"
- "Add logging system"
- "Add application lifecycle"
3. Reset the last TWO commits (default is --mixed):
```bash
git reset HEAD~2
# This is equivalent to: git reset --mixed HEAD~2
```
4. Check what happened:
```bash
# Commits are gone
git log --oneline
# Should only show 2 commits (lifecycle + logging)
# NO staged changes
git diff --cached
# Should be empty
# Changes are in working directory (unstaged)
git status
# Should show "Changes not staged for commit"
# View the unstaged changes
git diff
# Should show experimental and debug code
```
### What to Observe
After `--mixed` reset (the default):
- ✅ Commits removed from history
- ✅ Staging area cleared
- ✅ Changes moved to working directory (unstaged)
- ✅ Can selectively stage and re-commit parts
**When to use --mixed (default):**
- Undo commits and start over with clean staging
- Split one large commit into multiple smaller ones
- Review changes before re-committing
- Most common reset mode for cleanup
## Challenge 3: Hard Reset (MOST DANGEROUS!)
### ⚠️ EXTREME CAUTION REQUIRED ⚠️
**This will PERMANENTLY DELETE your work!**
Only use `--hard` when you're absolutely sure you want to throw away changes.
### Scenario
You committed completely broken code that you want to discard entirely. There's no salvaging it—you just want it gone.
**Use case:** Throwing away failed experiments or completely wrong code.
### Your Task
1. Switch to the hard-reset branch:
```bash
git switch hard-reset
```
2. View the commits and the broken code:
```bash
git log --oneline
# Shows "Add broken helper D - DISCARD COMPLETELY!"
cat utils.py
# Shows the broken helper_d function
```
3. Reset the last commit with --hard:
```bash
git reset --hard HEAD~1
```
**WARNING:** This will permanently discard all changes from that commit!
4. Check what happened:
```bash
# Commit is gone
git log --oneline
# Should only show 2 commits
# NO staged changes
git diff --cached
# Empty
# NO unstaged changes
git diff
# Empty
# Working directory clean
git status
# "nothing to commit, working tree clean"
# File doesn't have broken code
cat utils.py
# helper_d is completely gone
```
### What to Observe
After `--hard` reset:
- ✅ Commit removed from history
- ✅ Staging area cleared
- ✅ Working directory reset to match
- ⚠️ All changes from that commit PERMANENTLY DELETED
**When to use --hard:**
- Discarding failed experiments completely
- Throwing away work you don't want (CAREFUL!)
- Cleaning up after mistakes (use reflog to recover if needed)
- Resetting to a known good state
**⚠️ WARNING:** Files in the discarded commit are NOT gone forever—they're still in reflog for about 90 days. See "Recovery with Reflog" section below.
## Understanding HEAD~N Syntax
When resetting, you specify where to reset to:
```bash
# Reset to the commit before HEAD
git reset HEAD~1
# Reset to 2 commits before HEAD
git reset HEAD~2
# Reset to 3 commits before HEAD
git reset HEAD~3
# Reset to a specific commit hash
git reset abc123
# Reset to a branch
git reset main
```
**Visualization:**
```
HEAD~3 HEAD~2 HEAD~1 HEAD
↓ ↓ ↓ ↓
A → B → C → D → E
Current commit
```
- `git reset HEAD~1` moves HEAD from E to D
- `git reset HEAD~2` moves HEAD from E to C
- `git reset abc123` moves HEAD to that specific commit
## Verification
Verify your solutions by running the verification script:
```bash
cd .. # Return to module directory
./verify.ps1
```
The script checks that:
- ✅ Commits were reset (count decreased)
- ✅ --soft: Changes remain staged
- ✅ --mixed: Changes are unstaged
- ✅ --hard: Everything is clean
## Recovery with Reflog
**Good news:** Even `--hard` reset doesn't immediately destroy commits!
Git keeps a "reflog" (reference log) of where HEAD has been for about 90 days. You can use this to recover "lost" commits.
### How to Recover from a Reset
1. View the reflog:
```bash
git reflog
```
Output example:
```
abc123 HEAD@{0}: reset: moving to HEAD~1
def456 HEAD@{1}: commit: Add broken helper D
...
```
2. Find the commit you want to recover (def456 in this example)
3. Reset back to it:
```bash
git reset def456
# Or use the reflog reference:
git reset HEAD@{1}
```
4. Your "lost" commit is back!
### Reflog Safety Net
**Important:**
- Reflog entries expire after ~90 days (configurable)
- Reflog is LOCAL to your repository (not shared)
- `git gc` can clean up old reflog entries
- If you really lose a commit, check reflog first!
**Pro tip:** Before doing dangerous operations, note your current commit hash:
```bash
git log --oneline | head -1
# abc123 Current work
```
## When to Use Git Reset
Use `git reset` when:
- ✅ **Commits are LOCAL only** (never pushed)
- ✅ **Cleaning up messy history** before sharing
- ✅ **Undoing recent commits** you don't want
- ✅ **Combining commits** into one clean commit
- ✅ **Unstaging files** (mixed mode)
- ✅ **Polishing commit history** before pull request
**Golden Rule:** Only reset commits that are local to your machine!
## When NOT to Use Git Reset
DO NOT use `git reset` when:
- ❌ **Commits are pushed/shared** with others
- ❌ **Teammates have your commits** (breaks their repos)
- ❌ **In public repositories** (use revert instead)
- ❌ **Unsure if pushed** (check `git log origin/main`)
- ❌ **On main/master branch** after push
- ❌ **Need audit trail** of changes
**Use git revert instead** (Module 05) for pushed commits!
## Decision Tree: Reset vs Revert
```
Need to undo a commit?
├─ Have you pushed this commit?
│ │
│ ├─ YES → Use git revert (Module 05)
│ │ Safe for shared history
│ │ Preserves complete audit trail
│ │
│ └─ NO → Can use git reset (local only)
│ │
│ ├─ Want to keep changes?
│ │ │
│ │ ├─ Keep staged → git reset --soft
│ │ └─ Keep unstaged → git reset --mixed
│ │
│ └─ Discard everything? → git reset --hard
│ (CAREFUL!)
```
## Reset vs Revert vs Rebase
| Command | History | Safety | Use Case |
|---------|---------|--------|----------|
| **reset** | Erases | ⚠️ Dangerous | Local cleanup before push |
| **revert** | Preserves | ✅ Safe | Undo pushed commits |
| **rebase** | Rewrites | ⚠️ Dangerous | Polish history before push |
**This module teaches reset.** You learned revert in Module 05.
## Command Reference
### Basic Reset
```bash
# Reset last commit, keep changes staged
git reset --soft HEAD~1
# Reset last commit, unstage changes (default)
git reset HEAD~1
git reset --mixed HEAD~1 # Same as above
# Reset last commit, discard everything (DANGEROUS!)
git reset --hard HEAD~1
# Reset multiple commits
git reset --soft HEAD~3 # Last 3 commits
# Reset to specific commit
git reset --soft abc123
```
### Unstaging Files
```bash
# Unstage a specific file (common use of reset)
git reset HEAD filename.txt
# Unstage all files
git reset HEAD .
# This is the same as:
git restore --staged filename.txt # Modern syntax
```
### Reflog and Recovery
```bash
# View reflog
git reflog
# Recover from reset
git reset --hard HEAD@{1}
git reset --hard abc123
```
### Check Before Reset
```bash
# Check if commits are pushed
git log origin/main..HEAD
# If output is empty, commits are pushed (DO NOT RESET)
# If output shows commits, they're local (safe to reset)
# Another way to check
git log --oneline --graph --all
# Look for origin/main marker
```
## Common Mistakes
### 1. Resetting Pushed Commits
```bash
# ❌ NEVER do this if you've pushed!
git push
# ... time passes ...
git reset --hard HEAD~3 # BREAKS teammate repos!
# ✅ Do this instead
git revert HEAD~3..HEAD # Safe for shared history
```
### 2. Using --hard Without Thinking
```bash
# ❌ Dangerous - loses work!
git reset --hard HEAD~1
# ✅ Better - keep changes to review
git reset --mixed HEAD~1
# Now you can review changes and decide
```
### 3. Resetting Without Checking If Pushed
```bash
# ❌ Risky - are these commits pushed?
git reset HEAD~5
# ✅ Check first
git log origin/main..HEAD # Local commits only
git reset HEAD~5 # Now safe if output showed commits
```
### 4. Forgetting Reflog Exists
```bash
# ❌ Panic after accidental --hard reset
# "I lost my work!"
# ✅ Check reflog first!
git reflog # Find the "lost" commit
git reset --hard HEAD@{1} # Recover it
```
## Best Practices
1. **Always check if commits are pushed before reset:**
```bash
git log origin/main..HEAD
```
2. **Prefer --mixed over --hard:**
- You can always discard changes later
- Hard to recover if you use --hard by mistake
3. **Commit often locally, reset before push:**
- Make many small local commits
- Reset/squash into clean commits before pushing
4. **Use descriptive commit messages even for local commits:**
- Helps when reviewing before reset
- Useful when checking reflog
5. **Know your escape hatch:**
```bash
git reflog # Your safety net!
```
6. **Communicate with team:**
- NEVER reset shared branches (main, develop, etc.)
- Only reset your personal feature branches
- Only before pushing!
## Troubleshooting
### "I accidentally reset with --hard and lost work!"
**Solution:** Check reflog:
```bash
git reflog
# Find the commit before your reset
git reset --hard HEAD@{1} # Or the commit hash
```
**Prevention:** Always use --mixed first, then discard if really needed.
### "I reset but teammates still have my commits"
**Problem:** You reset and pushed with --force after they pulled.
**Impact:** Their repository is now broken/inconsistent.
**Solution:** Communicate! They need to:
```bash
git fetch
git reset --hard origin/main # Or whatever branch
```
**Prevention:** NEVER reset pushed commits!
### "Reset didn't do what I expected"
**Issue:** Wrong mode or wrong HEAD~N count.
**Solution:** Check current state:
```bash
git status
git diff
git diff --cached
git log --oneline
```
Undo the reset:
```bash
git reflog
git reset HEAD@{1} # Go back to before your reset
```
### "Can't reset - 'fatal: ambiguous argument HEAD~1'"
**Issue:** No commits to reset (probably first commit).
**Solution:** You can't reset before the first commit. If you want to remove the first commit entirely:
```bash
rm -rf .git # Nuclear option - deletes entire repo
git init # Start over
```
## Advanced: Reset Internals
Understanding what reset does under the hood:
```bash
# Reset moves the branch pointer
# Before:
main → A → B → C (HEAD)
# After git reset --soft HEAD~1:
main → A → B (HEAD)
C still exists in reflog, just not in branch history
# The commit object C is still in .git/objects
# It's just unreachable from any branch
```
**Key insight:** Reset moves the HEAD and branch pointers backward. The commits still exist temporarily in reflog until garbage collection.
## Going Further
Now that you understand reset, you're ready for:
- **Module 07: Git Stash** - Temporarily save uncommitted work
- **Module 08: Multiplayer Git** - Collaborate with complex workflows
- **Interactive Rebase** - Advanced history polishing (beyond this workshop)
## Summary
You've learned:
- ✅ `git reset` rewrites history by moving HEAD backward
- ✅ `--soft` keeps changes staged (safest)
- ✅ `--mixed` (default) unstages changes
- ✅ `--hard` discards everything (most dangerous)
- ✅ NEVER reset pushed/shared commits
- ✅ Use reflog to recover from mistakes
- ✅ Check if commits are pushed before resetting
- ✅ Use revert (Module 05) for shared commits
**The Critical Rule:** Reset is for LOCAL commits ONLY. Once you push, use revert!
## Next Steps
1. Complete all three challenge scenarios
2. Run `./verify.ps1` to check your solutions
3. Practice checking if commits are pushed before reset
4. Move on to Module 07: Git Stash
---
**⚠️ FINAL REMINDER ⚠️**
**Before any `git reset` command, ask yourself:**
> "Have I pushed these commits?"
If YES → Use `git revert` instead!
If NO → Proceed carefully, choose the right mode.
**When in doubt, use --mixed instead of --hard!**