gradle

Stop execution of finalizedBy task, or only execute follow-up task on a condition


I'm using the com.google.cloud.tools.appengine gradle plugin, which has a task appengineDeploy.

I have two tasks that configure the appengineDeploy task before executing it. My current solution looks something like that:

task deployTest() {
    doFirst {
        appengine.deploy {
            version = 'test'
            ...
        }
    }
    finalizedBy appengineDeploy
}


task deployProduction() {
    doFirst {
        appengine.deploy {
            version = '7'
            ...
        }
    }
    finalizedBy appengineDeploy
}

Now I wanted to add a security question before the deployProduction task is executed, like this:

println "Are you sure? (y/n)"
def response = System.in.newReader().readLine()
if (response != 'y') {
    throw new GradleException('Task execution stopped')
}

The problem is, by defintion the finalizedBy task is executed even if my task throws an exception, and that is exactly the opposite of what I want.

I can't change it to appengineDeploy dependsOn deployTest and call appengineDeploy as I have two tasks with different configuration.
And I can't change the appengineDeploy task as it comes from a plugin.

Is there any other way I can either stop the execution of appengineDeploy, or use something other than finalizedBy to execute that task after my deploy task?


Solution

  • I modified the answer from thokuest a bit (thanks for the help!), to prevent executing any tasks inbetween.
    I created it as extension method since I needed it more than once:

    ext.securityQuestion = { project, task ->
      println "Are you sure you want to execute ${project.name}:${task.name}? (y/n)"
      def response = System.in.newReader().readLine()
    
      if (response != 'y') {
        project.tasks.each {
          if (it != task)
            it.enabled = false
        }
        throw new GradleException("Execution of ${project.name}:${task.name} aborted")
      }
    }
    

    and my task now looks like this:

    task deployProduction() { task ->
      doFirst {
        securityQuestion(this, task)
      }
    
      finalizedBy appengineDeploy
    }