Skip to content

Pre commit hook for linters

chetanyakan edited this page May 10, 2018 · 1 revision

This is a pre commit hook to automatically run linters before a commit can be made.

Instructions

  1. If you have never added any pre commit hooks to this project:
    • Add the code for the hook to [project]/.git/hooks/pre-commit.sample
    • Rename [project]/.git/hooks/pre-commit.sample to [project]/.git/hooks/pre-commit (remove the .sample)
  2. If you have added pre commit hooks to this project:
    • Add the code for the hook to your already existing pre-commit file in .git/hooks

NOTE: It is usually a better idea to actually rename the sample file rather than create a new file and name it pre-commit because the permissions have to change. If you do decide to create a new file you need to update the permissions of it with chmod +x pre-commit.

You should now have a pre-commit file inside of .git/hooks that contains the given hook.

#!/bin/sh
# Copyright 2012 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

# git gofmt pre-commit hook
#
# To use, store as .git/hooks/pre-commit inside your repository and make sure
# it has execute permissions.
#
# This script does not handle file names that contain spaces.

# go list ./... | xargs -L1 golint
gofiles=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$')
[ -z "$gofiles" ] && exit 0

unformatted=$(gofmt -l $gofiles)
[ -z "$unformatted" ] && exit 0

# Some files are not gofmt'd. Print message and fail.

echo >&2 "Go files must be formatted with gofmt. Please run:"
for fn in $unformatted; do
	echo >&2 "  gofmt -w $PWD/$fn"
done

exit 1

Clone this wiki locally