Sonar Java 規則插件開發 (基於阿裏開發手冊)
阿新 • • 發佈:2019-04-09
efault debug 靜態 ons status ever target ant cost 實現:
AbstractClassNameCheck
引言
最近在做Sonar靜態代碼掃描管理,以此順手接了Sonar的插件開發,基於阿裏開發手冊進行開發,在整體開發過程中,其中還是遇到不少坑位,也以此給大家做相應借鑒
官網Demo演示插件開發地址:
https://docs.sonarqube.org/display/PLUG/Writing+Custom+Java+Rules+101
基於官網的我暫時不多說,基礎框架按照官網的範例進行搭建即可
#開源地址:
https://github.com/tigerge000/sonar-java-custom-rules.git
sonar常用方法說明
範例
需求:【強制】抽象類命名使用 Abstract 或 Base 開頭;異常類命名使用 Exception 結尾;測試類 命名以它要測試的類的名稱開始,以 Test 結尾。
AbstractClassNameCheck
package org.finger.java.rule.checks.namerules;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.JavaFileScanner;
import org.sonar.plugins.java.api.JavaFileScannerContext;
import org.sonar.plugins.java.api.tree.*;
/**
* 抽象類命名檢查
* 抽象類命名使用 Abstract 或 Base 開頭
* Created by 古月隨筆 on 2017/3/17.
*/
@Rule(key = "AbstractClassNameCheck")
public class AbstractClassNameCheck extends BaseTreeVisitor implements JavaFileScanner{
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractClassNameCheck.class);
private JavaFileScannerContext context;
@Override
public void scanFile(JavaFileScannerContext context) {
this.context = context;
scan(context.getTree());
}
@Override
public void visitClass(ClassTree tree) {
String className = tree.simpleName().name();
LOGGER.info(className + "<<>>" + tree.symbol().isAbstract());
if(tree.symbol().isAbstract()){
//判斷名稱是否以Abstract 或 Base 開頭
String abName = "Abstract";
String bsName = "Base";
//判斷類名如果小於Abstract 或 Base
if (className.length() < abName.length() || className.length() < bsName.length()) {
context.reportIssue(this, tree, "The Name Of Abstract Class should use Abstract or Base first");
} else {
//判斷是否存在 Abstract 或 Base
if (!className.contains(abName)) {
if (!className.contains(bsName)) {
context.reportIssue(this, tree, "The Name Of Abstract Class should use Abstract or Base first");
} else {
if (className.indexOf(bsName) != 0) {
context.reportIssue(this, tree, "The Name Of Abstract Class should use Abstract or Base first");
}
}
} else {
if (className.indexOf(abName) != 0) {
context