Jee*_*tha 6 java git pre-commit-hook
我需要用Java编写一个Git预提交钩子,如果由开发商COMMITED代码根据特定的格式,其将检查Eclipse代码格式化实际上commiting之前,否则从commiting拒绝它.是否可以在Java中编写预提交钩子?
我们的想法是调用一个脚本,然后调用你的java程序(检查格式).
你可以在这里看到一个用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)
Run Code Online (Sandbox Code Playgroud)
这个另一个例子直接调用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
Run Code Online (Sandbox Code Playgroud)
从 Java 11 开始,您现在可以使用 java 命令运行未编译的主类文件。
$ java Hook.java
Run Code Online (Sandbox Code Playgroud)
如果您使用的是基于 Unix 的操作系统(例如 MacOS 或 Linux),您可以去掉.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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后您可以像处理任何其他脚本文件一样简单地执行它。
$ ./Hook
Run Code Online (Sandbox Code Playgroud)
如果您重命名该文件pre-commit,然后将其移动到您的.git/hooks目录中,那么您现在就有了一个可用的 Java Git Hook。
注意:您可以使用 Cygwin 或 Git Bash 或类似的终端模拟器使其在 Windows 上运行。然而,shebangs 不能很好地处理空间。我通过将 java 的副本移动到不带空格的目录中来测试它的工作原理,并且工作正常。