gitjenkinssonarqubesonarqube-scan

Jenkins/Sonarqube: Fetch target branch in multibranch pipeline?


I am running a Jenkins a multibranch pipeline with SonarQube scanner. It looks like the scanner requires target branch of the PR to be fetched in order to run the analysis but Jenkins is only fetching the pull request branch(feature/add-jenkins in below example).

...
 > git fetch --no-tags --force --progress -- https://github.com/my-user/sonar-test.git +refs/heads/feature/add-jenkins:refs/remotes/origin/feature/add-jenkins # timeout=10
...

My Jenkins pipeline looks like this:

pipeline {
    agent any
    environment {
        SONAR_TOKEN = credentials('sonar-token')
    }
    stages {
        stage('Build') {
            steps {
                echo 'Building..'
            }
        }
        stage('Test') {
            steps {
                sh '''
                    printenv
                    ./gradlew sonar -Dsonar.pullrequest.key=4 -Dsonar.pullrequest.branch=feature/add-jenkins -Dsonar.pullrequest.base=main
                '''
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying....'
            }
        }
    }
}

How can I tell Jenkins to pull the PR's target branch also?


Solution

  • You don't need to if you configure the multibranch pipeline properly.

    From Setting up the pull request analysis section of SonarQube documentation:

    The SonarScanner can automatically detect the pull request parameters when running on the following CI services (you don’t need to perform any additional setup):

    • Azure Pipelines
    • Bitbucket Pipelines
    • Cirrus CI
    • Codemagic
    • GitHub Actions
    • GitLab CI/CD
    • Jenkins (with the Branch Source plugin configured)

    The documentation also emphasizes that the autodetection doesn't work if you set the parameters by yourself:

    Manually setting pull request parameters overrides automatic detection.

    Regarding your statement:

    Jenkins is only fetching the pull request branch

    If it's the only log entry about fetching, chances are that you didn't actually configure yur multibranch pipeline to detect pull requests. This part is also covered by SonarQube docs:

    From your Jenkins job, go to Configure > Branch Sources > Behaviors and:

    • Under Discover branches, make sure Exclude branches that are also filed as PRs (or MRs) is selected.
    • Under Discover pull (or merge) requests from origin, make sure The current pull (or merge) request revision is selected.
    • Under Specify ref specs, make sure the Ref Spec value will include any target branches (the default value should be enough).
    • If the Specify ref specs behavior is not active, click on Add and select Specify ref specs.

    Your settings could include some other parameters as well, if they don't conflict with the mentioned ones, but these are essential.