Skip to content

Instantly share code, notes, and snippets.

@teeli
Last active July 5, 2016 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teeli/29584f5d513fef172a70191089635580 to your computer and use it in GitHub Desktop.
Save teeli/29584f5d513fef172a70191089635580 to your computer and use it in GitHub Desktop.
Pre-commit hook for Git to run ESLint and CSSComb before every commit to prevent committing bad code
#!/bin/sh
#
# Run ESLint and CSSComb before every commit to prevent committing bad code
#
HAS_NODE=`which node 2> /dev/null || which nodejs 2> /dev/null || which iojs 2> /dev/null`
#
# There are some issues with Source Tree because paths are not set correctly for
# the given environment. Sourcing the bash_profile seems to resolve this for bash users,
# sourcing the zshrc for zshell users.
#
# https://answers.atlassian.com/questions/140339/sourcetree-hook-failing-because-paths-don-t-seem-to-be-set-correctly
#
function source_home_file {
file="$HOME/$1"
[[ -f "${file}" ]] && source "${file}"
}
source_home_file ".bash_profile" || source_home_file ".zshrc" || true
#
# Determine node.js binary name and location
#
NODE=`which node 2> /dev/null`
NODEJS=`which nodejs 2> /dev/null`
IOJS=`which iojs 2> /dev/null`
LOCAL="/usr/local/bin/node"
BINARY=
#
# Figure out which binary we need to use for our script execution.
#
if [[ -n "$NODE" ]]; then
BINARY="$NODE"
elif [[ -n "$NODEJS" ]]; then
BINARY="$NODEJS"
elif [[ -n "$IOJS" ]]; then
BINARY="$IOJS"
elif [[ -x "$LOCAL" ]]; then
BINARY="$LOCAL"
fi
#
# check for errors with eslint and csscomb
#
lint_errors=()
while read status file; do
# do a check only on the js files
if [[ "$file" =~ ".js" ]] && ! $BINARY node_modules/eslint/bin/eslint.js "$file" 2>&1 > /dev/null; then
(>&2 echo "Error in $file")
lint_errors[${#eslint_errors[@]}]=$file
#exit 1
fi
# do a check only on the scss files
if [[ "$file" =~ ".scss" ]] && ! $BINARY node_modules/csscomb/bin/csscomb --lint "$file" 2>&1 > /dev/null; then
(>&2 echo "Error in $file")
lint_errors[${#eslint_errors[@]}]=$file
#exit 1
fi
done <<<"$(git diff --cached --name-status --diff-filter=ACMR)"
#
# Display error message and exit with error if lint errors were encountered
#
if [ "${#lint_errors[@]}" -gt 0 ]; then
(>&2 echo "\033[0;31mLint errors detected. Aborting commit. Run \033[1;31m'npm run lint'\033[0;31m or \033[1;31m'npm run csslint'\033[0;31m for details.\033[0m")
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment