Problem

Many people use gofmt in CI to lint their code, ensuring that only correctly formatted code gets committed to the repository. However, gofmt does not currently have a way to return a non-zero exit code for incorrectly formatted code. This makes it harder to use in CI, leading to common workarounds like this:

test -z "$(gofmt -l .)"

However, the above example swallows all output, leaving users with only a generic error message rather than informing them which files have failed the linting step. More complex examples use tee to fix this, however all implementations are ugly and GitHub's code search shows many examples of users using gofmt in a way that hides the output. Many of the examples show that users are incorrectly assuming that gofmt already returns a non-zero exit code.

Ideally, gofmt should return a non-zero exit code directly to simplify this common use case and to make it harder for users to shoot themselves in the foot.

Proposal

To avoid breaking backwards compatibility with other use cases which rely on the current behaviour, a new flag could be added which allows users to opt in to the new behaviour. This would allow the above example to be simplified to:

gofmt -d -x

Since the output is no longer swallowed, the use of the -d flag would also allow users to see a full diff which clearly shows which files are incorrectly formatted and what the correct formatting would be.

Implementation

I put together an example change to show that this is relatively straightforward to implement. If this proposal has support then I'll create a proper change and submit it for review.