阿里的開發規約插件是基於PMD進行的代碼檢測,並且已經有PMD的Gradle插件。html
參考gradle pmd插件的自定義規則的使用這文章後,剩下的問題就是如何把阿里制定的Rule也引進來。java
新建文件 etc/pmd/ruleset.xml,其內容以下:android
<?xml version="1.0"?> <ruleset name="Custom ruleset" xmlns="http://pmd.sourceforge.net/ruleset/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd"> <description> 自定義Rule set </description> <!-- 引入PMD制定的Rule, 來源於https://github.com/pmd/pmd/tree/master/pmd-java/src/main/resources/rulesets/java --> <rule ref="rulesets/java/android.xml"> <exclude name="CallSuperLast"/> </rule> <rule ref="rulesets/java/basic.xml"> <exclude name="CollapsibleIfStatements"/> </rule> <rule ref="rulesets/java/clone.xml"/> <rule ref="rulesets/java/finalizers.xml"/> <rule ref="rulesets/java/imports.xml"/> <rule ref="rulesets/java/javabeans.xml"/> <rule ref="rulesets/java/optimizations.xml"> <exclude name="LocalVariableCouldBeFinal"/> <exclude name="MethodArgumentCouldBeFinal"/> </rule> <rule ref="rulesets/java/sunsecure.xml"/> <rule ref="rulesets/java/unnecessary.xml"> <exclude name="UselessParentheses"/> </rule> <!-- 引入阿里的Rule, 來源於 https://github.com/alibaba/p3c/tree/master/p3c-pmd/src/main/resources/rulesets/java --> <rule ref="rulesets/java/ali-comment.xml"> </rule> <rule ref="rulesets/java/ali-concurrent.xml"> </rule> <rule ref="rulesets/java/ali-constant.xml"> </rule> <rule ref="rulesets/java/ali-exception.xml"> </rule> <rule ref="rulesets/java/ali-flowcontrol.xml"> </rule> <rule ref="rulesets/java/ali-naming.xml"> </rule> <rule ref="rulesets/java/ali-oop.xml"> </rule> <rule ref="rulesets/java/ali-orm.xml"> </rule> <rule ref="rulesets/java/ali-other.xml"> </rule> <rule ref="rulesets/java/ali-set.xml"> </rule> </ruleset>
從上面例子能夠看出,很是方便定製rule。甚至還能夠使用 exclude 標籤排隊不須要的rule。git
apply plugin: 'java' apply plugin: 'pmd' ext { p3cPmdVersion = "1.3.0" pmdVersion = '5.5.2' # 與p3c-pmd 中使用pmd的版本一致 } // PMD配置 pmd { toolVersion = pmdVersion // 避免使用比較舊的版本,須要指定pmd的版本 ignoreFailures = true ruleSetConfig = resources.text.fromFile("etc/pmd/ruleset.xml") } dependencies { pmd "com.alibaba.p3c:p3c-pmd:${p3cPmdVersion}" }
經過上面例子能夠看出,使用p3c-pmd,其實很簡單,只須要把其一些rule 導到ruleSetConfig 文件中便可。github
PMD插件提供了以下幾個任務:app
任務名稱 ...... 描述less
pmdMain ...... 檢查src/main/java下的代碼oop
pmdTest ...... 檢查src/main/test下的代碼單元測試
pmdSourceSet ...... 檢查給定範圍的代碼測試
check ...... 檢查源碼和單元測試代碼
執行下面命令:
gradle check
會將執行結果輸出到 build/reports/pmd目錄中的main.html、test.html等文件中。