I'm looking for a way to force developers to use the same Java code formatting rules. My requirements are:
- Gradle integration
Task that checks if code is correctly formatted. This will be used on CI to cause a build failure if incorrectly formatted code is submitted
Task that fixes incorrectly formatted code (nice-to-have)
- IntelliJ integration
- Incorrectly formatted code can be fixed within the IDE via the "Reformat Code" action
- Code that is generated by the IDE (e.g. getter/setter generation) conforms to the rules
- Supports the OpenJDK/Oracle Java formatting rules
Currently I'm using Spotless with the following configuration
spotless {
java {
toggleOffOn()
eclipse().configFile("${project.rootDir}/tools/eclipse-java-formatter.xml")
indentWithSpaces()
removeUnusedImports()
}
}
For IntelliJ integration, I've installed the Eclipse Code Formatter plugin and configured it to use the same rules as Spotless.
This approach meets all of the requirements above except for 2.2 i.e. any code generated by IntelliJ must be reformatted before it conforms to the formatting rules. A further problem is that the imports seem to be arbitrarily reordered when code is reformatted. This generates a lot of spurious changes which makes pull requests more difficult to review.
Is there another approach (e.g. CheckStyle) that does not suffer from these shortcomings?