| 1 | #!/usr/bin/env bash |
| 2 | # Wrapper for the rust-* pre-commit hooks. |
| 3 | # |
| 4 | # Skips (with a warning) when `cargo` or the requested cargo subcommand is |
| 5 | # not installed, so contributors who don't touch the Rust code aren't forced |
| 6 | # to install the Rust toolchain (or niche cargo extensions like cargo-sort |
| 7 | # / cargo-autoinherit). Buildkite CI covers the rust hooks regardless. |
| 8 | # |
| 9 | # Usage: tools/pre_commit/rust-check.sh <cargo-subcommand> [extra cargo args...] |
| 10 | |
| 11 | set -euo pipefail |
| 12 | |
| 13 | # Pre-commit captures stdout/stderr and only replays on failure. Try to write |
| 14 | # to /dev/tty so the warning is visible during a normal `git commit` even |
| 15 | # though we exit 0; fall back to stderr where there's no controlling tty |
| 16 | # (e.g. CI). |
| 17 | # |
| 18 | # The leading newline pushes the warning off pre-commit's dot-leader line so |
| 19 | # the message doesn't mash into "Rust - ... ........WARNING:". The hook's |
| 20 | # "Passed" still lands on its own line just below the warning. |
| 21 | warn() { |
| 22 | { printf '\n%s\n' "$*" >/dev/tty; } 2>/dev/null || printf '\n%s\n' "$*" >&2 |
| 23 | } |
| 24 | |
| 25 | subcommand="$1" |
| 26 | shift |
| 27 | |
| 28 | if ! command -v cargo >/dev/null 2>&1; then |
| 29 | warn "WARNING: 'cargo' not found in PATH; skipping rust pre-commit hook (cargo ${subcommand}). |
| 30 | Install the Rust toolchain via https://rustup.rs/ if you need to run rust hooks locally." |
| 31 | exit 0 |
| 32 | fi |
| 33 | |
| 34 | # Cargo subcommands resolve to a `cargo-<name>` binary on PATH. Check up-front |
| 35 | # so a missing helper produces a friendly skip instead of a cargo error. |
| 36 | if ! command -v "cargo-${subcommand}" >/dev/null 2>&1; then |
| 37 | case "${subcommand}" in |
| 38 | fmt) install_hint="rustup component add rustfmt" ;; |
| 39 | *) install_hint="cargo install cargo-${subcommand}" ;; |
| 40 | esac |
| 41 | warn "WARNING: 'cargo ${subcommand}' is not installed; skipping rust pre-commit hook. |
| 42 | Install it with: ${install_hint}" |
| 43 | exit 0 |
| 44 | fi |
| 45 | |
| 46 | cd "$(git rev-parse --show-toplevel)/rust" |
| 47 | exec cargo "${subcommand}" "$@" |