Search code examples
androidgradleandroid-librarygradle-plugingradle-kotlin-dsl

How to add a generated code from build folder to the path in a Gradle Android Library plugin


I've got an Android Library module, and in the build.gradle.kts script I've made a plugin class, inside the apply method of the plugin I am doing:

import com.android.build.gradle.LibraryExtension

val libExtension = project.extensions.findByType(LibraryExtension::class.java)!!
libExtension.libraryVariants.all {
     val variantName = this.name
     val sourceDir = "${project.buildDir}/generated/my-plugin/$variantName"
     libExtension.sourceSets[variantName].kotlin.srcDir(sourceDir)
}

(where variantName is “debug” or “release”)

I thought this code would add the folder as a source folder, but it doesn't (and therefore the kotlin class I have in the folder is not available).

Under the build folder of my android library module:

My folder (not working / not blue):

enter image description here

A correctly working folder in the build directory, created by another plugin:

enter image description here


Solution

  • Ok so the code in the question works, I'm not so crazy ><.

    When I split this out into the demo it showed it working.

    Here is the code that does not work:

    import com.android.build.gradle.LibraryExtension
    
    val libExtension = project.extensions.findByType(LibraryExtension::class.java)!!
    libExtension.libraryVariants.all {
         val variantName = this.name
         val sourceDir = "${project.buildDir}/generated/my-plugin/$variantName"
         // This task generates some code and puts it in the sourceDir
         val tp = project.tasks.register<MyTask>("${variantName}MyTask")
         tp.get().doLast {
             libExtension.sourceSets[variantName].kotlin.srcDir(sourceDir)
         }
    }
    

    I am assuming the "doLast" is what's stopping it working in the IDE. My guess is that if I generate the files first and then set the folder as a sourceset the IDE isn’t triggered into action. But if I set it as a sourceset first, and then generate the files, it kinda kicks in? 🤷

    Leaving the question here anyway, as I found it hard to even find anyone talking about this.