From f84e9baf19853cd7681c3a7863d255bcae52551a Mon Sep 17 00:00:00 2001 From: chengshiwen Date: Sat, 10 Aug 2024 12:45:50 +0800 Subject: [PATCH] chore: add checkfmt.sh in workflows --- .github/workflows/go.yml | 13 ++++++++----- checkfmt.sh | 31 +++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 5 deletions(-) create mode 100755 checkfmt.sh diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index f3e8919..53005a3 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -14,18 +14,21 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Go - uses: actions/setup-go@v3 + uses: actions/setup-go@v4 with: go-version: 1.21 + - name: Fmt + run: ./checkfmt.sh + + - name: Vet + run: go vet ./... + - name: Build run: go build ./... - name: Test run: go test -race ./... - - - name: Vet - run: go vet ./... diff --git a/checkfmt.sh b/checkfmt.sh new file mode 100755 index 0000000..320a669 --- /dev/null +++ b/checkfmt.sh @@ -0,0 +1,31 @@ +#!/bin/bash + +go install golang.org/x/tools/cmd/goimports + +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}}{{range .TestGoFiles}}{{printf "%s/%s\n" $dir .}}{{end}}{{range .IgnoredGoFiles}}{{printf "%s/%s\n" $dir .}}{{end}}{{range .CgoFiles}}{{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="$(goimports -l -d $file)" + # ... and if goimports 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 '' +fi +exit "$HAS_FMT_ERR"