Learning Objectives
- Use
git bisectto find the commit that caused a regression - Master
cherry-pickfor a single commit or a range - Get the most out of
git stashwith named stashes - Understand
git worktree,submodulevssubtree, andsparse-checkout - Install and configure Git hooks with Husky/lint-staged
- Recognize the monorepo context (Nx, Turborepo)
1. git bisect — Binary Search for Regressions
git bisect uses binary search to find the first commit that introduced a bug.
Manual workflow
# Scenario: feature X works in v1.0.0 but is broken at HEAD
# You need to find which of 200 commits caused the bug
# Start a bisect session
git bisect start
# Mark the "bad" commit (currently buggy)
git bisect bad HEAD
# Mark the "good" commit (last known OK)
git bisect good v1.0.0
# Git checks out a commit in the middle (around commit 100)
# You test it: if the bug is still there → bad, if OK → good
npm test
git bisect bad # or git bisect good
# Git keeps halving → checks out the next commit
# Repeat until Git identifies the culprit commit:
# abc1234 is the first bad commit
# commit abc1234
# Author: Dev <dev@team.com>
# Date: ...
# feat: refactor payment processor
# End the bisect and return to HEAD
git bisect reset
Automating with bisect run
# Write a test script: exit 0 = good, exit 1-127 (except 125) = bad, exit 125 = skip the commit
cat test-bisect.sh
#!/bin/bash
npm install --silent
npm test -- --testNamePattern="payment processor"
chmod +x test-bisect.sh
# Let Git bisect automatically
git bisect start
git bisect bad HEAD
git bisect good v1.0.0
git bisect run ./test-bisect.sh
# Git runs the script at every step → finds the bad commit with no manual intervention
git bisect reset
Number of bisect steps needed
200 commits → ~8 steps (log2(200) ≈ 7.6)
1000 commits → ~10 steps
10000 commits → ~14 steps
2. cherry-pick — Picking Specific Commits
Cherry-pick applies the changes from a commit onto the current branch without merging the whole branch.
Cherry-picking a single commit
# Scenario: a bug fix on hotfix/1.2.1 needs to be backported to develop
git switch develop
# Cherry-pick one commit
git cherry-pick abc1234
# Cherry-pick and edit the message
git cherry-pick abc1234 --edit
# Cherry-pick without committing automatically (only stage the changes)
git cherry-pick abc1234 --no-commit
# Review the changes before committing
git diff --staged
git commit -m "fix: backport payment validation fix"
Cherry-picking a range
# Cherry-pick from commit A to commit B (inclusive)
git cherry-pick A^..B
# The ^ after A = A's parent → the range A^..B includes A (from A to B inclusive)
# Example: cherry-pick 3 commits abc, def, ghi
git cherry-pick abc^..ghi
# Equivalent to cherry-picking abc, def, ghi in order
# If a conflict occurs during a range cherry-pick:
git cherry-pick --continue # after resolving
git cherry-pick --abort # cancel everything
git cherry-pick --skip # skip the current commit
When to use cherry-pick instead of merge/rebase?
Use cherry-pick when:
✓ Backporting a specific bug fix to an older release branch
✓ Grabbing a feature commit from an abandoned branch
✓ Applying a hotfix to multiple release versions (1.x, 2.x)
Don't use cherry-pick when:
✗ You want to merge a whole feature → use merge
✗ Syncing a fork with upstream → use rebase
✗ Cherry-picking the same commit many times → messy history, duplicate SHAs
3. Advanced git stash
Named stashes and managing multiple stashes
# Stash with a meaningful name
git stash push -m "WIP: payment refactor — validation half done"
git stash push -m "experiment: GraphQL schema draft"
# List stashes
git stash list
# stash@{0}: On feature/payment: WIP: payment refactor — validation half done
# stash@{1}: On feature/graphql: experiment: GraphQL schema draft
# stash@{2}: WIP on main: abc1234 chore: update deps
# Inspect a stash
git stash show stash@{1} # summary of changed files
git stash show -p stash@{1} # full diff
# Apply a stash without removing it (keep it in the stash list)
git stash apply stash@{1}
# Pop a stash (apply + remove from the list)
git stash pop stash@{0}
# Pop the default stash (stash@{0} — the most recent)
git stash pop
# Drop a specific stash
git stash drop stash@{2}
# Drop all stashes
git stash clear
Advanced stash options
# Also stash untracked files (--include-untracked)
git stash push -u -m "WIP: including new files"
# Stash untracked + ignored files as well
git stash push -a -m "WIP: full save including ignored"
# Stash only staged changes (leave unstaged ones alone)
git stash push --staged -m "Only staged changes"
# Create a new branch from a stash (useful when the stash conflicts with current code)
git stash branch feature/new-from-stash stash@{1}
# Creates a branch at the stash's commit, applies the stash, drops the stash
4. git worktree — Multiple Working Directories
git worktree lets you check out multiple branches at once into different directories — no extra clone needed.
# Scenario: you're working on feature/new-ui and need an urgent hotfix on main
# You don't want to stash or commit WIP
# List current worktrees
git worktree list
# Create a new worktree for the hotfix
git worktree add ../hotfix-1.2.1 main
# Creates the directory ../hotfix-1.2.1/ with branch main checked out
# Branch main lives in the other worktree, without affecting feature/new-ui here
# Work in the new worktree
cd ../hotfix-1.2.1
git switch -c hotfix/1.2.1
vim src/api/auth.ts
git add . && git commit -m "fix: critical security patch"
git push origin hotfix/1.2.1
# Go back to the main worktree
cd ../original-project
# feature/new-ui is untouched, completely unaffected
# Remove the worktree when done
git worktree remove ../hotfix-1.2.1
# Or force-remove if there are still uncommitted changes
git worktree remove --force ../hotfix-1.2.1
Advantages over stash
stash: fast, simple, good for short interruptions
git worktree: true parallelism, good for:
- a multi-day hotfix while the feature is running CI
- reviewing a PR without interrupting the feature branch
- comparing code between 2 branches side by side
- testing on multiple branches at once
5. Submodule vs Subtree
Two ways to embed another repository inside yours.
Git Submodule
# Add a submodule
git submodule add https://github.com/org/shared-utils.git lib/shared-utils
# Clone a repository that has submodules
git clone --recurse-submodules https://github.com/org/main-project.git
# Or after a normal clone:
git submodule init && git submodule update
# Update the submodule to the latest version
cd lib/shared-utils
git pull origin main
cd ../..
git add lib/shared-utils
git commit -m "chore: update shared-utils to latest"
# Remove a submodule (takes several steps)
git submodule deinit lib/shared-utils
git rm lib/shared-utils
rm -rf .git/modules/lib/shared-utils
Git Subtree
# Add a subtree (no .gitmodules file needed)
git subtree add --prefix lib/shared-utils \
https://github.com/org/shared-utils.git main --squash
# Update the subtree
git subtree pull --prefix lib/shared-utils \
https://github.com/org/shared-utils.git main --squash
# Push changes back to the remote
git subtree push --prefix lib/shared-utils \
https://github.com/org/shared-utils.git main
Comparison
6. sparse-checkout — Monorepo Subset
Check out only part of a large monorepo.
# Clone without checking out any files
git clone --no-checkout --depth=1 https://github.com/big-org/monorepo.git
cd monorepo
# Enable sparse-checkout and pick the packages to check out
# (cone mode is the default; `git sparse-checkout init` is deprecated)
git sparse-checkout set packages/frontend packages/shared-ui
# Checkout
git checkout main
# See the checked-out files
ls
# Add another package
git sparse-checkout add packages/api-gateway
# Disable sparse-checkout (check out everything)
git sparse-checkout disable
7. Git Hooks
Git hooks are scripts that run automatically at specific points in the Git workflow.
Common hooks
Client-side hooks (in .git/hooks/):
pre-commit → runs before a commit is created (lint, format, test)
commit-msg → validates the commit message (Conventional Commits format)
pre-push → runs before a push (test suite, type-check)
post-merge → runs after a merge (npm install if package.json changed)
post-checkout → runs after checking out a branch
Server-side hooks (on the remote server):
pre-receive → validates before accepting a push
post-receive → triggers a deploy after accepting a push
Writing a hook by hand
# Example pre-commit hook: block the commit if console.log remains
cat .git/hooks/pre-commit
#!/bin/bash
if git diff --cached --name-only | xargs grep -l "console\.log" 2>/dev/null; then
echo "Error: Remove console.log before committing"
exit 1
fi
exit 0
chmod +x .git/hooks/pre-commit
# Example commit-msg hook: validate Conventional Commits format
cat .git/hooks/commit-msg
#!/bin/bash
commit_msg=$(cat "$1")
pattern="^(feat|fix|docs|style|refactor|perf|test|chore|build|ci|revert)(\(.+\))?: .{1,72}"
if ! echo "$commit_msg" | grep -Eq "$pattern"; then
echo "Error: Commit message must follow Conventional Commits format"
echo "Example: feat: add user authentication"
exit 1
fi
exit 0
chmod +x .git/hooks/commit-msg
Husky — Git Hooks for Node.js Projects
# Install Husky (makes hooks easier to manage, shareable via npm)
npm install --save-dev husky
npx husky init
# Add a pre-commit hook
echo "npx lint-staged" > .husky/pre-commit
# Add a commit-msg hook (validated with commitlint)
npm install --save-dev @commitlint/cli @commitlint/config-conventional
echo "npx --no -- commitlint --edit \$1" > .husky/commit-msg
# commitlint config
cat commitlint.config.js
module.exports = { extends: ['@commitlint/config-conventional'] };
lint-staged — Lint Only Changed Files
# Install
npm install --save-dev lint-staged
# Configure in package.json
{
"lint-staged": {
"*.{ts,tsx}": ["eslint --fix", "prettier --write"],
"*.{js,jsx}": ["eslint --fix", "prettier --write"],
"*.{css,scss}": ["prettier --write"],
"*.md": ["prettier --write"]
}
}
# Workflow:
# git add src/auth.ts
# git commit -m "feat: add auth"
# → Husky pre-commit: runs lint-staged
# → lint-staged: lints only src/auth.ts (not the whole project)
# → ESLint fix + Prettier format
# → Auto re-stage if anything was fixed
# → The commit continues
8. Monorepo Context — Nx and Turborepo
A monorepo is a single Git repository that contains many packages/applications.
Turborepo — Task Caching
# Install
npx create-turbo@latest
turbo.json — defines the task graph (turbo 2.x uses the tasks key; older 1.x versions use pipeline):
{
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": [".next/**", "dist/**"]
},
"test": {
"dependsOn": ["build"],
"outputs": ["coverage/**"]
},
"lint": {
"outputs": []
}
}
}
"dependsOn": ["^build"] — the ^ means run build for the package's dependencies first, then build the current package. (JSON doesn't support comments, so the explanation lives outside the file.)
# Run build for all packages (with caching)
npx turbo run build
# Build only the packages affected by the current change
npx turbo run build --filter=[HEAD^1]
# Remote caching (share the cache with your team via Vercel)
npx turbo login
npx turbo link
Git + Monorepo tips
# Find packages affected by a change
git diff --name-only HEAD~1 HEAD | sed 's|/.*||' | sort -u
# Or use Nx:
npx nx affected --target=test --base=main --head=HEAD
# Conventional Commits with a scope for monorepos
git commit -m "feat(ui): add Button variant outline"
git commit -m "fix(api): resolve auth middleware race condition"
git commit -m "chore(config): update shared ESLint rules"
Review Questions
-
What exit codes does the script for
git bisect runneed in order to distinguish "good" from "bad"?Show answer
Exit code 0 = "good" commit (the bug hasn't appeared yet). An exit code from 1 to 127, except 125 = "bad" commit (the bug is present); a code outside that range (e.g. 128 and above) aborts the bisect. The script is usually a test runner:
npm testexits 0 on pass, 1 on failure. Special case: exit code 125 = "skip this commit" (e.g. a compile error unrelated to the bug you're hunting). -
What does
git cherry-pick A^..Bmean? What does the^after A do?Show answer
It cherry-picks from commit A to commit B in order, inclusive. The
^after A means A's parent — so the rangeA^..B= "from A (inclusive) to B (inclusive)". Without the^(writingA..B), the range starts at the commit after A (A is excluded). Example:git cherry-pick abc^..defcherry-picks abc, def, and every commit in between. -
What is the difference between
git stash applyandgit stash pop?Show answer
Both apply the stash to the working directory. The difference:
git stash applyapplies the stash but keeps it in the stash list.git stash popapplies the stash and removes it from the stash list (apply + drop). Useapplywhen you want to apply the same stash to several branches; usepopwhen you're sure you only need to apply it once. -
When should you use
git worktreeinstead ofgit stash?Show answer
Use
git worktreewhen you need to work on two branches in parallel for a longer time: e.g. a multi-day hotfix while the feature has CI running, reviewing a PR without interrupting your feature branch, or comparing code between 2 branches side by side in the IDE. Usegit stashfor short interruptions (< a few hours) because it's simpler. Worktree = two truly parallel working directories; stash = temporarily set aside and restore. -
Why is lint-staged more efficient than linting the whole project in a pre-commit hook?
Show answer
lint-staged runs the linter only on staged files (the files going into this commit), instead of scanning the whole project. A large project can have thousands of files — linting all of them on every commit takes minutes, frustrating developers until they skip the hook. lint-staged finishes in seconds because it only lints the 1-5 changed files — the commit flow isn't blocked. Result: the hook gets respected and the codebase stays cleaner.
Hands-on Exercises
mkdir advanced-tools-lab && cd advanced-tools-lab
git init -b main
git config user.name "Dev" && git config user.email "dev@test.com"
git config rerere.enabled true
# === BISECT LAB ===
# Create a history with a "bug" in commit 5 (append with >> so the bug stays until HEAD)
for i in 1 2 3 4 5 6 7 8 9 10; do
echo "code version $i" >> app.js
# Commit 5: add the "bug"
if [ $i -eq 5 ]; then
echo "BUG_INTRODUCED=true" >> app.js
fi
git add . && git commit -m "feat: version $i"
done
# Bisect to find the commit that introduced BUG_INTRODUCED
git bisect start
git bisect bad HEAD
git bisect good HEAD~9 # commit 1 is good
# Test script
cat > /tmp/test-bisect.sh << 'EOF'
#!/bin/bash
if grep -q "BUG_INTRODUCED" app.js; then
exit 1 # bad
fi
exit 0 # good
EOF
chmod +x /tmp/test-bisect.sh
git bisect run /tmp/test-bisect.sh
# Git finds the commit "feat: version 5"
git bisect reset
# === CHERRY-PICK LAB ===
git switch -c hotfix/backport
echo "critical fix" >> app.js
git add . && git commit -m "fix: critical security patch"
CHERRY_HASH=$(git rev-parse HEAD)
git switch main
git cherry-pick $CHERRY_HASH
git log --oneline -3
# === STASH LAB ===
echo "WIP code" >> app.js
git stash push -m "WIP: important feature in progress"
# Make another change so there is a second stash
echo "experiment" >> app.js
git stash push -m "experiment: trying new approach"
git stash list
git stash show -p stash@{1}
git stash pop stash@{1}
# === WORKTREE LAB ===
# main is checked out in the main repo, so the worktree needs a new branch
git worktree add -b hotfix/demo ../lab-hotfix main
git worktree list
# Work inside the worktree
echo "hotfix content" > ../lab-hotfix/hotfix.js
cd ../lab-hotfix && git add . && git commit -m "fix: hotfix via worktree"
cd ../advanced-tools-lab
git log hotfix/demo --oneline -3
git worktree remove ../lab-hotfix
git branch -D hotfix/demo
References
- git bisect documentation
- git cherry-pick documentation
- git stash documentation
- git worktree documentation
- git submodule documentation
- Husky — Git Hooks
- lint-staged
- Turborepo Documentation