确定是否在外部build.gradle文件中定义了任务 [英] Determine if a task is defined in an external build.gradle file

查看:65
本文介绍了确定是否在外部build.gradle文件中定义了任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个gradle任务,该任务在运行时创建,以调用另一个任务(位于"myOtherTask")中,该任务位于单独的gradle文件中.问题是如果其他任务不存在,则会引发异常.可以在尝试调用外部gradle文件之前检查它是否存在?

I have a gradle task that is created at runtime to call another task ("myOtherTask") which is in a separate gradle file. The problem is if that other task doesn't exist an exception will be thrown. Is it possible to check that a task exists in an external gradle file before attempting to call it?

示例:

  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"
}

推荐答案

您可以检查任务是否存在.例如,如果我们要模拟这一点,我们可以使任务创建由命令行属性触发

You can check if the tasks exists. For example if we wanted to simulate this we could make the task creation triggered by a command line property

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"
}

然后我们可以很容易地看到这两种用例

Then we can see both uses cases rather easily

$ ./gradlew -q build -Psuperman
SUPERMAN!!!!
$ ./gradlew -q build
Superman not yet added

这篇关于确定是否在外部build.gradle文件中定义了任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