Where to put generated java or kotlin source when creating a gradle plugin?

1.6k views Asked by At

I'm not quite sure about this - there's usually a directory under /build/generated, but I'm wondering if there is a standard location that's safe to write source files to which also will be included in the compilation? Environment variables? I couldn't find anything in the docs.

If it matters, this use case is a single kotlin file which I generate as a separate task based off of configs and want to include in java/kotlin compilation.

2

There are 2 answers

0
LazerBanana On

buildSrc it's a place for custom plugins, and it's a special Gradle folder as well that is read before the build.

As for generated sources, you can just define a source set for it.

sourceSets {
  main {
    java {
      srcDirs = [
        "$projectDir/src/main/java",
        "$projectDir/src/main/generated",
      ]
      include '**/*.java'
    }
  }
}
0
Vampire On

Configuring a hard-code path manually like @LazerBanana suggests halfway works if you are lucky, but is pretty bad practice.

If you have a task generateMyKotlinFile that properly declares its outputs, just configure that task as srcDir, then you get necessary task dependencies automatically for any task that needs source files like compileKotlin, sourcesJar, ...

kotlin {
    sourceSets {
        main {
            kotlin.srcDir(generateMyKotlinFile)
        }
    }
}

Regarding where to generate the file to, there is no defined standard location. But make sure you do not have overlapping outputs in tasks. Each task should have its dedicated output directory where no other task intervenes. So just configure a unique output direcotry for your generateMyKotlinFile task.