Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a task is defined in an external build.gradle file

Tags:

gradle

groovy

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?

Example:

  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"
}
like image 492
Ben Avatar asked Dec 19 '16 17:12

Ben


1 Answers

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
like image 129
JBirdVegas Avatar answered Oct 23 '22 11:10

JBirdVegas