2012-11-06 90 views
5

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

回答

5

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

你可以写钩,可以通过外壳可以理解的任何语言,用正确配置的解释器(bash中,蟒蛇,perl的)等

但是,为什么不写Java代码格式在Java中,并从预提交钩子调用它。