Skip to content

Instantly share code, notes, and snippets.

@louis89
Created March 15, 2015 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save louis89/f3136c79c9367320e86b to your computer and use it in GitHub Desktop.
Save louis89/f3136c79c9367320e86b to your computer and use it in GitHub Desktop.
A Groovy script to automatically set a Jenkins build's description to the title of the pull request that triggered the build. Works with GitHub and Bitbucket.
import groovy.json.JsonSlurper
def build = Thread.currentThread().executable
def workspace = new File(build.workspace.getRemote())
def repositoryMatcher = "git config --get remote.origin.url".execute(null, workspace).text =~ /.+?(bitbucket.org|github.com)(?::|\/)(.*?).git$/
def pullIdMatcher = "git log ${build.getEnvironment()["GIT_COMMIT"]} --merges --oneline -n 1".execute(null, workspace).text =~ /pull request #(\d+)/
if (!pullIdMatcher) {
println "Could not find pull request for commit '${build.getEnvironment()["GIT_COMMIT"]}'."
return
}
def serviceApiUrl
switch(repositoryMatcher[0][1]) {
case "bitbucket.org":
serviceApiUrl = "https://api.bitbucket.org/2.0/repositories/${repositoryMatcher[0][2]}/pullrequests/${pullIdMatcher[0][1]}"
break;
case "github.com":
serviceApiUrl = "https://api.github.com/repos/${repositoryMatcher[0][2]}/pulls/${pullIdMatcher[0][1]}"
break;
default:
println "Unknown SCM service '${repositoryMatcher[0][1]}'."
return
}
println "Loading pull request from '${serviceApiUrl}'."
def conn = serviceApiUrl.toURL().openConnection()
if(binding.variables.username && binding.variables.password) {
def authString = "${binding.variables.username}:${binding.variables.password}".getBytes().encodeBase64().toString()
conn.setRequestProperty("Authorization", "Basic ${authString}")
}
def pullRequestTitle = new JsonSlurper().parseText(conn.content.text).title
println "Setting build description to pull request title '${pullRequestTitle}'."
build.setDescription(pullRequestTitle)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment