00.3 Git Fundamentals

FoundationsLesson 3 of 914,716 words8 parts
Module 00 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9

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 status line 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
  • .gitignore pattern rules, global ignores, untracking committed files, .gitattributes and line endings, why secrets and large files must never enter history, and what Git LFS is for
  • Branches: switch vs checkout, 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, the reflog safety 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 main in 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:

bash
SCRATCH=$(mktemp -d)   # macOS/Linux/WSL — a fresh empty temp folder
echo $SCRATCH          # remember this path; it is your playground
cd $SCRATCH

On Windows PowerShell the equivalent is:

powershell
$SCRATCH = Join-Path $env:TEMP ("gitdemo-" + [guid]::NewGuid().ToString("N").Substring(0,8))
New-Item -ItemType Directory -Path $SCRATCH | Out-Null
Set-Location $SCRATCH

The 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:

bash
git cat-file -t HEAD        # what kind of object is HEAD? -> "commit"
git cat-file -p HEAD        # print the commit object: tree, parents, author, message
Example output · illustrative7 lines
commit
tree 41a9d0648ea72340c32a3d48f9de097582802520
parent 4dfd7299df7d7a2b603dd2d9bef536ace6d4aeb7
author Learner <learner@example.com> 1770454800 +0000
committer Learner <learner@example.com> 1770454800 +0000

    Add logger.py

That 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"] -.-> B1

Notice 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 add copies 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, like refs/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:

bash
git --version

As 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:

bash
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:

bash
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 terminal

Two details that save confusion later:

  • init.defaultBranch matters because the upstream default is still master. Git announced in the 2.52 release notes (2025) that Git 3.0 will switch the built-in default to main, but as of November 2026 released versions still initialise master unless configured — except on platforms that set it for you: GitHub has defaulted new repos to main since October 2020, and Apple's Command Line Tools ship a system gitconfig that already sets init.defaultBranch=main (which is why git init on a fresh Mac gives you main with no hint). Setting the config yourself makes behaviour identical on every machine you use.
  • core.autocrlf and .gitattributes control line endings. On Windows, git's default can rewrite LF↔CRLF and create noisy diffs. The modern fix is a .gitattributes file in the repo (4.3); core.autocrlf is the older per-machine knob. Leave it alone unless you see ^M characters 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):

bash
git config --list --show-origin
Example output · illustrative3 lines
file:/Library/Developer/CommandLineTools/usr/share/git-core/gitconfig	init.defaultbranch=main
file:.git/config	user.name=Learner
file:.git/config	user.email=learner@example.com

Read 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:

bash
mkdir -p ~/code/ai-path && cd ~/code/ai-path
git init

On 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:

bash
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:

bash
git add README.md tickets.py notes/api-facts.md
git commit -m "Initial commit: README, ticket helper, API notes"
git log --oneline

git 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:

bash
git status
Example output · illustrative9 lines
On 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:

Example output · illustrative6 lines
 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#

bash
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:

bash
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 main
Example output · illustrative11 lines
diff --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#

bash
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:

Example output · illustrative6 lines
*   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:

bash
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 step

git 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-pick and code review all work properly.
  • Body for the why: wrap at ~72 chars; explain motivation, trade-offs, links to issues.
text
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:

text
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 case

Common 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 from feature but not from main: "what would merging bring?"
  • main...feature — commits reachable from either but not both: the changes on feature since it diverged from main. This is the form git diff main...feature uses 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.txt in 4.3. During a merge conflict, :1:path, :2:path, :3:path address 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:

bash
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 form

Tags 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:

