Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy Switch statement with list of values

I want to use Switch statement in Jenkins pipeline job.

def version = "1.2"
switch(GIT_BRANCH) {
  case "develop":
    result = "dev"
    break
  case ["master", "support/${version}"]:
    result = "list"
    break
  case "support/${version}":
    result = "sup"
    break
  default:
    result = "def"
    break
}
echo "${result}"

When GIT_BRANCH is equal to:

  • develop - returned value is dev - OK
  • master - returned value is list - OK
  • support/1.2 - returned value is sup - why not list?
like image 379
Maciej Szymonowicz Avatar asked Aug 10 '16 19:08

Maciej Szymonowicz


1 Answers

My guess is that the type of GIT_BRANCH is a String whereas "support/${version}" is a GString. If you convert the latter to a String it should work:

def version = "1.2"
switch(GIT_BRANCH) {
  case "develop":
    result = "dev"
    break
  case ["master", "support/${version}".toString()]:
    result = "list"
    break
  case "support/${version}":
    result = "sup"
    break
  default:
    result = "def"
    break
}
echo "${result}"

The difference between the two string types doesn't matter when comparing them to each other, but it can matter for other types of comparison, e.g. in your code you're implicitly comparing a GString with the elements of a List.

like image 153
Dónal Avatar answered Oct 21 '22 22:10

Dónal