Skip to content

Instantly share code, notes, and snippets.

@trane
Last active October 31, 2018 21:52
Show Gist options
  • Save trane/d6510c4cb4e6126ab31cd4fd7c18e2f4 to your computer and use it in GitHub Desktop.
Save trane/d6510c4cb4e6126ab31cd4fd7c18e2f4 to your computer and use it in GitHub Desktop.
Does some simple go/ruby linting to add to your .git/hooks/pre-commit file
#!/bin/bash
function go_golangci_lint() {
echo "Running golangci-lint..."
local -r files="${1}"
# shellcheck disable=SC2086
golangci-lint run \
--no-config \
--presets bugs,format,style,unused \
--out-format=tab \
-D goimports \
-D lll \
-D megacheck \
-D gofmt \
-D golint \
-D typecheck \
$files
}
function go_goimports() {
echo "Fixing formatting with goimports..."
local -r files="${1}"
# shellcheck disable=SC2086
goimports -w $files && git add $files
}
function ruby_rubocop() {
echo "Autocorrecting ruby files..."
local -r files="${1}"
# shellcheck disable=SC2086
bundle exec rubocop --force-exclusion -a $files && git add $files
}
function check_requirements() {
local -r golangci_lint_version="1.11.2"
if ! command -v golangci-lint > /dev/null; then
2> echo "ERROR: please 'brew install golangci/tap/golangci-lint'"
return 1
fi
if ! golangci-lint --version | grep -q "$golangci_lint_version"; then
echo "WARNING: golangci-lint is out-of-date, please run 'brew upgrade golangci/tap/golangci-lint'"
return 1
fi
}
function ask_to_continue() {
exec < /dev/tty
read -rp "Errors happen. Do you want to ignore them and commit anyway? (y/N) " yn
case $yn in
[Yy] ) return 0;;
* ) return 1;;
esac
}
function lint() {
local -r files="$(git diff --diff-filter=ACMRTUXB --cached HEAD --name-only)"
local -r go_files="$(echo "$files" | grep -E '[.]go$' | xargs)"
local -r ruby_files="$(echo "$files" | grep -E '[.]rb$' | xargs)"
local -i errors=0
if [ "${files}" = "" ]; then
exit 0
fi
if ! check_requirements 1> /dev/null; then
echo "Must have golangci-lint, goimports installed"
exit 1
fi
if [ "${go_files}" != "" ]; then
if ! go_goimports "${go_files}"; then
errors+=1
fi
if ! go_golangci_lint "${go_files}"; then
errors+=1
fi
fi
if [ "${ruby_files}" != "" ]; then
if ! ruby_rubocop "${ruby_files}"; then
errors+=1
fi
fi
return $errors
}
if ! lint; then
ask_to_continue
fi
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment