scala - 如何使用 SBT 使用 build.scala 中的 -D 变量?

标签 scala sbt

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

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

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

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

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

我会做“-Dbranch=unstable”或“-Dbranch=stable”

我非常不清楚如何使用 SBT 和 build.scala 文件来做到这一点。

最佳答案

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

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

如果您想从 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

p.s myproj.build.properties 文件如下所示:

sbt.version=0.13.1

scalaVersion=2.10.4

parallelExecution=true

branch=stable

关于scala - 如何使用 SBT 使用 build.scala 中的 -D 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26394237/

相关文章:

java - 如何将 web3j 库加载到 sbt 项目?

java - 适用于 Android 的 Scala 库

scala - SBT:可以从磁盘读取变量吗?

scala - 使用安全助手不编译 : play framework 2. 3.x

json - 如何使用 json4s 从 akka-http 响应实体读取 json 响应

scala - 如何将Scala宏作为项目分发?

scala - 使用SBT程序集JAR在Spark提交中,Spark无法找到应用程序类本身(ClassNotFoundException)

scala - sbt test-only 在 fork jvm 进行测试时不选择 jvm 选项

java - 在scala中重用java连接池

scala - 在 Scala 中有一个 'empty' 的 case 语句是什么意思?