How to share version values between project/plugins.sbt and project/Build.scala?

后端 未结 3 884
情话喂你
情话喂你 2020-12-01 13:02

I would like to share a common version variable between an sbtPlugin and the rest of the build

Here is what I am trying:

in project/Build.scala:

3条回答
  •  日久生厌
    2020-12-01 13:38

    My proposal is to hack. For example, in build.sbt you can add a task:

    val readPluginSbt = taskKey[String]("Read plugins.sbt file.")
    
    readPluginSbt := {
            val lineIterator = scala.io.Source.fromFile(new java.io.File("project","plugins.sbt")).getLines
                val linesWithValIterator = lineIterator.filter(line => line.contains("scalaxbVersion"))
                val versionString =  linesWithValIterator.mkString("\n").split("=")(1).trim
                val version = versionString.split("\n")(0) // only val declaration
            println(version)
            version
        }
    

    When you call readPluginSbt you will see the contents of plugins.sbt. You can parse this file and extract the variable.

    For example:

    resolvers += Resolver.sonatypeRepo("public")
    
    val scalaxbVersion = "1.1.2"
    
    addSbtPlugin("org.scalaxb" % "sbt-scalaxb" % scalaxbVersion)
    
    addSbtPlugin("org.xerial.sbt" % "sbt-pack" % "0.5.1")
    

    You can extract scalaxbVersion with regular expressions/split:

    scala> val line = """val scalaxbVersion = "1.1.2""""
    line: String = val scalaxbVersion = "1.1.2"
    
    scala>  line.split("=")(1).trim
    res1: String = "1.1.2"
    

提交回复
热议问题