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 sourceSets
with the following code :
(got it from a genius in the linked question above)
import com.android.build.gradle.api.AndroidSourceSet
android {
sourceSets {
[flavor2, flavor4].each { AndroidSourceSet ss ->
ss.assets.srcDirs = ['repo-assets/flavor2']
ss.res.srcDirs = ['repo-res/flavor2']
}
}
}
Now, I was wondering if the list [flavor2, flavor4]
could be pulled from any of the following:
- An XML file over which i can iterate to get all flavors (which i'll put there)
- A CSV file over which i can iterate and fetch values.
- A custom class which i can write in a separate file and fetch data from static members in the class.
In addition to the flavor name, I intend to store the following in the external source (one of above):
- application id (which i will pull to
productFlavors
) - ad unit ids (two per flavor)
- some other custom values like category etc.
PORPOSE: I want to write a generic piece of code to iterate and dynamically create the productFlavors
and sourceSets
. I have generalized sourceSets
to almost 90% and one block is now sufficing for all flavors.
It looks something like this now:
sourceSets {
[flavor1, flavor2, flavor3 ...].each { AndroidSourceSet ss ->
ss.assets.srcDirs = ['repo-assets/' + ss.name.split('_')[0]]
ss.res.srcDirs = ['repo-mipmap/' + ss.name.split('_')[0] , 'repo-strings/' + ss.name]
}
}
Also want to do the same thing for productFlavors
as hinted above.
STUCK AT: getting the list [flavor2, flavor4]
in the code above from an external source (along with a few additional fields per flavor as listed above).
I see methods like
productFlavors.add()
productFlavors.addAll()
but am not quite sure about how to go about using these. As the methods are available I'm sure it is possible to do what I'm trying to.
Has anyone done this and has some pointers?
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:
Groovy can load it like this:
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 regularandroid { ... }
configuration. Internal types may change at any time, in fact I'm working with 1.5 they may already have changed in 2.0.I finally got it to work this way:
Created a custom class
MyFlavor
withinbuild.gradle
and added each flavor from the csv file to anArrayList
ofMyFlavor
Then iterated over the
ArrayList
to dynamically create theproductFlavors
andsourceSets
as follows:Hope this helps someone. I was successful in getting rid of 1000s of lines of code (because i have a lot of flavors) and bring it down to these 10s of lines you see here.