Skip to content

Instantly share code, notes, and snippets.

@faveoled
Last active July 21, 2023 15:45
Show Gist options
  • Save faveoled/b78e5ead733100b61ba88051d423862b to your computer and use it in GitHub Desktop.
Save faveoled/b78e5ead733100b61ba88051d423862b to your computer and use it in GitHub Desktop.
Run command in Tauri Scala.js
import tauri.ShellMod
import typings.std.stdStrings.close
import typings.tauriAppsApi.tauriAppsApiStrings
import scala.util.Failure
import scala.util.Success
import scala.concurrent.Future
import scala.collection.mutable.ArrayBuffer
import scala.concurrent.Promise
import scalajs.js.JSConverters.iterableOnceConvertible2JSRichIterableOnce
def lineAsString(line: Any): String = {
if (line.isInstanceOf[String]) {
return line.asInstanceOf[String]
}
throw Exception("Bad line type")
}
def runCommand(cmd: String, args: List[String]): Future[String] = {
val command = ShellMod.Command(cmd, args.toJSArray)
val lines = ArrayBuffer[String]()
val errLines = ArrayBuffer[String]()
val completionPromise = Promise[String]
command.on(tauriAppsApiStrings.close, data => {
val code = data.asInstanceOf[js.Dynamic].selectDynamic("code").asInstanceOf[Int]
if (code == 0) {
completionPromise.success(lines.mkString("\n"))
} else {
completionPromise.failure(new Exception(errLines.mkString("\n")))
}
println(s"command finished with code ${code}")
})
command.stdout.on(tauriAppsApiStrings.data, line => {
println("line: " + line)
lines += lineAsString(line)
})
command.stderr.on(tauriAppsApiStrings.data, line => {
println("line: " + line)
errLines += lineAsString(line)
})
command.spawn().toFuture.onComplete(tr => {
tr match
case Failure(exception) =>
completionPromise.failure(exception)
case Success(value) =>
// child pid not needed
})
completionPromise.future
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment