SBT including the version number in a program

前端 未结 4 1150
春和景丽
春和景丽 2020-12-13 19:36

I want a program I\'m building to be able to report its own version at runtime (e.g. scala myprog.jar --version). Traditionally in a maven project, I\'d use res

4条回答
  •  隐瞒了意图╮
    2020-12-13 20:20

    In general, without any plugins, you can do something like this:

    sourceGenerators in Compile += Def.task {
      val file = (sourceManaged in Compile).value / "foo" / "bar" / "BuildInfo.scala"
    
      IO.write(
        file,
        s"""package foo.bar
           |object BuildInfo {
           |  val Version = "${version.value}"
           |}""".stripMargin
      )
    
      Seq(file)
    }.taskValue
    

    And then do with foo.bar.BuildInfo.Version constant whatever you like.

    Or more general:

    def generateBuildInfo(packageName: String,
                          objectName: String = "BuildInfo"): Setting[_] =
      sourceGenerators in Compile += Def.task {
        val file =
          packageName
            .split('.')
            .foldLeft((sourceManaged in Compile).value)(_ / _) / s"$objectName.scala"
    
        IO.write(
          file,
          s"""package $packageName
             |object $objectName {
             |  val Version = "${version.value}"
             |}""".stripMargin
        )
    
        Seq(file)
      }.taskValue
    

    Example:

    settings(generateBuildInfo("foo.bar"))
    

    You can even change this to pass object properties as a Map[String, String] and generate the object appropriately.

提交回复
热议问题