#!/bin/sh
# Refuses a commit whose Rust is not as rustfmt writes it, or that clippy warns about. Clippy only
# checks and never links, so it is light beside a test build (CLAUDE.md, Tests). It checks the
# crates the commit touches and those built on them, not the workspace: ipx uses ipx-directory,
# and both use ipx-feed. A commit to the page alone runs nothing here.
staged=$(git diff --cached --name-only --diff-filter=ACMD)
echo "$staged" | grep -q -e '\.rs$' -e 'Cargo\.toml$' -e '^Cargo\.lock$' || exit 0
if ! cargo fmt --all --check >/dev/null 2>&1; then
	echo "pre-commit: the Rust is not formatted; run cargo fmt --all" >&2
	exit 1
fi
if echo "$staged" | grep -q -e '^Cargo\.toml$' -e '^Cargo\.lock$' -e '^crates/feed/'; then
	pkgs="ipx-feed ipx-directory ipx"
elif echo "$staged" | grep -q '^crates/directory/'; then
	pkgs="ipx-directory ipx"
elif echo "$staged" | grep -q '^crates/ipx/'; then
	pkgs="ipx"
else
	exit 0
fi
args=$(for p in $pkgs; do printf ' -p %s' "$p"; done)
# shellcheck disable=SC2086 # one word a flag
if ! cargo clippy $args --all-targets -q -- -D warnings; then
	echo "pre-commit: clippy has warnings in $pkgs; fix them, or allow one where it is wrong, with a comment saying why" >&2
	exit 1
fi
