master
in 57 lines 1.94 KB
Raw
1 #!/bin/sh
2 # Copyright (c) Microsoft Corporation. All rights reserved.
3 # Licensed under the MIT License. See LICENSE in the project root for license information.
4 #
5 # Pre-commit hook: validates clang-format on staged C/C++ files.
6 # Generated by CMake from tools/hooks/pre-commit.in
7 # Install with: tools\SetupClangFormat.bat
8 #
9 # Mode: @WSL_PRE_COMMIT_MODE@ (set WSL_PRE_COMMIT_MODE in UserConfig.cmake)
10 # warn - report formatting issues without blocking the commit (default)
11 # error - block the commit when formatting issues are found
12 # fix - automatically fix formatting and re-stage files
13
14 MODE="@WSL_PRE_COMMIT_MODE@"
15 REPO_ROOT="$(git rev-parse --show-toplevel)"
16 CLANG_FORMAT="@LLVM_INSTALL_DIR@/clang-format.exe"
17
18 # --- Collect staged C/C++ source files ---
19 STAGED=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(c|cpp|cxx|h|hpp|hxx)$')
20 if [ -z "$STAGED" ]; then
21 exit 0
22 fi
23
24 # --- Verify clang-format is available ---
25 if [ ! -f "$CLANG_FORMAT" ]; then
26 echo "[pre-commit] clang-format not found, skipping. Run 'cmake .' to set up."
27 exit 0
28 fi
29
30 # --- fix mode: format in-place and re-stage ---
31 if [ "$MODE" = "fix" ]; then
32 echo "[pre-commit] Fixing formatting..."
33 echo "$STAGED" | while IFS= read -r file; do
34 "$CLANG_FORMAT" --style=file -i "$REPO_ROOT/$file"
35 git add "$REPO_ROOT/$file"
36 done
37 echo "[pre-commit] Formatting applied and files re-staged."
38 exit 0
39 fi
40
41 # --- warn / error mode: check formatting ---
42 echo "[pre-commit] Checking formatting (mode: $MODE)..."
43 FILES=$(echo "$STAGED" | sed "s|^|$REPO_ROOT/|")
44 echo "$FILES" | xargs "$CLANG_FORMAT" --style=file -Werror --dry-run 2>&1
45 RESULT=$?
46
47 if [ $RESULT -ne 0 ]; then
48 echo ""
49 echo "[pre-commit] Formatting errors found. Run to fix:"
50 echo " powershell FormatSource.ps1 -Staged \$true"
51 if [ "$MODE" = "error" ]; then
52 exit 1
53 fi
54 echo "[pre-commit] Continuing commit (mode: warn)."
55 else
56 echo "[pre-commit] All checks passed."
57 fi