Skip to content

Commit 3c0aa71

Browse files
committed
Default sonar.branch.name to the current git branch
Without sonar.branch.name set, `./gradlew sonar` posts the analysis to whatever the SonarCloud project's main branch is. So local runs from a feature/bugfix branch silently overwrite the main branch's quality gate snapshot — which is what you noticed during the rebase work on develop. Derive sonar.branch.name from the current git ref at config time: - if -Psonar.branch.name=… is already passed (CI does this), honor it - else read GITHUB_REF_NAME or GITHUB_HEAD_REF if set - else run `git rev-parse --abbrev-ref HEAD` - if everything resolves to "HEAD" (detached, no useful ref), leave sonar.branch.name unset so SonarCloud falls back to its configured main branch rather than getting a garbage value CI keeps explicitly overriding via -P in build-artifacts.yml, so this only changes behavior locally and on workflows that don't pass the flag.
1 parent 874be23 commit 3c0aa71

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

build.gradle

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,24 @@ sonar {
387387
property "sonar.coverage.jacoco.xmlReportPaths", "**/build/reports/jacoco/test/jacocoTestReport.xml"
388388
property "sonar.buildbreaker.skip", "false"
389389
property "sonar.qualitygate.wait", true
390+
391+
// Default sonar.branch.name to the current git branch so local `./gradlew sonar`
392+
// analyses land on the branch you're on, not the project's main branch.
393+
// CI keeps overriding via -Psonar.branch.name=<ref>; that takes precedence via
394+
// findProperty(). On detached HEAD (no detectable branch) we leave it unset and
395+
// SonarCloud falls back to the project's configured main branch.
396+
if (!findProperty("sonar.branch.name")) {
397+
def envBranch = System.getenv("GITHUB_REF_NAME") ?: System.getenv("GITHUB_HEAD_REF")
398+
def gitBranch = providers.exec {
399+
commandLine 'git', 'rev-parse', '--abbrev-ref', 'HEAD'
400+
}.standardOutput.asText.map { it.trim() }.getOrElse('')
401+
def branch = (envBranch && envBranch != 'HEAD') ? envBranch
402+
: (gitBranch && gitBranch != 'HEAD') ? gitBranch
403+
: null
404+
if (branch) {
405+
property "sonar.branch.name", branch
406+
}
407+
}
390408
}
391409
}
392410

0 commit comments

Comments
 (0)