javacheckstyle

Disable checkstyle Indentation for a certain token


I'm using clang-format with checkstyle in Java project and having an issue with Lambda indentation

Specifically - due to clang-format Java limitations in certain scenarios my lambdas are formatted as follows:

    IntStream.range(0, numberOfPartitions)
        .forEach(
            i
            -> this.flushConsumer.accept(  // <- Issue here
                eventList.stream().skip(i * partitionSize).limit(partitionSize).collect(Collectors.toSet())
            )
        );

In that case the indent is not inserted before the -> and that triggers checkstyle indentation error due to the configuration being:

<module name="Indentation">
    <property name="basicOffset" value="4"/>
    <property name="braceAdjustment" value="4"/>
    <property name="caseIndent" value="4"/>
    <property name="throwsIndent" value="4"/>
    <property name="lineWrappingIndentation" value="4"/>
    <property name="arrayInitIndent" value="4"/>
</module>

The issue is - according to Checkstyle docs there doesn't seem to be any valid way to suppress this error using LAMBDA token or regexp ignorePattern for <module name="Indentation">

The only way I found - is to have SuppressionCommentFilter, which makes it ugly to insert everywhere or write a custom checkstyle check, which is complicated and doesn't work with some code editors

Question: Is there any known way or at least a simple workaround to suppress the error in that case?


Solution

  • You can use SuppressionXpathFilter to suppress the violation reported by Indentation check for LAMBDA token:

    Suppression filter file (suppressions-ind.xml):

    <?xml version="1.0"?>
    <!DOCTYPE suppressions PUBLIC
            "-//Checkstyle//DTD SuppressionXpathFilter Experimental Configuration 1.2//EN"
            "https://checkstyle.org/dtds/suppressions_1_2_xpath_experimental.dtd">
    <suppressions>
        <suppress-xpath checks="Indentation" query="//LAMBDA"/>
    </suppressions>
    

    Checkstyle configuration (referencing the suppression file above):

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE module
      PUBLIC "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN" "https://checkstyle.org/dtds/configuration_1_3.dtd">
    <module name="Checker">
       <module name="TreeWalker">
          <module name="SuppressionXpathFilter">
            <property name="file" value="suppressions-ind.xml"/>
          </module>
          <module name="Indentation">
             <property name="basicOffset" value="4"/>
             <property name="braceAdjustment" value="4"/>
             <property name="caseIndent" value="4"/>
             <property name="throwsIndent" value="4"/>
             <property name="lineWrappingIndentation" value="4"/>
             <property name="arrayInitIndent" value="4"/>
          </module>
       </module>
    </module>