Is there a built-in way to check if Go code is already formatted?

2,333 views
Skip to first unread message

mrush...@pivotallabs.com

unread,
Nov 16, 2013, 1:51:01 AM11/16/13
to golan...@googlegroups.com
I want to set up Travis CI to fail a build if the code wasn't formatted correctly.  It doesn't appear that gofmt has a flag that will cause the command to pass or fail based on whether any files were or need to be reformatted.

My imaginary shell session with this imaginary command would be something like:

$ gofmt -checkFormatting ./... # some files need formatting, command exits 1
$ go fmt ./...
$ gofmt -checkFormatting ./... # all files already formatted, command exits 0

I just found codereview.py which has its own CheckGoFmt function that does something similar to what I want to do, so that makes it look like gofmt does not currently have the feature I'm looking for.  Is this something that belongs in gofmt?  Or does an external script for this functionality make more sense from the Go authors' perspectives?

Mark

andrey mirtchovski

unread,
Nov 16, 2013, 2:04:54 AM11/16/13
to mrush...@pivotallabs.com, golang-nuts
you can use a combination of gofmt -l file and the exit code of gofmt. if you had parsing errors exit code would be 2 (generally), and if you didn't have parsing errors but you had a differing formatting the -l flag would force some output.

for example, try this in $GOROOT/test/:

% for i in $GOROOT/test/*; do gofmt -l $i 2>/dev/null; echo $?; done

remove the redirect of stderr to /dev/null to see what the errors were.

​HTH

aro...@gmail.com

unread,
Nov 16, 2013, 3:01:44 AM11/16/13
to golan...@googlegroups.com, mrush...@pivotallabs.com
gofmt -d path/to/file.go 2>&1 | read; [ $? == 1 ]

should do it:

If the file has formatting issues, gofmt will output to stdout.  If the file has parsing errors, gofmt will output to stderr.  2>&1 combines stderr and stdout.  | read will succeed if there's any output.

So if there's any formatting/syntax issues, the read returns 0.  Otherwise it returns 1.

[ $? == 1 ] inverts read's return code.

Matt Harden

unread,
Nov 22, 2013, 4:16:48 PM11/22/13
to aro...@gmail.com, golang-nuts, mrush...@pivotallabs.com
Instead of [ $? == 1 ], just use the not (!) prefix:

! gofmt -d path/to/file.go 2>&1 | read


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply all
Reply to author
Forward
0 new messages