如何使用 SBT 在 build.scala 中使用 -D 变量? [英] How do I consume -D variables in build.scala using SBT?

查看:35
本文介绍了如何使用 SBT 在 build.scala 中使用 -D 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 build.scala 文件,它的依赖项如下所示:

I have a build.scala file that has a dependency that looks like this:

"com.example" % "core" % "2.0" classifier "full-unstable"

这会引入一个带有完全不稳定分类器的 JAR

This pulls in a JAR with the classifier of full-unstable

我需要做的是从 Jenkins(构建服务器)为 SBT(使用我假设的 -D)指定不稳定"或稳定"以更改分类器.如果变量替换像在 Maven 中那样工作,则依赖项将如下所示:

What I need to do is specify either "unstable" or "stable" to SBT (using a -D I presume) from Jenkins (the build server) to change the classifier. If variable substitution worked like it does in Maven, the dependency would look like:

"com.example" % "core" % "2.0" classifier "full-${branch}"

我会做-Dbranch=unstable"或-Dbranch=stable"

And I would do "-Dbranch=unstable" or "-Dbranch=stable"

我不太清楚我是如何使用 SBT 和 build.scala 文件做到这一点的.

I'm very unclear how I do this with SBT and a build.scala file.

推荐答案

您可以简单地访问 sys.props:表示当前系统属性的双向可变映射."所以,你可以这样做:

You can simply access sys.props: "A bidirectional, mutable Map representing the current system Properties." So, you can do something like this:

val branch = "full-" + sys.props.getOrElse("branch", "unstable")
"com.example" % "core" % "2.0" classifier branch

如果您想从 Build.scala 中的文件中获得更高级的自定义属性:

If you want to have more advanced custom properties from file in your Build.scala:

import java.io.{BufferedReader, InputStreamReader, FileInputStream, File}
import java.nio.charset.Charset
import java.util.Properties

object MyBuild extends Build {

  // updates system props (mutable map of props)
  loadSystemProperties("project/myproj.build.properties")

  def loadSystemProperties(fileName: String): Unit = {
    import scala.collection.JavaConverters._
    val file = new File(fileName)
    if (file.exists()) {
      println("Loading system properties from file `" + fileName + "`")
      val in = new InputStreamReader(new FileInputStream(file), "UTF-8")
      val props = new Properties
      props.load(in)
      in.close()
      sys.props ++ props.asScala
    }
  }

  // to test try:
  println(sys.props.getOrElse("branch", "unstable"))
}

SBT 比 Maven 更强大,因为如果您需要非常定制的东西,您可以简单地编写 Scala 代码.在这种情况下,您可能希望使用 Build.scala 而不是 build.sbt.

SBT is more powerful than Maven because you can simply write Scala code if you need something very custom. You would want to use Build.scala instead of build.sbt in such case.

p.s myproj.build.properties 文件看起来像这样,例如:

p.s myproj.build.properties file looks like this for example:

sbt.version=0.13.1

scalaVersion=2.10.4

parallelExecution=true

branch=stable

这篇关于如何使用 SBT 在 build.scala 中使用 -D 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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