Itai Ganot Itai Ganot - 25 days ago 12
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"
BUILDTYPE = "Debug"


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

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


for example:

App01-staging-debug.apk


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:

App01-$(aa}-${bb}.apk


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"
BUILDTYPE = "Debug"
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

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)

Comments