Skip to content

Commit 8726a4c

Browse files
committed
feat: register generated sources in Gradle
1 parent 7b393c4 commit 8726a4c

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

docs/topics/gradle/gradle-configure-project.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1367,6 +1367,40 @@ dependencyResolutionManagement {
13671367
Any declared repositories in subprojects override repositories declared centrally. For more information on how to control
13681368
this behavior and what options are available, see [Gradle's documentation](https://docs.gradle.org/current/userguide/declaring_repositories.html#sub:centralized-repository-declaration).
13691369
1370+
## Register generated sources
1371+
1372+
To help IDEs, third-party plugins, or other tools distinguish between generated code and regular source files, register
1373+
the generated sources using the [`KotlinSourceSet`](https://kotlinlang.org/api/kotlin-gradle-plugin/kotlin-gradle-plugin-api/org.jetbrains.kotlin.gradle.plugin/-kotlin-source-set/) interface.
1374+
1375+
To register a directory that contains Kotlin or Java files, use the `generatedKotlin` property with the [`SourceDirectorySet`](https://docs.gradle.org/current/kotlin-dsl/gradle/org.gradle.api.file/-source-directory-set/index.html)
1376+
type in your `build.gradle(.kts)` file. For example:
1377+
1378+
```kotlin
1379+
val generatorTask = project.tasks.register("generator") {
1380+
val outputDirectory = project.layout.projectDirectory.dir("src/main/kotlinGen")
1381+
outputs.dir(outputDirectory)
1382+
doLast {
1383+
outputDirectory.file("generated.kt").asFile.writeText(
1384+
// language=kotlin
1385+
"""
1386+
fun printHello() {
1387+
println("hello")
1388+
}
1389+
""".trimIndent()
1390+
)
1391+
}
1392+
}
1393+
1394+
kotlin.sourceSets.getByName("main").generatedKotlin.srcDir(generatorTask)
1395+
```
1396+
1397+
This example creates a new task `"generator"` with an output directory of `"src/main/kotlinGen"`. When the task runs,
1398+
the `doLast {}` block creates a `generated.kt` file in the output directory. Finally, the example registers the task's
1399+
output as a generated source.
1400+
1401+
The `allKotlinSources` property provides access to all sources registered in the `KotlinSourceSet.kotlin` and
1402+
`KotlinSourceSet.generatedKotlin` properties.
1403+
13701404
## What's next?
13711405
13721406
Learn more about:

0 commit comments

Comments
 (0)