#!/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
#!C:/Progra~1/Java/jdk-17.0.1/bin/java.exe --source 17
#Using Progra~1 to represent "Program Files" as escaping the space
#or surrounding the path in double quotes didn't work for me.
public class Hook {
public static void main(String[] args) {
System.out.println("No committing please.");
System.exit(1);
}
}
但我收到了这个错误消息,并有困难的故障排除
$ git commit -m "Message"
Error: Could not find or load main class .git.hooks.commit-msg
Caused by: java.lang.ClassNotFoundException: /git/hooks/commit-msg
4条答案
按热度按时间whlutmcx1#
这个想法是调用一个脚本,然后调用你的java程序(检查格式)。
你可以see here an example written in python,它调用java。
这个other example calls directly
ant
,为了执行一个ant脚本(反过来调用Java JUnit测试套件)8i9zcol22#
从Java 11开始,您现在可以使用java命令运行未编译的主类文件。
如果您使用的是基于Unix的操作系统(例如MacOS或Linux),则可以剥离
.java
并在顶部行添加一个shebang,如下所示:那么你可以简单地执行它,就像你执行任何其他脚本文件一样。
如果您将文件重命名为
pre-commit
,然后将其移动到.git/hooks
目录中,那么现在就有了一个可以工作的Java Git Hook。注意:你可以使用Cygwin或Git Bash或类似的终端模拟器在Windows上运行。然而,shebangs不能很好地处理空间。我测试了一下,通过将java的副本移动到一个没有空格的目录中,它工作得很好。
xlpyo6sf3#
你可以用shell可以理解的任何语言编写钩子,并适当配置解释器(bash,python,perl)等。
但是,为什么不用java编写java代码格式化程序,并从pre-commit钩子调用它呢?
cczfrluj4#
你可以用java写一个git hook。
尝试解决
我尝试了Rudi对我的commit-msg钩子的解决方案:
但我收到了这个错误消息,并有困难的故障排除
适合我的解决方案
然后我找到了一个来源,概述了另一种方式。
https://dev.to/awwsmm/eliminate-unnecessary-builds-with-git-hooks-in-bash-java-and-scala-517n#writing-a-git-hook-in-java
commit-msg钩子如下所示
这会将git commit命令的当前目录(.git/hooks)保存到一个变量中,以帮助构建java文件的路径。然后,shell执行java命令,其中包含java文件的路径和一个参数,参数中包含COMMIT_EDITMSG文件的路径。
然后你可以把上面定义的Hook类移到它自己的java文件中(在本例中是commit-msg.java),并把它放在.git/hooks目录中。
现在你可以运行git commit -m“Message”,commit-msg钩子会阻止提交