用java编写预提交钩子?

问题描述 投票:0回答:4

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

java git githooks pre-commit-hook
4个回答
9
投票

这个想法是调用一个脚本,该脚本又调用您的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)

这个 其他示例直接调用

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

4
投票

从 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 或类似的终端模拟器。然而,shebangs 并不 处理好空间。我通过将 java 的副本移动到不带空格的目录中来测试它的工作原理,并且工作正常。


1
投票

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

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


1
投票

是的,你可以用java写一个git hook。

尝试过的解决方案

我尝试了 Rudi 的解决方案来解决我的 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 钩子将阻止提交

© www.soinside.com 2019 - 2024. All rights reserved.