SonarQube 在处理 golangci-lint
生成的 Checkstyle 报告时,依赖slang CheckstyleFormatImporter
类的逻辑来映射 severity
(严重等级)和 issue
类型
一、背景:SonarQube 对 severity 的映射逻辑
源码:https://github.com/SonarSource/slang/blob/ecefaee360329a052164201e4ae5509c3692ae9c/checkstyle-import/src/main/java/org/sonarsource/slang/externalreport/CheckstyleFormatImporter.java#L171
issue
类型(RuleType
):
-
- 若报告中
severity
为error
→RuleType.BUG
(缺陷)。 - 其他值(
warning
/info
)→RuleType.CODE_SMELL
(代码异味)。
- 若报告中
- 严重等级(
Severity
):
-
- 若报告中
severity
为info
→Severity.MINOR
( minor)。 - 其他值(
error
/warning
)→Severity.MAJOR
( major)。
- 若报告中
二、修改源码以支持更多 severity 映射(方案)
调整 SonarQube 对 severity
的映射规则(例如支持 warning
映射为不同等级),修改 CheckstyleFormatImporter.java
中的逻辑。以下是具体修改点:
1. 修改 ruleType
方法(调整 issue 类型)
原逻辑(仅 error
映射为 BUG
):
protected RuleType ruleType(String ruleKey, @Nullable String severity) {
return "error".equals(severity) ? RuleType.BUG : RuleType.CODE_SMELL;
}
修改后(支持 warning
映射为 VULNERABILITY
或其他类型):
protected RuleType ruleType(@Nullable String severity, String source) {
if ("gosec".equals(source)) {
return RuleType.VULNERABILITY;
}
if ("error".equals(severity) || "waning".equals(severity)) {
return RuleType.BUG;
}
return RuleType.CODE_SMELL;
}
2. 修改 severity
方法(调整严重等级)
原逻辑(仅 info
映射为 MINOR
):
protected Severity severity(String ruleKey, @Nullable String severity) {
return "info".equals(severity) ? Severity.MINOR : Severity.MAJOR;
}
修改后(支持 warning
映射为 MEDIUM
等级):
protected Severity severity(@Nullable String severity) {
// return "info".equals(severity) ? Severity.MINOR : Severity.MAJOR;
switch (severity) {
case "error":
return Severity.BLOCKER;
case "warning":
return Severity.MAJOR; // 或 Severity.MINOR/MAJOR
case "info":
return Severity.MINOR;
default:
return Severity.MAJOR;
}
}
三、修改后的编译与部署
- 克隆 SonarSource/slang 仓库:
git clone https://github.com/SonarSource/slang.git
cd slang
- 修改
CheckstyleFormatImporter.java
:
-
- 按上述方案修改
ruleType
和severity
方法。
- 按上述方案修改
-
编译并打包:
-
- 在根目录执行
./gradlew clean build -x test --no-scan
编译后生成的 JAR 包位于 checkstyle-import/target/
目录。
- 替换 SonarQube 插件:
-
- 停止 SonarQube 服务
- 将编译后的 JAR 包替换为 SonarQube 安装目录下的
extensions/plugins/sonar-checkstyle-plugin.jar
(需根据实际插件版本调整) - 重启 SonarQube