Skip to content

Instantly share code, notes, and snippets.

@patrickmclaren
Last active October 5, 2015 20:20
Show Gist options
  • Save patrickmclaren/784b472744f8838bed53 to your computer and use it in GitHub Desktop.
Save patrickmclaren/784b472744f8838bed53 to your computer and use it in GitHub Desktop.
Git Pre-Commit for Style Checkers
#!/bin/bash
#
# Checks staged files for linter exceptions
# Add to PROJECT_ROOT/.git/hooks/, and make executable (i.e. chmod +x .git/hooks/pre-commit)
LINTERS_STATUS=0
function linter {
local name=${1}
local pattern=${2}
local args="${@:3}"
local msg_prefix="git pre-commit ($name)"
# Messages
fail() { >&2 echo "$msg_prefix: FAILED - $1"; LINTERS_STATUS=$(($LINTERS_STATUS|1)); }
info() { echo "$msg_prefix: $1"; }
# Check if linter is installed
which "$name" > /dev/null 2>&1 || fail "Please install \`$name\`."
local files=$(git diff --cached --name-only --diff-filter=AMC | grep "$pattern" | tr '\n' ' ')
if [ -n "$files" ]; then
msg="Validating $files"; info "${msg//\ \:/\:}"
local margin=$(printf "%-4s" " ")
local linter_output
linter_output=$($name ${!args} $files)
local linter_status=$?
echo
echo "$linter_output" | sed "s/^/$margin/"
echo
if [ $linter_status -ne 0 ]; then
fail "Please fix Ruby style issues commiting."
fi
else
info "No files to check."
fi
}
linter rubocop "\.rb$" -f -s -c "$(git rev-parse --show-toplevel)/.rubocop.yml"
linter coffeelint "\.coffee$"
exit $LINTERS_STATUS
@patrickmclaren
Copy link
Author

I might refactor this to allow for coffeelint usage too.

EDIT: Done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment