SonarCloud - Update main branch

Hello,

We work with release branches in our projects, and we would like to update the main branch to the next release branch so that feature branches analysis are targeting the correct release branch.

Example:

Default branch in GitLab = release-A
Main branch in SonarCloud = release-A

Update default branch in Gitlab to release-B
Main branch in SonarCloud = release-A ← I would like to be able to update the main branch in SonarCloud to release-B, ideally automatically.

Is there a way to achieve this currently?

All release branches are correctly set as long-lived branches, the only problem is with feature branch analysis targeting the wrong release branch.

Thanks in advance.

Hi,

Welcome to the community!

If you’re asking if you can swap release-A out of being main and release-B in, that’s not currently available on SonarCloud.

What you can do (although it will screw up your branch history) is to just analyze release-B as main - so either no branch name in analysis or the branch name you’ve been using for branch-A.

I know it’s not great. :frowning:

 
Ann

If you use the sonar scanner to run your analysis you could pretend that your current branch being analysed is some other branch name. SonarCloud will not know any better. This can be achieved by adding this to your sonar-project.properties file:

sonar.branch.name = ${env.SONAR_BRANCH}

And then before calling the scanner have a script decide what branch name to report to SonarCloud.

I had to do this as a workaround for the Sonar GitHub action which does not always detect the current branch name properly. See: Sonarcloud-github-action publishes branch analysis to main and not the current branch - #5 by sodul

For example if you were to rename the MAIN branch in sonarcloud to be release-current, but that is not an actual branch in git, and then your CI pipeline get the default branch name from the gitlab API, then if the current branch is the same as the default gitlab branch, then you set SONAR_BRANCH=release-current and the MAIN branch in SonarCloud will get the report.

To rename the MAIN branch in sonar you need to go to the Branches tab to the left and click on the 3 dots and then Rename Branch.

There is yet an other option: write a script that calls the GitLab API to switch the default branch and then calls the SonarCloud API to rename the MAIN branch, then you will need to trigger a new analysis.

Look for ‘rename’ here: SonarCloud
General docs on the API: SonarCloud Web API

1 Like