Skip to content

Instantly share code, notes, and snippets.

@fizzy33
Created July 27, 2016 13:05
Show Gist options
  • Save fizzy33/260808a91d518d31f9ed6bb52606a855 to your computer and use it in GitHub Desktop.
Save fizzy33/260808a91d518d31f9ed6bb52606a855 to your computer and use it in GitHub Desktop.
package a8.recipe
import java.io.{ByteArrayOutputStream, PrintWriter}
import m3.fs._
import m3.json.JsonToString
import m3.predef._
object Exec {
def apply(args: String*): Exec =
Exec(args, None)
case class Result(
exitCode: Int,
stdout: String,
stderr: String
) extends JsonToString
}
case class Exec(
args: Iterable[String],
workingDirectory: Option[Directory] = None
)
extends JsonToString
with Logging
{
def inDirectory(directory: Directory) =
copy(workingDirectory = Some(directory))
import Exec._
private def _process =
sys.process.Process(args.toSeq, workingDirectory.map(d => new java.io.File(d.canonicalPath)))
def execCaptureOutput(failOnNonZeroExitCode: Boolean = true): Result = {
import sys.process._
val stdout = new ByteArrayOutputStream
val stderr = new ByteArrayOutputStream
val stdoutWriter = new PrintWriter(stdout)
val stderrWriter = new PrintWriter(stderr)
logger.info(toString)
val exitCode = _process.!(ProcessLogger(stdoutWriter.println, stderrWriter.println))
stdoutWriter.close()
stderrWriter.close()
val result = Result(
exitCode = exitCode,
stdout = stdout.toString,
stderr = stderr.toString
)
if ( failOnNonZeroExitCode && exitCode != 0 )
m3x.error(s"error running \n ${this}\n ${result}")
result
}
def execInline(failOnNonZeroExitCode: Boolean = true): Int = {
logger.info(toString)
val exitCode = _process.!
if ( failOnNonZeroExitCode && exitCode != 0 )
m3x.error(s"error running ${this}")
exitCode
}
lazy val argsAsString =
args
.map { arg =>
if ( arg.exists(_.isWhitespace) ) s"'${arg}'"
else arg
}
.mkString(" ")
override def toString =
s"running ${workingDirectory.map(d=>s"with a cwd of ${d}").getOrElse("")} the command -- ${argsAsString}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment