Tuesday, December 6, 2011

Example Puppet 2.7 git pre-commit script

I had a hard time finding a decent pre-commit script for puppet 2.7. This is composed of snippets I found at code.seas.harvard.edu. The pre-commit script will check the puppet syntax of the changed .pp files, and also check if an attempt has been made to properly document the .pp file.


#!/bin/sh
#
# install this as .git/hooks/pre-commit to check Puppet manifests
# for errors before committing changes.

rc=0

[ "$SKIP_PRECOMMIT_HOOK" = 1 ] && exit 0

# Make sure we're at top level of repository.
cd $(git rev-parse --show-toplevel)

trap 'rm -rf $tmpdir $tmpfile1 $tmpfile2' EXIT INT HUP
tmpdir=$(mktemp -d precommitXXXXXX)
tmpfile1=$(mktemp errXXXXXX)
tmpfile2=$(mktemp errXXXXXX)

echo "$(basename $0): Validating changes."

# Here we copy files out of the index into a temporary directory. This
# protects us from a the situation in which we have staged an invalid
# configuration using ``git add`` but corrected the changes in the
# working directory. If we checked the files "in place", we would
# fail to detect the errors.

git diff-index --cached --name-only HEAD |
grep '\.pp$' |
git checkout-index --stdin --prefix=$tmpdir/

find $tmpdir -type f -name '*.pp' |
while read manifest; do
puppet parser validate $manifest | sed "s#$tmpdir/##" >> $tmpfile1 2>&1

if ! head -1 $manifest | grep -q '^#'; then
echo $manifest | sed "s#$tmpdir/##" >> $tmpfile2
fi
done

if [ -s "$tmpfile1" ]; then
echo
echo Error: Puppet parse problem:
echo ----------------------------
cat $tmpfile1
echo ----------------------------
echo

rc=1
fi

if [ -s "$tmpfile2" ]; then
echo
echo Error: missing manifest documentation
echo see http://projects.puppetlabs.com/projects/puppet/wiki/Puppet_Manifest_Documentation
echo for more information.
echo Files with problems:
echo -------------------------------------
cat $tmpfile2
echo -------------------------------------
echo

rc=1
fi

exit $rc