How to print something on the console when a task is up-to-date

I have a cache-able task, and I want it to prints a “report” on the console when it has finished.

@CacheableTask
abstract class MuzzlePrintReferencesTask @Inject constructor(
  providers: ProviderFactory,
  objects: ObjectFactory,
) : DefaultTask() {
  // ...
}

Of course when the task is up-to-date, the main task action is not run. Using doLast on this task won;t work as well since it’s part of the task execution phase.

What are my options, if I want to keep the code that print on stdout within MuzzlePrintReferencesTask ?

Forgot to mention my current workaround is :

    project.tasks.register<MuzzlePrintReferencesTask>("printReferences") {
      dependsOn(compileMuzzle)
    }.also {
      val printReferencesTask = project.tasks.register("actuallyPrintReferences") {
        doLast {
          println(it.get().outputFile.get().asFile.readText())
        }
      }
      it.configure { finalizedBy(printReferencesTask) }
    }

But I wonder if there is a better way ?

Well, better probably depends.
You could for example register an operation completion listener that reacts on that task being finished like:

abstract class Foo : DefaultTask() {
    @get:Inject
    abstract val buildEventsListenerRegistry: BuildEventsListenerRegistry

    @get:Inject
    abstract val providers: ProviderFactory

    @get:Input
    abstract val input: Property<String>

    init {
        input.convention("foo")
        outputs.upToDateWhen { true }
        buildEventsListenerRegistry.onTaskCompletion(
            providers.provider {
                object : OperationCompletionListener {
                    override fun onFinish(event: FinishEvent?) {
                        if ((event is TaskFinishEvent) && (event.descriptor.taskPath == path) && (event.result is TaskSuccessResult)) {
                            println("Task $path has finished.")
                        }
                    }
                }
            }
        )
    }

    @TaskAction
    fun execute() {
        println("Task action!")
    }
}

But whether that is nice, … :man_shrugging: :slight_smile:

Interesting approach thanks!

1 Like