Unable to get default branch, defaulting to 'master': TypeError: Cannot read property 'defaultBranch

We’re using Enterprise EditionVersion 10.1 (build 73491)

I posted this question also on SonarQube warning: Unable to get default branch, defaulting to 'master': TypeError: Cannot read property 'defaultBranch' of null - Stack Overflow

We use Azure DevOps and YAML pipelines to build and analyze our code.
This all works fine, except for the code that uses main instead of master as the default branch name. Then SonarQube emits a warning: Unable to get default branch, defaulting to 'master': TypeError: Cannot read property 'defaultBranch' of null

The warning is a false positive. When I go to the SonarQube portal everything looks fine for the project and it even displays the default branch as main.

We have a ‘no warnings’ policy, so it is very sad SonarQube is emitting this warning, which should be in my opinion Information.

I think I need to instruct SonarQube not to look for the master branch or tell it to also look for the main branch. But I can’t figure out how to do this. The documentation is not very helpful at this point.

This is my yaml task:

  - task: SonarQubePrepare@5
    displayName: Prepare analysis on SonarQube ($(SonarProjectKey))
    inputs:
      SonarQube: 'SonarQube - Developer Edition'
      projectKey: $(SonarProjectKey)
      projectName: '${{ parameters.AnalyseProjectName }}'
      projectVersion: '$(Build.BuildNumber)'
      extraProperties: |
        sonar.verbose=true
        sonar.branch.name=$(Build.SourceBranchName)
        sonar.branch.target=main
        sonar.cs.opencover.reportsPaths=**/coverage.opencover.xml
        sonar.cs.vscoveragexml.reportsPaths=$(Agent.BuildDirectory)\TestResults\*.coveragexml
        sonar.exclusions=**\Tests\**\*, **\TestApps\**\*, **\GlobalSuppressions.cs

If needed I can make changes to our build agents.

Please advise.

Hey there.

The Azure DevOps Extension makes a call to the Azure DevOps API to try and determine the default branch of the repository.

I’m not sure why this would work for repos called master but not main.

Can you share your full Azure DevOps Pipeline YAML?

Here’s my complete build pipeline YAML script:

parameters:
  # build parameters
  - name: BuildConfiguration
    type: string
    default: Release
  - name: BuildPlatform
    type: string
    default: x64
  - name: AnalyseProjectName
    type: string
    default: "Foo"
  - name: AnalysersContinueOnError
    type: boolean
    default: false

