gradle kotlin dsl:如何创建使用插件的共享函数 class?

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

一个简化的子模块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"
              }
         }
    }

是否可以提取用于计算 buildVariant 启用状态的函数?

    fun calculateIsEnabled(lvb: com.android.build.api.variant.LibraryVariantBuilder): Boolean {
         return lvb.productFlavors[0].second == "flavor" && lvb.buildType == "debug"
    }
  1. 我试图在根目录中声明该函数 build.gradle.kts 但我不知道如何从子模块访问它以及是否可能
  2. 我试图在 buildSrc 模块中声明它,但是 com.android.build.api.variant.LibraryVariantBuilder 在这里未定义,因为这里没有插件 com.android.library,我认为这是不允许的 and/or 无意义

所以,问题是:在哪里声明一个共享函数,它使用在 gradle 插件中定义的类型,并且需要在类型 android 库的所有子模块中访问?

经过几次尝试我解决了:

  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. library/build.gradle.ktsapp/build.gradle.kts
android {
    androidComponents.beforeVariants {
        it.enabled = isFlavorEnabled(it)
    }
}