【问题标题】:Write GIT pre-commit hook in java?在java中编写GIT预提交钩子?
【发布时间】:2012-10-26 03:01:32
【问题描述】:

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

【问题讨论】:

    标签: java git pre-commit-hook


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      $ java Hook.java
      

      如果你去掉 .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。

      【讨论】:

      • 有趣的更新,比我 2012 年的答案更新。赞成。
      【解决方案3】:

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

      但是,为什么不在 java 中编写您的 java 代码格式化程序,并从 pre-commit 挂钩中调用它。

      【讨论】:

        猜你喜欢
        • 2013-12-15
        • 2019-07-12
        • 2015-01-13
        • 2018-05-21
        • 1970-01-01
        • 1970-01-01
        • 2015-08-17
        • 2021-03-01
        相关资源
        最近更新 更多