square / moshi

A modern JSON library for Kotlin and Java.
https://square.github.io/moshi/1.x/
Apache License 2.0
9.75k stars 761 forks source link

Is it possible to fail build when KSP is not configured but @JsonClass(generateAdapter = true) is used? #1778

Open nacyolsa opened 9 months ago

nacyolsa commented 9 months ago

Is it possible to fail build when KSP is not configured but @JsonClass(generateAdapter = true) is used? Now when KSP is not added but @JsonClass(generateAdapter = true) is used adapter is not generated.

SarveshRD commented 2 weeks ago

Yes, it's possible to fail the build if KSP (Kotlin Symbol Processing) is not properly configured but the @JsonClass(generateAdapter = true) annotation from Moshi is used. Currently, the default behavior in this scenario is that the adapter is not generated, and there is no explicit failure of the build, which can lead to runtime errors due to missing adapters.

To force the build to fail when this happens, you can take the following approach:

  1. Use a Gradle Task to Check KSP Configuration You can add a custom Gradle task to check whether KSP is correctly configured. This task could verify if the necessary KSP dependencies are included in the build or check if generated adapters exist after compilation.

tasks.register("checkKspConfigured") { doLast { if (!project.plugins.hasPlugin("com.google.devtools.ksp")) { throw GradleException("KSP is not configured, but @JsonClass(generateAdapter = true) is used.") } } }

You can then add a dependency to your build task to ensure that this check runs during the build process:

tasks.named("compileKotlin").configure { dependsOn("checkKspConfigured") }

  1. Use a Linter or Custom Annotation Processor

Another approach is to enforce this rule using a static analysis tool or a custom lint rule. This can ensure that any use of @JsonClass(generateAdapter = true) without KSP or generated adapters causes a warning or failure at build time.

You could also create a custom annotation processor or lint rule to detect the use of @JsonClass without the necessary configuration and fail the build.

  1. Consider Adding a Kotlin Compiler Plugin

You can create a Kotlin compiler plugin or use a pre-existing one to analyze the source code for the presence of the @JsonClass(generateAdapter = true) annotation without proper KSP configuration, then halt the build process.