-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathclang-format-pre-commit-hook
executable file
·61 lines (56 loc) · 1.57 KB
/
clang-format-pre-commit-hook
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
#!/usr/bin/env bash
config=$(git config couchbase.clangformat)
has_issues () {
diff=$(git clang-format --diff)
[[ $diff == diff* ]]
}
reformat () {
if [ ! $config = "commit" ] ; then
echo -n "Commit rejected. "
fi
echo "Running \`git clang-format\` to fix style..."
reformat_results=$(git clang-format)
ret_val=$?
echo "$reformat_results"
return $ret_val
}
add_reformatted_files () {
# Hacky. Skips the first line of the output from clang-format,
# strips leading spaces, and replaces newlines with nulls, to
# pass to xargs -0 (because xargs -d is a GNU extension)
# to stage all changes. Better ways would be appreciated!
echo "$reformat_results" | tail -n +2 | sed -e 's/^[[:space:]]*//' | tr '\n' '\0' | xargs -0 git add
}
if has_issues ; then
case $config in
(fix)
reformat
if [ $? = 0 ] ; then
echo "Review changes, add, and commit again."
fi
exit 1
;;
(stage)
reformat
if [ $? = 0 ] ; then
add_reformatted_files
fi
exit 1
;;
(commit)
reformat
if [ $? = 0 ] ; then
add_reformatted_files
exit 0
fi
exit 1
;;
(*)
echo "Commit rejected as clang-format detected formatting issues."
echo " Run \`git clang-format --diff\` to view suggested changes"
echo " and \`git clang-format\` to apply them."
echo " Alternatively, use \`git commit --no-verify\` to skip hooks."
exit 1
;;
esac
fi