Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .config/flakebox/id
Original file line number Diff line number Diff line change
@@ -1 +1 @@
515ae2f3483180933c9d348041bafad0ce0e59fd7972f984d0a0119b8ed1b7c5649b9f52d580fabe6d70f6853477927bd6cbe6e2d8882b0221b3cbdb7964386f
8ec289da601860ebbfa8eb50af1b67ee78411530a7242b10ec197fcea94891fd591831186d94aff57d312cfdbd3f5bafdc6f99810596bd3ebd96800b8ddbce4f
86 changes: 86 additions & 0 deletions checks/git-hooks.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -192,6 +203,7 @@ pkgs.runCommand "git-hooks-tests"
timer
testFlakeboxBin
]
++ newlineLib.config.env.shellPackages
++ pkgs.lib.optionals pkgs.stdenv.isLinux [ pkgs.util-linux ];
}
''
Expand Down Expand Up @@ -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
Expand Down
57 changes: 33 additions & 24 deletions lib/modules/git.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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
{

Expand All @@ -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;
Expand Down Expand Up @@ -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
'';
})

Expand Down Expand Up @@ -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}
#
Expand All @@ -267,7 +270,13 @@ in
'';
};

env.shellPackages = [ gitHookCheckTimer ];
env.shellPackages = [
gitHookCheckTimer
]
++ lib.optionals config.git.pre-commit.trailing_newline [
gitCheckNewline
pkgs.gnugrep
];

})

Expand Down
8 changes: 4 additions & 4 deletions lib/modules/git/pre-commit.body.bash
Original file line number Diff line number Diff line change
Expand Up @@ -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
22 changes: 22 additions & 0 deletions lib/pkgs/git-check-newline.nix
Original file line number Diff line number Diff line change
@@ -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
'';
}
108 changes: 108 additions & 0 deletions lib/pkgs/git-check-newline.rs
Original file line number Diff line number Diff line change
@@ -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<bool> {
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<bool> {
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)
}
}
}
Loading
Loading