1 import com.android.build.api.variant.BuiltArtifactsLoader
2 import org.gradle.api.file.DirectoryProperty
3 import org.gradle.api.provider.Property
4 import org.gradle.api.tasks.AbstractExecTask
5 import org.gradle.api.tasks.InputFiles
6 import org.gradle.api.tasks.Internal
7 import javax.inject.Inject
8 
9 abstract class PushApkTask
10 @Inject constructor() : AbstractExecTask<PushApkTask>(PushApkTask::class.java) {
11 
12     @get:InputFiles
13     abstract val apkFolder: DirectoryProperty
14 
15     @get:Internal
16     abstract val builtArtifactsLoader: Property<BuiltArtifactsLoader>
17 
execnull18     override fun exec() {
19         val builtArtifacts = builtArtifactsLoader.get().load(apkFolder.get())
20             ?: throw RuntimeException("Cannot load APKs")
21         if (builtArtifacts.elements.isEmpty()) {
22             throw RuntimeException("Build artifact not found. Can't install apk if it doesn't exist.")
23         }
24         val numArtifacts = builtArtifacts.elements.size
25         if (numArtifacts > 1) {
26             throw RuntimeException(
27                 "Too many build artifacts. Expected 1 apk file but received $numArtifacts. " +
28                         "The push-apk.sh script only supports installing one apk file."
29             )
30         }
31         // TODO(b/234033515): This does not yet account for ANDROID_ADB_SERVER_PORT
32         val deviceSerials =
33             project.providers.gradleProperty("internal.android.inject.device.serials")
34         if (!deviceSerials.isPresent) {
35             throw RuntimeException(
36                 "No Android serial present. Make sure your Android Studio VM options contains " +
37                         "-Dgradle.ide.internal.build.injection.device.serial.number=true"
38             )
39         }
40         builtArtifacts.elements.forEach {
41             commandLine("sh", "push-apk.sh", it.outputFile, deviceSerials.get())
42         }
43 
44         CommandLineUtils.debugPrintCommandLineArgs(this)
45         super.exec()
46     }
47 }
48