From 174d24460c5f57d5f93af0def6e70fe3464c8e0b Mon Sep 17 00:00:00 2001 From: Christopher Fenner Date: Wed, 27 Nov 2019 21:16:01 +0100 Subject: [PATCH] chore(go): add pre-commit hook (#1006) * chore(go): add pre-commit hook run go mod tidy add description * use bash * adjust indentation * fix code climate issue * docs: clarify git hook usage description * Update .hooks/README.md --- .hooks/README.md | 33 +++++++++++++++++++++++++++++++++ .hooks/pre-commit | 11 +++++++++++ 2 files changed, 44 insertions(+) create mode 100644 .hooks/README.md create mode 100755 .hooks/pre-commit diff --git a/.hooks/README.md b/.hooks/README.md new file mode 100644 index 000000000..4b5013b5e --- /dev/null +++ b/.hooks/README.md @@ -0,0 +1,33 @@ +# Git Hooks + +From [Git docs](https://git-scm.com/docs/githooks#_description): + +> Hooks are programs you can place in a hooks directory to trigger actions at certain points in git’s execution. Hooks that don’t have the executable bit set are ignored. + +## Usage + +To use the hook, execute this command in the project root directory to link the script into the `.git/hooks` directory: + +```sh +ln -s -f ../../.hooks/pre-commit ./.git/hooks/pre-commit +``` + +Make sure the file is executable: + +```sh +chmod +x ./.hooks/pre-commit +``` + +## Pre-Commit Hook + +From [Git docs](https://git-scm.com/docs/githooks#_pre_commit): + +> This hook is invoked by git-commit, and can be bypassed with the --no-verify option. It takes no parameters, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with a non-zero status from this script causes the git commit command to abort before creating a commit. + +### Content + +Executes `go mod tidy` and stages `go.mod` & `go.sum`. + +From [Golang docs](https://github.com/golang/go/wiki/Modules): + +> `go mod tidy` — Prune any no-longer-needed dependencies from `go.mod` and add any dependencies needed for other combinations of OS, architecture, and build tags (details). diff --git a/.hooks/pre-commit b/.hooks/pre-commit new file mode 100755 index 000000000..7384ace6b --- /dev/null +++ b/.hooks/pre-commit @@ -0,0 +1,11 @@ +#!/bin/bash + +STAGED_GO_FILES=$(git diff --staged --name-only | grep "\.go$") + +if [[ "$STAGED_GO_FILES" = "" ]]; then + exit 0 +fi + +echo "cleaning GO dependencies" +go mod tidy +git add go.mod go.sum