How to create a source generator task for kotlin along with kapt dependency?

I like to create a gradle task which generates a kotlin source file and build the project with the generated file. There is a also a separate kapt dependency in the project

Here is what I have done till now

 apply plugin: 'kotlin'
 apply plugin: 'kotlin-kapt'

 dependencies {
    kapt project(':plugin')
    ...
 }

 task versionInfo {
     doLast {
         println("Generating Version Info")
         def dir = new File("${buildDir}/generated/source/kapt/main/${project.group.replace('.', '/')}/${project.name.replace('-', '/')}")
         dir.mkdirs()
         def file = new File("$dir/version.kt")
         file.createNewFile()
         file.text = """
 package ${project.group}.${project.name.replace('-', '.')}
 
 val appVersion: String = \"$version\"
 
         """
     }
 }
 
compileKotlin.dependsOn versionInfo

When I run ./gradlew clean build -x test I get compilation error and when I see the build folder, I can’t see the file under ${buildDir}/generated/source/kapt/main. But again when I run ./gradlew build -x test (without clean) I see a different error:

* What went wrong:
Execution failed for task ':service:compileJava'.
> no source files

When I remove the kapt plugin and dependency the project compiles fine. So how do I make everything works - keep the kapt dependency and generate a kotlin file via task as well?

1 Like

build.dependsOn(versionInfo)