PMD/CPD: Ignore bits of code using comments

33.2k views Asked by At

Is there a way to tell PMD to ignore checking parts of code for duplication?

For example, can I do something like this:

// CPD-Ignore-On
...
// CPD-Ignore-Off

Currently I have PMD set up like this using Maven, but don't see any arguments that would like me do what I want unless I am missing something.

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-pmd-plugin</artifactId>
            <version>2.5</version>
            <configuration>
                <minimumTokens>40</minimumTokens>
                <targetJdk>1.5</targetJdk>
                <ignoreIdentifiers>true</ignoreIdentifiers>
                <ignoreLiterals>true</ignoreLiterals>
            </configuration>
        </plugin>
4

There are 4 answers

4
Avik On

After digging around enough, I finally came across it.

By adding the annotations @SuppressWarnings("CPD-START") and @SuppressWarnings("CPD-END") all code within will be ignored by CPD - thus you can avoid false positives.

Source - http://pmd.sourceforge.net/pmd-5.0.5/cpd-usage.html.

0
kamuflage661 On

I found it possible only to disable a whole class check in maven-pmd-plugin configuration in project pom. It is performed by adding <excludes> tag. If you would like to do it, your conf should be like this:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-pmd-plugin</artifactId>
    <version>2.5</version>
    <configuration>
        <minimumTokens>40</minimumTokens>
        <targetJdk>1.5</targetJdk>
        <ignoreIdentifiers>true</ignoreIdentifiers>
        <ignoreLiterals>true</ignoreLiterals>
        <excludes>
            <exclude>**/YourClassName.java</exclude>
            ........
            <exclude>....</exclude>
        </excludes>
    </configuration>
</plugin>
0
Johnco On

I know this is a 8 years old question, but for completeness, CPD does support this since PMD 5.6.0 (April 2017).

The complete (current) docs for comment-based suppression are available at https://pmd.github.io/pmd-6.13.0/pmd_userdocs_cpd.html#suppression

It's worth noting, if a file has a // CPD-OFF comment, but no matching // CPD-ON, everything will be ignored until the end of file.

0
chris On

Is there a way to tell PMD to ignore checking parts of code for duplication?

For duplication, you have 3 options:

  1. You can use @SuppressWarnings("CPD-START") and @SuppressWarnings("CPD-END") around the code you want to skip.

  2. If you want to ignore a file from a specific line til EOF, using @SuppressWarnings("CPD-START") alone is enough.

  3. And if you already have Suppressing annotations you can add CPD-START as explained in the docs, i.e. @SuppressWarnings({"PMD", "CPD-START"})