jenkinsgithubjenkins-pipelinemultibranch-pipeline

How to get the list of labels of the Github PR that triggered my multibranch Jenkins build


More precisely I need to get the list of labels of the PR that triggered my multibranch build. Is it possible?

I am aware of https://github.com/jenkinsci/pipeline-github-plugin but incompatible version of Jenkins and multibranch pipeline is used.


Solution

  • After some investigation I found 2 ways of getting list of PR labels.

    1. Needs configuration for github user in Jenkins Credentials and requires node allocation for sending http request via curl.
    def getLabels() {
    
        def labels
    
        def scmHead = jenkins.scm.api.SCMHead.HeadByItem.findHead(currentBuild.rawBuild.getParent())
        def owner = scmHead.getSourceOwner()
        def repo = scmHead.getSourceRepo()
        def prId = scmHead.getId()
    
        withCredentials([usernamePassword(credentialsId: 'GITHUB_CREDENTIALS_ID', usernameVariable: 'UUU', passwordVariable: 'PPP')]) {
            def json = sh(
                    script: "curl -u ${env.UUU}:${env.PPP} https://api.github.com/repos/${owner}/${repo}/issues/${prId}",
                    returnStdout: true
            )
    
            // requires https://plugins.jenkins.io/pipeline-utility-steps plugin
            def prInfo = readJSON(text: json)
    
            labels = prInfo.labels
        }
        return labels
    } 
    
    1. Via https://github.com/jenkinsci/pipeline-github-plugin, requires upgrading Jenkins up to v2.128 or newer.
         if (env.BRANCH_NAME ==~ /PR-\d+/) {
             pullRequest.labels.each{
                echo "label: $it"
             }
         }