steps:
  # ============ DOWNLOAD .NET 7 =========================================
  - task: UseDotNet@2
    displayName: Downloading .Net 7 SDK
    inputs:
      packageType: "sdk"
      version: "7.x"

  # ======= Install the reportgenerator =========
  - script: dotnet tool install -g dotnet-reportgenerator-globaltool | echo "Already installed but results in a !0 exit code. See https://github.com/dotnet/sdk/issues/9500"
    displayName: 'Install ReportGenerator'

  # ===================
  # =================== Prepare analysis on SonarQube ============================
  - task: SonarQubePrepare@5
    displayName: Prepare analysis on SonarQube ($(SonarProjectKey))
    condition: and(succeeded(), eq(variables['Build.RunSonarQube.Enabled'], 'true'))
    inputs:
      SonarQube: 'SonarQube - Developer Edition'
      projectKey: $(SonarProjectKey)
      projectName: '${{ parameters.AnalyseProjectName }}'
      projectVersion: '$(Build.BuildNumber)'
      extraProperties: |
        sonar.verbose=true
        sonar.branch.name=$(Build.SourceBranchName)
        sonar.branch.target=main  # Specify the correct default branch name here
        sonar.cs.opencover.reportsPaths=**/coverage.opencover.xml
        sonar.cs.vscoveragexml.reportsPaths=$(Agent.BuildDirectory)\TestResults\*.coveragexml
        sonar.exclusions=**\Tests\**\*, **\TestApps\**\*, **\GlobalSuppressions.cs

  # ======
  # ======= Restore solution =========================================      
  - task: DotNetCoreCLI@2
    displayName: Restore solution
    condition: succeeded()
    inputs:
      command: "restore"
      projects: "$(Build.Repository.LocalPath)/**/*.sln"
      feedsToUse: 'config'
      nugetConfigPath: 'nuget.config'

  # =========
  # ========= Build solution =========================================                        
  - task: DotNetCoreCLI@2
    displayName: Build solution
    condition: succeeded()
    inputs:
      command: "build"
      projects: "$(Build.Repository.LocalPath)/**/*.sln"
      arguments: '/p:Configuration=${{ parameters.BuildConfiguration }} /p:Platform="${{ parameters.BuildPlatform }}" /p:Version=$(Build.BuildNumber) --no-restore'

  # ============= Run Unit Tests =========================================    
  - task: DotNetCoreCLI@2
    displayName: Run Tests
    condition: succeeded()
    inputs:
      command: "test"
      projects: "$(Build.Repository.LocalPath)/**/*.Tests.csproj" # Specific for this app
      arguments: '/p:Configuration=${{ parameters.BuildConfiguration }} /p:Platform="${{ parameters.BuildPlatform }}" --no-restore /p:CollectCoverage=true /p:CoverletOutputFormat=opencover%2ccobertura --collect "XPlat Code Coverage"'

  # ========== Generate code coverage report =========================================  
  - script: reportgenerator "-reports:$(Agent.TempDirectory)/**/coverage.cobertura.xml" "-targetdir:$(Build.SourcesDirectory)/CodeCoverage" -reporttypes:Cobertura
    displayName: 'Generate Code Coverage Report'

  - task: PublishCodeCoverageResults@1
    displayName: 'Publish Code Coverage Report'
    inputs:
      codeCoverageTool: Cobertura
      summaryFileLocation: $(Build.SourcesDirectory)/CodeCoverage/Cobertura.xml
      reportDirectory: $(Build.SourcesDirectory)/CodeCoverage

  # ===========
  # =========== Fortify Source Analyzer =========================================
  # Run Fortify Source Analyzer
  - task: FortifySourceAnalyzer@2
    displayName: 'Fortify: Run Code Analysis'
    condition: eq(variables['Build.RunFortify.Enabled'], 'true')
    inputs:
      SourcesDirectory: '$(FortifySourcesDirectory)'
      BuildNumber: '$(ServiceTeam).${{ parameters.analyseProjectName }}-$(Build.BuildNumber)'
      SkipClean: false
      ScanType: 'msbuild'
      PrimarySolutionFileFilter: '$(SolutionFilename)'
      MsbuildOptions: '/p:Configuration=${{ parameters.BuildConfiguration }} /p:Platform="${{ parameters.BuildPlatform }}" /t:rebuild'
  
  # Upload to Fortify Cloudscan    
  - task: UploadToFortifyCloudscan@1
    displayName: 'Fortify: Upload to Fortify Cloudscan'
    condition: and(succeededOrFailed(), eq(variables['Build.RunFortify.Enabled'], 'true'))
    inputs:
      ProjectName: $(SonarProjectKey)
      ServiceTeam: '$(ServiceTeam)'
      AuthorisationGroupFilters: "$(ServiceTeam)_*"
      BuildNumber: '$(ServiceTeam).${{ parameters.analyseProjectName }}-$(Build.BuildNumber)'
      EmailAddress: '$(Build.RequestedForEmail)'
      FortifyToken: '$(FortifyToken)'
      SSCEncodedToken: '$(FortifyEncToken)'

  # Check Quality Gate
  - task: CheckFortifyGate@1
    displayName: 'Fortify: Check Quality Gate'
    condition: and(succeededOrFailed(), eq(variables['Build.RunFortify.Enabled'], 'true'))
    continueOnError: ${{ parameters.AnalysersContinueOnError }}
    inputs:
      ProjectName: $(SonarProjectKey)
      BuildNumber: '$(ServiceTeam).${{ parameters.analyseProjectName }}-$(Build.BuildNumber)'
      MaxIssueCountDelta: '$(Fortify.Delta.MaxIssueCount)'
      MinPercentAuditedDelta: '$(Fortify.Delta.MinPercentAudited)'
      MaxCriticalPriorityIssueCountDelta: '$(Fortify.Delta.MaxCriticalPriorityIssueCount)'
      MinPercentCriticalPriorityIssuesAuditedDelta: '$(Fortify.Delta.MinPercentCriticalPriorityIssuesAudited)'
      IssuesGroupingName: '$(Fortify.GroupBy)'
      MaxWaitMinutes: '10'
      SSCEncodedToken: '$(FortifyEncToken)'      

  # ==============
  # ============== SonarQube, next steps =========================================      
  # Run Code Analysis
  - task: SonarQubeAnalyze@5
    displayName: 'SonarCube: Run Code Analysis'
    condition: eq(variables['Build.RunSonarQube.Enabled'], 'true')   

  # Publish Quality Gate Result
  - task: SonarQubePublish@5
    displayName: 'SonarCube: Publish Quality Gate Result'
    condition: and(succeededOrFailed(), eq(variables['Build.RunSonarQube.Enabled'], 'true'))
    continueOnError: ${{ parameters.AnalysersContinueOnError }}
    inputs:
      pollingTimeoutSec: '300'    

  # ============ Mend (WhiteSource) Code Analysis =========================================      
  # Mend Licenses and Vulnerabilities Scan
  - task: MendScan@1
    displayName: 'Mend Licenses and Vulnerabilities Scan'
    condition: eq(variables['Build.RunMend.Enabled'], 'true')
    continueOnError: ${{ parameters.AnalysersContinueOnError }}
    inputs:
      MendConnection: '[GUID]'
      SourcesDirectory: '$(FortifySourcesDirectory)'
      ServiceteamName: '$(ServiceTeam)'
      ApplicationName: $(SonarProjectKey)

  # Mend Quality Gate 
  - task: MendQualityGate@1
    displayName: 'Mend Quality Gate'
    condition: and(succeededOrFailed(), eq(variables['Build.RunMend.Enabled'], 'true'))
    continueOnError: ${{ parameters.AnalysersContinueOnError }}
    inputs:
      MendConnection: '[GUID]'
      ServiceteamName: '$(ServiceTeam)' 
      ApplicationName: $(SonarProjectKey)
      HighRiskLicense: true
      MediumRiskLicense: true
      LowRiskLicense: false
      UnknownLicense: false
      HighRiskVulnerability: true
      MediumRiskVulnerability: true
      LowRiskVulnerability: true
      CheckQualityGate: true

  # ======================
  # ====================== Publish Blazor app =========================================      
  - task: DotNetCoreCLI@2
    displayName: Dotnet Publish Blazor App
    inputs:
      command: "publish"
      publishWebProjects: true
      projects: "$(Build.Repository.LocalPath)/**/WebUi.csproj"
      arguments: '--configuration ${{ parameters.BuildConfiguration }} --output "$(Build.ArtifactStagingDirectory)/blazorapp" --no-restore'
      modifyOutputPath: false
  - task: PublishBuildArtifacts@1
    displayName: Publish Artifact blazor App
    condition: succeeded()
    inputs:
      PathtoPublish: "$(Build.ArtifactStagingDirectory)/blazorapp"
      ArtifactName: "$(SonarProjectKey)" # Artifact folder
      publishLocation: "Container" 

