com.geirsson.PipeFail.scala Maven / Gradle / Ivy
package com.geirsson
import java.io.ByteArrayInputStream
import scala.sys.process.{ProcessBuilder, ProcessLogger}
import scala.util.{Failure, Success, Try}
object PipeFail:
implicit class PipeFailOps(p1: ProcessBuilder):
@volatile
private var error: Option[String] = None
def #|!(p2: ProcessBuilder): ProcessBuilder =
val logger = new ProcessLogger:
override def out(s: => String): Unit = ()
override def err(s: => String): Unit =
error = Some(s)
override def buffer[T](f: => T): T = f
Try(p1.!!(logger)).map((result) =>
(p2 #< new ByteArrayInputStream(result.getBytes))
) match
case Failure(ex) =>
error match {
case Some(errorMessageFromPipe) =>
throw new RuntimeException(errorMessageFromPipe, ex)
case None => throw ex
}
case Success(value) => value
end PipeFail