git diff --cached | git apply: Seven Traps in Copying a Staged Index

I wanted a review tool to see exactly what my next commit will contain, and nothing else. No unstaged edits, no untracked scratch files. The obvious way is to rebuild the staged index in a temporary repository and point the tool at that:
git -C "$src" diff --cached | git -C "$tmp" apply --index
A separate post argues why the staged diff is the right boundary for an AI assistant. This one is about moving that boundary to another directory without changing it.
My first probe of the idea passed.
A staged patch with a modification, a deletion, a rename, a mode change, and a binary file went into a fresh repository through git apply --index --binary, and the index listing matched byte for byte.
Then seven things went wrong, in the pipe or in the fixes around it, before the feature merged as PR #86 of my andrew-code-agent project.
In one of them the copied index matched the original entry for entry, and the reviewer could still read a file I had not staged.
None of the seven was found in production.
A second probe found some, the final whole-branch review found others, and the rest came from hosted review rounds or the local review pass before each push.
The spec records which was which.
That second probe ran on Git 2.54.0. The output below is from my rerun on git 2.50.1 (Apple Git-155), macOS 26.7.3, in a throwaway repository.
1. The source repository's own diff settings
git diff is porcelain, so it reads diff.* and color.* from the repository it runs in.
Three settings each produce a patch that git apply rejects.
# diff.noprefix=true
error: git diff header lacks filename information when removing 1 leading pathname component (line 5)
# color.ui=always
error: No valid patches in input (allow with "--allow-empty")
# diff.context=0
error: patch failed: a.txt:5
error: a.txt: patch does not apply
The second probe caught diff.noprefix and color.ui while the design was still on paper.
diff.context=0 got through and was caught later, by a hosted review round or the local pass.
The fix is to pin the output format instead of trusting defaults:
git -c core.quotePath=true diff --cached \
--no-color --unified=3 --src-prefix=a/ --dst-prefix=b/ \
--no-ext-diff --no-textconv --binary --full-index --
core.quotePath belongs to trap 4.
2. The plumbing escape changes what "staged" means
The textbook answer to trap 1 is plumbing: git diff-index --cached -p HEAD ignored all three settings in my rerun.
It also changes the answer for git add -N.
$ git ls-files --stage
100644 7155914b3e2999c8b0588cbf18442cd9975fa0ce 0 a.txt
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0 new.txt
$ git diff --cached --name-status
M a.txt
$ git diff-index --cached --name-status HEAD
M a.txt
A new.txt
An intent-to-add entry sits in the index with the empty blob.
Porcelain omits it; plumbing emits it as an empty new file.
With plumbing, the reviewer would get an empty new.txt, a file the commit will not contain.
With porcelain, the temp index lacks the entry, the listings differ, and the tool refuses.
Plumbing was considered while fixing diff.context and rejected for this reason.
I kept porcelain and the pinned flags, and I come back to that choice below.
3. Decoding the patch as UTF-8
My tool is Node, and the first version read Git's stdout with encoding: "utf8".
A patch is bytes.
A Latin-1 text file containing café has the byte e9, which is not valid UTF-8.
raw bytes: 198
after utf8 decode and re-encode: 200
raw tail: 2b636166e90a
decoded tail: 2b636166efbfbd0a
Decoding replaced e9 with U+FFFD, three bytes.
The spec lists three kinds of file that hit this: a legacy-encoded text file, a binary file without a NUL byte, and a binary file that a diff driver forces to a text diff.
Each stopped with the mismatch error until the patch was read as a Buffer.
A redirect to a file kept the bytes intact in my rerun; a wrapper that decodes stdout into a string before writing it back did not.
4. A path that is not UTF-8
The same decoding hits file names.
With core.quotePath=false, Git writes the raw path into the header; with true, it writes an escape:
diff --git "a/caf\351.txt" "b/caf\351.txt"
The unquoted form went through the UTF-8 decode and the file was renamed.
Worse, the string comparison of the two index listings still passed, so the identity check did not stop it.
The final branch review found it, and -c core.quotePath=true fixed the patch.
The spec records that such a path still ends in a refusal with exit 3, because APFS will not create the file.
That is the right outcome: stop, do not rename.
5. A case-only rename on a case-insensitive file system
git mv Foo.txt foo.txt, then apply the patch to a temp repository whose worktree is already checked out:
error: foo.txt: already exists in working directory
git apply --index updates the index and the worktree together, and on a case-insensitive volume the old Foo.txt answers for foo.txt.
The final branch review found this too.
The fix reorders the build: never check out HEAD, apply the patch to the index only, and write the worktree once from the finished index.
6. A tracked absolute symlink walks back out
The index stores a symlink as its target string.
checkout-index recreates the link, and an absolute target points into the source worktree.
In my rerun, a tracked link to a file with an unstaged edit gave the temp checkout this:
$ cat latest
UNSTAGED SECRET
The index matched perfectly, and the reviewer could still read content I had not staged.
Setting core.symlinks=false in the temp repository writes the link as a plain file that holds the target path.
git diff --quiet still exits 0 with that setting.
7. diff.ignoreSubmodules=all hides a staged gitlink
The tool refuses to review a staged submodule change, and it detects one by scanning git diff --cached --raw for mode 160000.
With diff.ignoreSubmodules=all, the scan printed nothing while the gitlink sat in the index:
$ git diff --cached --raw
$ git diff --cached --raw --ignore-submodules=none
:000000 160000 0000000 7149875 A vendor/lib
This one is not in the transport path. It is the same bug class in a guard beside it, and it also affected the commit command that shares the reader.
The construction that held
This is the tool's sequence rewritten as a shell script.
It is a variant, not the tool: the tool also sets core.logAllRefUpdates=false, LC_ALL=C and GIT_NO_REPLACE_OBJECTS=1, which the script leaves out.
Commands in the temporary repository ignore system and global configuration; the source is read with whatever configuration it has, because the pinned flags are what neutralize it.
#!/bin/bash
set -euo pipefail
src=$(cd "$1" && pwd -P) # the repository with staged changes, as an absolute path
tmp=$(mktemp -d) # holds the patch, the listing, and the new repository
tgit() { GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 git -C "$tmp/repo" "$@"; }
# 1. Read the source: HEAD, the index listing, and the patch with pinned flags.
head=$(git -C "$src" rev-parse HEAD)
git -C "$src" ls-files --stage -z > "$tmp/index"
git -C "$src" -c core.quotePath=true diff --cached \
--no-color --unified=3 --src-prefix=a/ --dst-prefix=b/ \
--no-ext-diff --no-textconv --binary --full-index -- > "$tmp/patch"
# 2. Build the index first, and the worktree once, from the index.
mkdir "$tmp/repo"
tgit init --quiet --initial-branch=scratch
tgit fetch --quiet --no-tags --no-write-fetch-head --update-shallow \
"$src" "$head:refs/heads/review-head"
tgit update-ref --no-deref HEAD "$head"
tgit config core.symlinks false
tgit read-tree review-head
tgit apply --cached --binary "$tmp/patch"
tgit checkout-index --all
# 3. Accept the result only if all four checks pass.
[ "$(tgit rev-parse --verify 'HEAD^{commit}')" = "$head" ]
tgit ls-files --stage -z | cmp - "$tmp/index"
tgit diff --quiet --no-ext-diff --no-textconv
[ -z "$(tgit ls-files --others)" ]
echo "$tmp/repo"
I ran it against a source repository with diff.noprefix=true, color.ui=always, diff.context=0, and core.quotePath=false set, holding a staged edit, a case-only rename, a deletion, a mode change, a binary file, a Latin-1 file, an unstaged edit, and an untracked file.
It exited 0, and the temp worktree had neither the unstaged line nor the untracked file.
Against the intent-to-add repository from trap 2 it exited 1 at the cmp line.
The TypeScript original is createStagedReviewCheckout.
Why the check is the index listing
git ls-files --stage prints the mode, the blob object ID, and the path of every entry.
If two listings are equal, the two indexes describe the same content.
Comparing patch text is weaker, because trap 1 already showed that identical content produces different patch text under different configuration.
The listing alone is not enough, and traps 4 and 6 are why.
Compare it as bytes, as cmp does here, since a comparison of decoded strings passed with a renamed path.
Writing this article found that gap a second time.
When I checked the script against the tool, the tool was still comparing the two listings as decoded strings, so its last guard had the weakness of trap 4.
PR #148 moved it to raw bytes on November 13, with a test that builds the renamed checkout and failed before the change.
And an equal index says nothing about where a symlink in the worktree leads.
The choice I would expect pushback on
I pinned porcelain instead of switching to plumbing.
The strongest argument against that is good: plumbing exists so scripts do not depend on configuration, and a pinned flag list is a denylist.
Mine grew in three stages, a probe, a branch review, and review rounds, and I cannot prove it is complete.
Someone could reasonably use diff-index and detect intent-to-add entries separately.
I stayed with porcelain for one reason.
The tool reviews what git commit would create, and porcelain diff --cached already agrees with that about add -N.
With plumbing I would be re-deriving that rule myself.
What makes an incomplete denylist acceptable is the check after it: a setting I missed produces a refusal, not a review of the wrong content.
A different design skips the patch entirely: run git write-tree in the source and transport the tree.
That creates an object in the source repository, and this tool's spec says it writes no objects or refs there.
I did not build or test that design, so I cannot say which traps it has.
Limits
The spec gives Git 2.54.0 for the second probe and no version for the review-stage findings; my outputs are from git 2.50.1 (Apple Git-155) on APFS.
I did not run any of this on Linux or Windows, and trap 5 needs a case-insensitive volume to appear at all.
The tool also passes the source's object format to git init; the script above does not.
A merge in progress, an unresolved conflict, a staged submodule, an intent-to-add entry next to a staged change, and a path that is not UTF-8 all still stop with exit 3.
I did not reproduce the non-UTF-8 path refusal myself; the spec attributes it to APFS.
Symlinks reach the reviewer as plain files, so a review that depends on following a link sees less than a real checkout would.
And the tool caps captured Git output at 16 MiB, so a larger staged patch is refused, not truncated.
Get the next post.
Follow new posts in your RSS reader.