我有一个在运行时创建的 gradle 任务,用于调用另一个位于单独 gradle 文件中的任务(“myOtherTask”)。问题是,如果该其他任务不存在,则会引发异常。是否可以在尝试调用之前检查任务是否存在于外部 gradle 文件中?
例子:
task mainTaskBlah(dependsOn: ':setupThings')
task setupThings(){
//...
createMyOtherTask(/*...*/)
//...
}
def createMyOtherTask(projName, appGradleDir) {
def taskName = projName + 'blahTest'
task "$taskName"(type: GradleBuild) {
buildFile = appGradleDir + '/build.gradle'
dir = appGradleDir
tasks = ['myOtherTask']
}
mainTaskBlah.dependsOn "$taskName"
}
最佳答案
您可以检查任务是否存在。例如,如果我们想模拟这一点,我们可以通过命令行属性触发任务创建
apply plugin: "groovy"
group = 'com.jbirdvegas.q41227870'
version = '0.1'
repositories {
jcenter()
}
dependencies {
compile localGroovy()
}
// if user supplied our parameter (superman) then add the task
// simulates if the project has or doesn't have the task
if (project.hasProperty('superman')) {
// create task like normal
project.tasks.create('superman', GradleBuild) {
println "SUPERMAN!!!!"
buildFile = project.projectDir.absolutePath + '/build.gradle'
dir = project.projectDir.absolutePath
tasks = ['myOtherTask']
}
}
// check if the task we are interested in exists on the current project
if (project.tasks.findByName('superman')) {
// task superman exists here we do whatever work we need to do
// when the task is present
def supermanTask = project.tasks.findByName('superman')
project.tasks.findByName('classes').dependsOn supermanTask
} else {
// here we do the work needed if the task is missing
println "Superman not yet added"
}
然后我们可以很容易地看到两个用例
$ ./gradlew -q build -Psuperman
SUPERMAN!!!!
$ ./gradlew -q build
Superman not yet added
关于gradle - 确定任务是否在外部 build.gradle 文件中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41227870/