Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gradle get value from extension (pass as input to task)

Tags:

plugins

gradle

I have following code in my plugin:

    @Override
    void apply(Project project) {

        project.extensions.create(EXTENSION,TestExtension)

        project.task("task1") << {
            println "Task 1"
            println(project.mmm.test)
            def extension = project.extensions.findByName(EXTENSION)
            println(extension.test)
        }

        project.task("task2",type: TestTask) {
            println "Task 2 "
            def extension = project.extensions.findByName(EXTENSION)
//            conventionMapping.test = {extension.test}
//            println(project.extensions.findByName(EXTENSION).test)
//            test = "test"

        }
    }

In task 1 extension.test return correct value. However in task2 extension.test always return null. What I am doing wrong? Is there a better way to pass some of the extensions values as input for task? I am using gradle 1.12 with jdk 1.8 on Mac. Best Regards

Edit :correct version:

   project.task("task2", type: TestTask) {
        project.afterEvaluate {
            def extension = project.extensions.findByName(EXTENSION)
            println(project.extensions.findByName(EXTENSION).test)
            test = project.extensions.findByName(EXTENSION).test
        }
    }
like image 346
John Avatar asked Sep 02 '25 04:09

John


1 Answers

task1 prints the value at execution time (notice the <<), task2 at configuration time (before the rest of the build script after the apply plugin: ... has been evaluated). This explains why the println for task1 works as expected, and the println for task2 doesn't.

However, configuring a task at execution time is too late. Instead, a plugin needs to defer reading user-provided values until the end of the configuration phase (after build scripts have been evaluated, but before any task has been executed). There are several techniques for doing so. One of the simpler ones is to wrap any such read access with project.afterEvaluate { ... }.

like image 86
Peter Niederwieser Avatar answered Sep 04 '25 23:09

Peter Niederwieser