Make gofmt exit with exit status 1, when gofmt suggests changes?
Asked Answered
A

2

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?

Alcazar answered 3/5, 2019 at 10:12 Comment(0)
L
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.

Lebkuchen answered 3/5, 2019 at 10:20 Comment(1)
I know Golang wants to be aggressively minimal but this could easily have been a valuable flag / option on gofmt itself.Whitson
D
2

You can use

test -z $(gofmt -l .)
Domela answered 13/6, 2021 at 21:4 Comment(2)
This fails with test: too many arguments when more than one .go file fails gofmtHeliocentric
@JacobMarble Use double quotes around the command substitution, like so: test -z "$(gofmt -l .)"Raby

© 2022 - 2024 — McMap. All rights reserved.