set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"
if command -v gitleaks >/dev/null 2>&1; then
GL_CFG=""
if [ -f "$ROOT/.gitleaks.toml" ]; then
GL_CFG="$ROOT/.gitleaks.toml"
elif [ -f "$HOME/Code/.gitleaks.toml" ]; then
GL_CFG="$HOME/Code/.gitleaks.toml"
fi
gl_args=(git --staged --no-banner --redact)
[ -n "$GL_CFG" ] && gl_args+=(-c "$GL_CFG")
if ! gitleaks "${gl_args[@]}"; then
echo "pre-commit: gitleaks found a secret in the staged changes."
echo " remove it (or allowlist a false positive), then restage."
echo " bypass: git commit --no-verify."
exit 1
fi
echo "pre-commit: gitleaks clean."
else
echo "pre-commit: gitleaks not installed; skipping secret scan (astra gates on push)."
fi
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."