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

Chr*_*ler 6 scala sbt

我有一个build.scala文件,其依赖关系如下所示:

"com.example" % "core" % "2.0" classifier "full-unstable"
Run Code Online (Sandbox Code Playgroud)

这会使用完全不稳定的分类器来提取JAR

我需要做的是从Jenkins(构建服务器)向SBT(使用-DI presme)指定"unstable"或"stable"以更改分类器.如果变量替换像在Maven中那样工作,则依赖关系看起来像:

"com.example" % "core" % "2.0" classifier "full-${branch}"
Run Code Online (Sandbox Code Playgroud)

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

我很不清楚如何使用SBT和build.scala文件执行此操作.

yǝs*_*ǝla 10

您只需访问sys.props:"表示当前系统属性的双向可变Map." 所以,你可以这样做:

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

如果您希望从以下文件中获得更高级的自定义属性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"))
}
Run Code Online (Sandbox Code Playgroud)

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

ps myproj.build.properties文件看起来像这样:

sbt.version=0.13.1

scalaVersion=2.10.4

parallelExecution=true

branch=stable
Run Code Online (Sandbox Code Playgroud)