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

1 comment:

  1. Hey,

    Grazie! Grazie! Grazie! Your blog is indeed quite interesting around It's all fundamental Java code formatting hook for git just follows it! agree with you on lot of points!

    Getting memory violation error when I use string function "strlwr", what wrong in step 3, please help, I am new to c language

    Very useful article, if I run into challenges along the way, I will share them here.

    Kind Regards,