I need to write a Git pre commit hook in Java, which would check if the code commited by the developer is formatted according to a specific eclipse code formatter before actually commiting it, otherwise reject it from commiting. Is it possible to write the pre commit hook in Java?
The first four hooks have to do with the committing process. The pre-commit hook is run first, before you even type in a commit message. It's used to inspect the snapshot that's about to be committed, to see if you've forgotten something, to make sure tests run, or to examine whatever you need to inspect in the code.
The goal of pre-commit hooks is to improve the quality of commits. This is achieved by making sure your commits meet some (formal) requirements, e.g: that they comply to a certain coding style (with the hook style-files ). that you commit derivatives such as README.md or .
The idea is to call a script which in turns call your java program (checking the format).
You can see here an example written in python, which calls 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)
This other example calls directly ant
, in order to execute an ant script (which in turns call a Java JUnit test suite)
#!/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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With