Created
March 15, 2015 19:17
-
-
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.
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
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