Monday, November 26, 2012

Sharing information between SBT build.sbt and your project code...

One way to share data between SBT build.sbt file and your project code is to automatically generate a class. This is quite easy, everything is done directly inside build.sbt file :
import AssemblyKeys._

seq(assemblySettings: _*)

name := "ScalaDummyProject"

version := "0.1.3"

scalaVersion := "2.9.2"

scalacOptions ++= Seq("-unchecked", "-deprecation")

mainClass in assembly := Some("dummy.Dummy")

jarName in assembly := "dummy.jar"

libraryDependencies += "org.scalatest" %% "scalatest" % "1.8" % "test"

libraryDependencies += "junit" % "junit" % "4.10" % "test"


sourceGenerators in Compile <+= 
 (sourceManaged in Compile, version, name, jarName in assembly) map {
  (dir, version, projectname, jarexe) =>
  val file = dir / "dummy" / "MetaInfo.scala"
  IO.write(file,
  """package dummy
    |object MetaInfo { 
    |  val version="%s"
    |  val projectName="%s"
    |  val jarbasename="%s"
    |}
    |""".stripMargin.format(version, projectname, jarexe.split("[.]").head) )
  Seq(file)
}

And that's all, then once done, you can write such things :
package dummy

object Dummy {
  val message = "Hello %s by %s release %s".format(
       util.Properties.userName,
       MetaInfo.projectName,
       MetaInfo.version
  )

  def main(args:Array[String]) {
    println(message)
  }
}

Full example is available on github.

No comments:

Post a Comment