I'm looking for a simple way to find out if an Android App is being built for Debug or Release mode inside my library's build.gradle
script (in a task).
I have a task called prepareHermes
that extracts a .aar file. I currently always extract the debug variant, but in Release builds I want to use the release variant:
task prepareHermes() {
doLast {
def IS_DEBUG = // TODO: here
def aarName = IS_DEBUG ? "hermes-debug.aar" : "hermes-release.aar"
def hermesAAR = file("$hermesPackagePath/android/${aarName}")
if (!hermesAAR.exists()) {
throw new GradleScriptException("The hermes-engine npm package is missing \"android/${aarName}\"", null)
}
def soFiles = zipTree(hermesAAR).matching({ it.include "**/*.so" })
copy {
from soFiles
from "$reactNative/ReactAndroid/src/main/jni/first-party/hermes/Android.mk"
into "$thirdPartyNdkDir/hermes"
}
}
}
This task is later used in various places (see full code here), so making two separate tasks (prepareHermesDebug
and prepareHermesRelease
) is a bit inconvenient since I then have a ton of duplicate code. (this task is a dependency for a few other tasks, as seen in the full code.)
CodePudding user response:
You also can generate as many tasks as you like:
[ 'debug', 'release' ].each{ name ->
task "prepareHermes-$name"{
doLast {
def aarName = "hermes-${name}.aar"
def hermesAAR = file "$hermesPackagePath/android/$aarName"
// the rest...
}
}
}
Then if you run gradlew tasks
, you will see prepareHermes-debug
and prepareHermes-release
in the output
CodePudding user response:
Use gradle.startParameter.taskRequests
to determine current variant is NOT a nice idea.**
- Android Gradle Plugin (AGP) is built over Gradle Platform.
- Android Variant is a concept from Upper layer.
- Gradle
gradle.startParameter.taskRequests
API is Under layer, and it's not Variant Aware.
It does not support the scenario like:
./gradlew clean assemble
The above command produces both Debug
and Release
artifacts which breaks the check script using taskRequests
.
making two separate tasks (prepareHermesDebug and prepareHermesRelease) is a bit inconvenient...
Yes, we are going to take onVariants{}
API to do similar thing. Basically, it iterates all variant objects for you to get a chance to register Variant Aware task respectively:
androidComponents {
onVariants { variant ->
project.tasks.register<AarUploadTask>("${variant.name}AarUpload") {
aar.set(variant.artifacts.get(SingleArtifact.AAR))
}
}
}
abstract class AarUploadTask: DefaultTask() {
@get:InputFile
abstract val aar: RegularFileProperty
@TaskAction
fun taskAction() {
println("Uploading ${aar.get().asFile.absolutePath} to fantasy server...")
}
}
Through the new Variant&Artifact APIs above(In Kotlin DSL sorry, but you can easily transform it to groovy), you can get the corresponding .aar
of the Variant and pass it to a custom task conveniently(no hardcode any more).
Check full scripts from android/gradle-receipt, and more API doc from Extend the Android Gradle plugin.