检查以确定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.

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.

I found this pre-commit hook enter link description here

1   #!/bin/sh
 2  # Copyright 2012 The Go Authors. All rights reserved.
 3  # Use of this source code is governed by a BSD-style
 4  # license that can be found in the LICENSE file.
 5  
 6  # git gofmt pre-commit hook
 7  #
 8  # To use, store as .git/hooks/pre-commit inside your repository and make sure
 9  # it has execute permissions.
10  #
11  # This script does not handle file names that contain spaces.
12  
13  gofiles=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$')
14  [ -z "$gofiles" ] && exit 0
15  
16  unformatted=$(gofmt -l $gofiles)
17  [ -z "$unformatted" ] && exit 0
18  
19  # Some files are not gofmt'd. Print message and fail.
20  
21  echo >&2 "Go files must be formatted with gofmt. Please run:"
22  for fn in $unformatted; do
23      echo >&2 "  gofmt -w $PWD/$fn"
24  done
25  
26  exit 1