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

Access Android application variants / library variants in buildSrc


I am migrating my gradle files to kotlin dsl. My current setup in Groovy is I have a sonar.gradle, a projectjacoco.gradle and a modulegradle.gradle all included in my build.gradle. I have now migrated my build.gradle to build.gradle.kts. I understand I now need to re-write these external gradle files in kotlin-dsl and include them in the buildSrc folder structure: e.g.

buildSrc
|__src
      |__main
            |__kotlin
                     |__modulegradle.build.kts

And then add them as a plugin.

My question is, how do I access the android baseappmodule extension inside those gradle files? e.g.

    android.applicationVariants.forEach { variant ->
        val variantName = variant.name.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ENGLISH) else it.toString() }
        val testTaskName = "test${variantName}UnitTest"

but within the gradle.kts file within the buildSrc folder structure

I followed this vid on creating gradle plugins, however it didn't give me the functionality I needed. So if anyone can help me, I wish to be able to access the android application / library variants from gradle files within the buildSrc folder structure e.g. in modulegradle.build.kts

Any and all help, tips, advice is greatly appreciated.


Solution

  • You need to import the artifact containing the Android application or library plugin in the buildSrc build.gradle.kts file to use it in a script plugin in buildSrc:

    // buildSrc/build.gradle.kts
    
    repositories {
        google()
    }
    
    dependencies {
        implementation("com.android.application:com.android.application.gradle.plugin:8.3.2")
    }
    

    Or for the library plugin:

    // buildSrc/build.gradle.kts
    
    dependencies {
        implementation("com.android.library:com.android.library.gradle.plugin:8.3.2")
    }
    

    Then you can apply the plugin in the script plugin:

    plugins {
        id("com.android.application")
    }