欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

静态代码自动扫描p3c的使用

时间:2023-07-03

当一家公司上了一定的规模,项目越来越多,代码也越来越庞大,然后就是各种五花八门的代码格式、代码规范,通过主程们code review 耗时耗力,很多主程也缺少主观能动性和精力去cover code review这事项,如果有东西能自动化去检查团队成员的编码规范,这样就可以大大的提高代码质量,也可以让核心人员从code review 中解脱出来,本文提到的P3C-PMD就是这种神器。

p3c-pmd是静态代码自动扫描框架,规则是基于pmd规则上修改而来,可以直接参考pmd与jekins集成文档,将规则包换成p3c的包就可以,集成在sonar或gradle或jekins及在线扫描,在流水线上做个定时任务,每天定时扫描,同时它也支持自定义规则,让团队根据自身的需求。

类似的神器还有腾讯的codecc等。

P3C的git仓库如下:
https://github.com/alibaba/p3c/

下面简单说说使用:

1.使用三种方式
1.1、Eclipse plugin
1.2、IDEA plugin
1.3、命令行扫描

2 规范
规范符合阿里 JAVA代码规范,大的54种大的规则和一系列的小规则,请参考:Java开发手册(黄山版).pdf

规则集

3.如何自定义规则
1.如何新增规范(命令行):
如何提示System.currentTimeMillis() 的禁用?

Summary Rule nameNumber of violationsAvoidCallSystemCurrentTimeMillisRule1PMD report Problems found FileLineProblemjava/com/yorha/game/controller/UserController.java45

核心类:AvoidCallSystemCurrentTimeMillisRule.java

public class AvoidCallSystemCurrentTimeMillisRule extends AbstractXpathRule { private static final String XPATH = "//PrimaryPrefix/Name[@Image='System.currentTimeMillis']"; public AvoidCallSystemCurrentTimeMillisRule() { setXPath(XPATH); } @Override public void addViolation(Object data, Node node, String arg) { ViolationUtils.addViolationWithPrecisePosition(this, node, data, I18nResources.getMessage("java.extend.AvoidCallSystemCurrentTimeMillisRule.violation.msg")); }}

国际化
messages.xml

messages_en.xml

rulesets/ali-extend.xml

<?xml version="1.0"?> AlibabaJavaExtends java.extend.AvoidCallSystemCurrentTimeMillisRule.rule.desc 1

4.如何屏蔽规范:
在命令行中,可以根据优先级屏蔽部分规则,根据你需要的加入ruleset白名单黑名单规则

5.如何启动

java -server -jar $PWD/p3c-pmd-2.1.1.jar -d ../../../proj/yorha-game/src/main -f summaryhtml -cache cache.log -shortnames -R rulesets/java/ali-exception.xml,rulesets/java/ali-oop.xml,rulesets/java/ali-flowcontrol.xml,rulesets/java/ali-naming.xml,rulesets/java/ali-extend.xml -r /home/cnc_build/pmd/report.html -encoding UTF-8 > p3c.log 2>&1 &

具体使用选项说明如下:

Usage: pmd [options] Options: -failOnViolation, --failonViolation By default PMD exits with status 4 if violations are found、Disable this option with '-failonViolation false' to exit with 0 instead and just write the report. Default: true -auxclasspath Specifies the classpath for libraries used by the source code、This is used by the type resolution、Alternatively, a 'file://' URL to a text file containing path elements on consecutive lines can be specified. -benchmark, -b Benchmark mode - output a benchmark report upon completion; default to System.err. Default: false -cache Specify the location of the cache file for incremental analysis、This should be the full path to the file, including the desired file name (not just the parent directory)、If the file doesnt exist, it will be created on the first run、The file will be overwritten on each run with the most up-to-date rule violations. -dir, -d Root directory for sources. -encoding, -e Specifies the character set encoding of the source code files PMD is reading (i.e., UTF-8). Default: UTF-8 -filelist Path to a file containing a list of files to analyze. -format, -f Report format type. Default: text -help, -h, -H Display help on usage. -ignorelist Path to a file containing a list of files to ignore. -language, -l Specify a language PMD should use. -minimumpriority, -min Rule priority threshold; rules with lower priority than configured here won.t be used、Valid values are integers between 1 and 5 (inclusive), with 5 being the lowest priority. Default: 5 -no-cache Explicitly disable incremental analysis、The '-cache' option is ignored if this switch is present in the command line. Default: false -norulesetcompatibility Disable the ruleset compatibility filter、The filter is active by default and tries automatically 'fix' old ruleset files with old rule names Default: false -property, -P {name}={value}: Define a property for the report format. Default: [] -reportfile, -r Sends report output to a file; default to System.out. * -rulesets, -R Comma separated list of ruleset names to use. -shortnames Prints shortened filenames in the report. Default: false -showsuppressed Report should show suppressed rule violations. Default: false -stress, -S Performs a stress test. Default: false -suppressmarker Specifies the string that marks a line which PMD should ignore; default is NOPMD. Default: NOPMD -threads, -t Sets the number of threads used by PMD. Default: 1 -uri, -u Database URI for sources. -debug, -verbose, -D, -V Debug mode. Default: false -version, -v Specify version of a language PMD should use.

5.静态扫描流水线
拉取最新代码—>每日定时扫描—>生成报表—>发送链接到企业微信群

Summary Rule nameNumber of violationsAbstractClassShouldStartWithAbstractNamingRule20ClassNamingShouldBeCamelRule11AvoidComplexConditionRule7AvoidStartWithDollarAndUnderLineNamingRule1PojoMustOverrideToStringRule1SwitchStatementRule2LowerCamelCaseVariableNamingRule64EqualsAvoidNullRule3AvoidCallSystemCurrentTimeMillisRule1ConstantFieldShouldBeUpperCaseRule13PackageNamingRule67PojoMustUsePrimitiveFieldRule6 #FileLineProblem1java/com/yorha/game/controller/IOController.java19【IOController】不符合UpperCamelCase命名风格2java/com/yorha/game/controller/UserController.java45请使用SystemClock.now()代替System.currentTimeMillis()3java/com/yorha/game/db/GameTcaplusManager.java253变量名【ScenePlayerId】不符合lowerCamelCase命名风格4java/com/yorha/game/db/GameTcaplusManager.java410变量名【ClanId】不符合lowerCamelCase命名风格5java/com/yorha/game/db/GameTcaplusManager.java424变量名【ClanId】不符合lowerCamelCase命名风格6java/com/yorha/game/db/GameTcaplusManager.java459变量名【ClanId】不符合lowerCamelCase命名风格7java/com/yorha/game/db/GameTcaplusManager.java489方法名【getPlayerEntityDBX】不符合lowerCamelCase命名风格

P3C和CodeCC的比较

名称P3CCodeCC便利性需要自行打包,配置规则和命令行很方便,直接界面操作使用界面友好性只有明细,没有界面能看到综合信息默认扫描规则默认54条规则默认51条针对JAVA的规则,如要其他规则,还可以从627条备用规则里去选自定义规则支持扩展 ,但要学习XPATH的语法当前版本暂不支持「自定义规则的添加」,相关功能在排期开发中蓝盾流水线整合很方便通过添加插件的方式,不支持私有构建机,可使用Docker公共构建机执行插件报表明细只能看到某一行出现了代码问题,但不能定位到责任人是谁能定位到问题,责任人,以及代码质量的发展和修复趋势,还可以跟进问题的状态及评论过滤规则通过去掉rule配置通过页面勾选

总结
总之,项目越来越大,团队越来越大,代码越来越来多,然后就是各种五花八门的代码格式、代码规范。通过阿里P3C-PMD配合Gitlab做编码规范检查,可以大大提升团队代码质量。

扩展阿里p3c实现自定义代码规范检查

扩展ALIBABA P3C 实现自定义代码规范检查

扩展阿里p3c实现自定义代码规范检查

Java P3C自定义规则

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。