From b170f2110c980066f0f193d34c434d7cee49311f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Thu, 19 Nov 2026 16:27:11 -0800 Subject: [PATCH] perf(git): batch the pre-commit final newline check The hook used a `tail` subprocess per tracked text file, paying for thousands of process launches on every commit. Shell splitting also lost valid filenames and reported some binary files as missing an LF. Ast-grep's language-specific node regexes cannot check the raw EOF of an arbitrary tracked file reliably. Pass NUL-delimited paths and the existing exclusions to a standalone Rust checker. Read one byte for files that already end in LF; for the rest, report a violation only after ruling out NUL bytes. Keep the legacy inventories for other hooks and accept an empty selection. The generated newline-only pre-commit dispatcher and runner took 0.205s instead of 3.872s (median of seven warm runs, 2,048 synthetic tracked files on x86_64 Linux). Both versions rejected a staged missing-LF text file. Review: fixed absent paths whose parent was replaced by a file, tested production package wiring, and guarded the non-UTF-8 filename test on filesystems that forbid it. The follow-up review passed. --- .config/flakebox/id | 2 +- checks/git-hooks.nix | 86 +++++++++++++++++++++ lib/modules/git.nix | 57 ++++++++------ lib/modules/git/pre-commit.body.bash | 8 +- lib/pkgs/git-check-newline.nix | 22 ++++++ lib/pkgs/git-check-newline.rs | 108 +++++++++++++++++++++++++++ misc/git-hooks/pre-commit | 37 ++++----- 7 files changed, 268 insertions(+), 52 deletions(-) create mode 100644 lib/pkgs/git-check-newline.nix create mode 100644 lib/pkgs/git-check-newline.rs diff --git a/.config/flakebox/id b/.config/flakebox/id index 2c55ff5..7e83cbc 100644 --- a/.config/flakebox/id +++ b/.config/flakebox/id @@ -1 +1 @@ -515ae2f3483180933c9d348041bafad0ce0e59fd7972f984d0a0119b8ed1b7c5649b9f52d580fabe6d70f6853477927bd6cbe6e2d8882b0221b3cbdb7964386f +8ec289da601860ebbfa8eb50af1b67ee78411530a7242b10ec197fcea94891fd591831186d94aff57d312cfdbd3f5bafdc6f99810596bd3ebd96800b8ddbce4f diff --git a/checks/git-hooks.nix b/checks/git-hooks.nix index 4102d59..bcdbc74 100644 --- a/checks/git-hooks.nix +++ b/checks/git-hooks.nix @@ -69,6 +69,17 @@ let inherit (flakeboxLib.config.git.pre-commit.hooks) shellcheck; }; + newlineLib = mkLib pkgs { + config.git.pre-commit = { + trailing_newline = true; + trailing_whitespace = false; + hooks = builtins.mapAttrs (_: _: pkgs.lib.mkForce null) ( + builtins.removeAttrs flakeboxLib.config.git.pre-commit.hooks [ "trailing_newline" ] + ); + }; + }; + newlineHooks = newlineLib.root; + gitDisabledLib = mkLib pkgs { config = { git.enable = false; @@ -192,6 +203,7 @@ pkgs.runCommand "git-hooks-tests" timer testFlakeboxBin ] + ++ newlineLib.config.env.shellPackages ++ pkgs.lib.optionals pkgs.stdenv.isLinux [ pkgs.util-linux ]; } '' @@ -1176,6 +1188,80 @@ pkgs.runCommand "git-hooks-tests" [ "$(grep -c '^invocation$' "$FLAKEBOX_SHELLCHECK_LOG")" -eq 2 ] cd .. + # The newline hook sees all tracked files and uses raw path records, not + # Git's quoted display or shell word splitting. + mkdir newline-repo + cd newline-repo + git init -q + git config user.email flakebox@example.invalid + git config user.name Flakebox + printf 'ok\n' > good + printf 'ok\r\n' > crlf + touch empty + printf 'bad' > 'space name' + printf 'bad' > 'literal[glob]' + printf 'ok\n' > literalg + printf 'bad' > $'embedded\nnewline' + # APFS only accepts valid UTF-8 at creation. + if printf 'bad' 2>/dev/null > $'non-utf8-\377'; then + expected_violations=5 + else + expected_violations=4 + fi + printf 'bad' > ./-leading-dash + printf 'bad' > global.ignore + printf 'bad' > text.ignore + printf 'bad' > image.png + printf 'bad' > deleted + mkdir directory + printf 'bad' > directory/child + printf '\0payload' > binary + printf 'payload\0' > binary-last-nul + { head -c 32768 /dev/zero | tr '\0' A; printf '\0payload'; } > binary-late-nul + ln -s 'space name' symlink + git add . + git commit -qm base + rm deleted + mv directory saved-directory + printf 'untracked\n' > directory + printf 'bad' > untracked + + if NO_STASH=1 FLAKEBOX_GIT_LS_IGNORE='^global[.]ignore$' \ + FLAKEBOX_GIT_LS_TEXT_IGNORE='^text[.]ignore$' \ + bash ${newlineHooks}/misc/git-hooks/pre-commit > result 2>&1; then + echo "expected newline hook to reject tracked text files" >&2 + exit 1 + fi + grep -F -- 'space name doesn' result + grep -F -- 'literal[glob] doesn' result + grep -F -- '"embedded\nnewline" doesn' result + if [ "$expected_violations" -eq 5 ]; then + grep -F -- '"non-utf8-\xFF" doesn' result + fi + grep -F -- '-leading-dash doesn' result + [ "$(grep -c "doesn't end with a newline" result)" -eq "$expected_violations" ] + grep -F 'Fix the problems above or use --no-verify' result + [ ! -e deleted ] + + # Check the index in an ordinary Git repo, and restore unstaged edits. + rm directory + mv saved-directory directory + git rm -q directory/child + git add -u -- deleted + printf 'fixed\n' > 'space name' + git add 'space name' + printf 'bad' > 'space name' + FLAKEBOX_GIT_LS_TEXT_IGNORE='^(-leading-dash|literal\[glob\]|embedded|non-utf8-|global[.]ignore|text[.]ignore)' \ + bash ${newlineHooks}/misc/git-hooks/pre-commit + [ "$(cat 'space name')" = bad ] + + # Zero selected files is success, both with filtered and empty inventories. + FLAKEBOX_GIT_LS_IGNORE='.' bash ${newlineHooks}/misc/git-hooks/pre-commit + FLAKEBOX_GIT_LS_TEXT_IGNORE='.' bash ${newlineHooks}/misc/git-hooks/pre-commit + git rm -qrf --cached . + bash ${newlineHooks}/misc/git-hooks/pre-commit + cd .. + # Private patch restoration exposes indexed content to checks and restores # tracked worktree changes afterwards without touching the user stash. mkdir stash-repo diff --git a/lib/modules/git.nix b/lib/modules/git.nix index 70392c8..d8b8a48 100644 --- a/lib/modules/git.nix +++ b/lib/modules/git.nix @@ -8,6 +8,8 @@ let inherit (lib) types; gitHookCheckTimer = pkgs.callPackage ../pkgs/git-hook-check-timer.nix { }; + gitCheckNewline = pkgs.callPackage ../pkgs/git-check-newline.nix { }; + textExclude = ''\.(png|ods|jpg|jpeg|woff2|keystore|wasm|ttf|jar|ico|gif)$''; in { @@ -21,9 +23,17 @@ in default = true; }; - trailing_newline = lib.mkEnableOption "git pre-commit trailing newline check" // { - default = true; - }; + trailing_newline = + lib.mkEnableOption "git pre-commit trailing newline check for tracked text files" + // { + default = true; + description = '' + Require a final LF in nonempty tracked text files. Known binary + extensions and files containing a NUL byte are skipped. + `FLAKEBOX_GIT_LS_IGNORE` and `FLAKEBOX_GIT_LS_TEXT_IGNORE` are + extended regular expressions matched against raw Git paths. + ''; + }; trailing_whitespace = lib.mkEnableOption "git pre-commit trailing whitespace check" // { default = true; @@ -88,26 +98,17 @@ in (lib.mkIf config.git.pre-commit.trailing_newline { git.pre-commit.hooks.trailing_newline = '' - errors="" - for path in $(echo "$FLAKEBOX_GIT_LS_TEXT"); do - - # extra branches for clarity - if [ ! -f "$path" ] || [ ! -s "$path" ]; then - # echo "$path is not a file or is empty" - true - elif [ -z "$(tail -c 1 < "$path")" ]; then - # echo "$path ends with a newline or with a null byte" - true - else - >&2 echo "$path doesn't end with a newline" 1>&2 - errors="true" - fi - done - - if [ -n "$errors" ]; then - >&2 echo "Fix the problems above or use --no-verify" 1>&2 - return 1 + # Keep filenames as NUL-delimited records, not Git-quoted shell words. + excludes=(-e '${textExclude}') + if [[ -n "''${FLAKEBOX_GIT_LS_IGNORE:-}" ]]; then + excludes+=(-e "$FLAKEBOX_GIT_LS_IGNORE") fi + if [[ -n "''${FLAKEBOX_GIT_LS_TEXT_IGNORE:-}" ]]; then + excludes+=(-e "$FLAKEBOX_GIT_LS_TEXT_IGNORE") + fi + git ls-files -z --deduplicate | + { grep -azEv "''${excludes[@]}" || [[ $? == 1 ]]; } | + flakebox-git-check-newline ''; }) @@ -247,7 +248,9 @@ in exit 0 fi - ${builtins.readFile ./git/pre-commit.body.bash} + ${builtins.replaceStrings [ "@textExclude@" ] [ textExclude ] ( + builtins.readFile ./git/pre-commit.body.bash + )} ${hooksFns} ${runHooks} # @@ -267,7 +270,13 @@ in ''; }; - env.shellPackages = [ gitHookCheckTimer ]; + env.shellPackages = [ + gitHookCheckTimer + ] + ++ lib.optionals config.git.pre-commit.trailing_newline [ + gitCheckNewline + pkgs.gnugrep + ]; }) diff --git a/lib/modules/git/pre-commit.body.bash b/lib/modules/git/pre-commit.body.bash index a5273e4..7b71ae5 100644 --- a/lib/modules/git/pre-commit.body.bash +++ b/lib/modules/git/pre-commit.body.bash @@ -40,14 +40,14 @@ fi export FLAKEBOX_GIT_LS if [ -z "${FLAKEBOX_GIT_LS_IGNORE:-}" ]; then - FLAKEBOX_GIT_LS="$(git ls-files | while read -r file; do [ ! -L "$file" ] && echo "$file"; done)" + FLAKEBOX_GIT_LS="$(git ls-files | while read -r file; do if [ ! -L "$file" ]; then printf '%s\n' "$file"; fi; done)" else - FLAKEBOX_GIT_LS="$(git ls-files | grep -v -E "${FLAKEBOX_GIT_LS_IGNORE}" | while read -r file; do [ ! -L "$file" ] && echo "$file"; done)" + FLAKEBOX_GIT_LS="$(git ls-files | { grep -v -E -e "${FLAKEBOX_GIT_LS_IGNORE}" || [[ $? == 1 ]]; } | while read -r file; do if [ ! -L "$file" ]; then printf '%s\n' "$file"; fi; done)" fi export FLAKEBOX_GIT_LS_TEXT if [ -z "${FLAKEBOX_GIT_LS_TEXT_IGNORE:-}" ]; then - FLAKEBOX_GIT_LS_TEXT="$(echo "$FLAKEBOX_GIT_LS" | grep -v -E "\.(png|ods|jpg|jpeg|woff2|keystore|wasm|ttf|jar|ico|gif)\$")" + FLAKEBOX_GIT_LS_TEXT="$(printf '%s\n' "$FLAKEBOX_GIT_LS" | { grep -v -E -e '@textExclude@' || [[ $? == 1 ]]; })" else - FLAKEBOX_GIT_LS_TEXT="$(echo "$FLAKEBOX_GIT_LS" | grep -v -E "\.(png|ods|jpg|jpeg|woff2|keystore|wasm|ttf|jar|ico|gif)\$" | grep -v -E "${FLAKEBOX_GIT_LS_TEXT_IGNORE}")" + FLAKEBOX_GIT_LS_TEXT="$(printf '%s\n' "$FLAKEBOX_GIT_LS" | { grep -v -E -e '@textExclude@' -e "${FLAKEBOX_GIT_LS_TEXT_IGNORE}" || [[ $? == 1 ]]; })" fi diff --git a/lib/pkgs/git-check-newline.nix b/lib/pkgs/git-check-newline.nix new file mode 100644 index 0000000..b589d60 --- /dev/null +++ b/lib/pkgs/git-check-newline.nix @@ -0,0 +1,22 @@ +{ stdenv, rustc }: + +stdenv.mkDerivation { + pname = "flakebox-git-check-newline"; + version = "0.1.0"; + dontUnpack = true; + + nativeBuildInputs = [ rustc ]; + + buildPhase = '' + runHook preBuild + rustc --edition 2024 -D warnings -O ${./git-check-newline.rs} \ + -o flakebox-git-check-newline + runHook postBuild + ''; + + installPhase = '' + runHook preInstall + install -Dm755 flakebox-git-check-newline "$out/bin/flakebox-git-check-newline" + runHook postInstall + ''; +} diff --git a/lib/pkgs/git-check-newline.rs b/lib/pkgs/git-check-newline.rs new file mode 100644 index 0000000..ab38c4f --- /dev/null +++ b/lib/pkgs/git-check-newline.rs @@ -0,0 +1,108 @@ +//! Check a NUL-delimited list of paths on stdin for a missing final LF. + +use std::ffi::OsStr; +use std::fs::{self, File}; +use std::io::{self, BufRead as _, Read as _, Seek as _, SeekFrom, Write as _}; +use std::os::unix::ffi::OsStrExt as _; +use std::path::Path; +use std::process::ExitCode; + +fn missing_newline(path: &Path) -> io::Result { + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + // The path may have been removed or its parent replaced in the + // worktree. + Err(err) + if matches!( + err.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + return Ok(false); + } + Err(err) => return Err(err), + }; + if !metadata.is_file() || metadata.len() == 0 { + return Ok(false); + } + + let mut file = File::open(path)?; + file.seek(SeekFrom::End(-1))?; + let mut last_byte = [0]; + file.read_exact(&mut last_byte)?; + if matches!(last_byte[0], b'\n' | 0) { + return Ok(false); + } + + // A file with a NUL anywhere is considered binary. Only scan the + // contents when the last byte would otherwise make the check fail. + file.rewind()?; + let mut buf = [0; 16 * 1024]; + loop { + let len = match file.read(&mut buf) { + Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, + result => result?, + }; + if len == 0 { + return Ok(true); + } + if buf[..len].contains(&0) { + return Ok(false); + } + } +} + +fn path_label(path: &Path) -> String { + match path.to_str() { + Some(text) if !text.chars().any(char::is_control) => text.to_owned(), + _ => format!("{path:?}"), + } +} + +fn check_paths() -> io::Result { + let mut stdin = io::stdin().lock(); + let mut stderr = io::stderr().lock(); + let mut record = Vec::new(); + let mut failed = false; + + while stdin.read_until(0, &mut record)? != 0 { + if record.pop() != Some(0) || record.is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid path record", + )); + } + let path = Path::new(OsStr::from_bytes(&record)); + match missing_newline(path) { + Ok(true) => { + writeln!(stderr, "{} doesn't end with a newline", path_label(path))?; + failed = true; + } + Ok(false) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => {} + Err(err) => { + return Err(io::Error::new( + err.kind(), + format!("{}: {err}", path_label(path)), + )); + } + } + record.clear(); + } + + if failed { + writeln!(stderr, "Fix the problems above or use --no-verify")?; + } + Ok(failed) +} + +fn main() -> ExitCode { + match check_paths() { + Ok(false) => ExitCode::SUCCESS, + Ok(true) => ExitCode::FAILURE, + Err(err) => { + eprintln!("flakebox-git-check-newline: {err}"); + ExitCode::from(2) + } + } +} diff --git a/misc/git-hooks/pre-commit b/misc/git-hooks/pre-commit index 524ed80..beaad92 100755 --- a/misc/git-hooks/pre-commit +++ b/misc/git-hooks/pre-commit @@ -48,16 +48,16 @@ fi export FLAKEBOX_GIT_LS if [ -z "${FLAKEBOX_GIT_LS_IGNORE:-}" ]; then - FLAKEBOX_GIT_LS="$(git ls-files | while read -r file; do [ ! -L "$file" ] && echo "$file"; done)" + FLAKEBOX_GIT_LS="$(git ls-files | while read -r file; do if [ ! -L "$file" ]; then printf '%s\n' "$file"; fi; done)" else - FLAKEBOX_GIT_LS="$(git ls-files | grep -v -E "${FLAKEBOX_GIT_LS_IGNORE}" | while read -r file; do [ ! -L "$file" ] && echo "$file"; done)" + FLAKEBOX_GIT_LS="$(git ls-files | { grep -v -E -e "${FLAKEBOX_GIT_LS_IGNORE}" || [[ $? == 1 ]]; } | while read -r file; do if [ ! -L "$file" ]; then printf '%s\n' "$file"; fi; done)" fi export FLAKEBOX_GIT_LS_TEXT if [ -z "${FLAKEBOX_GIT_LS_TEXT_IGNORE:-}" ]; then - FLAKEBOX_GIT_LS_TEXT="$(echo "$FLAKEBOX_GIT_LS" | grep -v -E "\.(png|ods|jpg|jpeg|woff2|keystore|wasm|ttf|jar|ico|gif)\$")" + FLAKEBOX_GIT_LS_TEXT="$(printf '%s\n' "$FLAKEBOX_GIT_LS" | { grep -v -E -e '\.(png|ods|jpg|jpeg|woff2|keystore|wasm|ttf|jar|ico|gif)$' || [[ $? == 1 ]]; })" else - FLAKEBOX_GIT_LS_TEXT="$(echo "$FLAKEBOX_GIT_LS" | grep -v -E "\.(png|ods|jpg|jpeg|woff2|keystore|wasm|ttf|jar|ico|gif)\$" | grep -v -E "${FLAKEBOX_GIT_LS_TEXT_IGNORE}")" + FLAKEBOX_GIT_LS_TEXT="$(printf '%s\n' "$FLAKEBOX_GIT_LS" | { grep -v -E -e '\.(png|ods|jpg|jpeg|woff2|keystore|wasm|ttf|jar|ico|gif)$' -e "${FLAKEBOX_GIT_LS_TEXT_IGNORE}" || [[ $? == 1 ]]; })" fi # NOTE: THIS FILE IS AUTO-GENERATED BY FLAKEBOX @@ -124,26 +124,17 @@ export -f check_shellcheck function check_trailing_newline() { set -euo pipefail - errors="" - for path in $(echo "$FLAKEBOX_GIT_LS_TEXT"); do - - # extra branches for clarity - if [ ! -f "$path" ] || [ ! -s "$path" ]; then - # echo "$path is not a file or is empty" - true - elif [ -z "$(tail -c 1 < "$path")" ]; then - # echo "$path ends with a newline or with a null byte" - true - else - >&2 echo "$path doesn't end with a newline" 1>&2 - errors="true" - fi - done - - if [ -n "$errors" ]; then - >&2 echo "Fix the problems above or use --no-verify" 1>&2 - return 1 + # Keep filenames as NUL-delimited records, not Git-quoted shell words. + excludes=(-e '\.(png|ods|jpg|jpeg|woff2|keystore|wasm|ttf|jar|ico|gif)$') + if [[ -n "${FLAKEBOX_GIT_LS_IGNORE:-}" ]]; then + excludes+=(-e "$FLAKEBOX_GIT_LS_IGNORE") + fi + if [[ -n "${FLAKEBOX_GIT_LS_TEXT_IGNORE:-}" ]]; then + excludes+=(-e "$FLAKEBOX_GIT_LS_TEXT_IGNORE") fi + git ls-files -z --deduplicate | + { grep -azEv "${excludes[@]}" || [[ $? == 1 ]]; } | + flakebox-git-check-newline } export -f check_trailing_newline