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

1

5

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.

Knudsen answered 21/8, 2018 at 14:16 Comment(0)
K
8

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"
         }
     }
Knudsen answered 22/8, 2018 at 11:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.