Kinoko's TIL Log

Git Worktree Mental Model -- Shared Object Store and Branch Lock

The Point

A git worktree is not a repo copy. It checks out an independent working directory (with its own HEAD + index) from a shared .git object store. This architecture is what drives the branch:worktree 1:1 lock and the “cd instead of git switch” workflow.

Explanation

The .git inside a new worktree directory is a file, not a folder. It contains a single line: gitdir: <main repo>/.git/worktrees/<name>/, pointing back to the main repo’s object store. All immutable git data (blobs, trees, commits, remote config) lives in the main .git/ and is shared. Each worktree only owns an independent HEAD and index (staging area). Because the index is per-worktree, git enforces that the same branch can only be checked out by one worktree at a time – otherwise two worktrees running git add simultaneously would overwrite each other’s staging state. So in a multi-worktree setup, “looking at another branch’s code” means cd-ing to the corresponding directory, not running git switch.

Knowledge Sugar

The difference between a worktree and a clone is that a clone copies the entire object database, while a worktree shares it. Docker analogy: clone is like docker save + docker load (a full copy of image layers); worktree is like running a second container from the same image (shared layers, just one more writable layer on top). In large repos where .git/ can be hundreds of MB, the savings are significant.

Useful operations: git worktree list shows all worktrees and their branch bindings; cat <worktree-dir>/.git directly verifies the pointer relationship; when you no longer need a worktree, git worktree remove <path> releases the branch lock – only then can you git switch to that branch from the main worktree.

Claude Code’s design of auto-opening worktrees is worth noting: it avoids touching the state of your current working directory, so it opens an isolated environment to make changes – the same isolation principle as CI not running builds directly on a developer’s checkout.

#git #git-worktree #version-control #til

← Back to Main Page