Skip to content
This repository has been archived by the owner on Jul 2, 2024. It is now read-only.

Commit

Permalink
Optimize Shell
Browse files Browse the repository at this point in the history
  • Loading branch information
SanmerDev committed Jun 29, 2024
1 parent b4e22d7 commit 5ebe3d0
Showing 1 changed file with 23 additions and 33 deletions.
56 changes: 23 additions & 33 deletions core/src/main/kotlin/dev/sanmer/mrepo/impl/Shell.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,30 @@ import android.util.Log
internal object Shell {
private const val TAG = "Shell"

fun String.exec(): Result<String> = 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<String> =
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()

Expand All @@ -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
Expand Down

0 comments on commit 5ebe3d0

Please sign in to comment.