使用 Gradle 插件進行代碼分析
來自: http://www.codeceo.com/article/analysis-code-with-gradle.html
代碼分析在大多數項目中通常是作為最后一個步驟(如果做了的話)完成的。其通常難以配置及與現有代碼整合。
本文旨在勾勒出使用 Gradle 整合 PMD 與 FindBugs 的步驟,并將其與一個現有的 Sonar 構建工具進行整合。
PMD、CheckStyle 和 FindBugs
首先要做的就是在我們的 build.gradle 文件中添加插件:
apply plugin: 'checkstyle' apply plugin: 'pmd' apply plugin: 'findbugs'
這些插件能在我們的代碼中啟用 PMD、CheckStyle 和 FindBugs。
默認情況下,這些插件將對測試程序和主程序都進行分析。對于我們,需要避免在測試程序上運行FindBugs和PMD,我們使用如下命令:
findbugs{ findbugsTest.enabled=false } pmd { pmdTest.enabled=false }
下面,我們從Gradle中執行:
./gradlew clean findBugsMain pmdMain
這將對工程進行清理,然后對源代碼執行FindBugs和PMD。
輸出結果如下:
:clean :compileJava Note: Some input files use unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. :processResources :classes :findbugsMain FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':findbugsMain'. > FindBugs rule violations were found. See the report at: file:///myprojects/build/reports/findbugs/main.xml * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. BUILD FAILED Total time: 24.597 secs
由于違背FindBugs規則,還沒運行PMD構建已經失敗。FindBugs和PMD的輸出格式為XML。
結果報告保存在<proj_home>/build/reports文件夾。
為了生成可讀的HTML文檔并忽略錯誤繼續構建,我們在build.gradle文件中加入:
findbugs{ ignoreFailures=true findbugsTest.enabled=false } tasks.withType(FindBugs) { reports { xml.enabled = false html.enabled = true } } tasks.withType(Pmd){ reports{ xml.enabled=true html.enabled=true } } pmd { ignoreFailures = true pmdTest.enabled=false }
task.withType用于對每種任務進行配置,您可以對PMD啟用HTML和XML報告,對FindBugs啟用HTML報告。
注意:在輸出報告時,FindBugs僅支持一種可用的輸出格式。
./gradlew clean findBugsMain pmdMain :clean :compileJava Note: Some input files use unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. :processResources :classes :findbugsMain FindBugs rule violations were found. See the report at: file:///myprojects/build/reports/findbugs/main.html :pmdMain Removed misconfigured rule: LoosePackageCoupling cause: No packages or classes specified Removed misconfigured rule: LoosePackageCoupling cause: No packages or classes specified 174 PMD rule violations were found. See the report at: file:///myprojects/build/reports/pmd/main.html BUILD SUCCESSFUL Total time: 6.013 secs
對于PMD,您可以使用ruleSet選項設置規則集。下面是一些常用的規則集。
pmd { ignoreFailures = true pmdTest.enabled=false ruleSets = [ 'java-basic', 'java-braces', 'java-clone', 'java-codesize', 'java-comments', 'java-controversial', 'java-coupling', 'java-design', 'java-empty', 'java-finalizers', 'java-imports', 'java-optimizations', 'java-strictexception', 'java-strings', 'java-typeresolution', 'java-unnecessary', 'java-unusedcode' ] }
一個輸出示例如下:
與Sonar整合
PMD,Checkstyle和Sonar都是很有用的工具。但是,從一個組織的角度,我們需要追蹤項目代碼質量的變化和一段時間內的技術債務。我們需要能夠對照其它類似的團隊。
為了能夠做到這些,我們使用Sonar。本文假設您已經安裝好了Sonar。
對于這種情況,Altassian提供了相應的Sonar插件。為了使用它,我們需要添加必要的插件。
buildscript { repositories { mavenCentral() maven { url "http://mvnrepo.nordstrom.net/nexus/content/groups/public" } maven { url "http://repo.maven.apache.org/maven2" } } dependencies { classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:1.2" } }
構建腳本安裝完畢,我們隊sonarqube進行配置:
apply plugin: "org.sonarqube" sonarqube{ check properties { // Sonar Specific properties property 'sonar.projectName', 'Project Services' // This is the display project name property 'sonar.host.url','http://sonar:8080/' // This is the Sonar Server property 'sonar.projectKey', 'com.wordpress.mrvivekr:project' // The Key using which the project details are tracked // JDBC Properties property 'sonar.jdbc.url','jdbc:jtds:sqlserver://ABCD:1433/SonarDB;domain=MYCOMP;SelectMethod=Cursor' property 'sonar.jdbc.username','userName' property 'sonar.jdbc.password','Secr#%' //Which Sonar Profile to use - this is optional property 'sonar.profile','JavaProfile' } }
注意:sonar.profile是預配置sonar配置(和規則),應由您的公司預先配置完成。但這是可選而非必須。我的JDBC連接使用SQLServer連接。
./gradlew sonarqube
:compileJava UP-TO-DATE :processResources UP-TO-DATE :classes UP-TO-DATE :compileTestJava :processTestResources :testClasses :test ....... ommitted ..... 11:27:36.713 INFO - Java Main Files AST scan done: 812 ms 11:27:36.714 INFO - 13/13 source files have been analyzed 11:27:36.715 INFO - Java bytecode scan... 11:27:36.762 INFO - Java bytecode scan done: 47 ms 11:27:36.762 INFO - Java Test Files AST scan... 11:27:36.762 INFO - 5 source files to be analyzed 11:27:36.885 INFO - Java Test Files AST scan done: 123 ms 11:27:36.885 INFO - 5/5 source files have been analyzed 11:27:36.888 INFO - Package design analysis... 11:27:39.868 INFO - Package design analysis done: 2980 ms 11:27:39.884 INFO - Sensor JavaSquidSensor (done) | time=4307ms 11:27:39.884 INFO - Sensor Lines Sensor 11:27:39.888 INFO - Sensor Lines Sensor (done) | time=4ms 11:27:39.888 INFO - Sensor QProfileSensor 11:27:39.891 INFO - Sensor QProfileSensor (done) | time=3ms 11:27:39.891 INFO - Sensor InitialOpenIssuesSensor 11:27:45.592 INFO - Sensor InitialOpenIssuesSensor (done) | time=5701ms 11:27:45.592 INFO - Sensor ProjectLinksSensor 11:27:45.730 INFO - Sensor ProjectLinksSensor (done) | time=138ms 11:27:45.730 INFO - Sensor VersionEventsSensor 11:27:47.690 INFO - Sensor VersionEventsSensor (done) | time=1960ms 11:27:47.690 INFO - Sensor org.sonar.plugins.findbugs.FindbugsSensor@7894f007 11:27:47.694 INFO - Execute Findbugs 3.0.1... 11:27:48.557 INFO - Found findbugs plugin: /myprojects/build/sonar/findbugs/fb-contrib.jar 11:27:48.596 INFO - Found findbugs plugin: /myprojects/build/sonar/findbugs/findsecbugs-plugin.jar 11:27:48.612 INFO - Findbugs output report: /myprojects/build/sonar/findbugs-result.xml The following classes needed for analysis were missing: javax.crypto.spec.SecretKeySpec 11:27:50.846 INFO - Execute Findbugs 3.0.1 done: 3153 ms 11:29:31.499 INFO - Sensor org.sonar.plugins.findbugs.FindbugsSensor@7894f007 (done) | time=103809ms 11:29:31.499 INFO - Sensor SurefireSensor 11:29:31.500 INFO - parsing /myprojects/build/test-results 11:29:31.558 INFO - Sensor SurefireSensor (done) | time=59ms 11:29:31.558 INFO - Sensor JaCoCoOverallSensor 11:29:31.565 WARN - You are not using the latest JaCoCo binary format version, please consider upgrading to latest JaCoCo version. 11:29:31.565 INFO - Analysing /myprojects/build/jacoco/test.exec 11:29:31.601 WARN - You are not using the latest JaCoCo binary format version, please consider upgrading to latest JaCoCo version. ......... Ommitted ............. 11:30:38.654 INFO - ANALYSIS SUCCESSFUL, you can browse http://sonar:8080/dashboard/index/com.wordpress.mrvivekr:project 11:30:38.654 INFO - Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report. 11:30:38.655 INFO - Executing post-job class org.sonar.plugins.buildbreaker.AlertBreaker 11:30:38.657 INFO - Executing post-job class org.sonar.plugins.buildbreaker.ForbiddenConfigurationBreaker BUILD SUCCESSFUL Total time: 5 mins 16.499 secs
您應該看到類似的輸出:
享受代碼分析吧!