Version Control Fundamentals

Version Control Fundamentals in DevOps Tools: --- In a letterpress composing room the raw material is loose metal type, kept in shallow wooden cases divided…


The Analogy: The Composing Room's Galley and Forme

In a letterpress composing room the raw material is loose metal type, kept in shallow wooden cases divided into compartments, one for each letter, figure and space. A compositor standing at the case can lift any sort out, turn it round, drop it back into the wrong compartment, or knock a handful onto the floor, and no record of any of that exists anywhere. The case is simply the current condition of the metal in the shop. Two compositors working the same case will quietly undo each other's picking, and by the end of the shift nobody can say what the case held that morning.

When the compositor has picked the lines for a page, they go into a galley: a long shallow brass tray on the bench holding the lines that have been deliberately chosen for this job, and nothing else. The galley is not the page yet. It is a statement of intent that can still be corrected freely. The foreman can pull a galley proof from it, read the proof, and send lines back to the case without any of that reaching the record. What sits on the galley is what will go into the page if nothing else changes.

Once the galley reads correctly it is lifted into an iron frame called a chase, wedged tight with quoins until nothing can shift, and that locked-up forme goes onto the rack with a stamped job ticket: job number, date, page. The forme is now a fact about the shop. It can be carried to the press, printed, taken off, stored, and re-mounted six months later to print the same page identically. The rack and the job register together are the shop's history, and they are the only part of the whole process that outlives the shift.

The failure mode is the galley left standing overnight. Metal type is a finite resource, so the next shift robs a standing galley for the sorts it is short of, and the tray you thought was your page comes back missing every capital W. Worse is the forme that was never locked up and never entered in the register: knock the bench and the type pies into an unsorted heap on the floor, and nothing anywhere describes that page well enough to set it again. The lesson the trade learned the hard way, and the lesson Git encodes in its design, is that the recorded, locked-up snapshot is the only thing you actually own. Everything still sitting on the bench is weather.


Syntax or Core Structure

Every Git command you will ever type is a move between three places. The working tree is the ordinary files on disk. The index, also called the staging area or the cache, is a single binary file at .git/index that lists exactly what the next commit will contain. The object store under .git/objects holds the commits and the file contents they point at, and nothing in it is ever rewritten in place.

The session below is deliberately deterministic: every command uses --short or an explicit format string, so the output carries no dates, no author lines and no object ids.

git init -q -b main demo
cd demo
git config user.email "dev@example.com"
git config user.name "Dev"

printf 'alpha\n' > a.txt
printf 'beta\n'  > b.txt

git add a.txt
git status --short

Output:

A  a.txt
?? b.txt

Read the two leading columns as index-then-worktree. A in the first column means the index holds a path that no commit has yet. The space in the second column means the copy on disk is byte-identical to the copy in the index. ?? means Git has never heard of b.txt at all: it is in neither the index nor any commit, so committing right now would not capture it.

Now lock the galley into a forme.

git commit -q -m "feat: add a"
git log --format='%s'
git rev-list --count HEAD

Output:

feat: add a
1

Note --format='%s' rather than --pretty=format:'%s'. The two look interchangeable and are not. The format: spelling puts a separator between entries and so emits no newline after the last one, which means the next command's output lands on the same line as the last subject. The --format= spelling uses terminator semantics and ends every entry with a newline. That one-character difference is the most common cause of mangled output in shell pipelines built around git log.


Technical Depth: What the Index Actually Stores

The three places, and what moves between them

Almost every confusing Git moment comes from not knowing which of the three places a command reads and which it writes. Learn this table and most of the confusion goes away permanently.

PlaceWhere it livesWhat writes to itWhat reads from it
Working treeThe project folder itselfYour editor, code generators, build outputgit add, git diff, git status
IndexOne binary file, .git/indexgit add, git rm --cached, git restore --stagedgit commit, git diff --cached
Object storeCompressed files under .git/objectsgit commit, git hash-object -wgit log, git show, git checkout

The important consequence is that git diff with no arguments compares the working tree against the index, not against the last commit. If you have staged a change and then edited the file again, plain git diff shows only the second edit. To see what you are about to commit you need git diff --cached, which compares the index against HEAD.

The status codes are two columns, not one

git status --short prints a two-character prefix per path. Most people read it as a single word and get it wrong.

First columnSecond columnState of the path
AspaceNew path staged, disk copy matches the index
MspaceEdit staged, disk copy matches the index
spaceMTracked path edited on disk, nothing staged
MMEdit staged, then the same file edited again
DspaceDeletion staged
??Untracked path, never seen by Git

Continuing in the demo repository from the previous section, where a.txt is committed and contains one line:

printf 'alpha\ngamma\n' > a.txt
git status --short -- a.txt
git add a.txt
printf 'alpha\ngamma\ndelta\n' > a.txt
git status --short -- a.txt

Output:

 M a.txt
MM a.txt

That MM is the single most expensive state in day-to-day Git, because it is the state in which the code you tested is not the code you are about to commit. The galley has been robbed and the tray no longer matches the proof you read.

Content addressing: the store is keyed by content, not by path

Git does not store "the history of a.txt". It stores blobs of content, each named by the SHA-1 of a short header plus the bytes themselves, and then stores trees that map names onto those blobs. A path is just a label in a tree. Two paths holding identical bytes therefore share a single blob, and Git never notices or cares that they are two files.

git init -q -b main blobs
cd blobs
printf 'same\n'  > x.txt
printf 'same\n'  > y.txt
printf 'other\n' > z.txt
git add x.txt y.txt z.txt

git ls-files | wc -l
git ls-files --stage | awk '{print $2}' | sort -u | wc -l

Output:

3
2

Three paths in the index, two distinct object ids among them. git ls-files --stage prints four fields per entry -- file mode, object id, merge stage number, path -- and the second field is what awk picks out. The object ids themselves are omitted here on purpose, because a printed hash is the sort of value that rots in a tutorial the moment anything upstream changes. You can see the shape of one without printing it:

printf 'alpha\n' | git hash-object --stdin | wc -c

Output:

41

Forty hexadecimal characters plus the trailing newline that wc also counts. That value is a pure function of the bytes fed in, which is why git hash-object needs no repository, why two developers on opposite sides of the world produce the same id for the same file, and why Git can tell whether it already has your content before you finish typing.

What a commit object contains

A commit is a tiny text object: a pointer to one tree, zero or more parent pointers, an author line, a committer line, a blank line, and the message. You can inspect the field order without printing any ids.

git cat-file -t HEAD
git cat-file -t "HEAD^{tree}"
git cat-file -p HEAD | cut -d' ' -f1 | sed -n '1,3p'

Output:

commit
tree
tree
author
committer

The first two lines are object types: HEAD resolves to a commit, and HEAD^{tree} peels that commit to the tree it points at. The last three are the leading words of the commit's own body, in order. Note what is absent: there is no diff anywhere in a commit. Git stores whole snapshots and computes diffs on demand, which is exactly the forme on the rack rather than a note saying "same as last week but with the headline changed".


Real World Example: A Guard That Refuses Debris in the Index

Every team eventually commits a stray TODO:, a leftover conflict marker, or -- worst of all -- a file whose staged copy is not the copy anybody tested. The guard below is the smallest genuinely useful thing you can hang off a pre-commit hook or a CI job. It walks the staged paths, refuses debris, and reports drift between the index and the disk.

#!/usr/bin/env bash
# staged-guard.sh -- refuse a commit whose staged files carry debris, and
# report any staged file that has drifted from the copy now on disk.
set -u

FORBIDDEN='TODO:|FIXME:|<<<<<<<'

staged=$(git diff --cached --name-only --diff-filter=ACM)
if [ -z "$staged" ]; then
  echo "guard: nothing staged"
  exit 0
fi

scanned=0
debris=0
drifted=0

for path in $staged; do
  scanned=$((scanned + 1))
  hits=$(grep -c -E "$FORBIDDEN" "$path" || true)
  if [ "$hits" -gt 0 ]; then
    echo "debris  $path  $hits"
    debris=$((debris + hits))
  fi
  if ! git diff --quiet -- "$path"; then
    echo "drifted $path"
    drifted=$((drifted + 1))
  fi
done

echo "guard: scanned=$scanned debris=$debris drifted=$drifted"
[ "$debris" -eq 0 ] || exit 1
exit 0

Here is a repository set up to trip both checks at once. Three files are staged; one of them still carries a TODO:, and one of them is edited again after staging. A fourth file is left untracked so you can confirm the guard ignores it.

mkdir -p src
printf '# Payments\n\nRun the service with make run.\n' > README.md
printf 'export function charge(cents) {\n  // TODO: wire retries\n  return cents;\n}\n' > src/app.js
printf 'export const round2 = (n) => Math.round(n * 100) / 100;\n' > src/util.js
printf 'scratch\n' > notes.txt

git add README.md src/app.js src/util.js
printf 'export const clamp = (n) => (n < 0 ? 0 : n);\n' >> src/util.js

bash staged-guard.sh
echo "exit=$?"

Output:

debris  src/app.js  1
drifted src/util.js
guard: scanned=3 debris=1 drifted=1
exit=1

Remove the marker, re-stage both files, and the guard falls silent:

printf 'export function charge(cents) {\n  return cents;\n}\n' > src/app.js
git add src/app.js src/util.js
bash staged-guard.sh
echo "exit=$?"

Output:

guard: scanned=3 debris=0 drifted=0
exit=0

The guard is worth running because it catches two unrelated classes of accident in a single pass over the same list of paths. The first is content nobody meant to ship: a marker left in while you were thinking, a conflict marker that survived a bad merge. The second, and by far the more expensive, is drift between the index and the disk. A file that is staged and then edited again produces a commit describing code that has never been run anywhere, and the person who eventually bisects to that commit will lose an afternoon to it. Catching it costs one git diff --quiet per path.

The mechanics are worth reading closely because each flag is doing real work. --diff-filter=ACM keeps added, copied and modified paths and drops deletions, so the loop never tries to grep a file that is no longer on disk. git diff --quiet -- "$path" prints nothing and communicates entirely through its exit status, returning 1 when the working tree differs from the index for that one path, which is why the test is spelled as a negation. The || true after grep -c exists because grep exits non-zero when it finds nothing, and a count of zero is a perfectly good answer that should not look like a failure.

Where you install it changes what it means. Dropped into .git/hooks/pre-commit it is advisory only: hooks live inside a single clone, are not versioned with the project, and anyone in a hurry can skip the whole thing with git commit --no-verify. The same script running in CI against a checked-out commit is enforcement, because nobody can bypass it -- but note that in CI the drift half of the script is dead code, since a fresh checkout has no index drift by construction. The honest deployment is both: the hook for fast local feedback including drift, and the debris half again in CI as the gate that actually holds.

Now the limits, and there is a real one. The guard greps the copy of the file on disk, not the copy in the index -- and the index copy is what gets committed. Stage a file containing TODO:, then delete that line on disk without re-staging, and the guard reports drift, reports zero debris, and exits 0, allowing exactly the commit it was written to stop. The fix is to read the staged blob instead, piping git show :"$path" into grep. Three smaller flaws sit alongside it: for path in $staged splits on whitespace, so any path containing a space is scanned as two paths that do not exist; grep -c counts matching lines rather than matches, so two markers on one line are reported as one and the debris total is a line count wearing a hit count's name; and the pattern is plain substring matching, so a file legitimately documenting how the team uses TODO: markers is unshippable until someone adds an ignore mechanism.


Common Mistakes

  1. Reading plain git diff as "what I am about to commit." It compares the working tree against the index, not against HEAD. A change you staged and then left alone does not appear in it at all, so the output can be completely empty while the next commit is enormous. git diff --cached is the command that answers the question you actually asked.
  2. Using git add . as a reflex. It stages whatever happens to be in the tree, which on a real working day includes build output, editor swap files, coverage reports and the .env you were testing against. Name the paths, or use git add -p and look at each hunk.
  3. Committing from the MM state. Staging a file and then editing it again means the committed content was never executed by anybody. The tests that passed did so against the copy on disk, and that copy is not what went into the object store.
  4. Treating git commit -am as a safe shortcut. The -a flag stages modifications to already-tracked files and silently ignores new ones, so a commit whose message says it adds a module can ship without the module in it. The build then fails for everybody except the author, whose working tree still has the file.
  5. Believing .gitignore protects a file that is already tracked. Ignore rules are consulted only for untracked paths. Once a path is in the index, adding it to .gitignore changes nothing, and the file keeps being committed until you run git rm --cached on it.
  6. Thinking a commit stores a diff. It stores a complete tree. This is why a revert is a new commit containing the old content rather than an erasure, why a file that has not changed costs nothing extra in the object store, and why history rewriting has to rebuild every downstream commit rather than editing one patch.
  7. Running git restore <path> casually. It overwrites the working-tree copy from the index and there is no undo, because the content it destroyed was never recorded anywhere. This is the one everyday Git command that can genuinely lose work.
  8. Writing commit messages that narrate the diff. "Updated three files" adds nothing the diff does not already say. The message is the only place the reasoning can live, so it should record why the change was necessary and what was rejected.
  9. Running git init in a directory that is already inside a repository. Git resolves the nearest .git upwards from the current directory, so the inner repository silently shadows the outer one. Files then look untracked from one working directory and invisible from the other, and the confusion usually survives several days.

Best Practices

  • Stage deliberately, never wholesale. Name paths explicitly, or step through hunks with git add -p. The index exists so that you can choose; using git add . throws that away.
  • Read git status --short as two columns before every commit. Index status first, working-tree status second. Most bad commits are visible in that output before they happen.
  • Keep commits atomic. One logical change per commit means one thing to review, one thing to revert, and one thing for git bisect to land on.
  • Write an imperative subject line under about fifty characters, then a blank line, then the reasoning. Tools everywhere assume that shape, and the reasoning is the part that cannot be recovered from the code later.
  • Decide line-ending policy on day one with a .gitattributes file. Mixed CRLF and LF in a shared repository turns every diff into noise and every merge into a fight, and retrofitting the fix rewrites history.
  • Commit early and often, even to a throwaway branch. The working tree is not a backup: nothing you have not committed exists anywhere Git can return it from.
  • Keep generated artefacts out of the object store. Build output, dependency directories and minified bundles inflate every future clone permanently, because history is immutable and deleting them later does not shrink it.
  • Enforce guards in CI as well as in hooks. A hook is local, unversioned and bypassable with --no-verify; only the pipeline is a gate that everyone actually passes through.

Practice Exercises

  1. Reproduce the dangerous state. In a scratch repository, create a file, commit it, edit it, stage it, then edit it again. Show that git status --short reports MM, that plain git diff shows only the second edit, and that git diff --cached shows only the first. Write down which of the two would end up in a commit.
  2. Prove content addressing. Create three files where two hold identical bytes, stage all three, and use git ls-files --stage with awk to count paths and distinct object ids separately. Then change one byte in one of the identical pair and show the count of distinct ids change.
  3. Fix the guard's real flaw. Rewrite staged-guard.sh so the debris check reads the staged blob with git show instead of the file on disk. Demonstrate the fix by staging a file containing TODO:, removing that line on disk without re-staging, and showing that the original script exits 0 while yours exits 1.
  4. Make the guard safe for awkward paths. Replace the word-splitting loop with a NUL-delimited read using git diff --cached -z --name-only, then prove it works by staging a file whose name contains a space. Note in a comment which other commands in the script also needed quoting once paths could contain spaces.