Internally expose required import statements

Hi,

Is there a way to internally add/expose import statements when a Plugin is applied instead of requesting the user to explicitly writing them in their build script? At least for specific packages that should be exposed by default for the plugin.

For example, I am developing a plugin in Java that provides several tasks. An example task might be org.compay.project.task.myTask.java. To be able to invoke my tasks after applying my plugin in the build.gradle script (plugins { id 'myplugin' }) I need to call import org.company,project.task.* before invoking any task by their name exclusively (e.g. task(myTask)). Otherwise I need to provide the fully qualified name for the task (e.g. task(org.compay.project.task.myTask)).

Is it possible to expose the required or main imports from the plugin application? Is this recommended?

Thanks

Some plugins do this by creating a property on the project whose value is the task class. For example, https://github.com/nebula-plugins/gradle-ospackage-plugin/blob/master/src/main/groovy/com/netflix/gradle/plugins/rpm/RpmPlugin.groovy#L34

Hi Chris,

Thanks for your reply.

I tried the following in the apply method of the Plugin

project.getProperties().put("MyTask", MyTask.class);

but it seems that the put method is not happy taking classes as property values. It didn’t work either passing the fully qualified class as a string value. Any ideas?

Try this:

project.getExtensions().getExtraProperties().set( "MyTask", MyTask.class )
1 Like

Thank you! It worked :slight_smile:

Note that this will only work in Groovy Gradle scripts. It won’t in Kotlin Gradle scripts.

Allowing plugins to contribute to the script default imports would be more correct and interoperable. It sounds like an good feature request. @beatrizsanchez, could you please open an issue ?

1 Like

Done: https://github.com/gradle/gradle/issues/7557

1 Like