-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpre-commit
More file actions
executable file
·97 lines (73 loc) · 2.39 KB
/
pre-commit
File metadata and controls
executable file
·97 lines (73 loc) · 2.39 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/bin/bash
# This script is a pre-commit hook designed to automate code formatting and ensure style
# consistency before committing code. It automatically checks for and fixes trailing whitespaces,
# converts tabs to spaces, and runs clang-format on C/C++ source files. This helps maintain a
# clean and readable codebase across all contributions.
set -o pipefail
echo "Running pre-commit hook"
print_failure() {
echo -ne "................................................................\033[1;37;41mFailed\033[0m"
echo -e "\r❌ $1"
echo "- Files were modified by this hook"
}
print_success() {
echo -ne "................................................................\033[1;37;42mPassed\033[0m"
echo -e "\r✅ $1"
}
print_skip() {
echo -ne "...............................................................\033[1;37;46mSkipped\033[0m"
echo -e "\r$1"
}
declare -A results=(["whitespaces"]=0 ["tabs"]=0 ["clang-format"]=0)
exit_code=0
remove_white_spaces() {
diff -u <(cat $1) <(sed -E 's/[ '$'\t'']+$//g' $1) > /dev/null 2>&1
if [[ $? -ne 0 ]]; then
sed -i -E 's/[ '$'\t'']+$//g' $1
results["whitespaces"]=1
fi
}
change_tabs_for_spaces() {
diff -u <(cat $1) <(sed -E 's/\t/ /g' $1) > /dev/null 2>&1
if [[ $? -ne 0 ]]; then
sed -i -E 's/\t/ /g' $1
results["tabs"]=1
fi
}
stagedFiles=$(git diff --diff-filter=d --cached --name-only)
if [[ -z ${stagedFiles} ]]; then
echo -e "No staged files. Nothing to check."
exit 0
fi
generalFiles=$(echo "${stagedFiles}" | grep -E '.*\.(sh|s|S|asm|ld|txt|cmake|clang-format)$') 2>&1
if [[ -z ${generalFiles} ]]; then
results["whitespaces"]=2
results["tabs"]=2
else
for file in $generalFiles; do
remove_white_spaces $file
change_tabs_for_spaces $file
done
fi
srcFiles=$(echo "${stagedFiles}" | grep -E '.*\.(h|c|hpp|cpp|cppm)$') 2>&1
if [[ -z ${srcFiles} ]]; then
results["clang-format"]=2
else
clang-format --dry-run --Werror ${srcFiles} > /dev/null 2>&1
if [[ $? -ne 0 ]]; then
clang-format -i -style=file ${srcFiles} > /dev/null 2>&1
results["clang-format"]=1
fi
fi
for key in "${!results[@]}"
do
if [[ ${results["$key"]} -eq 1 ]]; then
print_failure "$key"
exit_code=1
elif [[ ${results["$key"]} -eq 2 ]]; then
print_skip "$key"
else
print_success "$key"
fi
done
exit $exit_code