Skip to content

Commit c74529a

Browse files
JIghtusedanmar
authored andcommitted
Add git pre-commit hook script
1 parent b856ac5 commit c74529a

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

tools/git-pre-commit-cppcheck

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#!/bin/sh
2+
3+
# Usage: add this file to your project's .git/hooks directory. Rename it to
4+
# just 'pre-commit'.
5+
# Now, when you change some files in repository and try to commit these
6+
# changes, git will run this script right before commit. Cppcheck will scan
7+
# changed/new files in repository. If it finds some issues, script returns with
8+
# exit code 1, rejecting commit. Otherwise, script returns 0, and you can
9+
# actually commit your changes.
10+
#
11+
# Example:
12+
# $ cat hello.c
13+
# int main() {
14+
# int *s = malloc(10);
15+
# }
16+
# $ git add hello.c
17+
# $ git commit
18+
# Checking hello.c...
19+
# [hello.c:3]: (error) Memory leak: s
20+
# [hello.c:2]: (error) The allocated size 10 is not a multiple of the underlying type's size.
21+
#
22+
# $ vim hello.c
23+
# $ cat hello.c
24+
# int main() {
25+
# }
26+
# $ git add hello.c
27+
# $ git commit
28+
# Checking hello.c...
29+
# $
30+
31+
if git rev-parse --verify HEAD >/dev/null 2>&1
32+
then
33+
against=HEAD
34+
else
35+
# Initial commit: diff against an empty tree object
36+
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
37+
fi
38+
39+
# We should not pass non-C/C++ files to cppcheck. Filter filenames with pattern.
40+
pattern='\.(c|cpp|cc|cxx|h|hpp)$'
41+
changed_files=$(git diff-index --cached --name-only $against | grep -E $pattern)
42+
43+
if [ -n "$changed_files" ]; then
44+
cppcheck --error-exitcode=1 $changed_files
45+
exit $?
46+
fi

0 commit comments

Comments
 (0)