diff --git a/.github/hooks/clang-format-check.sh b/.github/hooks/clang-format-check.sh new file mode 100644 index 0000000000..a9f4f25f79 --- /dev/null +++ b/.github/hooks/clang-format-check.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash + +set -euo pipefail + +RANGE="" + +while [[ $# -gt 0 ]]; do + echo $1 + echo $2 + case "$1" in + --range) + RANGE="$2" + shift 2 + ;; + *) + echo "Unknown arg $1" >&2 + exit 64 + ;; + esac +done + +regex='\.(c|cc|cpp|cxx|h|hh|hpp|hxx)$' + +if [[ -n $RANGE ]]; then + files=$(git diff --name-only "$RANGE" | grep -E "$regex" || true) +else + files=$(git diff --cached --name-only --diff-filter=ACMR | grep -E "$regex" || true) +fi +echo "Checking $files" +[[ -z $files ]] && exit 0 + +clang_bin="${CLANG_FORMAT:-clang-format}" +if ! command -v "$clang_bin" >/dev/null 2>&1; then + if [[ -x "/c/Program Files/LLVM/bin/clang-format.exe" ]]; then + clang_bin="/c/Program Files/LLVM/bin/clang-format.exe" + fi +fi + +"$clang_bin" -style=file --dry-run -fallback-style=none -n -Werror $files diff --git a/.github/hooks/pre-commit b/.github/hooks/pre-commit new file mode 100644 index 0000000000..f42d5a3174 --- /dev/null +++ b/.github/hooks/pre-commit @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +exec "$(git rev-parse --show-toplevel)/.github/hooks/clang-format-check.sh" diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml new file mode 100644 index 0000000000..b17babaa2f --- /dev/null +++ b/.github/workflows/clang-format.yml @@ -0,0 +1,22 @@ +name: Clang format check + +on: + push: + +jobs: + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Install clang-format + run: | + sudo apt update && sudo apt install -y clang-format + + - name: Run clang-format-check + id: clang-format + run: | + chmod +x .github/hooks/clang-format-check.sh + ./.github/hooks/clang-format-check.sh --range "${{ github.event.before }}..${{ github.sha }}"