Skip to content

Instantly share code, notes, and snippets.

@vStone
Created April 14, 2015 08:58
Show Gist options
  • Save vStone/660e045938cd9b19907d to your computer and use it in GitHub Desktop.
Save vStone/660e045938cd9b19907d to your computer and use it in GitHub Desktop.
Jenkins groovy script which lists remote tags.
/*** BEGIN META {
"name": "List GIT TAGS",
"comment": "You can use this to fill up a dynamic list parameter with tags. Optionally, you can filter the tags to show. You can include a fallback branch as ALWAYS_INCLUDE like 'develop'",
"parameters": [ 'FILTER', 'REMOTE', 'ALWAYS_INCLUDE' ],
"core": "1.580",
"authors": [
{ name : "Jan Vansteenkiste" }
]
} END META**/
def origin
// Small hack to deal with a empty default value for REMOTE.
if (binding.variables.get('REMOTE') == null) {
origin = ""
}
else {
origin = REMOTE
}
def filter
if (binding.variables.get('FILTER') == null) {
filter = ".*"
}
else {
filter = FILTER
}
def always_include
if (binding.variables.get('ALWAYS_INCLUDE') == null) {
always_include = null
}
else {
always_include = ALWAYS_INCLUDE
}
import hudson.model.*
import java.util.regex.Pattern
// Compile the regex patern for the provided FILTER
def pattern = Pattern.compile(filter)
// Get the current jenkins job.
def jenkinsJob() {
def threadName = Thread.currentThread().getName()
def pattern = Pattern.compile("job/(.*)/build")
def matcher = pattern.matcher(threadName); matcher.find()
def jobName = matcher.group(1)
def jenkinsJob = Hudson.instance.getJob(jobName)
}
// Gets the GIT remote (lists configured scms and takes the first one)
def gitRemote(name) {
if (name == "" || name == null) {
def urls = jenkinsJob().scm.userRemoteConfigs.collect {
v -> v.url
}
def url = urls[0]
}
else {
def urls = jenkinsJob().scm.userRemoteConfigs.findAll {
v -> v.name == name
}
def url = urls[0].url
}
}
def remote_url = gitRemote(origin)
def command = [ "/bin/bash", "-c", "git ls-remote --tags " + remote_url + " | awk '{print \$2}' | grep -v '\\^{}\$' | sort -r -V | sed 's@refs/tags/@@'" ]
def process = command.execute();
process.waitFor()
def result = process.in.text.tokenize("\n")
def tags = []
if (always_include != null && always_include != "") {
tags.add(always_include)
}
for(i in result) {
if (pattern.matcher(i).matches()) {
tags.add(i)
}
}
return tags
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment