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

gradle kotlin dsl: how to create a shared function which uses a plugin class?


A simplified child module build.gradle.kts:

    plugins {
        id("com.android.library")
        kotlin("android")
    }

    android {
         androidComponents.beforeVariants { it: com.android.build.api.variant.LibraryVariantBuilder ->
              it.enabled = run {
                   // logic to calculate if
                   it.productFlavors[0].second == "flavor" && it.buildType == "debug"
              }
         }
    }

Is it possible to extract function for calculation of enabled state of buildVariant?

    fun calculateIsEnabled(lvb: com.android.build.api.variant.LibraryVariantBuilder): Boolean {
         return lvb.productFlavors[0].second == "flavor" && lvb.buildType == "debug"
    }
  1. I tried to declare the function in the root build.gradle.kts but I don't know how to access it from submodule and if it is possible at all
  2. I tried to declare it in buildSrc module, but com.android.build.api.variant.LibraryVariantBuilder is undefined here because the plugin com.android.library is not present here and I think it is not allowed and/or meaningless

So, the question is: where to declare a shared function that uses types defined in a gradle plugin and need to be accessible in all submodules of type android library?


Solution

  • After several tries I solved it:

    1. buildSrc/build.gradle.kts
    repositories {
        google()
        mavenCentral()
    }
    
    plugins {
        `kotlin-dsl`
    }
    
    dependencies {
         // important: dependency only in simple string format!
         implementation("com.android.tools.build:gradle:7.2.0-alpha03")
    }
    
    1. buildSrc/src/main/kotlin/Flavors.kt
    import com.android.build.api.variant.LibraryVariantBuilder
    import com.android.build.api.variant.ApplicationVariantBuilder
    
    private fun isFlavorEnabled(flavor1: String, buildType: String): Boolean {    
        return flavor1 == "flavor" && buildType == "debug"
    }
    
    fun isFlavorEnabled(lvb: LibraryVariantBuilder): Boolean {
        // productFlavors are pairs of flavorType(dimension) - flavorName(selectedFlavor)
        return lvb.run { isFlavorEnabled(productFlavors[0].second, buildType ?: "") }
    }
    
    fun isFlavorEnabled(avb: ApplicationVariantBuilder): Boolean {
        return avb.run { isFlavorEnabled(productFlavors[0].second, buildType ?: "") }
    }
    
    1. In library/build.gradle.kts and app/build.gradle.kts
    android {
        androidComponents.beforeVariants {
            it.enabled = isFlavorEnabled(it)
        }
    }