From 5ebe3d0f2319181e48eeacb29f405f043810eaa1 Mon Sep 17 00:00:00 2001 From: SanmerDev Date: Sat, 29 Jun 2024 14:50:26 +0800 Subject: [PATCH] Optimize `Shell` --- .../kotlin/dev/sanmer/mrepo/impl/Shell.kt | 56 ++++++++----------- 1 file changed, 23 insertions(+), 33 deletions(-) diff --git a/core/src/main/kotlin/dev/sanmer/mrepo/impl/Shell.kt b/core/src/main/kotlin/dev/sanmer/mrepo/impl/Shell.kt index 3c451c2e..3646b249 100644 --- a/core/src/main/kotlin/dev/sanmer/mrepo/impl/Shell.kt +++ b/core/src/main/kotlin/dev/sanmer/mrepo/impl/Shell.kt @@ -5,36 +5,30 @@ import android.util.Log internal object Shell { private const val TAG = "Shell" - fun String.exec(): Result = try { - Log.d(TAG, "exec: $this") - val process = ProcessBuilder("sh", "-c", this).start() - val output = process.inputStream.bufferedReader().readText() - .removeSurrounding("", "\n") - - val error = process.errorStream.bufferedReader().readText() - .removeSurrounding("", "\n") - - when { - process.waitFor().ok() -> { - Log.d(TAG, "output: $output") - Result.success(output) - } - else -> { - Log.d(TAG, "error: $error") - Result.failure(RuntimeException(error)) - } + fun String.exec(): Result = + runCatching { + Log.d(TAG, "exec: $this") + val process = ProcessBuilder("sh", "-c", this).start() + val output = process.inputStream.bufferedReader().readText() + .removeSurrounding("", "\n") + + val error = process.errorStream.bufferedReader().readText() + .removeSurrounding("", "\n") + + require(process.waitFor().ok()) { error } + Log.d(TAG, "output: $output") + + output + }.onFailure { + Log.e(TAG, Log.getStackTraceString(it)) } - } catch (e: Throwable) { - Log.e(TAG, Log.getStackTraceString(e)) - Result.failure(e) - } fun String.exec( stdout: (String) -> Unit, stderr: (String) -> Unit - ) = try { - Log.d(TAG, "submit: ${this@exec}") - val process = ProcessBuilder("sh", "-c", this@exec).start() + ) = runCatching { + Log.d(TAG, "exec: $this") + val process = ProcessBuilder("sh", "-c", this).start() val output = process.inputStream.bufferedReader() val error = process.errorStream.bufferedReader() @@ -44,17 +38,13 @@ internal object Shell { } error.forEachLine { - Log.d(TAG, "stderr: $it") + Log.d(TAG, "error: $it") stderr(it) } - when { - process.waitFor().ok() -> Result.success(true) - else -> Result.failure(RuntimeException()) - } - } catch (e: Throwable) { - Log.e(TAG, Log.getStackTraceString(e)) - Result.failure(e) + require(process.waitFor().ok()) + }.onFailure { + Log.e(TAG, Log.getStackTraceString(it)) } private fun Int.ok() = this == 0