|
| 1 | +#!/usr/bin/env bash |
| 2 | +# |
| 3 | +# Pre-commit hook to run lightweight checks and auto-format the code. It's designed |
| 4 | +# to be blazingly fast, so it checks only changed files. |
| 5 | +# |
| 6 | +# You can install this hook and some of its dependencies by running `scripts/init.sh`. |
| 7 | + |
| 8 | +set -euo pipefail |
| 9 | + |
| 10 | +# Using `readlink` because the pre-commit hook is installed via a symlink, so |
| 11 | +# we need to resolve it before we can make path relative to this script's file. |
| 12 | +. "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../scripts/lib.sh" |
| 13 | + |
| 14 | +function command_exists() { |
| 15 | + bin_name=$(basename "$1") |
| 16 | + |
| 17 | + if command -v "$1" &> /dev/null; then |
| 18 | + return 0 |
| 19 | + fi |
| 20 | + |
| 21 | + warn "$bin_name CLI was not found. Ignoring it..." |
| 22 | + return 1 |
| 23 | +} |
| 24 | + |
| 25 | +files=$(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g') |
| 26 | + |
| 27 | +if [[ -z "$files" ]]; then |
| 28 | + info "No files changed. Exiting the pre-commit hook..." |
| 29 | + exit 0 |
| 30 | +fi |
| 31 | + |
| 32 | +if command_exists typos; then |
| 33 | + echo "$files" | step xargs typos |
| 34 | +fi |
| 35 | + |
| 36 | +if command_exists npx; then |
| 37 | + echo "$files" | step xargs npx prettier --ignore-unknown --write |
| 38 | +fi |
| 39 | + |
| 40 | +if command_exists cargo; then |
| 41 | + # `rustfmt` doesn't ignore non-rust files automatically |
| 42 | + rust_files=$(echo "$files" | { grep -E '\.rs$' || true; }) |
| 43 | + |
| 44 | + if [[ -n "$rust_files" ]]; then |
| 45 | + echo "$rust_files" | step xargs cargo fmt --manifest-path native/Cargo.toml -- |
| 46 | + fi |
| 47 | +fi |
| 48 | + |
| 49 | +if command_exists mix; then |
| 50 | + echo "$files" | step xargs mix format |
| 51 | +fi |
| 52 | + |
| 53 | +# Add the modified/prettified files to staging |
| 54 | +echo "$files" | step xargs git add |
0 commit comments