Search code examples
formatspotless

How to instruct Spotless to ignore a code segment?


How can I instruct the Spotless code formatter to ignore a specific code section?

I wrote this Java code section:

String content = Joiner.on(System.lineSeparator()).join(
    "services:", 
    "- name: name", 
    "  image: artifacts-dev/image"
);

Spotless formats it to this:

String content =
        Joiner.on(System.lineSeparator())
            .join("services:", "- name: name", "  image: artifacts-dev/image");

I want to instruct Spotless to ignore (skip formatting) the above code segment.

How do I do that?


For comparison, the Prettier formatter can be instructed to ignore code segments by adding a comment:

// prettier-ignore

Is there a similar feature for Spotless?


Solution

  • Spotless can be turned off and on using the toggle comments, spotless:off and spotless:on. So the above code block could look like below:

    // spotless:off
    String content = Joiner.on(System.lineSeparator()).join(
        "services:", 
        "- name: name", 
        "  image: artifacts-dev/image"
    );
    // spotless:on
    

    For the spotless:off and spotless:on comments to take effect, the toggle needs to be enabled explicitly in the language-specific or custom config blocks. A minimal gradle config, with the toggle enabled for java is below:

    plugins {
        id 'com.diffplug.spotless' version '6.18.0'
    }
    
    spotless {
        java {
            eclipse()
            toggleOffOn()
        }
    }