How to change the main branch in SonarQube?

Hello here,
From my sonarcube dashboard, I am seeing the coverage for master branch which is the main branch. is there any way to change the main branch to ‘develop’?
master branch is for prod which can’t be deleted. Our all the features development is based on develop branch. So I am wondering is there any way to show the coverage for develop branch as a default on the dashboard.

Cheers,
He Hainan

Hi,

you didn’t mention your Sonarqube version, but since version 6.6 it’s possible via Web api,
POST api/Project_branches_rename to rename the main branch.
see documentation ../web_api/api/project_branches in your Sonarqube instance.

Gilbert

Hello He Han,

@Rebse is correct. I would complement with the point that obviously you should analyse your develop branch as main branch (and not analyze master). Analyzing as main branch simply means analyzing without any sonar.branch.* parameters.
Once your develop branch is analyzed as main branch, it will be called master by default by SonarQube, and you can just rename the branch to develop (once for all), either through the APIs (see @Rebse’s post), or directly from the UI through the Projects --> Administration --> Branches & Pull Requests menu as per the below

Thanks so much! I’ll try!

Follow-up
These menu items do not show up for me. Is this still available ? API calls also failing.


Thanks

As per @OlivierK.
Thanks

Yes, the menus and API are still available.
The problem is that you must have at least one branch analyzed to define the default/main branch. You cannot do it before that branch has been analyzed.
In your case, it seems you just created the project but did not analyze it yet.

Thanks for jumping back in.
So is this a catch 22 situation? I am trying to analyze the project for the first time, but it is located on a branch not called master.
But from what you said I can’t change that branch name from master to something unless until it is analyzed first.
The analysis is failing with the branch related error:

##[error]ERROR: Error during SonarQube Scanner execution
ERROR: Error during SonarQube Scanner execution
##[error]ERROR: Validation of project reactor failed:
ERROR: Validation of project reactor failed:
##[error]o To use the property “sonar.branch.name” and analyze branches, Developer Edition or above is required. See https://redirect.sonarsource.com/doc/branches.html for more information.
o To use the property “sonar.branch.name” and analyze branches, Developer Edition or above is required. See https://redirect.sonarsource.com/doc/branches.html for more information.
##[error]ERROR:
ERROR:
##[error]The SonarQube Scanner did not complete successfully
The SonarQube Scanner did not complete successfully
##[error]21:54:58.645 Post-processing failed. Exit code: 1
21:54:58.645 Post-processing failed. Exit code: 1

No it is not. You must simply analyze the branch that you want to be your main without any sonar.branch.name parameter.

Let’s say your main branch should be develop. Just execute:

git checkout develop 
# Build if you have to
sonar-scanner # (or mvn sonar:sonar or gradle sonarqube or whatever command to run the scan, but **without** the sonar.branch.name property)

This creates by default in SonarQube a branch named master. It’s probably not an excellent idea to always call the main branch master by default, we may fix that in the future. Anyway, for now you can rename this branch once for all as develop and that’s it.
Of course you must continue to run subsequent scans of your develop branch without the sonar.branch.name parameter.

Regards

Thanks, I’ll need to dig in further. I am not specifying the sonar.branch.name parameter. I’m running in AzureDevops and pointing to a SonarQube server. The sonar plugins in AzureDevops must be setting it under the covers somewhere.
The entry in the .yml file is just:

  • task: SonarQubeAnalyze@4

Hmm. Tried changing the prepare task from msbuild integrated to standalone. Slightly different report, but same error. Is there any way to bypass/uncheck the branch parameter causing the issue ?

Thanks

I missed the information that you were using Azure DevOps. It’s an important point.
With Azure DevOps the SonarQube Prepare Analysis task automatically sets the sonar.branch.name property based on an (hopefully meaningful) internal logic. You don’t control this.
The logic is the following:

  • There is a nothing of “Default branch” in Azure DevOps (nothing specific to SonarQube, it’s an AzDo concept)
  • If the branch you analyze is this default branch then the SonarQube Prepare Analysis task will not set sonar.branch.name and you will scan this branch as the main branch in SonarQube. This branch will be by default named master in SonarQube, that you can afterward rename to whatever it is really, as explain in earlier post
  • If the branch you analyze is not the default, then sonar.branch.name is automatically set an you will get a “branch analysis” in SonarQube with the right branch name

