@@ -65,8 +65,8 @@ class DeviceFileManager(
6565 devices.forEach { device ->
6666 val serial = device.serialNumber
6767 // List files in the remote folder; ignore errors if the folder doesn't exist yet
68- val lsOutput = runAdbCapture(serial, " shell" , " ls" , remotePath)
69- val fileNames = lsOutput .lines()
68+ val lsResult = runAdbCapture(serial, " shell" , " ls" , remotePath)
69+ val fileNames = lsResult.output .lines()
7070 .map { it.trim() }
7171 .filter { it.isNotBlank() && ! it.startsWith(" ls:" ) && ! it.contains(" No such file" ) }
7272 // Pull each file to the local destination
@@ -78,22 +78,42 @@ class DeviceFileManager(
7878 }
7979
8080 private fun runAdb (serial : String , vararg args : String ) {
81- val output = runAdbCapture(serial, * args)
82- println (output)
81+ val result = runAdbCapture(serial, * args, throwOnError = true )
82+ println (result. output)
8383 }
8484
85- private fun runAdbCapture (serial : String , vararg args : String ): String {
85+ private fun runAdbCapture (
86+ serial : String ,
87+ vararg args : String ,
88+ throwOnError : Boolean = false,
89+ ): AdbResult {
8690 val command = buildList {
8791 add(adbExecutablePath)
8892 add(" -s" )
8993 add(serial)
9094 addAll(args.toList())
9195 }
92- val process = ProcessBuilder (command)
93- .redirectErrorStream(true )
94- .start()
95- val output = process.inputStream.bufferedReader().readText()
96- process.waitFor(60 , TimeUnit .SECONDS )
97- return output
96+ try {
97+ val process = ProcessBuilder (command)
98+ .redirectErrorStream(false )
99+ .start()
100+ val output = process.inputStream.bufferedReader().readText()
101+ val error = process.errorStream.bufferedReader().readText()
102+ val finished = process.waitFor(60 , TimeUnit .SECONDS )
103+ val exitCode = process.exitValue()
104+ if (! finished || exitCode != 0 ) {
105+ val message = " ADB command failed: ${command.joinToString(" " )} \n Exit code: $exitCode \n Output: $output \n Error: $error "
106+ if (throwOnError) throw RuntimeException (message)
107+ else println (message)
108+ }
109+ return AdbResult (output, error, exitCode)
110+ } catch (e: Exception ) {
111+ val message = " Exception running ADB command: ${command.joinToString(" " )} \n ${e.message} "
112+ if (throwOnError) throw RuntimeException (message, e)
113+ else println (message)
114+ return AdbResult (" " , e.message ? : " " , - 1 )
115+ }
98116 }
117+
118+ private data class AdbResult (val output : String , val error : String , val exitCode : Int )
99119}
0 commit comments