Skip to content

Commit a16a38e

Browse files
committed
Let pre-commit hook run go mod tidy
amend
1 parent be30575 commit a16a38e

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

DEV.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
## Development
44

5-
After cloning this repository, set up the pre-commit hook to ensure proper formatting of the Go code:
5+
After cloning this repository, set up the pre-commit hook to ensure proper formatting of the Go code and the `go.mod` and `go.sum` files:
66
```shell
77
ln -s ../../git-hooks/pre-commit .git/hooks/pre-commit
88
```

git-hooks/pre-commit

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,31 @@
33
# Use of this source code is governed by a BSD-style
44
# license that can be found in the LICENSE file.
55

6-
# git gofmt pre-commit hook
6+
# git gofmt & go mod tidy pre-commit hook
77
#
88
# To use, store as .git/hooks/pre-commit inside your repository and make sure
99
# it has execute permissions.
1010
#
1111
# This script does not handle file names that contain spaces.
1212

13+
function failWithMessage {
14+
echo >&2 $1
15+
exit 1
16+
}
17+
18+
# Adapted from dnephin/pre-commit-golang
19+
go mod tidy -v 2>&1 | grep -q "updates to go.mod needed" && failWithMessage "go mod tidy: updates to go.mod needed"
20+
git diff --exit-code go.* &> /dev/null || failWithMessage "go.mod or go.sum differs, please re-add it to your commit"
21+
1322
gofiles=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$')
1423
[ -z "$gofiles" ] && exit 0
1524

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

1928
# Some files are not gofmt'd. Print message and fail.
20-
21-
echo >&2 "Go files must be formatted with gofmt. Please run:"
29+
msg="Go files must be formatted with gofmt. Please run:"
2230
for fn in $unformatted; do
23-
echo >&2 " gofmt -w $PWD/$fn"
31+
msg+="\n gofmt -w $PWD/$fn"
2432
done
25-
26-
exit 1
33+
failWithMessage msg

0 commit comments

Comments
 (0)