Sub topic 5
Checking what is actually being committed
This chapter assumes you can write a basic pre-commit hook that exits non-zero to block a commit. It also assumes you know the difference between the index (the staging area) and the working tree. If the shell scripts below look unfamiliar, review those two ideas first.
The problem: the working tree is not the commit
A commit records the index, not the files in your working directory. Most of the time the two match, so a hook that reads files from disk appears to work. They diverge as soon as you use git add -p, stage only some files, or keep editing after git add.
Here is a demonstration:
printf 'echo "clean"\n' > deploy.sh
git add deploy.sh
printf 'echo "debug" \n' >> deploy.sh
git diff --cached --check; echo "staged check: $?"
git diff --check; echo "working tree check: $?"The first command inspects what would be committed. It finds nothing and exits with status 0. The second command compares the working tree to the index. It reports the trailing whitespace on the new line and exits non-zero. That line is not staged, so it will not be in the commit.
A hook that runs the second command would block a perfectly good commit. The opposite mistake is worse. If the staged version has a problem but the file on disk has since been fixed, a hook that reads the disk passes the commit, and the broken content is committed anyway.
Commands that read staged state
Git has several ways to read the index. Choose by what your checking tool needs as input.
| Goal | Command |
|---|---|
| Show staged changes as a diff | `git diff --cached` |
| List staged paths | `git diff --cached --name-only --diff-filter=ACM -z` |
| Print one staged file | `git show :path/to/file` |
| Write staged files into a directory | `git checkout-index --prefix=dir/ -- path/to/file` |
| List files with unstaged edits | `git diff --name-only -z` |
--cached and --staged are synonyms. In git show :path, the leading colon means "the version of this path in the index". The path is relative to the repository root.
Built-in checks
Some checks need no external tool. git diff --cached --check reports whitespace errors and leftover conflict markers in added lines only. It looks at the staged diff, so it ignores old problems in lines you did not touch. That makes it a good first check for a new project, because it does not demand cleanup of existing code.
Other checks can scan the staged diff with grep. This hook rejects staged lines that add a debugger call:
#!/bin/sh
# .githooks/pre-commit
# Reject added lines that contain a leftover debugger statement.
if git diff --cached -U0 | grep -E '^\+.*(debugger;|import pdb|binding\.pry)'; then
echo "pre-commit: remove the debugger statement above." >&2
exit 1
fi
exit 0With -U0 the diff has no context lines. The pattern starts with ^\+, so it matches only added lines. The +++ b/file header lines also start with +, but they would match only if a file name contained one of those strings.
Listing files: filters and file names
Most hooks need the list of files to check. Two details matter.
Filter by change type
--diff-filter=ACM keeps files that were Added, Copied or Modified. It drops Deleted files, which no longer exist and would make your linter fail with "file not found". Renamed files appear as R and would be skipped by ACM. Add R (--diff-filter=ACMR) if you want to check them. Git detects renames in git diff by default, so a file you moved and edited appears as a rename.
Handle awkward names with `-z`
By default, Git prints paths one per line and quotes names that contain unusual characters. Splitting that output on whitespace breaks for names with spaces. The -z option prints each path terminated by a NUL byte, which cannot appear in a file name. Read it in Bash with read -d ''.
This version of the shellcheck hook checks the staged content and survives spaces in names:
#!/bin/bash
# .githooks/pre-commit
# Run shellcheck on the staged version of each added, copied or modified .sh file.
status=0
while IFS= read -r -d '' f; do
git show ":$f" | shellcheck - || status=1
done < <(git diff --cached --name-only --diff-filter=ACM -z -- '*.sh')
exit $statusThree points about this script:
- It uses
#!/bin/bashbecauseread -d ''and process substitution are not POSIXsh. - It reads the loop input through
< <(...)instead of a pipe. A pipe would run the loop in a subshell, and thestatus=1assignment would be lost when the subshell ends. - It does not stop at the first failure. It checks every file, so the developer sees all problems in one run.
The sh version in the earlier chapters loops over $(git diff ...), which splits on whitespace. That is acceptable for a repository where you control all file names. Use the -z version when you do not.
Tools that need real files
Some tools cannot read standard input. They need a file on disk, or they need to see neighbouring files such as a config or a tsconfig.json. For those, export the index to a temporary directory and run the tool there.
#!/bin/bash
# .githooks/pre-commit
# Check the staged tree, not the working tree, using a temporary export.
tmp=$(mktemp -d) || exit 1
trap 'rm -rf "$tmp"' EXIT
git checkout-index --all --prefix="$tmp/" || exit 1
cd "$tmp" || exit 1
find . -name '*.sh' -print0 | xargs -0 shellcheckgit checkout-index --all --prefix="$tmp/" writes every file in the index under the prefix directory. The trailing slash in the prefix matters, because Git concatenates the prefix and the path. The trap removes the directory when the script exits, including when it fails.
The script's exit status is the status of the last command, xargs. When xargs runs shellcheck and any invocation fails, xargs exits with a non-zero status, which aborts the commit. If the repository has no .sh files, GNU xargs still runs shellcheck once with no arguments, and shellcheck reports a usage error. In a real hook, guard that case or use a tool that tolerates empty input.
Exporting the whole index costs time and disk in a large repository. Export only the needed paths, or limit the export with a pathspec. Run git checkout-index --prefix="$tmp/" -- path1 path2 for a chosen list.
Rewriting hooks and partially staged files
A formatter in a hook can fix problems automatically. The naive version runs the formatter on the working tree files and then runs git add on them. This has a hazard: if you staged only part of a file with git add -p, the formatter works on the whole file, and git add stages the unstaged hunks too. The commit then includes changes you chose to leave out.
There are three safe approaches:
- Check only, and fail. The hook reports the problem, the developer runs the formatter, and the developer stages the result.
- Skip auto-fix for files that have unstaged changes. Detect them with
git diff --name-only -zand compare against the staged list. - Use a tool that handles this for you. The
pre-commitframework andlint-stagedstash unstaged changes before running, then restore them after the hooks finish.
Edge cases to plan for
- Commits with paths or
-a. Withgit commit -a, Git stages tracked changes before it runspre-commit, so the hook sees them in the index. Withgit commit path/to/file, Git builds a temporary index containing only the named paths and runs the hook withGIT_INDEX_FILEpointing to it. Plaingit diff --cachedcalls inside the hook honour that variable automatically, so your commands stay correct. Do not unset or overrideGIT_INDEX_FILEin the hook. - First commit. In a repository with no commits,
git diff --cachedstill works. Git compares the index against the empty tree. - Deleted and renamed files. Filter with
--diff-filter, as above. A hook that calls a linter on a deleted path fails for a reason unrelated to code quality. - Merge commits. During a conflicted merge, the index holds extra entries for unresolved paths, and a commit cannot proceed until they are resolved. After you resolve the conflicts and run
git commit,pre-commitruns on the merge result. Your check may flag lines that came from the other branch. Decide whether you want to check merges, and testgit rev-parse -q --verify MERGE_HEADif you want to skip them. - Binary files and symlinks.
git diff --cached --checkskips binary content. A symlink in the index is stored as the link target text, sogit show :linkprints the target path, not the file it points to. - Submodules. A submodule appears in the index as a commit ID, not as files. Filter these out if your tool expects file contents.
Summary of rules
- Read content from the index with
git show :path,git diff --cachedor an export fromgit checkout-index. - Filter by change type so deleted paths are not passed to tools.
- Use
-zwith NUL-safe reading when file names may contain spaces. - Do not stage files automatically from a hook unless you have handled partial staging.
- Treat hook failures as information for the developer. Print what failed and what to do.
Exercise
A developer stages app.py with git add app.py, then edits the file again and introduces a syntax error without staging it. The pre-commit hook runs python -m py_compile app.py. Does the hook block the commit, and is that the right outcome? How would you change the hook?
Show answer
The hook blocks the commit, because py_compile reads the working tree file with the syntax error. That is the wrong outcome. The staged version is valid, so the commit itself is fine. Change the hook to read the index, for example git show :app.py | python -c 'import sys; compile(sys.stdin.read(), "app.py", "exec")', or export the staged files with git checkout-index --prefix="$tmp/" and compile them there.
Exercise
Why does the shellcheck hook in this chapter read its file list with done < <(git diff ...) and not git diff ... | while ...?
Show answer
In a pipeline, the while loop runs in a subshell. Any change to status inside the loop is lost when the subshell exits, so the final exit $status would always return 0 and the hook would never block a commit. Process substitution keeps the loop in the main shell, so the variable survives.
Exercise
You add --diff-filter=ACM to your file list. A developer renames old.sh to new.sh without editing it and commits. Is new.sh checked? What would you change if you want it checked?
Show answer
It is not checked. Git reports the rename with status R, which ACM excludes. Use --diff-filter=ACMR to include renamed files.