在java中编写GIT预提交钩子?

时间:2012-11-06 07:23:54

标签: java git pre-commit-hook

我需要在Java中编写一个Git pre commit hook,它会检查开发人员提交的代码是否在实际提交之前根据特定的 eclipse代码格式化程序格式化,否则拒绝它commiting。是否可以在Java中编写预提交钩子?

3 个答案:

答案 0 :(得分:5)

这个想法是调用一个脚本,然后调用你的java程序(检查格式)。

你可以see here an example written in python,它会调用java。

try:
    # call checkstyle and print output
    print call(['java', '-jar', checkstyle, '-c', checkstyle_config, '-r', tempdir])
except subprocess.CalledProcessError, ex:
    print ex.output  # print checkstyle messages
    exit(1)
finally:
    # remove temporary directory
    shutil.rmtree(tempdir)

这个other example calls directly ant,为了执行一个ant脚本(反过来调用Java JUnit测试套件)

#!/bin/sh

# Run the test suite.
# It will exit with 0 if it everything compiled and tested fine.
ant test
if [ $? -eq 0 ]; then
  exit 0
else
  echo "Building your project or running the tests failed."
  echo "Aborting the commit. Run with --no-verify to ignore."
  exit 1
fi

答案 1 :(得分:2)

从Java 11开始,您现在可以使用java命令运行未编译的主类文件。

$ java Hook.java

如果您剥离.java并在顶部添加一个shebang,如下所示:

#!/your/path/to/bin/java --source 11
public class Hook {
    public static void main(String[] args) {
        System.out.println("No committing please.");
        System.exit(1);
    }
} 

然后,您可以像使用其他脚本文件一样简单地执行它。

$ ./Hook

如果重命名文件pre-commit,然后将其移动到.git/hooks目录中,那么您现在可以使用Java Git Hook。

答案 2 :(得分:1)

你可以用shell可以理解的任何语言编写钩子,使用正确配置的解释器(bash,python,perl)等。

但是,为什么不在java中编写java代码格式化程序,并从预提交钩子中调用它。