Mastodon Mastodon Mastodon Systeemkabouter blog – windows git pre-commit hook for puppet development

windows git pre-commit hook for puppet development

Posted on wo 09 augustus 2017 in desktop

For a recent client I was asked to provide a puppet development setup on the windows platform. The toolchain included Git for windows / Git bash / Turtoise GIT / Atom and some others. It also includes the windows adaption of my git pre-commit hook.

To use this hook, you need to install the puppet v4 agent and install a couple of ruby gems within the provided ruby environment. Something like :

c:\program files\puppetlabs\puppet\sys\ruby\bin\gem.bat install r10k
c:\program files\puppetlabs\puppet\sys\ruby\bin\gem.bat install puppet-lint

(from an elevated command prompt)

The hook needs to be saved in every git repository that contains puppet code in het directory [repo]/.git/hooks/

Warning : The windows linefeed bit is really recent and might need some additional testing.

#!/bin/bash
# Requires bash, as it uses the [[ ]] syntax.
#
# https://puppetlabs.com/blog/using-puppet-lint-to-save-yourself-from-style-faux-pas
# https://docs.puppetlabs.com/guides/templating.html#syntax-checking
#
# If it's puppet code, lint it up.
# 20150915 syncaddict
# - Added support for erb syntax checking
#
# 20151020 syncaddict
# - Added support for YAML syntax checking
# - more verbose operation
#
# 20170615 syncaddict
# - version that works on windows
#
# 20170809 syncaddict
# - detect / convert windows linefeeds
#
# Variables goes hither



PUPPETLINT="/c/Progra~1/Puppet~1/Puppet/sys/ruby/bin/puppet-lint.bat"
PUPPETAGENT="/c/Progra~1/Puppet~1/Puppet/bin/puppet.bat"
ERB="/c/Progra~1/Puppet~1/Puppet/sys/ruby/bin/erb.bat"
RUBY="/c/Progra~1/Puppet~1/Puppet/sys/ruby/bin/ruby.exe"

DOS2UNIX=/usr/bin/dos2unix
GREP=/usr/bin/grep
WC=/usr/bin/wc

declare -a FILES

IFS="
"
FILES=$(git diff --cached --name-only --diff-filter=ACM )


for file in ${FILES[@]}
do

## replace windows linefeeds on all changed files - WIP
LFCHECK=`$GREP "\r\n$" $file | $WC -l`
if [[ $? > 0 ]]; then echo "LF check failed"; fi

if [[ $LFCHECK -gt 0 ]];
then
$DOS2UNIX $file
echo "Converted linefeeds on $file, please re-add and retry your commit"
exit 666
fi





case $file in
*\.pp*)
echo "Checking puppet file $file"
$PUPPETLINT --no-puppet_url_without_modules-check --no-arrow_on_right_operand_line-check --no-140chars-check --fail-on-warnings --fix --with-filename "$file"
RC=$?
if [ $RC -ne 0 ]; then exit $RC;fi

      $PUPPETAGENT parser validate "$file"
      RC=$?
      if [ $RC -ne 0 ]; then exit $RC;fi
    ;;
    *\.erb*)
      echo "Checking erb template $file"
      $ERB -P -x -T '-' $file | $RUBY -c
      RC=$?
      if [ $RC -ne 0 ]; then exit $RC;fi
    ;;
    *\.yaml*)
      echo "Checking yaml file $file"
      $RUBY -e "require 'yaml'; YAML.load_file('$file')"
      RC=$?
      if [ $RC -ne 0 ]; then exit $RC;fi
    ;;
    *)
      echo "Not checking file $file"
    ;;
esac
done

exit 0