set -euo pipefail
[ "${SKIP_FMT:-0}" = "1" ] && exit 0
mapfile -t rs_files < <(git diff --cached --name-only --diff-filter=ACM -- '*.rs')
[ "${#rs_files[@]}" -eq 0 ] && exit 0
if ! command -v rustfmt >/dev/null 2>&1; then
echo "pre-commit: rustfmt not found in PATH; skipping fmt check" >&2
exit 0
fi
repo_root="$(git rev-parse --show-toplevel)"
config_arg=()
[ -f "${repo_root}/rustfmt.toml" ] && config_arg=(--config-path "${repo_root}/rustfmt.toml")
tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT
unformatted=()
for f in "${rs_files[@]}"; do
tmpfile="${tmpdir}/check.rs"
git show ":$f" > "$tmpfile"
if ! rustfmt "${config_arg[@]}" --config skip_children=true --check "$tmpfile" >/dev/null 2>&1; then
unformatted+=("$f")
fi
done
if [ "${#unformatted[@]}" -gt 0 ]; then
echo "pre-commit: the following staged files are not formatted:" >&2
for f in "${unformatted[@]}"; do echo " - $f" >&2; done
echo >&2
echo "Run 'cargo fmt' and re-stage your changes, then commit again." >&2
echo "(bypass with SKIP_FMT=1 git commit ...)" >&2
exit 1
fi
exit 0