Way to always perform some code when a task is requested

I am trying to figure out a way to perform some actions whenever a particular task is requested by the build command, regardless of any “short circuit” checks on that task (e.g. UP_TO_DATE).

I have tried adding a doLast action, but that is not triggered if the task is not executed for whatever reason.

My specific use-case is that I am writing a plugin that “augments” a file in the project’s src/test/resources based on a setting. Concretely, this is for the Hibernate build and the setting is the “database profile” to run the tests against. To implement this, we “augment” the ${buildDir}/resources/test/hibernate.properties to apply the profile’s settings (as well as other stuff like expand the testRuntime config). In the optimal case, its like the processTestResources task would be marked dirty whenever this extension (DatabaseProfilesExtension#selectedProfileName) property is changed - almost like adding a new @Input on processTestResources - but I do not know a way to do that.

Any ideas?

Someone pointed me to another thread where the solution was to use finalizedBy. But finalizedBy only works with other tasks - e.g. I’d say processTestResources is finalizedBy my “profile task”.

But ideally I would like to not have a task.

Hey Steve,
have you checked TaskExecutionGraph#afterTask()?

That seems to fit what you’re after. see https://docs.gradle.org/current/javadoc/org/gradle/api/execution/TaskExecutionGraph.html#afterTask-org.gradle.api.Action- for details.

Rene, I’m sure I’m just being dense, but I just cannot see how you tell that method which task you want to do things after

You don’t. The code you provide is called after every task, with the task as an argument. If you only want to do something for a particular task, write a conditional that inspects the task. i.e. the long Java version:

project.getGradle().getTaskGraph().afterTask(new Action<Task>() {
    @Override
    public void execute(Task task) {
        if (task.getName().equals("processTestResources")) {
            // do something
        }
    }
});

Makes sense, thanks James