Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking to find out if go code has been formatted

Tags:

go

My goal is to enforce the formatting of go source code on commit. Is there a way to find out if running go fmt over a file/set of files would make any changes? The only technique I can think of is to:

  • store the current time t
  • run go fmt over the source
  • iterate the source files to see if any of the last mod dates > t

I could write a tool/script to do this and execute during circle CI build. I wanted to check that I'm not reinventing the wheel before I go ahead.

like image 702
Myles McDonnell Avatar asked Sep 30 '16 13:09

Myles McDonnell


4 Answers

According to gofmt -h you can use -l option:

-l list files whose formatting differs from gofmt's`

Something like:

> gofmt -l .

And pass the received list of files further.

like image 137
u_mulder Avatar answered Nov 01 '22 12:11

u_mulder


If you want the exit code to be 1 if fails, and to be able to run it on Linux or Mac or other Unix OS, you can use:

files=$(gofmt -l .) && [ -z "$files" ]
like image 29
jmaitrehenry Avatar answered Nov 01 '22 11:11

jmaitrehenry


I found this pre-commit hook:

#!/bin/sh

gofiles=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$')
[ -z "$gofiles" ] && exit 0

unformatted=$(gofmt -l $gofiles)
[ -z "$unformatted" ] && exit 0

# Some files are not gofmt'd. Print message and fail.

echo >&2 "Go files must be formatted with gofmt. Please run:"
for fn in $unformatted; do
    echo >&2 "  gofmt -w $PWD/$fn"
done

exit 1
like image 5
Myles McDonnell Avatar answered Nov 01 '22 12:11

Myles McDonnell


Add additional info for @u_mulder 's answer.

If you want the exit code be 1 if fails, you can use

test -z $(gofmt -l .)

This is helpful in CI. However, this won't list the list of different files.

like image 3
Hongbo Miao Avatar answered Nov 01 '22 10:11

Hongbo Miao