我可以从代码中访问我的 Scala 应用程序的名称和版本(在 SBT 中设置)吗? [英] Can I access my Scala app's name and version (as set in SBT) from code?

查看:13
本文介绍了我可以从代码中访问我的 Scala 应用程序的名称和版本(在 SBT 中设置)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SBT (0.11.0) 使用 Scala 构建定义构建一个应用程序,如下所示:

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: _*)
    [...]

我将在过程结束时打包一个 .jar.

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

我的问题很简单:有没有办法从我的 Scala 代码中以编程方式访问应用程序的名称(my-app-name")和版本(0.1")?如果可以的话,我不想在两个地方重复它们.

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.

非常感谢任何指导!

推荐答案

sbt-buildinfo

我刚刚写了 sbt-buildinfo.安装插件后:

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

以上代码段已更新以反映 sbt-buildinfo 的更新版本.

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

它通过自定义 buildInfoKeys 生成具有您想要的任何设置的 foo.BuildInfo 对象.

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

我一直想为此制作一个插件,(我写了它)但这里有一个生成文件的快速脚本:

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)
}

您可以通过 foo.Info.version 获取您的版本.

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

这篇关于我可以从代码中访问我的 Scala 应用程序的名称和版本(在 SBT 中设置)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