Spotless: google-java-format and indentation settings

Created on 17 Jul 2019  路  6Comments  路  Source: diffplug/spotless

We would like to use Google Java Format and still enforce 4 space indentation. Ideal way of doing this would be to use both googleJavaFormat("1.7") and indentWithSpaces(4) in the order and expect spotless to apply them in the given order and get the required result.

    java {
            removeUnusedImports()
            googleJavaFormat("1.7")
            indentWithSpaces(4)
            trimTrailingWhitespace()
            endWithNewline()
            paddedCell()
        }

Is there a way to enforce order of the execution of spotless to get the best of both?

question

Most helpful comment

I strongly recommend googleJavaFormat("1.7").aosp() over @nedtwigg's solution in this case because it is the official solution. :)

All 6 comments

The execution order is enforced, and they are running in the order that you expect. The problem is that indentWithSpaces() is simpler than you expect. It doesn't know anything about the grammar of your language, it just does a simple find-replace of leading tabs and turns them into spaces. To do what you want, you need to to turn google's 2-space indentation to tabs, then the tabs to 4-space indentation.

indentWithTabs(2)
indentWithSpaces(4)

See #317

Worth noting that Google Java Format indents with 4 spaces when set to AOSP style:
https://github.com/diffplug/spotless/tree/master/plugin-gradle#applying-to-java-source-with-google-java-format

I strongly recommend googleJavaFormat("1.7").aosp() over @nedtwigg's solution in this case because it is the official solution. :)

As this issue pops up in searches when trying to solve this for Java and Maven, I will paste the solution here as well. Similarly as said here for Gradle build:

indentWithTabs(2)
indentWithSpaces(4)

you can do the same with Maven:

    <java>
        <googleJavaFormat>
            <version>1.8</version>
            <style>GOOGLE</style>
        </googleJavaFormat>
        <indent>
            <tabs>true</tabs>
            <spacesPerTab>2</spacesPerTab>
        </indent>
        <indent>
            <spaces>true</spaces>
            <spacesPerTab>4</spacesPerTab>
        </indent>
    </java>

@varjoranta I still strongly recommend using "AOSP" mode over the solution you've proposed, as it's built into google-java-format. Have you tried that solution yet? If so, what problem does it give you?

I agree that it's better to use the AOSP style with 4 space indentation. I have also witnessed that some prefer using the Google style, which has some differences to AOSP, and not only two-space indentation. The continuation indent and annotation formatting (e.g. OpenAPI specs in annotations) have been couple of issues I know of.

Was this page helpful?
0 / 5 - 0 ratings