Skip to content

Commit 81a775b

Browse files
authored
Add Go pre-commit hook (#55)
1 parent b76ac40 commit 81a775b

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

Makefile

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,14 @@ GOSEC ?= $(GOBIN)/gosec
88
OPA ?= opa
99
export PATH := $(GOBIN):$(PATH)
1010

11-
.PHONY: all tidy build test lint format lint-go lint-python format-go format-python docker-up docker-down docker-logs db-migrate opa-test cert-refresh setup-venv security
11+
.PHONY: all tidy build test lint format lint-go lint-python format-go format-python docker-up docker-down docker-logs db-migrate opa-test cert-refresh setup-venv security install-hooks
1212

1313
all: build
1414

15+
install-hooks:
16+
mkdir -p .git/hooks
17+
install -m 0755 scripts/pre-commit .git/hooks/pre-commit
18+
1519
tidy:
1620
go mod tidy
1721

scripts/pre-commit

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#!/usr/bin/env bash
2+
3+
set -euo pipefail
4+
5+
repo_root=$(git rev-parse --show-toplevel)
6+
cd "$repo_root"
7+
8+
mapfile -t staged_go_files < <(git diff --cached --name-only --diff-filter=ACM -- "*.go")
9+
if [ ${#staged_go_files[@]} -eq 0 ]; then
10+
exit 0
11+
fi
12+
13+
stashed=0
14+
cleanup() {
15+
if [ "$stashed" -eq 1 ]; then
16+
git stash pop -q >/dev/null 2>&1 || true
17+
fi
18+
}
19+
trap cleanup EXIT
20+
21+
if ! git diff --quiet -- . || [ -n "$(git ls-files --others --exclude-standard)" ]; then
22+
git stash push -q --keep-index --include-untracked -m "pre-commit-$(date +%s)"
23+
stashed=1
24+
fi
25+
26+
echo "Running gofmt on staged files..."
27+
gofmt -w "${staged_go_files[@]}"
28+
git add -- "${staged_go_files[@]}"
29+
30+
if ! command -v golangci-lint >/dev/null 2>&1; then
31+
echo "golangci-lint is required for this repo. Install it and retry." >&2
32+
exit 1
33+
fi
34+
35+
echo "Running golangci-lint..."
36+
golangci-lint run ./...
37+
38+
echo "Running go test..."
39+
go test ./...

0 commit comments

Comments
 (0)