00.3 Git Fundamentals
Every serious software project — including every project in this learning path — lives in git, the version-control system that remembers every version of every file, lets you experiment safely on branches, and lets hundreds of people work on the same codebase without destroying each other's work. This lesson teaches git from zero: what a commit actually is, the three areas every file moves through, the daily loop of status/add/commit/diff/log, .gitignore and .gitattributes, branches and merges (including resolving conflicts), how to undo almost anything safely, and the everyday tools — stash, tag, blame, bisect — that turn git from a save button into a debugging and collaboration superpower. GitHub, pull requests and team workflows are the subject of the next lesson; here the focus is the tool itself, practised in a small repository — ai-path — that you build up as you go.
What you'll learn
- Why version control exists, a short history of git and GitHub, and the mental model underneath everything: content-addressed snapshots forming a commit graph
- How to install nothing new — git is already on your machine — and configure your identity, default branch, editor and line-ending behaviour
- The three areas of git (working tree, staging area, repository),
git statusline by line, and the daily loop:add,commit,diff,log,show,restore,rm,mv— plus how to name any commit (HEAD,~,^, ranges,rev:path) - How to write commit messages people (and tools) can use: imperative mood, atomic commits, and Conventional Commits
.gitignorepattern rules, global ignores, untracking committed files,.gitattributesand line endings, why secrets and large files must never enter history, and what Git LFS is for- Branches:
switchvscheckout, fast-forward vs merge commits, reading and resolving merge conflicts,merge --abort, rebase (and the rule about shared history),cherry-pick, and detached HEAD - Undoing things safely: a decision table covering unstage, discard, amend, revert,
reset --soft/--mixed/--hard, thereflogsafety net, recovering deleted branches and lost commits, and what is truly unrecoverable - Everyday tools:
stash, annotated vs lightweight tags,blame,bisect,git grep, aliases,worktree, submodules, and living with large repositories - Workflows and habits: feature branches, small commits, pulling before pushing, never working on
mainin a team, tags for releases — and a "git panic" decision tree for when things go wrong
What you don't need
- Any prior version-control experience. If you've used SVN, Mercurial or Perforce, the "Coming from another stack" callouts will map the ideas across.
- A GitHub account or any network access. Nearly everything here runs in local scratch repositories. Remote workflows —
clone,push,pull, pull requests — are previewed briefly and taught properly in 00.4: GitHub and Collaboration. - Python or any programming language, though the running example is a small Python project because that's what the rest of the path uses.
Setup
You need a working terminal and text editor — 00.1: Setting Up Your Computer covers both if you haven't done it — and git itself, which 00.1 has you install and verify with git --version. No API key is needed for anything in this lesson.
The commands below are written for bash/zsh (macOS, Linux, WSL). On Windows, run them in WSL 2 or Git Bash; the git commands themselves are identical, and differences in file commands (cat, ls) are covered in 00.2. Parts 2–4 build your real ai-path repository; everything that rewrites or destroys history (Parts 5–7 and the Exercises) is meant for a throwaway directory so your real files are never touched (8.3 explains the split). Make a scratch folder now:
SCRATCH=$(mktemp -d) # macOS/Linux/WSL — a fresh empty temp folder
echo $SCRATCH # remember this path; it is your playground
cd $SCRATCHOn Windows PowerShell the equivalent is:
$SCRATCH = Join-Path $env:TEMP ("gitdemo-" + [guid]::NewGuid().ToString("N").Substring(0,8))
New-Item -ItemType Directory -Path $SCRATCH | Out-Null
Set-Location $SCRATCHThe heredoc file creation below (cat > file <<'EOF') needs bash/zsh/WSL/Git Bash — in PowerShell, create the same files in your editor or with Set-Content; every git command itself is identical.
What you must be able to do after this lesson#
- Explain working tree, staging area and repository
- Run the daily loop of add, commit, diff and log
- Write a clear commit message
- Keep secrets and large files out of git with .gitignore
- Create a branch, merge it and resolve a merge conflict
- Undo a mistake safely with restore, revert or reset and find lost work with reflog
Why this matters for an AI engineer#
Git is not a "developer tool" you can postpone — it is the substrate the whole path runs on. Your ai-path workspace becomes a git repository in this lesson and stays one forever. Prompts are versioned like code, CI runs on commits, every provider API key must stay out of history, and "which version of this file produced that output?" is a question only git can answer.
| You'll hear... | You'll understand it after... |
|---|---|
| "Just commit it and push." | Part 3: The daily loop |
| "What's the commit hash / SHA for this build?" | 1.3 Snapshots, not diffs |
"Rebase your branch onto main before the PR." |
5.4 Rebase, cherry-pick and friends |
"You can't force-push to main." |
Part 6: Undoing things safely |
"Check the reflog — the commit is probably still there." |
6.5 The reflog: git's safety net |
"Add it to .gitignore first." |
Part 4: What never goes into git |
| "That file is in LFS." | 4.5 Large files and Git LFS |
| "Bisect it — find the commit that broke it." | 7.4 git bisect: binary-search your history |
| "You have a detached HEAD." | 5.5 Detached HEAD |
| "We tag releases." | 7.2 Tags |
"What does HEAD~3 / main...feature mean?" |
3.7 Specifying commits |
| "Prompts are versioned in git too." | 3.6 Writing good commit messages and 04.10 |
Part 1: Why version control — and what git actually is#
1.1 The problems version control solves#
Imagine you are writing tickets.py for the ai-path workspace. Without version control, your folder is a pile of files that only ever hold their latest state. That single fact causes almost every pain beginners (and seniors) feel:
- "I broke it and don't know how to get back." There is no undo button for a file you overwrote.
- "What changed since yesterday?" Without history you can't diff, can't review, can't explain.
- "Who wrote this line, and why?" With several contributors — or with an AI assistant editing code for you — blame and history are the only way to understand a file.
- "I want to try an experiment without risking the working version." Copying the whole folder (
project-v2-final-FINAL) is how people lose work. - "My laptop died / I deleted the folder." A folder on one disk is not a backup.
- "Two people edited the same file." Without a merge mechanism, one person's work overwrites the other's.
A version control system (VCS) solves all of these by recording every state of your project as a sequence of snapshots you can return to, compare, branch from, and share.
1.2 A short history: from centralised to distributed#
Version control is older than the web. The 1970s and 1980s produced centralised systems — SCCS, then RCS, then CVS and SVN (Subversion, 2000) — where one server held the repository and every developer checked out files from it. "The repo" lived in exactly one place; if it was down or lost, everyone was stuck.
In 2005, Linus Torvalds — already famous for Linux — needed a fast distributed system to manage the Linux kernel's tens of thousands of files and hundreds of contributors. He wrote git in a few weeks. The name is British slang for an unpleasant person; Torvalds has joked that he names projects after himself and that the tool's early reputation earned the name. Whatever the joke, the design was radical: every clone of a repository is a complete repository — full history, no dependence on a central server. You can commit, branch, merge and search history with no network at all.
Around the same years, companies built hosting services on top of git:
| Service | Started | What it adds on top of git |
|---|---|---|
| GitHub | 2008 | Web hosting for repos, pull requests, issues, Actions CI, code search — the default home for open source and most private projects |
| Bitbucket | 2008 | Similar hosting, historically strong with teams already using Jira/Confluence (Atlassian) |
| GitLab | 2011–2012 | Hosting plus a built-in CI/CD platform you can also self-host |
| Self-hosted (Gitea, GitLab CE, bare repos on a server) | — | Full control; you run the server yourself |
Two vocabularies matter from now on:
- git (lowercase) is the tool and the protocol — the thing you type commands into.
- GitHub (capitalised) is a company and a service — one place your git repositories can live, plus collaboration features git itself doesn't have (pull requests, issues, Actions).
1.3 Snapshots, not diffs: the object model#
Here is the single most important mental model in this lesson. Two families of version control exist:
- Delta-based systems (CVS, SVN) store "file version 7 = version 6 plus these changes". To reconstruct a file you replay a chain of patches.
- Snapshot-based systems (git, and Mercurial) store, for each commit, the complete state of every file — but cleverly: identical content is stored only once.
Git's cleverness is the object model. Everything in a repository is one of three kinds of object, each named by the SHA-1 hash of its contents — a 40-character hexadecimal fingerprint:
| Object | What it stores | Analogy |
|---|---|---|
| blob | The raw bytes of one file | A sealed envelope containing a document |
| tree | A directory listing: names → blob or subtree hashes | The folder's index card |
| commit | A tree hash + parent commit hash(es) + author/committer + timestamp + message | A labelled photograph of the whole project at one moment, with a pointer to the previous photograph |
Because objects are named by content, two files with identical content share one blob — git stores it once. Because the name is the content's fingerprint, a corrupted object is detected immediately (its hash won't match). This is why git is fast, why git log can show any historical state instantly, and why a "commit hash" like a1b2c3d is really just the name of one snapshot.
You can see this yourself in any repository:
git cat-file -t HEAD # what kind of object is HEAD? -> "commit"
git cat-file -p HEAD # print the commit object: tree, parents, author, messagecommit
tree 41a9d0648ea72340c32a3d48f9de097582802520
parent 4dfd7299df7d7a2b603dd2d9bef536ace6d4aeb7
author Learner <learner@example.com> 1770454800 +0000
committer Learner <learner@example.com> 1770454800 +0000
Add logger.pyThat is a whole commit: it says "the project looked like tree 41a9d06…, and it came after commit 4dfd729…". The tree in turn points at blobs for app.py, README.md and every other file. Follow the pointers recursively and you have the entire project at that moment.
flowchart TB
subgraph objects ["Objects inside .git/objects (content-addressed)"]
C1["commit a1b2c3d<br/>tree → T2, parent → C0"]
C0["commit 9f8e7d6<br/>tree → T1, parent → none"]
T2["tree T2<br/>app.py → B2<br/>README.md → B1"]
T1["tree T1<br/>app.py → B0<br/>README.md → B1"]
B2["blob B2<br/>'def greet…'"]
B1["blob B1<br/>'# Demo project'"]
B0["blob B0<br/>'def greet…v1'"]
end
C1 -->|points to| T2
C1 -->|parent| C0
C0 --> T1
T2 --> B2 & B1
T1 --> B0 & B1
note1["README.md unchanged → same blob B1 reused"] -.-> B1Notice B1 is shared: because README.md didn't change between the two commits, both trees point at the same blob. Git never stores a file twice unless its content changed. This is also why git repositories stay small even with long histories.
1.4 The three areas: working tree, staging area, repository#
Every file you work with sits in one of three zones, and every git command is really a question about moving data between them:
flowchart LR
subgraph wt ["1 · Working tree"]
F["files you see and edit<br/>in Finder/Explorer/VS Code"]
end
subgraph idx ["2 · Staging area (index)"]
I[".git/index — 'what the<br/>next commit will contain'"]
end
subgraph repo ["3 · Repository"]
R[".git/objects + refs<br/>the permanent history"]
end
F -->|"git add"| I
I -->|"git commit"| R
R -->|"git restore / checkout / reset"| F
R -->|"git restore --staged / reset"| I- Working tree — the files on disk that you edit. Nothing here is safe yet; it's just bytes.
- Staging area (also called the index) — a special file,
.git/index, listing exactly what the next commit will contain.git addcopies file contents into it (as blobs). This is your "preview" of the commit and the reason you can stage part of your work. - Repository —
.git/, the permanent record: all objects plus refs (pointers to commits, likerefs/heads/main).
git status is the command that shows all three zones at once: what you've edited but not staged, what you've staged, and what's untracked. You'll read it line by line in 3.1.
Inside .git/ you'll also find HEAD (which branch you're on), config (this repo's settings), hooks/ (scripts git can run automatically), logs/ (the reflog — covered in 6.5), and index. You never edit these by hand, but knowing they exist demystifies a lot of git's messages.
1.5 Commits, branches, HEAD and tags: pointers to snapshots#
Four everyday words are all the same kind of thing — a named pointer to a commit:
| Thing | What it is | Moves? |
|---|---|---|
| Commit | A snapshot + parent pointer(s) + message + author | Never — immutable once written |
| Branch | A movable pointer to a commit (e.g. main, feature/login) |
Yes — every commit on it advances it |
HEAD |
"Where you are": normally a pointer to the current branch, which points to a commit | Yes — git switch moves it |
| Tag | A (usually permanent) name for a specific commit, conventionally used for releases | Shouldn't — tags mark milestones like v0.2.0 |
The set of all commits forms a directed acyclic graph (DAG) — a family tree where each commit can have one parent (normal work) or two (a merge commit joining two lines of work). "Acyclic" just means it never loops back on itself: history only points backwards.
gitGraph
commit id: "c1"
commit id: "c2"
branch feature
checkout feature
commit id: "f1"
commit id: "f2"
checkout main
commit id: "m1"
merge feature id: "M"
commit id: "m2"Reading it: main and feature diverged after c2; f1/f2 happened on the feature branch while m1 happened on main; the merge commit M has two parents (m1 and f2), joining the lines; m2 continues on main. Branches are just bookmarks into this graph — creating one costs nothing and takes no space, because it stores only a 40-character hash.
Part 2: Setting up git#
2.1 Check what's installed#
Git ships with macOS's Command Line Tools, most Linux distributions, and Git for Windows (which also gives you Git Bash). Verify yours:
git --versionAs of November 2026 the latest upstream release is Git 2.56.1 (26 October 2026, per git-scm.com), and Git for Windows tracks the same 2.56 series. Anything from the last few years has every command in this lesson — git switch and git restore need 2.23 or newer (August 2019), and you should be well past that.
2.2 git config: your identity and preferences#
Every commit records an author name and email. If you don't set them, git guesses from your OS username and hostname — producing commits like Ada Learner <ada@Adas-Laptop.local>, which is ugly on GitHub and breaks the "which human wrote this" link. Set yours once, globally:
git config --global user.name "Your Name"
git config --global user.email "you@example.com"Use the email associated with your GitHub account (a @users.noreply.github.com address works and keeps your real email private — see 00.4). Other settings worth making once:
git config --global init.defaultBranch main # new repos start on 'main', not 'master'
git config --global pull.rebase false # 'git pull' = fetch + merge (the safe default to understand first)
git config --global core.editor "code --wait" # which editor 'git commit' opens (use your editor; 'nano' works everywhere)
git config --global color.ui auto # coloured diffs/status in the terminalTwo details that save confusion later:
init.defaultBranchmatters because the upstream default is stillmaster. Git announced in the 2.52 release notes (2025) that Git 3.0 will switch the built-in default tomain, but as of November 2026 released versions still initialisemasterunless configured — except on platforms that set it for you: GitHub has defaulted new repos tomainsince October 2020, and Apple's Command Line Tools ship a system gitconfig that already setsinit.defaultBranch=main(which is whygit initon a fresh Mac gives youmainwith no hint). Setting the config yourself makes behaviour identical on every machine you use.core.autocrlfand.gitattributescontrol line endings. On Windows, git's default can rewrite LF↔CRLF and create noisy diffs. The modern fix is a.gitattributesfile in the repo (4.3);core.autocrlfis the older per-machine knob. Leave it alone unless you see^Mcharacters or every-line-changed diffs.
2.3 Where config lives: system, global, local#
git config writes to one of several files, and later files override earlier ones:
| Scope | Flag | File | Use for |
|---|---|---|---|
| system | --system |
OS-wide (e.g. /Library/Developer/CommandLineTools/usr/share/git-core/gitconfig on macOS CLT, /etc/gitconfig on Linux) |
Rarely touched by users |
| global | --global |
~/.gitconfig (and ~/.config/git/config) |
Your identity and preferences, every repo |
| local | --local (default inside a repo) |
<repo>/.git/config |
Settings for this repository only |
| worktree | --worktree |
<repo>/.git/config.worktree |
Per-worktree settings (rare) |
| command | git -c key=value … |
nothing written | One-off overrides |
See where every value comes from (real output, abridged):
git config --list --show-originfile:/Library/Developer/CommandLineTools/usr/share/git-core/gitconfig init.defaultbranch=main
file:.git/config user.name=Learner
file:.git/config user.email=learner@example.comRead it as "these files, in this order; later wins". If git commit ever uses the wrong identity, --show-origin is the first place to look. A per-repo override is legitimate: a work repo might need a different user.email than your personal one — set it with git config user.email … inside that repo (no --global).
2.4 Your first repository: git init#
A repository ("repo") is just a folder with a .git directory inside it. Create the ai-path workspace that the rest of the path uses:
mkdir -p ~/code/ai-path && cd ~/code/ai-path
git initOn a machine where init.defaultBranch isn't set you'll see a hint about the default branch name (master) and how to change it — that's the hint doing its job; configure init.defaultBranch main per 2.2 and re-run, or simply git branch -M main after your first commit. Repos created on github.com have defaulted to main since October 2020, but that setting lives on GitHub's side — a local git init follows only init.defaultBranch and platform gitconfigs, so set it yourself and every machine behaves the same.
Then create your first files — a README, the notes folder this path uses, and a first Python file:
mkdir -p notes data
cat > README.md <<'EOF'
# ai-path
My workspace for the AI engineer learning path.
EOF
cat > notes/api-facts.md <<'EOF'
# API facts
- OpenAI Responses API: POST https://api.openai.com/v1/responses
- Auth header: Authorization: Bearer <your key>
EOF
cat > tickets.py <<'EOF'
"""Support ticket helpers for the ai-path workspace."""
def ticket_summary(ticket_id: int, subject: str, status: str) -> str:
return f"#{ticket_id} [{status}] {subject}"
EOF(If heredocs feel exotic, just create the same files in your editor — git doesn't care how bytes got there.)
Now the first commit — you'll meet each command properly in Part 3; here it's just to get a repository with history:
git add README.md tickets.py notes/api-facts.md
git commit -m "Initial commit: README, ticket helper, API notes"
git log --onelinegit log --oneline prints one line per commit, newest first: a short hash and the message. That hash is the commit's name — the same fingerprint from 1.3.
2.5 git clone: a preview#
git clone <url-or-path> downloads a whole repository — full history, all branches — into a new folder. Against GitHub it looks like git clone https://github.com/you/ai-path.git; against a local path (perfectly valid, and used for offline practice in 00.4) it's git clone /path/to/repo. Cloning is how you get someone else's history onto your machine, and later how you get your repo onto a second machine. The remote side — origin, push, pull — is 00.4's subject; treat clone here as "download the whole story".
Part 3: The daily loop#
This is the part you'll actually type every day. Learn it until it's reflex.
3.1 Reading git status#
After editing files, run:
git statusOn branch main <- which branch HEAD points at
Changes not staged for commit: <- edited in working tree, NOT in index
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: tickets.py <- tracked file, changed, unstaged
Untracked files: <- never added; git ignores them entirely
(use "git add <file>..." to include in what will be committed)
scratch.txt
no changes added to commit (use "git add" and/or "git commit -a")The three sections map exactly to the three areas: "Changes not staged" = working tree vs index; "Changes to be committed" = index vs last commit; "Untracked files" = files git has never seen. git status --short (-s) gives the dense version you should learn to read:
M tickets.py <- space-M: modified, unstaged
M README.md <- M-space: modified, staged
A notes/new.md <- added to index
D old.py <- deleted, staged
?? scratch.txt <- untracked
!! .env <- ignored by .gitignore (only with --ignored)The two-letter code is <index><worktree>: first letter = staged state, second = working-tree state. M (space then M) means "worktree differs from index"; M means "index differs from HEAD". Memorise that ordering — it's the most common source of "wait, did I stage it?".
3.2 git add and git commit#
git add tickets.py # stage one file
git add notes/ # stage a whole directory
git add -A # stage everything tracked + untracked (except ignored)
git add -p # stage interactively, hunk by hunk (see below)
git status --short # confirm what's staged before committing
git commit -m "Add reopen_ticket helper"git add copies the file's current content into the index as a blob and records the path. git commit writes a commit object pointing at the index's tree, links it to the current branch, and moves the branch forward. Until you commit, nothing is permanent — the index can be restaged any number of times.
git add -p (patch mode) is the pro move: it walks you through each hunk of your diff and asks stage this hunk? [y,n,q,a,d,s,e,?]. Use it when one file contains two logical changes — stage the bug fix, leave the experiment unstaged. (s splits a hunk, e opens the diff in your editor for surgical staging.)
What git commit -a does and doesn't do: -a/--all stages modified tracked files automatically — but not untracked files. git commit -am "…" is convenient but bypasses the review step that makes git valuable; get in the habit of status → add → commit.
Committing with an editor: bare git commit opens your $EDITOR/core.editor with a template — subject line, blank line, body. Multi-line messages are normal for anything non-trivial; see 3.6.
3.3 git diff: three different diffs#
git diff answers "what changed?" — but between which two states matters:
git diff # working tree vs index (unstaged changes)
git diff --staged # index vs HEAD (what the next commit adds)
git diff HEAD # working tree vs HEAD (everything pending)
git diff HEAD~1 HEAD # commit vs commit (what that commit changed)
git diff main..feature # tip of main vs tip of feature
git diff main...feature # changes on feature since it diverged from maindiff --git a/tickets.py b/tickets.py
index 0ae6e3e..9a8e27c 100644
--- a/tickets.py
+++ b/tickets.py
@@ -2,3 +2,6 @@
def ticket_summary(ticket_id: int, subject: str, status: str) -> str:
return f"#{ticket_id} [{status}] {subject}"
+
+def reopen_ticket(ticket_id: int) -> str:
+ return f"Reopened ticket #{ticket_id}"Read it as: a/ is the "before" side, b/ the "after"; @@ -2,3 +2,6 @@ means "starting at old line 2, 3 lines of context; new file has 6"; + lines are additions, - deletions, space = context. The index 0ae6e3e..9a8e27c line shows the blob hashes before/after — the same content-addressing from 1.3, visible in everyday output.
Useful flags: --stat (files changed, no content), -w (ignore whitespace), --word-diff (word-level instead of line-level), --name-only/--name-status.
3.4 git log and git show#
git log --oneline # compact: hash + subject
git log --oneline --graph # ASCII graph of the DAG
git log --oneline --graph --all # include all branches
git log --stat # which files each commit touched
git log -p # full patches (same as --patch)
git log --follow -- notes/api-facts.md # history of one file, across renames
git log -S "reopen_ticket" # commits that added/removed that string ("pickaxe")
git log --since="2 weeks ago" --author="you"
git show HEAD # one commit + its diff (default: HEAD)
git show HEAD~2:path/to/file # file contents at that commit — no checkout needed--graph is the one to internalise — it renders the DAG from 1.5:
* 220534d Merge branch 'feature/readme-badge'
|\
| * bd01bd9 Add build badge to README
* | 27d3b00 Add CHANGELOG for 0.2.0
|/
* af2551b Add docs.py help text* marks a commit; | columns are branch lines; the |\ junction is where the merged branch joins. If git log --graph ever looks like spaghetti, you're looking at real branching — that's normal.
git show is log -1 -p with better defaults: commit metadata, message, and the diff. It's the "inspect this commit" command; git show HEAD~3 or git show v0.2.0 work on any revision.
3.5 restore, rm and mv#
Git 2.23 (2019) split the overloaded git checkout into two clearer commands — use these:
git restore tickets.py # discard unstaged working-tree changes (DANGER: edits lost)
git restore --staged tickets.py # unstage: index back to HEAD, worktree untouched
git restore --source=HEAD~1 f.py # take the file's content from an older commit
git rm old-file.py # delete file AND stage the deletion
git rm --cached secret-notes.txt # untrack but keep the file on disk (used with .gitignore)
git mv old.py new.py # rename + stage in one stepgit rm only works on tracked files — for an untracked file just rm it (covered in 00.2). git mv is mv plus staging; plain mv works too but leaves the rename as delete+add until you git add -A (git detects renames automatically at commit/diff time anyway — see the => rename notation in git show --stat output).
3.6 Writing good commit messages#
A commit message has two parts: a subject (first line, ≤ ~72 chars) and an optional body. Rules that matter:
- Imperative mood, no period: "Add login helper", not "Added login helper" or "Adds login helper". Read it as "If applied, this commit will ___".
- Say what and why, not how. The diff shows how; the message carries intent.
- One logical change per commit — the atomic commit rule. "Fix login redirect AND update README AND bump deps" is three commits. Atomic commits make
bisect,revert,cherry-pickand code review all work properly. - Body for the why: wrap at ~72 chars; explain motivation, trade-offs, links to issues.
Fix invoice total rounding for half-cent discounts
Rounding happened per line before summing, so 3 x $0.335 came to
$1.02 instead of $1.01. Round once on the total instead. Found
while investigating ticket #482.Conventional Commits is a popular convention — type(scope): subject — that makes history machine-readable:
feat(tickets): add reopen_ticket helper
fix(invoices): round totals after summing lines
chore: bump pytest to the latest release
docs: correct API endpoint in notes
test: cover empty-ticket edge caseCommon types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert. A ! after the type or a BREAKING CHANGE: footer marks API-breaking changes. Tools like commitlint, changelog generators and release automation parse this format — the spec is at conventionalcommits.org. You don't have to adopt it, but knowing it means you can read any serious repo's history.
3.7 Specifying commits: revisions, ranges and paths#
Half the commands in this lesson take a revision — a way of naming a commit — and you've already met several without a formal introduction: HEAD, HEAD~1, HEAD~3, main..feature, feature/logging~1, HEAD@{1}, HEAD~2:path/to/file, :crlf-test.txt. Here is the whole vocabulary in one place.
The atoms — ways to name a single commit:
| Revision | Means | Example |
|---|---|---|
HEAD |
the commit you're on right now | git show HEAD |
<hash> |
that commit, directly — any unambiguous prefix works (a1b2c3d) |
git show 4dfd729 |
<branch> / <tag> |
whatever commit the branch/tag currently points at | git show main, git diff v0.1.0 v0.2.0 |
<rev>~N |
N commits back along the first-parent chain | HEAD~3 = three commits ago |
<rev>^ / <rev>^N |
the Nth parent of a commit (^ alone means ^1) |
on a merge commit, HEAD^2 = the tip of the branch that was merged in |
<rev>@{n} |
where HEAD (or a branch) pointed n moves ago — the reflog |
HEAD@{1} = "where I was before the last move" — 6.5 |
<branch>@{u} |
the branch's upstream (its remote counterpart) | git log @{u}.. shows unpushed commits — remotes are 00.4 |
~ and ^ only differ on merge commits: HEAD~2 walks back two first-parents, HEAD^^ asks for the first parent's first parent — identical on linear history, different once merges appear. Think of ~ as "N commits ago" and ^ as "parent number N".
Ranges — sets of commits, used by log, diff, cherry and friends:
main..feature— commits reachable fromfeaturebut not frommain: "what would merging bring?"main...feature— commits reachable from either but not both: the changes onfeaturesince it diverged frommain. This is the formgit diff main...featureuses in 3.3, and the same idea behind a pull request's "files changed" view.
Paths at a revision — read file contents without checking anything out:
<rev>:<path>— the file's contents at that commit:git show HEAD~2:app.py,git show v0.1.0:README.md. The same idea narrows diffs:git diff HEAD~1 HEAD -- app.py.:<path>— the file's contents in the index (what's staged right now):git show :crlf-test.txtin 4.3. During a merge conflict,:1:path,:2:path,:3:pathaddress the base/ours/theirs stages.
The helper: git rev-parse <rev> resolves any revision to its full 40-character hash — git rev-parse HEAD~1, git rev-parse main, git rev-parse 'HEAD@{1}'. Scripts and debugging sessions use it constantly; it's also how you check what a shorthand actually means before trusting it:
git rev-parse HEAD # full hash of the current commit
git rev-parse HEAD~1 # its first parent
git rev-parse HEAD^2 # second parent (meaningful on merges)
git rev-parse --short HEAD~1 # abbreviated formTags name commits permanently, and git describe --tags finds the nearest tag — both covered in 7.2. Learn the atoms once and every command in Parts 5–7 becomes readable.
Part 4: What never goes into git#
4.1 .gitignore: telling git what to skip#
Some files should never be committed: secrets, dependencies, build output, OS noise. .gitignore is a plain-text file in the repo root listing patterns for files git should pretend don't exist. Create one now:
cat > .gitignore <<'EOF'
# Secrets — never commit
.env
.env.*
!.env.example
# Python
__pycache__/
*.py[cod]
.venv/
venv/
# Node (if you ever touch JS)
node_modules/
# Editor and OS noise
.DS_Store
.idea/
.vscode/*
!.vscode/extensions.json
# Data exports — keep the small seed file only
/data/*.csv
!/data/tickets.csv
EOF
git add .gitignore
git commit -m "Add .gitignore"The pattern rules, in order of importance:
| Pattern | Matches | Notes |
|---|---|---|
.env |
any file named .env at any depth |
No slash = matches everywhere |
/data/*.csv |
CSVs directly inside data/ |
Leading / anchors to repo root |
__pycache__/ |
the directory and everything under it | Trailing / = directories only |
*.py[cod] |
x.pyc, x.pyo, x.pyd |
* doesn't cross / |
**/build |
build at any depth |
** crosses directories |
data/ |
the directory and everything under it | excluding a dir beats later !file rules (see below) |
!.env.example |
negation: re-include | Last matching pattern wins |
# comment |
— | # starts a comment; \# for a literal hash |
Three rules explain most confusion:
- Last matching pattern wins.
.env.*ignores.env.example, but the later!.env.exampleun-ignores it. Order matters — put negations after the broad rule. - You can't ignore a file that's already tracked.
.gitignoreonly affects untracked files. If you committeddata/old-export.csvlast week, adding/data/old-export.csvto.gitignorechanges nothing — git keeps tracking it. The fix is 4.2. - A negation can't resurrect a file inside an excluded directory. If a pattern excludes the directory itself (
data/), git never looks inside it — a later!data/keep.csvsilently does nothing. This is why the/data/*.csv+!/data/tickets.csvpair above works (thedata/directory is never excluded, only matching files inside it) whiledata/+!data/keep.csvfails. To keep some files inside a mostly-ignored folder, ignore the contents rather than the directory —data/*plus!data/keep.csv— or restructure so secrets and data live in separate trees.
Verify what git thinks, per path:
git check-ignore -v .env data/big-export.csv __pycache__/x.pyc.gitignore:2:.env .env
.gitignore:22:/data/*.csv data/big-export.csv
.gitignore:7:__pycache__/ __pycache__/x.pycAnd see ignored files that status hides:
git status --ignored --short?? .env.example
!! .env
!! .venv/
!! __pycache__/
!! data/big-export.csv!! = ignored. This is the command to run when "where did my file go?" — it's probably sitting there, ignored.
Where else ignore rules live (in increasing scope):
.git/info/exclude— repo-local ignore file, not committed (personal rules for one clone)..gitignorefiles in subdirectories — apply to that subtree (e.g.scripts/.gitignoreignoringscripts/*.log).- Global excludes —
core.excludesFile, default~/.config/git/ignore: patterns applied to every repo you touch, like a personal.DS_Storefilter. This is what GitHub's docs call the machine-wide ignore; the repo's own.gitignoreis what teammates inherit — prefer committing project rules there.
Templates: don't hand-write .gitignore from scratch — github.com/github/gitignore is GitHub's official collection (Python, Node, macOS, VS Code, Jupyter…). When you create a repo on GitHub it offers these as a starting point; locally you can copy the matching file. A solid Python .gitignore already covers __pycache__/, *.py[cod], .venv/, .env, .pytest_cache/, .mypy_cache/, *.egg-info/, .DS_Store.
4.2 Untracking a file that was already committed#
The trap from 4.1: the file is tracked, so .gitignore can't touch it. The fix has two steps — add the ignore rule, then remove the file from the index while keeping it on disk:
echo "/data/old-export.csv" >> .gitignore
git rm --cached data/old-export.csv
git status --short
# M .gitignore
# D data/old-export.csv <- staged deletion from the index
git commit -m "Stop tracking data/old-export.csv (kept on disk, now ignored)"
ls data/old-export.csv # still there!git rm --cached removes the path from the index only — the working-tree file survives. After the commit, git forgets the file entirely; the ignore rule then keeps it invisible forever. (git rm without --cached deletes the file from disk too — read the flag.)
Note what this does not do: it doesn't remove the file from history. Every past commit still contains it. For secrets that's the 6.7 problem; for big data files it's usually acceptable — the file just stops growing in the repo.
4.3 .gitattributes and line endings#
Files on Windows often use CRLF line endings; macOS/Linux use LF. If a Windows teammate commits CRLF and a Mac teammate commits LF, git sees every line as changed — noisy diffs and merge conflicts that aren't real. .gitattributes tells git how to normalise each file type:
cat > .gitattributes <<'EOF'
# Text files: store LF in the repo, let each OS check out its preference
* text=auto eol=lf
# Shell scripts: always LF in the repo and on checkout
*.sh text eol=lf
# Binary files: never normalise, never diff
*.png binary
*.db binary
*.pdf binary
EOF
git add .gitattributes
git commit -m "Add .gitattributes for consistent line endings"What text=auto eol=lf does: on commit, git converts CRLF→LF inside the repository (the stored blob is always LF); on checkout, it writes LF (because eol=lf). The repo becomes OS-independent. You can see the normalisation live:
printf 'line1\r\nline2\r\n' > crlf-test.txt # CRLF on disk
git add crlf-test.txt
git show :crlf-test.txt | od -c | head -2
# 0000000 l i n e 1 \n l i n e 2 \n
od -c crlf-test.txt | head -2
# 0000000 l i n e 1 \r \n l i n e 2 \r \nIndex (what git stored): LF only. Working tree: still CRLF as written. Git warned CRLF will be replaced by LF the next time Git touches it — that warning is .gitattributes doing its job. git check-attr text eol -- file shows which rules apply to a path.
.gitattributes does more than line endings — it's also where Git LFS patterns live (*.psd filter=lfs diff=lfs merge=lfs -text), where you mark files linguist-generated or export-ignore for archives, and where you declare encodings (*.py working-tree-encoding=UTF-16). Treat it as "the repo's file-type rulebook".
4.4 Secrets: the rule that has no exceptions#
An API key, token, password or private key must never be committed — not "temporarily", not "just to test", not "it's a fake". Three reasons:
- GitHub is scanned. Secret scanning checks every push on public repos for free, and partner patterns catch OpenAI/Anthropic/Google/OpenRouter-style keys automatically. Push protection can block the push outright.
- History is forever (practically). Deleting the file doesn't delete it from history — 6.7 shows the secret still readable via
git log -p. - Once pushed, assume compromised. Treat any committed secret as leaked: rotate/revoke it first, clean history second.
The habit that prevents 99% of incidents — start it in this lesson, and 03.1 Part 3 goes deep on it when you have real keys:
# .env — real secrets, NEVER committed (already in .gitignore)
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
# .env.example — committed template, names only, safe to share
OPENAI_API_KEY=
ANTHROPIC_API_KEY=Keys live in the environment or a .env file that git ignores; code reads them via os.environ (Python picks this up properly in 01B.2); .env.example documents which variables exist. 03.1 §3.4 has the full setup. Beyond .env, watch for secrets in: config files, Jupyter notebooks outputs, .npmrc/.pypirc credentials, SSH private keys (id_rsa), *.pem, kubeconfigs, and — increasingly — prompts and eval fixtures that quote real customer data.
4.5 Large files and Git LFS#
Git stores every version of every file forever. A 2 GB dataset committed today is downloaded by every clone, forever, and every small edit adds another near-copy internally. GitHub's limits (as of November 2026, docs.github.com):
| Limit | Value |
|---|---|
| Warning on push | file > 50 MiB (push still succeeds) |
| Hard block | file > 100 MiB — push rejected |
| Web-UI upload | max 25 MiB per file |
| Repo size guidance | ideally < 1 GB, strongly recommended < 5 GB on-disk |
| Single push | 2 GiB max (split a huge first push into batches) |
The right answer for big binaries (datasets, model weights, videos, design files) is Git LFS (Large File Storage): git lfs track "*.psd" writes an lfs filter rule into .gitattributes; the repo then stores a small pointer file (text, ~130 bytes) while the real bytes live on an LFS server. Clones fetch pointers instantly and download content on demand. On GitHub, Free/Pro plans include 10 GiB storage + 10 GiB/month bandwidth metered (data packs were retired); Team gets 250 GiB of each; per-file caps are 2 GB (Free/Pro), 4 GB (Team) and 5 GB (Enterprise Cloud). git lfs install once per machine, git lfs track per file type, git lfs migrate to convert history. Awareness is enough here — you'll rarely need it in the AI path (models come from providers or Hugging Face, not your repo) — but now you know why a .gitattributes line mentioning lfs exists and why "just commit the checkpoint" is a bad idea.
Other escapes for large/generated files: keep them out of git entirely (object storage, a data/ folder that's gitignored and downloaded by a script), or store only references (IDs, URLs, checksums) in the repo. The principle: git is for text and small binaries; everything else needs a plan.
Part 5: Branches and merging#
5.1 Why branch, and switch vs checkout#
A branch is a movable name for a line of commits (1.5). You branch to:
- Experiment safely — try a rewrite; if it fails,
switchback and the experiment never touchedmain. - Work in parallel — feature A and bugfix B proceed independently, merge when ready.
- Review before merging — a branch is the unit a pull request reviews (00.4).
- Keep
mainalways working —mainstays releasable while features cook.
Since Git 2.23 there are dedicated commands — prefer them, they can't accidentally touch files:
git switch main # change branch (old: git checkout main)
git switch -c feature/login # create AND switch (-c = --create)
git switch -c fix/typo HEAD~2 # branch from an older commit
git switch - # back to the previous branch (very handy)
git branch # list local branches (* = current)
git branch -a -v # all branches incl. remotes, with tip hashes
git branch --show-current # just the name, for scripts
git branch -m old new # rename a branchgit checkout still works for branches (and is required for some operations like git checkout <commit> → detached HEAD), but its second job — restoring files — now belongs to git restore (3.5). The old combined command is the #1 source of "I thought I switched branches but my files changed" confusion; the split exists to end that.
5.2 Fast-forward vs merge commits#
When you merge a branch into main, two outcomes exist:
Fast-forward — main hasn't moved since you branched, so the branch's commits can simply be slid onto main. No merge commit is created; history stays linear:
git switch -c feature/login-form
# …edit, commit…
git switch main
git merge feature/login-formUpdating c9b326b..8bad214
Fast-forward
app.py | 2 ++
1 file changed, 2 insertions(+)Graph after: * 8bad214 Add login() stub → * c9b326b Initial commit — a straight line.
Merge commit — main also moved while you worked, so the lines diverged. Git can't fast-forward; it creates a merge commit with two parents, joining the lines:
git switch -c feature/readme-badge # from main's tip
# …commit on the branch…
git switch main
# …commit something else on main…
git merge feature/readme-badge --no-editMerge made by the 'ort' strategy.
README.md | 2 ++* 220534d Merge branch 'feature/readme-badge'
|\
| * bd01bd9 Add build badge to README
* | 27d3b00 Add CHANGELOG for 0.2.0
|/
* af2551b Add docs.py help textgit show -s --format='%P' HEAD on that merge prints two hashes — 27d3b00 bd01bd9 — its two parents. The --no-edit flag accepts the default merge message ("Merge branch 'x'"); without it, git opens your editor so you can write a real merge message — worth doing for non-trivial merges ("Merge feature/login: combines OAuth flow with session refactor").
Which is better? Linear history (fast-forward or rebase) is easier to read; merge commits preserve exactly when lines of work joined and never rewrite commits. Teams pick a convention; solo, either is fine. git merge --no-ff forces a merge commit even when fast-forward is possible — useful to mark "a feature landed here". git merge --ff-only refuses to create a merge commit — useful in CI/scripts that demand linearity.
flowchart LR
subgraph ff ["Fast-forward: main had not moved"]
A1["c1"] --> A2["c2"] --> A3["f1 (now on main too)"]
end
subgraph mc ["Merge commit: both sides moved"]
B1["c1"] --> B2["m1"] --> BM(("M<br/>two parents")) --> B4["m2"]
B1 --> B3["f1"] --> BM
end5.3 Merge conflicts: reading, resolving, aborting#
A conflict happens when both sides changed the same lines differently. Git stops and writes markers into the file:
def greet(name):
<<<<<<< HEAD
return "Hello, " + name + " (v2)"
=======
return "Hi there, " + name + "!"
>>>>>>> fix/greeting<<<<<<< HEAD— the version on the branch you're merging into (your current work).=======— separator.>>>>>>> fix/greeting— the version coming from the branch being merged.
git status during a conflict says both modified: app.py under "Unmerged paths" and reminds you: fix conflicts and run "git commit" or git merge --abort. Resolve by editing the file to the intended final content — keep one side, the other, or combine them — then:
git add app.py # mark resolved
git commit --no-edit # or: git merge --continue (opens editor for merge msg)If you'd rather start over:
git merge --abort # restores pre-merge state completelyOther conflict types: modify/delete (one side edited, other deleted — git rm or git add to choose), rename/rename, binary files (marked "warning: Cannot merge binary files" — pick a side with git checkout --ours/--theirs file). During a conflict git switch/git checkout to another branch is refused — finish or abort the merge first. git diff during a conflict shows the combined diff; git checkout --ours file / --theirs file grabs one whole side when resolution is "just take theirs".
Conflict-resolution strategy for the AI era: when an AI assistant produces the conflicting change, resolve by reading both diffs (git log -p on each side, or git show <commit>) and choosing the intent, not the text. And prefer small, frequent merges — conflicts grow teeth with time.
5.4 Rebase, cherry-pick and friends#
Rebase replays your branch's commits on top of another base, producing a linear history as if you'd started from the newer point:
git switch feature/logging # has 2 commits
git rebase main # replay them onto main's tipRebasing (1/2)...Rebasing (2/2)...Successfully rebased and updated refs/heads/feature/logging.Before: feature forked from an older main and main gained commits → branched graph. After: feature's commits sit on top of main's tip — same changes, new commit hashes (a commit's hash covers its parent, so replaying onto a new parent rewrites it). The old commits remain in the object store, reachable via reflog (6.5).
git rebase -i (interactive rebase) opens a todo list of your commits to reword, squash (combine into previous), fixup (combine, discard message), drop, or reorder. It's the tool for cleaning a feature branch before review — "squash these five 'wip' commits into one tidy commit". git commit --fixup=<hash> + git rebase -i --autosquash automates the fixup flow. Master it later; know it exists now.
git cherry-pick <commit> copies one specific commit onto your current branch — no merge, no branch:
git switch main
git cherry-pick feature/logging~1 # apply just the "Add logger.py" commit[main e4e61b7] Add logger.py
Date: ...
1 file changed, 3 insertions(+)
create mode 100644 logger.pyUse it for: backporting a fix to a release branch, rescuing one commit from an abandoned branch, applying a commit someone emailed you. If the pick conflicts, resolve like a merge and git cherry-pick --continue / --abort.
Also worth knowing: git revert <commit> (6.4) is cherry-pick's inverse — it undoes a commit by adding a new one; git range-diff compares two versions of a rebased branch; git rerere ("reuse recorded resolution") can auto-apply conflict resolutions you've made before — enable with git config rerere.enabled true if you hit the same conflicts repeatedly.
5.5 Detached HEAD#
git checkout <commit-hash> (or git switch --detach) puts HEAD directly on a commit instead of a branch — detached HEAD. Git warns you:
Note: switching to 'HEAD~1'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:
git switch -c <new-branch-name>
Or undo this operation with:
git switch -
Turn off this advice by setting config variable advice.detachedHead to false
HEAD is now at 4dfd729 Add NOTES.mdLegitimate uses: "what did the code look like at v0.1.0?", git bisect (which detaches HEAD internally per step), building an old release. The danger: commits made while detached are reachable only via HEAD — switch away carelessly and they're orphaned (reflog still has them, but why rely on that). If you do want to keep work started in detached state: git switch -c my-rescue-branch before switching back.
5.6 Branch naming and hygiene#
Conventions that scale:
main / master / trunk <- the integration branch; always releasable
feature/add-export-csv <- new work
fix/login-redirect-loop <- bug fixes
chore/bump-deps <- maintenance
docs/api-notes <- docs-only
release/v0.2.0 <- release preparation (optional)
hotfix/critical-patch <- urgent fix branched from the releaseShort, kebab-case, prefixed by intent. Delete merged branches promptly: git branch -d name refuses if unmerged (safe); -D force-deletes (the commits stay in reflog for a while). In teams, delete the branch after its PR merges — branch clutter is a real cost on GitHub.
Part 6: Undoing things safely#
Git's undo story is better than any editor's — if you pick the right tool. The wrong reset --hard is the most common way people lose work, so learn the ladder before you need it.
6.1 The undo decision table#
| You want to… | Command | What happens to your file edits | Safe after push? |
|---|---|---|---|
| Unstage a file (keep edits) | git restore --staged f |
untouched | yes — nothing shared changed |
| Throw away unstaged edits | git restore f |
edits lost | yes, but unrecoverable |
| Fix the last commit's message/content | git commit --amend |
rewrites the commit | only if unpushed |
| Undo a pushed/public commit | git revert <hash> |
adds an inverse commit | yes — history preserved |
| Move branch pointer back N commits, keep changes | git reset --soft HEAD~N |
staged | only if unpushed |
| Move back N commits, keep changes unstaged | git reset HEAD~N (--mixed) |
unstaged | only if unpushed |
| Nuke back N commits AND discard changes | git reset --hard HEAD~N |
lost | only if unpushed |
| Recover anything recent | git reflog + git reset/branch/cherry-pick |
— | yes |
The pattern: anything that rewrites history (reset, amend, rebase) is fine locally and forbidden once shared; revert is the only safe undo for public history.
6.2 git reset: moving the branch pointer#
git reset moves HEAD/the branch to a different commit. The three modes decide what happens to your files:
# state: HEAD = C3, index matches C3, worktree has extra edits
git reset --soft HEAD~1 # HEAD -> C2; index & worktree untouched
git reset HEAD~1 # HEAD -> C2; index reset to C2; worktree untouched (= --mixed, the default)
git reset --hard HEAD~1 # HEAD -> C2; index AND worktree forced to C2 — edits destroyedReal walkthrough on the scratch repo:
git commit -qam "Experiment: add EXTRA flag" # new commit E on top of L
git reset --soft HEAD~1
git status --short # "M app.py" — change is staged, commit is gone from log
git reset HEAD~1 # --mixed: now unstaged
git status --short # " M app.py"
git restore app.py # discard the edits entirelyM app.py
M app.py--soft and --mixed are safe — they only move pointers, your edits survive in the worktree/index. --hard is the destroyer: worktree files are overwritten to match the target commit, uncommitted changes vanish without going through any object (there's nothing to recover from — reflog tracks commits, not your unsaved edits). Rule: before any reset --hard, ask "is there anything in my worktree I haven't committed that I might want?" If yes: commit it to a scratch branch or git stash first.
git reset also takes paths: git reset app.py unstages just that file (old-school equivalent of git restore --staged app.py). And git reset --hard with no arguments resets the worktree to HEAD — the "make my folder match the last commit exactly" button.
6.3 git commit --amend: fix the last commit#
Made a typo in the message? Forgot a file? Before pushing:
git commit --amend -m "Better message"
git add forgotten.py && git commit --amend --no-edit # fold file in, keep message--amend replaces the tip commit with a new one (new hash, same parent). It also re-stamps the committer date. Never amend a pushed commit — same shared-history rule as rebase.
6.4 git revert: the safe undo for shared history#
git revert <commit> doesn't touch history — it creates a new commit that applies the inverse diff, publicly recording "this change is undone":
git revert e4e61b7[main d8aa747] Revert "Add logger.py"
1 file changed, 3 deletions(-)
delete mode 100644 logger.pyLog afterwards shows both commits — the original and its reversal — which is exactly what you want on a shared branch: everyone pulling gets the undo without history surgery. git revert -n <commit> applies the inverse to the worktree/index without committing (handy for stacking reverts); git revert --abort bails mid-conflict. Reverting a merge commit needs -m 1 (specify which parent's line to consider "main") — a detail you'll meet if you ever need it; git revert -m 1 <merge> is the form.
6.5 The reflog: git's safety net#
Every time HEAD or a branch moves, git appends an entry to the reflog (.git/logs/) — "HEAD moved from X to Y because of: commit/rebase/reset/merge…". It's the undo database for pointers:
git reflog -10e4e61b7 HEAD@{0}: reset: moving to HEAD~1
85fb227 HEAD@{1}: commit: Throwaway commit
e4e61b7 HEAD@{2}: reset: moving to HEAD~1
335552b HEAD@{3}: reset: moving to HEAD~1
e5b8afd HEAD@{4}: commit: Experiment: add EXTRA flag
335552b HEAD@{5}: commit (amend): Add login helper
2e11724 HEAD@{6}: commit: Add login with plaintext password check
e4e61b7 HEAD@{7}: checkout: moving from 4dfd729... to mainRead it newest-first: HEAD@{0} is where you are, HEAD@{1} is where you just were. Recovering is mechanical:
# find the commit you lost
git reflog
git branch rescue 85fb227 # or: git reset --hard 85fb227 / git cherry-pick 85fb227The reflog is why "I did reset --hard and lost everything" is almost never true for commits: the commit objects still exist and reflog points at them. What reflog does not save: uncommitted worktree edits (they were never objects), and it expires — gc.reflogExpire defaults to 90 days for reachable entries and gc.reflogExpireUnreachable to 30 days for entries not reachable from any tip (exactly the amend/rebase orphans). After git gc prunes them, recovery needs backups.
6.6 What's truly unrecoverable#
- Uncommitted, unstaged edits overwritten by
restore/checkout --/reset --hard/clean -f. Never objects, never recoverable by git. (git fsck --lost-foundonly finds dangling objects — things that were committed/staged at some point.) - Commits past reflog expiry + gc. Rare in practice; the window is weeks-to-months.
git clean -fdxon untracked files.git cleandeletes untracked files from the working tree (-fforce,-dinclude directories,-xinclude ignored files such as.envand.venv/). Same asrm— untracked means git never saw it. The safe habit: rungit clean -n(dry run, lists what would go) first.- Files deleted from all history via
filter-repo/filter-branch— intentionally gone everywhere.
The professional habit that makes all of this theoretical: commit early and often, even WIP commits on a scratch branch — a committed mistake is always recoverable; an uncommitted one may not be.
6.7 A secret in history#
You committed .env by accident — happens to everyone. The recovery order, from GitHub's own docs:
- Rotate/revoke the secret first. This is the step people skip and regret. A leaked key is compromised whether or not you clean the repo — go to the provider's dashboard and kill it now.
- Assess exposure. Was it pushed? Public or private repo? How long? That decides urgency.
- Remove it from history if warranted —
git filter-repois the tool GitHub recommends (git filter-branchis deprecated-ish: slow and footgunny). It is a separate tool, not part of core git: install it withbrew install git-filter-repo, your distro's package, orpip install git-filter-repo, and run it on a fresh clone (it deliberately refuses to rewrite a repo that is not a fresh clone unless you pass--force). It rewrites every commit that touched the path, changing all descendant hashes. - Coordinate the rewrite. Every collaborator must re-clone or carefully rebase — old clones will re-push the secret otherwise. Force-push is required afterwards, which branch protection may block.
- Let the forge help. GitHub secret scanning will keep flagging the old commits in cached views until support purges them; push protection prevents recurrence.
For a local-only, never-pushed repo the calculus is simpler: git filter-repo --path .env --invert-paths, or if it's just the last commit, git rm --cached + commit --amend. The full procedure is 03.1 §3.7 when you have real keys at stake.
Part 7: Everyday tools#
Reference
7.1 git stash: shelve work in progress#
Mid-refactor but need to switch branches? git stash snapshots worktree+index changes, cleans the tree, and files them away:
git stash push -u -m "WIP refactor" # -u includes untracked files
git status --short # clean
git stash list # stash@{0}: On main: WIP refactor
git stash pop # restore and drop the stash entry
git stash apply # restore but keep the entry
git stash show -p # diff of what's stashed
git stash drop # delete the entry
git stash branch fix-from-stash # apply stash onto a NEW branch (escapes conflicts)Stashes are commits under the hood (a merge of index+worktree+untracked states) — they show in git log -g refs/stash and are reflog-protected like everything else. Use stash for "I need a clean tree for five minutes", not as a substitute for committing — stashes are easy to forget and stash pop can itself conflict.
7.2 Tags: lightweight and annotated#
Tags name a specific commit permanently — releases, milestones, "the commit that shipped v0.2.0":
git tag v0.2.0 # lightweight: just a pointer to the commit
git tag -a v0.2.0 -m "Release 0.2.0" # annotated: a tag OBJECT with tagger+message+date$ git cat-file -t v0.2.0 → tag (annotated: its own object)
$ git cat-file -t v0.1.0 → commit (lightweight: points straight at a commit)Prefer annotated for anything released — it carries who/when/why and is what git describe and release tooling expect. git describe --tags prints the nearest tag reachable from HEAD ("v0.2.0" or "v0.2.0-3-gabc123" = 3 commits after the tag). Push tags explicitly: git push origin v0.2.0 or git push --tags (00.4 covers pushing).
7.3 git blame and git log -S#
git blame -L 1,4 app.py^c9b326b (Learner 2026-02-02 09:00:00 +0000 1) def greet(name):
1336c144 (Learner 2026-02-06 09:00:00 +0000 2) return "Hi there, " + name + "! (v2)"
8bad2141 (Learner 2026-02-03 09:00:00 +0000 3) def login(user, password):Per line: last-modifying commit, author, date, line number. ^ before a hash = boundary commit (the file's first commit — blame can't look further back). Caveats: blame shows the last commit that touched the line, which after merges/refactors may be a formatting commit, not the author of the logic; git blame -w ignores whitespace changes; git blame -M/-C detect lines moved/copied between files.
To answer "which commit introduced/removed this string?":
git log -S "Hi there" --oneline # pickaxe: commits where the COUNT of the string changed
git log -G "password" --oneline # -G: commits whose diff mentions a regex match
git log --follow --oneline -- app.py # follow renames backwards7.4 git bisect: binary-search your history#
When "it worked last week" and you have dozens of commits, don't read them one by one — bisect. Git checks out the middle commit; you (or a script) say good/bad; repeat until it finds the first bad commit in O(log n) steps.
Setup: a scratch repo where commit c4 planted a bug (div returns a*b instead of a/b):
git bisect start
git bisect bad HEAD # current tip is broken
git bisect good HEAD~3 # three commits ago was fine
# git checks out the middle commit automaticallyBisecting: 0 revisions left to test after this (roughly 1 step)
[74e0b9e8b2c926cb556cbc8bedccf295c0d59c6b] c4: BUG - div actually multipliesTest that commit by hand, then answer git bisect good or git bisect bad, and git picks the next one. Five commits need only two tests to find the culprit. Better still, automate the "good/bad" judgement with a script:
#!/bin/bash
# test_div.sh — exit 0 = good, 1-127 except 125 = bad, 125 = skip (can't test),
# anything else (e.g. 128+) aborts the whole bisect
cd "$(dirname "$0")"
python3 -c "import calc,sys; sys.exit(0 if calc.div(10,2)==5 else 1)"git bisect run ./test_div.sh # git drives the whole search itself
git bisect reset # return to your branch when donerunning './test_div.sh'
Bisecting: 0 revisions left to test after this (roughly 0 steps)
[3e4dd40c904395e5b1491583da2f037d31f9a5d3] c3: add div
running './test_div.sh'
74e0b9e8b2c926cb556cbc8bedccf295c0d59c6b is the first bad commit
commit 74e0b9e8b2c926cb556cbc8bedccf295c0d59c6b
c4: BUG - div actually multipliesThe contract is strict: 0 marks good, 1–127 except 125 marks bad, 125 means "can't test — skip this commit", and any other exit code aborts the bisect entirely (useful when your build itself is broken — exit 125, don't let a crash masquerade as "bad").
Manual mode: after each checkout, test, then git bisect good or git bisect bad. git bisect skip marks untestable commits (bisect widens the search). This is the same algorithm as binary search — and the same one lesson 00.9 teaches for debugging generally. Real-world version: your test suite is the oracle (git bisect run pytest tests/test_calc.py).
7.5 git grep: search committed content#
git grep -n "def " -- '*.py' # like grep, but searches TRACKED files at HEAD
git grep -n "password" # all tracked files
git grep -n "TODO" HEAD~5 -- '*.py' # search an older commit's tree!
git grep -l "import json" # just filenames
git grep -c "def " -- '*.py' # counts per fileWhy it beats shell grep -r: it searches the index/commits, respects .gitignore (won't wade through .venv/), handles binary files sanely, and can search any revision — git grep pattern v0.1.0 answers "did the old release contain this?" without checking anything out.
7.6 Aliases and quality-of-life config#
git config --global alias.<name> <command> creates shortcuts:
git config --global alias.st status
git config --global alias.lg "log --oneline --graph --decorate"
git config --global alias.co checkout # or use 'switch' per modern habit
git config --global alias.last "log -1 HEAD@{1}" # what did I just do? (reflog!)
git config --global alias.unstage "restore --staged"Then git st, git lg, git unstage file work. Other QoL: git config --global help.autocorrect prompt (when you mistype, say git stats, git shows its single best guess, status, and asks before running it; the value 1 runs the guess immediately, which is riskier), sequence.editor for rebase todo lists, fetch.prune true (auto-delete stale remote-tracking branches), push.default simple (the safe default — requires upstream + same name). The last two only matter once you have remotes — that's 00.4's subject; they just keep remote bookkeeping tidy.
7.7 git worktree: two folders, one repo#
Since Git 2.5 (2015), git worktree attaches additional working directories to the same repository — each can have a different branch checked out:
git worktree add -b hotfix ../ai-path-hotfix main # new branch 'hotfix' at main's tip
git worktree list
# /path/ai-path abc1234 [main]
# /path/ai-path-hotfix def5678 [hotfix]
cd ../ai-path-hotfix # a real folder with its own checked-out branch
git worktree remove ../ai-path-hotfixOne rule surprises people: a branch can only be checked out in one worktree at a time. git worktree add ../ai-path-hotfix main fails with fatal: 'main' is already used by worktree at … (exit 128) because main is already checked out in ai-path — that's why the -b hotfix form above: it creates a new branch at main's tip for the second folder. To inspect an old release without creating a branch, detach instead: git worktree add --detach ../ai-path-old v0.1.0 checks out the tag read-only-style (detached HEAD — 5.5). git worktree remove refuses if the worktree has uncommitted changes; commit or clean it first.
Why it matters to you: reviewing a PR while keeping your working tree untouched, building an old release in a second folder, running two experiments at once, and letting an AI agent work in a separate worktree without touching your files. One object store, many worktrees — no clone needed. (Submodules are the older, clunkier mechanism for the same "multiple checkouts" itch — next.)
7.8 Submodules: awareness only#
A submodule embeds one git repo inside another — the parent stores a pointer to a specific commit of the child. You meet them in the wild (e.g. vendored libraries, docs themes). The commands: git submodule add <url> <path>, git submodule update --init --recursive after cloning. They are notoriously fiddly (detached HEADs inside, "did the submodule pointer get committed?" confusion) — modern alternatives (vendoring, package managers, git subtree) often fit better. When a repo has a .gitmodules file, clone with --recurse-submodules or run the update command; don't try to edit inside a submodule's .git — it's a gitfile pointer, not a directory.
7.9 Living with large repositories#
Real repos (Linux kernel, big monorepos) need extra habits:
git sparse-checkout— check out only the directories you work in; the rest stays in the object store but not on disk.- Partial clone (
--filter=blob:none) — fetch commits/trees but download file contents lazily. GitHub supports it. git maintenance/git gc— git auto-maintains (gc --autoruns after certain commands), packing loose objects into packfiles. Rungit gcmanually on huge repos;git count-objects -vshows the stats.- Shallow clones (
--depth 1) — CI and "just look at the code" clones that skip history entirely. git logon huge repos — always bound it:--since,-n 50, a path, or--author. An unboundedgit log -pon a giant repo will humble you.
7.10 Hooks: awareness#
Git hooks are executable scripts git runs automatically at defined points in its workflow — pre-commit (before a commit is created: lint, format, run fast tests), commit-msg (validate the message, e.g. enforce Conventional Commits), post-checkout, pre-push and others. They live in .git/hooks/ as *.sample files that ship disabled — rename one without .sample and it runs. Two things to know: hooks are local to each clone (they don't travel with the repo — that's why teams standardise on the pre-commit framework, which installs hooks from a committed .pre-commit-config.yaml), and a failing pre-commit hook is a feature, not an obstacle — it's the cheapest place to catch a broken commit before it exists. For prompts/evals gates in CI, that's 11C.2's subject.
Part 8: Workflows and habits#
Deep-dive
8.1 The feature-branch workflow#
The loop you'll use for the rest of your career, solo or team:
flowchart LR
A["main: always<br/>releasable"] -->|"git switch -c<br/>feature/x"| B["feature branch:<br/>small atomic commits"]
B -->|"merge / PR"| A
B -.->|"rebase onto main<br/>(local only)"| Bmainstays green — every commit on it works.- New work = new branch (
feature/,fix/,chore/). - Commit early, commit often, atomically — a WIP commit on your branch is free insurance.
- Keep the branch short-lived; merge (or PR, in 00.4) when done; delete the branch.
git pull(fetch+merge) before starting work and before pushing — see 8.2.
Trunk-based development — everyone commits to main behind CI gates, with feature flags — is the lighter alternative for small teams; 00.4 compares it with Git Flow honestly.
8.2 Habits that prevent pain#
- Commit early, push often. Commits are local; pushes are backups. "I'll commit when it's done" is how work gets lost.
- Pull before you start, pull before you push.
git pullfetches remote changes and merges them in before your push is rejected — 00.4 §3.1 unpacksfetchvspullproperly. On a shared branch, pull/rebase first, resolve locally, then push. - Never work directly on
mainin a team. Even a "tiny fix" — branch it.mainis the shared contract; branches are where experiments live. - Read
git statusbefore every commit. The #1 committed-by-accident files are.env,node_modules/,.venv/, and giant data exports — all preventable by the 5-second status check. - Small diffs review better. A 40-line PR gets reviewed; a 4,000-line one gets rubber-stamped.
- Write the message for the reviewer — including future-you.
- Tags mark releases, branches mark work.
v0.2.0should point at a commit you'd happily deploy. - When confused:
git status,git diff,git log --oneline -10,git reflog. In that order, every time.
8.3 The ai-path thread continues#
Your ~/code/ai-path repo now has real history. Keep feeding it: every lesson's exercises produce files worth committing (notes/api-facts.md grows each module; tickets.db arrives in 00.7; prompts get versioned in 04.10). When 00.4 adds GitHub, this same history pushes to a remote — nothing you've learned here changes; remotes just add origin.
One clarification on "scratch": Parts 2–4 deliberately build real, kept history inside ai-path — it's the thread the rest of the path continues. The branching, undo and everyday-tool demos in Parts 5–7 (which use a file called app.py) and the Exercises are the opposite: run them in throwaway scratch repos, so they can be repeated destructively without touching anything you care about.
8.4 Git panic: a decision tree#
flowchart TD
P["Something went wrong with git"] --> Q1{"Did you commit<br/>or push something<br/>you shouldn't have?"}
Q1 -->|"unpushed commit"| R1["git reset --soft HEAD~1<br/>or --amend / restore --staged"]
Q1 -->|"pushed commit"| R2["git revert <hash><br/>(never reset pushed history)"]
Q1 -->|"no / other"| Q2{"Did you lose work?"}
Q2 -->|"uncommitted edits gone"| R3["Probably unrecoverable.<br/>Check editor local history /<br/>Time Machine. Lesson learned."]
Q2 -->|"commits 'missing'"| R4["git reflog → find hash →<br/>git branch rescue <hash>"]
Q2 -->|"no / other"| Q3{"Merge/rebase conflict?"}
Q3 -->|"yes"| R5["Edit markers out → git add →<br/>git commit / merge --continue<br/>or git merge --abort"]
Q3 -->|"detached HEAD?"| R6["git switch -c rescue<br/>to keep commits,<br/>or git switch - to go back"]
Q3 -->|"no"| R7["git status + git diff<br/>read what git says,<br/>then 00.9's debugging loop"]8.5 Cheat sheet#
| Task | Command |
|---|---|
| See everything pending | git status / git status --short |
| Stage files | git add <path> / git add -p / git add -A |
| Commit | git commit -m "subject" |
| Unstage | git restore --staged <path> |
| Discard edits | git restore <path> ⚠️ |
| See changes | git diff / git diff --staged / git diff HEAD~1 HEAD |
| History | git log --oneline --graph --all / git show <rev> |
| Name a commit | HEAD~2, rev^2, rev:path, a..b, a...b, git rev-parse <rev> |
| Switch/create branch | git switch main / git switch -c feat/x |
| Merge | git merge feat/x (--no-ff, --ff-only, --abort) |
| Rebase | git rebase main (local branches only!) |
| Copy one commit | git cherry-pick <hash> |
| Undo safely | git revert <hash> |
| Undo locally | git reset --soft/--mixed/--hard HEAD~N |
| Fix last commit | git commit --amend |
| Emergency recovery | git reflog → git branch rescue <hash> |
| WIP shelf | git stash push -u / git stash pop |
| Releases | git tag -a v1.0.0 -m "…" |
| Who wrote this | git blame <file> / git log -S "str" |
| Find bad commit | git bisect start → good/bad → bisect run ./test.sh |
| Search code | git grep -n "pat" |
| Ignore files | .gitignore + git check-ignore -v <path> |
| Untrack file | git rm --cached <path> |
| Second worktree | git worktree add ../dir branch |
| Repo size | git count-objects -v |
8.6 Failure gallery#
| Classic mistake | What actually happens | Prevention |
|---|---|---|
git add . sweeps in .env, node_modules/ |
Secret or 10k files committed | .gitignore first; read status before add -A |
git commit of conflict markers |
Broken code pushed; <<<<<<< in prod |
Resolve → grep '<<<<<<<' → then commit |
git push --force on shared main |
Teammates' work overwritten/orphaned | Never force-push shared branches; --force-with-lease if you must |
git reset --hard with uncommitted work |
Edits gone forever | Commit/stash first; reset --hard is nuclear |
Working directly on main |
One bad commit = broken main for everyone | Feature branches always |
| Rebase a pushed branch | Duplicate/divergent history for the team | Rebase only local branches |
git checkout . / git restore . in a panic |
All unstaged work destroyed | git stash or commit first; diff to a patch file |
Committed .env "just to test" |
Key in history; rotation required | .env in .gitignore from commit #1 |
git clone inside an existing repo |
Nested repo confusion (repo/repo/.git) |
Clone into a new sibling directory |
| Deleting a branch thinking it deletes work | Commits orphaned (reflog saves them ~30-90 days) | git branch -d is safe; merged work lives on |
git commit opens vim, panic :q! |
Commit aborted (harmless) | Set core.editor to something friendly |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Git and GitHub are the same thing." | Git is the tool/protocol; GitHub is a hosting service. Your local repo works with no GitHub at all. |
| "A branch is a copy of the code." | It's a 40-character pointer to a commit. Creating one costs nothing; deleting it doesn't delete commits. |
"git add . is the normal way to stage." |
It's how secrets and node_modules/ get committed. Add deliberately; status first. |
"git checkout is unsafe/deprecated." |
Only its file-restoring half moved to git restore (2.23). Branch switching works — but git switch is clearer. |
"git reset --hard is how you undo a commit." |
It destroys uncommitted work too. For pushed history use git revert; for local cleanup --soft/--mixed first. |
| "Deleting a file removes it from git." | It removes it from the next commit only; history keeps every version forever (see 6.7). |
".gitignore can hide a committed file." |
It only affects untracked files. git rm --cached first. |
"!pattern can always undo an ignore." |
Not inside an excluded directory — git never looks in, so data/ + !data/keep.csv silently fails. Ignore data/* instead. |
| "Rebasing makes history nicer, so always rebase." | Rebase rewrites commits — fine locally, destructive on shared/pushed branches. |
| "Merge conflicts mean git is broken." | They mean both sides changed the same lines — git stopped precisely so you could decide. |
| "Detached HEAD means something went wrong." | It's a normal state for exploring old commits; just don't leave new commits there. |
"Small repos don't need .gitattributes." |
Line-ending bugs appear on the first Windows teammate, not the hundredth commit. |
"git commit --amend is safe anytime." |
Only before pushing — it rewrites the commit hash. |
"Once git gc runs, lost commits are gone forever." |
gc respects reflog expiry (90/30 days default); recovery is possible for weeks, not guaranteed forever. |
Key takeaways#
- Git stores snapshots, not diffs. Every file version is a content-addressed blob; directories are trees; commits point at a tree + parent(s). Identical content is stored once; hashes detect corruption.
- Three areas: working tree (your files) → staging area/index (
.git/index, the next commit's preview) → repository (.git/).git statusshows all three;--short's two-letter codes are<staged><worktree>. - The daily loop:
status→add(deliberately,-pfor hunks) →commit(imperative, atomic, Conventional Commits optional) →diff/log/showto review. - Name any commit precisely:
HEAD~Nwalks back N first-parents,rev^Npicks parent N (matters on merges),a..b/a...bare commit ranges,rev:pathreads a file at that revision,HEAD@{n}uses the reflog, andgit rev-parseresolves any of it to a full hash. - Never commit:
.envand secrets (rotate first if leaked — 6.7),__pycache__/.venv/node_modules, OS noise, giant data files (>50 MiB warns, >100 MiB blocks on GitHub — use LFS or keep them out). .gitignorepatterns: last match wins,!negates, can't ignore tracked files (git rm --cachedfixes that), and can't re-include a file inside an excluded directory..gitattributesnormalises line endings and hosts LFS rules.- Branches are pointers.
git switch/-cto move; merges are fast-forward (linear) or merge commits (two parents). Conflicts show<<<<<<<markers — resolve,git add,git commit, orgit merge --abort. - Rebase replays commits onto a new base (new hashes) — local branches only.
cherry-pickcopies one commit. Never rebase or force-push shared history. - Undo ladder:
restore --staged(unstage) →restore(discard edits, unrecoverable) →commit --amend/reset --soft|mixed|hard(local only) →revert(safe for shared history) →reflog(the safety net for commits, ~90/30-day expiry). - Everyday tools:
stashshelves WIP, annotatedtag -amarks releases,blame/log -Strace lines,bisectbinary-searches bugs,git grepsearches tracked content,worktreegives parallel checkouts. - Habits: feature branches, atomic commits, pull before push, never work on
mainin a team, commit early/often — a committed mistake is recoverable, an uncommitted one may not be.
Where you'll use this in the AI path#
Git is the connective tissue of everything that follows:
- Every project in the path lives in a git repo — your
ai-pathworkspace started here and continues through Modules 01–14. - Secrets discipline pays off immediately: 03.1 Part 3 is entirely about keeping provider keys out of code and history — the
.env/.gitignorehabits from 4.4 are its foundation, and 03.1 §3.7 is 6.7 applied to real API keys. - Prompts are code: 04.10 versions prompt templates in git — atomic commits and good messages are what make "which prompt produced this output?" answerable.
- CI/CD for prompts and evals: 11C.2 runs tests and eval gates on every commit/PR — the branch/commit discipline here is what those pipelines assume.
- Collaboration at scale: 00.4 adds remotes, pull requests, code review and GitHub Actions on top of exactly these commands.
- Debugging production issues:
git bisect(7.4) andgit blame(7.3) reappear in 00.9 and 11A.1-style incident work. - Career evidence: your git history is your portfolio — 14B Career Appendix builds on repos like
ai-path.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Version control system (VCS) | Software that records every state of a project so you can return, compare and share them |
| Git | The distributed VCS tool and protocol; every clone is a complete repository |
| GitHub | A hosting service and collaboration layer built on git (PRs, issues, Actions) |
| Repository / repo | A folder plus its .git directory containing full history |
| Snapshot | Git's storage unit: the complete state of all files at one commit |
| Blob | Git object storing one file's raw contents, named by its SHA-1 hash |
| Tree | Git object storing a directory listing (names → blob/tree hashes) |
| Commit | Git object: tree + parent(s) + author/committer + timestamp + message |
| Object model / content-addressing | Objects named by hash of their contents — identical content stored once, corruption detectable |
| SHA-1 / SHA-256 | Hash algorithms naming git objects; SHA-256 repos exist but don't interoperate yet |
| Working tree | The files you see and edit on disk |
| Staging area / index | .git/index: what the next commit will contain |
git status |
Shows working-tree/index/HEAD differences and untracked files |
| Commit hash | A commit's content fingerprint; how you name any revision |
| Branch | A movable pointer to a commit; a line of work |
HEAD |
Pointer to current branch (or detached commit) |
| Detached HEAD | HEAD pointing directly at a commit, not a branch |
| Tag | A (usually permanent) name for a commit; annotated tags are objects with messages |
| DAG | Directed acyclic graph — the shape of commit history |
| Merge commit | A commit with two parents joining two lines of work |
| Fast-forward | Merge that slides a branch pointer forward when no divergence occurred |
| Merge conflict | Both sides changed the same lines; resolved manually via markers |
| Rebase | Replay commits onto a new base — rewrites hashes; local branches only |
| Cherry-pick | Copy one commit onto another branch |
.gitignore |
Pattern file listing paths git should not track |
.gitattributes |
Rule file for line endings, binary types, LFS and linguist hints |
| Git LFS | Large File Storage: pointer files in git, real bytes on an LFS server |
git stash |
Shelve worktree+index changes and clean the tree |
git reflog |
Log of where HEAD/branches moved — the recovery mechanism |
git reset |
Move branch pointer; --soft/--mixed/--hard decide file fate |
git revert |
Undo a commit by adding an inverse commit — safe for shared history |
git bisect |
Binary-search history for the first bad commit |
| Revision | Any name for a commit: hash, branch, tag, HEAD, HEAD~N, rev^, a..b |
Revision range (.. / ...) |
a..b = commits in b not a; a...b = changes on either side since they diverged |
git blame |
Per-line last-modifying commit, author and date |
git worktree |
Extra working directories attached to one repository |
| Submodule | A nested repository embedded at a pinned commit |
| Conventional Commits | type(scope): subject message convention for machine-readable history |
| Atomic commit | One logical change per commit |
| Bare repository | A .git-only repo (no worktree) — what remotes usually are |
| Origin / remote | A named pointer to another repository you fetch/push (taught fully in 00.4) |
| Force push | Overwriting remote history — forbidden on shared branches |
| Git hook | An executable script git runs automatically at workflow points (pre-commit, commit-msg, pre-push) |
All terms are also collected in the glossary.
Exercises#
Do these in a scratch directory (SCRATCH=$(mktemp -d); cd $SCRATCH on macOS/Linux/WSL), never in a repo you care about. Once you've git inited a scratch repo, give it a throwaway identity — repo-local, not --global (a global setting would overwrite the real identity you configured in 2.2 on every repo on your machine):
git config user.name "Learner" # writes to THIS repo's .git/config only
git config user.email "learner@example.com"Run those two lines inside each new scratch repo after git init (each repo needs its own), or prefix commits one-off with git -c user.name=Learner -c user.email=learner@example.com commit … — nothing is written anywhere. If you already set your real identity in 2.2 you can skip this entirely: commits will carry your real name, which is fine for local practice.
-
First repo (2.4, Part 3):
git inita folder, createhello.pycontainingprint("hi"), and make two commits: first the file, then an edit that adds a second print. Rungit log --oneline --graph,git status, andgit show HEAD~1 --stat. Explain in one sentence what the--statoutput tells you. -
The three areas (1.4, 3.1): edit
hello.pywithout staging. Rungit status --short, thengit diff, thengit add hello.py, thengit status --shortagain, thengit diff --staged. For each command, say which two areas it compares. -
.gitignore(4.1): write a.gitignorefor a Python project that ignores.env,__pycache__/,.venv/, and*.log, but keeps.env.example. Create all four file types plus.env.example, rungit status --ignored --short, and confirm withgit check-ignore -vwhich pattern decides each path. -
Untracking (4.2): commit a file
data/export.csv, then add/data/*.csvto.gitignore, then trygit status— is the file still tracked? Fix it withgit rm --cachedand prove the file still exists on disk withls. What doesgit log -- data/export.csvstill show, and why does that matter for secrets? -
Branches and merges (5.2–5.3): create
feature/xwith one commit, return tomainwithout committing anything new, and merge — observe the fast-forward. Now make a second feature branch, commit on it, commit something different onmain, and merge again — observe the merge commit and its two parents (git show -s --format='%P' HEAD). -
Conflicts (5.3): on two branches change the same line of the same file differently, merge, and inspect the
<<<<<<</=======/>>>>>>>markers. Resolve by hand,git add,git commit. Then redo it and usegit merge --abortinstead — confirm the file returns to its pre-merge state. -
Rebase vs merge (5.4): repeat exercise 5's diverged case but finish with
git rebase mainon the feature branch instead of merging. Comparegit log --oneline --graphbefore and after — what changed about the hashes and why? -
Cherry-pick (5.4): with at least three commits on a branch,
git cherry-pick <middle-hash>ontomain. What lands onmain, and what happens to the branch? -
Undo ladder (Part 6): make three commits, then: (a)
git reset --soft HEAD~1and inspectgit status --short; (b)git reset --mixed(or baregit reset) and inspect again; (c) recover withgit reflog— find the "lost" commit's hash andgit branch rescue <hash>. Explain why--hardwould have been the only mode that actually loses the commit's content. -
Revert (6.4): pick a commit that adds a file,
git revertit, and show thatgit log --onelinenow contains both commits. Why is this the right undo for a pushed branch, and why is it wrong for removing a committed secret? -
Stash and tags (7.1–7.2): make uncommitted edits,
git stash -u, confirm a cleangit status,git stash pop. Then create a lightweight tagv0.1.0and an annotated tagv0.2.0 -m "release", and comparegit cat-file -ton each. -
Bisect (7.4): rebuild the lesson's five-commit
calc.pyrepo (or any repo where you can plant a bug in a middle commit), mark good/bad endpoints, and rungit bisect run ./test.sh. How many test runs did git need for 5 commits? Predict the count for 100 commits before checking. -
Blame and archaeology (7.3): edit a file across three commits, then use
git blameto find which commit wrote each line,git log -S "<a string you added>"to find when it appeared, andgit log --followon a file you renamed. -
Secret in history (6.7, 4.4): commit a
.envcontainingOPENAI_API_KEY=sk-FAKE-EXAMPLE-ONLY, remove it withgit rm --cachedplus a.gitignoreentry, and commit again. Prove the secret is still recoverable viagit log -p -S "sk-FAKE"andgit show <commit>:.env. Write down the correct recovery order (what do you do first?). -
Worktrees (7.7):
git worktree add ../ai-path-wt -b experimentfrom your repo, verify both folders share history (git log --oneline -3in each), commit something in the worktree, and remove it withgit worktree remove.
Solutions
-
Commands:
git init && cd <dir>; writehello.py;git add hello.py && git commit -m "Add hello"; edit;git add -A && git commit -m "Add second print"; thengit log --oneline --graphshows two*lines newest-first;git statusis clean;git show HEAD~1 --statshows the first commit touched onlyhello.pywith its line counts — proof each commit is a self-contained snapshot, not a diff. -
git status --short→M hello.py(worktree vs index).git diffcompares working tree vs index. Aftergit add,MbecomesMandgit diffis empty whilegit diff --stagedshows the change — it compares index vs HEAD. -
Sample
.gitignore:.env/!.env.example/__pycache__//.venv//*.log.git status --ignored --shortshows!!for the ignored files and??for.env.example.check-ignore -vprints the deciding.gitignoreline per path. -
After the ignore rule,
git statusstill listsdata/export.csvunder tracked changes — ignore rules don't apply to tracked files.git rm --cached data/export.csv && git commit -m "…"untracks it;lsproves it remains on disk.git log -- data/export.csvstill shows the old commit — history retains the content, which is why secrets need rotation + history rewrite, not just untracking. -
First merge prints
Fast-forwardandgit log --graphstays linear. Second merge printsMerge made by the 'ort' strategyand creates a merge commit;git show -s --format='%P' HEADprints two parent hashes. -
The conflicted file contains
<<<<<<< HEAD,=======,>>>>>>> branch. After editing to the intended content:git add file && git commit. With--abort,git statusreturns to the pre-merge branch and the file has no markers. -
After
git rebase main, the feature commits have new hashes (same changes, new parents → new content fingerprints) andgit log --graphis linear. The pre-rebase commits still exist viagit reflog. -
git cherry-pick <hash>applies just that commit's diff ontomainas a new commit; the source branch and its other commits are untouched. -
(a)
--softleaves the change staged (Min status) and the commit gone fromlog. (b)--mixedleaves it unstaged (M). (c)git refloglistsHEAD@{n}entries newest-first;git branch rescue <hash>restores a pointer to the "lost" commit.--hardis the only mode that overwrites the worktree — and even then the commit survives in reflog; what--hardtruly destroys is uncommitted edits. -
Log shows e.g.
abc1234 Revert "Add feature file"above the originaldef5678 Add feature file; the file is gone but both commits exist — auditable undo. For secrets this fails because the original commit (with the secret) remains in history. -
After
stash -u,git status --shortis clean;stash poprestores edits and drops the entry.git cat-file -t v0.1.0→commit(lightweight);git cat-file -t v0.2.0→tag(annotated object with tagger/message). -
With 5 commits bisect needed ~2–3 test runs. For 100 commits it's ⌈log₂100⌉ ≈ 7 runs — that's the point of binary search.
-
git blame fileattributes each line to its last-touching commit;-Sfinds the commit that changed the count of a string;--followkeeps a file's history across renames. -
git log -p -S "sk-FAKE"prints the commit that introduced the line, andgit show <hash>:.envprints the file's content at that commit — the secret is fully recoverable. Correct order: rotate/revoke the key first, then remove from history (filter-repo), then coordinate force-push with collaborators. -
git worktree add ../ai-path-wt -b experimentcreates a second folder on a new branch sharing the same.gitobject store; commits in either appear in both histories;git worktree remove ../ai-path-wtcleans up.
Check yourself#
- Why does git store whole snapshots rather than per-file deltas, and what makes that efficient anyway?Snapshots make any historical state instant to reconstruct (no patch replay). Efficiency comes from content-addressing: unchanged files share one blob, so only changed content is stored.
- Name the three areas of git and the command that shows all three at once.Working tree, staging area (index), repository.
git status(especially--short). - In
git status --short, what doesMmean versusM?M= modified in worktree, not staged.M= modified and staged (index differs from HEAD). First letter = index vs HEAD, second = worktree vs index. - What's the difference between
git diff,git diff --staged, andgit diff HEAD~1 HEAD?git diff= worktree vs index;--staged= index vs HEAD;HEAD~1 HEAD= previous commit vs current commit. - Why can't
.gitignorehide a file that's already committed, and what's the fix?.gitignoreonly affects untracked files. Fix:git rm --cached <file>(keeps it on disk) and commit. - What does
.gitattributes'* text=auto eol=lfactually do to a CRLF file?On commit, CRLF is normalised to LF inside the repo;eol=lfwrites LF on checkout — the stored blob is always LF regardless of OS. - When is a fast-forward merge possible, and what does a merge commit's "two parents" represent?Fast-forward is possible when the target branch hasn't moved since you branched (no divergence). A merge commit's two parents are the two line tips being joined.
- You resolve a conflicted file but forget
git add. What happens if you try to commit or switch branches?The merge is still in progress: commit will complain about unmerged paths, andgit switch/checkoutto another branch is refused until yougit addthe resolved file (orgit merge --abort). - State the golden rule about rebasing, and the command that is always safe for undoing a pushed commit.Never rebase commits that have been pushed/shared — it rewrites history others may have.
git revert <hash>is always safe for public history. - What's the difference between
git reset --soft,--mixed, and--hard?--soft: move pointer, keep index+worktree.--mixed(default): move pointer, reset index, keep worktree edits.--hard: move pointer and overwrite index+worktree — destroys uncommitted changes. - A commit seems lost after
git reset --hard. Where do you look first and why does it work?git reflog— it logs every HEAD/branch movement with the old and new hashes, so the "lost" commit is still reachable viaHEAD@{n}for ~90 days (30 for unreachable entries) untilgcprunes it. - What's the correct first step when you discover a committed API key — and why isn't
git revertenough?Rotate/revoke the key first — it's compromised the moment it was committed/pushed. Revert only adds a deletion commit; the secret remains readable in history, so history rewriting (e.g.git filter-repo) plus collaborator coordination is needed. - What's the difference between a lightweight and an annotated tag?Lightweight = a plain pointer to a commit. Annotated = a tag object containing tagger, date and message — preferred for releases.
- How does
git bisectfind a bug in 100 commits, and what does the test script's exit code mean?Bisect checks out the midpoint of the good..bad range and halves the suspects each step: ⌈log₂n⌉ tests (≈7 for 100). The script exits 0 for good, 1–127 except 125 for bad, 125 for skip — any other exit code aborts the search. - Decode these revisions:
HEAD~2,HEAD^2,main..feature,main...feature,HEAD~1:app.py,HEAD@{1}.HEAD~2= two commits back along the first-parent chain;HEAD^2= HEAD's second parent (only differs from~on merge commits);main..feature= commits onfeaturenot onmain;main...feature= changes since the branches diverged;HEAD~1:app.py=app.py's contents one commit ago;HEAD@{1}= where HEAD pointed one move ago (reflog).
Further resources#
- Pro Git (free book, git-scm.com): the definitive free reference — read chapters 1–3 once, keep it bookmarked forever.
- git-scm.com/docs: official man pages for every command in this lesson (
gitignore,gitattributes,reflog,bisect…). - GitHub Docs: Ignoring files and About large files on GitHub: the
.gitignore/rm --cachedprocedure and the exact size limits. - GitHub Docs: Removing sensitive data from a repository: the official secret-in-history procedure this lesson summarises.
- github/gitignore: GitHub's official
.gitignoretemplate collection. - git-lfs.com and GitHub Docs: Configuring Git LFS: when you need it.
- Conventional Commits 1.0.0: the commit-message spec.
- Learn Git Branching: the best interactive visual trainer for branches/merges/rebases — do it after this lesson.
- GitHub Skills: free interactive courses (Introduction to Git and more) built into GitHub.
- Atlassian Git Tutorials: well-written beginner-to-advanced walkthroughs, including "undoing changes" deep dives.
← 00.2 — The Terminal and Shell | Module 00 overview | 00.4 — GitHub and Collaboration →