git 在java中写pre-commit hook

uz75evzq  于 12个月前  发布在  Git
关注(0)|答案(4)|浏览(164)

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

whlutmcx

whlutmcx1#

这个想法是调用一个脚本,然后调用你的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
8i9zcol2

8i9zcol22#

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

$ java Hook.java

如果您使用的是基于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);
    }
}

那么你可以简单地执行它,就像你执行任何其他脚本文件一样。

$ ./Hook

如果您将文件重命名为pre-commit,然后将其移动到.git/hooks目录中,那么现在就有了一个可以工作的Java Git Hook。
注意:你可以使用Cygwin或Git Bash或类似的终端模拟器在Windows上运行。然而,shebangs不能很好地处理空间。我测试了一下,通过将java的副本移动到一个没有空格的目录中,它工作得很好。

xlpyo6sf

xlpyo6sf3#

你可以用shell可以理解的任何语言编写钩子,并适当配置解释器(bash,python,perl)等。
但是,为什么不用java编写java代码格式化程序,并从pre-commit钩子调用它呢?

cczfrluj

cczfrluj4#

你可以用java写一个git hook。

尝试解决

我尝试了Rudi对我的commit-msg钩子的解决方案:

  • commit-msg文件 *
#!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

适合我的解决方案

然后我找到了一个来源,概述了另一种方式。
https://dev.to/awwsmm/eliminate-unnecessary-builds-with-git-hooks-in-bash-java-and-scala-517n#writing-a-git-hook-in-java
commit-msg钩子如下所示

#!bin/sh
DIR=$(dirname "$0")
exec java $DIR/commit-msg.java "$@"

这会将git commit命令的当前目录(.git/hooks)保存到一个变量中,以帮助构建java文件的路径。然后,shell执行java命令,其中包含java文件的路径和一个参数,参数中包含COMMIT_EDITMSG文件的路径。
然后你可以把上面定义的Hook类移到它自己的java文件中(在本例中是commit-msg.java),并把它放在.git/hooks目录中。
现在你可以运行git commit -m“Message”,commit-msg钩子会阻止提交

相关问题