下载sonar-java项目并查看pom文件
通过克隆该存储库获取模板项目(https://github.com/SonarSource/sonar-java.git),然后在IDE中导入子模块java-custom-rules-examples。该项目已经包含了自定义规则的示例。我们目标是创建一个新的规则!
自定义插件是一个Maven项目,在深入研究代码之前,重要的是要注意与即将发布的自定义插件的配置相关的几行。Maven项目的根是一个名为pom.xml的文件。
在我们的例子中,我们有两个:
pom.xml:使用Java Analyzer的快照版本
pom_SQ_8_9_LTS.xml:自包含的LTS文件,配置了与SonarQube LTS需求匹配的依赖项
在本教程中,我们将只使用名为pom_SQ_8_9_LTS.xml的文件,因为它完全独立于Java Analyzer的构建,并且将针对SonarQube的版本。
查看pom_SQ_8_9_LTS.xml文件内容,您将看到SonarQube和Java Analyzer版本都是硬编码的。这是因为SonarSource的分析器直接嵌入到各种SonarQube版本中,并一起发布。例如,SonarQube 8.9(以前的LTS)随Java Analyzer的版本6.15.1.26025一起发布,而SonarQube 9.9 (LTS)随Java Analyzer的最新版本7.16.0.30901一起发布。这些版本不能更改。
<properties>
<sonarqube.version>8.9.0.43852</sonarqube.version>
<sonarjava.version>6.15.1.26025</sonarjava.version>
<!-- [...] -->
</properties>
先执行一个简单的命令
mvn clean install -f pom_SQ_8_9_LTS.xml
在下面的代码片段中,重要的是要注意,插件的入口点是作为sonar- packagingmaven插件配置中的< plugclasass >提供的,使用java类MyJavaRulesPlugin的完全限定名。如果重构代码、重命名或移动实现org.sonar.api.Plugin的类,则必须更改此配置。属性<sonarQubeMinVersion>还保证与目标SonarQube实例的兼容性。
<plugin>
<groupId>org.sonarsource.sonar-packaging-maven-plugin</groupId>
<artifactId>sonar-packaging-maven-plugin</artifactId>
<version>1.21.0.505</version>
<extensions>true</extensions>
<configuration>
<pluginKey>java-custom</pluginKey>
<pluginName>Java Custom Rules</pluginName>
<pluginClass>org.sonar.samples.java.MyJavaRulesPlugin</pluginClass>
<sonarLintSupported>true</sonarLintSupported>
<skipDependenciesPackaging>true</skipDependenciesPackaging>
<sonarQubeMinVersion>8.9</sonarQubeMinVersion>
<requirePlugins>java:${sonarjava.version}</requirePlugins>
</configuration>
</plugin>
编写规则
主要通过三个文件创建规则
- 在
/java-custom-rules-examples/src/test/files
路径创建文件MyFirstCustomCheck.java
,编写测试用例
/**
*This file is the sample code against we run our unit test.
*It is placed src/test/files in order to not be part of the maven compilation.
**/
class MyClass {
MyClass(MyClass mc) { }
int foo1() { return 0; }
void foo2(int value) { }
int foo3(int value) { return 0; } // Noncompliant
Object foo4(int value) { return null; }
MyClass foo5(MyClass value) {return null; } // Noncompliant
int foo6(int value, String name) { return 0; }
int foo7(int ... values) { return 0;}
}
- 在
/java-custom-rules-examples/src/test/java
路径的org.sonar.samples.java.checks
下创建测试类文件MyFirstCustomCheck
,通过测试类链接到我们的规则,如下面的代码片段所示。这个测试类包含一个测试,其目的是验证我们将要实现的规则的行为。为此,它依赖于由Java Analyzer规则测试API提供的CheckVerifier类的使用。这个CheckVerifier类提供了验证规则实现的有用方法,允许我们完全抽象所有与Analyzer初始化相关的机制在验证规则时,验证者将收集标记为Noncompliant的行,并验证该规则是否提示了预期的问题,并且只提示了这些问题。
package org.sonar.samples.java.checks;
import org.junit.jupiter.api.Test;
import org.sonar.java.checks.verifier.CheckVerifier;
class MyFirstCustomCheckTest {
@Test
void test() {
CheckVerifier.newVerifier()
.onFile("src/test/files/MyFirstCustomCheck.java")
.withCheck(new MyFirstCustomCheck())
.verifyIssues();
}
}
- 在路径
/src/main/java
的包org.sonar.samples.java.checks
下创建一个类MyFirstCustomCheck.java
,此类需要继承org.sonar.plugins.java.api.IssuableSubscriptionVisitor
。
package org.sonar.samples.java.checks;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.semantic.Symbol;
import org.sonar.plugins.java.api.semantic.Type;
import org.sonar.plugins.java.api.tree.MethodTree;
import org.sonar.plugins.java.api.tree.Tree;
import org.sonar.plugins.java.api.tree.Tree.Kind;
import java.util.Collections;
import java.util.List;
@Rule(key = "MyFirstCustomRule")
public class MyFirstCustomCheck extends IssuableSubscriptionVisitor {
@Override
public List<Kind> nodesToVisit() {
return Collections.singletonList(Kind.METHOD);
}
@Override
public void visitNode(Tree tree) {
MethodTree method = (MethodTree) tree;
if (method.parameters().size() == 1) {
Symbol.MethodSymbol symbol = method.symbol();
Type firstParameterType = symbol.parameterTypes().get(0);
Type returnType = symbol.returnType().type();
if (returnType.is(firstParameterType.fullyQualifiedName())) {
reportIssue(method.simpleName(), "Never do that!");
}
}
}
}
在自定义插件中注册规则
为了对规则进行详细的描述并进行展示,需要创建一个HTML文件以及一个JSON文件,HTML文件主要提供规则的扩展文本描述,可以展示在sonarQube中,JSON文件描述的信息具体为元数据,主要描述了规则的类型、标签以及严重等级等等。在路径src/main/resources/org/sonar/l10n/java/rules/java/
创建MyFirstCustomRule.html
和MyFirstCustomRule.json
,MyFirstCustomRule.html
代码如下
<p>For a method having a single parameter, the types of its return value and its parameter should never be the same.</p>
<h2>Noncompliant Code Example</h2>
<pre>
class MyClass {
int doSomething(int a) { // Noncompliant
return 42;
}
}
</pre>
<h2>Compliant Solution</h2>
<pre>
class MyClass {
int doSomething() { // Compliant
return 42;
}
long doSomething(int a) { // Compliant
return 42L;
}
}
</pre>
MyFirstCustomRule.json
代码如下,其中规则名称为:Return type and parameter of a method should not be the same
{
"title": "Return type and parameter of a method should not be the same",
"type": "Bug",
"status": "ready",
"tags": [
"bugs",
"gandalf",
"magic"
],
"defaultSeverity": "Critical"
}
规则激活
下一步需要激活插件中的规则,找到org.sonar.samples.java.RulesList
并打开RulesList类。在这个类中,有两个方法getJavaChecks()
和getJavaTestChecks()
方法。这些方法用于将我们的规则与Java插件的规则的注册。在getJavaChecks()
中注册的规则将只对源文件起作用,而在getJavaTestChecks()
中注册的规则将只对测试文件起作用。要注册规则,只需将规则类添加到列表构建器中,如下面的代码片段所示:
public static List<Class<? extends JavaCheck>> getJavaChecks() {
return Collections.unmodifiableList(Arrays.asList(
// other rules...
MyFirstCustomCheck.class
));
}
规则注册
由于添加了一个新规则,所以需要更新在\sonar-java\docs\java-custom-rules-example\src\test\java\org\sonar\samples\java\MyJavaFileCheckRegistrarTest.java
路径下的类MyJavaFileCheckRegistrarTest
,以确保新规则被考虑在内。导航到其对应的测试类MyJavaFileCheckRegistrarTest
,并将原本的自定义的规则数量从8个更新为9个。
class MyJavaFileCheckRegistrarTest {
@Test
void checkNumberRules() {
CheckRegistrar.RegistrarContext context = new CheckRegistrar.RegistrarContext();
MyJavaFileCheckRegistrar registrar = new MyJavaFileCheckRegistrar();
registrar.register(context);
assertThat(context.checkClasses()).hasSize(8); // change it to 9, we added a new one!
assertThat(context.testCheckClasses()).isEmpty();
}
}
通过以上操作,规则被激活、注册,并且应该可以进行测试了。但在此之前,还可以对自定义的规则设置所属的存储库名称。
该存储库的键和名称在src/main/java/org/sonar/samples/java/
路径下MyJavaRulesDefinition.java
中定义,代码如下:
public class MyJavaRulesDefinition implements RulesDefinition {
// ...
public static final String REPOSITORY_KEY = "fellowship-inc";
public static final String REPOSITORY_NAME = "The Fellowship's custom rules";
// ...
}
自定义规则在sonarQube中如图所示:
测试自定义插件
首先需要下载安装sonarQube
首先使用Maven构建项目。在路径/sonar-java/docs/java-custom-rules-exampl
下执行命令
mvn clean install -f pom_SQ_8_9_LTS.xml
然后,从项目的目标文件夹中获取jar文件java-custom-rules-example-1.0.0-SNAPSHOT.jar
,并将其移动到SonarQube实例的扩展文件夹中,该文件夹位于$SONAR_HOME/extensions/plugins
。
在SonarQube中的language下,选择“Java”,然后在Repository
部分下选择“the Fellowship’s custom rules”,如图所示,便可以看到创建的自定义规则。
参考:https://github.com/SonarSource/sonar-java/blob/master/docs/CUSTOM_RULES_101.md