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 for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why version control, why Git won, the analogy | Why 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-object | Objects |
| refs, HEAD, detached HEAD, reflog | Refs, HEAD and the reflog |
| packfile, SHA-1, SHA-256, git maintenance | Packfiles, hashes, maintenance |
| working tree, index, staging area, git add -p, git diff --staged | The three areas |
| Conventional Commits, commit trailers, signed commits, SSH signing, GPG | Commits and messages |
| fast-forward, three-way merge, ort strategy, --no-ff | Merging |
| merge conflict, rerere | Conflicts and rerere |
| rebase, interactive rebase, --onto, --update-refs, fixup, autosquash | Rebase |
| rewriting history, force-with-lease | Rewriting shared history |
| trunk-based development, GitHub Flow, GitLab Flow, git-flow, release branch, feature flags | Branching strategies |
| pull request, merge request, stacked PRs, squash merge, rebase merge, protected branches, required checks, CODEOWNERS | Pull and merge requests |
| remote, origin, upstream, SSH vs HTTPS, credential helper, personal access token | Remotes and hosting |
| annotated tag, lightweight tag, semver, git describe | Tags and releases |
| git restore, git reset --soft --mixed --hard, git revert, reflog recovery | Undoing things |
| git bisect, git blame -w -C, git log -S (pickaxe), -G | Finding the commit that did it |
| git worktree, git stash | Worktrees and stash |
| submodule vs subtree | Submodules and subtrees |
| .gitignore, .gitattributes, EOL, autocrlf, export-ignore, linguist | Ignore and attributes |
| Git LFS | Large files |
| monorepo, sparse-checkout, partial clone, --filter=blob:none | Monorepos |
| hooks, pre-commit | Hooks |
| secrets in history, git filter-repo, verified badge | Security |
| How a commit, a merge, a rebase and a push work underneath; knobs; error messages | Mechanics |
| go.mod pseudo-version, go get tag, go generate, a commit-message linter in Go | Go |
| composer.lock, .env ignored, migrations as history, Envoy deploys from tags | Laravel |
| Undo the last commit, a leaked key, a huge PR, a regression | Solving the classic problems |
| Merge or rebase or squash; which strategy; submodule or subtree | Choosing |
| One repo to many services and many regions | In architecture |
| Commands with real output | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, 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.
| Object | Holds | Points at | Created by | See it with |
|---|---|---|---|---|
| blob | The bytes of one file version (no name, no mode) | Nothing | git add, git hash-object -w | git cat-file -p <id> |
| tree | A directory listing: mode, type, id, name per entry | Blobs and trees | git commit, git write-tree | git cat-file -p 'HEAD^{tree}', git ls-tree |
| commit object | tree id, parent ids, author, committer, message (and an optional signature) | One tree, 0..n parent commits | git commit, git merge, git rebase | git cat-file -p HEAD |
| tag object | Target id and type, tag name, tagger, message (and an optional signature) | Usually a commit | git tag -a, git tag -s | git cat-file -p v1.0.0 |
The three areas and the commands between them.
| From → to | Command | What it changes |
|---|---|---|
| Working tree → index | git add <path>, git add -p | Stages content (a blob is written now) |
| Index → repository | git commit | Writes trees and a commit; moves the current branch |
| Index → working tree | git restore <path> | Discards unstaged edits (unrecoverable) |
| HEAD → index | git restore --staged <path> | Unstages; the edit stays on disk |
| Compare working tree vs index | git diff | What you have not staged |
| Compare index vs HEAD | git diff --staged (alias --cached) | What the next commit will contain |
| Move branch (+ index, + working tree) | git reset --soft, --mixed (default), --hard | Soft: branch; mixed: + index; hard: + working tree |
Integrating a branch: the four shapes.
| Method | History afterwards | Commit ids of the branch | Typical place |
|---|---|---|---|
| Fast-forward | Straight line; the branch ref just moves | Unchanged | git merge when the target has not moved |
Merge commit (three-way, --no-ff) | A commit with two parents; the branch is visible | Unchanged | GitHub "Create a merge commit", GitLab default |
| Rebase then fast-forward | Straight line; commits replayed on the new base | New ids | git rebase main, GitHub "Rebase and merge" |
| Squash merge | One new commit with one parent | Branch commits are not in main | GitHub "Squash and merge", GitLab "Squash commits" |
Undo, by situation.
| Situation | Command | Safe on shared branches? |
|---|---|---|
| Throw away an unstaged edit | git restore <path> | Local only |
| Unstage | git restore --staged <path> | Local only |
| Redo the last commit (message or content) | git commit --amend, or git reset --soft HEAD~1 | No, if already pushed |
| Undo a pushed commit | git 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 branch | git reflog, git switch -c name <id> | Local recovery |
| A secret was committed and pushed | Rotate the secret, then git filter-repo, then force-push and tell everyone | Coordinated rewrite |
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 copy | Every clone holds the full history |
| Commit = talk to the server | Commit is local and instant; push/pull share it |
| Branches are directory copies, expensive culturally | A branch is a 41-byte file; branching is free |
| Locks on binary files are natural | No locks; large binaries need Git LFS |
| Partial checkout of a huge tree is easy | Needs sparse-checkout and partial clone |
| Access control per path | Access 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
- "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 -palways gives you whole objects (Objects, Packfiles). - "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.
- "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 / version | Event | Why it matters here |
|---|---|---|
| 2005 | Git 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 |
| 2010 | Vincent Driessen publishes "A successful Git branching model" (git-flow) | The long-lived develop + release/hotfix model many teams adopted |
| 2017-02-23 | SHAttered: "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.29 | SHA-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-05 | Driessen'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.45 | The 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 c8441fdReal 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:
#!/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):
$ 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.0The 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.
| Object | Mutable? | Survives git gc? | Hosted platforms show it as |
|---|---|---|---|
| blob, tree | Never (a change is a new object) | If reachable from a ref or a reflog entry | File view, directory view |
| commit object | Never; amend and rebase create new commits | Same | Commit page; "Verified" badge if signed |
| tag object | Never; moving a tag means deleting and recreating the ref | Same | Release / 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 againReal output:
$ 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~1Real 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 kind | Where | Moves when | Shared on push? |
|---|---|---|---|
Branch refs/heads/main | .git/refs/heads/ or packed-refs | You commit, merge, reset, rebase | Yes, if you push it |
Remote-tracking refs/remotes/origin/main | Same | Only on fetch/pull/push | No (it is your copy of theirs) |
Tag refs/tags/v1.0.0 | Same | Should never move | Only with --tags / --follow-tags or by name |
HEAD, ORIG_HEAD, FETCH_HEAD, MERGE_HEAD | .git/ | Each operation | Never |
| Reflog | .git/logs/ | Every ref update | Never |
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:
$ 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
2cf8d83d9ee29543b34a87727421fdecb7e3f3a183d337639025de576db9ebb4Real 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) | Does | Schedule in the incremental strategy that register/start sets |
|---|---|---|
gc | Full repack and prune | Disabled (gc: disabled in the manual) |
commit-graph | Writes the commit-graph file for fast history walks | Hourly |
prefetch | Fetches into refs/prefetch/ so git fetch later is cheap | Hourly |
loose-objects | Packs loose objects | Daily |
incremental-repack | Repacks packs into larger ones using the multi-pack-index | Daily |
pack-refs | Moves loose refs into packed-refs | Not 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)#!/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 --shortReal output (abridged from runs/02-three-areas.txt):
$ 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
49f0a8316d7be30d2cb780793ea8a80069b688a5HEAD: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 --short | Index vs HEAD | Working tree vs index | Meaning |
|---|---|---|---|
M | Same | Modified | Edited, not staged |
M | Modified | Same | Staged, nothing more |
MM | Modified | Modified | Staged, then edited again |
A | Added | Same | New file staged |
D / D | - / Deleted | Deleted / - | 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 MAJORSSH signing, run for real with a throwaway key:
#!/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>/'$ 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 method | Key you already have? | Local verify needs | GitHub | GitLab |
|---|---|---|---|---|
GPG (gpg.format=openpgp) | Rarely | gpg keyring with the public key | Upload 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 with | gpg.ssh.allowedSignersFile | Add the key as a signing key; "Verified" | Key usage "Authentication & Signing" or "Signing"; "Verified" |
S/MIME (gpg.format=x509, Git 2.19+) | Corporate certificates | gpgsm | Supported | X.509 certificate, supported |
| Hosting-made commits (web UI edits) | n/a | n/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")#!/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_workReal output, the three shapes (runs/03-merge-vs-rebase.txt):
--- 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 v1Real 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) | Heads | Use |
|---|---|---|
ort (default since 2.34) | 2 | Every normal merge, pull, rebase step, cherry-pick |
recursive | 2 | Default from v0.99.9k until v2.33.0; "redirected to mean ort in v2.50.0" |
octopus | 3+ | Default for 3+ heads; refuses on conflicts |
ours | 2+ | Record history but keep our tree (supersede an old branch) |
subtree | 2 | Merge a project into a subdirectory |
resolve | 2 | Legacy 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."#!/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 -4Real output:
$ 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.txtNote 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) | Cause | Typical resolution |
|---|---|---|
CONFLICT (content) | Same lines changed on both sides | Edit, git add |
CONFLICT (modify/delete) | One side edited, the other deleted | git rm or git add the kept version |
CONFLICT (rename/delete), (rename/rename) | Renamed on one side, deleted or renamed differently on the other | Decide the final path |
CONFLICT (add/add) | Both added a file with the same path | Merge contents or rename one |
| Binary file conflict | No textual merge possible | git checkout --ours/--theirs <path> |
| Lock files | Generated content | Take 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 gcReal output (the script is the one imported in Merging):
--- 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: initTwo 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 command | Effect | Typical use |
|---|---|---|
pick | Use the commit | Default |
reword | Use it, edit the message | Fix a subject |
edit | Stop after applying it | Split a commit (git reset HEAD~, add in parts) |
squash | Meld into the previous, combine messages | Combine steps |
fixup (-C keeps this message) | Meld into the previous, keep the previous message | Review fixes |
drop | Remove the commit | Debug commits |
exec <cmd> | Run a shell command | exec go test ./... after each step |
update-ref <ref> | Move a branch to this point | Written 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 -> okReal output (end of runs/03-merge-vs-rebase.txt):
$ 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 form | Overwrites a commit you never saw? | Use |
|---|---|---|
git push | Never (fast-forward only) | Default |
git push --force | Yes | Almost never |
git push --force-with-lease | Yes, if a fetch already updated your remote-tracking ref | Own branches, with care |
--force-with-lease --force-if-includes | No: also requires the fetched tip to be in your history | Own branches (alias pushf in config/gitconfig.example) |
--force-with-lease=main:<id> | No: you name the exact expected id | Scripts 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 onmainor 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:
mainis always deployable; a branch and a pull request per change; review, checks, merge, deploy frommain. 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 frommain(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):
mainholds released versions,developis the integration branch,feature/*fromdevelop,release/*to stabilise,hotfix/*frommainmerged 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.4cut frommainwhen you must stabilise or support a version whilemainmoves on; fixes land onmainfirst and are cherry-picked (git cherry-pick -x) to the release branch.
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 pathReal 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.
| Strategy | Long-lived branches | Release from | Best for | Cost |
|---|---|---|---|---|
| Trunk-based | main only | Tag on main (or short release branch) | Continuous delivery, web services | Needs feature flags, fast CI, discipline |
| GitHub Flow | main | main after each merge | Small and medium teams with PRs | No story for supporting old versions |
| GitLab Flow (environment) | main, pre-production, production | The environment branch | Teams that promote through environments | Extra merges; drift between branches |
| GitLab Flow (release) | main, x-y-stable | The stable branch | Versioned products | Cherry-pick discipline |
| git-flow | main, develop (+ release/hotfix) | main after release/* | Explicitly versioned software, slow release trains | Double 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, thendocs/; 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:
{
"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" }
]
}
}
]
}# 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#!/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):
# .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 deletedReal 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 method | GitHub name | GitLab name | main history | Keeps branch commits | Signed? |
|---|---|---|---|---|---|
| Merge commit | Create a merge commit | Merge commit | Graph with merge commits | Yes | Merge commit signed by the platform |
| Squash | Squash and merge | Squash commits (option) | One commit per PR, linear | No | Platform-signed commit |
| Rebase | Rebase and merge | Fast-forward merge (requires rebased MR) | Linear, all commits | Re-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 history | Merge commits over a rebased branch | Yes | Merge 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 updatesReal 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.
| SSH | HTTPS | |
|---|---|---|
| Authenticates with | Key pair (~/.ssh/id_ed25519), agent | Token as password, via credential helper |
| Firewalls / proxies | Port 22 often blocked; GitHub offers 443 | Works almost everywhere |
| Scope control | Per key: full account (user key) or one repository (deploy key) | Fine-grained PAT: repositories and permissions, expiry |
| Same key can sign commits | Yes (gpg.format=ssh) | n/a |
| CI typical | Deploy key for one repository | Job 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.
#!/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$ 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.3Without 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.0Real 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 tag | Annotated tag | Signed tag | |
|---|---|---|---|
| Object | None (ref only) | Tag object | Tag object + signature |
| Tagger, date, message | No | Yes | Yes |
git describe (no --tags) | Ignored | Used | Used |
--follow-tags pushes it | No | Yes | Yes |
| Use | Local bookmarks, CI build markers | Releases | Releases 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.
#!/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)"--- 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).
| Command | Moves branch | Index | Working tree | Safe after push |
|---|---|---|---|---|
git restore <path> | No | No | Reset from index | n/a (uncommitted) |
git restore --staged <path> | No | Reset from HEAD | No | n/a |
git reset --soft <c> | Yes | No | No | No |
git reset --mixed <c> (default) | Yes | Reset | No | No |
git reset --hard <c> | Yes | Reset | Reset (uncommitted work lost) | No |
git revert <c> | Adds a commit | Updated | Updated | Yes |
git commit --amend | Replaces the tip | n/a | n/a | No |
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.
#!/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')"$ 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 envThe -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.
| Tool | Question | Cost | Gotcha |
|---|---|---|---|
git bisect run | Which commit introduced it? | log2(n) builds/tests | Needs a reliable test; skip unbuildable commits with 125 |
git blame -w -C -C | Who last changed this line, really? | One file | Default blame credits reformat/move commits |
git log -S | When did this string appear/disappear? | Scans all diffs | Counts occurrences; a moved line is not listed |
git log -G | Which diffs touch lines matching this regex? | Scans all diffs | Also lists moves and edits of matching lines |
git log -L | History of one function or line range | One file | Needs 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.
#!/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$ 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-hotfixReal 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.
| Need | Stash | Worktree |
|---|---|---|
| Five-minute interruption | Good | Overkill |
| Keep a server or build running on the current branch | No | Yes |
| Two branches side by side for comparison | No | Yes |
| Disk cost | None | One checkout (objects shared) |
| Risk | Forgotten stashes, pop conflicts | Stale 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.
#!/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$ 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/moneyprotocol.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.
| Submodule | Subtree | Package manager (Go modules, Composer) | |
|---|---|---|---|
| Stored in parent | Commit pointer + .gitmodules | Full files (+ history or a squash) | A version in a manifest + lock file |
| Clone needs | --recurse-submodules | Nothing | go mod download, composer install |
| Updating | submodule update --remote + commit | subtree pull | go get -u, composer update |
| Contributing back | Commit inside the submodule, push there | subtree split/push | Separate repository and release |
| Pitfalls | Detached HEADs inside, forgotten bumps, CI auth to two repos | Big merges, history noise | Needs 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.
# .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# .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#!/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$ 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: seti/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 OSReal 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).
| Mechanism | Scope | Versioned? | Use for |
|---|---|---|---|
.gitignore | Directory and below | Yes | Build output, dependencies, secrets (.env) |
.git/info/exclude | This clone | No | Personal scratch files |
core.excludesFile | All your repositories | No | Editor and OS files (.idea/, .DS_Store) |
.gitattributes | Directory and below | Yes | EOL, binary, LFS, export-ignore, linguist, merge drivers |
core.autocrlf | Per user | No | Legacy; 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 versionReal 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.
| Approach | Clone size | Needs | Fits |
|---|---|---|---|
| Plain Git | Every version of every file | Nothing | Text, small binaries |
| Git LFS | Pointers + checked-out versions | LFS client + server | Large binaries that version with the code |
Partial clone (--filter=blob:limit=1m) | Blobs fetched on demand | Server support | Big history, any content |
| Object storage + manifest (S3, GCS) | Only the manifest | Your own tooling | Datasets, 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.
#!/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| |"'$ 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/.gitThe 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 demandReal 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.
| Technique | Downloads | Working tree | Breaks |
|---|---|---|---|
| Full clone | Everything | Everything | Nothing; slow for huge repos |
--depth=1 (shallow) | One commit's trees and blobs | Everything | History tools, describe, some merges |
--filter=blob:none (partial, blobless) | All commits and trees; blobs on demand | Everything (fetched at checkout) | Offline work on unfetched blobs |
--filter=tree:0 (treeless) | Commits; trees and blobs on demand | Everything | Many lazy fetches for history walks |
| Sparse-checkout (cone) | Unchanged | Listed directories only | Tools that expect the whole tree |
| Partial + sparse | Commits, trees, blobs of your directories | Your directories | The 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.
#!/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"#!/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#!/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# .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]#!/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_$ 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 applyReal 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.
| Hook | When | Arguments / input | Skipped by --no-verify | Typical job |
|---|---|---|---|---|
pre-commit | Before the message editor | None | Yes | Format, lint, secret scan on staged files |
prepare-commit-msg | Before the editor opens | Message file, source, sha | No | Insert the ticket id from the branch name |
commit-msg | After the message is written | Message file | Yes | Conventional Commits check |
post-commit | After the commit | None | n/a | Notifications |
pre-push | Before objects are sent | Remote name, URL; refs on stdin | Yes | Tests, refuse pushes to main |
post-checkout, post-merge | After switch / merge | Old/new refs; squash flag | n/a | composer install, go generate |
pre-receive, update (server) | On the server, before refs move | Refs on stdin / as args | Never (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:
--- 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 configThe filter-repo step, expected and not run (the tool is not installed on the build host); the command shape is from the saved README:
# 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 temporarilyReal 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.
| Control | Stops | Where | Bypassable by the developer? |
|---|---|---|---|
.gitignore for .env, keys | Accidental git add . | Client | Yes (git add -f) |
| pre-commit secret scan | Most accidental commits | Client | Yes (--no-verify) |
| Push protection / secret detection | Pushes containing known token formats | Server | Only with an audited bypass |
| Required signed commits | Unattributed commits on protected branches | Server | No |
git filter-repo | Secret in your copies of history | Repository owner | n/a (cleanup) |
| Rotation | Use of the leaked secret | Provider | n/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 mainThe 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 tipHow 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
| Setting | Values | Effect | Recommended |
|---|---|---|---|
init.defaultBranch | name | Initial branch for git init | main |
pull.rebase | false, true, merges | What git pull does after fetch | true on feature branches |
pull.ff | true, only, false | Fast-forward policy for pull merges | only if you never want accidental merges |
merge.conflictStyle | merge, diff3, zdiff3 | Conflict markers | zdiff3 |
rerere.enabled, rerere.autoUpdate | bool | Record and reuse resolutions | true, false (review first) |
rebase.autoSquash, rebase.updateRefs, rebase.autoStash | bool | Defaults for rebase -i | true |
push.autoSetupRemote, push.followTags, push.useForceIfIncludes | bool | Push conveniences and safety | true |
fetch.prune | bool | Delete remote-tracking refs gone on the server | true |
commit.gpgSign, tag.gpgSign, gpg.format, user.signingkey, gpg.ssh.allowedSignersFile | Signing | SSH signing | |
core.autocrlf, core.eol | true/input/false; lf/crlf/native | Line endings without attributes | Prefer .gitattributes |
core.hooksPath | path | Directory for hooks | A versioned hooks/ |
credential.helper | osxkeychain, manager, libsecret, cache, store | HTTPS credentials | OS keychain or Git Credential Manager |
gc.reflogExpire, gc.reflogExpireUnreachable | time | Reflog retention (90 / 30 days default) | Default |
uploadpack.allowFilter (server) | bool | Allow partial clone filters | true on servers you run |
protocol.file.allow | always, never, user | Local-path transport policy | Default (user) |
All of these together, as a starting ~/.gitconfig:
# ~/.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-includesError messages you will actually see
Rows marked "(transcript)" appeared in this chapter's runs/ transcripts; the others are labelled with where they come from.
| Message | Meaning | Fix |
|---|---|---|
CONFLICT (content): Merge conflict in price.txt / Automatic merge failed (transcript) | Overlapping changes | Resolve, git add, git commit (or --abort) |
! [rejected] main -> main (stale info) (transcript) | --force-with-lease: remote moved since your last fetch | Fetch, look, integrate |
! [rejected] main -> main (remote ref updated since checkout) (transcript) | --force-if-includes: you fetched but did not integrate | Rebase 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 not | git pull --rebase, then push |
fatal: No names found, cannot describe anything. (transcript) | No annotated tag reachable | Tag, or git describe --tags --always |
fatal: 'hotfix' is already used by worktree at '...' (transcript) | Branch checked out in another worktree | Use 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 HEAD | git branch <name> <id> |
Could not verify signature. / Signature verification failed: incorrect signature (transcript) | Object changed after signing, or wrong key | Investigate; never ship it |
warning: in the working copy of 'deploy.sh', CRLF will be replaced by LF (transcript) | .gitattributes normalises EOL | Expected; 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 conflicted | Resolve, 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 policy | Use 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 push | Open 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:
#!/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
// 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
}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")
}
}// 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
}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)
}
}// 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
}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")
}
}// 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)
}module academy/git-version-control
go 1.24The 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 releasevX.Y.Z) andvX.Y.Z-pre.0.ts-hash(after a pre-release). Thepseudopackage implements exactly those rules and its test reuses the reference's example commit; in the lab,pseudoversionprintedv0.0.0-20260101100200-cb0c4a0a627abefore any tag,v1.2.4-0.20260101100500-5f0f15b598e2two commits afterv1.2.3andv1.3.0-rc.1.0.20260101100700-f1ce51d7d680afterv1.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;@masteror@<commit>resolve to a pseudo-version written intogo.mod. Tags must be semver with avprefix, and for a module in a subdirectory the tag carries the path:libs/money/v1.4.0. Modules with major version 2+ need the/v2path suffix inmoduleand 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 (
retractingo.modis the way to withdraw a bad version). Fix forward with a new patch version. Private modules skip the proxy and checksum database withGOPRIVATE=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/appordebug.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-generatedin.gitattributes, and have CI rungo generate ./... && git diff --exit-codeto catch stale output. - go.sum and merges.
go.sumconflicts are resolved by taking either side and runninggo mod tidy; never hand-edit hashes. Thegitattributes.examplemarksgo.sum-diffto keep PR diffs readable. - Workspaces in a monorepo. A
go.workfile at the root lets several modules in one repository use each other withoutreplacedirectives; teams decide whether to commit it. - Modules, versions and the
gocommand 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:
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):
@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
@endtaskThe CI step that runs on a pushed tag and refuses lightweight tags, tags not on main, and edits to already released migrations:
#!/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):
--- 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
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'),
]);
}
}# .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), nevercomposer update. A merge conflict incomposer.lock: take one side, re-run thecomposer require/updatethat 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.examplewith every key and safe defaults; production values live in the server's shared.envor 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.shenforces this withgit 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.2becomes the release name, thegit archivesource and theVERSIONfile.@storygroups tasks;'parallel' => trueruns a task on all servers at once. The same flow works from GitHub Actions or GitLab CI onpush: 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,/.githubandphpunit.xmlmarkedexport-ignorenever reach users'vendor/. - Hooks for PHP. The pre-commit config runs
php -lon 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
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Last commit has a typo or a missing file (not pushed) | Amend | git add f; git commit --amend --no-edit | One clean commit | Rewrites the tip; never on pushed shared commits |
Committed to main instead of a branch | Move the commits | git branch feat; git reset --hard origin/main; git switch feat | Nothing lost | Only before pushing main |
| "I lost my work after reset/rebase" | Reflog | git reflog, git branch rescue HEAD@{n} | Recovers any recent commit | Only commits; uncommitted edits are gone |
| A pushed commit broke production | Revert | git revert <id> (merge: -m 1), push | History intact, safe for everyone | The revert must be reverted to re-apply |
| A regression somewhere in 300 commits | Bisect | git bisect start bad good; git bisect run ./test.sh | log2(300) ≈ 9 test runs | Needs a scriptable test |
| A 3,000-line PR nobody reviews | Stacked PRs | Split into dependent branches, rebase --update-refs | Real reviews, earlier merges | Tooling and discipline |
| Same conflicts on every rebase of a long branch | rerere, then shorter branches | rerere.enabled=true | Resolve once | Treats the symptom; integrate more often |
| A secret was pushed | Rotate, rewrite, prevent | Revoke; git-filter-repo --sensitive-data-removal; push protection | Key useless, history clean | Every clone must re-clone; forks keep it |
| CRLF/LF diffs in every PR | Attributes | * text=auto eol=lf, git add --renormalize . | Consistent everywhere | One noisy normalisation commit |
| Clone of the monorepo takes 20 minutes | Partial + sparse | --filter=blob:none, sparse-checkout set --cone | Minutes, small disk | Needs server filter support; lazy fetches |
| Need to fix production while mid-feature | Worktree | git worktree add ../hotfix -b hotfix origin/main | No stash juggling | Extra checkout on disk |
| Unreadable history of "fix", "wip", "asdf" | Conventions + squash or autosquash | Conventional Commits + commitlint; squash merge or rebase -i --autosquash | Changelogs, bisectable main | Squash loses intermediate steps |
Undo the last commit, keep the changes
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 indexBring a feature branch up to date before review
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-includesSplit one commit into two
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 --continueChoosing
Merge, rebase or squash
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Updating your own feature branch | Rebase on origin/main | --autosquash, --update-refs | Clean, linear, no merge noise |
| Integrating a PR, team values one commit per change | Squash merge | Conventional Commit PR title | main reads like a changelog; bisect per PR |
| Integrating a PR whose commits are each meaningful | Rebase merge (or merge commit) | Required linear history | Keeps the steps |
| Integrating a long-lived or shared branch | Merge commit | --no-ff, rerere | Never rewrites commits others have |
Release branch back into main | Merge commit | cherry-pick -x for single fixes | Hotfix ids stay stable |
| Branch shared by two people | Merge, not rebase | Agree who integrates | Rebase would replace commits the other has |
| Stacked PRs | Rebase with --update-refs; avoid squash or retarget after each squash | Graphite, ghstack | Squash breaks the ancestry of the next PR |
Which branching strategy
| Team / product | Strategy | Release mechanism | Must have |
|---|---|---|---|
| Web service, continuous delivery | Trunk-based + GitHub Flow PRs | Tag on main, deploy on merge | Feature flags, fast CI, required checks |
| Several environments promoted manually | GitLab Flow with environment branches (or GitOps folders) | Merge main → pre-production → production | Upstream-first rule |
| Versioned product with supported versions | Release branches (GitLab Flow release or git-flow) | Tag on release/x.y | Cherry-pick discipline, backport labels |
| Open-source library | GitHub Flow + semver tags | Signed annotated tags | Changelog, CI matrix |
| Mobile app with store review | Trunk-based + short release branches | Branch per store submission | Hotfix path off the release branch |
Submodule, subtree, package or monorepo
| Need | Choice | Why |
|---|---|---|
| Share a versioned library between services | Package manager (Go modules, Composer) | Versions, lock files, tooling everyone knows |
| Pin an external repository you do not control, exact commit | Submodule | Reproducible pointer, small parent repo |
| Vendor code you will patch locally, consumers should not care | Subtree | No extra commands for consumers |
| Change an API and all callers atomically, one CI | Monorepo with partial clone + sparse-checkout | One commit across services |
| Independent teams, independent release cadences | Polyrepo with packages | Clear ownership, smaller blast radius |
Hosting
| Need | Choice | Note |
|---|---|---|
| Integrated PRs, Actions, large ecosystem | GitHub | Rulesets, CODEOWNERS, push protection, merge queue |
| Integrated CI/CD, self-managed option, MR approvals | GitLab | Protected branches, approval rules, merge trains |
| Small self-hosted, low resources | Gitea / Forgejo | Pull requests, Actions-compatible runners |
| SHA-256 repositories, full control | Self-hosted (bare repositories over SSH, or a forge that supports them) | Check SHA-256 support before choosing |
| Air-gapped mirror | git clone --mirror + scheduled fetch | Read-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 itDistributed 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
| Scale | Repository shape | What changes in Git usage |
|---|---|---|
| 1x (one team, one app) | One repository, GitHub Flow | Protected main, required checks, squash merges, signed tags |
| 10x (several teams, modules or 10 services) | Modular monolith or a few repositories | CODEOWNERS 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 platform | git 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)
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-runs01-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 linesThe shared library every script sources:
#!/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
}#!/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#!/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.02. 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:
cd go && gofmt -l . && go vet ./... && go test -race -count=1 ./... # transcript: runs/go-checks.txt$ 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.424s8. Tools not installed on the build host (expected, not run)
# 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 nothing9. 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
| Belief | Reality |
|---|---|
| Git stores diffs between versions | It stores snapshots (blobs and trees); packfiles delta-compress similar objects underneath |
| A branch is a sequence of commits | A branch is a pointer to one commit; history is what its parents reach |
git reset --hard deletes commits | It moves a pointer; commits stay in the reflog for 30-90 days; only uncommitted edits are destroyed |
| Rebase moves commits | It creates new commits with new ids and abandons the old ones |
.gitignore removes a file from the repository | It 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 leak | The secret stays in history and in every clone; rotate it, then rewrite |
--force-with-lease cannot overwrite others' work | A 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 commit | It is free text; only a verified signature ties a commit to an account |
| Squash merge "merges" the branch | It makes a new unrelated commit; the branch is not an ancestor of main |
| Sparse-checkout makes clones small | Only together with partial clone (--filter=blob:none) |
| Trunk-based development means no code review | Short-lived branches with PRs and required checks are trunk-based; long-lived branches are what it forbids |
git pull is safe and simple | It is fetch + merge (or rebase) into your current branch; know which one pull.rebase selects |
| A lightweight tag is fine for releases | It has no tagger, date, message or signature and is ignored by plain git describe and --follow-tags |
Cheat sheet
| Topic | Remember |
|---|---|
| Objects | blob (content), tree (names), commit (tree + parents + who + why), tag (named, signed pointer); id = hash of type size\0content |
| Inspect | git cat-file -t/-p, git ls-tree -r, git rev-parse, git log --oneline --graph --all |
| Three areas | add → index → commit; diff = unstaged, diff --staged = to be committed; add -p for partial |
| Messages | type(scope)!: description, body explains why, trailers last; --fixup + rebase -i --autosquash |
| Signing | gpg.format=ssh, user.signingkey, commit.gpgSign=true; verify with allowedSignersFile; "Verified" on the host |
| Merge | Fast-forward if possible; --no-ff to record the branch; ort is the default; conflicts = stages 1/2/3 |
| Rebase | New 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 |
| Undo | restore (files), reset --soft/--mixed/--hard (local commits), revert (shared), reflog (rescue) |
| Find | bisect run, blame -w -C -C, log -S (string count), log -G (regex in diff), log -L |
| Parallel work | worktree add for a second checkout; stash -u for a quick switch |
| Releases | Annotated 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 |
| Go | Pseudo-versions = base + UTC commit time + 12-char hash; never move a published tag; commit go generate output |
| Laravel | Commit composer.lock, ignore .env, migrations are append-only, deploy tags with Envoy |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
.gitattributes | Versioned file assigning attributes (text/eol, binary, filter, export-ignore, linguist) to paths |
.gitignore | Versioned file listing patterns of untracked files Git should not show or add |
| composer.lock | Composer's lock file with exact dependency versions; committed so every install is identical |
| git add -p | Patch mode: stage selected hunks of a file |
| git cat-file | Print an object's type (-t), size (-s) or content (-p) |
| git describe | Name a commit as nearest annotated tag + commits since + g<abbrev id> |
| git diff --staged | Compare the index with HEAD (synonym --cached) |
| git hash-object | Compute an object id for content; -w writes the object |
| git reset | Move the current branch; --soft, --mixed (default), --hard decide what else is reset |
| git restore | Restore working-tree files from the index, or the index from HEAD (--staged) |
| git revert | Create a commit that inverts an earlier commit |
| annotated tag | A tag object with tagger, date, message and optional signature; used for releases |
| autosquash | rebase -i --autosquash: moves fixup!/squash! commits under their targets and melds them |
| autocrlf | core.autocrlf: per-user line-ending conversion (true, input, false); superseded by .gitattributes |
| bisect | git bisect: binary search over history for the first bad commit; run automates it |
| blame | git blame: last commit per line; -w ignores whitespace, -C follows moved/copied code |
| blob | Object holding one file's bytes, without name or mode |
| CODEOWNERS | File mapping paths to required reviewers on GitHub and GitLab; last matching pattern wins |
| commit object | Object with tree, parents, author, committer, optional signature and message |
| commit trailers | Token: value lines at the end of a message (Refs:, Co-authored-by:, BREAKING CHANGE:) |
| Conventional Commits | Message convention type(scope)!: description mapping to semver bumps |
| credential helper | credential.helper: program that stores and supplies HTTPS credentials (keychain, GCM, libsecret) |
| detached HEAD | HEAD containing a commit id instead of a branch name |
| Envoy | Laravel's SSH task runner; tasks are Blade-templated shell scripts (Envoy.blade.php) |
| EOL | End of line: LF (\n) or CRLF (\r\n); controlled by the eol and text attributes |
| export-ignore | Attribute that leaves a path out of git archive output |
| fast-forward | Integration that only moves a ref because the target is an ancestor of the source |
| feature flags | Runtime switches that hide unfinished code merged to trunk (feature toggles) |
| fixup | git commit --fixup=<c>: a commit meant to be melded into <c> by autosquash |
| force-with-lease | Forced push that succeeds only if the remote ref still has the expected value |
| GitHub Flow | main always deployable; a branch and pull request per change |
| git-flow | 2010 model with develop, main, feature, release and hotfix branches |
| git filter-repo | Tool that rewrites history (remove paths, replace text); GitHub's recommended way to purge secrets |
| GitLab Flow | Feature branches into main plus downstream environment or release branches; fixes flow from main downstream |
| Git LFS | Large File Storage: pointer files in Git, content on an LFS server |
| git maintenance | Background or on-demand repository optimisation tasks (commit-graph, prefetch, repack, gc) |
| GPG | GNU Privacy Guard; OpenPGP signing for commits and tags (gpg.format=openpgp) |
| HEAD | The current commit, usually via a symbolic ref to a branch |
| hooks | Scripts 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 rebase | rebase -i: edit a todo list of pick/reword/edit/squash/fixup/drop/exec |
| lightweight tag | A ref pointing straight at a commit, with no tag object |
| merge base | Best common ancestor of two commits; the base of a three-way merge |
| merge conflict | Overlapping changes the merge cannot combine; stages 1/2/3 in the index |
| merge request | GitLab's name for a pull request |
| monorepo | One repository holding many projects or services |
--no-ff | Merge option that always creates a merge commit |
--onto | Rebase option to replay a range onto a different base |
| origin | Conventional name of the remote you cloned from |
| ort strategy | Git's default two-head merge strategy since 2.34 ("Ostensibly Recursive's Twin") |
| packfile | Compressed file of many objects with delta compression and an index |
| partial clone | Clone with an object filter (--filter=blob:none); missing objects fetched on demand from a promisor remote |
| personal access token | Token used instead of a password for HTTPS Git and API access (fine-grained or classic on GitHub) |
| pickaxe | git log -S (and -G): search history for added or removed strings |
| pre-commit | The hook that runs before a commit, and the framework (pre-commit.com) that manages such hooks |
| protected branches | Host rules that restrict pushes, force pushes and merges on chosen branches |
| pseudo-version | Go version for an untagged commit: base + UTC commit time + 12-char hash (go.mod) |
| pull request | Host review object proposing to merge one branch into another |
| rebase | Replay commits on a new base, creating new commits |
| rebase merge | Host merge method that replays PR commits onto the base without a merge commit |
| reflog | Local log of every value of HEAD and each branch; basis of reflog recovery |
| refs | Named pointers to objects: branches, tags, remote-tracking branches |
| release branch | Branch cut to stabilise or maintain a released version |
| remote | Named URL of another repository (origin, upstream) |
| required checks | CI statuses that must pass before a protected branch accepts a merge |
| rerere | "Reuse recorded resolution": replays previous conflict resolutions |
| rewriting history | Any operation that replaces commits (amend, rebase, filter-repo) |
| semver | Semantic Versioning: MAJOR.MINOR.PATCH with pre-release suffixes |
| SHA-1 / SHA-256 | Object hash functions; SHA-1 default, SHA-256 via --object-format=sha256, not interoperable |
| signed commits | Commits carrying a GPG, SSH or S/MIME signature in a gpgsig header |
| sparse-checkout | Checking out only some directories (cone mode) |
| squash merge | Host merge method creating one new commit from all PR changes |
| SSH signing | Signing with an SSH key (gpg.format=ssh, Git 2.34+) |
| SSH vs HTTPS | The two Git transports: key-based SSH or token-based HTTPS |
| stacked PRs | Dependent pull requests built on each other's branches |
| stash | Saved uncommitted changes (refs/stash) |
| submodule | Gitlink (mode 160000) plus .gitmodules pointing at a commit of another repository |
| subtree | Another project's files merged into a subdirectory (git subtree) |
| tag object | Object naming another object with tagger, message and optional signature |
| three-way merge | Merge using the merge base and both tips |
| tree | Object listing names, modes and ids of blobs and subtrees |
| trunk-based development | All work integrates into one trunk via very short-lived branches |
| upstream | Remote of the original project when origin is a fork; also a branch's configured tracking branch |
--update-refs | Rebase option that moves every branch pointing into the rebased range |
| verified badge | GitHub/GitLab mark for a commit or tag with a verified signature |
| working tree | The checked-out files on disk |
| worktree | An 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).
- Git manual pages, git-scm.com: git, gitglossary, gitrevisions, git-cat-file, git-hash-object, git-commit, git-interpret-trailers, git-merge, merge-strategies, git-rebase, git-push, git-reset, git-restore, git-revert, git-reflog, git-rerere, git-bisect, git-blame, git-log, git-worktree, git-stash, git-submodule, gitignore, gitattributes, git-tag, git-describe, git-maintenance, githooks, git-sparse-checkout, partial-clone, hash-function-transition, git-config, gitcredentials, git-clone, git-switch, git-init.
- git-subtree documentation (Git source, contrib): https://raw.githubusercontent.com/git/git/master/contrib/subtree/git-subtree.adoc
- Git release notes (Git source tree): 2.23, 2.29, 2.30, 2.34, 2.35, 2.38, 2.45, 2.54.
- Pro Git (Chacon, Straub): Git Objects, Git References, Packfiles, Rebasing, Basic Branching and Merging, Distributed Workflows, Rerere.
- Conventional Commits 1.0.0; Semantic Versioning 2.0.0.
- Martin Fowler, Patterns for Managing Source Code Branches and Pete Hodgson, Feature Toggles (aka Feature Flags). (trunkbaseddevelopment.com could not be reached from the build host; it is not quoted.)
- Vincent Driessen, A successful Git branching model (with the 2020 note of reflection).
- GitLab: What is GitLab Flow, merge methods, merge request approvals, protected branches, protected branches API, Code Owners, signed commits, SSH-signed commits, merge trains.
- GitHub Docs: about pull requests, creating a pull request, merge methods, merge queue, protected branches, rulesets, rules REST API, code owners, commit signature verification, telling Git about your signing key, about remote repositories, personal access tokens, removing sensitive data, about Git LFS, large files, line endings, about git rebase.
- Git LFS and the Git LFS specification; Linguist overrides.
- pre-commit, pre-commit-hooks README, gitleaks README, git-filter-repo README.
- GitHub Actions: actions/checkout README, actions/setup-go README.
- Go: Go Modules Reference, module version numbering, Go 1.18 release notes, Generating code (Go blog).
- PHP and Laravel: Composer basic usage, Laravel 13 Envoy, deployment, configuration, migrations, package development (AboutCommand).