21

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.

4
  • 2
    Why not format it unconditionally? Commented Sep 30, 2016 at 13:33
  • 5
    This is built-in to the gofmt program: gofmt -l ... Commented Sep 30, 2016 at 13:53
  • you could always run md5sum before and after to be sure the file hasn't changed even if the timestamp has. Commented Sep 30, 2016 at 14:07
  • 1
    @coredump because if changes were made they would need to be committed which would break the flow; the build job is to assert not mutate Commented Aug 2, 2019 at 5:21

4 Answers 4

24

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.

Sign up to request clarification or add additional context in comments.

Comments

9

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.

Comments

5

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

Comments

3

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" ]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.