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

回眸只為那壹抹淺笑 提交于 2019-12-03 02:10:06

问题


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 basicSettings = Seq[Setting[_]](
    organization  := "com.my",
    version       := "0.1",
    description   := "Blah",
    scalaVersion  := "2.9.1",
    scalacOptions := Seq("-deprecation", "-encoding", "utf8"),
    resolvers     ++= Dependencies.resolutionRepos
  )

  lazy val myAppProject = Project("my-app-name", file("."))
    .settings(basicSettings: _*)
    [...]

I'm packaging a .jar at the end of the process.

My question is a simple one: is there a way of accessing the application's name ("my-app-name") and version ("0.1") programmatically from my Scala code? I don't want to repeat them in two places if I can help it.

Any guidance greatly appreciated!


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/8732891/can-i-access-my-scala-apps-name-and-version-as-set-in-sbt-from-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!