Git In Depth — The Real-World Playbook
How to use this page
Module 1 taught you Git for the daily job. This page is the reference you keep open when something goes wrong — the internals that explain why commands behave as they do, and a long catalogue of real incidents with copy-paste solutions. Skim it once so you know what's here; come back to it the day you commit a secret or a rebase explodes.
The one idea to carry through everything below: almost nothing in Git is ever truly deleted. Commits live on for weeks after you "lose" them. Once you internalize how Git stores history, every scary situation becomes a lookup, not a panic.
Part 1 — How Git Really Works (The Object Model)
Git is not a diff tool that stores changes. It is a content-addressed key–value store: you hand it content, it hands you back a hash (an SHA-1, or SHA-256 in newer repos), and that hash is forever the address of that exact content.
The four object types
Everything in .git/objects is one of four things:
| Object | Is | Points to |
|---|---|---|
| blob | the raw bytes of one file (no name, no metadata) | nothing |
| tree | one directory: a list of names → blob/tree hashes + modes | blobs and other trees |
| commit | a snapshot: one root tree + parent(s) + author/committer + message | one tree, zero-or-more parent commits |
| tag (annotated) | a named, signed pointer to a commit | one commit |
A commit does not store a diff. It stores a pointer to a complete tree (the whole project at that instant). "The diff" you see in git show is computed on the fly by comparing a commit's tree to its parent's tree.
# See it yourself — peek inside the object database:
git cat-file -t HEAD # → commit
git cat-file -p HEAD # prints: tree <hash>, parent <hash>, author..., message
git cat-file -p HEAD^{tree} # the root directory listing (names → hashes)
git rev-parse HEAD # the full commit hashAnalogy
Git is a warehouse where every item is filed by a fingerprint of its contents, not by its name. Two identical files anywhere in history are stored once (same content, same fingerprint). A commit is a numbered photograph of the entire warehouse floor at a moment in time, stapled to the photo taken just before it — follow the staples backwards and you have the whole history.
Why hashes matter
Because a commit's hash is derived from its content and its parent's hash, changing anything — a file, a message, a date, a parent — produces a completely new hash. This is why "editing history" (rebase, amend) never mutates a commit; it creates new commits with new hashes and leaves the originals sitting in the database, orphaned but recoverable.
Refs — the human-readable names
Hashes are unusable by humans, so Git keeps refs: tiny files containing a hash.
- A branch is a 41-byte file holding one hash. Creating a branch writes one file. That is why branches are "free."
- HEAD normally holds
ref: refs/heads/<branch>— a pointer to a pointer. When HEAD points straight at a commit hash instead of a branch, you are in detached HEAD (Scenario 12). git commitcreates a commit object, then advances the current branch ref to it. That is all a commit "moves."
Analogy
Refs are sticky-note labels on the warehouse photos. main is a note reading "latest approved photo"; moving it is just peeling the note onto a newer photo — no photo is copied or destroyed. HEAD is the "you are here" arrow, usually stuck to a label rather than directly to a photo.
The three areas, precisely
"the next snapshot" — files arrive here via git add
"committed history" — the index becomes a commit via git commit
And content flows back the other way — git restore / git checkout copy
from the index or HEAD into your working tree.
git status and git diff are just comparisons between these three:
git diff # working tree vs index (unstaged changes)
git diff --staged # index vs HEAD (what the next commit will contain)
git diff HEAD # working tree vs HEAD (everything uncommitted)Part 2 — Configuration Mastery
Config lives at three levels; the most specific wins: system (/etc/gitconfig) → global (~/.gitconfig) → local (.git/config).
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main
git config --global pull.rebase true # pull = fetch + rebase (linear history)
git config --global push.autoSetupRemote true # first push needs no -u
git config --global rerere.enabled true # remember conflict resolutions (Part 5)
git config --global fetch.prune true # auto-remove deleted remote branches
git config --global diff.colorMoved zebra # highlight moved (vs added) lines
git config --list --show-origin # every setting + which file set itAliases turn multi-word muscle memory into two letters:
git config --global alias.lg "log --oneline --graph --decorate --all"
git config --global alias.st "status -sb"
git config --global alias.last "log -1 HEAD --stat"
git config --global alias.unstage "restore --staged"
git config --global alias.amend "commit --amend --no-edit"Conditional includes — different identity per directory (work vs personal), a real must-have:
# ~/.gitconfig
[includeIf "gitdir:~/work/"]
path = ~/.gitconfig-work # sets your work email only under ~/work/Part 3 — The Everyday Commands, Deeper
Staging with precision
git add -p # stage HUNK BY HUNK — review each change, split (s), edit (e)
git add -N file # "intent to add" — makes an untracked file visible to git add -p
git restore --staged file # unstage (index → working), keep edits
git restore file # DISCARD working-tree edits (destructive — no reflog!)
git restore -p file # discard selected hunks onlyrestore/checkout of a file has no safety net
Uncommitted working-tree changes are not in the object database, so git restore file (or the old git checkout -- file) throws them away permanently — the reflog cannot bring them back. When unsure, git stash instead of discarding.
Reading history like a detective
git log --oneline --graph --decorate --all # the mental-model view
git log -p file # every change to one file, with diffs
git log -S "functionName" # commits that ADDED/REMOVED that string (the "pickaxe")
git log -G "regex" # commits whose diff matches a regex
git log --follow file # history across renames
git log main..feature # commits on feature NOT on main
git log --since="2 weeks ago" --author="alice"
git shortlog -sn # commit counts per author
git blame -L 10,20 file # who last touched lines 10–20
git blame -w -C file # ignore whitespace, detect moved codeA..B means "reachable from B but not A" (a range); A...B means "reachable from either but not both" (symmetric difference). This trips everyone up once — memorize it.
Part 4 — Branching & Merging, Deep
The two kinds of merge
before: A-B-C on main, feature adds D-E on top
after merge: main just slides forward to E — no new commit
main added commits after C, feature added D-E from B
after merge: a merge commit M with 2 parents ties both tips
together
- Fast-forward: no merge commit;
mainsimply advances. Clean, but loses the "these commits were a unit" information. Force a merge commit withgit merge --no-ffto preserve feature grouping. - Three-way: Git finds the common ancestor (the merge base), compares both tips to it, and records a merge commit with two parents.
Analogy
A three-way merge is two people editing photocopies of the same page, then a clerk reconciling them against the original master. Where only one side changed a line, the clerk takes that change silently; where both rewrote the same line differently, the clerk cannot choose and hands it back to you — that hand-back is the conflict. The "three" is the two edited copies plus the original they are both measured against (the merge base).
git merge feature # merge feature into current branch
git merge --no-ff feature # always create a merge commit (keeps feature history grouped)
git merge --squash feature # combine all feature work into ONE staged change (no merge commit)
git merge --abort # bail out of an in-progress conflicted mergeResolving conflicts methodically
A conflict is Git saying "you both changed the same lines; I won't guess."
<<<<<<< HEAD
port = 8080 ← your side (current branch)
=======
port = 3000 ← their side (branch being merged)
>>>>>>> feature/paymentgit status # lists "both modified" files — your worklist
# ...edit each file: pick the right content, delete ALL <<<<<<< ======= >>>>>>> markers...
git add config.py # marking THIS conflict resolved
git merge --continue # (or: git commit) once every file is added
# tools that help:
git mergetool # opens a 3-way visual merge tool
git checkout --ours file # take your version wholesale
git checkout --theirs file # take their version wholesale
git diff --check # find leftover conflict markers before committingrerere — never solve the same conflict twice
git config --global rerere.enabled true makes Git reuse recorded resolutions. The first time you resolve a given conflict it memorizes the fix; if the same conflict reappears (common during long-lived branches and repeated rebases), Git re-applies your resolution automatically. One setting, hours saved.
Part 5 — Rebase, Deep
Rebase replays your commits onto a new base, producing linear history — by creating new commits (new hashes) and abandoning the originals.
git rebase main # replay current branch's commits on top of main
git rebase --onto main old-base # replay ONLY commits after old-base onto main (surgical)
git rebase --continue # after resolving a conflict during rebase
git rebase --abort # give up, return exactly to where you started
git rebase --skip # drop the current conflicting commit and continueInteractive rebase — the history editor
git rebase -i HEAD~5 # opens an editor listing the last 5 commitspick a1b2c3 add login endpoint
squash b2c3d4 fix typo ← fold into the commit above
reword c3d4e5 wip ← keep commit, edit its message
edit d4e5f6 add tests ← pause here to amend the snapshot itself
drop e5f6a7 debug print ← delete this commit entirely
# reorder lines to reorder commitsfixup is squash but discards the folded message. Pair it with autosquash for a pro workflow:
git commit --fixup=a1b2c3 # makes a commit tagged "fixup! add login endpoint"
git rebase -i --autosquash HEAD~5 # auto-arranges the fixup next to its targetAnalogy
Interactive rebase is a film editor recutting raw footage before release. You reorder scenes, merge two takes into one, re-record a line of narration, or cut a blooper — but the moment the reel has been handed to other cinemas (pushed and pulled by teammates), you never recut it, or every cinema's copy disagrees about what the film is.
The iron rule of rewriting
rebase, commit --amend, and reset all rewrite history. Never rewrite commits others have already pulled. If you must (e.g., to purge a secret), coordinate with the team and everyone re-syncs deliberately. On shared branches, prefer revert (Part 6).
Part 6 — Undoing & Recovery (The Safety Net)
The three resets
git reset --soft HEAD~1 # move branch back 1; keep changes STAGED
git reset --mixed HEAD~1 # (default) move back; changes UNSTAGED but kept
git reset --hard HEAD~1 # move back; DISCARD working-tree + index changesThink of reset as answering "move the branch pointer to X, and what do I do with the differences?" — soft keeps them staged, mixed keeps them unstaged, hard obliterates them.
reset vs revert vs restore
| Command | Rewrites history? | Safe on shared branches? | Use for |
|---|---|---|---|
reset | yes (moves branch) | no | local cleanup before pushing |
revert | no (adds a new commit) | yes | undoing a pushed commit |
restore | no (touches files only) | yes | discarding/unstaging file changes |
The reflog — your time machine
Every time HEAD moves (commit, checkout, reset, rebase, merge) Git logs it. Even "destroyed" commits live in the reflog and object store for ~90 days (gc.reflogExpire).
git reflog # HEAD@{0}, HEAD@{1}... every position, with what moved it
git reflog show feature # a specific branch's movements
git reset --hard HEAD@{2} # jump back to how things were 2 moves ago
git branch recovered HEAD@{5} # resurrect a state as a new branchAlso handy: ORIG_HEAD is set before any "dangerous" operation (merge, reset, rebase), so git reset --hard ORIG_HEAD undoes the last one.
Analogy
The reflog is the security-camera roll of every move you made inside the warehouse, kept for three months — including walking to a shelf you later "cleared." Deleted the wrong commits? Roll the tape back to the timestamp just before the mistake and step back onto that spot. The commits were never gone; you just lost the sticky-note pointing at them.
Part 7 — Real-World Scenarios and Solutions
The heart of this page. Each entry is a situation you will meet, with the exact fix. Read the whole set once; the pattern-matching pays off under pressure.
Committing & message mistakes
Scenario 1 — "My last commit message has a typo (not pushed yet)."
git commit --amend -m "correct message" # replaces the last commitScenario 2 — "I forgot to add a file to the last commit (not pushed)."
git add forgotten.py
git commit --amend --no-edit # fold it in, keep the messageScenario 3 — "I already pushed the commit I want to amend." Amending rewrites the hash, so you must force-push — safely:
git commit --amend -m "better message"
git push --force-with-lease # refuses if someone else pushed meanwhileOnly do this on a branch that is yours (a feature/PR branch), never shared main.
Scenario 4 — "I committed to main but it should have been a feature branch."
git branch feature/x # create the branch pointing at your commit(s)
git reset --hard origin/main # move main back to the remote's tip
git switch feature/x # your work is safe on the new branchScenario 5 — "I need to split one big commit into several."
git rebase -i HEAD~1 # mark the commit "edit"
git reset HEAD~ # un-commit it, keeping changes unstaged
git add -p # stage the first logical chunk...
git commit -m "part 1" # ...commit it, repeat for the rest
git rebase --continueScenario 6 — "My last 4 commits are messy 'wip' noise; I want one clean commit."
git reset --soft HEAD~4 # un-commit all four, keep everything staged
git commit -m "feat: add rate limiter with tests"Undo & recovery
Scenario 7 — "Undo the last commit but keep my changes to keep working."
git reset --soft HEAD~1 # commit undone; changes stay stagedScenario 8 — "A bad commit is already on shared main and broke prod."
git revert a3f9c21 # NEW commit that undoes it; history stays honest
git pushScenario 9 — "I ran git reset --hard and destroyed commits I needed."
git reflog # find the hash from just before the reset, e.g. b7d2e9a
git reset --hard b7d2e9a # everything is backScenario 10 — "I deleted a branch that wasn't merged."
git reflog # or: git fsck --no-reflogs --lost-found
git branch recovered <hash-of-old-tip>Scenario 11 — "I discarded uncommitted changes with git restore — can I get them back?"
If they were never staged/committed: no (that is why the warning above exists). If you had ever git added them, git fsck --lost-found may recover a dangling blob. Lesson: git stash instead of discarding.
Scenario 12 — "Git says 'HEAD detached at a3f9c21' — what happened and how do I save my work?" You checked out a commit/tag directly, so HEAD points at a commit, not a branch. Any commits you make here are unreferenced and will be garbage-collected. Save them by naming them:
git switch -c fix-from-here # turns your detached work into a real branchHistory surgery
Scenario 13 — "I committed a secret (API key / password) and pushed it." Deleting it in a later commit is not enough — it lives in history forever. Correct order:
- Rotate/revoke the secret immediately (assume it is already scraped — bots find public keys in minutes).
- Scrub it from all history:
# modern, fast tool (pip install git-filter-repo):
git filter-repo --path config/secrets.yml --invert-paths # remove a file entirely
git filter-repo --replace-text <(echo 'AKIA...==>REDACTED') # or scrub a string everywhere
# then force-push and have EVERY collaborator re-clone
git push --force- Add the path to
.gitignoreand a secret-scanner (gitleaks) to CI so it cannot recur.
Scenario 14 — "A huge binary is bloating the repo (every clone is 2 GB)." Same tool; then migrate large files to Git LFS going forward:
git filter-repo --strip-blobs-bigger-than 10M
git lfs install && git lfs track "*.psd" && git add .gitattributesScenario 15 — "I need to change the author on old commits (wrong email)."
git filter-repo --mailmap my-mailmap.txt # maps old email → correct name/emailBranch & merge situations
Scenario 16 — "My feature branch is 30 commits behind main; I want it current with clean history."
git switch feature
git fetch origin
git rebase origin/main # replay your work on top of the latest main
# resolve any conflicts, then:
git push --force-with-leaseScenario 17 — "I want just ONE commit from another branch (a hotfix) on my release branch."
git switch release/1.4
git cherry-pick <hash> # copies that single commit here (new hash)
git cherry-pick A^..B # a range, inclusive of AScenario 18 — "I merged the wrong branch and already pushed the merge commit."
git revert -m 1 <merge-hash> # -m 1 = keep the FIRST parent's side (usually main)Reverting a merge needs -m to say which parent line to keep — omitting it errors out.
Scenario 19 — "A rebase is a mess of conflicts and I just want out."
git rebase --abort # returns you exactly to the pre-rebase stateWorking-tree & workflow
Scenario 20 — "An urgent bug arrives mid-feature; I have half-done uncommitted work."
git stash push -m "half-done payment form"
git switch -c hotfix/login && ...fix... && git switch feature
git stash pop # resume; (git stash list / git stash apply stash@{2} for more)git stash -u also stashes untracked files; git stash -p stashes selected hunks.
Scenario 21 — "I need to review a PR while keeping my current work untouched."
git worktree add ../review-pr origin/pr-branch # a SECOND working directory, same repo
# ...review/build there; your main working dir is undisturbed...
git worktree remove ../review-prScenario 22 — "Something broke somewhere in the last 200 commits; I don't know where."
git bisect start
git bisect bad # current commit is broken
git bisect good v1.3.0 # this old tag was fine
# Git checks out the midpoint; you test and mark git bisect good / bad
# ...repeat (log2(200) ≈ 8 steps)... Git names the exact culprit commit.
git bisect run ./test.sh # or fully automate it with a script that exits 0/non-0
git bisect reset # done — return to where you wereScenario 23 — "A file I already committed should be ignored (e.g., .env slipped in)."
.gitignore only affects untracked files. For an already-tracked one:
echo ".env" >> .gitignore
git rm --cached .env # stop tracking it, keep it on disk
git commit -m "chore: stop tracking .env"Scenario 24 — "git pull created an ugly merge commit; I want linear history."
git config --global pull.rebase true # make pull = fetch + rebase, permanently
# one-off: git pull --rebaseScenario 25 — "Line-ending hell: the whole file shows as changed but I edited one line."
git config --global core.autocrlf input # Linux/Mac: store LF, don't mangle
# and commit a .gitattributes: *.sh text eol=lfScenario 26 — "I want to undo a git add before committing."
git restore --staged file # (older: git reset HEAD file)Scenario 27 — "Clean out all untracked junk (build artifacts, stray files)."
git clean -nd # DRY RUN first — shows what WOULD be deleted
git clean -fd # actually delete untracked files + dirs
git clean -fdx # also remove ignored files (careful: nukes .env, node_modules)Part 8 — Remotes & Collaboration, Deep
git remote -v # list remotes and URLs
git remote add upstream <url> # e.g., the original repo you forked
git fetch --all --prune # update all remotes, drop deleted branches
git branch -vv # show each local branch's tracking + ahead/behind
git push -u origin feature # push and set upstream
git push --force-with-lease # safe force: aborts if remote moved unexpectedly
git switch --track origin/hotfix # create a local branch tracking a remote one--force-with-lease vs --force: plain --force overwrites the remote no matter what — it can silently destroy a teammate's pushed work. --force-with-lease first checks that the remote is still where you last saw it, and refuses otherwise. Always prefer --force-with-lease.
Analogy
Plain --force mails a replacement chapter to every library and orders them to bin whatever they currently hold — even a newer edition a colleague shelved an hour ago. --force-with-lease first checks that the shelf still holds the exact copy you last saw; if a newer one appeared, it refuses. Same envelope, one glance at the shelf first — and that glance is the whole difference between a clean fix and erasing someone's work.
Keeping a fork current:
git fetch upstream
git rebase upstream/main # or merge, per team norms
git push --force-with-leasePart 9 — Hooks & Automation
Hooks are scripts Git runs at lifecycle points (they live in .git/hooks, so they are not shared by default).
| Hook | Fires | Common use |
|---|---|---|
pre-commit | before a commit is created | lint, format, block secrets, run fast tests |
commit-msg | after message is written | enforce Conventional Commits |
pre-push | before a push | run the full test suite |
pre-receive / update | server-side, on push | enforce policy no client can bypass |
Because .git/hooks is local, teams use the pre-commit framework to version and share hooks:
# .pre-commit-config.yaml (run: pip install pre-commit && pre-commit install)
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks: [{ id: trailing-whitespace }, { id: end-of-file-fixer }, { id: check-yaml }]
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks: [{ id: gitleaks }] # blocks secrets BEFORE they ever get committedClient hooks are a convenience, not a control
A developer can skip client hooks with git commit --no-verify. Anything that must hold (no secrets, no direct push to main) belongs in server-side enforcement — branch protection rules and CI checks (Module 6), which no local flag can bypass.
Part 10 — Branching Strategies (Pick One On Purpose)
| Strategy | Shape | Best for |
|---|---|---|
| GitHub Flow | short-lived feature branches off main; PR; merge; deploy | continuous delivery, most web teams |
| Trunk-Based | tiny commits straight to main (behind feature flags), branches live hours | elite CI/CD, high deploy frequency |
| Git Flow | long-lived develop + release/* + hotfix/* + main | versioned/desktop software, scheduled releases |
Most modern DevOps shops run GitHub Flow or trunk-based — they keep main always deployable and make small, frequent, low-risk merges (exactly the CI/CD thesis of Module 6). Git Flow's heavier branching suits products that ship on a calendar, not on every merge.
Pair any of them with Conventional Commits (feat:, fix:, chore:, BREAKING CHANGE:) so tooling can auto-generate changelogs and version bumps (feat → minor, fix → patch, breaking → major).
Analogy
A branching strategy is your team's traffic system, and the choice is about how many cars (changes) you push through and how fast. Trunk-based is a busy roundabout — everyone keeps moving in tiny, constant merges, so nothing ever piles up. Git Flow is a scheduled ferry with staging lanes — right when releases depart on a timetable, needlessly slow when you just want to cross the street.
Part 11 — Security & Integrity
- Sign your commits so authorship can't be forged. SSH signing is the easy modern path:
bash
git config --global gpg.format ssh git config --global user.signingkey ~/.ssh/id_ed25519.pub git config --global commit.gpgsign true # add the same key as a "signing key" on GitHub → commits show "Verified" - Credential storage: use a helper, never plaintext.
git config --global credential.helper→manager(Windows),osxkeychain(Mac), orcache(Linux, in-memory). For servers/CI, prefer short-lived tokens or SSH deploy keys over passwords. - Never commit secrets (Scenario 13). Defense in depth:
.gitignore+ apre-commitgitleaks hook + a CI secret-scan + branch protection.
Part 12 — Git in CI/CD and GitOps (Where This Course Goes)
Everything above is why "if it's not in Git, it doesn't exist" is the DevOps mantra:
- CI triggers on Git events — a push or tag runs the pipeline (Module 6).
git tag v2.3.1is often the deploy signal; the tag is the release version. - Immutable version = commit SHA.
${{ github.sha }}becomes your Docker image tag, giving perfect traceability from a running container back to one exact commit. - GitOps (Module 12) makes a Git repo the desired state of your infrastructure: an agent in the cluster continuously reconciles reality to what's committed. Rollback becomes
git revert; the audit log becomesgit log. Every recovery skill in Part 6 is now an operations skill.
Analogy
In GitOps, the Git history you now know how to inspect, bisect, and revert is not just your code's story — it is the control panel for your entire production system. git revert stops being "undo a typo" and becomes "roll production back to 14:02," and git bisect becomes "find the exact change that started the outage." The reference you just read is, quietly, an incident-response manual.
Emergency Cheat Sheet (Bookmark This)
Undo last commit, keep changes staged ....... git reset --soft HEAD~1
Undo a PUSHED commit (safe) ................. git revert <hash> && git push
Recover "lost" commits after a hard reset ... git reflog → git reset --hard <hash>
Committed to wrong branch ................... git branch feature; git reset --hard origin/main
Amend last commit (pushed) ................. git commit --amend && git push --force-with-lease
Move one commit onto here .................. git cherry-pick <hash>
Get out of a broken rebase ................. git rebase --abort
Get out of a broken merge .................. git merge --abort
Stash work for an urgent switch ............ git stash → ... → git stash pop
Find the commit that broke it .............. git bisect start / good / bad (or: run)
Stop tracking an already-committed file .... git rm --cached <file>
Purge a secret from all history ............ rotate key → git filter-repo --path <f> --invert-paths
Preview what a clean would delete .......... git clean -nd
Detached HEAD — save the work .............. git switch -c <new-branch>Self-Check (You Know Git Deeply When…)
- You can explain why
commit --amendproduces a new hash and where the old commit goes. - You can recover any "lost" commit from the last few weeks without hesitating.
- You know when to
revert(shared history) vsreset(local) vsrestore(files) — instantly. - You reach for
--force-with-lease, never bare--force. - You can purge a leaked secret from history and know why rotating the key comes first.
- You can find a regression with
bisectin a few steps instead of reading 200 diffs. - You treat
git reflogas the first move when anything looks lost — because almost nothing ever is.
