我需要用Java编写一个Git pre commit钩子,它将在实际提交它之前检查开发人员提交的代码是否根据特定的eclipse代码格式化程序进行了格式化,否则将其拒绝提交。是否可以用Java编写pre commit钩子?
您可以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 directlyant
,以执行一个蚂蚁脚本(依次称为Java JUnit测试套件)
ant
但是,为什么不用Java编写Java代码格式化程序,并从预提交钩子中调用它呢?
#!/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
[如果您剥离$ java Hook.java
并在顶部添加一个Shebang,如下所示:
.java
然后,您可以像使用任何其他脚本文件一样简单地执行它。
#!/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
目录中,那么您现在有了一个可用的Java Git Hook。