bashgogofmt

Make gofmt exit with exit status 1, when gofmt suggests changes?


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?


Solution

  • 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.