Ch 04Time Travel & History Surgery: `git reset` (Soft, Mixed, Hard) & `git cherry-pick`
Chapter 04 of 05·25 min

Time Travel & History Surgery: `git reset` (Soft, Mixed, Hard) & `git cherry-pick`

Every engineer makes mistakes: committing half-finished code, including accidental API keys, writing typo-ridden commit messages, or wanting a single bug-fix commit from an experimental branch without merging weeks of unfinished work. Git provides surgical time-travel primitives to handle these exact scenarios. In this chapter, you will master `git reset` across its three distinct modes (`--soft`, `--mixed`, `--hard`), understand why you should never reset public history (and use `git revert` instead), and perform surgical commit transplants using `git cherry-pick`.

Learning objectives
  • 01Deconstruct how Git's Three Trees (HEAD, Index/Staging, and Working Directory) behave during undo operations
  • 02Master the three operational modes of git reset: --soft (preserves staging), --mixed (un-stages changes), and --hard (wipes changes)
  • 03Safely recover from accidental data loss using Git's internal flight recorder: git reflog
  • 04Internalize the Golden Rule of Git: why git reset is strictly for local private history, and git revert is used for pushed public history
  • 05Surgically transplant individual commits from one branch to another using git cherry-pick
  • 06Resolve and finalize cherry-pick merge conflicts using git cherry-pick --continue and git cherry-pick --abort

4.1 The Anatomy of Undoing: Git's Three Trees Revisited

To understand how Git undoes changes, remember where your code lives at any moment: 1. **HEAD (Commit History)**: The last recorded snapshot on your current branch in `.git`. 2. **Index (Staging Area)**: The prepared snapshot for your next commit. 3. **Working Directory**: The actual readable files on your computer's filesystem. When you run `git reset <commit>`, you are telling Git to move the current branch pointer (and `HEAD`) backward to a previous commit. What happens to your Index and Working Directory depends entirely on which flag you pass: `--soft`, `--mixed`, or `--hard`.
Understanding HEAD~1
`HEAD` represents your current latest commit. `HEAD~1` (or `HEAD^`) refers to the immediate parent commit (1 commit before HEAD). `HEAD~2` refers to 2 commits back.

4.2 `git reset` Demystified: The Three Modes (--soft, --mixed, --hard)

Here is the definitive architectural comparison of the three reset modes: | Mode | Moves HEAD? | Modifies Staging Index? | Modifies Working Directory? | Typical Real-World Use Case | |---|---|---|---|---| | **`--soft`** | **YES** | **NO** (remains staged) | **NO** (untouched) | Fix commit message, combine multiple commits before pushing | | **`--mixed`** (default) | **YES** | **YES** (un-stages changes) | **NO** (untouched) | Un-stage accidentally staged files to re-stage them cleanly | | **`--hard`** | **YES** | **YES** (un-stages changes) | **YES** (overwrites files) | Discard completely broken experiments and return to known good state | ### 1. `git reset --soft HEAD~1` (The Surgical Undo) Moves the branch pointer back 1 commit. The changes from the undone commit remain staged in your Index. This is perfect if you committed too early, made a typo in the commit message, or forgot to add a file. ### 2. `git reset --mixed HEAD~1` (The Default Reset) Moves the branch pointer back 1 commit and clears the staging area. All the file changes remain safely in your working directory as unstaged modifications. This lets you re-examine files with `git diff` and stage them with surgical precision. ### 3. `git reset --hard HEAD~1` (The Nuclear Option) Moves the branch pointer back, clears the staging index, AND overwrites all files in your working directory to match the target commit snapshot. Any uncommitted work is permanently erased!
The Golden Rule: Never Reset Pushed History
Never use `git reset` on commits that have already been pushed to a shared remote (like `origin/main`). Doing so rewrites history, forcing a rejected push (`fetch first`) and corrupting teammates' repositories.
Terminal Command 1: Soft vs Hard Reset in Practice

Undo a commit softly to amend code, and use git reflog to recover from a hard reset.

# Scenario A: Soft reset to reword or add files to the last commit
git commit -m "wip: bad commit message with typos"

# Undo the commit, keeping all changes staged in the Index
git reset --soft HEAD~1

# Check status: notice changes are still staged (green)!
git status -s

# Re-commit with a clean, professional commit message
git commit -m "feat(heuristics): implement baseline risk score threshold"

# Scenario B: Hard reset to discard an experimental failure
# DANGER: permanently overwrites modified files in working directory!
git reset --hard HEAD~1

# Scenario C: Recovering an 'erased' commit using Git's flight recorder (reflog)
git reflog
# Output shows: 7a8b9c0 HEAD@{1}: commit: ...
# Restore the lost commit:
git reset --hard HEAD@{1}
Execution walkthrough
  1. 1.Run git reset --soft HEAD~1: the commit disappears from git log, but your files remain staged.
  2. 2.Run git status to verify files are staged and ready for a revised commit message.
  3. 3.If git reset --hard is ever run accidentally, immediately run git reflog to locate the lost commit hash.
  4. 4.Run git reset --hard <hash> to restore your repository to that exact point in time.
Expected output
[main a1b2c3d] feat(heuristics): implement baseline risk score threshold
 1 file changed, 3 insertions(+)
Edge cases

• Uncommitted files (untracked or unstaged modifications) overwritten by git reset --hard CANNOT be recovered by reflog, because Git never took a snapshot of them! Always commit or stash before running a hard reset.

Why it happens: Git never deletes commit objects immediately. Even after a hard reset, the commit objects remain in .git/objects for weeks until garbage collection runs, letting reflog rescue you.

4.3 Reversing Public Commits Safely: `git revert`

When a buggy commit has already been pushed to GitHub and pulled by your team, you cannot rewrite history with `git reset`. Instead, you use `git revert <commit-hash>`. ### How `git revert` Works Unlike `reset` (which removes commits from history), `revert` creates a **brand-new forward commit** that applies the exact inverse mathematical diff of the target commit: • If the buggy commit added lines 10-15, the revert commit deletes lines 10-15. • If the buggy commit deleted a file, the revert commit restores that file. Because `git revert` only moves history forward, it can be pushed cleanly to GitHub without requiring force-pushing (`--force`).
Terminal Command 2: Reverting a Public Commit

Create an inverse commit to safely undo a change on a shared branch.

# View recent commit hashes
git log --oneline -n 3

# Revert a specific buggy commit (creates a new inverse commit)
git revert a1b2c3d --no-edit

# Inspect history: notice a new 'Revert ...' commit exists
git log --oneline -n 2
Execution walkthrough
  1. 1.Find the hash of the commit you need to undo with git log --oneline.
  2. 2.Run git revert <hash>.
  3. 3.Git applies the inverse diff and creates a new commit snapshot.
  4. 4.Push the new revert commit to GitHub with standard git push.
Expected output
[main e5f6a7b] Revert "feat: experimental payment endpoint"
 1 file changed, 10 deletions(-)

Why it happens: Linear history is preserved, and your teammates will cleanly pull the reversal without any merge conflicts.

4.4 Surgical Commit Transplant: `git cherry-pick`

Imagine you are working on a long-running experimental branch (`experiment-llm`) with 12 un-reviewed commits. In commit #3 (`c8d9e0f`), you discovered and fixed a critical security vulnerability that affects production `main`. You cannot merge `experiment-llm` into `main` because the other 11 commits are unfinished and unstable. How do you extract and apply **only commit #3** to `main`? The answer is **`git cherry-pick <commit-hash>`**. ### The Cherry-Pick Process: 1. Find the commit hash on the source branch: `git log --oneline experiment-llm` 2. Switch to your destination branch: `git switch main` 3. Execute the cherry-pick: `git cherry-pick c8d9e0f` Git extracts the exact patch introduced by `c8d9e0f` and replays it on top of `main`, creating a new commit snapshot with identical changes and commit message, but a fresh timestamp and hash.
Cherry-Pick Creates a New Hash
Because the cherry-picked commit now has a different parent commit on main, Git calculates a new SHA hash. While the code changes are identical, it is technically a distinct commit object.
Terminal Command 3: Cherry-Picking a Commit Across Branches

Extract a specific commit from a feature branch and transplant it onto main.

# Step 1: Inspect the feature branch to find the desired commit hash
git log --oneline feature/experimental-heuristics -n 3

# Step 2: Switch to the destination branch (main)
git switch main

# Step 3: Cherry-pick the specific bug-fix commit (e.g. c8d9e0f)
git cherry-pick c8d9e0f

# If a conflict occurs during cherry-pick:
# 1. Edit the conflicted file to resolve markers
# 2. Stage the resolved file: git add <file>
# 3. Complete cherry-pick: git cherry-pick --continue
# (Or abort safely: git cherry-pick --abort)
Execution walkthrough
  1. 1.Use git log to identify the SHA-1 hash of the specific commit you want.
  2. 2.Always switch to the destination branch before cherry-picking.
  3. 3.Run git cherry-pick <hash>.
  4. 4.Verify with git log --oneline: the commit now appears at the top of your destination branch.
Expected output
[main 4a5b6c7] fix(security): sanitize email header control characters
 1 file changed, 5 insertions(+)
 create mode 100644 security.py
Edge cases

• Cherry-pick conflicts: If the code in the cherry-picked commit depends on prior changes on the source branch that do not exist on main, Git halts with a conflict. Resolve the file, git add it, and run git cherry-pick --continue.

Why it happens: Cherry-pick applies a diff rather than merging branch pointers, making it ideal for hotfixes and extracting isolated utilities.

Practice exercise

Work through the exercise before starting the chapter assignment

Exercise 4: Practice Soft Reset & Cherry-Pick Workflow

intermediate

Open your terminal in a test Git repository and execute: (1) create a test commit, (2) undo it softly with git reset --soft HEAD~1, (3) verify changes remain staged with git status, and (4) cherry-pick a commit using its hash.

Chapter summary

Key concepts and syntax cards for review

Key concepts
  • 01git reset moves the branch pointer and HEAD backward across your commit history
  • 02--soft moves HEAD but preserves Staging Index and Working Tree (ideal for fixing commit messages)
  • 03--mixed (default) moves HEAD and un-stages files, preserving Working Tree modifications
  • 04--hard moves HEAD, un-stages files, and overwrites working files (destructive!)
  • 05git reflog records every movement of HEAD, enabling recovery of commits lost during hard resets
  • 06Never reset pushed public history; use git revert to create a safe inverse forward commit
  • 07git cherry-pick surgically transplants an individual commit from one branch to another
Syntax reference
git reset --soft HEAD~1Undoes the latest commit, keeping all changes staged in the Index
git reset --mixed HEAD~1Undoes latest commit and un-stages changes into the working directory (default)
git reset --hard HEAD~1Undoes latest commit and discards all uncommitted working directory changes
git reflogDisplays the chronological log of all HEAD pointer movements for disaster recovery
git revert <commit-hash>Creates a new commit that applies the exact inverse changes of a targeted commit
git cherry-pick <commit-hash>Applies the changes from a specific commit on another branch onto the current branch
git cherry-pick --continueResumes an interrupted cherry-pick operation after resolving merge conflicts
git cherry-pick --abortCancels an in-progress cherry-pick conflict and restores original branch state

Knowledge check

Verify your grasp of the chapter concepts

Which command undoes your latest commit while keeping all modified files safely staged in the Index?

When should you use 'git cherry-pick <commit>'?