Skip to content

Commit 3c4576d

Browse files
authored
Pre-commit hook to test if the code needs restyling (project-chip#7506)
* Pre-commit hook to test if the code needs restyling * use diff patch to save unstaged changes * Fix spelling
1 parent e7ff132 commit 3c4576d

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

.githooks/pre-commit

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#!/bin/sh
2+
3+
here=${0%/*}
4+
5+
CHIP_ROOT=$(cd "$here/.." && pwd)
6+
7+
SAVED_UNSTAGED=0
8+
SAVED_UNSTAGED_FILE=$(git rev-parse --short HEAD)-unstaged.diff
9+
10+
RESTYLED=0
11+
12+
save_unstaged() {
13+
if [[ $SAVED_UNSTAGED -ne 0 ]]; then
14+
git diff --output="$SAVED_UNSTAGED_FILE"
15+
git apply -R "$SAVED_UNSTAGED_FILE"
16+
fi
17+
}
18+
19+
revert_unstaged() {
20+
if [[ $SAVED_UNSTAGED -ne 0 ]]; then
21+
git apply "$SAVED_UNSTAGED_FILE"
22+
rm "$SAVED_UNSTAGED_FILE"
23+
fi
24+
SAVED_UNSTAGED=0
25+
}
26+
27+
revert_restyled() {
28+
if [[ $RESTYLED -ne 0 ]]; then
29+
# Reset the changes introduced by restyle
30+
git stash push -q --keep-index
31+
git stash drop -q
32+
fi
33+
RESTYLED=0
34+
}
35+
36+
revert_if_needed() {
37+
revert_restyled
38+
revert_unstaged
39+
}
40+
41+
trap "revert_if_needed; exit 1" SIGINT SIGTERM SIGKILL
42+
43+
git diff --quiet
44+
SAVED_UNSTAGED=$?
45+
46+
# If there are unstaged files, save them for now
47+
save_unstaged
48+
49+
# Try restyling the code
50+
"$CHIP_ROOT"/scripts/helpers/restyle-diff.sh
51+
52+
git diff --quiet
53+
RESTYLED=$?
54+
FAILED_COMMIT="$RESTYLED"
55+
56+
revert_if_needed
57+
58+
if [[ $FAILED_COMMIT -ne 0 ]]; then
59+
echo "Commit Failed: Code needs restyling before committing."
60+
echo "Restyling can be done by running $CHIP_ROOT/scripts/helpers/restyle-diff.sh"
61+
exit 1
62+
fi
63+
64+
echo "Code doesn't need restyling. Committing."

0 commit comments

Comments
 (0)