Jenkinsfile-GitHub : resolve $CHANGE_ID from branch build

It can be frustrating to realize that env.CHANGE_ID is not defined in your jenkins job, just because the current job is a branch build and not a pull request build.
But this is only an obstacle, and can be overcome.

Proof (assuming you know the url of the github api, the github user name, the project name and the name of your repository) :

if (env.BRANCH_NAME != MAIN_BRANCH) {
  def pulls = httpRequest acceptType: 'APPLICATION_JSON',
          authentication: githubUsername,
          consoleLogResponseBody: true,
          contentType: 'APPLICATION_JSON',
          httpMode: 'GET',
          responseHandle: 'NONE',
          url: "${GITHUB_API_URL}/repos/${PROJECT_NAME}/${REPOSITORY_NAME}/pulls"
  def pullsList = new groovy.json.JsonSlurper().parseText(pulls.content)
  def pullRequest = pullsList.find { it.head.ref == env.BRANCH_NAME }
  if (pullRequest != null) {
    env.CHANGE_ID = pullRequest.number
  }
}

Insert this code at the top of your build, and you can have access to env.CHANGE_ID.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.