Getting the active flavor and build type at build-time

This is usually not relevant, but when getting creative with your Gralde scripts it might be handy to know which flavor is being built. Simply putting code inside a productFlavor block is not enough to exclude code from running, e.g. when including code from other scripts.

Built Type

/**
 * Returns the build type (debug/release) that is currently being built, or null
 * @return
 */
def getCurrentBuiltType() {
    Gradle gradle = getGradle()
    String tskReqStr = gradle.getStartParameter().getTaskRequests().toString()
    Pattern pattern
    if (tskReqStr.contains("assemble"))
        pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
    else
        pattern = Pattern.compile("generate(\\w+)(Release|Debug)")

    Matcher matcher = pattern.matcher(tskReqStr)
    if (matcher.find()) {
        return matcher.group(2).toLowerCase()
    } else {
        return null
    }
}

Flavor

Exactly the same, except we grab the 1st group form the regex, not the 2nd:

/**
 * Returns the flavor that is currently being built, or null
 * @return
 */
def getCurrentFlavor() {
    Gradle gradle = getGradle()
    String tskReqStr = gradle.getStartParameter().getTaskRequests().toString()
    Pattern pattern
    if (tskReqStr.contains("assemble"))
        pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
    else
        pattern = Pattern.compile("generate(\\w+)(Release|Debug)")

    Matcher matcher = pattern.matcher(tskReqStr)
    if (matcher.find()) {
        return matcher.group(1).toLowerCase()
    } else {
        return null
    }
}

Export

If these methods are in another file, export like so:

ext.currentBuildType = { return getCurrentBuiltType() }
ext.currentFlavor = { return getCurrentFlavor() }