Skip to content

Instantly share code, notes, and snippets.

@JIghtuse
Last active September 7, 2016 06:13
Show Gist options
  • Save JIghtuse/8fa5fe2a45e676e506226025c3bcef48 to your computer and use it in GitHub Desktop.
Save JIghtuse/8fa5fe2a45e676e506226025c3bcef48 to your computer and use it in GitHub Desktop.
git-hook-cppcheck-xmllint
#!/bin/sh
# Usage: add this file to your project's .git/hooks directory. Rename it to
# just 'pre-commit' and make it executable.
# Now, when you change some files in repository and try to commit these
# changes, git will run this script right before commit.
#
# This script checks:
# C/C++ files with cppcheck
# XML files with xmllint
#
# It scans changed/new files in repository. If it finds some issues, script returns with
# exit code 1, rejecting commit. Otherwise, script returns 0, and you can
# actually commit your changes.
#
# Example:
# $ cat hello.c
# int main() {
# int *s = malloc(10);
# }
# $ git add hello.c
# $ git commit
# Checking hello.c...
# [hello.c:3]: (error) Memory leak: s
# [hello.c:2]: (error) The allocated size 10 is not a multiple of the underlying type's size.
#
# $ vim hello.c
# $ cat hello.c
# int main() {
# }
# $ git add hello.c
# $ git commit
# Checking hello.c...
# $
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# cppcheck
changed_files=$(git diff-index --cached $against | \
grep -E '[MA] .*\.(c|cpp|cc|cxx)$' | cut -d' ' -f 2)
if [ -n "$changed_files" ]; then
cppcheck --error-exitcode=1 $changed_files
exit $?
fi
# xml linter
changed_files=$(git diff-index --cached $against | \
grep -E '[MA] .*\.xml$' | cut -d' ' -f 2)
if [ -n "$changed_files" ]; then
xmllint --noout $changed_files
exit $?
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment