set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"
SKIP_PATHS="${SKIP_PATHS:-}"
staged="$(git diff --cached --name-only --diff-filter=ACMR -- '*.rs')"
if [ -n "$SKIP_PATHS" ]; then
staged="$(printf '%s\n' "$staged" | grep -Ev "$SKIP_PATHS" || true)"
fi
[ -n "$staged" ] || exit 0
crates=""
while IFS= read -r f; do
[ -n "$f" ] || continue
d="$(dirname "$f")"
while [ "$d" != "." ] && [ ! -f "$d/Cargo.toml" ]; do
d="$(dirname "$d")"
done
[ -f "$d/Cargo.toml" ] || continue
crates="$crates$d"$'\n'
done <<< "$staged"
crates="$(printf '%s' "$crates" | sort -u)"
[ -n "$crates" ] || exit 0
failed=0
while IFS= read -r c; do
[ -n "$c" ] || continue
if ! (cd "$c" && cargo fmt --check >/dev/null 2>&1); then
echo "pre-commit: rustfmt gate failed in $c"
failed=1
fi
done <<< "$crates"
if [ "$failed" -ne 0 ]; then
echo "pre-commit: run 'cargo fmt' in the crates above, then restage."
echo "pre-commit: commit aborted (use --no-verify to bypass)."
exit 1
fi
echo "pre-commit: rustfmt gate clean."