Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 869
Alex Dean Avatar asked Jan 04 '12 19:01

Alex Dean


People also ask

Which Scala version does sbt use?

sbt uses that same version of Scala to compile the build definitions that you write for your project because they use sbt APIs. This version of Scala is fixed for a specific sbt release and cannot be changed. For sbt 1.7. 1, this version is Scala 2.12.

How do we specify library dependencies in sbt?

The libraryDependencies key Most of the time, you can simply list your dependencies in the setting libraryDependencies . It's also possible to write a Maven POM file or Ivy configuration file to externally configure your dependencies, and have sbt use those external configuration files.


2 Answers

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.

like image 144
Eugene Yokota Avatar answered Sep 21 '22 08:09

Eugene Yokota


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 
like image 20
Andrej Herich Avatar answered Sep 22 '22 08:09

Andrej Herich