Skip to content

Instantly share code, notes, and snippets.

@rclark
Last active April 4, 2023 19:05
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 rclark/316546e8939faca5f1a827f0feb74ca8 to your computer and use it in GitHub Desktop.
Save rclark/316546e8939faca5f1a827f0feb74ca8 to your computer and use it in GitHub Desktop.
Pre-commit hook for Golang formatting and linting

Pre-commit git hook to require Golang formatting and linting

  1. Add this file in a local repo at .githooks/pre-commit.
  2. git config core.hooksPath .githooks sets up the hook
#!/bin/sh
STAGED_GO_FILES=$(git diff --cached --name-only --diff-filter ACMR | grep ".go$" | grep -v '^vendor/')
if [ "$STAGED_GO_FILES" = "" ]
then exit 0
fi
directories=""
for filename in $STAGED_GO_FILES
do directories="$directories $(dirname $filename)"
done
STAGED_GO_PACKAGES=$(echo "$directories" | tr " " "\n" | sort | uniq)
PASS=true
if ! gofmt -s -w $STAGED_GO_FILES
then PASS=false
fi
if ! golangci-lint run --fix $STAGED_GO_PACKAGES
then PASS=false
fi
if ! git add $STAGED_GO_FILES
then PASS=false
fi
if [ "$PASS" = "false" ]
then exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment