Skip to content

Git & Version Control: Object Model, Branching Strategies, Rebase vs Merge, PRs, Hosting ​

"Git is a fast, scalable, distributed revision control system with an unusually rich command set that provides both high-level operations and full access to internals." — git(1), the Git manual page (git-scm.com/docs/git)

Summary: Git stores snapshots, not diffs: every file version is a blob, every directory a tree, every commit a small text object pointing at one tree and its parents, and every branch a 41-byte file holding a commit id. Once you see that graph, merge, rebase, reset, revert, reflog and --force-with-lease stop being incantations and become operations on pointers. This chapter builds the graph by hand in a throwaway repository, then walks through the daily workflow (three areas, commits, branches, conflicts, undo), the team workflow (branching strategies, pull and merge requests, protected branches, CODEOWNERS, signed commits) and the large-repository and security toolbox (sparse-checkout, partial clone, LFS, hooks, secrets in history). Focus: blob, tree, commit object and tag object, SHA-1 and SHA-256 repositories, refs, HEAD, detached HEAD, reflog, packfiles, git cat-file and git hash-object; the working tree, index (staging area) and HEAD with git status, git diff --staged and git add -p; Conventional Commits, commit trailers, signed commits with SSH signing or GPG, --fixup and autosquash; fast-forward, three-way merge, the ort strategy, merge conflicts, rerere and --no-ff; rebase, interactive rebase, --onto, --update-refs, rewriting history and force-with-lease; trunk-based development, GitHub Flow, GitLab Flow, git-flow, release branches and feature flags; pull requests and merge requests, stacked PRs, squash merge versus rebase merge, protected branches, required checks and CODEOWNERS; remotes (origin, upstream), SSH vs HTTPS, the credential helper and personal access tokens; annotated and lightweight tags, semver and git describe; git restore, git reset --soft --mixed --hard, git revert and reflog recovery; git bisect, git blame -w -C, git log -S (the pickaxe); git worktree, git stash; submodule versus subtree; .gitignore, .gitattributes, EOL and autocrlf, export-ignore; Git LFS; monorepo basics with sparse-checkout and partial clone (--filter=blob:none); hooks and pre-commit; git maintenance; secrets in history and git filter-repo; the verified badge; Go (go.mod pseudo-version, go get tag, go generate output) and Laravel (composer.lock, .env ignored, migrations, Envoy). Learning goal: Draw the object graph of any small repository and predict what each command does to it; choose merge, rebase or squash for a given team and defend it; recover any commit you "lost"; set up a repository with protection rules, code owners, signed commits and hooks; and remove a leaked secret the right way (rotate first, rewrite second).

This chapter belongs to the Linux & Tooling group. The shell the examples run in is Shell Scripting & Text Processing and the machine under it is Linux for Developers. What happens after a push (pipelines, required checks running, OIDC) is CI/CD Pipelines; using a Git repository as the source of truth for a cluster is GitOps: Argo CD and Flux; turning a tag into a rollout is Deployment Strategies. On the Go side, modules and versions are in Toolchain, Modules & Packages and repository layout and linting in Project Layout, golangci-lint, Makefile, Docker & Multi-Binary Builds. Secret scanning as a process, SAST and incident response live in Secure SDLC, DevSecOps, Logging, Incident Response; keeping commits small enough to review is half of Code Smells, Anti-Patterns & Refactoring.

Every transcript on this page (the text blocks) comes from a real run with Git 2.54.0 (Apple Git-157) on macOS in throwaway repositories created by the scripts under docs/snippets/platform/git-version-control/scripts/; blocks that could not be run here (GPG, Git LFS, git filter-repo, the pre-commit framework, hosting APIs) are labelled "expected, not run", and the short recipe blocks in Solving the classic problems are recipes, not transcripts. The scripts fix the author, committer and clock, so the commit ids you see are the ids you will get when you run them (except in the SSH-signing transcript, which generates a fresh key).

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why version control, why Git won, the analogyWhy it exists
Releases that changed daily use (switch/restore, ort, update-refs, SHA-256)Where it comes from
blob, tree, commit object, tag object, git cat-file, git hash-objectObjects
refs, HEAD, detached HEAD, reflogRefs, HEAD and the reflog
packfile, SHA-1, SHA-256, git maintenancePackfiles, hashes, maintenance
working tree, index, staging area, git add -p, git diff --stagedThe three areas
Conventional Commits, commit trailers, signed commits, SSH signing, GPGCommits and messages
fast-forward, three-way merge, ort strategy, --no-ffMerging
merge conflict, rerereConflicts and rerere
rebase, interactive rebase, --onto, --update-refs, fixup, autosquashRebase
rewriting history, force-with-leaseRewriting shared history
trunk-based development, GitHub Flow, GitLab Flow, git-flow, release branch, feature flagsBranching strategies
pull request, merge request, stacked PRs, squash merge, rebase merge, protected branches, required checks, CODEOWNERSPull and merge requests
remote, origin, upstream, SSH vs HTTPS, credential helper, personal access tokenRemotes and hosting
annotated tag, lightweight tag, semver, git describeTags and releases
git restore, git reset --soft --mixed --hard, git revert, reflog recoveryUndoing things
git bisect, git blame -w -C, git log -S (pickaxe), -GFinding the commit that did it
git worktree, git stashWorktrees and stash
submodule vs subtreeSubmodules and subtrees
.gitignore, .gitattributes, EOL, autocrlf, export-ignore, linguistIgnore and attributes
Git LFSLarge files
monorepo, sparse-checkout, partial clone, --filter=blob:noneMonorepos
hooks, pre-commitHooks
secrets in history, git filter-repo, verified badgeSecurity
How a commit, a merge, a rebase and a push work underneath; knobs; error messagesMechanics
go.mod pseudo-version, go get tag, go generate, a commit-message linter in GoGo
composer.lock, .env ignored, migrations as history, Envoy deploys from tagsLaravel
Undo the last commit, a leaked key, a huge PR, a regressionSolving the classic problems
Merge or rebase or squash; which strategy; submodule or subtreeChoosing
One repo to many services and many regionsIn architecture
Commands with real outputLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The four object types. Everything Git stores is one of these, named by the hash of its content.

ObjectHoldsPoints atCreated bySee it with
blobThe bytes of one file version (no name, no mode)Nothinggit add, git hash-object -wgit cat-file -p <id>
treeA directory listing: mode, type, id, name per entryBlobs and treesgit commit, git write-treegit cat-file -p 'HEAD^{tree}', git ls-tree
commit objecttree id, parent ids, author, committer, message (and an optional signature)One tree, 0..n parent commitsgit commit, git merge, git rebasegit cat-file -p HEAD
tag objectTarget id and type, tag name, tagger, message (and an optional signature)Usually a commitgit tag -a, git tag -sgit cat-file -p v1.0.0

The three areas and the commands between them.

From → toCommandWhat it changes
Working tree → indexgit add <path>, git add -pStages content (a blob is written now)
Index → repositorygit commitWrites trees and a commit; moves the current branch
Index → working treegit restore <path>Discards unstaged edits (unrecoverable)
HEAD → indexgit restore --staged <path>Unstages; the edit stays on disk
Compare working tree vs indexgit diffWhat you have not staged
Compare index vs HEADgit diff --staged (alias --cached)What the next commit will contain
Move branch (+ index, + working tree)git reset --soft, --mixed (default), --hardSoft: branch; mixed: + index; hard: + working tree

Integrating a branch: the four shapes.

MethodHistory afterwardsCommit ids of the branchTypical place
Fast-forwardStraight line; the branch ref just movesUnchangedgit merge when the target has not moved
Merge commit (three-way, --no-ff)A commit with two parents; the branch is visibleUnchangedGitHub "Create a merge commit", GitLab default
Rebase then fast-forwardStraight line; commits replayed on the new baseNew idsgit rebase main, GitHub "Rebase and merge"
Squash mergeOne new commit with one parentBranch commits are not in mainGitHub "Squash and merge", GitLab "Squash commits"

Undo, by situation.

SituationCommandSafe on shared branches?
Throw away an unstaged editgit restore <path>Local only
Unstagegit restore --staged <path>Local only
Redo the last commit (message or content)git commit --amend, or git reset --soft HEAD~1No, if already pushed
Undo a pushed commitgit revert <id>Yes: adds the inverse commit
"I reset --hard and lost a commit"git reflog, then git branch rescue HEAD@{1}Local recovery
Deleted a branchgit reflog, git switch -c name <id>Local recovery
A secret was committed and pushedRotate the secret, then git filter-repo, then force-push and tell everyoneCoordinated rewrite
Refs point at objects; objects point at objects by id (ids from the lab run)REFS (mutable names)HEADref: refs/heads/mainrefs/heads/mainc8441fdrefs/tags/v0.1.0c26eab2OBJECTS (immutable, named by the hash of their content)tag c26eab2object c8441fd, type committagger, messagecommit c8441fdtree 716babf, parent 374b8e7fix: greet the worldcommit 374b8e7tree 58426fc, no parentfeat: first commitparenttree 716babfgreeting.txt, src/tree 58426fcgreeting.txt, src/blob (greeting.txt v2)"hello, world"tree b9270dfsrc/ (shared)blob ce01362"hello"Unchanged subtrees are reused,not copied: both commitspoint at tree b9270df.

Why it exists ​

Without version control a team shares a folder and a convention ("don't touch checkout.php today"). The questions that matter in production then have no answer: what exactly is running, who changed this line and why, what changed between Tuesday and Wednesday, how do two people work on the same file, and how do we go back. Version control answers them by recording every change as an addressable, attributable unit. Git's specific answer is to store snapshots of the whole tree, named by content hash, in a repository every developer has a full copy of.

Centralised (Subversion, Perforce)Distributed (Git, Mercurial)
One server holds history; clients hold a working copyEvery clone holds the full history
Commit = talk to the serverCommit is local and instant; push/pull share it
Branches are directory copies, expensive culturallyA branch is a 41-byte file; branching is free
Locks on binary files are naturalNo locks; large binaries need Git LFS
Partial checkout of a huge tree is easyNeeds sparse-checkout and partial clone
Access control per pathAccess control per repository (plus CODEOWNERS for review)

An everyday picture. A Git repository is a photo album where every photo is a picture of the whole kitchen, not of "what changed". Each photo has a sticky note saying which photo came before it. A branch is a bookmark you move to the newest photo. Rebasing is re-taking your photos as if you had started cooking later; merging is gluing a photo that says "these two sequences both happened". Because the photos are named by what is in them, two identical kitchens get the same name automatically, and nobody can secretly retouch an old photo without its name changing.

Three common misunderstandings, up front ​

  1. "Git stores diffs." It stores full snapshots (blobs and trees) and computes diffs when you ask. Packfiles do use delta compression to save space, but that is a storage detail below the object model; git cat-file -p always gives you whole objects (Objects, Packfiles).
  2. "A branch is a line of commits." A branch is one pointer to one commit. The "line" is whatever is reachable by following parents from it. Deleting a branch deletes a pointer, not commits; that is why the reflog can bring them back.
  3. "Rebase is dangerous, merge is safe" (or the reverse). Both are safe on commits only you have. Rebase becomes dangerous the moment someone else has built on the commits you replace, because it creates new commits and abandons the old ones; merge never rewrites anything but can bury the history in merge commits. The rule is about shared history, not about the command (Rewriting shared history).

Where it comes from ​

Year / versionEventWhy it matters here
2005Git written by Linus Torvalds for Linux kernel development after the BitKeeper licence ended (general knowledge; no saved primary source)Design goals: speed, distributed, integrity by hash
2010Vincent Driessen publishes "A successful Git branching model" (git-flow)The long-lived develop + release/hotfix model many teams adopted
2017-02-23SHAttered: "a practical SHA-1 hash collision" (Git's hash-function-transition document)Git switches to a hardened SHA-1 and plans SHA-256
2018"In late 2018 the project picked SHA-256 as its successor hash" (same document)--object-format=sha256
Git 2.23"Two new commands git switch and git restore are introduced" (release notes)Splits the two jobs of git checkout; this page uses them
Git 2.29SHA-256 support, "marked as experimental"; "no interoperability between SHA-1 and SHA-256 repositories yet"A SHA-256 repository cannot push to a SHA-1 host
2020-03-05Driessen's "Note of reflection": for continuous delivery "adopt a much simpler workflow (like GitHub flow)"Why git-flow faded for web apps
Git 2.34"The ort strategy is used instead of recursive as the default merge strategy"The strategy name you see in "Merge made by the 'ort' strategy"
Git 2.38"git rebase -i learns to update branches whose tip appear in the rebased range with --update-refs"Stacked branches move together
Git 2.45The reftable backend integrated (git init --ref-format=reftable)Refs stored in a binary table instead of loose files
Git 2.54"git maintenance starts using the 'geometric' strategy by default"The build host's version for every transcript on this page

The primary references are the Git manual pages on git-scm.com (saved under pipeline/sources/git-version-control/, one file per page), the Pro Git book's internals chapters, the release notes in the Git source tree, and the hosting platforms' own documentation for the parts that are not Git (pull requests, rulesets, CODEOWNERS, the verified badge).

The concept catalogue ​

Objects: blob, tree, commit object, tag object Must-know ​

In plain words: Git is a key-value store. You give it bytes, it gives you back a hash, and from then on that hash is the name of those bytes. Files become blobs, directories become trees, and a commit is a short note that says "this tree, after these parents, by this person, because of this message".

Common misunderstanding: "The file name is part of the blob" or "a commit contains the changed files". A blob has no name; the tree that lists it does. A commit contains exactly one tree id (the whole snapshot) and its parents' ids; the "changed files" are computed by comparing two trees.

Definition: an object id is the SHA-1 (or SHA-256) of a header <type> <size>\0 followed by the content. git hash-object computes it and, with -w, writes the object to .git/objects/; git cat-file -t prints the type and -p pretty-prints the content. A tree entry is mode type id name; modes are 100644 (file), 100755 (executable), 120000 (symlink), 040000 (tree) and 160000 (gitlink, a submodule). A commit object has tree, zero or more parent lines, author, committer, an optional gpgsig header and the message. An annotated tag object has object, type, tag, tagger and a message.

1  git hash-object -w greeting.txt      -> blob ce01362   ("hello\n")
2  git add greeting.txt src/main.go     -> index records path -> blob id
3  git commit -m "feat: first commit"   -> tree 58426fc (greeting.txt, src/ -> tree b9270df)
4                                       -> commit 374b8e7 (tree 58426fc, no parent)
5  edit greeting.txt; git commit        -> new blob, new tree 716babf (src/ reused: b9270df)
6                                       -> commit c8441fd (tree 716babf, parent 374b8e7)
7  git tag -a v0.1.0                    -> tag object c26eab2 -> commit c8441fd

Real scenario: two services vendor the same 2 MB file: the repository stores it once, because identical content has the same id. A build reproduces a release exactly from a commit id, because the id covers the tree, which covers every blob. A security reviewer asks whether a release was altered after signing: a changed byte anywhere changes the commit id, which breaks the signature. A file renamed without changes costs one new tree entry and no new blob; Git detects renames by similarity when diffing, not by recording them.

The lab script builds this graph by hand:

bash
#!/usr/bin/env bash
# The object model by hand: blob, tree, commit, tag; refs, HEAD, packfiles; SHA-256.
source "$(dirname "$0")/lib.sh"
fresh objects

say "a blob is content only: same bytes, same id, anywhere"
run git hash-object --stdin <<< 'hello'
printf 'hello\n' > greeting.txt
run git hash-object -w greeting.txt
run git cat-file -t ce013625030ba8dba906f756967f9e9ca394464a
run git cat-file -p ce013625030ba8dba906f756967f9e9ca394464a

say "the id is SHA-1 over a header plus the content"
printf '$ printf '"'"'blob 6\\0hello\\n'"'"' | shasum -a 1\n'
printf 'blob 6\0hello\n' | shasum -a 1

say "a tree maps names to blobs and trees; a commit points at one tree"
mkdir -p src
printf 'package main\n' > src/main.go
git add greeting.txt src/main.go
run git write-tree
tick
run git commit -q -m "feat: first commit"
run git cat-file -p HEAD
run git cat-file -p 'HEAD^{tree}'
run git ls-tree -r HEAD

say "a second commit records its parent"
commit_file greeting.txt 'hello, world' "fix: greet the world"
run git cat-file -p HEAD
run git rev-parse HEAD~1 HEAD^

say "refs are files (or lines in packed-refs); HEAD is a symbolic ref"
run cat .git/HEAD
run cat .git/refs/heads/main
run git symbolic-ref HEAD

say "tags: lightweight = a ref; annotated = a tag object with its own id"
run git tag v0.1.0-light
tick
run git tag -a v0.1.0 -m "release 0.1.0"
run git cat-file -t v0.1.0-light
run git cat-file -t v0.1.0
run git cat-file -p v0.1.0
run git rev-parse v0.1.0 'v0.1.0^{commit}'

say "detached HEAD: HEAD holds a commit id, not a branch name"
run git switch --detach HEAD~1 2>&1
run cat .git/HEAD
tick
commit_file note.txt 'experiment' "chore: experiment on detached HEAD"
run git switch main 2>&1
run git reflog -3

say "loose objects, then a packfile"
run git count-objects -v
run git gc -q
run git count-objects -v
run sh -c 'ls .git/objects/pack/ | sed "s/pack-[0-9a-f]*/pack-<id>/"'
run sh -c 'git verify-pack -v .git/objects/pack/pack-*.idx | tail -3'
run cat .git/packed-refs

say "SHA-256 repositories: same model, 64-hex ids, not interoperable with SHA-1 remotes"
cd "$W" || exit 1
rm -rf sha256
run git init -q --object-format=sha256 sha256
cd sha256 || exit 1
run git rev-parse --show-object-format
run git hash-object --stdin <<< 'hello'

Real output (abridged; full transcript in pipeline/sources/git-version-control/runs/01-object-model.txt):

text
$ git hash-object --stdin
ce013625030ba8dba906f756967f9e9ca394464a
$ printf 'blob 6\0hello\n' | shasum -a 1
ce013625030ba8dba906f756967f9e9ca394464a  -
$ git cat-file -p HEAD
tree 58426fcaad9271581f340aba647a8afb0911666a
author Ada Dev <ada@example.com> 1767261720 +0000
committer Ada Dev <ada@example.com> 1767261720 +0000

feat: first commit
$ git cat-file -p 'HEAD^{tree}'
100644 blob ce013625030ba8dba906f756967f9e9ca394464a	greeting.txt
040000 tree b9270df7070cc6a5e7dbdec610a7ce4f54c47b20	src
$ git cat-file -t v0.1.0-light
commit
$ git cat-file -t v0.1.0
tag
$ git cat-file -p v0.1.0
object c8441fd12dcf98533ef75c69c6062c7926f70936
type commit
tag v0.1.0
tagger Ada Dev <ada@example.com> 1767261840 +0000

release 0.1.0

The shasum line is the whole trick: the blob id is the SHA-1 of blob 6\0hello\n, which anyone can recompute. That is what makes Git content-addressed.

ObjectMutable?Survives git gc?Hosted platforms show it as
blob, treeNever (a change is a new object)If reachable from a ref or a reflog entryFile view, directory view
commit objectNever; amend and rebase create new commitsSameCommit page; "Verified" badge if signed
tag objectNever; moving a tag means deleting and recreating the refSameRelease / tag page; "Verified" if signed

Refs, HEAD, detached HEAD and the reflog Must-know ​

In plain words: objects never change, so Git needs movable names. A ref is a file containing a commit id (refs/heads/main), HEAD says which ref you are on, and the reflog is Git's diary of every value HEAD and each branch ever had on your machine.

Common misunderstanding: "Detached HEAD means something is broken." It only means HEAD holds a commit id instead of a branch name, which is exactly what you want when you inspect an old release or bisect. The risk is making commits there and walking away: no branch points at them, and Git warns you when you leave.

Definition: the glossary says HEAD is "a reference to one of the heads in your repository, except when using a detached HEAD, in which case it directly references an arbitrary commit". Branches live under refs/heads/, remote-tracking branches under refs/remotes/<remote>/, tags under refs/tags/; git pack-refs (run by gc) moves them into .git/packed-refs. A symbolic ref (HEAD) contains ref: refs/heads/main. The reflog (git reflog, .git/logs/) records each update of HEAD and of each branch with the old and new id; entries are addressed as HEAD@{2} or main@{yesterday}. Defaults from git reflog and git config: reachable entries expire after 90 days (gc.reflogExpire), unreachable ones after 30 days (gc.reflogExpireUnreachable). The reflog is local: it is never pushed or cloned.

1  cat .git/HEAD                   ref: refs/heads/main          (attached)
2  git switch --detach HEAD~1      HEAD = 374b8e7                (detached)
3  git commit -m "experiment"      HEAD = 5d296e4, no branch points here
4  git switch main                 "Warning: you are leaving 1 commit behind"
5  git reflog -3                   5d296e4 HEAD@{1}: commit: chore: experiment on detached HEAD
6  git branch keep 5d296e4         the experiment is reachable again

Real output:

text
$ git switch --detach HEAD~1
HEAD is now at 374b8e7 feat: first commit
$ cat .git/HEAD
374b8e7f657ec43a475c5587278e8e7b4c81a53d
$ git switch main
Warning: you are leaving 1 commit behind, not connected to
any of your branches:

  5d296e4 chore: experiment on detached HEAD
...
$ git reflog -3
c8441fd HEAD@{0}: checkout: moving from 5d296e4f648d1802f36b303abb1582536a728e20 to main
5d296e4 HEAD@{1}: commit: chore: experiment on detached HEAD
374b8e7 HEAD@{2}: checkout: moving from main to HEAD~1

Real scenario: CI checks out the pushed commit, not the branch, so every CI job runs on a detached HEAD (GitHub Actions actions/checkout, GitLab runners); a step that commits and pushes there must name the target ref explicitly. A developer runs git reset --hard on the wrong branch: the old tip is HEAD@{1}. git bisect detaches HEAD on every step and git bisect reset returns you. A deploy server that does git checkout v1.4.2 runs from a detached HEAD by design.

Ref kindWhereMoves whenShared on push?
Branch refs/heads/main.git/refs/heads/ or packed-refsYou commit, merge, reset, rebaseYes, if you push it
Remote-tracking refs/remotes/origin/mainSameOnly on fetch/pull/pushNo (it is your copy of theirs)
Tag refs/tags/v1.0.0SameShould never moveOnly with --tags / --follow-tags or by name
HEAD, ORIG_HEAD, FETCH_HEAD, MERGE_HEAD.git/Each operationNever
Reflog.git/logs/Every ref updateNever

Packfiles, SHA-1 to SHA-256, and git maintenance Important ​

In plain words: new objects are written as separate compressed files ("loose objects"). Periodically Git packs them into one packfile with an index, storing similar objects as deltas against each other. That is why a repository with thousands of versions of a file stays small.

Common misunderstanding: "A packfile means Git stores diffs after all." The delta is a compression trick between any two similar objects (not necessarily consecutive versions); every read still reconstructs whole objects, and the object ids are those of the full content.

Definition: git gc (and git maintenance) writes .git/objects/pack/pack-<id>.pack plus .idx (offsets), .rev (reverse index) and, for unreachable objects kept for safety, a cruft pack with .mtimes. git verify-pack -v lists the objects in a pack. git count-objects -v shows loose versus packed counts. The hash: SHA-1 by default; SHAttered demonstrated "a practical SHA-1 hash collision" in 2017, Git uses a collision-detecting SHA-1 implementation, but "SHA-1 is still weak" (hash-function-transition). git init --object-format=sha256 creates a SHA-256 repository with 64-hex ids; as of the Git 2.29 notes there is "no interoperability between SHA-1 and SHA-256 repositories yet", and none of the GitHub or GitLab pages read for this chapter offers SHA-256 repositories, so treat SHA-256 as a self-hosted option today (check your host before choosing it). git maintenance run executes tasks (gc, commit-graph, prefetch, loose-objects, incremental-repack, pack-refs) in the foreground; git maintenance start registers the repository, sets maintenance.strategy=incremental if unset, and installs a scheduler entry (--scheduler=auto|crontab|systemd-timer|launchctl|schtasks). Git 2.54's notes say maintenance "starts using the 'geometric' strategy by default" for repacking.

1  12 commits/trees/blobs written      count: 12 loose, 0 packs
2  git gc -q                          count: 0, in-pack: 12, packs: 2 (one cruft pack for the unreachable experiment)
3  git verify-pack -v ...idx          "non delta: 9 objects ... .pack: ok"
4  git init --object-format=sha256    hash-object "hello" -> 2cf8d83d...ebb4 (64 hex)

Real output:

text
$ git count-objects -v
count: 12
...
$ git gc -q
$ git count-objects -v
count: 0
size: 0
in-pack: 12
packs: 2
...
$ git rev-parse --show-object-format
sha256
$ git hash-object --stdin
2cf8d83d9ee29543b34a87727421fdecb7e3f3a183d337639025de576db9ebb4

Real scenario: a monorepo's git status slows down: git maintenance start adds the commit-graph and prefetch tasks so fetches and history walks stay fast. A CI runner caches .git between jobs and the cache grows: run git maintenance run --task=gc in the cache step. A government customer requires SHA-256: self-host (Gitea, Forgejo or a plain SSH server) and accept that the repository cannot be mirrored to a SHA-1 host. A repository server (GitHub, GitLab Gitaly) runs repacking itself; you never run gc on the server copy.

Task (git maintenance)DoesSchedule in the incremental strategy that register/start sets
gcFull repack and pruneDisabled (gc: disabled in the manual)
commit-graphWrites the commit-graph file for fast history walksHourly
prefetchFetches into refs/prefetch/ so git fetch later is cheapHourly
loose-objectsPacks loose objectsDaily
incremental-repackRepacks packs into larger ones using the multi-pack-indexDaily
pack-refsMoves loose refs into packed-refsNot in that schedule; run it with git maintenance run --task=pack-refs (the lab does)

The three areas: working tree, index (staging area), HEAD Must-know ​

In plain words: every tracked file exists three times: the version in the last commit (HEAD), the version you have staged for the next commit (the index), and the version on disk (the working tree). git add copies disk → index, git commit copies index → a new commit. Everything else is moving content between those three.

Common misunderstanding: "git commit commits my changes." It commits the index. An edit you did not stage is not in the commit, and an edit you staged and then changed again is in the commit in its staged form. git status showing MM means exactly that: staged and further modified.

Definition: the index (.git/index, also called the staging area or cache) is a sorted list of mode, blob id, stage number, path plus stat data used to detect changes quickly. Staging writes the blob immediately; the commit writes trees from the index. git status --short prints two columns: left = index vs HEAD, right = working tree vs index. git diff compares working tree with index; git diff --staged (synonym --cached) compares index with HEAD; git diff HEAD compares working tree with HEAD. git add -p (patch mode) walks the hunks and asks y/n/s/e/q per hunk, so one file can contribute part of its changes to a commit.

1  edit app.txt: fix line 1, add a debug print on line 10      status: " M"
2  git add -p app.txt   -> y (fix), n (debug)                   status: "MM"
3  git diff             -> only the debug print (unstaged)
4  git diff --staged    -> only the fix (what will be committed)
5  git commit -m "fix: correct line 1"                          status: " M" (debug left behind)
6  git restore app.txt  -> debug print discarded (never stored, cannot be recovered)
Three copies of every file, and the commands that move content between themWorking treefiles on disk you edituntracked files live herenot stored by Git until addedIndex (staging area).git/index: path, mode, blob id= the next commit's treestages 1/2/3 during a conflictHEAD (repository)the commit the branch points atobjects in .git/objectshistory, refloggit add / add -pgit commitgit restorerestore --stagedgit diff (unstaged changes)git diff --staged (what the commit will contain)git diff HEAD (everything since the last commit)git reset <commit> moves the branch, then resets the areas from it:--soft: branch only--mixed (default): + index--hard: + working tree
bash
#!/usr/bin/env bash
# Working tree, index (staging area) and HEAD: status, diff, diff --staged, add -p, restore.
source "$(dirname "$0")/lib.sh"
fresh areas
printf 'line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\n' > app.txt
git add app.txt && tick && git commit -q -m "feat: add app.txt"

say "two unrelated edits in one file: top and bottom"
sed -e 's/^line 1$/line 1 (bug fix)/' -e 's/^line 10$/line 10 (debug print)/' app.txt > app.tmp && mv app.tmp app.txt
run git status --short
run git diff --stat

say "git add -p: stage the first hunk (y), skip the second (n)"
printf 'y\nn\n' | git add -p app.txt > /dev/null
echo '$ printf "y\nn\n" | git add -p app.txt'
run git status --short
say "git diff = working tree vs index (what is NOT staged)"
run git diff
say "git diff --staged = index vs HEAD (what the next commit will contain)"
run git diff --staged

say "the index is a real file: ls-files --stage shows the staged blob id"
run git ls-files --stage
run git rev-parse HEAD:app.txt :app.txt

tick
run git commit -q -m "fix: correct line 1"
say "after the commit: only the debug print is left, unstaged"
run git status --short

say "git restore throws away a working-tree change (no undo: it was never stored)"
run git restore app.txt
run git status --short
run tail -1 app.txt

say "git restore --staged unstages but keeps the edit"
echo 'new line' >> app.txt
git add app.txt
run git status --short
run git restore --staged app.txt
run git status --short

Real output (abridged from runs/02-three-areas.txt):

text
$ printf "y\nn\n" | git add -p app.txt
$ git status --short
MM app.txt
--- git diff = working tree vs index (what is NOT staged)
-line 10
+line 10 (debug print)
--- git diff --staged = index vs HEAD (what the next commit will contain)
-line 1
+line 1 (bug fix)
$ git ls-files --stage
100644 49f0a8316d7be30d2cb780793ea8a80069b688a5 0	app.txt
$ git rev-parse HEAD:app.txt :app.txt
fa2da6e55caa540725b55c04d13f1e42b4c725ce
49f0a8316d7be30d2cb780793ea8a80069b688a5

HEAD:app.txt and :app.txt (the index) are two different blobs: the index already holds the staged version before any commit exists.

Real scenario: a developer fixes a bug and adds debug logging in the same file; git add -p produces a clean fix commit and keeps the logging local. A reviewer asks "is the migration in this commit?": git diff --staged --stat answers before committing. A team sets commit.verbose = true so the editor shows the staged diff under the message. A git restore after a long afternoon of unstaged work deletes it for good: that is why git stash or a WIP commit is the habit before risky commands.

git status --shortIndex vs HEADWorking tree vs indexMeaning
MSameModifiedEdited, not staged
M ModifiedSameStaged, nothing more
MMModifiedModifiedStaged, then edited again
A AddedSameNew file staged
D / D - / DeletedDeleted / -Deleted on disk / deletion staged
??--Untracked
UU--Unmerged: both sides modified (conflict)

Commits and messages: Conventional Commits, trailers, signing, fixup Must-know ​

In plain words: a commit message is the only documentation that is guaranteed to be next to the code forever. A structured first line (fix(cart): round totals half-up) lets tools build changelogs and version numbers; trailers at the end (Refs: #412, Co-authored-by:) carry metadata; a signature proves who made it.

Common misunderstanding: "The author is who pushed it." Git records an author and a committer, both free text from your config. Anyone can write user.email = cto@company.com. Only a signature that the host verifies against a key registered to an account ties a commit to a person; that is what the GitHub "Verified" badge means.

Definition: Conventional Commits 1.0.0: "The commit message should be structured as follows: <type>[optional scope]: <description>, blank line, optional body, blank line, optional footer(s)". feat maps to a semver MINOR, fix to PATCH, and "a commit that has a footer BREAKING CHANGE:, or appends a ! after the type/scope, introduces a breaking API change (correlating with MAJOR in Semantic Versioning)". Other types (docs, refactor, test, ci, build, chore, perf, style, revert) are conventions the spec allows. Commit trailers are Token: value lines in the last paragraph (git interpret-trailers, git commit --trailer "Refs: #12", git log --format='%(trailers)'). Signed commits: git commit -S (or commit.gpgSign = true) adds a gpgsig header to the commit object; gpg.format = openpgp (GPG, the default), ssh (an SSH key; "SSH signature verification is available in Git 2.34 or later", GitHub docs) or x509 (S/MIME). git verify-commit, git log --show-signature and %G? (G good, B bad, U good with unknown validity, X/Y expired signature/key, R revoked key, E cannot be checked, N no signature) check it locally; SSH verification needs gpg.ssh.allowedSignersFile. Fixup commits: git commit --fixup=<commit> creates fixup! <subject>; git rebase -i --autosquash moves it under its target and melds it in (--fixup=amend:<commit> and squash! also change the message).

1  feat(cart)!: drop the legacy price field        <- header: type(scope)!: description, <= 72 chars
2                                                  <- blank line
3  Clients must send amount_minor (integer cents). <- body: why, not how
4                                                  <- blank line
5  Refs: #412                                      <- trailers: Token: value
6  Co-authored-by: Bob Ops <bob@example.com>
7  BREAKING CHANGE: price is removed               <- footer that also means MAJOR

SSH signing, run for real with a throwaway key:

bash
#!/usr/bin/env bash
# Signed commits and tags with an SSH key (gpg.format=ssh), verified locally
# through an allowed-signers file. GPG works the same way with gpg.format=openpgp.
source "$(dirname "$0")/lib.sh"
fresh signing
KEY="$W/home/ada_signing"
rm -f "$KEY" "$KEY.pub"
ssh-keygen -q -t ed25519 -N '' -C ada@example.com -f "$KEY"

say "configure SSH signing for this repository"
run git config gpg.format ssh
run git config user.signingkey "$KEY.pub"
printf 'ada@example.com %s\n' "$(cut -d' ' -f1,2 "$KEY.pub")" > "$W/home/allowed_signers"
run git config gpg.ssh.allowedSignersFile "$W/home/allowed_signers"
run git config commit.gpgSign true

commit_file app.txt 'v1' "feat: signed commit"
say "the signature lives inside the commit object, in a gpgsig header"
run sh -c 'git cat-file -p HEAD | sed -n "1,5p"'
run git verify-commit HEAD 2>&1 | sed -E 's/SHA256:[A-Za-z0-9+\/]+/SHA256:<fingerprint>/'
run git log -1 --format='%h %G? %GS %s'

say "an unsigned commit by someone else shows N"
git -c commit.gpgSign=false commit -q --allow-empty -m "chore: unsigned"
run git log -2 --format='%h %G? %s'
try git verify-commit HEAD

say "tags: -s signs an annotated tag"
tick
run git tag -s v1.0.0 -m "signed release"
run git verify-tag v1.0.0 2>&1 | sed -E 's/SHA256:[A-Za-z0-9+\/]+/SHA256:<fingerprint>/'

say "tampering: rewrite the commit body, the signature no longer matches"
git cat-file -p HEAD~1 | sed 's/feat: signed commit/feat: signed commit (edited)/' > "$W/home/forged"
forged=$(git hash-object -t commit -w "$W/home/forged")
try git verify-commit "$forged" | sed -E 's/SHA256:[A-Za-z0-9+\/]+/SHA256:<fingerprint>/'
text
$ sh -c 'git cat-file -p HEAD | sed -n "1,5p"'
tree b69ed90e1d5f2d4a148cb9ba6f4e30b6066da9e6
author Ada Dev <ada@example.com> 1767261720 +0000
committer Ada Dev <ada@example.com> 1767261720 +0000
gpgsig -----BEGIN SSH SIGNATURE-----
 U1NIU0lHAAAAAQAAADMAAAALc3NoLWVkMjU1MTkAAAAgZsFui9FPSOEYN3gDiLbjya/Bq4
$ git verify-commit HEAD
Good "git" signature for ada@example.com with ED25519 key SHA256:<fingerprint>
$ git log -1 '--format=%h %G? %GS %s'
6b07020 G ada@example.com feat: signed commit
--- an unsigned commit by someone else shows N
$ git log -2 '--format=%h %G? %s'
7133274 N chore: unsigned
6b07020 G feat: signed commit
$ git verify-commit HEAD
(exit 1)
--- tags: -s signs an annotated tag
$ git tag -s v1.0.0 -m 'signed release'
$ git verify-tag v1.0.0
Good "git" signature for ada@example.com with ED25519 key SHA256:<fingerprint>
--- tampering: rewrite the commit body, the signature no longer matches
$ git verify-commit 699a9082498b2f0b1fe0441ab517346e26cfe61c
Could not verify signature.
Signature verification failed: incorrect signature
(exit 1)

The tampering step verifies a forged copy of the signed commit whose message was edited: the bytes no longer match the signature. (The signature and commit ids in this transcript change on every run because the key is generated fresh; all other transcripts on the page are byte-for-byte reproducible.)

Real scenario: release tooling (semantic-release, release-please, git-cliff) reads Conventional Commits to bump the version and write the changelog. A regulated team requires signed commits on main (GitHub ruleset "Require signed commits", GitLab push rule "Reject unsigned commits"). A pair-programming session credits both people with Co-authored-by:, which GitHub shows on the commit. A review comment is answered with git commit --fixup so the reviewer sees the delta, and git rebase -i --autosquash cleans it up before merge.

Signing methodKey you already have?Local verify needsGitHubGitLab
GPG (gpg.format=openpgp)Rarelygpg keyring with the public keyUpload the GPG key; "Verified"Upload the GPG key; "Verified"
SSH (gpg.format=ssh, Git 2.34+; avoid OpenSSH 8.7)Yes, the one you push withgpg.ssh.allowedSignersFileAdd the key as a signing key; "Verified"Key usage "Authentication & Signing" or "Signing"; "Verified"
S/MIME (gpg.format=x509, Git 2.19+)Corporate certificatesgpgsmSupportedX.509 certificate, supported
Hosting-made commits (web UI edits)n/an/a"GitHub will automatically use GPG to sign commits you make using the web interface""GitLab signs the commits it creates, like commits made through the web UI"

Fast-forward, three-way merge and the ort strategy Must-know ​

In plain words: merging feature into main asks "what does a snapshot that contains both lines of work look like?". If main has not moved since feature started, the answer is "just feature", and Git simply moves the pointer (fast-forward). If both moved, Git compares each side against their last common commit (the merge base) and combines the two sets of changes into a new commit with two parents.

Common misunderstanding: "A merge compares the two branch tips." It compares each tip with the merge base; that is why it can tell "you changed this line and they did not" (take yours) from "both changed it" (conflict). Two-way comparison could not decide.

Definition: git merge <branch> fast-forwards when the current commit is an ancestor of <branch> (refuse with --ff-only otherwise, force a merge commit with --no-ff). Otherwise it runs a merge strategy. ort ("Ostensibly Recursive's Twin") is "the default merge strategy when pulling or merging one branch. This strategy can only resolve two heads using a 3-way merge algorithm"; it replaced recursive as the default in Git 2.34. Other strategies: octopus (several branches, no conflicts allowed), ours (record a merge but keep our tree), subtree, resolve. Strategy options with -X: ours/theirs (prefer a side on conflicting hunks only), ignore-space-change, renormalize, find-renames=<n>. git merge-base A B prints the base.

1  main:    B---M                     feature: B---C---D
2  git merge-base main feature   ->   B
3  ort: diff(B, M) + diff(B, D)  ->   no overlap: combine
4  new commit X: parents M and D, tree = combined snapshot
5  --no-ff on a fast-forwardable branch -> X anyway (records "this was a branch")
bash
#!/usr/bin/env bash
# Fast-forward, --no-ff, three-way merge (ort), rebase, --onto, --update-refs,
# interactive rebase with fixup/autosquash, and force-with-lease against a remote.
source "$(dirname "$0")/lib.sh"

base() { # a main with two commits and a feature branch with two commits
  fresh "$1"
  commit_file README 'shop' "chore: init"
  commit_file app.txt 'v1' "feat: app v1"
  git switch -q -c feature
  commit_file cart.txt 'cart' "feat(cart): add cart"
  commit_file cart.txt 'cart with totals' "feat(cart): totals"
  git switch -q main
}

say "fast-forward: main has not moved, so merge just moves the ref"
base ff
run git merge feature
run git log --oneline --graph

say "--no-ff: same situation, but force a merge commit that records the branch"
base noff
tick
run git merge --no-ff -m "Merge branch feature" feature
run git log --oneline --graph
run git cat-file -p HEAD

say "three-way merge: both sides moved; ort finds the merge base and combines"
base threeway
commit_file docs.txt 'docs' "docs: add docs"
run git merge-base main feature
tick
run git merge -m "Merge branch feature" feature
run git log --oneline --graph

say "rebase: replay feature on top of main; new commit ids, linear history"
base rebase
commit_file docs.txt 'docs' "docs: add docs"
git switch -q feature
run git rev-parse --short HEAD
tick
run git rebase main
run git rev-parse --short HEAD
run git log --oneline --graph main feature
git switch -q main
run git merge --ff-only feature
run git log --oneline --graph

say "--onto: move only the commits after a base onto a new parent"
fresh onto
commit_file a 'a' "chore: init"
git switch -q -c feature-a
commit_file a 'a2' "feat: A1 (belongs to feature-a)"
git switch -q -c feature-b
commit_file b 'b' "feat: B1 (only this should move)"
git switch -q main
commit_file m 'm' "chore: main moves"
git switch -q feature-b
tick
run git rebase --onto main feature-a feature-b
run git log --oneline --graph main feature-b

say "--update-refs: rebase a stack of branches and move every branch in it"
fresh stack
commit_file a 'a' "chore: init"
git switch -q -c part1
commit_file p1 'p1' "feat: part 1"
git switch -q -c part2
commit_file p2 'p2' "feat: part 2"
git switch -q main
commit_file m 'm' "chore: main moves"
git switch -q part2
tick
run git rebase --update-refs main 2>&1
run git log --oneline --graph --decorate main part2

say "fixup + autosquash: a review fix folded into the commit it fixes"
fresh fixup
commit_file a 'a' "chore: init"
commit_file api.go 'func Total() int { return 0 }' "feat: add Total"
commit_file ui.txt 'ui' "feat: add UI"
printf 'func Total() int { return 42 }\n' > api.go
git add api.go
tick
run git commit -q --fixup=HEAD~1
run git log --oneline
tick
GIT_SEQUENCE_EDITOR=true run git rebase -q -i --autosquash HEAD~3
run git log --oneline
run git show --stat --format=%s HEAD~1

say "interactive rebase: the todo list is a script; here an editor drops one commit"
cat > "$W/home/drop-ui.sh" <<'SEQ'
#!/bin/sh
# GIT_SEQUENCE_EDITOR receives the todo file as $1: show it, then edit it.
grep -v '^#' "$1" | grep -v '^$'
sed -e 's/^pick \(.*add UI\)$/drop \1/' "$1" > "$1.new" && mv "$1.new" "$1"
SEQ
chmod +x "$W/home/drop-ui.sh"
tick
GIT_SEQUENCE_EDITOR="$W/home/drop-ui.sh" run git rebase -q -i HEAD~2
run git log --oneline

say "force-with-lease: alice rewrites a pushed commit while bob pushed on top"
cd "$W" || exit 1
rm -rf remote.git alice bob
git init -q --bare remote.git
git clone -q remote.git alice 2>/dev/null
cd "$W/alice" || exit 1
commit_file f 'one' "feat: one"
git push -q origin main
cd "$W" && git clone -q remote.git bob && cd "$W/bob" || exit 1
as_bob commit_file g 'bob' "feat: bob adds g"
git push -q origin main
cd "$W/alice" || exit 1
printf 'one, fixed\n' > f
git add f
tick
git commit -q --amend -m "feat: one (amended)"
run git log --oneline --all

say "the lease is origin/main as alice last saw it; the remote moved, so the push is refused"
try git push --force-with-lease origin main | hide_work

say "trap: a fetch updates origin/main, the lease now matches, and bob's commit would be overwritten"
run git fetch -q origin
try git push --dry-run --force-with-lease origin main | hide_work
say "--force-if-includes also checks that alice integrated what she fetched"
try git push --force-with-lease --force-if-includes origin main | hide_work

say "the safe path: do not rewrite what others have; land the fix as a new commit"
run git reset -q origin/main
run git status --short
run git restore g
run git status --short
tick
run git commit -q -am "fix: correct f"
run git log --oneline --graph
try git push origin main | hide_work

Real output, the three shapes (runs/03-merge-vs-rebase.txt):

text
--- fast-forward: main has not moved, so merge just moves the ref
$ git merge feature
Updating fc1ed64..8e0b3d7
Fast-forward
$ git log --oneline --graph
* 8e0b3d7 feat(cart): totals
* 774bd5d feat(cart): add cart
* fc1ed64 feat: app v1
* 6bb2a9f chore: init
--- --no-ff: same situation, but force a merge commit that records the branch
$ git merge --no-ff -m 'Merge branch feature' feature
Merge made by the 'ort' strategy.
*   865f659 Merge branch feature
|\
| * 3b0afb7 feat(cart): totals
| * 0a0213d feat(cart): add cart
|/
* d394fa0 feat: app v1
$ git cat-file -p HEAD
tree 8141084b6ad232c72a30d1ae847221c1fd695c2a
parent d394fa090d4c34f7ad9dca8db4d6b04c1dc4804a
parent 3b0afb7786df836748ae5b1714839a23a4c3ff75
--- three-way merge: both sides moved; ort finds the merge base and combines
$ git merge-base main feature
bb93804bb0b6cc398bbd5890d1335cb7495bfbc5
*   9c2c056 Merge branch feature
|\
| * 700db11 feat(cart): totals
| * 7053604 feat(cart): add cart
* | 2f5d15b docs: add docs
|/
* bb93804 feat: app v1

Real scenario: GitLab's default merge method creates a merge commit for every merge request, so git log --first-parent main reads as one line per MR. A team that wants main to be a list of features uses --no-ff for every feature merge. A long-lived release branch is merged back into main with a normal merge so the hotfixes keep their ids and git branch --merged stays truthful. Two teams' branches both rename the same file: ort's rename detection handles it where recursive used to report rename/rename conflicts more often.

Strategy (-s)HeadsUse
ort (default since 2.34)2Every normal merge, pull, rebase step, cherry-pick
recursive2Default from v0.99.9k until v2.33.0; "redirected to mean ort in v2.50.0"
octopus3+Default for 3+ heads; refuses on conflicts
ours2+Record history but keep our tree (supersede an old branch)
subtree2Merge a project into a subdirectory
resolve2Legacy simple three-way

Merge conflicts and rerere Must-know ​

In plain words: a conflict is Git saying "both of you changed the same lines since you last agreed, and I will not guess". It writes both versions into the file between markers, records all three versions in the index, and waits for you to choose.

Common misunderstanding: "-X theirs resolves conflicts by taking their file." It takes their side only for conflicting hunks; non-conflicting changes from both sides are still merged. And git checkout --theirs during a rebase means the branch being replayed, not the upstream, because during a rebase "ours" is the base you are replaying onto.

Definition: during a conflicted merge the index holds stage 1 (merge base), stage 2 (ours, HEAD) and stage 3 (theirs, MERGE_HEAD) for the path; git status shows UU; git show :1:path, :2:path, :3:path print them. Markers: <<<<<<<, =======, >>>>>>>; with merge.conflictStyle = diff3 or zdiff3 (Git 2.35+) a ||||||| section shows the base too. Resolve by editing, then git add <path> and git commit (or git merge --continue; git merge --abort restores the pre-merge state). rerere ("reuse recorded resolution", rerere.enabled = true) saves the conflicted preimage and your resolution in .git/rr-cache/ and replays the resolution when the same conflict appears again (repeated rebases, re-merging a long-lived branch); rerere.autoUpdate also stages the result.

1  main:     price = 100  ->  price = 110  # VAT included
2  discount: price = 100  ->  price = 90   # 10% discount
3  git merge discount     ->  CONFLICT (content): Merge conflict in price.txt
4  index: :1 = "price = 100", :2 = "...110...", :3 = "...90..."
5  edit to "price = 99  # VAT included, 10% discount"; git add; git commit   ("Recorded resolution")
6  reset and merge again  ->  "Resolved 'price.txt' using previous resolution."
bash
#!/usr/bin/env bash
# A real merge conflict, the markers (merge and zdiff3 styles), resolution, and rerere.
source "$(dirname "$0")/lib.sh"
fresh conflicts
commit_file price.txt 'price = 100' "feat: price"
git switch -q -c discount
commit_file price.txt 'price = 90  # 10% discount' "feat: discount"
git switch -q main
commit_file price.txt 'price = 110  # VAT included' "feat: vat"

say "both sides changed the same line: the merge stops"
tick
try git merge discount
run git status --short
run cat price.txt
say "the index holds three versions: stage 1 = base, 2 = ours, 3 = theirs"
run git ls-files --stage price.txt
run git show :1:price.txt
run git show :2:price.txt
run git show :3:price.txt
run git merge --abort

say "zdiff3 conflict style also shows the merge base inside the markers"
git config merge.conflictStyle zdiff3
tick
try git merge discount >/dev/null
run cat price.txt
run git merge --abort

say "rerere: record a resolution once, replay it automatically next time"
git config rerere.enabled true
tick
try git merge discount
printf 'price = 99  # VAT included, 10%% discount\n' > price.txt
run git add price.txt
tick
run git commit -q --no-edit
run git rerere status
run ls .git/rr-cache

say "throw the merge away and do it again: rerere resolves the file by itself"
run git reset -q --hard HEAD~1
tick
try git merge discount
run cat price.txt
run git diff --name-only --diff-filter=U
say "rerere fixed the file but left it unmerged; review, then stage (rerere.autoUpdate would stage it)"
run git add price.txt
tick
run git commit -q --no-edit
run git log --oneline --graph -4

Real output:

text
$ git merge discount
Auto-merging price.txt
CONFLICT (content): Merge conflict in price.txt
Automatic merge failed; fix conflicts and then commit the result.
(exit 1)
$ git ls-files --stage price.txt
100644 f7e1494035a722d5e044a106161c5d4d08fa9123 1	price.txt
100644 fe3c94a0ef4ff758c433a9a0c2f139911d560f14 2	price.txt
100644 74ffb191500365a52e334bcf0f066434ce26007b 3	price.txt
--- zdiff3 conflict style also shows the merge base inside the markers
<<<<<<< HEAD
price = 110  # VAT included
||||||| 0c18e33
price = 100
=======
price = 90  # 10% discount
>>>>>>> discount
--- rerere: record a resolution once, replay it automatically next time
$ git merge discount
Auto-merging price.txt
CONFLICT (content): Merge conflict in price.txt
Recorded preimage for 'price.txt'
Recorded resolution for 'price.txt'.
--- throw the merge away and do it again: rerere resolves the file by itself
CONFLICT (content): Merge conflict in price.txt
Resolved 'price.txt' using previous resolution.
$ cat price.txt
price = 99  # VAT included, 10% discount
$ git diff --name-only --diff-filter=U
price.txt

Note the last line: rerere fixed the content but left the path unmerged until you git add it, which is your chance to review.

Real scenario: two developers bump the same dependency in composer.lock or go.sum: do not hand-merge lock files; take one side and regenerate (composer update --lock, go mod tidy). A long-lived release branch is merged into main weekly with the same conflicts each time: rerere. A conflict in a migration timestamp means two branches added migrations in parallel: keep both files, check the order. A conflict in generated code (protobuf, go generate output): regenerate rather than edit.

Conflict type (ort message)CauseTypical resolution
CONFLICT (content)Same lines changed on both sidesEdit, git add
CONFLICT (modify/delete)One side edited, the other deletedgit rm or git add the kept version
CONFLICT (rename/delete), (rename/rename)Renamed on one side, deleted or renamed differently on the otherDecide the final path
CONFLICT (add/add)Both added a file with the same pathMerge contents or rename one
Binary file conflictNo textual merge possiblegit checkout --ours/--theirs <path>
Lock filesGenerated contentTake one side, regenerate

Rebase: replay, interactive rebase, --onto, --update-refs, fixup and autosquash Must-know ​

In plain words: rebase takes your commits, sets them aside, moves your branch to a new starting point, and re-applies them one by one. The result looks as if you had started your work later. Interactive rebase lets you edit that list first: reorder, squash, reword, drop.

Common misunderstanding: "Rebase moves my commits." It cannot: commits are immutable and include their parent's id. Rebase creates new commits with the same changes and new ids (8af4bf2 became 054170e in the lab) and moves the branch to them. The old commits still exist until garbage collection, reachable from the reflog and from anyone else's clone.

Definition: git rebase <upstream> replays upstream..HEAD onto upstream. git rebase --onto <newbase> <upstream> <branch> replays only the commits after <upstream> onto <newbase> (move a branch that was cut from another feature branch). -i opens the todo list (pick, reword, edit, squash, fixup, drop, exec, break, label/reset/merge for --rebase-merges); GIT_SEQUENCE_EDITOR can script it. --autosquash (or rebase.autoSquash) reorders fixup!/squash!/amend! commits under their targets. --update-refs (Git 2.38+, rebase.updateRefs) will "automatically force-update any branches that point to commits that are being rebased", so a stack of branches moves together. --exec "make test" runs a command after each replayed commit. git pull --rebase (or pull.rebase = true) is fetch + rebase instead of fetch + merge.

1  before:  main  B---M            feature  B---C---D
2  git switch feature; git rebase main
3  Git:     set aside C, D; move feature to M; apply C -> C' (new id); apply D -> D'
4  after:   main  B---M            feature  B---M---C'---D'
5  git switch main; git merge --ff-only feature     -> straight line, no merge commit
6  C and D still exist (reflog, other clones) until gc
Same work, four history shapes (arrows point from a commit to its parent)StartBMCDmainfeatureThree-way merge (git merge, ort)BMCDXX has two parents; C and D keep their ids.Rebase (git rebase main, then fast-forward)BMC'D'CDC' and D' are NEW commits (new ids, new committer date);C and D still exist, reachable only from the reflog and fromanyone else's clone: never rebase what others have built on.Squash merge (GitHub/GitLab button)BMSS = C + D as one commit with ONE parent.The feature branch is not an ancestor of main,so git branch --merged does not list it and abranch stacked on D must be rebased with --onto.Fast-forward (no M on main): git merge only moves the main ref to D; --no-ff forces a merge commit like X anyway.

Real output (the script is the one imported in Merging):

text
--- rebase: replay feature on top of main; new commit ids, linear history
$ git rev-parse --short HEAD
8af4bf2
$ git rebase main
Successfully rebased and updated refs/heads/feature.
$ git rev-parse --short HEAD
054170e
* 054170e feat(cart): totals
* 0ca7a56 feat(cart): add cart
* 39d5fd8 docs: add docs
--- --onto: move only the commits after a base onto a new parent
$ git rebase --onto main feature-a feature-b
* 37f24dc feat: B1 (only this should move)
* e9856ed chore: main moves
* b72d1f2 chore: init
--- --update-refs: rebase a stack of branches and move every branch in it
$ git rebase --update-refs main
Successfully rebased and updated refs/heads/part2.
Updated the following refs with --update-refs:
	refs/heads/part1
* fa15fe9 (HEAD -> part2) feat: part 2
* d1e2b15 (part1) feat: part 1
* b1eab62 (main) chore: main moves
--- fixup + autosquash: a review fix folded into the commit it fixes
60f1c7b fixup! feat: add Total
d1bb748 feat: add UI
c6d5beb feat: add Total
$ git rebase -q -i --autosquash HEAD~3
794fd77 feat: add UI
ab81325 feat: add Total
--- interactive rebase: the todo list is a script; here an editor drops one commit
pick ab81325 # feat: add Total
pick 794fd77 # feat: add UI
$ git log --oneline
ab81325 feat: add Total
a6399e0 chore: init

Two details from the run: the todo list in Git 2.54 writes pick <id> # <subject> (older versions omit the #, so a sequence-editor script must match both), and the rebased stack shows part1 moved without being checked out.

Real scenario: before opening a pull request, git rebase -i origin/main squashes "wip" commits into reviewable steps. A team on GitHub "Rebase and merge" gets a linear main with every commit kept. A feature cut from a colleague's unmerged branch is moved onto main with --onto after their branch is squash-merged. A stacked series (part1 → part2 → part3) is kept in sync with main with one git rebase --update-refs main from the top branch.

Todo commandEffectTypical use
pickUse the commitDefault
rewordUse it, edit the messageFix a subject
editStop after applying itSplit a commit (git reset HEAD~, add in parts)
squashMeld into the previous, combine messagesCombine steps
fixup (-C keeps this message)Meld into the previous, keep the previous messageReview fixes
dropRemove the commitDebug commits
exec <cmd>Run a shell commandexec go test ./... after each step
update-ref <ref>Move a branch to this pointWritten by --update-refs

Rewriting shared history and --force-with-lease Must-know ​

In plain words: pushing normally only works if the remote branch is an ancestor of what you push (you only add commits). After a rebase or amend you are replacing commits, so you must force. --force replaces whatever is there, including a teammate's commits you never saw. --force-with-lease replaces it only if it is still what you last fetched.

Common misunderstanding: "--force-with-lease always protects me." Its default lease is your remote-tracking branch, and any git fetch updates it. Fetch in the background (an IDE does) and the lease matches again, without you ever having looked at the new commits. --force-if-includes (Git 2.30+) closes that gap: it forces only "if the tip of the remote-tracking ref has been integrated locally".

Definition: from git push: the option "overrides this restriction if the current value of the remote ref is the expected value. git push fails otherwise"; "It is like taking a 'lease' on the ref without explicitly locking it". Forms: --force-with-lease (all refs being pushed, expected = remote-tracking value), --force-with-lease=<ref>, --force-with-lease=<ref>:<expect> (explicit id; the only form the manual calls non-experimental). push.useForceIfIncludes = true adds --force-if-includes to every lease push. Servers reject forced pushes to protected branches regardless (non_fast_forward rule on GitHub, "Allowed to force push" off on GitLab).

1  alice: push "feat: one" (677af82)          origin/main = 677af82 on alice's machine
2  bob:   push "feat: bob adds g" (7ce91f0)   remote main = 7ce91f0
3  alice: amend -> 0bc75b6; push --force-with-lease     -> rejected (stale info): lease 677af82 != 7ce91f0
4  alice: git fetch                            origin/main = 7ce91f0: the lease now matches
5  alice: push --force-with-lease --dry-run    -> "+ 7ce91f0...0bc75b6 (forced update)": bob's commit would be lost
6  alice: push --force-with-lease --force-if-includes   -> rejected: remote tip not integrated
7  alice: reset to origin/main, commit the fix on top, normal push   -> ok

Real output (end of runs/03-merge-vs-rebase.txt):

text
$ git push --force-with-lease origin main
To $W/remote.git
 ! [rejected]        main -> main (stale info)
error: failed to push some refs to '$W/remote.git'
(exit 1)
$ git fetch -q origin
$ git push --dry-run --force-with-lease origin main
To $W/remote.git
 + 7ce91f0...0bc75b6 main -> main (forced update)
$ git push --force-with-lease --force-if-includes origin main
 ! [rejected]        main -> main (remote ref updated since checkout)
(exit 1)
--- the safe path: do not rewrite what others have; land the fix as a new commit
$ git reset -q origin/main
$ git status --short
 M f
 D g
$ git restore g
$ git commit -q -am 'fix: correct f'
* 52c1fad fix: correct f
* 7ce91f0 feat: bob adds g
* 677af82 feat: one
$ git push origin main
   7ce91f0..52c1fad  main -> main

$W is the scratch directory; the scripts print it that way instead of the host path.

Real scenario: your own feature branch after rebase -i: git push --force-with-lease --force-if-includes is the normal, safe habit. main: never; branch protection should make it impossible. A branch two people share: agree that only one rebases, or merge instead. A leaked secret: the one case where rewriting main is right, coordinated with everyone (Security).

Push formOverwrites a commit you never saw?Use
git pushNever (fast-forward only)Default
git push --forceYesAlmost never
git push --force-with-leaseYes, if a fetch already updated your remote-tracking refOwn branches, with care
--force-with-lease --force-if-includesNo: also requires the fetched tip to be in your historyOwn branches (alias pushf in config/gitconfig.example)
--force-with-lease=main:<id>No: you name the exact expected idScripts and bots

Branching strategies: trunk-based development, GitHub Flow, GitLab Flow, git-flow Must-know ​

In plain words: a branching strategy is a team agreement about how long branches live and where releases come from. The shorter branches live, the smaller and safer each merge is; the more long-lived branches you keep, the more you can support several released versions at once, at the cost of merging everything twice.

Common misunderstanding: "Trunk-based development means everybody commits straight to main without review." Martin Fowler's description: it "focuses on doing all work on Mainline ... and thus avoiding any kind of long-lived branches. Smaller teams commit directly to mainline using Mainline Integration, larger teams may use short-lived Feature Branching where 'short' means no more than a couple of days". Short-lived pull requests with required checks are trunk-based. What it forbids is the three-week branch.

Definition:

  • Trunk-based development: one long-lived branch (main, "trunk"); branches last hours to a couple of days; incomplete features merge behind feature flags ("Feature Toggles (often also refered to as Feature Flags) are a powerful technique, allowing teams to modify system behavior without changing code", Fowler); releases are tags on main or short release branches cut from it for stabilisation and hotfix cherry-picks. Pairs with continuous integration: "Developers do mainline integration as soon as they have a healthy commit they can share, usually less than a day's work" (Fowler, Patterns for Managing Source Code Branches).
  • GitHub Flow: main is always deployable; a branch and a pull request per change; review, checks, merge, deploy from main. Effectively trunk-based with mandatory PRs.
  • GitLab Flow: feature branches into main, plus downstream branches: environment branches (pre-production, production) or release branches (2-3-stable) that receive changes only from main (the rule usually called upstream first; the phrase is not on the saved GitLab page). GitLab's page: "GitLab Flow works with the main branch right away. GitLab Flow incorporates a pre-production branch to make bug fixes before merging changes back to main before going to production."
  • git-flow (2010): main holds released versions, develop is the integration branch, feature/* from develop, release/* to stabilise, hotfix/* from main merged into both. Its author's 2020 note: "If your team is doing continuous delivery of software, I would suggest to adopt a much simpler workflow (like GitHub flow) instead of trying to shoehorn git-flow into your team"; it remains reasonable for "software that is explicitly versioned" with several versions in the wild.
  • Release branch: release/1.4 cut from main when you must stabilise or support a version while main moves on; fixes land on main first and are cherry-picked (git cherry-pick -x) to the release branch.
Branching strategies: how long branches live and where releases come fromTrunk-based / GitHub FlowmainPR, hours to 2 daysv1.4.0Unfinished work merges dark behind feature flags;every merge is deployable; release = tag on main.GitLab Flow (environment branches)mainpreprodChanges flow downstream only (upstream first).git-flow (2010): long-lived develop, release and hotfix branchesmaindevelopfeature/* (days to weeks)release/1.4hotfix/*Every release and hotfix is merged twice; long branches mean big merges.
1  09:00  dev A: git switch -c checkout-coupons origin/main
2  11:30  dev A: PR #812 (120 lines, flag "coupons" off by default); CI green; review
3  12:10  merged to main (squash); deploy pipeline ships main to production, flag still off
4  15:00  dev A: PR #815 enables the flag for 5 % of users (config, not code)
5  next   week: flag at 100 %; PR #840 deletes the flag and the old code path

Real scenario: a SaaS team deploying several times a day uses trunk-based development with feature flags (LaunchDarkly, Unleash, a config table) and GitHub Flow PRs. A mobile app that must keep 3.2 alive while 3.3 is in store review uses release branches. An on-premise product with supported LTS versions keeps release/2024.1, release/2025.1 (git-flow-like, or GitLab Flow release branches). A platform team using GitOps treats environment folders or branches as the deploy target, which is GitLab Flow's environment-branch idea applied to manifests.

StrategyLong-lived branchesRelease fromBest forCost
Trunk-basedmain onlyTag on main (or short release branch)Continuous delivery, web servicesNeeds feature flags, fast CI, discipline
GitHub Flowmainmain after each mergeSmall and medium teams with PRsNo story for supporting old versions
GitLab Flow (environment)main, pre-production, productionThe environment branchTeams that promote through environmentsExtra merges; drift between branches
GitLab Flow (release)main, x-y-stableThe stable branchVersioned productsCherry-pick discipline
git-flowmain, develop (+ release/hotfix)main after release/*Explicitly versioned software, slow release trainsDouble merges, big integration events

Pull requests and merge requests Must-know ​

In plain words: Git itself has no "pull request". It is the hosting platform's review object: "please merge this branch into that one", with a diff, comments, checks and an approval state. GitHub, Gitea and Bitbucket call it a pull request; GitLab calls it a merge request.

Common misunderstanding: "Squash merge is just a tidier merge." It creates a new commit with one parent that is not related to your branch's commits. Your branch is never "merged" in Git's sense: git branch --merged main will not list it, and a branch stacked on it now contains commits that main has under a different id, so it must be rebased with --onto (or --update-refs from the top) after the squash.

Definition:

  • Merge methods (GitHub "Create a merge commit", "Squash and merge", "Rebase and merge"; GitLab "Merge commit", "Merge commit with semi-linear history", "Fast-forward merge", plus a "Squash commits" option). GitHub: "When you select the Squash and merge option on a pull request, the pull request's commits are squashed into a single commit ... Pull requests with squashed commits are merged using the fast-forward option."
  • Protected branches / rulesets (GitHub) and protected branches (GitLab): forbid direct pushes, force pushes and deletion; require pull requests, approvals, code-owner review, linear history, signed commits and required checks. GitHub: "Required status checks must have a successful, skipped, or neutral status before collaborators can make changes to a protected branch."
  • CODEOWNERS: a file mapping path patterns to users or teams who are requested (and, with the rule on, required) as reviewers. GitHub looks in .github/, the root, then docs/; GitLab in the root, docs/, then .gitlab/; in both "the last matching pattern takes the most precedence" (GitHub) / "the last matching entry is used" (GitLab).
  • Stacked PRs: a series of small dependent PRs (part1 ← part2 ← part3), each based on the previous branch, reviewed in order; tooling: git rebase --update-refs, Graphite, ghstack, git-branchless, GitHub's base-branch retargeting when a parent merges.
  • Review etiquette (team rules, not Git): PRs under about 400 changed lines; one concern per PR; description says why and how to test; reviewers comment on behaviour and risk before style; authors answer with fixup commits, then autosquash before merge; nobody approves what they did not read.

Branch protection as code, from the snippet directory:

json
{
  "name": "protect-main",
  "target": "branch",
  "enforcement": "active",
  "conditions": {
    "ref_name": { "include": ["~DEFAULT_BRANCH", "refs/heads/release/*"], "exclude": [] }
  },
  "bypass_actors": [],
  "rules": [
    { "type": "deletion" },
    { "type": "non_fast_forward" },
    { "type": "required_linear_history" },
    { "type": "required_signatures" },
    {
      "type": "pull_request",
      "parameters": {
        "required_approving_review_count": 1,
        "dismiss_stale_reviews_on_push": true,
        "require_code_owner_review": true,
        "require_last_push_approval": true,
        "required_review_thread_resolution": true
      }
    },
    {
      "type": "required_status_checks",
      "parameters": {
        "strict_required_status_checks_policy": true,
        "required_status_checks": [
          { "context": "test" },
          { "context": "lint" },
          { "context": "commitlint" }
        ]
      }
    }
  ]
}
text
# CODEOWNERS (GitHub: .github/CODEOWNERS, CODEOWNERS or docs/CODEOWNERS;
# GitLab: the same three locations). The LAST matching pattern wins, so put
# the broad rules first and the specific ones after them.

# Default owners for everything
*                       @acme/backend

# Go services and shared libraries
/services/billing/      @acme/payments
/services/checkout/     @acme/checkout
/libs/money/            @acme/payments @acme/architects

# Laravel app: migrations need a database reviewer as well
/app/                   @acme/laravel
/database/migrations/   @acme/laravel @acme/dba

# Platform: CI, deploy and infrastructure changes
/.github/workflows/     @acme/platform
/deploy/                @acme/platform
*.tf                    @acme/platform

# Lock files: no owner (an empty owner list removes ownership for the pattern)
/composer.lock
/go.sum
bash
#!/usr/bin/env bash
# Apply branch protection as code. Expected, not run: needs a token with admin
# rights on the repository (GitHub: fine-grained PAT with "Administration: write",
# GitLab: Maintainer role and an api-scoped token).
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)

# GitHub: create a repository ruleset from the JSON file (REST API via gh).
gh api --method POST \
  -H "Accept: application/vnd.github+json" \
  "repos/acme/shop/rulesets" \
  --input "$here/github-ruleset.json"

# GitHub: also allow only squash merges and delete head branches after merge.
gh api --method PATCH "repos/acme/shop" \
  -F allow_squash_merge=true -F allow_merge_commit=false -F allow_rebase_merge=false \
  -F delete_branch_on_merge=true

# GitLab: protect main (push: no one, merge: Maintainers) and require code owner approval
# (code_owner_approval_required is GitLab Premium and Ultimate only).
# Access levels: 0 = No access, 30 = Developer, 40 = Maintainer.
curl --fail --silent --show-error --request POST \
  --header "PRIVATE-TOKEN: ${GITLAB_TOKEN:?set GITLAB_TOKEN}" \
  "https://gitlab.example.com/api/v4/projects/acme%2Fshop/protected_branches?name=main&push_access_level=0&merge_access_level=40&code_owner_approval_required=true"

The required checks above are produced by a workflow whose job names match the contexts (full pipeline mechanics in CI/CD Pipelines):

yaml
# .github/workflows/pr-checks.yml: the checks that the ruleset marks as required.
# The job names (test, lint, commitlint) are the status-check contexts.
name: pr-checks
on:
  pull_request:
    branches: [main]
permissions:
  contents: read
jobs:
  commitlint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0 # full history: we lint every commit in the PR
      - uses: actions/setup-go@v7
        with:
          go-version: "1.24"
      - name: Lint every commit message in the pull request
        env:
          BASE: ${{ github.event.pull_request.base.sha }}
          HEAD: ${{ github.event.pull_request.head.sha }}
        run: |
          go build -o /tmp/commitlint ./cmd/commitlint
          for c in $(git rev-list "$BASE..$HEAD"); do
            git log -1 --format=%B "$c" | /tmp/commitlint || { echo "commit $c"; exit 1; }
          done
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - run: test -z "$(gofmt -l .)"
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-go@v7
        with:
          go-version: "1.24"
      - run: go test -race ./...
1  dev:      git push -u origin coupons; open PR (base main)
2  GitHub:   CODEOWNERS -> request @acme/checkout; ruleset -> needs 1 approval + test, lint, commitlint
3  CI:       three jobs report status on the head commit
4  reviewer: requests changes; dev pushes "fixup! ..." commits; dismiss_stale_reviews_on_push resets approval
5  dev:      git rebase -i --autosquash origin/main; git push --force-with-lease --force-if-includes
6  reviewer: approves; checks green; "Squash and merge" -> one commit on main, branch deleted

Real scenario: a payments directory needs two approvals including the payments team: CODEOWNERS plus "Require review from Code Owners". A bot opens dependency PRs (Dependabot, Renovate) that auto-merge when checks pass. A 3,000-line feature is split into four stacked PRs of 300-800 lines that each get a real review. A merge queue (GitHub merge queue, GitLab merge trains) tests each PR on top of the PRs ahead of it so main stays green under heavy merge traffic.

Merge methodGitHub nameGitLab namemain historyKeeps branch commitsSigned?
Merge commitCreate a merge commitMerge commitGraph with merge commitsYesMerge commit signed by the platform
SquashSquash and mergeSquash commits (option)One commit per PR, linearNoPlatform-signed commit
RebaseRebase and mergeFast-forward merge (requires rebased MR)Linear, all commitsRe-created (new ids on GitHub)GitHub rebase merge rewrites commits; check your signing rule
Semi-linear(rebase + merge commit by hand)Merge commit with semi-linear historyMerge commits over a rebased branchYesMerge commit

Remotes and hosting: origin, upstream, SSH vs HTTPS, tokens, credential helper Must-know ​

In plain words: a remote is a named URL of another copy of the repository. origin is the one you cloned from; upstream is, by convention, the original project when origin is your fork. Fetch downloads their objects and updates origin/* refs; push uploads yours and asks them to move a branch.

Common misunderstanding: "git pull updates my branch from the server." git pull is git fetch followed by a merge (or rebase, with pull.rebase) of the configured upstream into the current branch. The server side never changes on pull; and your origin/main is only as fresh as your last fetch.

Definition: git remote add upstream <url>, git remote -v, git fetch --prune, git push -u origin feature (sets branch.feature.remote and .merge, i.e. the branch's upstream; push.autoSetupRemote = true does it automatically). Two transports matter: SSH (git@github.com:acme/shop.git, key-based, port 22 or ssh.github.com:443) and HTTPS (https://github.com/acme/shop.git, works through proxies; GitHub: "Password-based authentication for Git has been removed", enter a personal access token when prompted or use a credential helper). GitHub recommends fine-grained personal access tokens over classic ones. A credential helper (credential.helper = osxkeychain, manager (Git Credential Manager), libsecret, cache --timeout=3600, store (plain text, avoid)) stores and supplies HTTPS credentials. Hosting choices: GitHub, GitLab (SaaS or self-managed), Bitbucket, Gitea/Forgejo (small self-hosted), or a bare repository over SSH (git init --bare, as the lab's remote.git).

1  git clone git@github.com:me/shop.git          origin   = my fork
2  git remote add upstream git@github.com:acme/shop.git
3  git fetch upstream                             upstream/main updated, nothing else
4  git rebase upstream/main                       my branch replayed on the project's latest
5  git push --force-with-lease origin feature     my fork's branch; the PR from fork to acme updates

Real scenario: a corporate proxy blocks port 22: use HTTPS with a credential helper or SSH over ssh.github.com:443. CI clones with a short-lived token (GitHub Actions GITHUB_TOKEN, GitLab CI_JOB_TOKEN) over HTTPS instead of a long-lived deploy key. An open-source contributor keeps origin (fork) and upstream (project). A mirror for a disaster-recovery site: git clone --mirror plus a scheduled git remote update.

SSHHTTPS
Authenticates withKey pair (~/.ssh/id_ed25519), agentToken as password, via credential helper
Firewalls / proxiesPort 22 often blocked; GitHub offers 443Works almost everywhere
Scope controlPer key: full account (user key) or one repository (deploy key)Fine-grained PAT: repositories and permissions, expiry
Same key can sign commitsYes (gpg.format=ssh)n/a
CI typicalDeploy key for one repositoryJob token (GITHUB_TOKEN, CI_JOB_TOKEN)

Tags and releases: annotated vs lightweight, semver, git describe Must-know ​

In plain words: a tag is a name for one commit that, unlike a branch, never moves. A lightweight tag is just that name; an annotated tag is a real object with who, when and why, and can be signed. Releases should use annotated (or signed) tags.

Common misunderstanding: "Tags are pushed with my branch." git push pushes no tags unless you name them, use --tags (all) or --follow-tags (annotated tags reachable from the pushed commits; push.followTags = true). And a tag that was moved after people fetched it stays at the old commit on their side; never move release tags.

Definition: git tag v1.2.3 (lightweight: a ref straight to the commit), git tag -a v1.2.3 -m msg (annotated: a tag object), git tag -s (signed annotated). Semantic Versioning 2.0.0: "MAJOR version when you make incompatible API changes", "MINOR version when you add functionality in a backward compatible manner", "PATCH version when you make backward compatible bug fixes"; pre-releases (1.3.0-rc.1) sort before the release. git describe names a commit relative to the nearest annotated tag: v1.2.3-2-g5f0f15b = 2 commits after v1.2.3, at abbreviated id 5f0f15b (g for git); --tags also considers lightweight tags; --dirty appends -dirty; --always falls back to the id. git tag --sort=-v:refname sorts by version; versionsort.suffix=-rc puts v1.3.0-rc.1 before v1.3.0.

bash
#!/usr/bin/env bash
# Tags and releases: annotated vs lightweight, semver, git describe,
# Go pseudo-versions from commits, and git maintenance on one repository.
source "$(dirname "$0")/lib.sh"
GO_DIR=$(cd "$(dirname "$0")/../go" && pwd -P)
fresh release
commit_file go.mod 'module example.com/shop' "chore: init module"

say "no tag yet: describe fails, Go would use a v0.0.0 pseudo-version"
try git describe
mkdir -p "$W/home/bin"
GOCACHE="$W/gocache" GOPATH="$W/gopath" go build -C "$GO_DIR" -buildvcs=false -o "$W/home/bin/pseudoversion" ./cmd/pseudoversion
run "$W/home/bin/pseudoversion"
run git log -1 --format='%H %ct %cd' --date=format-local:%Y%m%d%H%M%S

say "annotated release tag (a tag object with tagger, date, message)"
tick
run git tag -a v1.2.3 -m "v1.2.3: cart totals"
run git describe
run "$W/home/bin/pseudoversion"

say "two more commits: describe = nearest tag + commits since + g<abbrev hash>"
commit_file cart.go 'package cart' "feat(cart): add cart"
commit_file cart.go 'package cart // totals' "fix(cart): rounding"
run git describe
run git describe --dirty --always
echo 'edit' >> cart.go
run git describe --dirty
git checkout -q cart.go
run "$W/home/bin/pseudoversion"

say "a lightweight tag is ignored by plain describe; --tags includes it"
run git tag build-42
run git describe
run git describe --tags

say "pre-release tag and the pseudo-version form for it"
tick
run git tag -a v1.3.0-rc.1 -m "release candidate"
commit_file cart.go 'package cart // totals v2' "feat(cart): coupons"
run git describe
run "$W/home/bin/pseudoversion"

say "list release tags in semver order, newest first"
tick; git tag -a v1.10.0 -m "v1.10.0"
tick; git tag -a v1.9.0 -m "v1.9.0" HEAD~1
tick; git tag -a v1.3.0 -m "v1.3.0" HEAD
run git tag --list 'v*' --sort=-v:refname
run git -c versionsort.suffix=-rc tag --list 'v*' --sort=-v:refname

say "git maintenance run (foreground; 'start' would register a scheduler, not done here)"
run git maintenance run --task=commit-graph --task=pack-refs --task=gc
run git count-objects -v
run ls .git/objects/info
text
$ git describe
fatal: No names found, cannot describe anything.
(exit 128)
$ $W/home/bin/pseudoversion
v0.0.0-20260101100200-cb0c4a0a627a
$ git tag -a v1.2.3 -m 'v1.2.3: cart totals'
$ git describe
v1.2.3
--- two more commits: describe = nearest tag + commits since + g<abbrev hash>
$ git describe
v1.2.3-2-g5f0f15b
$ git describe --dirty
v1.2.3-2-g5f0f15b-dirty
$ $W/home/bin/pseudoversion
v1.2.4-0.20260101100500-5f0f15b598e2
$ git tag build-42
$ git describe
v1.2.3-2-g5f0f15b
$ git describe --tags
build-42
$ git tag --list 'v*' --sort=-v:refname
v1.10.0
v1.9.0
v1.3.0-rc.1
v1.3.0
v1.2.3
$ git -c versionsort.suffix=-rc tag --list 'v*' --sort=-v:refname
v1.10.0
v1.9.0
v1.3.0
v1.3.0-rc.1
v1.2.3

Without versionsort.suffix Git sorts v1.3.0-rc.1 after (newer than) v1.3.0, which is the opposite of semver; a release script that picks "the newest tag" must set it. pseudoversion is the chapter's Go program (Go) that computes what the go command would call this commit.

1  main: ... A (v1.2.3) --- B --- C                       describe C  -> v1.2.3-2-g<C>
2  CI on tag push v1.3.0 (annotated, signed)              build: -ldflags "-X main.version=$(git describe --tags)"
3  GitHub/GitLab release created from the tag, changelog from Conventional Commits since v1.2.3
4  Go consumers: go get example.com/shop@v1.3.0

Real scenario: a binary prints git describe --tags --dirty as its version, so a support ticket names the exact commit. A Go library is consumed by tag (go get example.com/lib@v1.4.0) and the proxy caches it forever, so a re-tagged version is a broken checksum for everyone. A Helm chart version follows semver separately from the app version. Deployment strategies promote one immutable tag through environments.

Lightweight tagAnnotated tagSigned tag
ObjectNone (ref only)Tag objectTag object + signature
Tagger, date, messageNoYesYes
git describe (no --tags)IgnoredUsedUsed
--follow-tags pushes itNoYesYes
UseLocal bookmarks, CI build markersReleasesReleases where provenance matters

Undoing things: restore, reset, revert, reflog recovery Must-know ​

In plain words: pick the undo by asking two questions. Is the thing committed? Has anyone else got it? Uncommitted edits are undone with git restore; local commits with git reset; shared commits with git revert, which adds a new commit that cancels the old one. And almost nothing that was ever committed is lost for 30 days: the reflog remembers.

Common misunderstanding: "git reset --hard deletes commits." It moves the branch pointer (and resets index and working tree). The commits it moved away from are still in the object store and in the reflog. What --hard really destroys is uncommitted work in the working tree, which was never stored anywhere.

Definition: git reset [--soft | --mixed | --hard] <commit> moves the current branch to <commit>; --soft leaves index and working tree, --mixed (default) resets the index, --hard resets index and working tree (also --keep, --merge). ORIG_HEAD holds the previous tip after reset, merge and rebase. git restore <path> (working tree from index), git restore --staged <path> (index from HEAD), git restore --source=<commit> <path> (from any commit). git revert <commit> creates the inverse commit ("This reverts commit ..."); -m 1 to revert a merge relative to its first parent. Recovery: git reflog (or git reflog show <branch>) lists old positions; git branch rescue HEAD@{1}; git fsck --lost-found finds dangling commits even after the reflog entries expired, until git gc --prune removes them.

bash
#!/usr/bin/env bash
# Undoing: reset --soft / --mixed / --hard, revert, and getting "lost" work back from the reflog.
source "$(dirname "$0")/lib.sh"
fresh undo
commit_file a.txt 'one' "feat: one"
commit_file a.txt 'two' "feat: two"
commit_file a.txt 'three' "feat: three"
run git log --oneline

say "reset --soft HEAD~1: move the branch only; index and working tree keep 'three'"
run git reset --soft HEAD~1
run git status --short
run git log --oneline -1
git reset -q --hard ORIG_HEAD

say "reset --mixed HEAD~1 (the default): move branch and index; working tree keeps 'three'"
run git reset HEAD~1
run git status --short
git reset -q --hard ORIG_HEAD

say "reset --hard HEAD~1: move branch, index and working tree; uncommitted work is gone"
echo 'uncommitted' >> a.txt
run git reset --hard HEAD~1
run cat a.txt
run git status --short

say "the commit 'three' is unreachable from any branch, but the reflog still has it"
run git reflog -4
run git branch rescue 'HEAD@{1}'
run git log --oneline rescue -1
run git reset -q --hard rescue
run git branch -q -D rescue

say "a deleted branch is also recoverable: its last tip is in HEAD's reflog"
git switch -q -c experiment
commit_file b.txt 'exp' "feat: experiment"
git switch -q main
run git branch -D experiment
run git reflog -3
run git switch -c experiment 'HEAD@{1}'
git switch -q main

say "revert: undo a commit that is already shared, by adding its inverse"
commit_file flags.txt 'checkout_v2=on' "feat: enable checkout v2"
commit_file a.txt 'four' "feat: four"
tick
run git revert --no-edit HEAD~1
run git log --oneline -4
run git show --stat --format=%B HEAD

say "git fsck finds commits that no ref and no reflog entry reaches (dangling)"
git reflog expire --expire-unreachable=now --all
git switch -q --detach HEAD
commit_file c.txt 'orphan' "feat: orphaned work"
orphan=$(git rev-parse --short HEAD)
git switch -q main
git reflog expire --expire-unreachable=now --all
run sh -c 'git fsck --no-reflogs --lost-found 2>/dev/null | head -3'
echo "(the orphan was $orphan)"
text
--- reset --soft HEAD~1: move the branch only; index and working tree keep 'three'
$ git status --short
M  a.txt
--- reset --mixed HEAD~1 (the default): move branch and index; working tree keeps 'three'
Unstaged changes after reset:
M	a.txt
--- reset --hard HEAD~1: move branch, index and working tree; uncommitted work is gone
HEAD is now at 5e32f75 feat: two
$ git reflog -4
5e32f75 HEAD@{0}: reset: moving to HEAD~1
d018ac3 HEAD@{1}: reset: moving to ORIG_HEAD
...
$ git branch rescue 'HEAD@{1}'
$ git log --oneline rescue -1
d018ac3 feat: three
--- a deleted branch is also recoverable: its last tip is in HEAD's reflog
Deleted branch experiment (was 0fc62c7).
0fc62c7 HEAD@{1}: commit: feat: experiment
$ git switch -c experiment 'HEAD@{1}'
Switched to a new branch 'experiment'
--- revert: undo a commit that is already shared, by adding its inverse
[main 5b4c92d] Revert "feat: enable checkout v2"
This reverts commit 54fbafa92fd7f7f8949d896e7238c1c1b305fe33.
--- git fsck finds commits that no ref and no reflog entry reaches (dangling)
dangling commit 82eb19f95b68d3c22078bd8b11cefe538acd9b10
(the orphan was 82eb19f)
1  09:00  commits A, B, C on main (not pushed)
2  09:05  git reset --hard HEAD~2         main = A; working tree = A
3  09:06  "where is C?"  git reflog       C is HEAD@{1}
4  09:07  git reset --hard HEAD@{1}       main = C again
5  ---- if C had been pushed and others pulled: never reset; git revert C (new commit C^-1)

Real scenario: a broken release on main at 18:00: git revert <merge> -m 1 and push, then fix forward tomorrow (re-reverting the revert later to re-apply). "I committed to main instead of my branch": git branch feature; git reset --hard origin/main; git switch feature. "I squashed too much in rebase": git reset --hard ORIG_HEAD. A colleague force-pushed over your work on a shared branch: your local reflog of origin/main still has the old tip (git reflog show origin/main).

CommandMoves branchIndexWorking treeSafe after push
git restore <path>NoNoReset from indexn/a (uncommitted)
git restore --staged <path>NoReset from HEADNon/a
git reset --soft <c>YesNoNoNo
git reset --mixed <c> (default)YesResetNoNo
git reset --hard <c>YesResetReset (uncommitted work lost)No
git revert <c>Adds a commitUpdatedUpdatedYes
git commit --amendReplaces the tipn/an/aNo

Finding the commit that did it: git bisect, git blame -w -C, git log -S Important ​

In plain words: bisect is binary search over history: tell Git one good and one bad commit and it checks out the middle until it finds the first bad one, in log2(n) steps; with git bisect run a script does the testing. Blame tells you who last touched each line; the pickaxe (log -S) tells you which commit added or removed a string.

Common misunderstanding: "git blame shows who wrote this code." It shows the last commit that changed each line, which is often a reformat or a move. -w ignores whitespace changes and -C (repeated up to three times) follows code moved or copied from other files, so the line is attributed to where it was really written. --ignore-revs-file .git-blame-ignore-revs (honoured by GitHub's blame view) skips listed mass-reformat commits.

Definition: git bisect start <bad> <good>, then good/bad/skip, or git bisect run <cmd> where the command exits 0 = good, 1-127 except 125 = bad, 125 = skip; git bisect log, git bisect reset. git blame -w -C -C -C <file>; -L 10,20 limits lines. Pickaxe: git log -S<string> lists commits where the number of occurrences of the string changed (added or removed); -G<regex> lists commits whose diff has an added or removed line matching the regex (also lines that merely moved); --pickaxe-regex makes -S take a regex. git log -L :funcName:file traces one function.

bash
#!/usr/bin/env bash
# Finding the commit that did it: bisect run, blame -w -C, log -S (pickaxe) and -G.
source "$(dirname "$0")/lib.sh"
fresh bisect
commit_file total.sh 'echo $((2 + 2))' "feat: total"
for i in 1 2 3 4 5; do commit_file "notes$i.txt" "note $i" "docs: note $i"; done
commit_file total.sh 'echo $((2 + 3))' "refactor: tidy total"
for i in 6 7 8 9; do commit_file "notes$i.txt" "note $i" "docs: note $i"; done
run git log --oneline

say "bisect run: the test exits 0 for good, 1 for bad, 125 for skip"
printf '#!/bin/sh\n[ "$(sh total.sh)" = 4 ]\n' > "$W/home/check-total.sh"
chmod +x "$W/home/check-total.sh"
run git bisect start HEAD "HEAD~10"
git bisect run "$W/home/check-total.sh" > "$W/home/bisect.out" 2>&1
echo '$ git bisect run $W/home/check-total.sh   # output without the "running" lines'
grep -v '^running' "$W/home/bisect.out" | hide_work
run git bisect log
run git bisect reset

say "blame: who last touched each line; -w ignores whitespace, -C follows moved/copied code"
fresh blame
A='func applyDiscount(total int, percent int) int { return total - total*percent/100 }'
B='func calculateShipping(weightGrams int, zone string) int { return weightGrams / 100 * 3 }'
printf '%s\n%s\n' "$A" "$B" > a.go
git add a.go && tick && git commit -q -m "feat: discount and shipping"
printf '%s\n    %s\n' "$A" "$B" > a.go
git add a.go && tick && as_bob git commit -q -m "style: indent"
run git blame -s a.go
run git blame -s -w a.go
printf '%s\n' "$A" > a.go
printf '%s\n' "$B" > b.go
git add a.go b.go && tick && as_bob git commit -q -m "refactor: move b to b.go"
run git blame -s b.go
run git blame -s -C -C b.go
run git blame -s -w -C -C b.go

say "pickaxe: -S finds commits where the number of occurrences changed; -G matches the diff by regex"
fresh pickaxe
commit_file cfg.php "<?php return ['key' => 'sk_live_123'];" "feat: config"
commit_file cfg.php "<?php return ['key' => env('PAY_KEY')];" "fix: read key from env"
commit_file cfg.php "<?php return ['key' => env('PAY_KEY'), 'timeout' => 5];" "feat: timeout"
run git log --oneline -S sk_live_
run git log --oneline -G "env\\("
run git log --oneline -S "env('PAY_KEY')"
text
$ git bisect start HEAD HEAD~10
Bisecting: 4 revisions left to test after this (roughly 2 steps)
[d409833e6395c2b7c8affa046e0aa2b6dd63e972] docs: note 5
$ git bisect run $W/home/check-total.sh   # output without the "running" lines
Bisecting: 2 revisions left to test after this (roughly 1 step)
[e060dfb4e85b490ee9301bdb771d55b9d23f150d] docs: note 6
Bisecting: 0 revisions left to test after this (roughly 0 steps)
[2390d1f1f9e4621011141f280ac1f64b067eef8b] refactor: tidy total
2390d1f1f9e4621011141f280ac1f64b067eef8b is the first 'bad' commit
$ git blame -s a.go
^0884497 1) func applyDiscount(total int, percent int) int { return total - total*percent/100 }
082185c2 2)     func calculateShipping(weightGrams int, zone string) int { return weightGrams / 100 * 3 }
$ git blame -s -w a.go
^0884497 1) func applyDiscount(total int, percent int) int { return total - total*percent/100 }
^0884497 2)     func calculateShipping(weightGrams int, zone string) int { return weightGrams / 100 * 3 }
$ git blame -s b.go
be31b7f 1) func calculateShipping(weightGrams int, zone string) int { return weightGrams / 100 * 3 }
$ git blame -s -C -C b.go
be31b7f 1) func calculateShipping(weightGrams int, zone string) int { return weightGrams / 100 * 3 }
$ git blame -s -w -C -C b.go
^0884497 a.go 1) func calculateShipping(weightGrams int, zone string) int { return weightGrams / 100 * 3 }
$ git log --oneline -S sk_live_
52d0ce7 fix: read key from env
39ceee3 feat: config
$ git log --oneline -G 'env\('
a63fb8c feat: timeout
52d0ce7 fix: read key from env

The -C -C without -w result is worth remembering: the moved line also changed indentation, so copy detection alone did not match it; together -w -C found the original author. And -S sk_live_ found both the commit that added the key and the one that removed it, which is how you find out whether a secret was ever in history.

1  good: feat: total (7c87c74)          bad: HEAD (c66d565), 10 commits apart
2  step 1: test d409833 -> good         step 2: test e060dfb -> bad
3  step 3: test 2390d1f -> bad          -> first bad commit: 2390d1f "refactor: tidy total"

Real scenario: "p99 latency doubled sometime last month": bisect with a benchmark script that exits 1 above a threshold. "When did we stop validating this field?": git log -S'validateEmail'. "Who knows this payment code?": git blame -w -C -C plus git log --format='%an' -- path | sort | uniq -c. A flaky test: git bisect run with exit 125 on infrastructure failures.

ToolQuestionCostGotcha
git bisect runWhich commit introduced it?log2(n) builds/testsNeeds a reliable test; skip unbuildable commits with 125
git blame -w -C -CWho last changed this line, really?One fileDefault blame credits reformat/move commits
git log -SWhen did this string appear/disappear?Scans all diffsCounts occurrences; a moved line is not listed
git log -GWhich diffs touch lines matching this regex?Scans all diffsAlso lists moves and edits of matching lines
git log -LHistory of one function or line rangeOne fileNeeds a language-aware funcname pattern

Worktrees and stash Important ​

In plain words: git stash puts your unfinished changes in a drawer so the working tree is clean; git worktree gives you a second working directory for another branch, sharing the same repository, so you do not need a drawer at all.

Common misunderstanding: "git stash saves everything." By default it saves tracked modifications only; untracked files stay (and may conflict); use -u (--include-untracked) or -a for ignored files too. And a stash is a commit object referenced by refs/stash; git stash drop makes it unreachable, recoverable only with git fsck until gc.

Definition: git stash push -u -m msg, list, show -p stash@{0}, pop (apply and drop; keeps the entry if it conflicts), apply, branch <name>. git worktree add ../hotfix -b hotfix main creates a linked working tree with its own HEAD and index but the same objects and refs; git worktree list, remove, prune, lock. A branch can be checked out in only one worktree at a time.

bash
#!/usr/bin/env bash
# Two branches checked out at once (worktree) and parking work (stash).
source "$(dirname "$0")/lib.sh"
fresh wt
commit_file app.txt 'v1' "feat: v1"
git switch -q -c feature
commit_file app.txt 'v2 in progress' "wip: v2"
git switch -q main

say "worktree: a second working tree for a hotfix, sharing one object store"
run git worktree add -q -b hotfix ../wt-hotfix main
run git worktree list | hide_work
cd "$W/wt-hotfix" || exit 1
commit_file app.txt 'v1.0.1' "fix: hotfix"
cd "$W/wt" || exit 1
run git log --oneline hotfix -1
say "a branch can be checked out in only one worktree at a time"
try git switch hotfix | hide_work
run git worktree remove ../wt-hotfix
run git worktree list --porcelain | hide_work

say "stash: park uncommitted work, switch, come back"
echo 'half-done' >> app.txt
echo 'scratch' > new.txt
run git status --short
run git stash push -u -m "half-done app change"
run git status --short
run git stash list
run git stash show --include-untracked --stat 'stash@{0}'
run git stash pop
run git status --short
text
$ git worktree add -q -b hotfix ../wt-hotfix main
$ git worktree list
$W/wt        37587e5 [main]
$W/wt-hotfix 37587e5 [hotfix]
$ git switch hotfix
fatal: 'hotfix' is already used by worktree at '$W/wt-hotfix'
(exit 128)
$ git stash push -u -m 'half-done app change'
Saved working directory and index state On main: half-done app change
$ git stash show --include-untracked --stat 'stash@{0}'
 app.txt | 1 +
 new.txt | 1 +
$ git stash pop
Dropped refs/stash@{0} (bc3ea4dc6ea5e659f7cdac63c99251c8e34d7e2f)
1  14:00  working on feature (dirty tree, a dev server running from it)
2  14:05  pager: production bug  ->  git worktree add ../shop-hotfix -b hotfix origin/main
3  14:30  fix, test, push, PR from ../shop-hotfix; the feature tree was never touched
4  15:00  git worktree remove ../shop-hotfix

Real scenario: reviewing a colleague's PR while your build runs: git worktree add ../review pr-812. Long-running benchmarks on main while developing on a branch. AI coding agents and CI jobs that need several branches of one clone at once. A quick context switch of five minutes: git stash -u, switch, git stash pop.

NeedStashWorktree
Five-minute interruptionGoodOverkill
Keep a server or build running on the current branchNoYes
Two branches side by side for comparisonNoYes
Disk costNoneOne checkout (objects shared)
RiskForgotten stashes, pop conflictsStale worktrees (git worktree prune)

Submodules vs subtrees Important ​

In plain words: a submodule is a pointer: the parent repository records "the library is at commit 771370d of that other repository". A subtree is a copy: the library's files (and optionally its history) are merged into a folder of the parent repository.

Common misunderstanding: "Updating the submodule repository updates every project that uses it." The parent pins an exact commit (a gitlink, mode 160000); nothing changes until someone runs git submodule update --remote, reviews and commits the new pointer. That is a feature (reproducibility) and a chore (bumps).

Definition: git submodule add <url> <path> writes .gitmodules and a gitlink; clones need git clone --recurse-submodules or git submodule update --init --recursive; git submodule status prefixes + when the checked-out commit differs from the recorded one. git subtree add --prefix=<dir> <repo> <ref> [--squash], git subtree pull, git subtree split / push to contribute back (subtree is in Git's contrib/, shipped by most distributions including Apple's). For dependencies in Go or PHP, prefer the package manager (Go modules, Composer) over either.

bash
#!/usr/bin/env bash
# Sharing code between repositories: a submodule (a pinned commit pointer)
# versus a subtree (the files copied into the history).
source "$(dirname "$0")/lib.sh"
fresh lib-src
commit_file money.go 'package money // v1' "feat: money v1"

fresh app
commit_file main.go 'package main' "chore: init app"

say "submodule: the superproject records a gitlink (mode 160000) and .gitmodules"
run git -c protocol.file.allow=always submodule add -q "$W/lib-src" vendor/money 2>&1 | hide_work
tick
git commit -q -m "build: add money as submodule"
run cat .gitmodules | hide_work
run sh -c 'git ls-tree HEAD vendor/money'
run git submodule status

say "upstream moves; the superproject still pins the old commit until someone bumps it"
cd "$W/lib-src" || exit 1
commit_file money.go 'package money // v2' "feat: money v2"
cd "$W/app" || exit 1
run git submodule status
run git -c protocol.file.allow=always submodule update -q --remote vendor/money 2>&1 | hide_work
run git status --short
run git submodule status

say "a fresh clone does not fetch submodules unless asked"
cd "$W" || exit 1
rm -rf app-clone
git clone -q app app-clone 2>/dev/null
run ls app-clone/vendor/money
cd "$W/app-clone" || exit 1
run git -c protocol.file.allow=always submodule update -q --init 2>&1 | hide_work
run ls vendor/money

say "subtree: the library's files and history are merged into a prefix; clones need nothing extra"
fresh app2
commit_file main.go 'package main' "chore: init app2"
run git subtree add -q --prefix=lib/money "$W/lib-src" main --squash 2>&1 | hide_work
run git log --oneline --graph
run ls lib/money
run git ls-tree HEAD lib/money
text
$ sh -c 'git ls-tree HEAD vendor/money'
160000 commit 771370d10646e6985bb233d4662dd746b76964a0	vendor/money
--- upstream moves; the superproject still pins the old commit until someone bumps it
$ git submodule status
 771370d10646e6985bb233d4662dd746b76964a0 vendor/money (heads/main)
$ git -c protocol.file.allow=always submodule update -q --remote vendor/money
$ git status --short
 M vendor/money
$ git submodule status
+bcee739b32e8e90764019455748281b5745efc81 vendor/money (remotes/origin/HEAD)
--- a fresh clone does not fetch submodules unless asked
$ ls app-clone/vendor/money
$ git -c protocol.file.allow=always submodule update -q --init
$ ls vendor/money
money.go
--- subtree: the library's files and history are merged into a prefix; clones need nothing extra
*   7185a97 Merge commit 'd047af9df8104dc73e8fc0f3962854c82d029a71' as 'lib/money'
|\
| * d047af9 Squashed 'lib/money/' content from commit bcee739
* 5524df7 chore: init app2
$ git ls-tree HEAD lib/money
040000 tree 87d1b07db594e7e0ec728a7a80fd80f3aea80adb	lib/money

protocol.file.allow=always is only needed because the demo uses local paths: git config documents that "all other protocols (including file) have a default policy of user", which is not usable by commands that run without user input, "e.g. recursive submodule initialization". (That default for file dates from the Git 2.38.1 security release, general knowledge; the saved page states only the policy.)

Real scenario: a firmware repository pins vendor SDKs as submodules to exact commits. A design-system repository is pulled into several apps as a subtree so app developers never see submodule commands. A monorepo migration imports old repositories with git subtree add (without --squash) to keep their history. Kubernetes manifests from another team are better consumed as a Helm chart or a Kustomize remote base than as a submodule.

SubmoduleSubtreePackage manager (Go modules, Composer)
Stored in parentCommit pointer + .gitmodulesFull files (+ history or a squash)A version in a manifest + lock file
Clone needs--recurse-submodulesNothinggo mod download, composer install
Updatingsubmodule update --remote + commitsubtree pullgo get -u, composer update
Contributing backCommit inside the submodule, push theresubtree split/pushSeparate repository and release
PitfallsDetached HEADs inside, forgotten bumps, CI auth to two reposBig merges, history noiseNeeds versioned releases

.gitignore and .gitattributes: EOL, autocrlf, export-ignore, linguist Must-know ​

In plain words: .gitignore tells Git which untracked files to pretend not to see. .gitattributes tells Git how to treat files it does track: which are text and what line endings they get, which are binary, which are left out of release archives, and (for GitHub) which count as generated or vendored.

Common misunderstanding: "Adding a file to .gitignore removes it from the repository." Ignore rules apply only to untracked files. A file that is already tracked keeps being tracked (the lab's laravel.log shows M after it was ignored); git rm --cached <file> stops tracking it, and the old versions stay in history.

Definition: ignore sources in increasing precedence of scope: core.excludesFile (global), .git/info/exclude (this clone), .gitignore files (per directory; later and deeper rules win; !pattern re-includes; / anchors; trailing / means directory; you cannot re-include a file if its parent directory is excluded). git check-ignore -v <path> names the matching rule. Attributes: text, text=auto (Git detects text), eol=lf|crlf (checkout line ending; the repository always stores LF for text), binary (= -text -diff), diff=<driver>, merge=<driver>, filter=<driver> (LFS uses filter=lfs), export-ignore (excluded by git archive, and so, as general knowledge, from GitHub/GitLab source zips and Composer dist downloads), linguist-generated, linguist-vendored, linguist-documentation (GitHub language statistics and diff collapsing; Git ignores them). core.autocrlf is the per-user older mechanism: true on Windows (CRLF on checkout, LF in the repository), input elsewhere (convert CRLF to LF on add); a committed .gitattributes overrides individual settings and is the reliable fix. git add --renormalize . re-applies attributes to existing files.

text
# .gitignore for a Laravel + Go repository (copy to the repository root as .gitignore)
# Later rules win; a leading ! re-includes; a trailing / matches directories only.

# Secrets and local configuration: never committed
.env
.env.*
!.env.example
*.pem
*.key

# Dependencies: restored from the lock files (composer.lock, package-lock.json, go.sum)
/vendor/
/node_modules/

# Laravel runtime output
/storage/*.key
/storage/logs/*.log
/storage/framework/cache/data/*
/bootstrap/cache/*.php
/public/hot
/public/storage

# Build output
/public/build/
/bin/
/dist/
*.test
coverage.out

# Editors and OS files belong in the global excludes file (core.excludesFile),
# but many teams list the common ones here as well.
.idea/
.vscode/
.DS_Store
text
# .gitattributes (copy to the repository root as .gitattributes)
# Line endings: store LF in the repository; let Git decide what is text.
* text=auto eol=lf

# Files that must keep CRLF on checkout (Windows tooling)
*.bat text eol=crlf
*.cmd text eol=crlf

# Shell scripts must stay LF even on Windows checkouts, or bash fails with $'\r'
*.sh text eol=lf

# Binary files: no EOL conversion, no textual diff
*.png binary
*.jpg binary
*.pdf binary

# Large media through Git LFS (requires `git lfs install`; written by `git lfs track`)
*.psd filter=lfs diff=lfs merge=lfs -text

# Lock files: generated; a union merge is wrong, so take one side and regenerate
composer.lock -diff linguist-generated
go.sum -diff linguist-generated

# Release archives (git archive, Composer dist zips from GitHub) leave these out
/tests export-ignore
/.github export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/phpunit.xml export-ignore

# GitHub Linguist: language statistics and diff collapsing only
/public/build/** linguist-generated
/docs/** linguist-documentation
/vendor/** linguist-vendored
bash
#!/usr/bin/env bash
# .gitignore precedence, .gitattributes for line endings (eol, text=auto),
# export-ignore for release archives, and linguist overrides for GitHub.
source "$(dirname "$0")/lib.sh"
SNIP=$(cd "$(dirname "$0")/.." && pwd -P)
fresh attrs
cp "$SNIP/config/gitignore.example" .gitignore
cp "$SNIP/config/gitattributes.example" .gitattributes
git add .gitignore .gitattributes && tick && git commit -q -m "chore: ignore and attributes"

say "ignored files: check-ignore -v names the rule that matched"
mkdir -p vendor storage/logs node_modules
touch .env .env.example storage/logs/laravel.log vendor/autoload.php node_modules/x.js
run git status --short --untracked-files=all
run git check-ignore -v .env storage/logs/laravel.log vendor/autoload.php node_modules/x.js
try git check-ignore -v .env.example

say "an already tracked file is not affected by a new ignore rule"
git add -f storage/logs/laravel.log && tick && git commit -q -m "chore: oops, a log"
echo 'more' >> storage/logs/laravel.log
run git status --short
run git rm -q --cached storage/logs/laravel.log
run git status --short

say "line endings: a CRLF file is normalised to LF in the repository"
printf 'line one\r\nline two\r\n' > windows.txt
printf 'echo hi\r\n' > deploy.sh
git add windows.txt deploy.sh 2>&1 | hide_work
run git ls-files --eol windows.txt deploy.sh
run git check-attr -a deploy.sh windows.txt

say "export-ignore: git archive leaves tests and CI out of the release tarball"
mkdir -p tests .github/workflows src
echo '<?php' > src/Money.php
echo '<?php // test' > tests/MoneyTest.php
echo 'name: ci' > .github/workflows/ci.yml
git add -A && tick && git commit -q -m "feat: package layout"
run sh -c 'git archive --format=tar HEAD | tar -tf - | sort'

say "linguist attributes change GitHub language stats only; git ignores them"
run git check-attr linguist-generated linguist-documentation -- public/build/app.js docs/api.md
text
$ git status --short --untracked-files=all
?? .env.example
$ git check-ignore -v .env storage/logs/laravel.log vendor/autoload.php node_modules/x.js
.gitignore:5:.env	.env
.gitignore:17:/storage/logs/*.log	storage/logs/laravel.log
.gitignore:12:/vendor/	vendor/autoload.php
.gitignore:13:/node_modules/	node_modules/x.js
$ git check-ignore -v .env.example
.gitignore:7:!.env.example	.env.example
--- an already tracked file is not affected by a new ignore rule
 M storage/logs/laravel.log
$ git rm -q --cached storage/logs/laravel.log
D  storage/logs/laravel.log
--- line endings: a CRLF file is normalised to LF in the repository
warning: in the working copy of 'deploy.sh', CRLF will be replaced by LF the next time Git touches it
$ git ls-files --eol windows.txt deploy.sh
i/lf    w/crlf  attr/text eol=lf      	deploy.sh
i/lf    w/crlf  attr/text=auto eol=lf 	windows.txt
--- export-ignore: git archive leaves tests and CI out of the release tarball
$ sh -c 'git archive --format=tar HEAD | tar -tf - | sort'
.env.example
deploy.sh
src/
src/Money.php
windows.txt
$ git check-attr linguist-generated linguist-documentation -- public/build/app.js docs/api.md
public/build/app.js: linguist-generated: set
docs/api.md: linguist-documentation: set

i/lf w/crlf reads "index has LF, working tree has CRLF": the repository is clean even though the Windows-edited file on disk is not. check-ignore -v on .env.example prints the ! rule, which means "matched by a negation, so not ignored".

1  Windows dev, no .gitattributes, core.autocrlf=false: commits deploy.sh with CRLF
2  Linux CI: bash deploy.sh  ->  $'\r': command not found
3  fix: .gitattributes "*.sh text eol=lf"; git add --renormalize .; commit
4  every checkout now writes LF for *.sh, on every OS

Real scenario: a Laravel package's GitHub zip includes tests/ and phpunit.xml until export-ignore is added. Diff noise in PRs from editors on Windows: * text=auto eol=lf. GitHub says a repository is "97 % JavaScript" because of a committed build directory: linguist-generated. Secrets in .env are ignored but .env.example documents the keys (Laravel).

MechanismScopeVersioned?Use for
.gitignoreDirectory and belowYesBuild output, dependencies, secrets (.env)
.git/info/excludeThis cloneNoPersonal scratch files
core.excludesFileAll your repositoriesNoEditor and OS files (.idea/, .DS_Store)
.gitattributesDirectory and belowYesEOL, binary, LFS, export-ignore, linguist, merge drivers
core.autocrlfPer userNoLegacy; rely on .gitattributes instead

Large files: Git LFS Important ​

In plain words: Git keeps every version of every file in every clone. For a 300 MB video edited ten times that means 3 GB in everyone's .git. Git LFS stores a three-line pointer file in Git and keeps the real bytes on an LFS server, downloading only the versions you check out.

Common misunderstanding: "Turning on LFS shrinks my repository." git lfs track affects files added from now on; big files already in history stay there until you rewrite history (git lfs migrate import), and every clone and fork still has them.

Definition: git lfs install sets up the smudge/clean filters; git lfs track "*.psd" writes *.psd filter=lfs diff=lfs merge=lfs -text to .gitattributes. The committed file is a pointer: "Example of a v1 text pointer: version https://git-lfs.github.com/spec/v1, oid sha256:4d7a...2393, size 12345" (LFS specification). The bytes go to the LFS endpoint of the host over HTTPS. GitHub's per-file limits: Free 2 GB, Pro 2 GB, Team 4 GB, Enterprise Cloud 5 GB; storage and bandwidth are metered. git lfs ls-files, git lfs pull, GIT_LFS_SKIP_SMUDGE=1 to clone pointers only.

1  git lfs track "*.psd"; git add .gitattributes design.psd; git commit     (expected, not run: git-lfs is not installed on the build host)
2  commit contains:  version https://git-lfs.github.com/spec/v1 / oid sha256:<64 hex> / size 314572800
3  git push   ->  Git pushes the pointer; the LFS client uploads 300 MB to the LFS endpoint
4  colleague: git clone  ->  smudge filter downloads only the checked-out version

Real scenario: game assets, design files and ML model weights in an app repository. A data team puts large CSV fixtures into Git and the push is rejected because "GitHub blocks files larger than 100 MiB"; LFS (or object storage plus a manifest) is the fix. A CI job that does not need assets sets GIT_LFS_SKIP_SMUDGE=1 to save minutes and bandwidth.

ApproachClone sizeNeedsFits
Plain GitEvery version of every fileNothingText, small binaries
Git LFSPointers + checked-out versionsLFS client + serverLarge binaries that version with the code
Partial clone (--filter=blob:limit=1m)Blobs fetched on demandServer supportBig history, any content
Object storage + manifest (S3, GCS)Only the manifestYour own toolingDatasets, build artefacts

Monorepos: sparse-checkout and partial clone Important ​

In plain words: a monorepo puts many services and libraries in one repository so one commit can change an API and all its callers atomically. The cost is size: Git's answer is to download less (partial clone) and to check out less (sparse-checkout).

Common misunderstanding: "Sparse-checkout makes the clone smaller." On its own it only limits which files are written to the working tree; a normal clone has already downloaded every blob. Combine it with partial clone (--filter=blob:none) so blobs for the directories you do not check out are never downloaded.

Definition: git clone --filter=blob:none <url> (blobless: all commits and trees, blobs on demand), --filter=tree:0 (treeless, more on-demand fetching), --filter=blob:limit=<size>; the remote becomes a "promisor remote" and missing objects are fetched lazily (the server must allow filters, uploadpack.allowFilter). git sparse-checkout set --cone <dir>... (cone mode, the default) checks out only the listed directories plus top-level files; git sparse-checkout list, add, disable. git rev-list --objects --all --missing=print prints missing objects with a ? prefix. Shallow clone (--depth=1) is a different thing: it cuts history, which breaks git describe, merge-base and blame; prefer blobless clones for developers and shallow only for throwaway CI checkouts.

bash
#!/usr/bin/env bash
# Monorepo basics: partial clone (--filter=blob:none) and cone-mode sparse-checkout.
source "$(dirname "$0")/lib.sh"
fresh mono-src
for svc in billing catalog checkout search; do
  mkdir -p "services/$svc"
  for n in 1 2 3; do # 200 KB of deterministic, incompressible bytes per file
    key=$(printf '%s%s' "$svc" "$n" | shasum | cut -c1-32)
    head -c 200000 /dev/zero | openssl enc -aes-128-ctr -nosalt -K "$key" -iv 0 > "services/$svc/data$n.bin"
  done
  printf 'package %s\n' "$svc" > "services/$svc/main.go"
done
mkdir -p libs/money && printf 'package money\n' > libs/money/money.go
git add . && tick && git commit -q -m "chore: monorepo"
git config uploadpack.allowFilter true
git config uploadpack.allowAnySHA1InWant true

cd "$W" || exit 1
rm -rf full partial
say "full clone versus blobless partial clone (file:// so the filter is honoured)"
run git clone -q --no-local "file://$W/mono-src" full 2>&1 | hide_work
run git clone -q --filter=blob:none --no-checkout "file://$W/mono-src" partial 2>&1 | hide_work
cd "$W/partial" || exit 1
run git config remote.origin.partialclonefilter
run sh -c 'git rev-list --objects --all --missing=print | grep -c "^?"'

say "cone-mode sparse-checkout: only the directories this team works on"
run git sparse-checkout set --cone services/checkout libs/money
run git checkout -q main
run git sparse-checkout list
run find services libs -type f
run sh -c 'git rev-list --objects --all --missing=print | grep -c "^?"'
say "blobs for the other services were never downloaded; disk use compared"
cd "$W" || exit 1
run sh -c 'du -sk full/.git partial/.git | sed "s|\t| |"'
text
$ git clone -q --filter=blob:none --no-checkout file://$W/mono-src partial
$ git config remote.origin.partialclonefilter
blob:none
$ sh -c 'git rev-list --objects --all --missing=print | grep -c "^?"'
17
$ git sparse-checkout set --cone services/checkout libs/money
$ git checkout -q main
$ find services libs -type f
services/checkout/data1.bin
services/checkout/data3.bin
services/checkout/data2.bin
services/checkout/main.go
libs/money/money.go
$ sh -c 'git rev-list --objects --all --missing=print | grep -c "^?"'
12
$ sh -c 'du -sk full/.git partial/.git | sed "s|\t| |"'
2464 full/.git
728 partial/.git

The repository has 17 blobs (four services with three 200 KB files and a main.go, plus one library file). After the blobless clone all 17 are missing; checking out two directories fetched exactly the 5 blobs needed, and the .git directory is 728 KB instead of 2,464 KB.

1  git clone --filter=blob:none --no-checkout <url> shop     commits + trees, 0 blobs
2  git sparse-checkout set --cone services/checkout libs/money
3  git checkout main          -> fetches the blobs of those two directories only
4  git log -- services/billing   works (trees are local); git show <old>:services/billing/x fetches that blob on demand

Real scenario: a 40-service Go monorepo where each team checks out its service and libs/; CI computes affected services from git diff --name-only origin/main...HEAD and builds only those (Bazel, Nx, Turborepo, Go workspaces with go.work). A Laravel monolith plus its Vue frontend plus Terraform in one repository, with CODEOWNERS per directory. GitOps repositories with one folder per environment are monorepos too.

TechniqueDownloadsWorking treeBreaks
Full cloneEverythingEverythingNothing; slow for huge repos
--depth=1 (shallow)One commit's trees and blobsEverythingHistory tools, describe, some merges
--filter=blob:none (partial, blobless)All commits and trees; blobs on demandEverything (fetched at checkout)Offline work on unfetched blobs
--filter=tree:0 (treeless)Commits; trees and blobs on demandEverythingMany lazy fetches for history walks
Sparse-checkout (cone)UnchangedListed directories onlyTools that expect the whole tree
Partial + sparseCommits, trees, blobs of your directoriesYour directoriesThe monorepo sweet spot

Hooks and pre-commit Must-know ​

In plain words: hooks are scripts Git runs at fixed moments (before a commit is created, when the message is written, before a push). They catch mistakes early: a bad message, an unformatted file, a secret. They run on the developer's machine, so they are a convenience, not a control: --no-verify skips them.

Common misunderstanding: "We committed our hooks to .git/hooks, so everyone has them." .git/ is never cloned. Hooks are shared by committing them to a normal directory and having each clone opt in (git config core.hooksPath hooks) or by a framework such as pre-commit; anything that must be enforced belongs on the server (branch rulesets, required checks, push protection).

Definition: client hooks (githooks(5)): pre-commit (no arguments; non-zero aborts; skipped by --no-verify), prepare-commit-msg, commit-msg (gets the message file path; skipped by --no-verify), post-commit, pre-rebase, post-checkout, post-merge, pre-push (stdin: <local ref> <local sha> <remote ref> <remote sha> per ref; skipped by --no-verify). Server hooks (pre-receive, update, post-receive) run on the server and cannot be skipped by the client; hosted platforms expose them as rulesets, push rules (GitLab) and webhooks. The pre-commit framework (pre-commit.com) installs versioned hooks from a .pre-commit-config.yaml with pinned revs and runs them on staged files; Husky and lefthook are the JavaScript and Go-flavoured equivalents.

bash
#!/bin/sh
# commit-msg hook: git passes the path of the message file as $1.
# A non-zero exit aborts the commit; `git commit --no-verify` skips the hook.
# Install for one clone:  git config core.hooksPath hooks   (hooks/ is versioned)
set -eu
lint=${COMMITLINT:-commitlint}
if ! command -v "$lint" >/dev/null 2>&1; then
  echo "commit-msg: $lint not found; build it with: go build -o bin/commitlint ./cmd/commitlint" >&2
  exit 1
fi
exec "$lint" "$1"
bash
#!/bin/sh
# pre-commit hook: runs before the message editor opens; looks only at what is
# staged (the index), not at the working tree.
set -eu

# 1. Refuse obvious secrets in the staged diff (a last line of defence; the
#    server-side scanner, e.g. GitHub push protection, is the real control).
patterns='(AKIA[0-9A-Z]{16}|sk_(live|test)_[0-9A-Za-z]{10,}|-----BEGIN [A-Z ]*PRIVATE KEY-----|ghp_[0-9A-Za-z]{36})'
if git diff --cached -U0 --no-color | grep '^+' | grep -Eq "$patterns"; then
  echo "pre-commit: staged changes look like they contain a secret:" >&2
  git diff --cached -U0 --no-color | grep '^+' | grep -En "$patterns" | sed 's/^/  /' >&2
  exit 1
fi

# 2. Refuse .env files even if someone forced them past .gitignore.
if git diff --cached --name-only --diff-filter=A | grep -Eq '(^|/)\.env$'; then
  echo "pre-commit: refusing to commit a .env file" >&2
  exit 1
fi

# 3. gofmt the staged Go files (only if Go is installed).
if command -v gofmt >/dev/null 2>&1; then
  files=$(git diff --cached --name-only --diff-filter=ACM -- '*.go')
  if [ -n "$files" ]; then
    # shellcheck disable=SC2086 # word splitting is intended: one name per word
    bad=$(gofmt -l $files)
    if [ -n "$bad" ]; then
      echo "pre-commit: not gofmt-ed: $bad" >&2
      exit 1
    fi
  fi
fi
exit 0
bash
#!/bin/sh
# pre-push hook: stdin has one line per ref being pushed:
#   <local ref> <local sha> <remote ref> <remote sha>
# This one refuses a direct push to main; branch protection on the server is
# the real rule, the hook only saves a round trip.
set -eu
while read -r local_ref local_sha remote_ref remote_sha; do
  if [ "$remote_ref" = "refs/heads/main" ]; then
    echo "pre-push: push a branch and open a pull request instead of pushing to main" >&2
    exit 1
  fi
done
exit 0
yaml
# .pre-commit-config.yaml for the pre-commit framework (https://pre-commit.com)
# Install once per clone: pip install pre-commit && pre-commit install --hook-type pre-commit --hook-type commit-msg
# Pin every `rev` to a tag or a full commit SHA; `pre-commit autoupdate` bumps them.
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v6.0.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-merge-conflict
      - id: check-added-large-files
        args: ["--maxkb=500"]
      - id: detect-private-key
      - id: mixed-line-ending
        args: ["--fix=lf"]
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.24.2
    hooks:
      - id: gitleaks
  - repo: local
    hooks:
      - id: gofmt
        name: gofmt
        entry: gofmt -l -w
        language: system
        types: [go]
      - id: php-lint
        name: php -l
        entry: php -l
        language: system
        types: [php]
      - id: commitlint
        name: Conventional Commits
        entry: go run ./cmd/commitlint
        language: system
        stages: [commit-msg]
bash
#!/usr/bin/env bash
# Client-side hooks (commit-msg with the Go linter, pre-commit secret scan,
# pre-push) and why a secret that was ever committed is still in history.
source "$(dirname "$0")/lib.sh"
SNIP=$(cd "$(dirname "$0")/.." && pwd -P)
mkdir -p "$W/home/bin"
GOCACHE="$W/gocache" GOPATH="$W/gopath" go build -C "$SNIP/go" -buildvcs=false -o "$W/home/bin/commitlint" ./cmd/commitlint
export PATH="$W/home/bin:$PATH"

fresh hooks
mkdir -p hooks && cp "$SNIP/hooks/commit-msg" "$SNIP/hooks/pre-commit" "$SNIP/hooks/pre-push" hooks/
git add hooks && tick && git -c core.hooksPath=/dev/null commit -q -m "build: versioned hooks"
say "hooks live in a versioned directory; each clone opts in with core.hooksPath"
run git config core.hooksPath hooks

say "commit-msg: a message that is not Conventional Commits is rejected"
echo 'a' > a.txt && git add a.txt
tick
try git commit -q -m "updated stuff"
try git commit -q -m "feat: add a."
run git commit -q -m "feat: add a" -m "Refs: #12"
run git log -1 --format='%s | trailers: %(trailers:key=Refs,valueonly,separator=%x2C)'

say "pre-commit: a staged secret stops the commit"
printf "<?php return ['stripe' => 'sk_live_51HxAbCdEfGhIjKl'];\n" > config.php
git add config.php
tick
try git commit -q -m "feat: payments config"
run git restore --staged config.php
rm config.php

say "--no-verify skips client hooks: they are a convenience, not a control"
printf "<?php return ['stripe' => 'sk_live_51HxAbCdEfGhIjKl'];\n" > config.php
git add config.php
tick
run git commit -q --no-verify -m "feat: payments config"
say "deleting the file in a new commit does not remove the secret from history"
git rm -q config.php
tick
run git commit -q -m "fix: remove leaked key"
run git log --oneline -S sk_live_
run git show HEAD~1:config.php

say "pre-push: refuse a direct push to main"
cd "$W" && rm -rf hooks-remote.git && git init -q --bare hooks-remote.git && cd "$W/hooks" || exit 1
git remote add origin "$W/hooks-remote.git"
try git push -q origin main | hide_work
run git push -q --no-verify origin main 2>&1 | hide_work
say "once pushed, every clone and fork has the blob: rotate the key first, then rewrite"
cd "$W" && rm -rf hooks-clone && git clone -q hooks-remote.git hooks-clone && cd hooks-clone || exit 1
run git log --oneline -S sk_live_
text
$ git config core.hooksPath hooks
$ git commit -q -m 'updated stuff'
commitlint: header "updated stuff" is not "type(scope)!: description"
commitlint: see https://www.conventionalcommits.org/en/v1.0.0/
(exit 1)
$ git commit -q -m 'feat: add a.'
commitlint: description must not end with a period
(exit 1)
$ git commit -q -m 'feat: add a' -m 'Refs: #12'
$ git log -1 '--format=%s | trailers: %(trailers:key=Refs,valueonly,separator=%x2C)'
feat: add a | trailers: #12
--- pre-commit: a staged secret stops the commit
pre-commit: staged changes look like they contain a secret:
  2:+<?php return ['stripe' => 'sk_live_51HxAbCdEfGhIjKl'];
(exit 1)
--- --no-verify skips client hooks: they are a convenience, not a control
$ git commit -q --no-verify -m 'feat: payments config'
$ git push -q origin main
pre-push: push a branch and open a pull request instead of pushing to main
(exit 1)

The commit-msg hook runs the Go linter from Go; the pre-commit hook pattern is written sk_(live|test)_ so that the hook file itself does not match a git log -S sk_live_ search (an early version of the demo did, which is exactly the kind of false positive real scanners have to handle). The pre-commit framework itself is not installed on the build host, so pre-commit-config.yaml is "expected, not run"; the rev values come from the saved READMEs of pre-commit-hooks (v6.0.0) and gitleaks (v8.24.2).

1  git commit           -> pre-commit (staged diff scan, gofmt)  -> editor -> commit-msg (commitlint) -> commit written
2  git push             -> pre-push (refuse main)                 -> server: ruleset, required checks, push protection
3  git commit --no-verify / git push --no-verify   -> client hooks skipped; server rules still apply

Real scenario: a team's pre-commit runs gofmt, php -l and gitleaks in under a second; CI runs pre-commit run --all-files so the same rules hold for people who never installed it. A Laravel team uses a post-merge hook to run composer install when composer.lock changed. GitHub push protection blocks a pushed secret server-side even when the client hook was skipped.

HookWhenArguments / inputSkipped by --no-verifyTypical job
pre-commitBefore the message editorNoneYesFormat, lint, secret scan on staged files
prepare-commit-msgBefore the editor opensMessage file, source, shaNoInsert the ticket id from the branch name
commit-msgAfter the message is writtenMessage fileYesConventional Commits check
post-commitAfter the commitNonen/aNotifications
pre-pushBefore objects are sentRemote name, URL; refs on stdinYesTests, refuse pushes to main
post-checkout, post-mergeAfter switch / mergeOld/new refs; squash flagn/acomposer install, go generate
pre-receive, update (server)On the server, before refs moveRefs on stdin / as argsNever (server side)Policy enforcement

Security: secrets in history, git filter-repo, signed commits, the verified badge Must-know ​

In plain words: once a secret is pushed it is compromised: it is in every clone, fork, CI cache and possibly the host's caches. Deleting the file in a new commit hides it from the tree, not from history. The order is always: rotate (revoke) the secret, then clean history, then make sure it cannot happen again.

Common misunderstanding: "We rewrote history with filter-repo, so the key is safe." The rewrite only removes it from the repositories you control and force-push to. Forks, existing clones, pull request refs on the host and anyone who already copied it still have it. Rotation is the fix; rewriting is hygiene.

Definition: find it: git log -S'<secret>' --all, gitleaks detect, trufflehog git. Remove it: GitHub's guide uses git-filter-repo --sensitive-data-removal --replace-text ../passwords.txt or --invert-paths --path <file>, which rewrites every commit id after the first affected one; GitHub's guide warns that signatures depend on commit hashes, so rewriting tools "will simply remove the signatures", and that hosts may need support to purge cached views and PR refs. git filter-branch is the slow, footgun-prone predecessor; BFG Repo-Cleaner an alternative. Prevent it: .env in .gitignore, a pre-commit secret scan, server-side push protection (GitHub), secret detection (GitLab), short-lived credentials. Verified badge: GitHub marks a commit or tag "Verified" when "a GPG, SSH, or S/MIME signature ... is cryptographically verifiable" against a key on the committer's account; "Partially verified" (signed, but an author who is not the committer has enabled vigilant mode) and "Unverified" are the other states; with vigilant mode on, "The commit is not signed and the committer has enabled vigilant mode" also shows "Unverified".

1  10:02  sk_live_... committed in config.php and pushed to main
2  10:05  scanner alert (GitHub secret scanning / gitleaks in CI)
3  10:06  ROTATE: revoke the key at the provider, issue a new one into the secret store (not Git)
4  10:20  git-filter-repo --sensitive-data-removal --replace-text ../passwords.txt  (expected, not run: not installed here)
5  10:25  coordinated force-push; everyone re-clones; host support purges cached refs if needed
6  10:40  add pre-commit + push protection; post-incident note (see secure-sdlc-incident-response)

Real output: the secret stays in history after the "fix" commit, and a fresh clone of the remote has it too:

text
--- deleting the file in a new commit does not remove the secret from history
$ git commit -q -m 'fix: remove leaked key'
$ git log --oneline -S sk_live_
e5a37bf fix: remove leaked key
a59cc6e feat: payments config
$ git show HEAD~1:config.php
<?php return ['stripe' => 'sk_live_51HxAbCdEfGhIjKl'];
--- once pushed, every clone and fork has the blob: rotate the key first, then rewrite
$ git log --oneline -S sk_live_
e5a37bf fix: remove leaked key
a59cc6e feat: payments config

The filter-repo step, expected and not run (the tool is not installed on the build host); the command shape is from the saved README:

bash
# passwords.txt contains one line: sk_live_51HxAbCdEfGhIjKl==>REMOVED
git clone https://github.com/acme/shop && cd shop          # GitHub's guide starts from a fresh clone
git-filter-repo --sensitive-data-removal --replace-text ../passwords.txt
git log --all -S sk_live_ --oneline                         # expected: no output
git push --force --mirror origin                            # every branch and tag rewritten; protected branches must allow it temporarily

Real scenario: an AWS key pushed to a public repository is typically abused within minutes, so rotation comes before any Git command. A private repository with a leaked database password: rotate, rewrite, and still assume every former employee's clone has it. A release process requires signed tags and verifies them before deploying (the Envoy file in Laravel runs git verify-tag). An attacker sets user.email to a maintainer's address: the commit shows the maintainer's avatar but no "Verified" badge.

ControlStopsWhereBypassable by the developer?
.gitignore for .env, keysAccidental git add .ClientYes (git add -f)
pre-commit secret scanMost accidental commitsClientYes (--no-verify)
Push protection / secret detectionPushes containing known token formatsServerOnly with an audited bypass
Required signed commitsUnattributed commits on protected branchesServerNo
git filter-repoSecret in your copies of historyRepository ownern/a (cleanup)
RotationUse of the leaked secretProvidern/a (the real fix)

Mechanics ​

What git commit actually writes ​

1  read .git/index (already contains blob ids for every staged path)
2  build tree objects bottom-up from the index; unchanged subtrees reuse their existing ids
3  write commit object: tree <id>, parent <HEAD>, author/committer + timestamp + timezone, message (+ gpgsig if signing)
4  run hooks around it: pre-commit, prepare-commit-msg, commit-msg (abort on non-zero), post-commit
5  update the ref HEAD points at (refs/heads/main) with a compare-and-swap against the old id; append to the reflogs of HEAD and main

The compare-and-swap in step 5 is why two Git processes on one repository do not corrupt a branch: the second sees .git/refs/heads/main.lock or a changed old value and fails with cannot lock ref.

How a merge and a rebase are computed ​

1  merge-base(ours, theirs): the best common ancestor (with several, ort merges them into a virtual base first)
2  diff base->ours and base->theirs, with rename detection
3  for each path: changed on one side only -> take it; on both, same change -> take it; on both, overlapping hunks -> conflict
4  conflicts: write markers into the working tree, stages 1/2/3 into the index, MERGE_HEAD/MERGE_MSG into .git
5  no conflicts: write the merged tree and a commit with parents [ours, theirs]
--- rebase upstream (default backend "merge", the sequencer)
6  list commits upstream..HEAD (skipping ones whose patch is already upstream), write the todo to .git/rebase-merge/
7  detach HEAD at upstream (or --onto), then for each todo line: cherry-pick = a three-way merge of (parent, commit, HEAD)
8  at the end: move the branch ref to the new tip (and with --update-refs every other ref in the range); ORIG_HEAD = old tip

How a push decides ​

1  client and server exchange ref advertisements (protocol v2: ls-refs), then negotiate which objects the server lacks
2  client sends a packfile with the missing objects
3  server checks: fast-forward? (old remote id must be an ancestor of the new one, unless the client asked to force)
4  --force-with-lease: client sends "expect old id = X"; server updates only if the ref still equals X
5  server-side policy: pre-receive/update hooks, GitHub rulesets / GitLab protected branches, push protection; any reject -> "! [remote rejected]"
6  success: refs updated atomically per ref (or all-or-nothing with --atomic)

The knobs ​

SettingValuesEffectRecommended
init.defaultBranchnameInitial branch for git initmain
pull.rebasefalse, true, mergesWhat git pull does after fetchtrue on feature branches
pull.fftrue, only, falseFast-forward policy for pull mergesonly if you never want accidental merges
merge.conflictStylemerge, diff3, zdiff3Conflict markerszdiff3
rerere.enabled, rerere.autoUpdateboolRecord and reuse resolutionstrue, false (review first)
rebase.autoSquash, rebase.updateRefs, rebase.autoStashboolDefaults for rebase -itrue
push.autoSetupRemote, push.followTags, push.useForceIfIncludesboolPush conveniences and safetytrue
fetch.pruneboolDelete remote-tracking refs gone on the servertrue
commit.gpgSign, tag.gpgSign, gpg.format, user.signingkey, gpg.ssh.allowedSignersFileSigningSSH signing
core.autocrlf, core.eoltrue/input/false; lf/crlf/nativeLine endings without attributesPrefer .gitattributes
core.hooksPathpathDirectory for hooksA versioned hooks/
credential.helperosxkeychain, manager, libsecret, cache, storeHTTPS credentialsOS keychain or Git Credential Manager
gc.reflogExpire, gc.reflogExpireUnreachabletimeReflog retention (90 / 30 days default)Default
uploadpack.allowFilter (server)boolAllow partial clone filterstrue on servers you run
protocol.file.allowalways, never, userLocal-path transport policyDefault (user)

All of these together, as a starting ~/.gitconfig:

ini
# ~/.gitconfig: the settings this chapter recommends (git 2.38+; zdiff3 needs 2.35)
[user]
	name = Ada Dev
	email = ada@example.com
	signingkey = ~/.ssh/id_ed25519.pub
[init]
	defaultBranch = main
[gpg]
	format = ssh
[gpg "ssh"]
	allowedSignersFile = ~/.config/git/allowed_signers
[commit]
	gpgSign = true
	verbose = true
[tag]
	gpgSign = true
[pull]
	rebase = true            # pull = fetch + rebase; no accidental merge commits
[rebase]
	autoSquash = true        # fixup!/squash! commits are placed automatically
	autoStash = true
	updateRefs = true        # move every branch in a stack (2.38+)
[merge]
	conflictStyle = zdiff3   # show the merge base inside conflict markers
[rerere]
	enabled = true           # reuse recorded conflict resolutions
[push]
	autoSetupRemote = true
	useForceIfIncludes = true
[fetch]
	prune = true
[diff]
	algorithm = histogram
	colorMoved = default
[core]
	autocrlf = input         # Windows users: true; everyone else: input (or rely on .gitattributes)
	excludesFile = ~/.config/git/ignore
[credential]
	helper = osxkeychain     # macOS; Linux: libsecret or cache; Windows: manager
[alias]
	lg = log --oneline --graph --decorate
	amend = commit --amend --no-edit
	pushf = push --force-with-lease --force-if-includes

Error messages you will actually see ​

Rows marked "(transcript)" appeared in this chapter's runs/ transcripts; the others are labelled with where they come from.

MessageMeaningFix
CONFLICT (content): Merge conflict in price.txt / Automatic merge failed (transcript)Overlapping changesResolve, git add, git commit (or --abort)
! [rejected] main -> main (stale info) (transcript)--force-with-lease: remote moved since your last fetchFetch, look, integrate
! [rejected] main -> main (remote ref updated since checkout) (transcript)--force-if-includes: you fetched but did not integrateRebase onto the fetched tip
! [rejected] main -> main (non-fast-forward) (seen in an earlier version of script 03, not in the final transcripts)Remote has commits you do notgit pull --rebase, then push
fatal: No names found, cannot describe anything. (transcript)No annotated tag reachableTag, or git describe --tags --always
fatal: 'hotfix' is already used by worktree at '...' (transcript)Branch checked out in another worktreeUse that worktree or another branch
Warning: you are leaving 1 commit behind, not connected to any of your branches (transcript)Commits made on a detached HEADgit branch <name> <id>
Could not verify signature. / Signature verification failed: incorrect signature (transcript)Object changed after signing, or wrong keyInvestigate; never ship it
warning: in the working copy of 'deploy.sh', CRLF will be replaced by LF (transcript).gitattributes normalises EOLExpected; commit the normalised file
error: could not apply <id>... <subject> (seen in an earlier version of script 03, not in the final transcripts)A rebase step conflictedResolve, git rebase --continue (or --skip, --abort)
fatal: transport 'file' not allowed (run by hand: git submodule add of a local path without protocol.file.allow)Local-path submodule blocked by policyUse a real URL, or allow it for that command
A push rejected by a GitHub ruleset or a GitLab protected branch (not run: server-side; the exact text is the host's)Policy blocked the pushOpen a pull request

Go ​

Go touches Git in three places: the module system resolves versions straight from Git tags and commits, the toolchain stamps the commit into binaries, and Go is a good language for the small tools a repository needs (hooks, release helpers). Two programs here: a commit-message linter used as the commit-msg hook, and a pseudo-version calculator that shows how the go command names an untagged commit.

Before ​

The usual starting point is a regular expression in a shell hook:

bash
#!/bin/sh
# .git/hooks/commit-msg: untested, not shared, silently skipped when the regex is wrong
grep -Eq '^(feat|fix|docs|chore)(\(.+\))?: .+' "$1" || { echo "bad message" >&2; exit 1; }

It rejects Merge branch ... and fixup! commits that Git itself writes, says nothing about why a message failed, ignores breaking-change footers and trailers, and lives in .git/hooks, which is never cloned.

After ​

go
// Package commitlint checks a commit message against the Conventional Commits
// 1.0.0 header grammar plus a few team rules (subject length, blank line after
// the header, trailer syntax). It is small enough to run as a commit-msg hook.
package commitlint

import (
	"fmt"
	"regexp"
	"strings"
)

// Commit is a parsed commit message.
type Commit struct {
	Type        string
	Scope       string
	Breaking    bool
	Description string
	Body        string
	Trailers    []Trailer
}

// Trailer is one "Token: value" line from the last paragraph.
type Trailer struct {
	Token string
	Value string
}

// Rules are the team's choices; DefaultRules matches the chapter's examples.
type Rules struct {
	Types        []string // allowed types, e.g. feat, fix
	MaxSubject   int      // maximum length of the whole first line
	RequireScope bool
}

// DefaultRules is the set used by the commit-msg hook in this chapter.
var DefaultRules = Rules{
	Types:      []string{"feat", "fix", "docs", "style", "refactor", "perf", "test", "build", "ci", "chore", "revert"},
	MaxSubject: 72,
}

var (
	header  = regexp.MustCompile(`^([a-z]+)(\(([a-z0-9._/-]+)\))?(!)?: (\S.*)$`)
	trailer = regexp.MustCompile(`^([A-Za-z][A-Za-z0-9-]*|BREAKING CHANGE): (.+)$`)
)

// Strip removes comment lines (git's "# Please enter the commit message...")
// and trailing blank lines, as git does with the default cleanup mode.
func Strip(raw string) string {
	var keep []string
	for _, l := range strings.Split(strings.ReplaceAll(raw, "\r\n", "\n"), "\n") {
		if strings.HasPrefix(l, "#") {
			continue
		}
		keep = append(keep, strings.TrimRight(l, " \t"))
	}
	return strings.TrimRight(strings.Join(keep, "\n"), "\n")
}

// Exempt reports messages that git or the hosting platform writes itself.
// fixup!/squash!/amend! commits are temporary and disappear with --autosquash.
func Exempt(msg string) bool {
	for _, p := range []string{"Merge ", "Revert \"", "fixup! ", "squash! ", "amend! "} {
		if strings.HasPrefix(msg, p) {
			return true
		}
	}
	return false
}

// Parse splits a message into header, body and trailers. It returns an error
// only when the header does not follow the grammar.
func Parse(msg string) (Commit, error) {
	paras := strings.Split(msg, "\n\n")
	first := paras[0]
	if strings.Contains(first, "\n") {
		return Commit{}, fmt.Errorf("the header must be one line followed by a blank line")
	}
	m := header.FindStringSubmatch(first)
	if m == nil {
		return Commit{}, fmt.Errorf("header %q is not \"type(scope)!: description\"", first)
	}
	c := Commit{Type: m[1], Scope: m[3], Breaking: m[4] == "!", Description: m[5]}
	rest := paras[1:]
	if n := len(rest); n > 0 {
		if ts, ok := parseTrailers(rest[n-1]); ok {
			c.Trailers = ts
			rest = rest[:n-1]
		}
	}
	c.Body = strings.Join(rest, "\n\n")
	for _, t := range c.Trailers {
		if t.Token == "BREAKING CHANGE" || t.Token == "BREAKING-CHANGE" {
			c.Breaking = true
		}
	}
	return c, nil
}

// parseTrailers accepts a paragraph only if every line is a trailer.
func parseTrailers(p string) ([]Trailer, bool) {
	var out []Trailer
	for _, l := range strings.Split(p, "\n") {
		m := trailer.FindStringSubmatch(l)
		if m == nil {
			return nil, false
		}
		out = append(out, Trailer{Token: m[1], Value: m[2]})
	}
	return out, len(out) > 0
}

// Lint returns every problem found; an empty slice means the message passes.
func Lint(raw string, r Rules) []string {
	msg := Strip(raw)
	if msg == "" {
		return []string{"empty commit message"}
	}
	if Exempt(msg) {
		return nil
	}
	var probs []string
	first := strings.SplitN(msg, "\n", 2)[0]
	if r.MaxSubject > 0 && len([]rune(first)) > r.MaxSubject {
		probs = append(probs, fmt.Sprintf("header is %d characters, limit is %d", len([]rune(first)), r.MaxSubject))
	}
	c, err := Parse(msg)
	if err != nil {
		return append(probs, err.Error())
	}
	if !contains(r.Types, c.Type) {
		probs = append(probs, fmt.Sprintf("type %q is not one of %s", c.Type, strings.Join(r.Types, ", ")))
	}
	if r.RequireScope && c.Scope == "" {
		probs = append(probs, "a scope is required, e.g. feat(cart): ...")
	}
	if strings.HasSuffix(c.Description, ".") {
		probs = append(probs, "description must not end with a period")
	}
	return probs
}

func contains(xs []string, x string) bool {
	for _, v := range xs {
		if v == x {
			return true
		}
	}
	return false
}
go
package commitlint

import (
	"strings"
	"testing"
)

func TestParseFull(t *testing.T) {
	msg := "feat(cart)!: drop the legacy price field\n\nClients must send amount_minor.\n\nRefs: #412\nCo-authored-by: Bob Ops <bob@example.com>\nBREAKING CHANGE: price is removed"
	c, err := Parse(msg)
	if err != nil {
		t.Fatal(err)
	}
	if c.Type != "feat" || c.Scope != "cart" || !c.Breaking || c.Description != "drop the legacy price field" {
		t.Fatalf("header parsed wrong: %+v", c)
	}
	if c.Body != "Clients must send amount_minor." {
		t.Fatalf("body = %q", c.Body)
	}
	if len(c.Trailers) != 3 || c.Trailers[1].Token != "Co-authored-by" || c.Trailers[2].Token != "BREAKING CHANGE" {
		t.Fatalf("trailers = %+v", c.Trailers)
	}
}

func TestBreakingFromFooterOnly(t *testing.T) {
	c, err := Parse("fix: tighten validation\n\nBREAKING CHANGE: empty names are rejected")
	if err != nil || !c.Breaking {
		t.Fatalf("want breaking via footer, got %+v %v", c, err)
	}
}

func TestBodyIsNotATrailer(t *testing.T) {
	c, err := Parse("docs: explain retries\n\nSee: the runbook explains it\nand this line is prose")
	if err != nil {
		t.Fatal(err)
	}
	if len(c.Trailers) != 0 || c.Body == "" {
		t.Fatalf("a mixed paragraph must stay body: %+v", c)
	}
}

func TestLint(t *testing.T) {
	cases := []struct {
		name string
		msg  string
		want string // substring of the first problem; "" means pass
	}{
		{"ok", "fix(api): return 404 for unknown orders", ""},
		{"ok with comments", "feat: add search\n# Please enter the commit message\n", ""},
		{"merge exempt", "Merge branch 'feature' into main", ""},
		{"fixup exempt", "fixup! feat: add Total", ""},
		{"revert exempt", "Revert \"feat: enable checkout v2\"", ""},
		{"no type", "updated stuff", "is not \"type(scope)!: description\""},
		{"unknown type", "feature: add search", "type \"feature\" is not one of"},
		{"period", "fix: handle nil cart.", "must not end with a period"},
		{"too long", "feat: " + strings.Repeat("x", 80), "header is 86 characters"},
		{"no blank line", "feat: a\nbody right away", "followed by a blank line"},
		{"empty", "# only a comment\n", "empty commit message"},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			probs := Lint(tc.msg, DefaultRules)
			if tc.want == "" {
				if len(probs) != 0 {
					t.Fatalf("want pass, got %v", probs)
				}
				return
			}
			if len(probs) == 0 || !strings.Contains(probs[0], tc.want) {
				t.Fatalf("want %q, got %v", tc.want, probs)
			}
		})
	}
}

func TestRequireScope(t *testing.T) {
	r := DefaultRules
	r.RequireScope = true
	if p := Lint("feat: no scope", r); len(p) == 0 {
		t.Fatal("want a scope problem")
	}
}
go
// Command commitlint is a commit-msg hook: git passes the path of the message
// file as the only argument; a non-zero exit aborts the commit.
//
//	go build -o .git/hooks/commitlint ./cmd/commitlint
//	printf '#!/bin/sh\nexec .git/hooks/commitlint "$1"\n' > .git/hooks/commit-msg
package main

import (
	"fmt"
	"io"
	"os"

	"academy/git-version-control/commitlint"
)

func main() {
	os.Exit(run(os.Args[1:], os.Stdin, os.Stderr))
}

func run(args []string, stdin io.Reader, stderr io.Writer) int {
	var data []byte
	var err error
	switch len(args) {
	case 0:
		data, err = io.ReadAll(stdin)
	case 1:
		data, err = os.ReadFile(args[0])
	default:
		fmt.Fprintln(stderr, "usage: commitlint [message-file]")
		return 2
	}
	if err != nil {
		fmt.Fprintln(stderr, "commitlint:", err)
		return 2
	}
	probs := commitlint.Lint(string(data), commitlint.DefaultRules)
	for _, p := range probs {
		fmt.Fprintln(stderr, "commitlint:", p)
	}
	if len(probs) > 0 {
		fmt.Fprintln(stderr, "commitlint: see https://www.conventionalcommits.org/en/v1.0.0/")
		return 1
	}
	return 0
}
go
package main

import (
	"bytes"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestRunFile(t *testing.T) {
	dir := t.TempDir()
	good := filepath.Join(dir, "good")
	bad := filepath.Join(dir, "bad")
	if err := os.WriteFile(good, []byte("feat(cart): add totals\n"), 0o600); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(bad, []byte("wip\n"), 0o600); err != nil {
		t.Fatal(err)
	}
	var errb bytes.Buffer
	if code := run([]string{good}, nil, &errb); code != 0 {
		t.Fatalf("good message: exit %d, %s", code, errb.String())
	}
	errb.Reset()
	if code := run([]string{bad}, nil, &errb); code != 1 || !strings.Contains(errb.String(), "commitlint:") {
		t.Fatalf("bad message: exit %d, %q", code, errb.String())
	}
}

func TestRunStdinAndUsage(t *testing.T) {
	var errb bytes.Buffer
	if code := run(nil, strings.NewReader("fix: ok\n"), &errb); code != 0 {
		t.Fatalf("stdin: exit %d", code)
	}
	if code := run([]string{"a", "b"}, nil, &errb); code != 2 {
		t.Fatalf("usage: exit %d", code)
	}
}
go
// Package pseudo builds Go module pseudo-versions from a commit, following the
// three forms in the Go Modules Reference (go.dev/ref/mod#pseudo-versions).
// The go command does this itself; the package exists to make the rule visible
// and testable: base version prefix, UTC commit time, 12-character hash prefix.
package pseudo

import (
	"fmt"
	"regexp"
	"strconv"
	"time"
)

var semver = regexp.MustCompile(`^v(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?$`)

// Version returns the pseudo-version for a commit.
//
//	base    = "" (no tag), a release tag like "v1.2.3" or a pre-release "v1.3.0-rc.1"
//	major   = the module's major version (0 or 1 for paths without /vN)
//	commit  = the committer time (git: %ct), converted to UTC
//	hash    = the full commit hash; the first 12 characters are used
func Version(base string, major int, commit time.Time, hash string) (string, error) {
	if len(hash) < 12 {
		return "", fmt.Errorf("hash %q is shorter than 12 characters", hash)
	}
	ts := commit.UTC().Format("20060102150405")
	rev := hash[:12]
	if base == "" {
		return fmt.Sprintf("v%d.0.0-%s-%s", major, ts, rev), nil
	}
	m := semver.FindStringSubmatch(base)
	if m == nil {
		return "", fmt.Errorf("base %q is not a semantic version tag", base)
	}
	if m[4] != "" { // pre-release: vX.Y.Z-pre.0.ts-rev
		return fmt.Sprintf("%s.0.%s-%s", base, ts, rev), nil
	}
	patch, _ := strconv.Atoi(m[3])
	return fmt.Sprintf("v%s.%s.%d-0.%s-%s", m[1], m[2], patch+1, ts, rev), nil
}
go
package pseudo

import (
	"testing"
	"time"
)

func TestVersionForms(t *testing.T) {
	// The example commit from the Go Modules Reference: 2019-11-09 02:19:31 UTC, daa7c04131f5.
	ct := time.Date(2019, 11, 9, 2, 19, 31, 0, time.UTC)
	hash := "daa7c04131f5aabbccddeeff0011223344556677"
	cases := []struct{ base, want string }{
		{"", "v0.0.0-20191109021931-daa7c04131f5"},
		{"v1.2.3", "v1.2.4-0.20191109021931-daa7c04131f5"},
		{"v1.3.0-rc.1", "v1.3.0-rc.1.0.20191109021931-daa7c04131f5"},
	}
	for _, c := range cases {
		got, err := Version(c.base, 0, ct, hash)
		if err != nil {
			t.Fatal(err)
		}
		if got != c.want {
			t.Errorf("base %q: got %s, want %s", c.base, got, c.want)
		}
	}
}

func TestVersionUsesUTC(t *testing.T) {
	tehran := time.FixedZone("IRST", 3*3600+1800)
	ct := time.Date(2026, 1, 1, 13, 30, 0, 0, tehran) // 10:00 UTC
	got, err := Version("", 0, ct, "0123456789abcdef")
	if err != nil {
		t.Fatal(err)
	}
	if want := "v0.0.0-20260101100000-0123456789ab"; got != want {
		t.Fatalf("got %s, want %s", got, want)
	}
}

func TestVersionErrors(t *testing.T) {
	if _, err := Version("", 0, time.Now(), "abc"); err == nil {
		t.Error("short hash must fail")
	}
	if _, err := Version("1.2.3", 0, time.Now(), "0123456789abcdef"); err == nil {
		t.Error("tag without v must fail")
	}
}
go
// Command pseudoversion prints the Go pseudo-version for HEAD of the git
// repository in the current directory, using git describe for the base tag.
package main

import (
	"fmt"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"time"

	"academy/git-version-control/pseudo"
)

func git(args ...string) (string, error) {
	out, err := exec.Command("git", args...).Output()
	return strings.TrimSpace(string(out)), err
}

func main() {
	hash, err := git("rev-parse", "HEAD")
	if err != nil {
		fmt.Fprintln(os.Stderr, "not a git repository with commits")
		os.Exit(1)
	}
	ct, err := git("log", "-1", "--format=%ct", "HEAD")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	sec, _ := strconv.ParseInt(ct, 10, 64)
	// The nearest semver tag reachable from HEAD; no tag means no base version.
	base, err := git("describe", "--tags", "--abbrev=0", "--match", "v[0-9]*", "HEAD")
	if err != nil {
		base = ""
	}
	if exact, _ := git("tag", "--points-at", "HEAD", "--list", "v[0-9]*"); exact != "" {
		fmt.Println(strings.Fields(exact)[0], "(HEAD is tagged: no pseudo-version needed)")
		return
	}
	v, err := pseudo.Version(base, 0, time.Unix(sec, 0), hash)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Println(v)
}
text
module academy/git-version-control

go 1.24

The linter is wired into Git by the versioned hooks/commit-msg (Hooks, with real rejections in the transcript) and into CI by hosting/pr-checks.yml, which lints every commit of a pull request, so --no-verify does not get a bad message into main.

The Go angle ​

  • go.mod pseudo-version. A dependency on an untagged commit is written as a pseudo-version. The Go Modules Reference: "A pseudo-version is a specially formatted pre-release version that encodes information about a specific revision in a version control repository. For example, v0.0.0-20191109021931-daa7c04131f5". Its parts are a base version prefix, "a timestamp (yyyymmddhhmmss), which is the UTC time the revision was created. In Git, this is the commit time, not the author time", and "a 12-character prefix of the commit hash". The three forms are vX.0.0-ts-hash (no tag), vX.Y.(Z+1)-0.ts-hash (after release vX.Y.Z) and vX.Y.Z-pre.0.ts-hash (after a pre-release). The pseudo package implements exactly those rules and its test reuses the reference's example commit; in the lab, pseudoversion printed v0.0.0-20260101100200-cb0c4a0a627a before any tag, v1.2.4-0.20260101100500-5f0f15b598e2 two commits after v1.2.3 and v1.3.0-rc.1.0.20260101100700-f1ce51d7d680 after v1.3.0-rc.1.
  • go get at a tag. go get golang.org/x/text@v0.3.2 (an example from the reference) resolves the tag in the module's repository; @master or @<commit> resolve to a pseudo-version written into go.mod. Tags must be semver with a v prefix, and for a module in a subdirectory the tag carries the path: libs/money/v1.4.0. Modules with major version 2+ need the /v2 path suffix in module and imports.
  • Never move or delete a published tag. "A version identifies an immutable snapshot of a module" (Go Modules Reference); the module proxy caches it and the checksum database records its hash, so a re-pointed tag gives consumers a checksum mismatch (retract in go.mod is the way to withdraw a bad version). Fix forward with a new patch version. Private modules skip the proxy and checksum database with GOPRIVATE=github.com/acme/* and authenticate through Git (SSH or a credential helper with a token).
  • VCS stamping. Since Go 1.18 "the go command now embeds version control information in binaries. It includes the currently checked-out revision, commit time, and a flag indicating whether edited or untracked files are present" (release notes); read it with go version -m ./bin/app or debug.ReadBuildInfo() (vcs.revision, vcs.time, vcs.modified), disable with -buildvcs=false (needed in some CI checkouts without .git). A human version still comes from -ldflags "-X main.version=$(git describe --tags --dirty)".
  • go generate output is committed. The Go blog: "if the containing package is intended for import by go get, once the file is generated (and tested!) it must be checked into the source code repository to be available to clients." Mark such files linguist-generated in .gitattributes, and have CI run go generate ./... && git diff --exit-code to catch stale output.
  • go.sum and merges. go.sum conflicts are resolved by taking either side and running go mod tidy; never hand-edit hashes. The gitattributes.example marks go.sum -diff to keep PR diffs readable.
  • Workspaces in a monorepo. A go.work file at the root lets several modules in one repository use each other without replace directives; teams decide whether to commit it.
  • Modules, versions and the go command in depth are in Toolchain, Modules & Packages; repository layout, golangci-lint and Makefiles in Project Layout, golangci-lint, Makefile, Docker & Multi-Binary Builds.

Laravel ​

Before ​

A deploy that many Laravel projects start with:

bash
ssh deploy@web-1 'cd /var/www/shop && git pull origin main && composer update && php artisan migrate'

It deploys whatever main is at that second (no tag, nothing reproducible), runs composer update on the server (so production gets dependency versions nobody tested, and composer.lock drifts from the repository), keeps a full working copy with .git in the web root, and has no way back except another git pull.

After ​

An Envoy file that deploys a tag, installs exactly what composer.lock says, links the shared .env, and switches a symlink so rollback is instant (Nginx and PHP-FPM serve /var/www/shop/current/public, so the switch is one atomic ln -sfn; reload PHP-FPM if OPcache is configured not to revalidate file timestamps):

php
@servers(['web-1' => ['deploy@10.0.1.11'], 'web-2' => ['deploy@10.0.1.12']])

@setup
    // Deploy a TAG, never a moving branch: the release is reproducible and
    // `git describe` on the server prints exactly what is running.
    if (empty($tag) || ! preg_match('/^v\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$/', $tag)) {
        throw new Exception('Usage: php vendor/bin/envoy run deploy --tag=v1.4.2');
    }
    $repo = 'git@github.com:acme/shop.git';
    $root = '/var/www/shop';
    $release = $root.'/releases/'.$tag;
@endsetup

@story('deploy')
    fetch
    install
    activate
@endstory

@task('fetch', ['on' => ['web-1', 'web-2']])
    set -euo pipefail
    test -d {{ $root }}/repo.git || git clone --bare --filter=blob:none {{ $repo }} {{ $root }}/repo.git
    git --git-dir={{ $root }}/repo.git fetch --tags --force origin
    # Verify the release tag's signature before shipping it (allowed signers on the server).
    git --git-dir={{ $root }}/repo.git verify-tag {{ $tag }}
    rm -rf {{ $release }} && mkdir -p {{ $release }}
    git --git-dir={{ $root }}/repo.git archive {{ $tag }} | tar -x -C {{ $release }}
    git --git-dir={{ $root }}/repo.git describe --tags {{ $tag }} > {{ $release }}/VERSION
@endtask

@task('install', ['on' => ['web-1', 'web-2']])
    set -euo pipefail
    cd {{ $release }}
    # composer.lock is committed: install exactly the locked versions, never update.
    composer install --no-dev --no-interaction --prefer-dist --optimize-autoloader
    ln -sfn {{ $root }}/shared/.env .env
    # git archive unpacked a real storage/ directory: replace it with the shared one
    rm -rf storage && ln -sfn {{ $root }}/shared/storage storage
    php artisan migrate --force --isolated
    php artisan optimize
@endtask

@task('activate', ['on' => ['web-1', 'web-2']])
    set -euo pipefail
    ln -sfn {{ $release }} {{ $root }}/current
    php {{ $root }}/current/artisan queue:restart
@endtask

@task('rollback', ['on' => ['web-1', 'web-2']])
    set -euo pipefail
    # Previous release = the newest directory that is not the current target.
    cur=$(readlink {{ $root }}/current)
    prev=$(ls -1dt {{ $root }}/releases/* | grep -vx "$cur" | head -1)
    ln -sfn "$prev" {{ $root }}/current
    php {{ $root }}/current/artisan queue:restart
@endtask

The CI step that runs on a pushed tag and refuses lightweight tags, tags not on main, and edits to already released migrations:

bash
#!/usr/bin/env bash
# CI step run on a pushed tag (e.g. GitHub Actions `on: push: tags: ['v*']`,
# GitLab `rules: - if: $CI_COMMIT_TAG`): checks, then hands the tag to Envoy.
set -euo pipefail
tag=${1:?usage: ci-release.sh v1.4.2}

# 1. The tag must be annotated and semver; lightweight tags are not releases.
[ "$(git cat-file -t "$tag")" = tag ] || { echo "not an annotated tag: $tag" >&2; exit 1; }
[[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "not semver: $tag" >&2; exit 1; }

# 2. The tag must point at a commit that is on main (released from trunk).
git merge-base --is-ancestor "$tag^{commit}" origin/main || { echo "$tag is not on main" >&2; exit 1; }

# 3. composer.lock must match composer.json (someone edited one without the other).
composer validate --no-check-publish --strict

# 4. Migrations are history: an already-released migration file must never change.
prev=$(git describe --tags --abbrev=0 --match 'v[0-9]*' "$tag^" 2>/dev/null || true)
if [ -n "$prev" ] && git diff --name-only --diff-filter=MD "$prev" "$tag" -- database/migrations | grep -q .; then
  echo "released migrations were modified or deleted since $prev; add a new migration instead" >&2
  exit 1
fi

php vendor/bin/envoy run deploy --tag="$tag"

Run for real against a scratch repository with composer and php stubbed (scripts/14-laravel-release-checks.sh):

text
--- a good release tag: annotated, semver, on main, migrations untouched
$ bash <snippets>/laravel/ci-release.sh v1.1.0
[stub] composer validate --no-check-publish --strict
[stub] php vendor/bin/envoy run deploy --tag=v1.1.0
--- a lightweight tag is refused
not an annotated tag: v1.1.1-light
(exit 1)
--- a tag on a branch that never reached main is refused
v1.2.0 is not on main
(exit 1)
--- editing an already released migration is refused
released migrations were modified or deleted since v1.1.0; add a new migration instead
(exit 1)

The release directory is built with git archive, so it has no .git; the version is written to a VERSION file at deploy time and exposed to php artisan about:

php
<?php

namespace App\Providers;

use Illuminate\Foundation\Console\AboutCommand;
use Illuminate\Support\ServiceProvider;

/**
 * Exposes the deployed git version. The deploy writes `git describe --tags`
 * into a VERSION file inside the release directory, because a release built
 * with `git archive` has no .git directory to ask at runtime.
 */
class ReleaseServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton('release.version', function (): string {
            $file = base_path('VERSION');

            return is_file($file) ? trim((string) file_get_contents($file)) : 'dev';
        });
    }

    public function boot(): void
    {
        // `php artisan about` then shows a "Release" section with the version.
        AboutCommand::add('Release', fn (): array => [
            'Version' => $this->app->make('release.version'),
        ]);
    }
}
ini
# .env.example IS committed: it documents every key with a safe default.
# .env is NOT committed (it is in .gitignore): it holds this machine's secrets.
APP_NAME=Shop
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=shop
DB_USERNAME=shop
DB_PASSWORD=

STRIPE_SECRET=

php -l reports "No syntax errors detected" for ReleaseServiceProvider.php and Envoy.blade.php (PHP on the build host); neither was executed inside a Laravel application, and Envoy was not run against servers.

The Laravel angle ​

  • composer.lock is committed. Composer's docs: "Commit your composer.lock file to version control"; "Committing this file to version control is important because it will cause anyone who sets up the project to use the exact same versions of the dependencies that you are using. Your CI server, production machines, other developers in your team, everything and everyone runs on the same dependencies". Production runs composer install (reads the lock), never composer update. A merge conflict in composer.lock: take one side, re-run the composer require/update that the other branch did, commit.
  • .env is ignored. Laravel's configuration docs: "Your .env file should not be committed to your application's source control, since each developer / server using your application could require a different environment configuration. Furthermore, this would be a security risk in the event an intruder gains access to your source control repository". Commit .env.example with every key and safe defaults; production values live in the server's shared .env or a secret manager.
  • Migrations are history. A migration that already ran in production is part of history like a commit on main: never edit or delete it, add a new one. ci-release.sh enforces this with git diff --diff-filter=MD <previous tag> <tag> -- database/migrations. Parallel branches adding migrations produce two files with different timestamps, not a conflict; check that their order still makes sense after merging.
  • Envoy deploys from tags. Envoy tasks are Blade-templated shell scripts run over SSH ("you may access the options within your tasks using Blade's 'echo' syntax", Envoy docs), so --tag=v1.4.2 becomes the release name, the git archive source and the VERSION file. @story groups tasks; 'parallel' => true runs a task on all servers at once. The same flow works from GitHub Actions or GitLab CI on push: tags, or from a hosted deploy tool (Laravel Forge, Envoyer; their docs were not read for this chapter).
  • Packages and export-ignore. For a Composer package, the dist zip that Composer downloads from GitHub is GitHub's source archive, which honours export-ignore (general knowledge, not from a saved page), so /tests, /.github and phpunit.xml marked export-ignore never reach users' vendor/.
  • Hooks for PHP. The pre-commit config runs php -l on staged PHP files; teams add Laravel Pint (vendor/bin/pint --test) and PHPStan the same way, and run them again in CI because hooks are optional.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Last commit has a typo or a missing file (not pushed)Amendgit add f; git commit --amend --no-editOne clean commitRewrites the tip; never on pushed shared commits
Committed to main instead of a branchMove the commitsgit branch feat; git reset --hard origin/main; git switch featNothing lostOnly before pushing main
"I lost my work after reset/rebase"Refloggit reflog, git branch rescue HEAD@{n}Recovers any recent commitOnly commits; uncommitted edits are gone
A pushed commit broke productionRevertgit revert <id> (merge: -m 1), pushHistory intact, safe for everyoneThe revert must be reverted to re-apply
A regression somewhere in 300 commitsBisectgit bisect start bad good; git bisect run ./test.shlog2(300) ≈ 9 test runsNeeds a scriptable test
A 3,000-line PR nobody reviewsStacked PRsSplit into dependent branches, rebase --update-refsReal reviews, earlier mergesTooling and discipline
Same conflicts on every rebase of a long branchrerere, then shorter branchesrerere.enabled=trueResolve onceTreats the symptom; integrate more often
A secret was pushedRotate, rewrite, preventRevoke; git-filter-repo --sensitive-data-removal; push protectionKey useless, history cleanEvery clone must re-clone; forks keep it
CRLF/LF diffs in every PRAttributes* text=auto eol=lf, git add --renormalize .Consistent everywhereOne noisy normalisation commit
Clone of the monorepo takes 20 minutesPartial + sparse--filter=blob:none, sparse-checkout set --coneMinutes, small diskNeeds server filter support; lazy fetches
Need to fix production while mid-featureWorktreegit worktree add ../hotfix -b hotfix origin/mainNo stash jugglingExtra checkout on disk
Unreadable history of "fix", "wip", "asdf"Conventions + squash or autosquashConventional Commits + commitlint; squash merge or rebase -i --autosquashChangelogs, bisectable mainSquash loses intermediate steps

Undo the last commit, keep the changes ​

bash
git reset --soft HEAD~1     # changes stay staged; re-commit differently
git reset HEAD~1            # (--mixed) changes stay in the working tree, unstaged
git commit --amend          # or: replace the last commit with the current index

Bring a feature branch up to date before review ​

bash
git fetch origin
git rebase -i --autosquash origin/main        # replay on the latest main, fold fixup! commits
go test ./... && php artisan test             # prove it still works after the replay
git push --force-with-lease --force-if-includes

Split one commit into two ​

bash
git rebase -i HEAD~3          # mark the commit "edit"
git reset HEAD~1              # undo it, keep the changes in the working tree
git add -p && git commit -m "refactor(cart): extract Total"
git add -A && git commit -m "feat(cart): coupons"
git rebase --continue

Choosing ​

Merge, rebase or squash ​

SituationRecommendationExtra techniqueReason
Updating your own feature branchRebase on origin/main--autosquash, --update-refsClean, linear, no merge noise
Integrating a PR, team values one commit per changeSquash mergeConventional Commit PR titlemain reads like a changelog; bisect per PR
Integrating a PR whose commits are each meaningfulRebase merge (or merge commit)Required linear historyKeeps the steps
Integrating a long-lived or shared branchMerge commit--no-ff, rerereNever rewrites commits others have
Release branch back into mainMerge commitcherry-pick -x for single fixesHotfix ids stay stable
Branch shared by two peopleMerge, not rebaseAgree who integratesRebase would replace commits the other has
Stacked PRsRebase with --update-refs; avoid squash or retarget after each squashGraphite, ghstackSquash breaks the ancestry of the next PR

Which branching strategy ​

Team / productStrategyRelease mechanismMust have
Web service, continuous deliveryTrunk-based + GitHub Flow PRsTag on main, deploy on mergeFeature flags, fast CI, required checks
Several environments promoted manuallyGitLab Flow with environment branches (or GitOps folders)Merge main → pre-production → productionUpstream-first rule
Versioned product with supported versionsRelease branches (GitLab Flow release or git-flow)Tag on release/x.yCherry-pick discipline, backport labels
Open-source libraryGitHub Flow + semver tagsSigned annotated tagsChangelog, CI matrix
Mobile app with store reviewTrunk-based + short release branchesBranch per store submissionHotfix path off the release branch

Submodule, subtree, package or monorepo ​

NeedChoiceWhy
Share a versioned library between servicesPackage manager (Go modules, Composer)Versions, lock files, tooling everyone knows
Pin an external repository you do not control, exact commitSubmoduleReproducible pointer, small parent repo
Vendor code you will patch locally, consumers should not careSubtreeNo extra commands for consumers
Change an API and all callers atomically, one CIMonorepo with partial clone + sparse-checkoutOne commit across services
Independent teams, independent release cadencesPolyrepo with packagesClear ownership, smaller blast radius

Hosting ​

NeedChoiceNote
Integrated PRs, Actions, large ecosystemGitHubRulesets, CODEOWNERS, push protection, merge queue
Integrated CI/CD, self-managed option, MR approvalsGitLabProtected branches, approval rules, merge trains
Small self-hosted, low resourcesGitea / ForgejoPull requests, Actions-compatible runners
SHA-256 repositories, full controlSelf-hosted (bare repositories over SSH, or a forge that supports them)Check SHA-256 support before choosing
Air-gapped mirrorgit clone --mirror + scheduled fetchRead-only copy for builds

In architecture: from a single process to a distributed system ​

Monolith: one repository, one deployable ​

A Laravel shop is one repository: app/, database/migrations/, resources/, composer.lock, .env.example, CI in .github/workflows/. Git's job is simple and strict: main is protected, PRs are squash-merged with Conventional Commit titles, releases are signed annotated tags (v2.14.0), Envoy deploys the tag. The migration list is the schema's history and is append-only. One CODEOWNERS file gives database/migrations/ to the DBA reviewers. The simplest correct setup: trunk-based development, required checks (test, lint, commitlint), linear history.

Modular monolith: one repository, owned directories ​

The shop grows modules (modules/Billing, modules/Catalog, modules/Checkout). The repository stays one, but ownership moves into CODEOWNERS (/modules/Billing/ @acme/payments), path-filtered CI jobs (on: pull_request: paths: ['modules/Billing/**']) and architecture tests that fail a PR when Checkout imports Billing internals. History tools become per-module: git log -- modules/Billing, git shortlog -sn -- modules/Billing for "who owns this really", git blame -w -C across moved files when code changes module. A shared libs/money directory has the strictest owners because every module depends on it.

Microservices: many repositories or a monorepo ​

Ten Go services and the Laravel storefront. Option A, polyrepo: each service has its own repository, tags (orders/v1.8.0 style tags only matter for Go modules in subdirectories; separate repositories just tag v1.8.0), pipeline and owners; shared contracts (protobuf, OpenAPI) live in a contracts repository consumed as a Go module and a Composer package at pinned versions. A cross-service change becomes a sequence of PRs: 1) contracts v1.5.0 adds the field, 2) the producer service starts filling it, 3) consumers read it, 4) a later contracts major removes the old field; Git cannot make that atomic, so each step must be backward compatible (expand and contract, see Deployment Strategies). Option B, monorepo: one PR changes the contract and all services; CI computes affected services from git diff --name-only origin/main...HEAD and builds only those; developers use --filter=blob:none and cone sparse-checkout of their service plus libs/. Either way, the deployable unit is an immutable tag or commit id that the CI/CD pipeline turns into an image tag (orders:1.8.0 and orders:sha-5f0f15b) that Docker builds and Kubernetes nodes pull through containerd; the Helm chart and the Terraform module that deploy it are versioned in Git the same way, with their own semver tags.

1  PR #120 in contracts: add Order.currency (optional)           -> tag contracts v1.5.0
2  PR #341 in orders:    go get .../contracts@v1.5.0, fill currency -> tag orders v1.8.0 -> deploy
3  PR #88  in storefront: composer require acme/contracts:^1.5, read currency -> tag v2.15.0 -> deploy
4  (months later) contracts v2.0.0 makes currency required; every consumer already sends it

Distributed data: replicas, mirrors, caches and GitOps ​

Git itself is a distributed database with eventual consistency between clones and one convention for the truth (the protected branch on the host). At scale the host itself is replicated (GitLab's Gitaly Cluster and Geo secondary sites are examples; general knowledge, not from a saved page), CI runners keep caches of .git that are stale by design and must fetch before trusting origin/main, and read-only mirrors serve builds near the runners. Where Git's model breaks: there are no cross-repository transactions (the microservice sequence above), no locks (two people editing a binary asset need LFS file locking), and a fetched ref is only as fresh as the fetch (the --force-with-lease trap). GitOps uses a Git repository as the desired state of a cluster: Argo CD or Flux poll or receive a webhook, compare the commit with the live cluster and reconcile; Git's audit trail, signed commits and protected branches become the change-control system for production, and reverting a commit is the rollback.

Scaling path: 1x, 10x, 100x ​

ScaleRepository shapeWhat changes in Git usage
1x (one team, one app)One repository, GitHub FlowProtected main, required checks, squash merges, signed tags
10x (several teams, modules or 10 services)Modular monolith or a few repositoriesCODEOWNERS per directory, path-filtered CI, merge queue, release automation from Conventional Commits, pre-commit everywhere
100x (hundreds of engineers, large monorepo or hundreds of repos)Monorepo with partial clone or polyrepo with a platformgit maintenance start, blobless clones, cone sparse-checkout, build-graph tools (Bazel), affected-target CI, rulesets at organisation level, server-side secret scanning, automated dependency PRs

Lab ​

Labelling: every numbered step marked "(ran)" was run on the build host (macOS, Git 2.54.0 Apple Git-157, OpenSSH ssh-keygen, Go 1.27.4, PHP for php -l) from docs/snippets/platform/git-version-control/, with W35_WORK pointing at an empty scratch directory outside any Git repository. scripts/lib.sh refuses to run when that directory is inside a repository, sets GIT_CEILING_DIRECTORIES, isolates configuration (HOME, GIT_CONFIG_GLOBAL, GIT_CONFIG_NOSYSTEM) and fixes identities and the clock, so the ids in the transcripts are reproducible: a second full run in a fresh directory produced byte-identical transcripts for 13 of 14 scripts (the SSH-signing one differs because it generates a new key). Transcripts: pipeline/sources/git-version-control/runs/. Nothing needs network access, root or Docker.

1. Run everything (ran) ​

bash
cd docs/snippets/platform/git-version-control
export W35_WORK=$(mktemp -d)          # must be outside any git repository
bash scripts/run-all.sh /tmp/w35-runs
text
01-object-model                  exit 0, 137 lines
02-three-areas                   exit 0, 63 lines
03-merge-vs-rebase               exit 0, 171 lines
04-conflicts-rerere              exit 0, 77 lines
05-undo-reflog                   exit 0, 72 lines
06-bisect-blame-log              exit 0, 70 lines
07-worktree-stash                exit 0, 49 lines
08-monorepo-partial-clone        exit 0, 28 lines
09-tags-describe-release         exit 0, 70 lines
10-ssh-signing                   exit 0, 36 lines
11-submodule-subtree             exit 0, 43 lines
12-ignore-attributes             exit 0, 49 lines
13-hooks-secrets                 exit 0, 46 lines
14-laravel-release-checks        exit 0, 21 lines

The shared library every script sources:

bash
#!/usr/bin/env bash
# Shared setup for every demo script in this directory.
# Usage: W35_WORK=/some/empty/scratch/dir bash scripts/01-object-model.sh
# The work directory must NOT be inside any git repository: the guard below
# refuses to run otherwise, so a demo can never touch a real project.
set -euo pipefail

: "${W35_WORK:?set W35_WORK to a scratch directory outside any git repository}"
mkdir -p "$W35_WORK"
W=$(cd "$W35_WORK" && pwd -P)

# Guard 1: the scratch directory itself must not be inside a repository.
if git -C "$W" rev-parse --git-dir >/dev/null 2>&1; then
  echo "refusing: $W is inside a git repository" >&2
  exit 2
fi
# Guard 2: repository discovery never walks above the scratch directory.
export GIT_CEILING_DIRECTORIES="$W"

# Isolate configuration: no system or user config, no credential helpers,
# no signing keys or aliases from the machine leak into the demo.
mkdir -p "$W/home"
export HOME="$W/home"
export GIT_CONFIG_NOSYSTEM=1
export GIT_CONFIG_GLOBAL="$W/home/gitconfig"
: > "$GIT_CONFIG_GLOBAL"
git config --global init.defaultBranch main
git config --global advice.detachedHead true
git config --global color.ui false
git config --global core.pager cat
export GIT_EDITOR=true GIT_PAGER=cat PAGER=cat TZ=UTC LC_ALL=C

# Reproducible hashes: fixed identities and a clock that only moves when we say so.
export GIT_AUTHOR_NAME="Ada Dev" GIT_AUTHOR_EMAIL="ada@example.com"
export GIT_COMMITTER_NAME="Ada Dev" GIT_COMMITTER_EMAIL="ada@example.com"
T=1767261600 # 2026-01-01 10:00:00 UTC
tick() {
  T=$((T + 60))
  export GIT_AUTHOR_DATE="$T +0000" GIT_COMMITTER_DATE="$T +0000"
}
tick

# as_bob: run one git command as a second developer.
as_bob() {
  GIT_AUTHOR_NAME="Bob Ops" GIT_AUTHOR_EMAIL="bob@example.com" \
    GIT_COMMITTER_NAME="Bob Ops" GIT_COMMITTER_EMAIL="bob@example.com" "$@"
}

# fresh <name>: create an empty repository under the scratch dir and cd into it.
fresh() {
  rm -rf "${W:?}/$1"
  git init -q "$W/$1"
  cd "$W/$1" || exit 1
}

# commit_file <file> <content> <message>: write, stage and commit in one step.
commit_file() {
  mkdir -p "$(dirname "$1")"
  printf '%s\n' "$2" > "$1"
  git add "$1"
  tick
  git commit -q -m "$3"
}

# say <text>: a visible section header in the transcript.
say() { printf '\n--- %s\n' "$*"; }

# run <cmd...>: echo the command, then run it; the transcript shows both.
run() {
  local a q line='$'
  for a in "$@"; do
    case "$a" in
      *\'*) # contains a single quote: show it double-quoted
        q=${a//\\/\\\\}; q=${q//\"/\\\"}; q=${q//\$/\\\$}; q=${q//\`/\\\`}
        line="$line \"$q\"" ;;
      *[[:space:]\"\$\*\?\;\|\&\<\>\(\)\^\{\}\[\]]*) line="$line '$a'" ;;
      *) line="$line $a" ;;
    esac
  done
  printf '%s\n' "${line//$W/\$W}"
  "$@"
}

# hide_work: replace the absolute scratch path with $W in output.
hide_work() { sed "s|$W|\$W|g"; }

# try <cmd...>: like run, but a failure is shown as "(exit N)" instead of stopping the demo.
try() {
  local rc=0
  run "$@" 2>&1 || rc=$?
  if [ "$rc" -ne 0 ]; then echo "(exit $rc)"; fi
}
bash
#!/usr/bin/env bash
# Run every demo and save one transcript per script.
# Usage: W35_WORK=/tmp/w35 bash scripts/run-all.sh <output-dir>
# Absolute paths of the snippet directory are shown as <snippets> and the
# scratch directory as $W, so transcripts do not depend on the machine.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd -P)
snip=$(cd "$here/.." && pwd -P)
out=${1:?usage: run-all.sh <output-dir>}
mkdir -p "$out"
for s in "$here"/[0-9][0-9]-*.sh; do
  name=$(basename "$s" .sh)
  rc=0
  bash "$s" > "$out/$name.raw" 2>&1 || rc=$?
  sed "s|$snip|<snippets>|g" "$out/$name.raw" > "$out/$name.txt"
  rm -f "$out/$name.raw"
  printf '%-32s exit %d, %d lines\n' "$name" "$rc" "$(wc -l < "$out/$name.txt")"
done
bash
#!/usr/bin/env bash
# Runs laravel/ci-release.sh against a scratch Laravel-shaped repository with
# composer and php stubbed on PATH (no Composer, no Envoy, no servers needed).
source "$(dirname "$0")/lib.sh"
SNIP=$(cd "$(dirname "$0")/.." && pwd -P)
mkdir -p "$W/home/stubs"
printf '#!/bin/sh\necho "[stub] composer $*"\n' > "$W/home/stubs/composer"
printf '#!/bin/sh\necho "[stub] php $*"\n' > "$W/home/stubs/php"
chmod +x "$W/home/stubs/composer" "$W/home/stubs/php"
export PATH="$W/home/stubs:$PATH"

cd "$W" && rm -rf shop.git && git init -q --bare shop.git
fresh shop
git remote add origin "$W/shop.git"
mkdir -p database/migrations
commit_file composer.json '{"name": "acme/shop"}' "chore: init"
commit_file database/migrations/2026_01_01_000000_create_orders_table.php '<?php // create orders' "feat: orders table"
tick; git tag -a v1.0.0 -m "v1.0.0"
commit_file app.txt 'feature' "feat: checkout"
tick; git tag -a v1.1.0 -m "v1.1.0"
git tag v1.1.1-light
git push -q origin main --tags
git fetch -q origin

say "a good release tag: annotated, semver, on main, migrations untouched"
try bash "$SNIP/laravel/ci-release.sh" v1.1.0
say "a lightweight tag is refused"
try bash "$SNIP/laravel/ci-release.sh" v1.1.1-light
say "a tag on a branch that never reached main is refused"
git switch -q -c experiment
commit_file x.txt 'x' "feat: experiment"
tick; git tag -a v1.2.0 -m "v1.2.0"
git switch -q main
try bash "$SNIP/laravel/ci-release.sh" v1.2.0
say "editing an already released migration is refused"
commit_file database/migrations/2026_01_01_000000_create_orders_table.php '<?php // create orders, edited' "fix: edit old migration"
tick; git tag -a v1.3.0 -m "v1.3.0"
git push -q origin main --tags
git fetch -q origin
try bash "$SNIP/laravel/ci-release.sh" v1.3.0

2. Build the object graph by hand (ran) ​

bash scripts/01-object-model.sh: compare your ids with Objects. Then answer from the output alone: which tree do both commits share, and why does v0.1.0 resolve to two different ids with and without ^{commit}?

3. Merge, rebase, lease (ran) ​

bash scripts/03-merge-vs-rebase.sh: the four history shapes, --onto, --update-refs, autosquash, and the three push outcomes (stale info, the dry-run forced update, remote ref updated since checkout).

4. Break things and recover (ran) ​

bash scripts/04-conflicts-rerere.sh && bash scripts/05-undo-reflog.sh: three index stages, zdiff3 markers, rerere replay, every reset mode, reflog rescue of a commit and a branch, revert, and a dangling commit found by fsck.

5. Find the bad commit (ran) ​

bash scripts/06-bisect-blame-log.sh: bisect run finds 2390d1f in three steps; blame -w -C -C attributes the moved line to its original commit and file; log -S finds the commit that added the key and the one that removed it.

6. Large repositories (ran) ​

bash scripts/08-monorepo-partial-clone.sh: 17 missing blobs after the blobless clone, 12 after a two-directory cone sparse-checkout, .git 728 KB instead of 2,464 KB.

7. Releases, signing, hooks, Laravel checks (ran) ​

bash scripts/09-tags-describe-release.sh && bash scripts/10-ssh-signing.sh && bash scripts/13-hooks-secrets.sh && bash scripts/14-laravel-release-checks.sh. The Go module tests:

bash
cd go && gofmt -l . && go vet ./... && go test -race -count=1 ./...   # transcript: runs/go-checks.txt
text
$ gofmt -l .
$ go vet ./...
$ go test -race -count=1 ./...
ok  	academy/git-version-control/cmd/commitlint	1.427s
?   	academy/git-version-control/cmd/pseudoversion	[no test files]
ok  	academy/git-version-control/commitlint	1.424s
ok  	academy/git-version-control/pseudo	1.424s

8. Tools not installed on the build host (expected, not run) ​

bash
# GPG signing: same flow as SSH signing with gpg.format=openpgp
gpg --quick-generate-key "Ada Dev <ada@example.com>" ed25519 sign never
git config gpg.format openpgp && git config user.signingkey <KEYID>
git commit -S -m "feat: gpg-signed"            # expected: git log --format=%G? prints G
# Git LFS
git lfs install && git lfs track "*.psd" && git add .gitattributes design.psd && git commit -m "build: track psd in LFS"
git show HEAD:design.psd                        # expected: the three-line pointer (version / oid sha256:... / size ...)
# pre-commit framework
pip install pre-commit && cp config/pre-commit-config.yaml .pre-commit-config.yaml && pre-commit install --hook-type pre-commit --hook-type commit-msg
pre-commit run --all-files                      # expected: each hook prints Passed / Failed
# git filter-repo
git-filter-repo --sensitive-data-removal --replace-text ../passwords.txt   # expected: history rewritten, git log -S finds nothing

9. Hosting-side steps (expected, not run) ​

hosting/protect-branches.sh creates the GitHub ruleset from github-ruleset.json, restricts merge methods to squash, and protects main on a GitLab instance; it needs admin tokens that do not exist in the build environment. Expected result: a push to main is rejected by the host, a PR without an approval from @acme/checkout (CODEOWNERS) or without green test, lint and commitlint checks cannot be merged.

Common misconceptions ​

BeliefReality
Git stores diffs between versionsIt stores snapshots (blobs and trees); packfiles delta-compress similar objects underneath
A branch is a sequence of commitsA branch is a pointer to one commit; history is what its parents reach
git reset --hard deletes commitsIt moves a pointer; commits stay in the reflog for 30-90 days; only uncommitted edits are destroyed
Rebase moves commitsIt creates new commits with new ids and abandons the old ones
.gitignore removes a file from the repositoryIt hides untracked files only; tracked files need git rm --cached, and history keeps old versions
Deleting a leaked secret in a new commit fixes the leakThe secret stays in history and in every clone; rotate it, then rewrite
--force-with-lease cannot overwrite others' workA fetch updates the lease; add --force-if-includes
Hooks enforce policy--no-verify skips client hooks; enforcement is server-side (rulesets, required checks, push protection)
The author field proves who wrote a commitIt is free text; only a verified signature ties a commit to an account
Squash merge "merges" the branchIt makes a new unrelated commit; the branch is not an ancestor of main
Sparse-checkout makes clones smallOnly together with partial clone (--filter=blob:none)
Trunk-based development means no code reviewShort-lived branches with PRs and required checks are trunk-based; long-lived branches are what it forbids
git pull is safe and simpleIt is fetch + merge (or rebase) into your current branch; know which one pull.rebase selects
A lightweight tag is fine for releasesIt has no tagger, date, message or signature and is ignored by plain git describe and --follow-tags

Cheat sheet ​

TopicRemember
Objectsblob (content), tree (names), commit (tree + parents + who + why), tag (named, signed pointer); id = hash of type size\0content
Inspectgit cat-file -t/-p, git ls-tree -r, git rev-parse, git log --oneline --graph --all
Three areasadd → index → commit; diff = unstaged, diff --staged = to be committed; add -p for partial
Messagestype(scope)!: description, body explains why, trailers last; --fixup + rebase -i --autosquash
Signinggpg.format=ssh, user.signingkey, commit.gpgSign=true; verify with allowedSignersFile; "Verified" on the host
MergeFast-forward if possible; --no-ff to record the branch; ort is the default; conflicts = stages 1/2/3
RebaseNew commits; --onto to transplant; --update-refs for stacks; never on commits others have
Push after rewrite--force-with-lease --force-if-includes, own branches only
Undorestore (files), reset --soft/--mixed/--hard (local commits), revert (shared), reflog (rescue)
Findbisect run, blame -w -C -C, log -S (string count), log -G (regex in diff), log -L
Parallel workworktree add for a second checkout; stash -u for a quick switch
ReleasesAnnotated or signed tags, semver, describe --tags --dirty, versionsort.suffix=-rc
Big repos--filter=blob:none + sparse-checkout set --cone; LFS for big binaries; git maintenance start
Security.env ignored, secret scan in pre-commit and on the server, rotate first, git-filter-repo second
GoPseudo-versions = base + UTC commit time + 12-char hash; never move a published tag; commit go generate output
LaravelCommit composer.lock, ignore .env, migrations are append-only, deploy tags with Envoy

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What exactly is a commit in Git, and what makes its id change? Must-know ​

Answer

Answer: A commit object is a small text object with one tree id (the full snapshot), zero or more parent ids, author and committer lines with timestamps, an optional gpgsig signature and the message. Its id is the hash of exactly those bytes, so changing any file (new blob, new tree), the parent, the dates, the message or the signature produces a different id. That is why amend and rebase always create new commits (Objects).

2 — What is the difference between git diff, git diff --staged and git diff HEAD? Must-know ​

Answer

Answer: git diff compares the working tree with the index (what you have not staged), git diff --staged compares the index with HEAD (what the next commit will contain), and git diff HEAD compares the working tree with the last commit (everything). After git add -p of one hunk, the first shows the remaining hunk and the second the staged one (The three areas).

3 — When does git merge fast-forward, and why would a team pass --no-ff? Must-know ​

Answer

Answer: It fast-forwards when the current branch's tip is an ancestor of the branch being merged, so no new snapshot is needed: the ref just moves. --no-ff forces a merge commit anyway, which records that the commits came in as one branch and lets git log --first-parent and git revert -m 1 treat the feature as one unit (Merging).

4 — You rebased your feature branch and git push is rejected. What do you run, and why not --force? Must-know ​

Answer

Answer: git push --force-with-lease --force-if-includes. A rebase replaces commits, so the push is not a fast-forward and must be forced; plain --force would also delete any commit a teammate pushed meanwhile. The lease refuses when the remote differs from your last fetched value, and --force-if-includes additionally refuses when you fetched but did not integrate the new tip, which closes the background-fetch hole (Rewriting shared history).

5 — You ran git reset --hard HEAD~3 by mistake. How do you get the commits back, and what is truly lost? Must-know ​

Answer

Answer: git reflog shows the previous tip as HEAD@{1}; git reset --hard HEAD@{1} (or git branch rescue HEAD@{1}) restores it. The commits were never deleted, only unreferenced, and the reflog keeps them for 30 days by default when unreachable. What is lost is any uncommitted change in the working tree or index at the time of the reset, because it was never stored as a commit (Undoing things).

6 — Merge, rebase merge or squash merge for pull requests: how do you choose? Important ​

Answer

Answer: Squash when PRs are small and you want one commit per change on main (readable, bisectable per PR), at the cost of losing intermediate commits and breaking stacked branches. Rebase merge when each commit in the PR is meaningful and you want a linear history. Merge commits when branches are long-lived or shared, because nothing is rewritten and the branch structure stays visible. Enforce the choice in the host settings and with required linear history if you pick squash or rebase (Choosing).

7 — A Stripe live key was pushed to main ten minutes ago. Walk through the response. Must-know ​

Answer

Answer: First rotate: revoke the key at the provider and issue a new one into the secret store, because every clone, fork and CI cache already has it. Then clean history with git-filter-repo --sensitive-data-removal --replace-text on a fresh clone, force-push all refs, ask collaborators to re-clone and ask the host to purge cached pull request refs. Finally prevent a repeat: .env in .gitignore, a pre-commit secret scan and server-side push protection. A follow-up commit that deletes the file does not remove the key from history (Security).

8 — What do the three parts of v1.2.3-2-g5f0f15b from git describe mean, and how would Go name the same commit? Important ​

Answer

Answer: Nearest annotated tag v1.2.3, 2 commits since that tag, and g plus the abbreviated commit id 5f0f15b. Go names the untagged commit with a pseudo-version: the next patch as base (v1.2.4-0.), the UTC commit time (20260101100500) and a 12-character hash prefix, giving v1.2.4-0.20260101100500-5f0f15b598e2 in the lab (Tags, Go).

9 — Compare trunk-based development, GitHub Flow, GitLab Flow and git-flow in one sentence each. Important ​

Answer

Answer: Trunk-based development keeps one long-lived branch, merges short-lived branches within about a day or two and hides unfinished work behind feature flags. GitHub Flow is that with a pull request per change and deployment from main. GitLab Flow adds downstream environment or release branches that only receive changes from main (upstream first). git-flow keeps develop plus main and uses release and hotfix branches; its author now recommends a simpler flow for continuously delivered software (Branching strategies).

10 — Why do hooks not enforce anything, and what does? Important ​

Answer

Answer: Client hooks live in each clone, are opt-in (core.hooksPath or the pre-commit framework, since .git/hooks is never cloned) and pre-commit, commit-msg and pre-push are skipped by --no-verify. They give fast feedback. Enforcement happens on the server: protected branches or rulesets, required status checks that re-run the same linters, required signed commits, CODEOWNERS review and push protection or secret detection (Hooks).

11 — Your monorepo clone is 8 GB and takes 20 minutes. What do you change for developers and for CI? Good to know ​

Answer

Answer: Developers: git clone --filter=blob:none (all commits and trees, blobs on demand) plus git sparse-checkout set --cone <their directories>, and git maintenance start for background prefetch and commit-graph. CI: a blobless or, for throwaway jobs, shallow clone (--depth=1, knowing it breaks describe and merge-base), cached between jobs, plus affected-target builds from git diff --name-only. Large binaries move to Git LFS (Monorepos).

12 — Submodule or subtree for sharing a library between two applications? Good to know ​

Answer

Answer: A submodule records a pinned commit (a gitlink) plus .gitmodules; it is exact and small but every consumer must init and update it, and bumps are explicit commits. A subtree copies the files (optionally squashed) into a directory, so consumers need nothing special, but history grows and contributing back needs subtree split. For Go and PHP code, a versioned package (Go module, Composer package) is usually better than either (Submodules and subtrees).

13 — Why must composer.lock be committed while .env must not be? Important ​

Answer

Answer: composer.lock records the exact dependency versions; committing it means CI, production and every developer install the same code, and production runs composer install, never update. .env holds per-environment configuration and secrets; Laravel's docs say it "should not be committed" because environments differ and a leaked repository would expose credentials. Commit .env.example with the keys and safe defaults instead (Laravel).

14 — What do the GitHub "Verified" badge and git log --format=%G? tell you, and what do they not? Good to know ​

Answer

Answer: "Verified" means the commit or tag carries a GPG, SSH or S/MIME signature that GitHub verified against a key on the account; %G? prints G for a good signature locally (N none, B bad, E cannot check). They do not say the code is correct or reviewed, and without vigilant mode an unsigned commit shows no badge at all, so "no badge" is not "forged". Requiring signed commits on protected branches turns the badge into a rule (Commits, Security).

Glossary ​

TermMeaning
.gitattributesVersioned file assigning attributes (text/eol, binary, filter, export-ignore, linguist) to paths
.gitignoreVersioned file listing patterns of untracked files Git should not show or add
composer.lockComposer's lock file with exact dependency versions; committed so every install is identical
git add -pPatch mode: stage selected hunks of a file
git cat-filePrint an object's type (-t), size (-s) or content (-p)
git describeName a commit as nearest annotated tag + commits since + g<abbrev id>
git diff --stagedCompare the index with HEAD (synonym --cached)
git hash-objectCompute an object id for content; -w writes the object
git resetMove the current branch; --soft, --mixed (default), --hard decide what else is reset
git restoreRestore working-tree files from the index, or the index from HEAD (--staged)
git revertCreate a commit that inverts an earlier commit
annotated tagA tag object with tagger, date, message and optional signature; used for releases
autosquashrebase -i --autosquash: moves fixup!/squash! commits under their targets and melds them
autocrlfcore.autocrlf: per-user line-ending conversion (true, input, false); superseded by .gitattributes
bisectgit bisect: binary search over history for the first bad commit; run automates it
blamegit blame: last commit per line; -w ignores whitespace, -C follows moved/copied code
blobObject holding one file's bytes, without name or mode
CODEOWNERSFile mapping paths to required reviewers on GitHub and GitLab; last matching pattern wins
commit objectObject with tree, parents, author, committer, optional signature and message
commit trailersToken: value lines at the end of a message (Refs:, Co-authored-by:, BREAKING CHANGE:)
Conventional CommitsMessage convention type(scope)!: description mapping to semver bumps
credential helpercredential.helper: program that stores and supplies HTTPS credentials (keychain, GCM, libsecret)
detached HEADHEAD containing a commit id instead of a branch name
EnvoyLaravel's SSH task runner; tasks are Blade-templated shell scripts (Envoy.blade.php)
EOLEnd of line: LF (\n) or CRLF (\r\n); controlled by the eol and text attributes
export-ignoreAttribute that leaves a path out of git archive output
fast-forwardIntegration that only moves a ref because the target is an ancestor of the source
feature flagsRuntime switches that hide unfinished code merged to trunk (feature toggles)
fixupgit commit --fixup=<c>: a commit meant to be melded into <c> by autosquash
force-with-leaseForced push that succeeds only if the remote ref still has the expected value
GitHub Flowmain always deployable; a branch and pull request per change
git-flow2010 model with develop, main, feature, release and hotfix branches
git filter-repoTool that rewrites history (remove paths, replace text); GitHub's recommended way to purge secrets
GitLab FlowFeature branches into main plus downstream environment or release branches; fixes flow from main downstream
Git LFSLarge File Storage: pointer files in Git, content on an LFS server
git maintenanceBackground or on-demand repository optimisation tasks (commit-graph, prefetch, repack, gc)
GPGGNU Privacy Guard; OpenPGP signing for commits and tags (gpg.format=openpgp)
HEADThe current commit, usually via a symbolic ref to a branch
hooksScripts Git runs at defined events (pre-commit, commit-msg, pre-push, server-side pre-receive)
index / staging area.git/index: the snapshot the next commit will record
interactive rebaserebase -i: edit a todo list of pick/reword/edit/squash/fixup/drop/exec
lightweight tagA ref pointing straight at a commit, with no tag object
merge baseBest common ancestor of two commits; the base of a three-way merge
merge conflictOverlapping changes the merge cannot combine; stages 1/2/3 in the index
merge requestGitLab's name for a pull request
monorepoOne repository holding many projects or services
--no-ffMerge option that always creates a merge commit
--ontoRebase option to replay a range onto a different base
originConventional name of the remote you cloned from
ort strategyGit's default two-head merge strategy since 2.34 ("Ostensibly Recursive's Twin")
packfileCompressed file of many objects with delta compression and an index
partial cloneClone with an object filter (--filter=blob:none); missing objects fetched on demand from a promisor remote
personal access tokenToken used instead of a password for HTTPS Git and API access (fine-grained or classic on GitHub)
pickaxegit log -S (and -G): search history for added or removed strings
pre-commitThe hook that runs before a commit, and the framework (pre-commit.com) that manages such hooks
protected branchesHost rules that restrict pushes, force pushes and merges on chosen branches
pseudo-versionGo version for an untagged commit: base + UTC commit time + 12-char hash (go.mod)
pull requestHost review object proposing to merge one branch into another
rebaseReplay commits on a new base, creating new commits
rebase mergeHost merge method that replays PR commits onto the base without a merge commit
reflogLocal log of every value of HEAD and each branch; basis of reflog recovery
refsNamed pointers to objects: branches, tags, remote-tracking branches
release branchBranch cut to stabilise or maintain a released version
remoteNamed URL of another repository (origin, upstream)
required checksCI statuses that must pass before a protected branch accepts a merge
rerere"Reuse recorded resolution": replays previous conflict resolutions
rewriting historyAny operation that replaces commits (amend, rebase, filter-repo)
semverSemantic Versioning: MAJOR.MINOR.PATCH with pre-release suffixes
SHA-1 / SHA-256Object hash functions; SHA-1 default, SHA-256 via --object-format=sha256, not interoperable
signed commitsCommits carrying a GPG, SSH or S/MIME signature in a gpgsig header
sparse-checkoutChecking out only some directories (cone mode)
squash mergeHost merge method creating one new commit from all PR changes
SSH signingSigning with an SSH key (gpg.format=ssh, Git 2.34+)
SSH vs HTTPSThe two Git transports: key-based SSH or token-based HTTPS
stacked PRsDependent pull requests built on each other's branches
stashSaved uncommitted changes (refs/stash)
submoduleGitlink (mode 160000) plus .gitmodules pointing at a commit of another repository
subtreeAnother project's files merged into a subdirectory (git subtree)
tag objectObject naming another object with tagger, message and optional signature
three-way mergeMerge using the merge base and both tips
treeObject listing names, modes and ids of blobs and subtrees
trunk-based developmentAll work integrates into one trunk via very short-lived branches
upstreamRemote of the original project when origin is a fork; also a branch's configured tracking branch
--update-refsRebase option that moves every branch pointing into the rebased range
verified badgeGitHub/GitLab mark for a commit or tag with a verified signature
working treeThe checked-out files on disk
worktreeAn extra working tree attached to the same repository (git worktree)

References ​

Every page below was fetched and saved under pipeline/sources/git-version-control/ (manifest.tsv lists URL, HTTP status and file).

Built by Morteza Negahi