Pages

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.
#!/bin/bash

# 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`
do
    # if it is java file
    if [[ $v == *.java ]]
    then
        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"
    fi

done

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 http://astyle.sourceforge.net/

For more information on git hooks please visit https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks

No comments:

Post a Comment