From 7e551a8fc193c475fbd9d77a27ed644646158004 Mon Sep 17 00:00:00 2001 From: Richard van der Hoff Date: Wed, 5 Apr 2017 14:51:07 +0100 Subject: [PATCH] fix up the pre-commit hook (#1) * Run the checks against the git index (ie, what you're about to commit), rather than the working copy * Add the changes made by `go fmt` back to the index, so that they are included in the commit, as well as the working copy. --- hooks/pre-commit | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/hooks/pre-commit b/hooks/pre-commit index d9ffbfb..736f559 100755 --- a/hooks/pre-commit +++ b/hooks/pre-commit @@ -1,9 +1,46 @@ -#! /bin/bash +#!/bin/bash set -eu +# make the GIT_DIR and GIT_INDEX_FILE absolute, before we change dir +export GIT_DIR=$(readlink -f `git rev-parse --git-dir`) +if [ -n "${GIT_INDEX_FILE:+x}" ]; then + export GIT_INDEX_FILE=$(readlink -f "$GIT_INDEX_FILE") +fi + +wd=`pwd` + +# create a temp dir. The `trap` incantation will ensure that it is removed +# again when this script completes. +tmpdir=`mktemp -d` +trap 'rm -rf "$tmpdir"' EXIT +cd "$tmpdir" + +# get a clean copy of the index (ie, what has been `git add`ed), so that we can +# run the checks against what we are about to commit, rather than what is in +# the working copy. +git checkout-index -a + +# run our checks golint src/... go fmt ./src/... go tool vet --shadow ./src gocyclo -over 12 src/ gb test + +# if there are no changes from the index, we are done +git diff --quiet && exit 0 + +# we now need to apply any changes made to both the index and the working copy. +# so, first get a patch +git diff > "$GIT_DIR/pre-commit.patch" + +# add the changes to the index +git add -u + +# attempt to apply the changes to the wc (but don't fail the commit for it if +# there are conflicts). +cd "$wd" +git apply "$GIT_DIR/pre-commit.patch" 2>/dev/null && + rm "$GIT_DIR/pre-commit.patch" || + echo "warning: unable to apply changes from commit hook to working copy; patch is in $GIT_DIR/pre-commit.patch" >&2