Gradle:如何使用扩展属性初始化SourceTask的属性“source”?

时间:2017-10-19 13:26:09

标签: gradle groovy gradle-plugin

我的插件注册了一个扩展和一些继承自<ce-title>的自定义任务。

org.gradle.api.tasks.SourceTask

现在,如果我配置构建脚本:

class MyPlugin implements Plugin<Project> {
    private final Instantiator instantiator
    private final FileResolver fileResolver
    @Inject
    MyPlugin (Instantiator instantiator, FileResolver fileResolver) {
        this.instantiator = instantiator
        this.fileResolver = fileResolver
    }
    void apply(Project project) {
        MyPluginExtension extension = project.extensions.create("myPlugin", MyPluginExtension, project, instantiator, fileResolver)
        project.tasks.create('doSomething', MyCustomTask) {}
    }
}

class MyPluginExtension {
    final MySourceSetContainer source
    MyPluginExtension(Project project, Instantiator instantiator, FileResolver fileResolver) {
        source = instantiator.newInstance(ImplMySourceSetContainer, project, instantiator, fileResolver)
    }
    void source(Closure closure) {
        ConfigureUtil.configure(closure, source)
    }
}

class MyCustomTask extends SourceTask {
    @TaskAction
    void act() {
        // something
    }
}

- 一切正常。但是我希望按myPlugin { source{ main { something { srcDirs "src/main/resources" } } } } doSomething { source = myPlugin.source.main.something.asFileTree } 的值初始化任务属性source

MyPluginExtension

我无法在执行阶段提取扩展属性,如用户指南(https://docs.gradle.org/4.2.1/userguide/custom_plugins.html#sec:mapping_extension_properties_to_task_properties)中所述,因为在超类source = extension.source.findAll().inject(project.files().asFileTree, { result, item -> result + item.html.asFileTree })中声明的source的getter标记有注释{{ 1}}和任务将被跳过。

如何在执行阶段之前使用扩展值初始化任务的属性? THX。

2 个答案:

答案 0 :(得分:0)

我不确定我是否完全理解你在做什么,但你可能会使用一个闭包来推迟评估。见Project.files(Object...)

例如:

doSomething {
    def myClosure = {
        extension.source.findAll().inject(project.files().asFileTree, { result, item -> result + item.html.asFileTree })
    }
    source = files(myClosure)
}

答案 1 :(得分:0)

通过将源init包装在闭包中解决:

class MyPlugin implements Plugin<Project> {
    // ...
    void apply(Project project) {
        MyPluginExtension extension = project.extensions.create("myPlugin", MyPluginExtension, project, instantiator, fileResolver)
        project.tasks.create('doSomething', MyCustomTask) { task ->
            task.source = { 
                extension.source.findAll().inject(new HashSet<File>(), { result, item -> result + item.html.srcDirs }) 
            }
        }
    }
}