Variabalize the baseName property for distributions


#1

I need to have a gradle script that is zipping up some files, and calling the distributions task. I’m running into an issue either passing in a variable for the basename/version or exporting those values to the main gradle file to reference elsewhere.

In the below example, how do I either pass in a variable for the baseName & version values from the main gradle script, or set them to strings to send outside of the task for use in, say the uploadArchives task?

apply plugin: 'distribution'

distributions {
    main {
        baseName = '$fileName'
        version = '$majorVersion'
        contents {
            from { 'src/readme' }
        }
    }
}

(James Justinic) #2

If you have the variables fileName and majorVersion defined in your build script, you should either use the variable directly (i.e. baseName = fileName) or use double quotes (i.e. baseName = "$fileName"). In your example, single quotes will take the String literally (i.e. base name is $fileName).


#3

Thanks jjustinic, that seems to have done the trick. I did have fileName and majorVersion defined, but I was using single quotes to call them.
It is confusing me though, that I can call a variable without any leading character and in several different ways. What is the best practice for this?

If fileName = test.zip:
baseName = fileName would output test.zip
baseName = “$fileName” would output test.zip
baseName = ‘$fileName’ would output $fileName…?
baseName = ${fileName} would output test.zip…?
baseName = ‘${fileName}’ would output test.zip?


(James Justinic) #4

The build.gradle file is written in Groovy. Java and Groovy don’t require anything special to reference a variable, i.e. for variable counter:

int counter = 0;
counter++;
System.out.println(counter);

Single quotes are a regular Java String. It’s literally the characters it contains. Variables are not relevant.

Double quotes are interpolated as a Groovy GString. Using $ in $fileName causes the expression to be evaluated rather than treated as literal characters. This can also be written as ${fileName}. Using the ${...} notation allows for any expression, but the {}'s can be omitted for a simple dotted expression like a variable.

Do whatever is most readable to you. For consistency, I use ${} exclusively, so I always prefer "${fileName}" over "$fileName". There’s no reason to use the interpolated string version though unless you’re doing something with the value other than just assigning it, like appending, i.e. absolutePath = "/path/to/${fileName}"