forked from Mdashdotdashn/LittleGPTracker
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathpre-commit
More file actions
executable file
·49 lines (40 loc) · 1.35 KB
/
pre-commit
File metadata and controls
executable file
·49 lines (40 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/bin/sh
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -iE '\.(cpp|h|c|hpp)$')
if [ -z "$STAGED_FILES" ]; then
exit 0
fi
NEEDS_FORMATTING=0
# Run clang-format on the changed lines of each staged file
for FILE in $STAGED_FILES; do
echo Formatting "$FILE" ...
# Format the originally staged changed lines
CHANGED_LINES=$(git diff --cached -U0 -- "$FILE" | grep -E '^@@' | awk '{print $3}' | cut -d',' -f1)
for LINE in $CHANGED_LINES; do
LINE_START=$(echo "$LINE" | cut -d'+' -f2)
[ -z "$LINE_START" ] && continue
clang-format -i --lines="$LINE_START:$LINE_START" "$FILE"
done
# clang-format can cascade into adjacent lines; loop until the file stabilises
MAX_ITER=5
ITER=0
while [ $ITER -lt $MAX_ITER ]; do
PREV=$(cksum "$FILE")
NEW_LINES=$(git diff -U0 -- "$FILE" | grep -E '^@@' | awk '{print $3}' | cut -d',' -f1)
for LINE in $NEW_LINES; do
LINE_START=$(echo "$LINE" | cut -d'+' -f2)
[ -z "$LINE_START" ] && continue
clang-format -i --lines="$LINE_START:$LINE_START" "$FILE"
done
[ "$(cksum "$FILE")" = "$PREV" ] && break
ITER=$((ITER + 1))
done
if ! git diff --quiet "$FILE"; then
NEEDS_FORMATTING=1
echo "$FILE"
fi
done
if [ $NEEDS_FORMATTING -eq 1 ]; then
echo "The above files were auto-formatted. Please review and commit again."
exit 1
fi
exit 0