|
| 1 | +#!/usr/bin/env bash |
| 2 | +# Auto-format staged code with oxfmt before each commit, so the CI `format` job |
| 3 | +# (`oxfmt --check .`) can never fail on a commit that originated here. Activated |
| 4 | +# by `git config core.hooksPath .githooks`, which `bun run bootstrap` sets for |
| 5 | +# every fresh checkout / agent worktree. |
| 6 | +# |
| 7 | +# Behaviour: formats the staged JS/TS/JSON files in place and re-stages them. |
| 8 | +# oxfmt honours `.oxfmtrc.json` `ignorePatterns` even for explicitly-passed |
| 9 | +# paths, so generated/vendored files (bun.lock, routeTree.gen.ts, ...) are |
| 10 | +# skipped automatically. |
| 11 | +# |
| 12 | +# NUL-delimited end to end (handles spaces/newlines in paths) and compatible |
| 13 | +# with the bash 3.2 that ships on macOS, so no `mapfile`. A shell variable |
| 14 | +# cannot hold NUL bytes, so the staged list is read into an array directly. |
| 15 | +# |
| 16 | +# Caveat: a file that is only partially staged (staged hunk + a separate |
| 17 | +# unstaged hunk in the same file) gets fully re-staged after formatting. Agent |
| 18 | +# flows stage whole files (`git add -A`), so this is not a concern in practice. |
| 19 | + |
| 20 | +set -euo pipefail |
| 21 | + |
| 22 | +cd "$(git rev-parse --show-toplevel)" |
| 23 | + |
| 24 | +oxfmt="node_modules/.bin/oxfmt" |
| 25 | +if [[ ! -x "$oxfmt" ]]; then |
| 26 | + echo "pre-commit: oxfmt not found ($oxfmt) - run 'bun run bootstrap'; skipping format." >&2 |
| 27 | + exit 0 |
| 28 | +fi |
| 29 | + |
| 30 | +# Staged Added/Copied/Modified/Renamed files, restricted to extensions oxfmt |
| 31 | +# formats. Read NUL records into an array (no NUL-in-variable bug). |
| 32 | +files=() |
| 33 | +while IFS= read -r -d '' f; do |
| 34 | + case "$f" in |
| 35 | + *.ts | *.tsx | *.mts | *.cts | *.js | *.jsx | *.mjs | *.cjs | *.json | *.jsonc) |
| 36 | + files+=("$f") |
| 37 | + ;; |
| 38 | + esac |
| 39 | +done < <(git diff --cached --name-only --diff-filter=ACMR -z) |
| 40 | + |
| 41 | +((${#files[@]})) || exit 0 |
| 42 | + |
| 43 | +# Format in place, then re-stage whatever oxfmt may have rewritten. |
| 44 | +# --no-error-on-unmatched-pattern keeps the hook from failing when every staged |
| 45 | +# file is ignored by .oxfmtrc.json. |
| 46 | +"$oxfmt" --write --no-error-on-unmatched-pattern "${files[@]}" |
| 47 | +git add -- "${files[@]}" |
0 commit comments