Note that the above logic only works when your repository is in Azure Git. If you use TFVC or GitHub or any other Git or SVN repo, that will not work.

Thank you Olivier,
I was able to analyze the branch following your steps.
However the “Branches & Pull Requests” option still doesn’t show up in the Administration menu. Anything else needed to get it to show up ?

Hello @trexx00 ,
The fact that you have no “branches and pull requests” menu is odd.
Can you confirm which version of SonarQube you run ?
Can you confirm that you did analyze some code ? (I see all your metrics to 0 in the dashboard I have a doubt). Can you provide a screenshot of your full project home page, including the right panel that shows various informations about the project, including nbr of lines of code analyzed.
Regards

Hello @trexx00,
Thanks to a colleague we spotted why you don’t have the branches and PR menu. It’s simply because you apparently run a SonarQube Community (free) Edition - We can tell that from the edition displayed in the footer of your first screenshot.
The Branch and PR analysis feature is available only from Developer Edition and higher.
Regards

Hi there, thanks for the useful information in this discussion!

I’m experiencing the exact same problem, while we are using the ‘Developer’ edition (currently on a trial license).
When using mercurial as the scm, the default branch is called ‘default’ (as opposed to ‘master’ for git). We have Jenkins CI set up to create the projects (which works fine), but it will create it as ‘master’ in SonarQube. After the first run, we can manually modify this on the project level.

This seems to fully correspond with the analysis by @OlivierK;

The problem is that you must have at least one branch analyzed to define the default/main branch. You cannot do it before that branch has been analyzed.

and therefore I’m also interested in the following comment;

This creates by default in SonarQube a branch named master . It’s probably not an excellent idea to always call the main branch master by default, we may fix that in the future.

Notifying @Nathan_Chase, as we had contact about this via email.

Hello @JortKoopmans,
Not sure why you involved @Nathan_Chase in the discussion here ?
Anyhow, I guess that you only remaining issue is that the main branch is called master (kinda git biased) and you would like it to be named default as per Mercurial conventions.
That is possible, after the fact: Once you have analyzed you Mercurial default branch, it will be called master in SonarQube. Just go in the UI and change that name to default, once for all for this project… and that’s it.

The process to set this for each project is fully understood, thanks for confirming that.
I involved Nathan because we experienced this issue during our Developer trial/evaluation, which we discussed over email and subsequently he pointed me to this Community Forum for further technical guidance.

I’ve created a Python3 script to set the main branch as “develop” on project where it’s “master”

it uses python-sonarqube-api

import os
from distutils.util import strtobool

from sonarqube import SonarQubeAPI
from sonarqube.exceptions import ClientError

SONAR_API = SonarQubeAPI(token=os.getenv('SONARQUBE_API_TOKEN', input('Enter SonarQube API token: ')),
                         sonarqube_url=os.getenv('SONARQUBE_API_URL', input('Enter SonarQube API url: ')))


def get_projects_where_develop_is_not_the_default_branch():
    global SONAR_API

    p = []
    for project in SONAR_API.projects:
        for branch in SONAR_API.project_branches.get_project_branches_list(project['key']):
            if branch['name'] == 'master' and branch['isMain'] == True:
                print(f"{project['name']} have master branch has default")
                p.append(project['key'])
    return p


def set_default_branch_to_develop(project_key):
    global SONAR_API

    user_input = input(f"Remove develop branch and set develop as default for {project_key} ? [y/n] ")
    if user_input and strtobool(user_input):
        try:
            SONAR_API.project_branches.delete_project_branch(project_key, 'develop')
        except ClientError:
            pass
        SONAR_API.project_branches.rename_project_branch(project_key, 'develop')


if __name__ == '__main__':
    projects = get_projects_where_develop_is_not_the_default_branch()
    for project_key in projects:
        set_default_branch_to_develop(project_key)
    else:
        print('Did not find any project to convert :)')

A setting to set the default branch globally would be very much welcomed tho :slight_smile:

1 Like