【问题标题】:How do I consume -D variables in build.scala using SBT?如何使用 SBT 在 build.scala 中使用 -D 变量?
【发布时间】:2014-10-17 09:20:40
【问题描述】:

我有一个 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 文件来做到这一点。

【问题讨论】:

    标签: scala sbt


    【解决方案1】:

    您可以简单地访问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
    

    【讨论】:

    • SBT 不是已经在 build.properties 中读取,您必须手动执行吗?或者我记错了。
    • 是的。我展示了一个额外的 build.properties 文件示例,您可能拥有 Jenkins 并且也可以由 Jenkins 预构建步骤自动生成。我将重命名示例中的文件名以避免混淆。
    猜你喜欢
    • 1970-01-01
    • 2014-12-11
    • 2015-05-03
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多