Georgii Oleinikov
Georgii Oleinikov

Reputation: 3915

Gradle task dependency on subproject

Is there a way to have gradle task depend on the code in one of the sub projects? Let's say I have project structure like so:

app/
  buid.gradle
  ...
myScripts/
  buid.gradle
  ...
settings.gradle
gradlew

I want to add a custom task to build.gradle.kts in myScripts project, which will depend on the classes defined in the app project. Is there a way to do this? My understanding is that because it's a different gradle project this shouldn't add circular dependency, so this should be possible in theory?

For context, I want to add a gradle task that would automatically generate .sql migration files based on the defined JPA entities. In order to do it, I need to load these entity classes and inspect them with reflection, and I can't seem to make them available within the build.gradle.kts

Upvotes: 0

Views: 792

Answers (1)

Simon Jacobs
Simon Jacobs

Reputation: 6463

Yes, certainly it is possible. Here is Gradle's word on the subject.

I suggest the way you go about it is:

  1. Create a new configuration which holds the dependencies needed for your new task in the myScripts project:
configurations {
    register("myConfiguration")
}
  1. Add a dependency on the app sub-project to that configuration:
dependencies {
    add("myConfiguration", project(":app"))
}

The new configuration will then contain the artifacts from the app project (presumably including the JAR containing the .class files you are after).

  1. You can then use it as an input for your new task (Configuration extends FileCollection) defined in a separate class:
open class MyTask : DefaultTask() {
    @InputFiles
    lateinit var fileInputs: FileCollection

    @TaskAction
    fun doSomething() {
        // task code
    }
}
  1. And you must of course also register and configure the task:
tasks.register<MyTask>("myTask") {
   fileInputs = configurations.getByName("myConfiguration")
}

Upvotes: 1

Related Questions