End

代码检测工具 PMD 插件

本文地址


目录

代码检测工具 PMD 插件

PMD 简介

PMD is a static source code analyzer. It finds common programming flaws 编程缺陷 like unused variables, empty catch blocks, unnecessary object creation, and so forth. It’s mainly concerned with Java and Apex, but supports six other languages.

PMD features many built-in checks (in PMD lingo 术语, rules), which are documented for each language in our Rule references. We also support an extensive 广泛 API to write your own rules, which you can do either in Java or as a self-contained 独立的 XPath query.

PMD is most useful when integrated into your build process. It can then be used as a quality gate 质量门, to enforce 强制 a coding standard for your codebase. Among other things, PMD can be run:

AS 插件 PMDPlugin

简介

PMD Plugin integrates PMD to intelliJ. It supports all the pre defined rulesets as well as custom rulesets. The user can run pmd on a single or set of files/folders and see the results in intelliJ. To run the predefined rulesets, go to Tools -> PMD -> PreDefined menu. PMD supports custom ruleset file, to configure goto settings -> PMD and add the rule set files that are required.

插件使用

  • 在代码编辑框或 Project 窗口的文件夹、包、文件右键,选择Run PMD => Pre Defined => All,可使用默认规则对指定的文件夹、包、文件进行分析
  • 可在 Setting -> PMD -> RuleSets 中引入自己定义的规则,并在后面使用此规则进行分析

检查项为:

  • all 全部检查
  • bestpractices 最佳实践
  • codeStyle 代码风格
  • design 设计
  • documentation 文档
  • errorprone 容易出错
  • multithreading 多线程
  • performance 性能

检查结果案例

检查完会在左下角 PMD 标签页展示检查结果

工具栏图标功能:

  • 重新运行PMD再次分析文件
  • 关闭PMD展示页面
  • 收缩结果集
  • 展开结果集
  • 在结果集中移动到下一个结果项
  • 在结果集中移动到上一个结果项
  • 点击结果集中某一个结果项跳转到Java代码
  • 将结果集导出到文件中

gradle 插件

The PMD plugin performs quality checks on your project’s Java source files using PMD and generates reports from these checks.

相关文档:

插件源码

插件相关源码:

Tips:

  • gradle 中使用的 pmd 插件实际定义在 plugins/quality 包中
  • 当前 gradle 使用的默认 PMD 版本为:6.20.0

配置选项

gradle 中的 PMD 插件可以使用的配置选项有:

  • ruleSetFiles:使用自定义规则集文件(如果只想使用ruleSetFiles,则必须清除ruleSets)
  • ruleSets:使用自定义规则集。将ruleSets数组设置为空,以避免使用默认配置
  • ignoreFailures:有警告时是否允许构建继续进行
  • consoleOutput:是否将结果写入标准输出中,设为true时可以通过点击链接快速定位到问题代码位置
  • incrementalAnalysis:是否使用增量分析。仅 PMD 6.0.0 或更高版本支持此功能
  • rulePriority:规则优先级阈值;不会报告优先级较低的规则的违反情况。默认值为5,这表示将报告所有违规情况 (这个属性有bug,不建议使用。后续会被rulesMinimumPriority替换)
  • targetJdk:与PMD一起使用的目标JDK
  • ruleSetConfig:要使用的自定义规则集(如果有)。替换ruleSetFiles,但当前不支持多个规则集
  • pmdClasspath:包含要使用的PMD库的类路径
  • maxFailures:停止构建之前允许的最大失败数(ignoreFailures为false时有效)。默认值为0,这将在任何失败时停止构建
  • reports:生成的报告文件存放位置
    • reports.html.enabled:生成xml还是html,只能有一个为true
    • reports.xml.enabled
    • reports.html.destination:对应的输出地址
    • reports.xml.destination

从父类继承过来的选项有:

  • source:需要进行代码检测的源码路径
  • include:需要检查的文件。可以多次调用此方法以追加新的规范
  • exclude:忽略检查的文件。可以多次调用此方法以追加新的规范

最佳集成案例

在 app 的build.gradle增加如下代码:

plugins {
    id 'com.android.application'
    id 'pmd'
}

pmd {
    toolVersion = "6.21.0" //使用指定的PMD版本,当前 gradle 使用的默认版本为 6.20.0
}
def ruleFilePath = "${project.rootDir}/codeCheck/" //检查规则文件路径
def sourcePath = "${project.rootDir}/app/src"  //需要进行代码检测的源码路径
def reportFilePath = "${project.rootDir}/codeCheck/reports/" //生成的报告文件存放位置

