Gin Rummy Indian Rummy Nine Men's Morris and more Air Attack

Friday, 8 January 2016

Java code formatting hook for git

Code formatting will be done using pre-commit hook, which runs first when user do a commit.

Code for the hook is given below. It formats java source code using astyle.

# don't do anything if astyle command is not available
command -v astyle >/dev/null 2>&1 || { exit 0; }

# get the root directory for the repository
RootDir=`git rev-parse --show-toplevel`

# get all the files that are staged
for v in `git diff --name-only --cached`
    # if it is java file
    if [[ $v == *.java ]]
        astyle --style=java "$RootDir/$v" > /dev/null 2>&1
        # remove the .orig file created by astyle
        [ -f "$RootDir/$v"".orig" ] && rm -f "$RootDir/$v"".orig"

        # stage the modified file
        # its ok if the file is unchanged after running astyle
        git add "$RootDir/$v"


exit 0
Copy the above code in .git/hooks with file name as pre-commit.

For this hook to work as expected astyle command needs to be in the path. Astyle can be downloaded from

For more information on git hooks please visit

No comments:

Post a Comment