From 2f2334a3f33221979ec63e88095d65dd0c9eee9e Mon Sep 17 00:00:00 2001 From: Chris Goller Date: Mon, 8 Oct 2018 13:16:06 -0500 Subject: [PATCH] ci(gofmt): check go formatting with each PR --- .circleci/config.yml | 1 + Makefile | 5 ++++- etc/checkfmt.sh | 29 +++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100755 etc/checkfmt.sh diff --git a/.circleci/config.yml b/.circleci/config.yml index 0a5a439182..f9613830c6 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -43,6 +43,7 @@ jobs: - platform-gocache- # Matches a new branch. - run: make test-go # This uses the test cache so it may succeed or fail quickly. - run: make vet + - run: make checkfmt - run: make test-go-race # This doesn't use the test cache, and will not complete quickly. # TODO add these checks to the Makefile # - run: go get -v -t -d ./... diff --git a/Makefile b/Makefile index 23f4a935d0..050fc63654 100644 --- a/Makefile +++ b/Makefile @@ -105,7 +105,10 @@ chronograf/ui/build: # fmt: $(SOURCES_NO_VENDOR) - goimports -w $^ + gofmt -w -s $^ + +checkfmt: $(SOURCES_NO_VENDOR) + ./etc/checkfmt.sh chronograf/dist/dist_gen.go: chronograf/ui/build $(UISOURCES) $(GO_GENERATE) ./chronograf/dist/... diff --git a/etc/checkfmt.sh b/etc/checkfmt.sh new file mode 100755 index 0000000000..dc2ad9ca65 --- /dev/null +++ b/etc/checkfmt.sh @@ -0,0 +1,29 @@ +#!/bin/bash + +HAS_FMT_ERR=0 +# For every Go file in the project, excluding vendor... +for file in $(go list -f '{{$dir := .Dir}}{{range .GoFiles}}{{printf "%s/%s\n" $dir .}}{{end}}' ./...); do + # ... if file does not contain standard generated code comment (https://golang.org/s/generatedcode)... + if ! grep -Exq '^// Code generated .* DO NOT EDIT\.$' $file; then + FMT_OUT="$(gofmt -l -d -e $file)" # gofmt exits 0 regardless of whether it's formatted. + # ... and if gofmt had any output... + if [[ -n "$FMT_OUT" ]]; then + if [ "$HAS_FMT_ERR" -eq "0" ]; then + # Only print this once. + HAS_FMT_ERR=1 + echo 'Commit includes files that are not gofmt-ed' && \ + echo 'run "make fmt"' && \ + echo '' + fi + echo "$FMT_OUT" # Print output and continue, so developers don't fix one file at a t + fi + fi +done + +## print at the end too... sometimes it is nice to see what to do at the end. +if [ "$HAS_FMT_ERR" -eq "1" ]; then + echo 'Commit includes files that are not gofmt-ed' && \ + echo 'run "make fmt"' && \ + echo '' +fi +exit "$HAS_FMT_ERR"