gradle - 确定任务是否在外部 build.gradle 文件中定义

标签 gradle groovy

我有一个在运行时创建的 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/

相关文章:

android - ateUpload到Bintray错误:app:compileDebugUnitTestJavaWithJavac

gradle - 如何在不修改 settings.gradle 的情况下添加 gradle 项目依赖项

Docker 标签在 Bitbucket 管道中的步骤之间丢失

groovy - 带有多个变量的常规 switch case 语句

grails - 在Grails中,有没有一种好的方法可以使用Joda time模拟当前时间?

android - 更改android API的正确方法

syntax - 列表上的 Groovy 点符号

java - Grails 属于,我应该吗?

Groovy 闭包、def 与类型化返回值

regex - 如何在groovy/gradle中使用正则表达式替换csv中的文本?