BuildScript dependencies in external script

I’ve got a master build.gradle, which uses a custom plugin. The plugin does all sorts of things, but it also defines a couple of task classes. To amend the functionality of the plugin, I iterate over all tasks with the specific type:

tasks.withType(my.plugin.Task) {}

I’ve now reached a point where I want to tidy this up a bit, and also re-use some of this logic in another project. It’s not quite ready to become a plugin on its own, so I just want to move this logic into a separate file and use apply from:. However, in the separate file, I cannot access the plugin task definition without adding it as a dependency, including repositories, etc., which leads to more repetition than I save.

So I wonder, is there any non-verbose way to have root gradle dependencies/types exposed to imported scripts, or do I have to move this to buildSrc, or even a plugin?

If I’m understanding your structure, you should be able to use the work-around that some plugin authors use to allow their task types to be used without imports. It works by storing a reference to the class as a property that is accessible across the project. This has the side effect of also working in the separate file that you apply from: in your main script.

I’m using your example task type and taking a liberty with the acceptable name (to avoid using just Task), but I expect your real task has a more meaningful name that would make sense here:

project.extensions.extraProperties.set('MyPluginTask', my.plugin.Task)

This should work in your build script just to try it out (add before you apply from the other script), but if you add it to your custom plugin, that would be optimal so that all consumers automatically take advantage.

Then, you can use tasks.withType(MyPluginTask) {} without needing to fully qualify the task type.

Cool, that worked!