-
Notifications
You must be signed in to change notification settings - Fork 46
/
clang-format-pre-commit-hook
executable file
·69 lines (63 loc) · 1.94 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
62
63
64
65
66
67
68
69
#!/usr/bin/env bash
# Copyright 2017-Present Couchbase, Inc.
#
# Use of this software is governed by the Business Source License included in
# the file licenses/BSL-Couchbase.txt. As of the Change Date specified in that
# file, in accordance with the Business Source License, use of this software
# will be governed by the Apache License, Version 2.0, included in the file
# licenses/APL2.txt.
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