task pmd(type: Pmd, group: "codeCheck") {
    ruleSetFiles = files(ruleFilePath + "pmd_rule.xml") //使用自定义规则集文件
    ruleSets = [] //使用自定义规则集(如果只想使用ruleSetFiles,则必须清除ruleSets)
    ignoreFailures = true //有警告时是否允许构建继续进行
    source = files(sourcePath) //需要进行代码检测的源码路径
    consoleOutput = true //是否将结果写入标准输出中,设为true时可以通过点击链接快速定位到问题代码位置
    include '**/*.java' //需要检查的文件
    exclude '**/*.xml' //忽略检查的文件

    reports {
        xml.enabled = false //生成xml还是html,只能有一个为true
        html.enabled = true
        xml.destination = file(reportFilePath + "pmd_result.xml") //对应的生成的报告文件存放位置
        html.destination = file(reportFilePath + "pmd_result.html")
    }
}

检测结果案例

点击之后会显示相关解释,例如:unusedlocalvariable


Since: PMD 0.1

Priority: Medium (3)

Detects when a local variable is declared and/or assigned, but not used.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.UnusedLocalVariableRule

Example(s):

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/UnusedLocalVariable" />

Jenkins 插件

Jenkins 上有两款支持 pmd 的插件:

  • Report Info:同时支持 Surefire, PMD, Findbugs and Checkstyle
  • Violations:下载量最大,但是因不再维护(5年没有更新了)所以不建议使用

This plugin allows you to see in a view some information from Surefire, PMD, Findbugs and Checkstyle reports.

Usage

In the jobs you want in the report info view, add Generated report info Post-build action.

You can add some folders to exclude.

Create a new Report Info view

Add the projects you want to see in the view

Now you need the rebuild the job to see the report information.

How PMD Works

How PMD Works

  • 解析命令行参数,并且加载增量分析缓存文件(incremental analysis cache file)
  • 加载规则集/规则(rulesets/rules)
  • 确定语言 -- 规则集中可能混合了不同语言的规则
  • 确定文件 -- 使用给定的 source 目录,按语言的文件扩展名(file extensions)过滤
  • 准备渲染器
  • 按名称对文件排序
  • 检查我们是否可以使用增量分析缓存(如果规则集更改,它将无效)
  • 根据配置准备 SourceCodeProcessor
  • 分析文件。单线程或多线程并行
    • 创建输入流
    • 调用源代码处理器
      • 确定语言
      • 检查文件是否已经被分析,并且分析缓存中提供了结果
      • 解析源代码。结果是根AST节点。
      • 始终运行 SymbolFacade visitor。它建立作用域,查找声明和用法。
      • 运行 DFA(data flow 分析)visitor(如果至少需要一条规则),以构建控制流程图和数据流节点。
      • 运行 TypeResolution visitor(如果至少有一条规则要求它)
      • 未来:运行多文件分析(如果至少一项规则要求这样做)
      • 执行规则:
        • 首先运行为规则链机制选择的规则
        • 运行所有其他规则,并让它们遍历AST。规则可以使用符号表,类型解析信息和DFA节点。
        • 规则会将发现的问题报告为 RuleViolations。
  • 将找到的违规呈现为所需的格式(XML,文本,HTML等)
  • 存储增量分析缓存
  • 根据发现的违规次数,以代码0或4退出。

Java Rules

Java Rules

  • Best Practices:Rules which enforce generally accepted best practices. 实施公认的最佳实践
  • Code Style:Rules which enforce a specific coding style. 实施特定代码样式
  • Design:Rules that help you discover design issues. 发现设计问题
  • Documentation:Rules that are related to code documentation. 与代码文档相关的规则
  • Error Prone:Rules to detect 检测 constructs that are either broken 损坏, extremely confusing 极度混乱 or prone 容易 to runtime errors.
  • Multithreading:Rules that flag issues when dealing with multiple threads of execution. 执行多线程时标记问题
  • Performance:Rules that flag suboptimal code. 标记次优代码
  • Security:Rules that flag potential security flaws. 标记潜在安全缺陷
  • Additional rulesets:附加规则集

2017-05-23

posted @ 2017-05-23 13:47  白乾涛  阅读(6146)  评论(0编辑  收藏  举报