How to create a FlavorConfig in BuildSrc?
Asked Answered
R

2

6

I'm trying to create a Flavor configuration to avoid boilerplate code in every Module and Library gradle file.

To do so I'm trying to convert Piotr Zawadzki solution (https://medium.com/stepstone-tech/modularizing-your-flavored-android-project-5db75c59fb0d) which uses the groovy with() method combined with a Closure containing the flavor config.

ext.flavorConfig = { // 1

    flavorDimensions "pricing"
    productFlavors {
        free {
            dimension "pricing"
            ext.myApplicationIdSuffix = '.free' // 2
        }
        paid {
            dimension "pricing"
            ext.myApplicationIdSuffix = '.paid'
        }
    }

    productFlavors.all { flavor -> // 3
        if (flavor.hasProperty('myApplicationIdSuffix') && isApplicationProject()) {
            flavor.applicationIdSuffix = flavor.myApplicationIdSuffix
        }
    }

}

def isApplicationProject() { // 4
    return project.android.class.simpleName.startsWith('BaseAppModuleExtension')
    // in AGP 3.1.x with library modules instead of feature modules:
    // return project.android instanceof com.android.build.gradle.AppExtension
}

What I'm not finding is the equivalent with() method for the Kotlin DSL or a proper way to translate the Closure.

Rima answered 19/11, 2019 at 16:25 Comment(0)
C
0

An equivalent should be apply or run, depending on what's the actual return value of with (which I couldn't figure out for some reason).

Ceres answered 20/11, 2019 at 8:26 Comment(0)
E
0

I found a solution with KotlinScript, I think it could be done with Groovy too.

First, add gradle-api dependency in your buildSrc/build.gradle.kts file

//buildSrc/build.gradle.kts

val agpVersion = "7.1.1"

plugins {
    `kotlin-dsl`
}

repositories {
    mavenCentral()
    google()
}

dependencies{
    implementation("com.android.tools.build:gradle-api:$agpVersion")
}

Then create a Gradle Plug-In in buildSrc.

//buildSrc/src/main/kotlin/FooPlugin.kt

abstract class FooPlugin : Plugin<Project> {
    override fun apply(project: Project) {
        val android = project.extensions.getByType(ApplicationExtension::class.java)
        android.defaultConfig {
            android.productFlavors.create("Bar")
        }
    }
}

Finally apply FooPlugin to your application's build.gradle.kts

//baz/build.gradle.kts

plugins {
    ...
}

apply<FooPlugin>()

android{
    ...
}

dependencies {
    ...
}
Electuary answered 15/2, 2022 at 9:24 Comment(1)
Do you have a link to a repository displaying this in action somewhere?Spearing

© 2022 - 2024 — McMap. All rights reserved.