Skip to content

Instantly share code, notes, and snippets.

@mattslack
Last active March 10, 2020 19:38
Show Gist options
  • Save mattslack/37c728e3b9ff653540747ea497f4f447 to your computer and use it in GitHub Desktop.
Save mattslack/37c728e3b9ff653540747ea497f4f447 to your computer and use it in GitHub Desktop.
git hooks
#!/bin/bash
# Built off of Standard JS's pre-commit example: https://standardjs.com/#is-there-a-git-pre-commit-hook
# Ensure all files staged for commit pass standard code style
function xargs-r() {
# Portable version of "xargs -r". The -r flag is a GNU extension that
# prevents xargs from running if there are no input files
if IFS= read -r -d $'\n' path; then
{ echo "$path"; cat; } | xargs $@
fi
}
# If there's a $RUBOCOP preference set in a project's .envrc, use it, even if
# standardrb is available
[[ -z $RUBOCOP ]] && {
[[ -x `command -v rubocop` ]] && RUBOCOP=rubocop
[[ -x `command -v standardrb` ]] && RUBOCOP=standardrb
}
[[ -n $RUBOCOP ]] && [[ -x `command -v ${RUBOCOP}` ]] && {
git diff --name-only --cached --relative | grep '\.rb$' | sed 's/[^[:alnum:]]/\\&/g' | xargs-r -E '' -t $RUBOCOP
if [[ $? -ne 0 ]]; then
echo 'Rubocop errors were detected. Aborting commit.'
exit 1
fi
}
[[ -x `command -v standard` ]] && {
git diff --name-only --cached --relative | grep '\.jsx\?$' | sed 's/[^[:alnum:]]/\\&/g' | xargs-r -E '' -t standard --fix
if [[ $? -ne 0 ]]; then
echo 'JavaScript Standard Style errors were detected. Aborting commit.'
exit 1
fi
}
[[ -x `command -v stylelint` ]] && {
git diff --name-only --cached --relative | grep '\.s(a|c)ss$' | sed 's/[^[:alnum:]]/\\&/g' | xargs-r -E '' -t stylelint --fix --mw 5
if [[ $? -ne 0 ]]; then
echo 'Stylelint errors were detected. Aborting commit.'
exit 1
fi
}
[[ -x `command -v mix` ]] && {
git diff --name-only --cached --relative | grep '\.ex$' | sed 's/[^[:alnum:]]/\\&/g' | xargs-r -E '' -t mix --check-formatted
if [[ $? -ne 0 ]]; then
echo 'Elixer formatting errors were detected. Aborting commit.'
exit 1
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment