SonarQube 自定義規則開發


SonarQube 自定義規則開發

如何開發自己的代碼規則
本文只是初步試了試自定義規則,可能有疏漏和錯誤,請大家僅做參考

以下內容需要了解 Java 和 Maven

開發自定義規則

開發步驟見 Writing Custom Java Rules 101,這是官方提供的 sonar-java 下面的指導文檔,簡述了怎么開發一個 Java 自定義規則。

文章的開始,給了一個模板地址 java-custom-rules,可以看到這個項目下還有別的語言模板。

我們下載這個 Java 自定義規則模板,為 Java 開發一種自定義規則。

下載項目后編譯

mvn clean package

把生成的文件放在 $SONAR_HOME/extensions/plugins 目錄

重啟 SonarQube

可以看到 Java 下面多了 MyCompany Custom Repository 倉庫,下面有新增的規則,這是模板自帶的例子。

接下來添加一個自定義規則,按照文檔一步一步走,最終我們添加/修改了以下代碼

創建 src/test/files/MyFirstCustomCheck.java 文件,這是被掃描的代碼,用於單元測試

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;}
}

創建單元測試代碼 src/test/java/org/sonar/samples/java/checks/MyFirstCustomCheckTest.java

package org.sonar.samples.java.checks;

import org.junit.Test;
import org.sonar.java.checks.verifier.JavaCheckVerifier;

public class MyFirstCustomCheckTest {

    @Test
    public void test() {
        JavaCheckVerifier.verify("src/test/files/MyFirstCustomCheck.java", new MyFirstCustomCheck());
    }

}

創建檢查規則 src/main/java/org/sonar/samples/java/checks/MyFirstCustomCheck.java

package org.sonar.samples.java.checks;

import com.google.common.collect.ImmutableList;

import org.sonar.check.Priority;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.semantic.Symbol.MethodSymbol;
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.List;

@Rule(
        key = "MyFirstCustomCheck",
        name = "Return type and parameter of a method should not be the same",
        description = "For a method having a single parameter, the types of its return value and its parameter should never be the same.",
        priority = Priority.CRITICAL,
        tags = {"bug"})
public class MyFirstCustomCheck extends IssuableSubscriptionVisitor {


    @Override
    public void visitNode(Tree tree) {
        if (method.parameters().size() == 1) {
            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! 01!");
            }
        }
    }

    @Override
    public List<Kind> nodesToVisit() {
        return ImmutableList.of(Kind.METHOD);
    }
}

將我們自定義的規則添加到規則列表中,修改 ‪src/main/java/org/sonar/samples/java/RulesList.java

  public static List<Class<? extends JavaCheck>> getJavaChecks() {
    return Collections.unmodifiableList(Arrays.asList(
      SpringControllerRequestMappingEntityRule.class,
      AvoidAnnotationRule.class,
      AvoidBrandInMethodNamesRule.class,
      AvoidMethodDeclarationRule.class,
      AvoidSuperClassRule.class,
      AvoidTreeListRule.class,
      MyCustomSubscriptionRule.class,
      SecurityAnnotationMandatoryRule.class,
      MyFirstCustomCheck.class));  # 添加我們的規則
  }

再次編譯

mvn clean package

把生成的文件放在 $SONAR_HOME/extensions/plugins 目錄

重啟 SonarQube,可以看到我們添加的規則,自定義規則開發完畢

驗證自定義規則

創建新的規則配置,只將我們添加自定義規則設置為檢查項,步驟截圖







創建項目驗證自定義規則,和之前的掃描測試一樣,在 Linux 服務器上執行

mkdir -p /usr/local/sonarqube/workspace/custom && cd /usr/local/sonarqube/workspace/custom

項目代碼只有一個 MyFirstCustomCheck.java,就是前邊用於單元測試的代碼

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;}
}

創建掃描配置文件 sonar-project.properties

sonar.projectKey=custom
sonar.sources=.
sonar.host.url=http://192.168.10.227:9000
sonar.login=c4765957e5ada82ebe21a7c2e1f56afbff4059d3
sonar.language=java
sonar.java.binaries=.
sonar.sourceEncoding=UTF-8

執行掃描

sonar-scanner

自定義規則生效了

備注

注意,以上自定義規則應該是對 SonarJava 的拓展,必須安裝了 SonarJava 才會生效。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM