75 lines
2.4 KiB
Groovy
75 lines
2.4 KiB
Groovy
#!/usr/bin/env groovy
|
|
|
|
/*
|
|
Calculate the current version by querying a list of assets in a Nexus Repository.
|
|
Return '0.0.1' if there are no matching assets.
|
|
|
|
Jenkins Plugin dependencies:
|
|
|
|
- HTTP Request
|
|
- Plugin Utilty Steps
|
|
|
|
*/
|
|
|
|
Map call(Map config = [:], Map queryParams = [:]) {
|
|
Map defaults = [
|
|
searchAPI: 'service/rest/v1/search'
|
|
]
|
|
|
|
Map queryParamsDefaults = [
|
|
sort: 'name'
|
|
]
|
|
|
|
Map runConfig = defaults + config
|
|
queryParamsDefaults.name = runConfig.nexusRepoPath + '/' + runConfig.name + '*'
|
|
queryParams.repository = runConfig.nexusRepository
|
|
Map query = queryParamsDefaults + queryParams
|
|
|
|
String version
|
|
|
|
nexusURL = runConfig.nexusBase + '/' + runConfig.searchAPI
|
|
nexusSearch = buildUrlWithQueryParams(nexusURL, query)
|
|
|
|
response = httpRequest acceptType: 'APPLICATION_JSON',
|
|
contentType: 'APPLICATION_JSON',
|
|
url: nexusSearch,
|
|
wrapAsMultipart: false
|
|
|
|
body = response.content
|
|
assets = readJSON text: body
|
|
if (assets.items && !assets.items.isEmpty()) {
|
|
latest = assets.items.last()
|
|
/* We have to use instanceof here. The value SHOULD be null, but it comes back
|
|
as class rather than null. This is probably a bug in the Pipeline Utilities
|
|
plugin. */
|
|
/* groovylint-disable-next-line Instanceof */
|
|
if (latest.version instanceof net.sf.json.JSONNull && latest.name) {
|
|
echo 'Info: Search result version field was null, looking in name field for a version'
|
|
java.util.regex.Matcher match = (latest.name =~ /(?<=-)(\d+\.\d+\.\d+)(?=[\.-].*)/)
|
|
if (!match) {
|
|
echo "Error: Match: ${match}"
|
|
error("Regular expression match failed for latest.name: ${latest.name}")
|
|
}
|
|
version = match[0][1]
|
|
} else if (latest.version) {
|
|
version = latest.version
|
|
}
|
|
} else {
|
|
version = '0.0.0'
|
|
echo 'Info: No matching assets found, assuming this is the first version.'
|
|
}
|
|
return version
|
|
}
|
|
|
|
/* groovylint-disable-next-line MethodParameterTypeRequired, NoDef */
|
|
String buildUrlWithQueryParams(baseUrl, queryParams) {
|
|
url = baseUrl
|
|
if (!queryParams.empty) {
|
|
queryParamsString = queryParams.collect { key, value ->
|
|
"${URLEncoder.encode(key, 'UTF-8')}=${URLEncoder.encode(value, 'UTF-8')}"
|
|
}.join('&')
|
|
url += '?' + queryParamsString
|
|
}
|
|
return url
|
|
}
|