Itai Ganot Itai Ganot - 1 year ago 113
Groovy Question

Groovy: How to define a manipulated string as a variable?

I'm writing a Jenkins pipeline as a code for an Android application.

I have the following strings:

BUILDFLAV = "Staging"

I want to define another variable called artifact_name which will look like:

product_name-BUILDFLAV(in lowercase)-BUILDTYPE(in lowercase).apk

for example:


Since I'm new to groovy i'm not sure that I'm doing it correctly.

I've defined 2 variables:

aa = BUILDFLAV[0].toLowerCase()+BUILDFLAV.substring(1)
bb = BUILDTYPE[0].toLowerCase()+BUILDTYPE.substring(1)

This allows me to change the first char of each string from uppercase to lowercase.

Then, I want the artifact_name variable to look like so:


So I've tried something like that:

artifact_name = "App01-${BUILDFLAV[0]}.toLowerCase()+${BUILDFLAV}.substring(1)+${BUILDTYPE[0]}.toLowerCase()+${BUILDTYPE}.substring(1).apk"

But it throws me an error.

Doing this, however, worked but seems like there's a more elegant way to do that:

BUILDFLAV = "Staging"
aa = BUILDFLAV[0].toLowerCase()+BUILDFLAV.substring(1)
bb = BUILDTYPE[0].toLowerCase()+BUILDTYPE.substring(1)
ARTIFACT_NAME = "App01-${aa}-${bb}.apk"

If you ask yourself why I'm not setting the variables in lowercase from the beginning is because the gradle task which is run in the build is using the first letter uppercase convention and what I'm trying to achieve is related to a more advanced step of the build.

Is it possible to achieve the same result by doing what I did in vars "aa" and "bb" in just one line? like the above example with artifact_name...

Rik Rik
Answer Source

If you want to use templates in strings in groovy, you can put it inside ${..} like you already did. However you need to put everything that needs to be executed inside it.

So use

ARTIFACT_NAME = "App01-${BUILDFLAV[0].toLowerCase()}${BUILDFLAV.substring(1).toLowerCase()-${BUILDTYPE[0].toLowerCase()}${BUILDTYPE.substring(1).toLowerCase()}.apk"`

But please note that it is unnecessary to cast the first char to lowercase and then appending the rest. The next will give the same result

`ARTIFACT_NAME = "App01-${BUILDFLAV.toLowerCase()}-${BUILDTYPE.toLowerCase()}.apk"`

If you for whatever reason want to do it like that anyway, you can use BUILDTYPE[1..-1] instead of BUILDTYPE.substring(1)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download