As said the 3rd task (first SonarQube task) is throwing the warning.

We’re still facing this problem.

Doesn’t anybody have a suggestion how to solve this?

I assume more developers use main as the name for the main branch.

Hey there.

Sorry this fell off my notifications.

  • Can you check for the presence (and values) of the System.TeamProject and Build.Repository.Name variables in your pipeline right before the SonarQubePublish step
  • I noticed various scanning tools like Fortify and Mend. Approximately how long does your build take overall?

This is one of our pipelines. It takes almost 8 minutes to finish.

We have other applications that take longer.

I checked the values you mentioned and they are correctly filled.
If needed, I can send the values directly to you.

I also checked $(Build.SourceBranch) and it has refs/heads/main

Any suggestions how to fix this?

I still would like to know how to solve this.
Are we really the only users that face this issue?

Hi Colin Do you already have any idea how to solve this?

Any suggestion would really be appreciated.

Hi Paul,

Thank you for your patience and I am sorry that you had to wait that long. I am currently looking into the problem and will get back to you ASAP.

Hello Paul,

As Colin mentioned, Prepare task tries to get information about the repository and its default branch. For some reason in your case, the response for getting the repository is null, therefore you see the warning. I wasn’t able to find the reason (Microsoft docs and codebase are not very helpful here), but it is most likely due to auth/permissions issues.

Can you check if System.TeamFoundationCollectionUri is correct in your pipeline for Prepare task?

One thing I want to point out is that you are already providing sonar.branch.name in extraProperties and our task is doing redundant work, since extraProperties override the ones that we compute internally.
Thus, the warning you see is indeed a false positive. We are going to create a ticket and do a release once we fix it, so the warning will disappear.

We are also facing an issue in Azure DevOps using YAML pipelines with SonarQube for code analysis, particularly when the default branch is ‘main’ instead of ‘master’. A warning pops up: “Unable to get default branch, defaulting to ‘master’: TypeError: Cannot read property ‘defaultBranch’ of null.” Despite this, the analysis runs fine and SonarQube rightly shows ‘main’ as the default branch. Looking for advice on how to eliminate this warning. Thanks

Yes, it is correctly filled with https://dev.azure.com/OurOrg/

I do see this in the pipeline logging: Loading analysis properties from D:\Data\a5\_tasks\SonarQubePrepare_15b84ca1-b62f-4a2a-a403-...\5.15.0\classic-sonar-scanner-msbuild\SonarQube.Analysis.xml

And this Incremental PR analysis: Base branch parameter was not provided.

And SonarScanner for MSBuild 5.13

And sonar.host.url=https://sonarqube.dev.OurOrg.nl/ sonar.projectKey=MySolution sonar.projectName=MyKey sonar.projectVersion=2023.10.09.2-main sonar.branch.name=main sonar.scanner.metadataFilePath=D:\\Data\\a5\\_temp\\sonar\\224946\\cf9aac5a-8b83-5646-....\\report-task.txt sonar.branch.target=main # Specify the correct default branch name here sonar.cs.opencover.reportsPaths=**/coverage.opencover.xml sonar.cs.vscoveragexml.reportsPaths=D:\\Data\\a5\\354\\TestResults\\*.coveragexml sonar.exclusions=**\\Tests\\**\\*, **\\TestApps\\**\\*, **\\GlobalSuppressions.cs sonar.visualstudio.enable=false

@Paul_Meems @Ugur_Celebi we released a minor version of AZDO extension, the warning should disappear on your side. Can you please confirm?

I’m pleased to confirm that the most recent version of the SonarQube AZDO extension no longer generates the mentioned warning.
Your actions in addressing this issue are greatly appreciated. I will go ahead and mark your response as the accepted solution.
I appreciate your diligence.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.