How to instruct Spotless to ignore a code segment?

2.9k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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()
    }
}
0
On

You can try the following when using Spotless with Maven.

Step 1: Add the following in your mvn plugin under spotless

<plugins>
  <plugin>
     ...spotless config
    <configuration>
      <java>
        <toggleOffOn />
      ...
      </java>
    </configuration>
   </plugin>
  </plugins>

Step 2:

Add the following in your Java Code:

// spotless:off
   public void someMethod() {
     String str = "temp";
       str = "I want this unformatted";
    ....
   }
// spotless:on