pipelineUtils/vars/addVersionFromNexusRepo.groovy
2024-02-07 22:40:59 -08:00

87 lines
2.3 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
*/
// Define the enum
enum BuildNumFlags {
IS_COMMITS_SINCE_TAG,
IS_JOB_BUILD_NUMBER,
IS_FROM_QUERY
}
Map call(Map config = [:]) {
def defaults = [
nexusBase: 'https://repo.thejimnicholson.com',
searchAPI: 'service/rest/v1/search',
buildFlag: BuildNumFlags.IS_FROM_QUERY,
queryParams: [
repository: 'tools',
sort: 'name',
name: 'tests/test-something*'
]
]
Map runConfig = defaults + config
nexusURL = runConfig.nexusBase + '/' + runConfig.searchAPI
nexusSearch = buildUrlWithQueryParams(nexusURL, runConfig.queryParams)
response = httpRequest acceptType: 'APPLICATION_JSON',
contentType: 'APPLICATION_JSON',
url: nexusSearch,
wrapAsMultipart: false
body = response.content
assets = readJSON text: body
latest = assets.items.last()
version = latest.version
if (version == 'null') {
matches = (latest.name =~ /.*-([0-9\.]+)-([0-9]+)\.)[0]/)[0]
version = matches[1]
query_build = matches[2]
}
switch (runConfig.buildFlag) {
case BuildNumFlags.IS_COMMITS_SINCE_TAG:
build = sh(
script: 'git rev-list $(git tag | tail -1).. --count',
returnStdout: true
).trim()
break
case BuildNumFlags.IS_JOB_BUILD_NUMBER:
build = env.BUILD_NUMBER
break
case BuildNumFlags.IS_FROM_QUERY:
build = query_build
break
default:
build = query_build
break
}
runConfig.nexusQuery = nexusSearch
runConfig.latestVersion = version
runConfig.latestBuild = build
return runConfig
}
/* 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
}