Skip to content

Instantly share code, notes, and snippets.

@berttejeda
Created October 28, 2020 18:51
Show Gist options
  • Save berttejeda/89299f262aa4b5ddc33570981237dcc3 to your computer and use it in GitHub Desktop.
Save berttejeda/89299f262aa4b5ddc33570981237dcc3 to your computer and use it in GitHub Desktop.
git pre-commit hook for validating YAML files
# .git/hooks/pre-commit
# inspired from https://gist.github.com/maciej-lasyk/f73f8aac271b4df4c7839dd425b4f092
FILES_PATTERN='.*\.yml$'
bin_path=$(type -p /usr/{,local/}{,s}bin/python 2>/dev/null)
if [[ ($bin_path == '') && ($(which python 2> /dev/null) == '') ]];then
echo '# Not checking Y.ML files, python not found';
exit 0
fi
if ! python -c 'import yaml';then
echo '# Not checking YML/YAML files';
echo '# pyyaml package not found, please install with';
echo '# pip install pyyaml';
exit 0
fi
for f in $(git diff --cached --diff-filter=d --name-only | grep -E $FILES_PATTERN | grep -v vault)
do
LINT_CHECK=`python -c 'import yaml,sys;yaml.safe_load(sys.stdin)' < $f 2> /dev/null`
LINT_STATUS=$?
if (( $LINT_STATUS != 0 )); then
SYNTAX_FILES+=("#\t$f")
fi
done
if (( ${#SYNTAX_FILES[@]} )); then
echo '# There are files with syntax (YAML) errors in the commit:'
echo '#'
( IFS=$'\n'; echo -e "${SYNTAX_FILES[*]}" )
echo '#'
echo "# Please fix these or force the commit with '--no-verify'"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment