How to format code according to google java format
You can let pre-commit hook trigger formatter for files staged for commit.
git-code-format-maven-plugin uses google-java-format formatter and can install client-side pre-commit git hook during compile phase. It requires Maven 3.5.x, which should be enforced.
<build>
<plugins>
<plugin>
<groupId>com.cosium.code</groupId>
<artifactId>git-code-format-maven-plugin</artifactId>
<version>VERSION</version>
<executions>
<execution>
<goals>
<goal>install-hooks</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-enforcer-plugin</artifactId>
<version>VERSION</version>
<executions>
<execution>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>[3.5.4,)</version>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Point to standalone Maven in IDE as git-code-format-maven-plugin does not play along nicely with embedded Maven.
mvn compile
to get hook installed. For IDEA, that's it.
As git-code-format-maven-plugin only formats changed files (which is good), it is probably good to format whole project upfront once (mvn git-code-format:format-code -Dgcf.globPattern=**/*
).
Workaround for Eclipse
Because of a bug in EGit, which sometimes ignores Git hooks completely, developers using Eclipse on Windows should have Cygwin in PATH. An empty cygpath.exe
will do. Run 'Command Prompt' as a administrator and execute C:\>echo "" > /"Program Files"/Git/bin/cygpath.exe
(kudos to hook is not working eclipse egit client).
Reboot.
A note on java import statements ordering
Optimise imports or reformat in IDE or reformat with plugins, can lead to changes in imports ordering. A nasty surprise if an older version of git-code-format-maven-plugin is being used together with fmt-maven-plugin (to format or validate code later in CI, for example).
- git-code-format-maven-plugin will sort imports (since version 1.20)
- fmt-maven-plugin will always sort imports
- googleformatter-maven-plugin can optionally sort imports (not per default)