Can I access my Scala app's name and version (as set in SBT) from code?

前端 未结 2 883
春和景丽
春和景丽 2021-01-30 12:14

I am building an app with SBT (0.11.0) using a Scala build definition like so:

object MyAppBuild extends Build {

  import Dependencies._

  lazy val basicSettin         


        
相关标签:
2条回答
  • 2021-01-30 13:04

    Name and version are inserted into manifest. You can access them using java reflection from Package class.

    val p = getClass.getPackage
    val name = p.getImplementationTitle
    val version = p.getImplementationVersion
    
    0 讨论(0)
  • 2021-01-30 13:18

    sbt-buildinfo

    I just wrote sbt-buildinfo. After installing the plugin:

    lazy val root = (project in file(".")).
      enablePlugins(BuildInfoPlugin).
      settings(
        buildInfoKeys := Seq[BuildInfoKey](name, version, scalaVersion, sbtVersion),
        buildInfoPackage := "foo"
      )
    

    Edit: The above snippet has been updated to reflect more recent version of sbt-buildinfo.

    It generates foo.BuildInfo object with any setting you want by customizing buildInfoKeys.

    Ad-hoc approach

    I've been meaning to make a plugin for this, (I wrote it) but here's a quick script to generate a file:

    sourceGenerators in Compile <+= (sourceManaged in Compile, version, name) map { (d, v, n) =>
      val file = d / "info.scala"
      IO.write(file, """package foo
        |object Info {
        |  val version = "%s"
        |  val name = "%s"
        |}
        |""".stripMargin.format(v, n))
      Seq(file)
    }
    

    You can get your version as foo.Info.version.

    0 讨论(0)
提交回复
热议问题