Spring Boot项目SonarCloud新代码分析异常排查求助
apply from: "gradle/sonar.gradle"
...
sonarqube {
properties {
property "sonar.projectKey", "somethingapp_something"
property "sonar.organization", "somethingapp"
property "sonar.host.url", "https://sonarcloud.io"
}
}
### sonar.gradle配置 ```groovy jacoco { toolVersion = "0.8.7" } jacocoTestReport { executionData tasks.withType(Test) classDirectories.from = files(sourceSets.main.output.classesDirs) sourceDirectories.from = files(sourceSets.main.java.srcDirs) reports { xml.enabled true } } plugins.withType(JacocoPlugin) { tasks["test"].finalizedBy 'jacocoTestReport' } file("sonar-project.properties").withReader { Properties sonarProperties = new Properties() sonarProperties.load(it) sonarProperties.each { key, value -> sonarqube { properties { property key, value } } } } test.dependsOn webapp_test compileJava.dependsOn processResources processResources.dependsOn bootBuildInfo
请问为何我的简单PR始终返回相同的分析信息?
问题排查及解决方案
1. PR分析缺少分支对比关键参数
SonarCloud在PR场景下需要明确知道当前PR的目标分支、源分支和PR编号,才能计算出新代码范围。你的Gradle sonarqube任务没有传递这些参数,导致SonarCloud无法识别PR上下文,只能默认扫描全量代码。
解决:修改PR Workflow中Build and analyze步骤的命令,添加PR分析参数:
./gradlew test jacocoTestReport sonarqube --info -x integrationTest \ -Dsonar.pullrequest.key=${{ github.event.number }} \ -Dsonar.pullrequest.base=${{ github.base_ref }} \ -Dsonar.pullrequest.branch=${{ github.head_ref }}
2. SonarCloud项目新代码定义未配置
即使传递了PR参数,如果项目后台的新代码规则设置错误,也会导致扫描全量代码。
解决:登录SonarCloud进入项目,依次点击「Project Settings」→「New Code」,将新代码定义设置为Pull Request模式,或选择Reference branch并指定你的目标分支(如development/main)。
3. Checkout深度不足导致分支历史缺失
默认的actions/checkout@v3只拉取最新提交,没有完整的分支历史,SonarCloud无法对比分支差异。
解决:在PR Workflow的checkout步骤中添加fetch-depth: 0:
- uses: actions/checkout@v3 with: fetch-depth: 0
4. sonar-project.properties可能覆盖配置
你的sonar.gradle会加载sonar-project.properties中的配置,如果该文件中有错误的新代码相关参数(比如sonar.newcode.referenceBranch设置错误),会干扰PR分析。
解决:检查sonar-project.properties文件,移除或修正与PR分析冲突的参数;或者在sonarqube任务中明确覆盖这些参数,确保优先级更高。
内容的提问来源于stack exchange,提问作者abiieez

