Reputation: 5232
In my application I maintain the 'user-frendly' version as a public String constant in the main class.
Is it possible to retrieve this variables in the build.gradle to set the version property of the project? Currently I have to do this manually, what of course can lead to problems.
Upvotes: 0
Views: 1740
Reputation: 15623
I've plussed Nikita's answer, which is great.
But, firstly, File.toURL()
is now deprecated. Something like this would be preferable:
ConfigObject conf = new ConfigSlurper().parse( file("src/main/resources/version.properties").toURI().toURL());
Secondly, note file( ...
here, not if this line is to be included in new File( ...
build.gradle
. The former makes a File
relative to the path of the root directory of your Gradle project and is in fact a method of Gradle interface Project. It's worth knowing that every method or property in build.gradle
which appears to "come from nowhere" is in fact a method or property of an underlying, "invisible" Gradle Project
instance.
If you put new File( "src/main... ")
in build.gradle
as in Nikita's answer you would in fact not notice any problems if running your Gradle task from a console with current directory the project/root directory... but (according to my experiments) if using the GradleTasks window in Eclipse, for example, you would then be creating a File
path relative to the directory where Eclipse was running from... and this would give an error message saying "system cannot find the path specified".
Using file( ...
, therefore, you can then go (in build.gradle
):
version = conf.versionNumber
NB version
here is another property of Project... but you'll be mystified if you look at the above Javadoc for Project
, because it's not there! However, you will see getVersion()
and setVersion(...)
. With Groovy every property automatically gets given, by Groovy magic, its own getter and setter method. I took a week out to learn a bit of Groovy, which is actually a fantastic language, and familiarising yourself with it a bit is highly recommended, and makes the learning curve of Gradle substantially less painful.
You can however find the version
property in the DSL (domain-specific language) API for Gradle class Project
here.
The file version.properties
would typically contain something like this:
versionNumber='1.0.0'
NB accessing version from your code ... if you wanted to access this version number from your app code (or test code), you would indeed use new File( ...
:
ConfigObject conf = new ConfigSlurper().parse( new File("src/main/resources/version.properties").toURI().toURL());
as in Nikita's answer.
Upvotes: 1
Reputation: 4923
Correct way of maintaining "user-friendly" version would be version.properties
file, stored in your source tree. E.g., under src/main/resources
. Then you can load this properties file in Gradle script:
def config = new ConfigSlurper().parse(new File("src/main/resources/version.properties").toURL())
println(config.versionNumber)
Upvotes: 3