This gist shows how to auto-format Java code using the Eclipse formatter at pre-commit.
Source: https://gist.github.com/ktoso/708972
Code:
#!/bin/sh
#
# This hook will run the eclipse code formatter before any commit
# to make the source look as it's supposed to look like in the repo.
ECLIPSE_HOME=$HOME/eclipse
STYLE_FILE=$HOME/org.eclipse.jdt.core.prefs
echo "Running pre-commit hook: run-eclipse-formatter---------------------"
echo "Will run eclipse formatter, using: $STYLE_FILE"
echo "Listing folders to run formatter on… "
code_dirs=`find . -maxdepth 3 | grep 'src/'`
for dir in $code_dirs; do
echo $dir;
done;
echo "Launching eclipse code formatter… "
exec $ECLIPSE_HOME/eclipse \
-nosplash \
-application org.eclipse.jdt.core.JavaCodeFormatter \
-verbose \
-config $STYLE_FILE \
$code_dirs
echo "done---------------------------------------------------------------"
I'd like to achieve this with IntelliJ and Android Studio. How would the script look like then?
Also I guess it would be best to only run the formatter on changed files. Maybe this is useful:
changedJavaFiles=$(git diff --cached --name-only --diff-filter=ACM | grep '.java$')
ACM stands for Added, Copied, Modified. Source: http://git-scm.com/docs/git-diff
Please comment if anything is unclear.
Update
My setup is Windows 10 and I'd like to use the command line tool MINGW32(Git Bash). Git version is 1.9.5 msysgit.1