google / google/ksp

Generate files that are neither source code nor resources

Open
#1,677 6 comments 11 reactions 0 assignees View on GitHub
Dominant language
Kotlin
Stars
3.5k
Forks
415
Avg merge
1d 2h
Merged PRs (30d)
53

Description

I wrote an annotation processor that collects all production classes with the `@Serializable` annotation, and checks for a corresponding test with the `@SerializationTest` annotation. It fails the build if a class is missing a test! It looks like this:

In src/commonMain/kotlin:
```kotlin
@Serializable
class Color (...)
```

In src/commonTest/kotlin:
```kotlin
@SerializationTest(Color::class)
class ColorTest {
...
}
```

This works nicely, but it wasn’t as easy to write as I’d hoped.

To be incremental, my processor must generate a file (which is used to track which `.kt` files were inputs to that file). I decided that the annotation processor should generate two files: `classes-annotated-serializable.txt` and `classes-with-serialization-tests.txt`, plus a helper Gradle task to diff the files and log an error if they differ.

That worked nicely, but I soon discovered that `classes-annotated-serializable.txt` was appearing in my production `.jar` file, which wasn’t what I wanted. I was surprised to learn that `CodeGenerator.createNewFile()` makes its outputs resources by default. I ended up manually stripping them out with Gradle:

```kotlin
tasks.withType {
exclude("**/classes-annotated-serializable.txt")
exclude("**/classes-with-serialization-tests.txt")
}
```

This worked for my use case.

But I don’t like that I have to generate a resource and then strip it out; I’d prefer a mechanism to generate this file in a directory that isn‘t for resources.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.