How to instruct Spotless to ignore a code segment?
Asked Answered
F

2

6

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?

Fauve answered 26/2, 2023 at 8:23 Comment(0)
L
6

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()
    }
}
Ledford answered 10/5, 2023 at 19:3 Comment(0)
O
1

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 
Oleviaolfaction answered 24/6, 2023 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.