AI review scripts: handle Git diff exit codes safely
TL;DR: A Git diff command returning a nonzero status can mean either “changes exist” or “the comparison failed.” Handle those states separately before sending a patch to an AI reviewer. Capture the original command’s result directly so that a successful formatter or pipe destination cannot turn a failed comparison into a clean review.
What you’ll be able to do:
- Distinguish an empty staged comparison, a captured patch, and a Git failure.
- Reproduce a shell pipeline that hides a failed diff.
- Prepare review evidence without overwriting an earlier packet.
Honest take: Fix the local evidence handoff before paying another model to review an empty or invalid patch.
Why can an AI review script report success after Git fails?
A shell pipeline can return the status of its final command even when Git failed earlier in the pipeline. For example, a successful cat or tee can leave a script with a successful pipeline status after an invalid revision caused Git to produce no patch. That status says nothing about whether the requested code comparison happened.
There is a second trap: git diff --exit-code intentionally uses a nonzero result when differences exist. A script that treats every nonzero result as a fatal error can reject exactly the patch it was supposed to send for review. The official Git diff manual, checked November 13, 2026, documents the distinction.
This workflow requires an existing Git installation and Python’s standard library. The local reproduction used Git 2.47.3 and needed no GPU, hosted review service, API request, or subscription. Its purpose is to protect the review input. It does not establish a monetary saving, a token reduction, or improved bug detection by any particular AI tool.
What do Git diff exit codes mean here?
For git diff --exit-code, status 0 means no differences in the requested comparison, and status 1 means differences were found. Treat other statuses as failures to investigate, rather than clean comparisons. Preserve stderr because an error message often explains the missing evidence immediately.
| Result of the requested diff | How the wrapper should classify it | May it claim a clean review? |
|---|---|---|
0 | No differences for this comparison | No; it only describes the selected snapshot |
1 | Differences exist | No; capture and inspect the patch |
| Any other status | Comparison failed | No; stop this review handoff |
The option matters. Plain git diff does not use the same “differences found” status behavior unless the relevant option is requested. Do not build one generic status rule and assume it describes every Git subcommand. --check, --quiet, and external diff programs also have their own documented implications.
An empty staged diff is narrower than a clean repository. It can coexist with unstaged edits or untracked files. Inspect repository status and decide what the reviewer should evaluate. The existing staged-diff guide explains that snapshot boundary.
How can you reproduce a false success locally?
Use a disposable repository and an intentionally invalid revision to separate command failure from review quality. The test below assumes a scratch repository containing a commit; do not create or rename branches in a real project merely to reproduce this.
git diff --exit-code missing-fixture-ref -- | cat >/dev/null
echo "$?"
In the local November 13 fixture, Git printed:
fatal: bad revision 'missing-fixture-ref'
The ordinary Bash pipeline returned 0, because its final command completed successfully. Running the same pipeline with pipefail enabled returned 128 in that fixture:
set -o pipefail
git diff --exit-code missing-fixture-ref -- | cat >/dev/null
echo "$?"
The installed Bash built-in help (bash -c 'help set') defines pipefail as returning the last nonzero command status, or zero when no command fails. We checked that primary local help alongside the actual pipeline test. The number 128 is the observed invalid-reference result here; the acceptance rule should reject every result outside the expected 0 and 1, rather than assuming all failures share that number.
pipefail helps propagate a failure, but it does not decide what 1 means for your chosen Git command. A wrapper still needs explicit classification. Nor does it preserve stdout, stderr, the comparison arguments, and the selected revision automatically. Those remain part of your evidence design.
How should a Python wrapper capture a staged patch?
Call Git directly, retain stdout and stderr separately, and classify the completed process before creating the output file. Python’s subprocess reference documents returncode, captured streams, and the behavior of check.
Save this as capture_review.py:
import json
from pathlib import Path
import subprocess
import sys
def capture_review(repo, output):
result = subprocess.run(
["git", "-C", str(repo), "diff", "--cached", "--exit-code",
"--no-ext-diff", "--no-textconv", "--no-color", "--"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False,
)
if result.returncode not in (0, 1):
raise RuntimeError("Git diff failed: " + result.stderr.decode(
"utf-8", errors="replace").strip())
if result.returncode == 0:
return {"status": "NO_STAGED_DIFF", "bytes": len(result.stdout)}
if not result.stdout:
raise RuntimeError("Git reported changes but supplied no patch")
with Path(output).open("xb") as target:
target.write(result.stdout)
return {"status": "PATCH_CAPTURED", "bytes": len(result.stdout)}
if __name__ == "__main__":
print(json.dumps(capture_review(sys.argv[1], sys.argv[2])))
Run it from a terminal, supplying the repository and a new private output path:
python3 capture_review.py /path/to/repository /private/review/staged.patch
The parent output directory must already exist. The helper uses exclusive binary creation, so a previous patch cannot be silently overwritten. It captures bytes directly; it does not decode and re-encode the patch. Diagnostic stderr is decoded only if Git fails.
The --cached comparison selects staged changes. --no-ext-diff and --no-textconv keep configured external display helpers out of this capture, while --no-color avoids terminal color sequences. These controls do not turn the patch into a semantic review of every artifact. They make the evidence path easier to interpret.
No shell is involved in this Python invocation, so there is no final pipeline command to mask Git’s result. The helper also keeps check=False deliberately: it must inspect the ordinary differences-found status rather than have Python classify that status as an unexpected exception. Errors still stop the handoff explicitly.
What did the wrapper tests verify?
The local test created a scratch repository, committed before in a text file, then staged a change to after. The published wrapper was executed against those actual Git states. Its results were:
| Local fixture | Observed result | Output artifact |
|---|---|---|
| Nothing staged after the initial commit | NO_STAGED_DIFF, 0 bytes | No patch created |
Text changed from before to after and staged | PATCH_CAPTURED, 128 bytes | Patch contains the added after line |
| Repository path does not exist | Exception with Git stderr | No patch created |
| Destination patch already exists | FileExistsError | Existing patch preserved |
Invalid revision piped to cat | Pipeline status 0 without pipefail | Demonstrates the masking problem |
The patch size is a measured byte count for this tiny fixture, not a tokenizer count or a price quote. Different paths, contents, Git versions, and settings can produce a different patch size. The helper reports the actual count instead of promising the fixture’s count for your project.
The tests establish control-flow behavior: known differences are captured, missing evidence is rejected, and an earlier artifact is preserved. They do not measure AI review accuracy. No external model was asked to inspect the fixture, and no claim is made about how many bugs this procedure would catch in a real codebase.
What should accompany the patch sent for review?
Attach the intended comparison description and a concise status inventory after reviewing them for the destination’s data policy. A reviewer needs to know whether the patch represents staged work, a branch comparison, or working-tree edits. The helper produces only the staged patch; it does not assemble a complete context package.
git -C /path/to/repository status --short
git -C /path/to/repository rev-parse --verify HEAD
git -C /path/to/repository diff --cached --stat
The rev-parse manual describes revision verification. If you later adapt the wrapper to compare named revisions, validate the intended revisions and preserve the exact arguments. Do not fall back to a different base when the requested base cannot be resolved; that changes the review question.
Keep the repository stable while capturing related artifacts. Another process can stage changes between commands, so a patch and a later status listing are not automatically one atomic snapshot. For a high-assurance review, establish a project-appropriate freeze or immutable comparison and record it. This small helper does not lock the index or freeze the working directory.
Review the files locally before uploading the packet. Disabling text conversion does not remove credentials or confidential source code from staged changes. The appropriate input budget is the smallest complete, authorized evidence set, not whatever happens to be shortest after a filter.
Does a captured patch cover binaries and submodules?
A captured text patch does not establish that binary payloads or submodule contents were meaningfully reviewed. Git can represent those changes without showing the complete artifact in the parent repository’s ordinary patch. A successful exit classification only establishes that this capture command completed as expected.
Use the binary and submodule inventory guide before treating a text packet as the whole change. For branch work, the merge-base review guide addresses another separate question: whether the comparison starts at the correct shared base.
Likewise, an empty path-limited diff can simply mean your path selection matched no changed files. Exit handling cannot infer the user’s intended paths. Keep selection, successful execution, artifact capture, and semantic review as separate checks. A wrapper that passes all execution tests can still ask the reviewer the wrong question.
Honest take: when is this wrapper the wrong choice?
Use a different comparison when the work has not been staged, when you need a branch-wide review, or when your project intentionally relies on a specialized diff driver. The wrapper is deliberately narrow. It should not quietly switch to working-tree changes or enable a helper just to produce a nonempty patch.
It also stores the entire patch in memory and writes directly to a new file after capture. A disk-write failure can leave a partial output file; require the successful PATCH_CAPTURED result before consuming it, and inspect an interrupted artifact before any retry. It is not a transactional artifact service or a long-running CI system.
For an ordinary staged review, the decision is straightforward: classify the original Git result, reject comparison failures, preserve the patch, then review the actual change. Another model pass cannot repair evidence that never reached the model.
Sources
- Diff options and exit-code behavior — Git
- Bash built-in
help set, checked locally with the pipeline fixture. - Exclusive file creation — Python
- Completed processes and captured output — Python
- Repository status — Git
- Revision verification — Git
Last updated November 13, 2026. Official documentation and local Git fixtures were checked on this date. Tests covered capture and failure handling, not AI review quality, billed tokens, or monetary savings.
Was this article helpful?
Thanks for the feedback — it helps improve future articles.
Need hands-on help?
I offer 1-on-1 technical consulting for local AI setup, GPU selection, and AI coding tool configuration — same topics covered on this site.
Book a session — $49 / hour →Know which coding tool is worth paying for
Hands-on comparisons of AI coding assistants and what each one costs to run — including the local-model path. Sent only when something changes. Unsubscribe anytime.