0
votes

I have a Groovy application that I build with Gradle. As usual I have defined the application version number/string in the build.gradle script.

Now I want to use that version string within the Groovy application, as hard-coded static piece of information. For example as a final static member in the main application class:

class MyApp {
    final static APP_VERSION = "0.1"
}

Since the version information comes from the build.gradle script, that Groovy class member above needs to be set by Gradle before the sources are compiled.

In other words: I need a Gradle task that allows me to set the value of a variable in the Groovy sources, before they are built by Gradle. I could for search for that value via regular expression and replace it in the Groovy source file, but that feels a bit clunky.

Any "best practice" ideas how to achieve that?

1
Does the class contain anything except the version? Is there some reason you can't write read it from a properties file? - Dylan Bijnagte
@DylanBijnagte: I want to hard-code the version, but not read it from a file at runtime. And yes, the class does contain other code beside this version attribute. - Matthias
If the file was minimal I would say template it, otherwise I think you may be stuck with the regex solution. - Dylan Bijnagte
How bout creating a MyAppVersion class file with only this value in it. MyApp references MyAppVersion but you wholesale replace MyAppVersion with the Gradle build before it compiles. No need for regexp then. - Todd W Crone
@ToddWCrone: Hmmm... I guess that is a nice approach, thanks. - Matthias

1 Answers

0
votes

i can't give you final solution, but, i think, you should look at AST Transformations

Another option, if you pack the application in jar / war, - you can get a version of the application from the manifest file (but it will not work if you are starting app from IDE)

final static versin = MyApp.class.getPackage().getSpecificationVersion()