开发者

PMD/CPD: Ignore bits of code using comments

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&l开发者_C百科t;/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>


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.


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.


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>


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"})

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