Dynamically generating productFlavors and sourceSets using a list of names (with properties) in a CSV/TXT file

后端 未结 2 1188
逝去的感伤
逝去的感伤 2021-01-05 18:55

This question in continuation of my other question, which i want to improve further.

I am being able to group flavors (having common configuration) under sourc

2条回答
  •  半阙折子戏
    2021-01-05 19:20

    For reading XML and CSV files you have the full power of Groovy on your hand. All Gradle scripts are meant to be written in Groovy. .each { Type var -> is part of that too. First result: https://stackoverflow.com/a/2622965/253468:

    Given a CSV file like this:

    #name,appId,ad1,ad2,category
    flavor1,app.id.flavor1,adunit1324523,adunit2234234,messenger
    flavor2,app.id.flavor2,adunit42346451,adunit4562,editor
    flavor3,app.id.flavor2.gpe,adunit345351,adunit3545342,messenger
    

    Groovy can load it like this:

    import com.android.build.gradle.BaseExtension
    import com.android.build.gradle.api.AndroidSourceSet
    import com.android.build.gradle.internal.dsl.ProductFlavor
    // TODO get a real CSV parser, this is hacky
    new File("flavors.csv").splitEachLine(",") { fields ->
        if (fields[0].charAt(0) == '#' as char) return; // skip comments
        def flavorName = fields[0];
        def baseName = flavorName.split('_')[0];
        def appId = fields[1];
        BaseExtension android = project.android // project.getExtensions().getByName('android'); 
        // productFlavors is declared as Collection, but it is a NamedDomainObjectContainer
        // if [flavorName] doesn't work, try .maybeCreate(flavorName) or .create(flavorName)
        ProductFlavor flavor = android.productFlavors[flavorName];
        AndroidSourceSet sourceSet = android.sourceSets[flavorName];
        flavor.applicationId = appId;
        sourceSet.res.srcDirs = [] // clear
        sourceSet.res.srcDir 'repo-mipmap/' + baseName
        sourceSet.res.srcDir 'repo-strings/' + flavorName
    }
    

    Types are imported for readability and code completion, you can replace any variable type with def and it'll still work. These types are just what is being used when you're doing the regular android { ... } configuration. Internal types may change at any time, in fact I'm working with 1.5 they may already have changed in 2.0.

提交回复
热议问题