How to get $ project.version in a custom Gradle plugin?

As part of the custom gradle plugin, project.version will always be unspecified . Why and how to extract project.version into a custom plugin (class)?

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 

Also, how would I really like to know why?

+7
source share
3 answers

You set the property after calling apply

If you move

 version = "1.0.0" 

To line

 apply plugin: MyPlugin 

He should work

Edit

After Peter's answer , you can see that this also works:

 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') { project.gradle.projectsEvaluated { println "In plugin: $project.version" } } } } 

To defer evaluation of $project.version until build evaluation is complete

+9
source

Working with evaluation order is a challenge when writing plugins, and this requires knowledge and experience.

Please note that in the script assembly the plugin is applied (and therefore executed!) Before the version is installed. This is the norm, and the plugin must handle this. Roughly speaking, whenever a plugin accesses a mutable property of the Gradle object model, it must defer this access until the end of the configuration phase. (Until then, the value of the property may still change.)

Some of the Gradle APIs (lazy collections, methods that receive callbacks, etc.) provide special support to solve this problem. In addition, you can wrap the affected code in project.gradle.projectsEvaluated { ... } or use the more sophisticated technique of mapping symbols.

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

+5
source

Check out my answer here

You can put this block after the project is completed. Close or close after closing. I have not tested just purely standalone, but it can work.

 AppExtension android = (AppExtension) project.extensions.findByName("android") String versionName = android.defaultConfig.versionName String versionCode = android.defaultConfig.versionCode 
0
source

All Articles