|
| 1 | +#!/usr/bin/env bash |
| 2 | + |
| 3 | +set -euo pipefail |
| 4 | + |
| 5 | +ROOT="$(git rev-parse --show-toplevel)" |
| 6 | +cd "$ROOT" |
| 7 | + |
| 8 | +log() { |
| 9 | + printf '[pre-commit] %s\n' "$1" |
| 10 | +} |
| 11 | + |
| 12 | +fail() { |
| 13 | + printf '[pre-commit] ERROR: %s\n' "$1" >&2 |
| 14 | + exit 1 |
| 15 | +} |
| 16 | + |
| 17 | +mapfile -t STAGED_FILES < <(git diff --cached --name-only --diff-filter=ACMR) |
| 18 | + |
| 19 | +if [ "${#STAGED_FILES[@]}" -eq 0 ]; then |
| 20 | + log "No staged files. Nothing to check." |
| 21 | + exit 0 |
| 22 | +fi |
| 23 | + |
| 24 | +mapfile -t CPP_FILES < <( |
| 25 | + printf '%s\n' "${STAGED_FILES[@]}" | |
| 26 | + grep -E '\.(c|cc|cpp|cxx|h|hh|hpp|hxx)$' || true |
| 27 | +) |
| 28 | + |
| 29 | +if [ "${#CPP_FILES[@]}" -gt 0 ]; then |
| 30 | + command -v clang-format >/dev/null 2>&1 || |
| 31 | + fail "clang-format is required to commit C/C++ files." |
| 32 | + |
| 33 | + DIRTY_CPP_FILES=() |
| 34 | + for file in "${CPP_FILES[@]}"; do |
| 35 | + if ! git diff --quiet -- "$file"; then |
| 36 | + DIRTY_CPP_FILES+=("$file") |
| 37 | + fi |
| 38 | + done |
| 39 | + |
| 40 | + if [ "${#DIRTY_CPP_FILES[@]}" -gt 0 ]; then |
| 41 | + printf '[pre-commit] These staged C/C++ files also have unstaged changes:\n' >&2 |
| 42 | + printf ' %s\n' "${DIRTY_CPP_FILES[@]}" >&2 |
| 43 | + fail "stage or stash those unstaged changes before committing so the hook does not include them accidentally." |
| 44 | + fi |
| 45 | + |
| 46 | + log "Formatting ${#CPP_FILES[@]} staged C/C++ file(s) with clang-format..." |
| 47 | + clang-format -i -- "${CPP_FILES[@]}" |
| 48 | + git add -- "${CPP_FILES[@]}" |
| 49 | +fi |
| 50 | + |
| 51 | +command -v python3 >/dev/null 2>&1 || |
| 52 | + fail "python3 is required to update translation coverage." |
| 53 | + |
| 54 | +if ! git diff --quiet -- README.md; then |
| 55 | + fail "README.md has unstaged changes; stage or stash them before committing so coverage updates stay explicit." |
| 56 | +fi |
| 57 | + |
| 58 | +log "Updating translation coverage in README.md..." |
| 59 | +python3 scripts/coverage.py --update |
| 60 | +git add README.md |
| 61 | + |
| 62 | +log "Done." |
0 commit comments