2016-09-30 49 views
1

我的目标是在提交时强制执行去源代码的格式。有没有办法找出在文件/文件集上运行go fmt是否会做出任何更改?我能想到的唯一方法是:检查以确定去代码是否已格式化

  • 店当前时间
  • 运行FMT走了过来源
  • 迭代的源文件,看是否有最后MOD日期>t

我可以写一个工具/脚本来做到这一点,并在圆形CI构建过程中执行。我想在继续之前检查一下我是不是在重新发明轮子。

+1

为什么不能无条件地格式化? – coredump

+4

这是内置于'gofmt'程序:'gofmt -l ...' –

+0

你可以在前后运行'md5sum',以确保即使时间戳记文件没有改变。 –

回答

0

根据gofmt -h您可以使用-l选项:

-l列表文件,其中的格式从gofmt's`

喜欢的东西不同:

> gofmt -l . 

而且将接收到的列表进一步的文件。

1

我发现这个pre-commit钩子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