我正在开发一个gradle插件,当我尝试动态创建任务时,我遇到了问题。
这是我的代码段:
apply plugin: BootstrapPlugin
bootstrapConfig {
basedir = "C:/temp/unzip"
componentList = [
[
zipName: "test1",
zipVersion: "_2",
zipNetworkLocation: "temp",
zipUnpackLocation: "${basedir}"
],
[
zipName: "test2",
zipVersion: "_1",
zipNetworkLocation: "temp",
zipUnpackLocation: "${basedir}"
]
]
}
class BootstrapPlugin implements Plugin<Project> {
void apply(Project project){
project.extensions.create("bootstrapConfig",BootstrapConfigPluginExtension)
project.task("unzipAll", dependsOn: project.tasks.matching { Task task -> task.name.startsWith("unzipSingle")}){
println "DOIT!"
}
project.bootstrapConfig.componentList.each { element ->
project.task "unzipSingle${element.zipName}" (type: Copy) {
def artifactFile = new File(project.bootstrapConfig.shareUrl + "/" + element.zipNetworkLocation + "/" + element.zipName + element.zipVersion + ".zip")
def pathDestination = element.zipUnpackLocation + "/" + element.zipName + element.zipVersion
def touchFileName = pathDestination + "/" + element.zipName + element.zipVersion + ".pid"
from project.zipTree(artifactFile)
into pathDestination
}
}
}
}
class BootstrapConfigPluginExtension {
String basedir
def componentList = []
}
当我尝试运行它时,问题是我尝试创建的任务中没有任何一个存在。运行unzipAll
它只运行该任务,因为它不依赖于其他任务。
我做错了什么?
答案 0 :(得分:4)
这是怎么回事:
apply plugin: BootstrapPlugin
已执行。BootstrapPlugin
被应用时bootstrapConfig
关闭尚未解析。由于它没有被解析BootstrapPlugin
对配置一无所知并且迭代空集合。bootstrapConfig
闭包现在解析它没用了。解决方案是在afterEvaluate
块中创建动态任务:
apply plugin: BootstrapPlugin
bootstrapConfig {
basedir = 'C:/temp/unzip'
shareUrl = 'http://lol.com'
componentList = [
[
zipName: "test1",
zipVersion: "_2",
zipNetworkLocation: "temp",
zipUnpackLocation: "${basedir}",
],
[
zipName: "test2",
zipVersion: "_1",
zipNetworkLocation: "temp",
zipUnpackLocation: "${basedir}",
],
]
}
class BootstrapPlugin implements Plugin<Project> {
void apply(Project project){
project.extensions.create('bootstrapConfig', BootstrapConfigPluginExtension)
project.afterEvaluate {
project.task("unzipAll", dependsOn: project.tasks.matching { Task task -> task.name.startsWith("unzipSingle")}){
println "DOIT!"
}
project.bootstrapConfig.componentList.each { element ->
project.task("unzipSingle${element.zipName}",type: Copy) {
def artifactFile = new File(project.bootstrapConfig.shareUrl + "/" + element.zipNetworkLocation + "/" + element.zipName + element.zipVersion + ".zip")
def pathDestination = element.zipUnpackLocation + "/" + element.zipName + element.zipVersion
def touchFileName = pathDestination + "/" + element.zipName + element.zipVersion + ".pid"
from project.zipTree(artifactFile)
into pathDestination
}
}
}
}
}
class BootstrapConfigPluginExtension {
String basedir
String shareUrl
def componentList = []
}
现在任务确实存在且可以运行,但是它们不会与gradle tasks
一起列出。
Here是演示。