Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get $project.version in Custom Gradle Plugin?

Tags:

gradle

groovy

Within a custom gradle plugin the project.version seems to always be unspecified. Why and how to retrieve the project.version within a custom plugin (class)?

For Example:

apply plugin: 'java'
apply plugin: MyPlugin

version = "1.0.0"

println "In build file: $project.version" 

class MyPlugin implements Plugin<Project> {
  public void apply(Project project) {
    project.task('myTask') {
      println "In plugin: $project.version"
    }
  }
}

Prints out:

%> gradle -q myTask
  In plugin: unspecified
  In build file: 1.0.0

Besides the how I really would like to know the why?

like image 685
jonbros Avatar asked Nov 02 '12 15:11

jonbros


1 Answers

Dealing with evaluation order is the challenge when writing plugins, and it requires some knowledge and expertise to master.

Notice that in the build script, the plugin gets applied (and therefore executed!) before the version is set. This is the norm, and the plugin has to deal with it. Roughly speaking, whenever the plugin accesses a mutable property of the Gradle object model, it has to defer that access until the end of the configuration phase. (Until then, the value of the property can still change.)

Some of Gradle's APIs (lazy collections, methods accepting callbacks, etc.) provide special support for dealing with this problem. Other than that, you can wrap affected code in project.gradle.projectsEvaluated { ... }, or use the more sophisticated "convention mapping" technique.

The Gradle User Guide and http://forums.gradle.org provide more information on these topics.

like image 87
Peter Niederwieser Avatar answered Oct 05 '22 17:10

Peter Niederwieser