Write GIT pre-commit hook in java?
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
As of Java 11, you can now run un-compiled main class files using the java command.
$ java Hook.java
If you are using a Unix based operating system (MacOS or Linux for example), you can strip off the .java
and add a shebang to the top line like so:
#!/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);
}
}
then you can simply execute it the same way you would with any other script file.
$ ./Hook
If you rename the file pre-commit
, and then move it into your .git/hooks
directory, you now have a working Java Git Hook.
Note: You may be able to get this to work on Windows using Cygwin or Git Bash or similar terminal emulators. However, shebangs do not handle spaces well. I tested that this works by moving a copy of java into a directory without spaces and it works fine.