Can gradle extensions handle lazy evaluation of a property?

前端 未结 2 884
执笔经年
执笔经年 2021-02-02 14:57

I\'m writing a custom gradle plugin to handle some vaguely complicated work and I have run into a frustrating problem while using properties to configure some of the tasks that

相关标签:
2条回答
  • 2021-02-02 15:30

    The answer by Peter in my question here indicates that conventionMapping feature will definitely go away. It's best to avoid it.

    Using afterEvaluate to solve the deferred configuration issue has made my code a lot cleaner than the conventionMapping approach.

    class MyPlugin implements Plugin<Project> {
        void apply(Project project) {
            project.extensions.create('myPluginProps', MyPluginExtension)
    
            project.afterEvaluate {
                project.task(type: MyTask, 'thisTaskWorksIncorrectly') {
                    input = project.myPluginProps.message
                }
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-02 15:41

    EDIT

    The below answer is now outdated. Since I provided it a better mechanism than convention mappings has been introduced for doing this called lazy properties.


    The usual solution for this problem is to use convention mapping:

    class MyPlugin implements Plugin<Project> {
        void apply(Project project) {
           project.extensions.create('myPluginProps', MyPluginExtension)
    
            project.task(type: MyTask, 'thisTaskWorksIncorrectly') {
                conventionMapping.input = { project.myPluginProps.message }
            }
        }
    }
    

    and then in the task:

    class MyTask extends DefaultTask {
        def String input
    
        @TaskAction
        def action() {
            println "You gave me this: ${getInput()}"
        }
    

    }

    Please note that I explicitly used getter for input - the convention mapping won't kick in if you reference the field directly.

    0 讨论(0)
提交回复
热议问题