SolveSoul
SolveSoul

Reputation: 2648

Dynamically add build flavor from within a custom Gradle plugin

I'm writing a custom Gradle plugin which will add one or more tasks to an Android project. One of the tasks needs to add an 'ad hoc' build flavor to the list of existing build flavors already defined by the Android project.

I've tried altering one of the existing build flavors by changing the name as shown by the following code:

import com.android.build.gradle.internal.dsl.ProductFlavor
import org.gradle.api.Plugin
import org.gradle.api.Project

class MyPlugin implements Plugin<Project> {

    @Override
    void apply(Project target) {
        ProductFlavor adHocFlavor = target.android.productFlavors.first()
        adHocFlavor.name = 'adHoc'
        target.android.productFlavors.add(adHocFlavor)
    }

}

The problem here is that all build flavors in target.android.productFlavors are read-only at this point and throws the following error:

Cannot set the value of read-only property 'name' for ProductFlavor_Decorated

Does anyone have any idea how I can dynamically add a build flavor from within the plugin?

Upvotes: 3

Views: 1690

Answers (1)

azizbekian
azizbekian

Reputation: 62189

It should be as simple as this:

@Override
void apply(Project target) {
    target.android.productFlavors.create("name")    
}

productFlavors is an instance of NamedDomainObjectContainer.

From docs of NamedDomainObjectContainer.create():

Creates a new item with the given name, adding it to this container.

Thus, this will create a ProductFlavor with provided name and it to productFlavors.

Upvotes: 4

Related Questions