Skip to content

Instantly share code, notes, and snippets.

@suclike
Last active October 19, 2015 09:13
Show Gist options
  • Save suclike/7a4d2320cad08b1a634c to your computer and use it in GitHub Desktop.
Save suclike/7a4d2320cad08b1a634c to your computer and use it in GitHub Desktop.
Get list of branches within groovy on Jenkins. /** On first run, text field should be set as 'Editable' and branch name e.g. 'master' should be entered manually; then list will be fetched **/
import jenkins.model.*
import jenkins.model.Jenkins
import hudson.model.User
import hudson.security.Permission
import hudson.EnvVars
BUILD_JOB_NAME = "APK_TEST"
def jobWorkspace (String jobName) {
jenkins.model.Jenkins.instance.getJob(jobName).getWorkspace()
}
def showbranches(cmd) {
def proc = cmd.execute(null, new File(jobWorkspace(BUILD_JOB_NAME).toURI()))
def sb = new StringBuffer()
proc.waitForProcessOutput(sb, sb)
def cod = proc.exitValue()
if (cod != 0)
throw new Exception("Error ${cod} when invoking '${cmd}':\n${sb}")
sb.toString()
}
showbranches("git fetch --all")
showbranches("git remote prune origin")
def re = ~ /->/
List<String> branches = showbranches("git branch -r")
.tokenize("\n")
.grep({!re.matcher(it).find()})
.collect(){it.replace("origin/", "").trim()}
.collect()
branches
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment