Checkstyle 外掛使用 Checkstyle 對專案的 Java 原始檔執行品質檢查,並從這些檢查產生報告。
用法
若要使用 Checkstyle 外掛,請在建置指令碼中包含下列內容
plugins {
checkstyle
}
plugins {
id 'checkstyle'
}
外掛會新增多項工作到專案,以執行品質檢查。您可以執行 gradle check
來執行檢查。
請注意,Checkstyle 會使用與執行 Gradle 相同的 Java 版本執行。
工作
Checkstyle 外掛會新增下列工作到專案
checkstyleMain
— Checkstyle-
相依於:
classes
針對製作用 Java 原始檔執行 Checkstyle。
checkstyleTest
— Checkstyle-
相依於:
testClasses
對測試 Java 原始檔執行 Checkstyle。
checkstyleSourceSet
— Checkstyle-
依賴於:
sourceSetClasses
對指定原始檔組的 Java 原始檔執行 Checkstyle。
新增至其他任務的依賴關係
Checkstyle 外掛會將下列依賴關係新增至 Java 外掛定義的任務。
check
-
依賴於: 所有 Checkstyle 任務,包括
checkstyleMain
和checkstyleTest
。
專案配置
預設情況下,Checkstyle 外掛預期組態檔會放置在根目錄專案中,但可以變更此設定。
<root> └── config └── checkstyle (1) └── checkstyle.xml (2) └── suppressions.xml
1 | Checkstyle 組態檔放置於此處 |
2 | 主要 Checkstyle 組態檔 |
相依性管理
Checkstyle 外掛會新增下列相依性組態
名稱 | 意義 |
---|---|
|
要使用的 Checkstyle 函式庫 |
預設情況下,checkstyle
組態會使用 com.puppycrawl.tools:checkstyle
。com.puppycrawl.tools:checkstyle
所使用的版本會從延伸模組的工具版本中衍生而來
checkstyle {
toolVersion = "10.12.4"
}
如果新增其他相依性,預設的 com.puppycrawl.tools:checkstyle
相依性會被移除
checkstyle {
toolVersion = "10.12.4"
}
dependencies {
checkstyle "group:artifact:version"
}
若要將相依性新增至 checkstyle
組態,同時保留對 com.puppycrawl.tools:checkstyle
的相依性,請使用下列解決方案
checkstyle {
toolVersion = "10.12.4"
}
dependencies {
checkstyle "com.puppycrawl.tools:checkstyle:${checkstyle.toolVersion}"
checkstyle "group:artifact:version"
}
組態
請參閱 API 文件中的 CheckstyleExtension 類別。
內建變數
Checkstyle 外掛會定義一個 config_loc
屬性,可以在 Checkstyle 組態檔中使用此屬性來定義其他組態檔(例如 suppressions.xml
)的路徑。
<module name="SuppressionFilter">
<property name="file" value="${config_loc}/suppressions.xml"/>
</module>
自訂 HTML 報告
由 Checkstyle 任務產生的 HTML 報告可以使用 XSLT 樣式表自訂,例如用來突顯特定錯誤或變更其外觀
tasks.withType<Checkstyle>().configureEach {
reports {
xml.required = false
html.required = true
html.stylesheet = resources.text.fromFile("config/xsl/checkstyle-custom.xsl")
}
}
tasks.withType(Checkstyle) {
reports {
xml.required = false
html.required = true
html.stylesheet resources.text.fromFile('config/xsl/checkstyle-custom.xsl')
}
}
產生 SARIF 報告
SARIF 報告支援 Checkstyle 版本 10.3.3 及更新版本。預設未啟用。
checkstyle {
toolVersion = "10.3.3"
}
tasks.withType<Checkstyle>().configureEach {
reports {
sarif.required = true
}
}
checkstyle {
toolVersion = '10.3.3'
}
tasks.withType(Checkstyle) {
reports {
sarif.required = true
}
}
變更提供給 Checkstyle 的記憶體量
Checkstyle 分析在個別程序中執行。預設情況下,Checkstyle 程序會獲得 512MB 的最大堆積。分析許多原始檔時,您可能需要提供額外的記憶體給這個程序。您可以透過設定 Checkstyle.maxHeapSize 來變更提供給 Checkstyle 的記憶體量。
tasks.withType<Checkstyle>().configureEach {
minHeapSize = "200m"
maxHeapSize = "1g"
}
tasks.withType(Checkstyle) {
minHeapSize = "200m"
maxHeapSize = "1g"
}