bash
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:

  1. Last matching pattern wins. .env.* ignores .env.example, but the later !.env.example un-ignores it. Order matters — put negations after the broad rule.
  2. You can't ignore a file that's already tracked. .gitignore only affects untracked files. If you committed data/old-export.csv last week, adding /data/old-export.csv to .gitignore changes nothing — git keeps tracking it. The fix is 4.2.
  3. 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.csv silently does nothing. This is why the /data/*.csv + !/data/tickets.csv pair above works (the data/ directory is never excluded, only matching files inside it) while data/ + !data/keep.csv fails. 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:

bash
git check-ignore -v .env data/big-export.csv __pycache__/x.pyc
Example output · illustrative3 lines
.gitignore:2:.env	.env
.gitignore:22:/data/*.csv	data/big-export.csv
.gitignore:7:__pycache__/	__pycache__/x.pyc

And see ignored files that status hides:

bash
git status --ignored --short
Example output · illustrative5 lines
?? .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).
  • .gitignore files in subdirectories — apply to that subtree (e.g. scripts/.gitignore ignoring scripts/*.log).
  • Global excludes — core.excludesFile, default ~/.config/git/ignore: patterns applied to every repo you touch, like a personal .DS_Store filter. This is what GitHub's docs call the machine-wide ignore; the repo's own .gitignore is 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:

bash
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:

bash
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:

bash
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  \n

Index (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:

  1. 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.
  2. History is forever (practically). Deleting the file doesn't delete it from history — 6.7 shows the secret still readable via git log -p.
  3. 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:

bash
# .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, switch back and the experiment never touched main.
  • 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 main always working — main stays releasable while features cook.

Since Git 2.23 there are dedicated commands — prefer them, they can't accidentally touch files:

bash
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 branch

git 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:

bash
git switch -c feature/login-form
# …edit, commit…
git switch main
git merge feature/login-form
Example output · illustrative4 lines
Updating 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:

bash
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-edit
Example output · illustrative2 lines
Merge made by the 'ort' strategy.
 README.md | 2 ++
Example output · illustrative6 lines
*   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

git 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
    end

5.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:

text
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:

bash
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:

bash
git merge --abort               # restores pre-merge state completely

Other 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:

bash
git switch feature/logging      # has 2 commits
git rebase main                 # replay them onto main's tip
Example output · illustrative1 line
Rebasing (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:

bash
git switch main
git cherry-pick feature/logging~1   # apply just the "Add logger.py" commit
Example output · illustrative4 lines
[main e4e61b7] Add logger.py
 Date: ...
 1 file changed, 3 insertions(+)
 create mode 100644 logger.py

Use 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:

Example output · illustrative18 lines
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.md

Legitimate 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:

text
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 release

Short, 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:

bash
# 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 destroyed

Real walkthrough on the scratch repo:

bash
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 entirely
Output · the two git status --short results, in order2 lines
M  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:

bash
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":

bash
git revert e4e61b7
Example output · illustrative3 lines
[main d8aa747] Revert "Add logger.py"
 1 file changed, 3 deletions(-)
 delete mode 100644 logger.py

Log 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:

bash
git reflog -10
Example output · illustrative8 lines
e4e61b7 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 main

Read it newest-first: HEAD@{0} is where you are, HEAD@{1} is where you just were. Recovering is mechanical:

bash
# find the commit you lost
git reflog
git branch rescue 85fb227          # or: git reset --hard 85fb227 / git cherry-pick 85fb227

The 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-found only 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 -fdx on untracked files. git clean deletes untracked files from the working tree (-f force, -d include directories, -x include ignored files such as .env and .venv/). Same as rm — untracked means git never saw it. The safe habit: run git 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:

  1. 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.
  2. Assess exposure. Was it pushed? Public or private repo? How long? That decides urgency.
  3. Remove it from history if warranted — git filter-repo is the tool GitHub recommends (git filter-branch is deprecated-ish: slow and footgunny). It is a separate tool, not part of core git: install it with brew install git-filter-repo, your distro's package, or pip 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.
  4. 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.
  5. 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:

bash
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":

bash
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
Output2 lines
$ 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#

bash
git blame -L 1,4 app.py
Example output · illustrative3 lines
^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?":

bash
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 backwards

7.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):

bash
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 automatically
Example output · illustrative2 lines
Bisecting: 0 revisions left to test after this (roughly 1 step)
[74e0b9e8b2c926cb556cbc8bedccf295c0d59c6b] c4: BUG - div actually multiplies

Test 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:

bash
#!/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)"
bash
git bisect run ./test_div.sh    # git drives the whole search itself
git bisect reset               # return to your branch when done
Example output · illustrative7 lines
running './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 multiplies

The 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#

bash
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 file

Why 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:

bash
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:

bash
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-hotfix

One 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 --auto runs after certain commands), packing loose objects into packfiles. Run git gc manually on huge repos; git count-objects -v shows the stats.
  • Shallow clones (--depth 1) — CI and "just look at the code" clones that skip history entirely.
  • git log on huge repos — always bound it: --since, -n 50, a path, or --author. An unbounded git log -p on 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)"| B
  1. main stays green — every commit on it works.
  2. New work = new branch (feature/, fix/, chore/).
  3. Commit early, commit often, atomically — a WIP commit on your branch is free insurance.
  4. Keep the branch short-lived; merge (or PR, in 00.4) when done; delete the branch.
  5. 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 pull fetches remote changes and merges them in before your push is rejected — 00.4 §3.1 unpacks fetch vs pull properly. On a shared branch, pull/rebase first, resolve locally, then push.
  • Never work directly on main in a team. Even a "tiny fix" — branch it. main is the shared contract; branches are where experiments live.
  • Read git status before 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.0 should 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
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 status shows all three; --short's two-letter codes are <staged><worktree>.
  • The daily loop: status → add (deliberately, -p for hunks) → commit (imperative, atomic, Conventional Commits optional) → diff/log/show to review.
  • Name any commit precisely: HEAD~N walks back N first-parents, rev^N picks parent N (matters on merges), a..b/a...b are commit ranges, rev:path reads a file at that revision, HEAD@{n} uses the reflog, and git rev-parse resolves any of it to a full hash.
  • Never commit: .env and 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).
  • .gitignore patterns: last match wins, ! negates, can't ignore tracked files (git rm --cached fixes that), and can't re-include a file inside an excluded directory. .gitattributes normalises line endings and hosts LFS rules.
  • Branches are pointers. git switch/-c to move; merges are fast-forward (linear) or merge commits (two parents). Conflicts show <<<<<<< markers — resolve, git add, git commit, or git merge --abort.
  • Rebase replays commits onto a new base (new hashes) — local branches only. cherry-pick copies 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: stash shelves WIP, annotated tag -a marks releases, blame/log -S trace lines, bisect binary-searches bugs, git grep searches tracked content, worktree gives parallel checkouts.
  • Habits: feature branches, atomic commits, pull before push, never work on main in 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-path workspace 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/.gitignore habits 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) and git 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):

bash
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.

  1. First repo (2.4, Part 3): git init a folder, create hello.py containing print("hi"), and make two commits: first the file, then an edit that adds a second print. Run git log --oneline --graph, git status, and git show HEAD~1 --stat. Explain in one sentence what the --stat output tells you.

  2. The three areas (1.4, 3.1): edit hello.py without staging. Run git status --short, then git diff, then git add hello.py, then git status --short again, then git diff --staged. For each command, say which two areas it compares.

  3. .gitignore (4.1): write a .gitignore for a Python project that ignores .env, __pycache__/, .venv/, and *.log, but keeps .env.example. Create all four file types plus .env.example, run git status --ignored --short, and confirm with git check-ignore -v which pattern decides each path.

  4. Untracking (4.2): commit a file data/export.csv, then add /data/*.csv to .gitignore, then try git status — is the file still tracked? Fix it with git rm --cached and prove the file still exists on disk with ls. What does git log -- data/export.csv still show, and why does that matter for secrets?

  5. Branches and merges (5.2–5.3): create feature/x with one commit, return to main without committing anything new, and merge — observe the fast-forward. Now make a second feature branch, commit on it, commit something different on main, and merge again — observe the merge commit and its two parents (git show -s --format='%P' HEAD).

  6. 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 use git merge --abort instead — confirm the file returns to its pre-merge state.

  7. Rebase vs merge (5.4): repeat exercise 5's diverged case but finish with git rebase main on the feature branch instead of merging. Compare git log --oneline --graph before and after — what changed about the hashes and why?

  8. Cherry-pick (5.4): with at least three commits on a branch, git cherry-pick <middle-hash> onto main. What lands on main, and what happens to the branch?

  9. Undo ladder (Part 6): make three commits, then: (a) git reset --soft HEAD~1 and inspect git status --short; (b) git reset --mixed (or bare git reset) and inspect again; (c) recover with git reflog — find the "lost" commit's hash and git branch rescue <hash>. Explain why --hard would have been the only mode that actually loses the commit's content.

  10. Revert (6.4): pick a commit that adds a file, git revert it, and show that git log --oneline now contains both commits. Why is this the right undo for a pushed branch, and why is it wrong for removing a committed secret?

  11. Stash and tags (7.1–7.2): make uncommitted edits, git stash -u, confirm a clean git status, git stash pop. Then create a lightweight tag v0.1.0 and an annotated tag v0.2.0 -m "release", and compare git cat-file -t on each.

  12. Bisect (7.4): rebuild the lesson's five-commit calc.py repo (or any repo where you can plant a bug in a middle commit), mark good/bad endpoints, and run git bisect run ./test.sh. How many test runs did git need for 5 commits? Predict the count for 100 commits before checking.

  13. Blame and archaeology (7.3): edit a file across three commits, then use git blame to find which commit wrote each line, git log -S "<a string you added>" to find when it appeared, and git log --follow on a file you renamed.

  14. Secret in history (6.7, 4.4): commit a .env containing OPENAI_API_KEY=sk-FAKE-EXAMPLE-ONLY, remove it with git rm --cached plus a .gitignore entry, and commit again. Prove the secret is still recoverable via git log -p -S "sk-FAKE" and git show <commit>:.env. Write down the correct recovery order (what do you do first?).

  15. Worktrees (7.7): git worktree add ../ai-path-wt -b experiment from your repo, verify both folders share history (git log --oneline -3 in each), commit something in the worktree, and remove it with git worktree remove.

Solutions
  1. Commands: git init && cd <dir>; write hello.py; git add hello.py && git commit -m "Add hello"; edit; git add -A && git commit -m "Add second print"; then git log --oneline --graph shows two * lines newest-first; git status is clean; git show HEAD~1 --stat shows the first commit touched only hello.py with its line counts — proof each commit is a self-contained snapshot, not a diff.

  2. git status --short → M hello.py (worktree vs index). git diff compares working tree vs index. After git add, M becomes M and git diff is empty while git diff --staged shows the change — it compares index vs HEAD.

  3. Sample .gitignore: .env / !.env.example / __pycache__/ / .venv/ / *.log. git status --ignored --short shows !! for the ignored files and ?? for .env.example. check-ignore -v prints the deciding .gitignore line per path.

  4. After the ignore rule, git status still lists data/export.csv under tracked changes — ignore rules don't apply to tracked files. git rm --cached data/export.csv && git commit -m "…" untracks it; ls proves it remains on disk. git log -- data/export.csv still shows the old commit — history retains the content, which is why secrets need rotation + history rewrite, not just untracking.

  5. First merge prints Fast-forward and git log --graph stays linear. Second merge prints Merge made by the 'ort' strategy and creates a merge commit; git show -s --format='%P' HEAD prints two parent hashes.

  6. The conflicted file contains <<<<<<< HEAD, =======, >>>>>>> branch. After editing to the intended content: git add file && git commit. With --abort, git status returns to the pre-merge branch and the file has no markers.

  7. After git rebase main, the feature commits have new hashes (same changes, new parents → new content fingerprints) and git log --graph is linear. The pre-rebase commits still exist via git reflog.

  8. git cherry-pick <hash> applies just that commit's diff onto main as a new commit; the source branch and its other commits are untouched.

  9. (a) --soft leaves the change staged (M in status) and the commit gone from log. (b) --mixed leaves it unstaged ( M). (c) git reflog lists HEAD@{n} entries newest-first; git branch rescue <hash> restores a pointer to the "lost" commit. --hard is the only mode that overwrites the worktree — and even then the commit survives in reflog; what --hard truly destroys is uncommitted edits.

  10. Log shows e.g. abc1234 Revert "Add feature file" above the original def5678 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.

  11. After stash -u, git status --short is clean; stash pop restores 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).

  12. 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.

  13. git blame file attributes each line to its last-touching commit; -S finds the commit that changed the count of a string; --follow keeps a file's history across renames.

  14. git log -p -S "sk-FAKE" prints the commit that introduced the line, and git show <hash>:.env prints 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.

  15. git worktree add ../ai-path-wt -b experiment creates a second folder on a new branch sharing the same .git object store; commits in either appear in both histories; git worktree remove ../ai-path-wt cleans up.


Check yourself#

  1. Why does git store whole snapshots rather than per-file deltas, and what makes that efficient anyway?
  2. Name the three areas of git and the command that shows all three at once.
  3. In git status --short, what does M mean versus M ?
  4. What's the difference between git diff, git diff --staged, and git diff HEAD~1 HEAD?
  5. Why can't .gitignore hide a file that's already committed, and what's the fix?
  6. What does .gitattributes' * text=auto eol=lf actually do to a CRLF file?
  7. When is a fast-forward merge possible, and what does a merge commit's "two parents" represent?
  8. You resolve a conflicted file but forget git add. What happens if you try to commit or switch branches?
  9. State the golden rule about rebasing, and the command that is always safe for undoing a pushed commit.
  10. What's the difference between git reset --soft, --mixed, and --hard?
  11. A commit seems lost after git reset --hard. Where do you look first and why does it work?
  12. What's the correct first step when you discover a committed API key — and why isn't git revert enough?
  13. What's the difference between a lightweight and an annotated tag?
  14. How does git bisect find a bug in 100 commits, and what does the test script's exit code mean?
  15. Decode these revisions: HEAD~2, HEAD^2, main..feature, main...feature, HEAD~1:app.py, HEAD@{1}.

Further resources#


← 00.2 — The Terminal and Shell | Module 00 overview | 00.4 — GitHub and Collaboration →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close