How to list all build variants using gradlew?

Viewed 802

Is it possible to list all build variants using gradlew or other command line tool?

For example for the following build.gradle:

buildTypes {
    debug {}
    release {}
}
productFlavors {
    dev {}
    prod {}
}

the command would return something like:

devDebug
devRelease
prodDebug
prodRelease

One option would be to create a gradle task in my build.gradle which I would then execute with gradlew. But I am looking for a generic solution that would work for any project without the need to add anything.

2 Answers

Gradle already has a task for this, it's called tasks

./gradlew tasks

There isn't a task that outputs all the variants, as far as I know. It wouldn't be terribly hard to create such a task, but I think there may be a better solution for your use-case here.

So you have a few options here. First of all, gradle task are set up in such a way that you would have the following tasks for your example:

assemble
assembleDev
assembleProd
assembleDebug
assembleRelease
assembleDevDebug
assembleDevRelease
assembleProdDebug
assembleProdRelease

If your goal is to build all variants, then you could simply run :app:assemble, and all productFlavor and buildType variants will be built. If you just want release builds, but of each flavor, then you could do :app:assembleRelease, and that would automatically run

assembleDevRelease
assembleProdRelease

Many other tasks follow this same pattern. But not necessarily all of them. So as Stephan mentions in https://stackoverflow.com/a/69254774/2923245, running :app:tasks can be a good start to see what tasks you have available.


If you really do need a task that outputs each variant name (or you want to access these names in code), then you can do something like this:

task("printVariants") {
    doFirst {
        println project.getExtensions().getByType(com.android.build.gradle.AppExtension.class).applicationVariants*.name
    }
}

Or, if you want to do something for each variant, then something like:

AppExtension android = project.getExtensions().getByType(AppExtension.class)
android.applicationVariants.each { appVariant ->
    // Variant-specific code goes here.
    // Example below: Creating a task for each variant.
    project.tasks.create("${appVariant.name}MyVariantSpecificTask", ...)
}

It helps to remember that build.gradle is just code. You can code in whatever here- as long as you get comfortable with Groovy and the gradle + android gradle plugin(AGP) api's.

Related