Fail a task if another task has not been run

(Eero Aaltonen) #1

We have a primary compilation task that does not have a clean way of checking if it’s up-to-date and a duration of about 40 mins. We have some supplementary tasks that depend on the outputs of the primary compilation task. We do not want to automatically run the first task because of the long duration. I came up with the below approach, but would like to know if there’s a recommended way to handle this kind of case.

task second() {
    doLast {
        if (! file('created_by_primary').exists()) {
            def errMessage = 'My error'
            logger.error(errMessage)
            throw new Exception(errMessage)
        }
        // actual work in 'second' task
    }
}
second.mustRunAfter first
(Justin) #2

Hi,

I think that approach is fine for a small detail. However if it gets more complicated maybe a concrete task in buildSrc vs just a script task would be the best route. That way you can specify the input file and leverage the Gradle api to do better incremental inspections. The InputFile annotation allows gradle to better analyze if a task needs to be run or not and if the file is missing. The entire task api can be really powerful IF you need more complexity than what you have here.

Example

open class SecondaryTask {
  @InputFile
  val createdByPrimary: RegularFileProperty = project.objects.fileProperty().apply {
    set(File("pathtofile"))
  }

  @TaskAction
  fun execute(incrementalTaskInputs: IncrementalTaskInputs) {
    if(incrementalTaskInputs.isIncremental) {
      return;
    }
    // do work
   }
}

Then just register the task in build script

task second (type: SecondaryTask)
second.mustRunAfter first

If the first task actual has an output then you can actually wire the output into the second task.

second.createdByPrimary.set(first.outputfile)

Info for project.objects object that i am referencing can be found here: https://docs.gradle.org/current/userguide/lazy_configuration.html#sec:lazy_properties

The task api can be found here: https://docs.gradle.org/current/userguide/custom_tasks.html