Sub topic 3
The index: staging as a plumbing concept
Assume you know git init, git add, git commit, and basic shell commands. The index is Git’s staging area. It is a binary file at .git/index that records which object should appear at each path in the next tree.
From the index to a commit
Porcelain commands hide several plumbing steps:
mkdir plumbing-demo
cd plumbing-demo
git init -q
git config user.name "Demo User"
git config user.email "[email protected]"
blob=$(printf 'hello\n' | git hash-object -w --stdin)
git update-index --add --cacheinfo 100644 "$blob" hello.txt
git ls-files --stage
tree=$(git write-tree)
commit=$(printf 'first commit\n' | git commit-tree "$tree")
git update-ref refs/heads/main "$commit"
git symbolic-ref HEAD refs/heads/main
git cat-file -p "$commit"
git ls-tree "$tree"git update-index places the blob’s object ID under hello.txt. git write-tree converts the index into a tree object. git commit-tree creates a commit that points to that tree. Finally, git update-ref makes main point to the commit. HEAD is a symbolic reference that names the current branch.
Annotated tags as objects
A lightweight tag is a ref directly naming an object. An annotated tag creates a separate tag object containing the target, tagger, message, and metadata:
git tag -a v1 -m "first release" "$commit"
git cat-file -t v1
git cat-file -p v1
git rev-parse v1 'v1^{commit}'The first command prints tag; the peeled expression v1^{commit} resolves through the tag to the commit.
Loose objects and packfiles
New objects usually begin as loose files under .git/objects/. git gc consolidates them into packfiles, typically .pack plus .idx files.
git count-objects -v
git gc
git count-objects -v
git verify-pack -v .git/objects/pack/pack-*.idxPackfiles reduce space by compressing and delta-encoding related objects.
Reachability and garbage collection
An object is reachable when a ref, such as main or v1, can follow links to it. Objects without such a path are dangling:
orphan=$(printf 'unreferenced\n' | git hash-object -w --stdin)
git fsck --unreachableGarbage collection can eventually delete unreachable objects after its expiration period.
Exercise
Which command turns the index into a tree object?
Show answer
git write-tree.