如何将提交哈希添加到播放模板?

时间:2014-06-12 18:28:21

标签: playframework sbt playframework-2.1 playframework-2.2

我想将提交哈希放入Play Framework模板文件中,以便我可以通过REST GET调用查看构建信息。

在sbt中,我可以获得一个git commit hash和git branch name,无论如何都要在构建过程中将这些信息放入模板文件中?

build.sbt

name := "my-project"

val branch = "git rev-parse --abbrev-ref HEAD".!!.trim
val commit = "git rev-parse HEAD".!!.trim
val buildTime = (new java.text.SimpleDateFormat("yyyyMMdd-HHmmss")).format(new java.util.Date())

version := "%s-%s-%s".format(branch, commit, buildTime)

2 个答案:

答案 0 :(得分:4)

添加我丑陋的解决方案以添加git head hash来构建:
(除了来自 Bob Kuhar 的答案的链接)
我已经有了#la; val root"所以这就是它现在的样子。

lazy val root = (project in file(".")).
  enablePlugins(PlayScala).
  enablePlugins(BuildInfoPlugin).
  settings(
    buildInfoKeys := Seq[BuildInfoKey](
      name, version, scalaVersion, sbtVersion,
      "hostname" -> java.net.InetAddress.getLocalHost().getHostName(),
      "whoami" -> System.getProperty("user.name"),
      "buildTimestamp" -> new java.util.Date(System.currentTimeMillis()),      
      "gitHash" -> new java.lang.Object(){
              override def toString(): String = {
                      try { 
                    val extracted = new java.io.InputStreamReader(
                              java.lang.Runtime.getRuntime().exec("git rev-parse HEAD").getInputStream())                         
                    (new java.io.BufferedReader(extracted)).readLine()
                      } catch {      case t: Throwable => "get git hash failed"    }
              }}.toString()
    ),
    buildInfoPackage := "buildpkg"
  )

答案 1 :(得分:3)

我使用了一个名为sbt-buildinfo的sbt插件来执行此操作。请参阅Does sbt have something like gradle's processResources task with ReplaceTokens support?的答案。从技术上讲,它奏效了。有效地说,每当有任何改变时,Play都会重新加载整个项目。也许他们现在已经克服了这个问题?试试sbt-buildinfo:https://github.com/sbt/sbt-buildinfo#usage

使用示例:

lazy val root = (project in file("."))
  .enablePlugins(BuildInfoPlugin)
  .settings(
    buildInfoKeys := Seq[BuildInfoKey](
      <whateverYouWant>,
      BuildInfoKey.action("commit") {
        scala.sys.process.Process("git rev-parse HEAD").!!.trim
      }
    )
  )