5

I would like to add gofmt to the CI/CD pipeline. If it produces changes, I want gofmt to exit with status 1.

For example if I run gofmt -s -l . and there are some files listed. I want it to exit with status 1. Right now when I run echo $? gives me 0, even if there are some files listed with gofmt's changes.

I checked the docs and couldn't find a corresponding command line option. Is there a bash hack to do it?

Vasantha Ganesh
  • 4,570
  • 3
  • 25
  • 33

2 Answers2

7

You just need to ensure if the gofmt lists one more lines of output by checking the output of wc -l is non-empty and then run the binary false which sets the exit code to 1 to the shell invoked or use exit 1 to exit out of the script explicitly.

if [ "$(gofmt -s -l . | wc -l)" -gt 0 ]; then
    exit 1
fi

When you say gofmt actually returns $? as 0 even if there are files listed?, in that case you could also simply do

if gofmt -s -l . > /dev/null; then
    exit 1
fi

The above if condition relies on the exit code returned by gofmt as 0 would indicate a success of the command, the conditional would assert a true.

Inian
  • 80,270
  • 14
  • 142
  • 161
  • 3
    I know Golang wants to be aggressively minimal but this could easily have been a valuable flag / option on `gofmt` itself. – abhchand Dec 28 '21 at 20:59
2

You can use

test -z $(gofmt -l .)
Hongbo Miao
  • 45,290
  • 60
  • 174
  • 267