public
Created

How to create DSL in Scala for command lines with minimum boilerplate

  • Download Gist
ShellSupport.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
package lib
import sys.process.{Process, stringToProcess}
 
class Shell {
var elems = Vector[String]()
var cwd = "/tmp"
 
def >(str: String) = elems :+= str
 
def run() = elems.map( cmd => {
val CdPattern = "cd (.*)".r
cmd match {
case CdPattern(dir) =>
cwd = dir
"directory changed to " + dir
case anyCmd => Process(anyCmd,new java.io.File(cwd))!!
}
}
)
}
 
 
trait ShellSupport extends DelayedInit{
var result = Vector[String]()
 
val $ = new Shell()
 
def delayedInit(x: => Unit) {
x
result = $.run()
}
 
}
SomeScript.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13
package scripting
 
import lib.ShellSupport
 
 
class Turismo extends ShellSupport {
 
$> "rm -rf /tmp/scripting"
$> "mkdir /tmp/scripting"
$> "cd /tmp/scripting"
$> "mkdir oops"
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.