禁止来自CPD的C/C++代码警告

Arn*_*nen 7 c c++ pmd static-code-analysis cpd

我们使用PMD复制粘贴检测器(CPD)来分析我们的C和C++代码.但是,代码的一些部分非常相似,但有充分的理由,我们希望抑制这些部分的警告.

PMD CPD文档仅提及有关注释的内容,但这对我们的这些语言不起作用.

我怎样才能忽略特定部件的警告?

也许有评论吗?

[更新]我正在使用以下Groovy脚本来运行CPD:

@GrabResolver(name = 'jcenter', root = 'https://jcenter.bintray.com/')
@Grab('net.sourceforge.pmd:pmd-core:5.4.+')
@Grab('net.sourceforge.pmd:pmd-cpp:5.4.+')
import net.sourceforge.pmd.cpd.CPD
import net.sourceforge.pmd.cpd.CPDConfiguration
import java.util.regex.Pattern

def tokens = 60
def scanDirs = ['./path/to/scan', './scan/this/too']
def ignores = [
    './ignore/this/path',
    './this/must/be/ignored/too'
    ].collect({ it.replace('/', File.separator) })
def rootDir = new File('.')
def outputDir = new File('./reports/analysis/')

def filename_date_format = 'yyyyMMdd'
def encoding = System.getProperty('file.encoding')
def language_converter = new CPDConfiguration.LanguageConverter()
def config = new CPDConfiguration()
config.language = new CPDConfiguration.LanguageConverter().convert('c')
config.minimumTileSize = tokens
config.renderer = config.getRendererFromString 'xml', 'UTF-8'
config.skipBlocksPattern = '//DUPSTOP|//DUPSTART'
config.skipLexicalErrors = true
def cpd = new CPD(config)

scanDirs.each { path ->
    def dir = new File(path);
    dir.eachFileRecurse(groovy.io.FileType.FILES) {
        // Ignore file?
        def doIgnore = false
        ignores.each { ignore ->
            if(it.path.startsWith(ignore)) {
                doIgnore = true
            }
        }
        if(doIgnore) {
            return
        }

        // Other checks
        def lowerCaseName = it.name.toLowerCase()
        if(lowerCaseName.endsWith('.c') || lowerCaseName.endsWith('.cpp') || lowerCaseName.endsWith('.h')) {
            cpd.add it
        }
    }
}

cpd.go();

def duplicationFound = cpd.matches.hasNext()

def now = new Date().format(filename_date_format)
def outputFile = new File(outputDir.canonicalFile, "cpd_report_${now}.xml")
println "Saving report to ${outputFile.absolutePath}"

def absoluteRootDir = rootDir.canonicalPath
if(absoluteRootDir[-1] != File.separator) {
    absoluteRootDir += File.separator
}

outputFile.parentFile.mkdirs()
def xmlOutput = config.renderer.render(cpd.matches);
if(duplicationFound) {
  def filePattern = "(<file\\s+line=\"\\d+\"\\s+path=\")${Pattern.quote(absoluteRootDir)}([^\"]+\"\\s*/>)"
  xmlOutput = xmlOutput.replaceAll(filePattern, '$1$2')
} else {
  println 'No duplication found.'
}

outputFile.write xmlOutput
Run Code Online (Sandbox Code Playgroud)

Joh*_*nco 1

我知道这是一个大约 3 年前的问题,但为了完整性,CPD 开始在 Java 的 PMD 5.6.0(2017 年 4 月)中支持这一点,并且自 6.3.0(2018 年 4 月)以来,它已扩展到许多其他语言,例如C/C++。如今,几乎所有 CPD 支持的语言都允许基于评论的抑制。

基于评论的抑制的完整(当前)文档可在https://pmd.github.io/pmd-6.13.0/pmd_userdocs_cpd.html#suppression获取

值得注意的是,如果文件有注释// CPD-OFF,但没有匹配// CPD-ON,则所有内容都将被忽略,直到文件末尾。