Skip to content

Instantly share code, notes, and snippets.

@j-keck
Last active July 12, 2017 20:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j-keck/7bd29de3a2d8b2ae6773 to your computer and use it in GitHub Desktop.
Save j-keck/7bd29de3a2d8b2ae6773 to your computer and use it in GitHub Desktop.
scala: cancelable / async scala.sys.process.Process
/*
The MIT License (MIT)
Copyright (c) 2016 j-keck <jhyphenkeck@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.sys.process.{Process, ProcessLogger}
import scala.util.Try
object Sys extends Sys {
type ExitValue = Int
type Stdout = String
type Stderr = String
type ExecResult = (ExitValue, Stdout, Stderr)
trait AsyncExecResult {
/**
* @see [[scala.concurrent.Future#map]]
*/
def map[T](f: ExecResult => T): Future[T]
/**
* @see [[scala.concurrent.Future#foreach]]
*/
def foreach(f: ExecResult => Unit): Unit
/**
* @see [[scala.concurrent.Future#onComplete]]
*/
def onComplete[T](pf: Try[ExecResult] => T): Unit
/**
* cancels the running process
*/
def cancel(): Unit
/**
* check if the process is still running
* @return `true` if the process is already completed, `false` otherwise
*/
def isRunning: Boolean
/**
* the underlying future
* @return the future, in which the process runs
*/
def get: Future[ExecResult]
}
type Cancelable = () => Unit
case class ExecutionCanceled(msg: String) extends Exception(msg)
}
trait Sys {
import Sys._
def exec(cmd: String): ExecResult = exec(cmd.split(" "))
/**
* executes the cmd and blocks until the command exits.
*
* @return {{{(ExitValue, Stdout, Stderr)}}}
* <pre>if the executable is unable to start, (-1, "", stderr) are returned</pre>
*/
def exec(cmd: Seq[String]): ExecResult = {
val stdout = new OutputSlurper
val stderr = new OutputSlurper
Try {
val proc = Process(cmd).run(ProcessLogger(stdout.appendLine, stderr.appendLine))
proc.exitValue()
}.map((_, stdout.get, stderr.get))
.recover{
case t => (-1, "", t.getMessage)
}.get
}
def execAsync(cmd: String)(implicit ec: ExecutionContext): AsyncExecResult = execAsync(cmd.split(" "))(ec)
/**
* executes the cmd asynchronous
* @see scala.concurrent.Future.map
*
* @return [[AsyncExecResult]]
*/
def execAsync(cmd: Seq[String])(implicit ec: ExecutionContext): AsyncExecResult = {
new AsyncExecResult {
val (fut, cancelFut) = runAsync(cmd)
override def map[T](f: ExecResult => T): Future[T] = fut.map(f)
override def foreach(f: ExecResult => Unit): Unit = fut.foreach(f)
override def onComplete[T](pf: Try[ExecResult] => T): Unit = fut.onComplete(pf)
override def cancel(): Unit = cancelFut()
override def isRunning: Boolean = !fut.isCompleted
override def get: Future[ExecResult] = fut
}
}
// helper for 'execAsync' - runs the given cmd asynchronous.
// returns a tuple with: (the running process in a future, function to cancel the running process)
private def runAsync(cmd: Seq[String])(implicit ec: ExecutionContext): (Future[ExecResult], Cancelable) = {
val p = Promise[ExecResult]
val stdout = new OutputSlurper
val stderr = new OutputSlurper
// start the process
val proc = Process(cmd).run(ProcessLogger(stdout.appendLine, stderr.appendLine))
p.tryCompleteWith(Future(proc.exitValue).map(c => (c, stdout.get, stderr.get)))
val cancel = {
p.tryFailure(new ExecutionCanceled(s"Process: '${cmd.mkString(" ")}' canceled"))
proc.destroy()
}
(p.future, () => cancel)
}
class OutputSlurper {
private val sb = new StringBuilder
def append(s: String): Unit = sb.append(s)
def appendLine(s: String): Unit = append(s + "\n")
def get: String = sb.toString
}
}
import scala.util.Failure
object SysExample extends App {
// blocking
println("current working dir: " + Sys.exec("pwd")._2)
println("bad process: " + Sys.exec("BOOM"))
println("=" * 80)
// cancelable async
import scala.concurrent.ExecutionContext.Implicits.global
import Sys._
val exe = Sys.execAsync("ssh -t -t root@vdr")
exe.foreach { case (exitCode, stdout, stderr) =>
println(s"done with exitCode: ${exitCode}, stdout: ${stdout}, stderr: ${stderr}")
}
exe.onComplete {
case Failure(ExecutionCanceled(msg)) => System.err.println(msg)
case Failure(t) => t.printStackTrace
case _ =>
}
Thread.sleep(1000)
if (exe.isRunning)
exe.cancel()
Thread.sleep(1000)
}
@Karry
Copy link

Karry commented Nov 7, 2016

Hi. it is very useful! Under what terms can I use it? Can you "release" it under BSD, MIT or LGPL license? Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment