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

Ben*_*Ben 5 groovy gradle

我有一个gradle任务,它在运行时创建,用于调用另一个任务("myOtherTask"),该任务位于一个单独的gradle文件中.问题是如果不存在其他任务,则抛出异常.在尝试调用之前,是否可以检查外部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"
}
Run Code Online (Sandbox Code Playgroud)

JBi*_*gas 9

您可以检查任务是否存在.例如,如果我们想要模拟这个,我们可以通过命令行属性触发任务创建

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"
}
Run Code Online (Sandbox Code Playgroud)

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

$ ./gradlew -q build -Psuperman
SUPERMAN!!!!
$ ./gradlew -q build
Superman not yet added
Run Code Online (Sandbox Code Playgroud)