添加 checkstyle 作为预提交 git 钩子

add checkstyle as pre-commit git hook

我正在尝试添加:https://gist.github.com/davetron5000/37350 checkstyle 代码格式检查作为预提交 git 挂钩。

我按照下面的说明操作,但它不起作用。

Steps 我试过了:

  1. Checkstyle's jar file somewhere
  2. Checkstyle XML check file somewhere
  3. To configure git:
    • git config --add checkstyle.jar <location of jar>
    • git config --add checkstyle.checkfile <location of checkfile>
    • git config --add java.command <path to java executable> [optional, defaults to assuming it's in your path]
  4. Put this in your .git/hooks directory as pre-commit

也许它不起作用,因为我不明白git config --add java.command <path to java executable>是什么意思。但它说它是可选的如果那不是问题,也许我需要以某种方式使脚本文件成为可执行文件?

ps: OS 是 Windows

好的,看来我终于找到了解决方案。我在说明中添加了一些评论我是如何工作的。

 1. checkstyle's jar file somewhere
 2. a checkstyle XML check file somewhere
 3. To configure git:
   * git config --add checkstyle.jar <location of jar>
   * git config --add checkstyle.checkfile <location of checkfile>
   * git config --add java.command <path to java executale> [optional
    defaults to assuming it's in your path]

我检查了我的配置(可以在您的 git 存储库的 .git 目录中找到),它看起来像这样:

 ...    
 [checkstyle]   
 checkfile = C:\Users\schuster\Desktop\checkstyle
 jar = C:\Users\schuster\Desktop\checkstyle    
  ...   

因此,自从我在 Windows 上工作后,我将其更改为:

...
[checkstyle]
    checkfile = C:/Users/schuster/Desktop/checkstyle/google_checks.xml
    jar = C:/Users/schuster/Desktop/checkstyle/checkstyle.jar
...

.

 4. Put this in your .git/hooks directory as pre-commit

'This' 是我在陈述问题时链接的文件。所以这个文件需要在/hooks目录下。但它必须重命名为已经存在的现有示例之一。由于我的钩子是预提交钩子,所以我使用了 "pre-commit" 文件名。接下来这个文件必须变成一个可执行文件。为此,请在 git 存储库的 /hooks 目录中输入 chmod +x pre-commit。如果您使用 Windows 使用 Git Bash.

编辑:

万一有人想使用这个脚本并且想知道为什么即使检查失败它也不会中止 - 这里是修复它的方法。 在第 58 行
if (&run_and_log_system ($command))
必须念到
if (!&run_and_log_system ($command))

配置 checkstyle.jar 和 checkstyle.checkfile 后。如果它没有在检查失败时中止,这里是修复。

第 58 行

if (&run_and_log_system ($command))

替换为下面

$command .= " | grep WARN ";
if (!&run_and_log_system ($command))