我可以从代码访问我的 Scala 应用程序的名称和版本(在 SBT 中设置)吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8732891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I access my Scala app's name and version (as set in SBT) from code?
提问by Alex Dean
I am building an app with SBT (0.11.0) using a Scala build definition like so:
我正在使用 Scala 构建定义构建一个带有 SBT (0.11.0) 的应用程序,如下所示:
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.
我在过程结束时打包了一个 .jar。
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.
我的问题很简单:有没有办法从我的 Scala 代码中以编程方式访问应用程序的名称(“my-app-name”)和版本(“0.1”)?如果可以的话,我不想在两个地方重复它们。
Any guidance greatly appreciated!
非常感谢任何指导!
采纳答案by Eugene Yokota
sbt-buildinfo
sbt-buildinfo
I just wrote sbt-buildinfo. After installing the plugin:
我刚刚写了sbt-buildinfo。安装插件后:
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.
编辑:以上代码段已更新以反映 sbt-buildinfo 的更新版本。
It generates foo.BuildInfoobject with any setting you want by customizing buildInfoKeys.
它foo.BuildInfo通过自定义生成具有您想要的任何设置的对象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.
您可以将您的版本作为foo.Info.version.

