java如何用Google Checkstyle规则和gradle编译项目?
我试图使用Google checkstyle配置(https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/google_checks.xml),但我经常在gradle check
上遇到错误:
Unable to create a Checker: cannot initialize module TreeWalker - Unable to instantiate EmptyCatchBlock
我用Gradle来做这个项目。下面是我的格拉德尔。建造
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'checkstyle'
sourceCompatibility = 1.8
version = '1.0'
checkstyle {
toolVersion = "6.3"
}
task "create-dirs" << {
sourceSets*.java.srcDirs*.each { it.mkdirs() }
sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}
jar {
manifest {
attributes 'Implementation-Title': 'xyz',
'Implementation-Version': 0.01
}
}
repositories {
mavenCentral()
}
dependencies {
compile (
['org.apache.logging.log4j:log4j-api:2.2'],
['org.apache.logging.log4j:log4j-core:2.2']
)
testCompile(
['junit:junit:4.11'],
['org.mockito:mockito-core:1.+']
)
}
test {
systemProperties 'property': 'value'
}
uploadArchives {
repositories {
flatDir {
dirs 'repos'
}
}
}
此外,当我尝试在IDEA中将XML配置文件添加到Checkstyle插件时,我会遇到类似的错误,但有一个堆栈跟踪:
org.infernus.idea.checkstyle.exception.CheckStylePluginException: <html><b>The CheckStyle rules file could not be loaded.</b><br>cannot initialize module TreeWalker - Unable to instantiate EmptyCatchBlock</html>
at org.infernus.idea.checkstyle.checker.CheckerFactory.blacklistAndShowMessage(CheckerFactory.java:234)
at org.infernus.idea.checkstyle.checker.CheckerFactory.createChecker(CheckerFactory.java:188)
at org.infernus.idea.checkstyle.checker.CheckerFactory.getOrCreateCachedChecker(CheckerFactory.java:98)
at org.infernus.idea.checkstyle.checker.CheckerFactory.getChecker(CheckerFactory.java:73)
at org.infernus.idea.checkstyle.checker.CheckerFactory.getChecker(CheckerFactory.java:41)
我不知道我做错了什么。任何帮助都将不胜感激。 渐变版本:2.2
# 1 楼答案
以下是一种适用于(目前)最新版本的Gradle&;Checkstyle(Gradle 6.1.1和Checkstyle 8.29):
请注意,Checkstyle依赖项不包括可传递依赖项,否则
resources.text.fromArchiveEntry
将失败,因为将存在多个JAR文件,并且它将无法选择单个JAR文件# 2 楼答案
问题在于,除了版本6.4-SNAPSHOT之外,
com.puppycrawl.tools.checkstyle.checks.blocks.EmptyCatchBlockCheck
确实添加到了checkstyle中。从checkstyle repository(pom.xml history)中可以看出,6.4版快照于2015年2月2日推出,而EmptyCatchBlockCheck
类于2015年2月18日创建Gradle仍然使用版本6.3,如下日志摘录所示:
所以根本就没有你想使用的类
根据docs,可以使用
checkstyleClasspath
属性指定checkstyle类路径——您可以尝试手动设置它我还准备了一个6.4-SNAPSHOT版本的演示,可以在here找到。Checkstyle jar是用
mvn clean package
构建的,源代码取自thisrepo