How to check out a Pull-Request with Jenkins Pipeline?

It turned out this can be made working by setting a refspec property on the checkout configuration object:

checkoutConfig.with {
    branches = [[ name: 'pr/4711' ]]
    userRemoteConfigs[0].refspec = '+refs/pull/*/head:refs/remotes/origin/pr/*'
}

See also: https://gist.github.com/piscisaureus/3342247


Inspired by previous responses and sources https://www.git-tower.com/learn/git/faq/detached-head-when-checkout-commit i wrote a simple shared library pipeline step:

checkoutPullRequest.groovy

Void call(String prNbr, String repo) {
    checkout([$class: 'GitSCM',
        branches: [[name: "FETCH_HEAD"]],
        doGenerateSubmoduleConfigurations: false,
        extensions: [[$class: 'LocalBranch'], [$class: 'RelativeTargetDirectory', relativeTargetDir: "${repo}"]],
        userRemoteConfigs: [[refspec: "+refs/pull/${prNbr}/head:refs/remotes/origin/PR-${prNbr} +refs/heads/master:refs/remotes/origin/master",
                            url: "https://${env.GITHUB_TOKEN}@github.com/githubusername/${repo}"]]
    ])
}

so in your pipeline Jenkinsfile you can just use

checkoutPullRequest('926', 'appgitrepo')

Based on this doc about fetching a pull request.

Assuming you pass the PR number as a parameter:

checkout([$class: 'GitSCM', branches: [[name: "FETCH_HEAD"]],
  extensions: [[$class: 'LocalBranch']],
  userRemoteConfigs: [[refspec: "+refs/pull/${params.PR_NUMBER}/head:refs/remotes/origin/PR-${params.PR_NUMBER}", url: "https://${GITHUB_TOKEN}@github.com/${YOUR_REPO}"]]])

What's going on here:

  • First, you fetch refs for PullRequests
  • Then you checkout to the FETCH_HEAD
  • LocalBranch is required to avoid detached HEAD on the Jenkins agent

Cheers!


If you're working with bitbucket:

checkout([$class: 'GitSCM', branches: [[name: 'FETCH_HEAD']], 
doGenerateSubmoduleConfigurations: false, extensions: [
                    [$class: 'LocalBranch'],
                    [$class: 'CleanBeforeCheckout']], 
                    submoduleCfg: [], userRemoteConfigs:  [
                    [refspec: "refs/pull-requests/${prNumber}/from:pr/${prNumber}", 
       credentialsId: "${credentialId}",url: "${cloneurl}"]]])