#!/usr/bin/env bash
# .githooks/pre-commit
#
# Auto-format staged Rust files with rustfmt and re-stage them.
# Keeps fmt-check / `make pre-merge` / `make publish` from ever
# failing because of a one-line vs three-line wrap drift.
#
# Installed by `make setup-hooks` (sets core.hooksPath = .githooks).
# Silent on success; exits non-zero only if rustfmt itself fails
# (e.g. a real syntax error in a staged file).

set -euo pipefail

# Only operate on files that are STAGED for the upcoming commit, and
# only those that survive past --diff-filter (so deletions/renames
# don't trip us up). Path: NUL-separated to handle exotic names.
mapfile -d '' staged_rs < <(
    git diff --cached --name-only --diff-filter=ACM -z -- '*.rs'
)

if [ "${#staged_rs[@]}" -eq 0 ]; then
    exit 0
fi

# rustfmt operates per-file when given paths directly, so we only
# touch what's staged — never reformats files the user didn't touch.
# --edition 2021 matches the workspace setting; rustfmt's default is
# 2015, which would mis-format some Rust 2021 constructs.
rustfmt --edition 2021 -- "${staged_rs[@]}"

# Re-stage any file rustfmt actually changed. `git add` on an
# unchanged file is a no-op, so this is safe to run unconditionally.
git add -- "${staged_rs[@]}"
