I have a requirement to set some property in Jenkinsfile based on multiple branches. Currently i am using below lines of code to do this task:
if (BranchType == 'dev') {
env.ID='env123'
} else if (BranchType == 'beta') {
env.ID='envbeta12'
} else if (BranchType == 'rel') {
env.ID='envrel45'
} else {
env.ID='test'
}
I wonder, is there any other smart way to handle this scenario?
What you have is the most flexible form of it, but if you are absolutely sure you will only ever need to match strings:
def mapBranchToId = [
'dev': 'env123',
'beta': 'envbeta12',
'rel': 'envrel45',
]
env.ID = mapBranchToId.get(branchType) ?: 'test'
Maybe make it into a function to keep the map and the default value close. Or maybe use switch
if you expect to match regular expressions in the future:
def mapBranchToId(branchType) {
switch(branchType) {
case 'dev':
return 'env123'
case 'beta':
return 'envbeta12'
case 'rel':
return 'envrel45'
default:
return 'test'
}
}