我在myplugin.gradle
创建了一个插件:
apply plugin: MyPlugin
class MyPluginExtension {
String srcDir = null
}
class MyTask extends DefaultTask {
@InputFiles FileCollection srcFiles
@TaskAction
def task() {
println srcFiles
}
}
class MyPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
project.with {
project.extensions.create("myConfig", MyPluginExtension)
tasks.create(name: "firstTask", type: MyTask) {
srcFiles = files(fileTree(dir: "mySrcDir", // need to access srcDir
include: "**/*.java"))
}
}
}
}
创建任务时,我需要设置srcFiles
。为此,我需要从插件扩展中访问srcDir
属性。我想将mySrcDir
替换为插件扩展名中指定的srcDir
。
我需要这样设置srcFiles
输入的MyTask
。这必须在任务之外设置,以便gradle可以跟踪任务是否是最新的以及是否有任何源文件已更改。
如何在创建任务期间从项目扩展程序访问属性?
答案 0 :(得分:1)
It's impossible. You need to create extension, use it and then configure the task. Now you create extension and at once use it to configure the task - srcDir
value will be always null. That's the way to go:
apply plugin: MyPlugin
myConfig {
srcDir = 'lol'
}
class MyTask extends DefaultTask {
@InputFiles
FileCollection srcFiles
@TaskAction
def task() {
println srcFiles
}
}
class MyPluginExtension {
String srcDir = null
}
class MyPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
project.extensions.create('myConfig', MyPluginExtension)
project.tasks.create(name: "firstTask", type: MyTask)
}
}
firstTask {
srcFiles = project.files(project.fileTree(dir: project.myConfig.srcDir, include: "**/*.java"))
}