Skip to content

Instantly share code, notes, and snippets.

@meoyawn
Last active October 28, 2019 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meoyawn/152cd9f33eb6278ba2916a2ea69ab98b to your computer and use it in GitHub Desktop.
Save meoyawn/152cd9f33eb6278ba2916a2ea69ab98b to your computer and use it in GitHub Desktop.
Calling CLI tools using kotlin coroutines with cancellation support
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