我一直在尝试为 Sonarqube ~5.4 编写一个自定义规则插件,虽然我已经实现并运行了一些规则,但那些依赖于标准库之外的类型的规则依赖于各种杂技字符串匹配。
我正在使用sonar-packaging-maven-plugin
来进行包装:
<plugin>
<groupId>org.sonarsource.sonar-packaging-maven-plugin</groupId>
<artifactId>sonar-packaging-maven-plugin</artifactId>
<version>1.16</version>
<configuration>
<pluginClass>${project.groupId}.sonar.BravuraRulesPlugin</pluginClass>
<pluginKey>SonarPluginBravura</pluginKey>
<skipDependenciesPackaging>false</skipDependenciesPackaging>
<basePlugin>java</basePlugin>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>sonar-plugin</goal>
</goals>
</execution>
</executions>
</plugin>
并且正在使用以下帮助程序扩展(kotlin)运行各种检查:
fun <T : JavaFileScanner> T.verify() {
val workDir = System.getProperty("user.dir");
val folder = Paths.get(workDir, "src/test/samples", this.javaClass.simpleName);
Files.list(folder).forEach { sample ->
try {
if (sample.toString().endsWith(".clean.java")) {
JavaCheckVerifier.verifyNoIssue(sample.toString(), this);
} else {
JavaCheckVerifier.verify(sample.toString(), this);
}
} catch (error: Exception) {
throw VerificationFailedException(sample, error);
}
}
};
class VerificationFailedException(path: Path, error: Exception)
: Exception("Failed to verify $path.", error);
我为规则创建了一个IssuableSubscriptionVisitor
子类,然后访问Tree.Kind.METHOD_INVOCATION
,寻找传递给AutoLongColumn
. 这是为了停止将标识符字段用于订购目的。
不幸的是,即使我在 maven 'test' 类路径上有必要的库,当我尝试获取任何类型时,它们只会显示为!unknown!
.
override fun visitNode(tree: Tree) {
if (tree !is MethodInvocationTree) {
return;
}
val methodSelect = tree.methodSelect();
if (methodSelect !is IdentifierTree || methodSelect.name() !in setOf("MAX", "MIN", "ASC", "DESC")) {
return;
}
val firstArg = statement.arguments().first();
if (firstArg !is MethodInvocationTree) {
return;
}
val firstArgSelect = firstArg.methodSelect();
if (firstArgSelect !is MemberSelectExpressionTree) {
return;
}
if (firstArgSelect.type is UnknownType) {
throw TableFlipException("(ノಥ益ಥ)ノ ┻━┻");
}
// It never gets here.
}
我确定我错过了拼图中的一些重要部分,如果有人能告诉我哪里出错了,我将不胜感激。
编辑:我正在使用org.sonarsource.java:sonar-java-plugin:3.14
分析器,虽然我不能发布分析目标的所有代码(商业 IP 和所有这些),但这里有一些与关键部分在结构上相同的东西:
import static com.library.UtilClass.MAX;
...
query.SELECT(biggestId = MAX(address._id())) // Noncompliant
.FROM(address)
.WHERE(address.user_id().EQ(userId)
.AND(address.type_id().EQ(typeId)));
...
的类型address.id()
是com.library.Identifier
一个长包装。我希望能够访问所有方法调用,检查它们是否匹配com.library.UtilCLass.MAX
,如果匹配,请确保第一个参数不是com.library.Identifier
. 如果没有类型信息,我必须对_id
方法引用进行正则表达式匹配,这很可能会丢失一些东西。