casualjim
12/1/2011 - 11:52 PM

Generates a scala source file with the sbt version number

Generates a scala source file with the sbt version number

package io.backchat.sbt
import sbt._
import Keys._

/**
usage
    <code>
    seq(ReflectPlugin.allSettings:_*)
    sourceGenerators in Compile <+= reflect map identity
    </code>
code
    println("project version=" + Reflect.version)
*/
object VersionGenPlugin extends Plugin {
    object VersionGenKeys {
      val versionGen     = TaskKey[Seq[File]]("version-gen")
      val versionGenPackage  = SettingKey[String]("version-gen-package")
      val versionGenClass  = SettingKey[String]("version-gen-class")
    }
    import VersionGenKeys._
    
    lazy val allSettings  = Seq(
        versionGenPackage  <<= Keys.organization { (org) => org },
        versionGenClass  := "Version",
        versionGen     <<= (sourceManaged in Compile, name, version, versionGenPackage, versionGenClass) map {
            (sourceManaged:File, name:String, version:String, vgp:String, vgc:String) =>
                val file  = sourceManaged / vgp.replace(".","/") / ("%s.scala" format vgc)
                val code  = 
                        (
                            if (vgp != null && vgp.nonEmpty)  "package " + vgp + "\n"
                            else              ""
                        ) +
                        "object " + vgc + " {\n" + 
                        "  val name\t= \"" + vgc + "\"\n" + 
                        "  val version\t= \"" + version + "\"\n" + 
                        "}\n"  
                IO write (file, code)
                Seq(file)
        },
        sourceGenerators in Compile <+= versionGen map identity
    )
}
val bumpPatch = TaskKey[String]("bump-patch")

settings ++ Seq(
  bumpPatch <<= (version) map { ver => 
    val Array(patch:Int, minor:Int, major:Int) = "0.0.1".split("\\.").reverse.map(_.toInt)
    val newVer = "%d.%d.%d".format(major, minor, patch+1)
    version := newVer
    newVer
  }
)