在Java中编写GIT预提交钩子吗?

问题描述 投票:6回答:3

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

java git pre-commit-hook
3个回答
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,以执行一个蚂蚁脚本(依次称为Java JUnit测试套件)

ant


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

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


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

#!/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

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

.java

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

#!/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目录中,那么您现在有了一个可用的Java Git Hook。
© www.soinside.com 2019 - 2024. All rights reserved.