Last active
October 28, 2019 07:33
-
-
Save meoyawn/152cd9f33eb6278ba2916a2ea69ab98b to your computer and use it in GitHub Desktop.
Calling CLI tools using kotlin coroutines with cancellation support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.CoroutineScope | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.cancel | |
import kotlinx.coroutines.launch | |
import kotlinx.coroutines.suspendCancellableCoroutine | |
import java.io.StringWriter | |
sealed class Cli { | |
data class Ok(val stdout: String) : Cli() | |
data class Err(val stderr: String) : Cli() | |
} | |
suspend fun cli(cmd: String): Cli = | |
suspendCancellableCoroutine { cont -> | |
val scope = CoroutineScope(cont.context) | |
scope.launch(Dispatchers.IO) { | |
val process = Runtime.getRuntime().exec(cmd) | |
cont.invokeOnCancellation { | |
process.destroy() | |
scope.cancel() | |
} | |
val stdout = StringWriter() | |
val stderr = StringWriter() | |
val ok = launch { process.inputStream.use { it.reader().copyTo(stdout) } } | |
val err = launch { process.errorStream.use { it.reader().copyTo(stderr) } } | |
val cli = when (process.waitFor()) { | |
0 -> { | |
ok.join() | |
Cli.Ok(stdout.toString().trim()) | |
} | |
else -> { | |
err.join() | |
Cli.Err(stderr.toString().trim()) | |
} | |
} | |
cont.resume(cli) { | |
process.destroy() | |
scope.cancel() | |
} | |
} | |
} | |
suspend fun cli(vararg cmd: String): Cli = | |
cli(cmd.joinToString(separator = " ")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment