My goal is to enforce the formatting of go source code on commit. Is there a way to find out if running go fmt
over a file/set of files would make any changes? The only technique I can think of is to:
I could write a tool/script to do this and execute during circle CI build. I wanted to check that I'm not reinventing the wheel before I go ahead.
According to gofmt -h
you can use -l
option:
-l list files whose formatting differs from gofmt's`
Something like:
> gofmt -l .
And pass the received list of files further.
If you want the exit code to be 1 if fails, and to be able to run it on Linux or Mac or other Unix OS, you can use:
files=$(gofmt -l .) && [ -z "$files" ]
I found this pre-commit hook:
#!/bin/sh
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
Add additional info for @u_mulder 's answer.
If you want the exit code be 1 if fails, you can use
test -z $(gofmt -l .)
This is helpful in CI. However, this won't list the list of different files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With