Home > Mobile >  Getting the resource path of the java project from a custom gradle plugin
Getting the resource path of the java project from a custom gradle plugin

Time:09-22

Trying to create a custom gradle plugin in java, how do i get the resources path from inside the task class?

public class MyCustomPlugin implements Plugin<Project> {

  @Override
  public void apply(Project project) {
    project.getTasks().register("doStuff", CustomTask.class);
  }
}
public class CustomTask extends DefaultTask {

  // How do I get java project resources dir from here?
  @Inject
  public CustomTask(ProjectLayout projectLayout) {
    directoryProperty = projectLayout.getBuildDirectory();
  }

  @TaskAction
  public void execute() {
    ...
  }



}

CodePudding user response:

I would recommend to not get the directory inside the task, because the plugin that provides it might not be applied. Instead I would do it from within your plugin that registers the task, this way you can also ensure that the necessary plugin is actually applied. Gradle will display an error if the task is used without a value being assigned to the input that explains that nothing was assigned.

With the kotlin-dsl:

@CacheableTask
abstract class CustomTask : DefaultTask() {
    @get:InputFiles
    abstract val resources: FileCollection
    //...
}

I cannot answer if @InputFiles is the right annotation for your use case, because I don't know what you want to do with the resource. Refer to the Gradle documentation for more information on the available annotations, and what they do.

plugins {
    java
}

tasks.register<CustomTask>("customTask") {
    resources.set(sourceSets.main.map { it.resources })
}

Notice the map {} which ensures that our task has a dependency on the processResources task, this is done automatically for us because we stick to the provider API of Gradle for everything.

Note that the resources are by default in one directory, but they don't have to be. This is why the resources are defined as SourceDirectorySet and not as Provider<Directory>. The same is true for anything that originates from the SourceSetContainer. It is easier to explain with Java source code: imagine you have Java and Kotlin, then you will have src/main/java and src/main/kotlin, hence, 2 directories. The former will have a **/*.java include filter, whereas the latter has a **/*.kt includes filter. If we just want to get all sources then we use sourceSets.main.map { it.java.sourceDirectories }, and if we want to get one of both it gets complicated.

  • Related