Created
November 6, 2017 14:39
-
-
Save foutoucour/84936210301e293b512f810434092fab to your computer and use it in GitHub Desktop.
Get Real Branch Name in Jenkins during PRs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def getBranchName() { | |
def branchName = env.BRANCH_NAME | |
// if it is a PR, then we need to find back the name of the real branch from the commit. | |
if (branchName.contains("PR-")) { | |
repoUrl = sh(returnStdout: true, script: "echo ${env.CHANGE_URL} | sed 's/pull.*//'").trim() | |
// simulate a git fetch | |
// but stays on the current branch | |
git branch: branchName, credentialsId: 'github_username_password', url: repoUrl | |
// store the current commit | |
gitCommit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim() | |
// find all the remote branches that have the git commit | |
// but it is not the a PR | |
// we tail -1 in case of several remote branches have the same commit. | |
// we don't really care about the name of the branch associated with the commit anyway | |
branchName = sh( | |
returnStdout: true, | |
script: "git branch -a --contains ${gitCommit} | grep -v PR- | sed 's/^.*\\///' | tail -1" | |
).trim() | |
} | |
branchName | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment