yet another start script plugin for sbt

My mental powers aren’t what they used to be, or at least that’s what I start feeling like when I try to use sbt for anything more then the compile step. It’s either breathtakingly brilliant or incredibly obfuscated, or both. I’m really not sure yet.

In any case, I wanted to generate scripts to launch a few simple tasks from my project. My solution, in case it’s useful

import sbt._
import Keys._

object GenerateScripts extends Plugin {
val scriptClasses = SettingKey[List[String]](
  "script-classes", "List of classes to generate start scripts for.")

val genScripts = TaskKey[Unit](
  "generate-scripts", "Generate start scripts."
)

val scriptTemplate = """
#!/bin/bash

CLASSPATH="%s"
MAINCLASS="%s"
java -cp $CLASSPATH $MAINCLASS

"""

def genScriptsTask = (streams, target, scriptClasses, fullClasspath in Runtime) map {
(stream, target, scripts, cp) => {
  val log = stream.log
  for (f <- scripts) {
    val scriptName = f.split('.').last
    val targetFile = (target / scriptName).asFile
    val classPath = cp.map(_.data).mkString(":")
    log.info("Generating script for %s".format(f))
    IO.write(targetFile, scriptTemplate.format(classPath, f))
    targetFile.setExecutable(true)
  }
}
}

override val settings = Seq(
  scriptClasses := List(),
  genScripts <<= genScriptsTask
)
 
}

Add this to your project/Build.scala, and add:

scriptClasses := List("a.b.foo", "b.c.bar")

to your build.sbt.

If someone would like to explain to me the difference between TaskKeys and Commands, as well as how to add this as a dependency of the compile step, I’d be much obliged.

Leave a Reply

Your email address will not be published. Required fields are marked *