Created
February 26, 2014 12:59
-
-
Save cosimo/9229072 to your computer and use it in GitHub Desktop.
Puppet manifests and templates syntax check git pre-commit hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# pre-commit hook to syntax check puppet manifests and erb templates | |
# at checkin. | |
# Stig Sandbeck Mathisen <ssm@fnord.no> | |
# | |
# Modified to run with puppet < 2.7 as well, Cosimo 13/Dec/2011 | |
# | |
# Requirements: | |
# - ruby and erb for .erb files | |
# Todo: | |
# - Check for invalid characters with "iconv" | |
errors=0 | |
message=$(mktemp /tmp/error_msg.XXXXXX) | |
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 | |
#------------------------------ | |
check_erb() { | |
file="$1" | |
msg=$(mktemp /tmp/erb.XXXXXXXX) | |
git cat-file blob ":0:${file}" | erb -x -P -T - | ruby -c >$msg 2>&1 | |
status=$? | |
if [ "$status" != "0" ]; then | |
cat $msg | sed -n '1 s|^-\(:[0-9][0-9]*:\)|'"${file}"'\1|p; 2,3p' | |
fi | |
rm -f $msg | |
return $status | |
} | |
#------------------------------ | |
check_pp() { | |
file="$1" | |
msg=$(mktemp /tmp/pp.XXXXXXXX) | |
puppet_version=$(puppet --version | tr -d '\.' | sed -e 's/^0+//') | |
if [ "$puppet_version" -ge "270" ]; then | |
# Version is >= 2.7 | |
puppet parser validate --color=false \ | |
<(git cat-file blob ":0:${file}") >$msg 2>&1 | |
else | |
# Version is < 2.7 | |
puppet --parseonly \ | |
<(git cat-file blob ":0:${file}") >$msg 2>&1 | |
fi | |
status=$? | |
if [ "$status" != "0" ]; then | |
cat $msg | sed -n \ | |
-e 's/^err: Could not parse for environment [a-z]*: //' \ | |
-e '1 s|\(.*\) at [a-z/0-9]*:\([0-9]*\)$|'"${file}"':\2: \1|p' | |
fi | |
rm -f $msg | |
return $status | |
} | |
#------------------------------ | |
# Check: whitespace | |
git diff-index --check --cached $against -- > $message | |
if [ "$?" -ne "0" ]; then | |
cat $message | |
(( errors ++ )) | |
fi | |
#------------------------------ | |
# Check: syntax for misc files | |
for file in $(git diff-index --cached --diff-filter=AM --name-only $against); do | |
# Do not check empty files | |
if [ $(git cat-file -s :0:"${file}") -gt 0 ]; then | |
case "$file" in | |
*.pp) | |
check_pp $file > $message | |
;; | |
*.erb) | |
check_erb $file > $message | |
;; | |
esac | |
if [ "$?" -ne "0" ]; then | |
cat $message | |
(( errors ++ )) | |
fi | |
fi | |
done | |
rm -rf $message | |
if [ "$errors" -ne "0" ]; then | |
echo | |
echo "Error: $errors errors found, aborting commit." | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment