Настройка уникальной версии моментального снимка при скрещивании в SBT

Когда publish, если в версии есть -SNAPSHOT, я бы хотел заменить его уникальной меткой времени. Я уже сделал это, и он работает, за исключением кросс-здания с +.

Кажется, что параметр version, установленный с меткой времени, очищается, когда версия Scala изменяется для кросс-сборки.

Когда я пытаюсь перекрестно построить publish, я использую следующую команду:

sbt ";stamp-version ;+publish"

Вот код для команды stamp-version:

object TimestampVersion {

  import Version.Snapshot

  lazy val versionSettings = Seq(commands += stampVersion)

  def stampVersion = Command.command("stamp-version") { state =>
    val extracted = Project.extract(state)
    extracted.append(List(version in ThisBuild ~= { ver =>
      val stmp = stamp(ver)
      Logging.info("Stamping version %s".format(stmp))
      stmp
    }), state)
  }

  def stamp(version: String): String = {
    if (version endsWith Snapshot) {
      // we use a dot here to not break rpm versioning rules
      (version stripSuffix Snapshot) + "." + timestamp(System.currentTimeMillis)
    } else {
      version
    }
  }

  def timestamp(time: Long): String = {
    // no delimiter between date & time in order to not break rpm versioning rules
    val sdf = new java.text.SimpleDateFormat("yyyyMMddHHmmss")
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"))
    sdf.format(new Date(time))
  }
}

Есть ли другой способ сохранить мою timestamped версию, к которой могут быть доступны мои кросс-сборки?

РЕДАКТИРОВАТЬ: Чтобы быть ясным, я хочу, чтобы каждая кросс-построенная версия имела одну и ту же метку времени, поэтому, когда я использую ее из другого места, я могу зависеть от этого: "x" %% "y" % "z"

Также было бы лучше, если бы решение могло работать с SBT 0.12.x, поскольку у меня все еще есть эта зависимость.

Ответ 1

Я не уверен, рекомендовал ли он подход в SBT 0.13.x, но следующее, казалось, сработало хорошо для меня.

Если вам нужно "иметь одну и ту же метку времени" для всех версий, перечисленных в crossScalaVersions, тогда вы можете использовать "Генерация файлов" , т.е. IO.write и IO.read, чтобы сохранить файл временной метки с уникальной версией моментального снимка.

ПРИМЕЧАНИЕ Не устанавливайте scalaVersion в build.sbt, поскольку он перезаписывает один, установленный +. Это была проблема в моем первоначальном ответе.

Выполните следующую задачу stampVersion в build.sbt (я оставляю переход на SBT < 0,13 в качестве упражнения):

lazy val stampVersion = taskKey[File]("Generates timestamp file with unique snapshot version")

stampVersion := {
  val log = streams.value.log
  val stmp = System.currentTimeMillis
  val file = target.value / "timestamp"
  log.info(s"Stamping version $stmp saved in $file")
  IO.write(file, s"""$stmp""")
  file
}

Когда вы запускаете задачу stampVersion, файл создается в файле target/timestamp.

Следуя задаче, вы можете прочитать ее содержимое.

lazy val getStampVersion = taskKey[String]("Retrieves unique snapshot version from timestamp file")

getStampVersion := {
  val log = streams.value.log
  val file = (target in Compile).value / "timestamp"
  val v = IO.read(file)
  log.info(s"Retrieving version from $file: $v [scalaVersion: ${scalaVersion.value}]")
  v
}

Используйте show getStampVersion, чтобы показать версию, сохраненную в файле.

[sbt-0-13-1]> stampVersion
[info] Stamping version 1390606523705 saved in /Users/jacek/sandbox/so/sbt-0.13.1/target/timestamp
[success] Total time: 0 s, completed Jan 25, 2014 12:35:23 AM
[sbt-0-13-1]> show getStampVersion
[info] Retrieving version from /Users/jacek/sandbox/so/sbt-0.13.1/target/timestamp: 1390606523705 [scalaVersion: 2.10.3]
[info] 1390606523705
[success] Total time: 0 s, completed Jan 25, 2014 12:35:34 AM

Чтобы установить ключ version в timestamped версию, я определил команду setVersionFromStampFile (поскольку она изменяет состояние проекта).

def setVersionFromStampFile = Command.command("setVersionFromStampFile") { state =>
  val e = Project extract state
  import e._
  val (newState, stampVersion) = runTask(getStampVersion, state)
  val scalaV = scalaVersion in currentRef get structure.data getOrElse Nil
  state.log.info(s"scalaVersion: $scalaV")
  val settings = Seq(
    version := stampVersion
  )
  append(settings ++ structure.settings, state)
}

commands += setVersionFromStampFile

С помощью команды setVersionFromStampFile, когда она запускается, version устанавливается соответствующим образом.

[sbt-0-13-1]> show version
[info] 0.1-SNAPSHOT
[sbt-0-13-1]> setVersionFromStampFile
[info] Retrieving version from /Users/jacek/sandbox/so/sbt-0.13.1/target/timestamp: 1390606523705 [scalaVersion: 2.10.3]
[info] scalaVersion: 2.10.3
[info] Set current project to sbt-0-13-1 (in build file:/Users/jacek/sandbox/so/sbt-0.13.1/)
[sbt-0-13-1]> show version
[info] 1390606523705

В определении сборки build.sbt задайте настройку crossScalaVersions, например.

crossScalaVersions := Seq("2.9.3", "2.10.3")

Определите псевдоним команды setStampAsVersionAndShow в build.sbt, чтобы облегчить тестирование - после выполнения команды setVersionFromStampFile вы увидите значения version и scalaVersion:

addCommandAlias("setStampAsVersionAndShow",
                "; setVersionFromStampFile ; show version; show scalaVersion")

Это позволяет перекрестно выполнять ряд команд:

[sbt-0-13-1]> + setStampAsVersionAndShow
[info] Setting version to 2.9.3
[info] Set current project to sbt-0-13-1 (in build file:/Users/jacek/sandbox/so/sbt-0.13.1/)
[info] Retrieving version from /Users/jacek/sandbox/so/sbt-0.13.1/target/timestamp: 1390606523705 [scalaVersion: 2.9.3]
[info] scalaVersion: 2.9.3
[info] Set current project to sbt-0-13-1 (in build file:/Users/jacek/sandbox/so/sbt-0.13.1/)
[info] 1390606523705
[info] 2.9.3
[info] Setting version to 2.10.3
[info] Set current project to sbt-0-13-1 (in build file:/Users/jacek/sandbox/so/sbt-0.13.1/)
[info] Retrieving version from /Users/jacek/sandbox/so/sbt-0.13.1/target/timestamp: 1390606523705 [scalaVersion: 2.10.3]
[info] scalaVersion: 2.10.3
[info] Set current project to sbt-0-13-1 (in build file:/Users/jacek/sandbox/so/sbt-0.13.1/)
[info] 1390606523705
[info] 2.10.3
[info] Setting version to 2.10.3
[info] Set current project to sbt-0-13-1 (in build file:/Users/jacek/sandbox/so/sbt-0.13.1/)

Определите параметр publishTo и еще один псевдоним команды setStampAsVersionAndPublish в build.sbt:

publishTo := Some(Resolver.file("file", target.value / "xxx"))

addCommandAlias("setStampAsVersionAndPublish",
                "; setVersionFromStampFile ; show scalaVersion ; publish")

Теперь вы должны иметь возможность publish, как и следовало ожидать:

  • Пусть начнется заново.

    [sbt-0-13-1]> clean
    [success] Total time: 0 s, completed Jan 25, 2014 12:50:22 AM
    
  • Создайте файл версии.

    [sbt-0-13-1]> stampVersion
    [info] Stamping version 1390607428495 saved in /Users/jacek/sandbox/so/sbt-0.13.1/target/timestamp
    [success] Total time: 0 s, completed Jan 25, 2014 12:50:28 AM
    
  • Проверьте это с помощью publish без перекрестного построения (нет +).

    [sbt-0-13-1]> setStampAsVersionAndPublish
    [info] Retrieving version from /Users/jacek/sandbox/so/sbt-0.13.1/target/timestamp: 1390607428495 [scalaVersion: 2.10.3]
    [info] scalaVersion: 2.10.3
    [info] Set current project to sbt-0-13-1 (in build file:/Users/jacek/sandbox/so/sbt-0.13.1/)
    [info] 2.10.3
    [info] Packaging /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/sbt-0-13-1_2.10-1390607428495-sources.jar ...
    [info] Done packaging.
    [info] Updating {file:/Users/jacek/sandbox/so/sbt-0.13.1/}sbt-0-13-1...
    [info] Wrote /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/sbt-0-13-1_2.10-1390607428495.pom
    [info] Resolving org.fusesource.jansi#jansi;1.4 ...
    [info] Done updating.
    [info] :: delivering :: default#sbt-0-13-1_2.10;1390607428495 :: 1390607428495 :: release :: Sat Jan 25 00:50:33 CET 2014
    [info]  delivering ivy file to /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/ivy-1390607428495.xml
    [info] Compiling 1 Scala source to /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/classes...
    [info] Main Scala API documentation to /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/api...
    model contains 2 documentable templates
    [info] Main Scala API documentation successful.
    [info] Packaging /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/sbt-0-13-1_2.10-1390607428495-javadoc.jar ...
    [info] Done packaging.
    [info] Packaging /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/sbt-0-13-1_2.10-1390607428495.jar ...
    [info] Done packaging.
    [info]  published sbt-0-13-1_2.10 to /Users/jacek/sandbox/so/sbt-0.13.1/target/xxx/default/sbt-0-13-1_2.10/1390607428495/sbt-0-13-1_2.10-1390607428495.pom
    [info]  published sbt-0-13-1_2.10 to /Users/jacek/sandbox/so/sbt-0.13.1/target/xxx/default/sbt-0-13-1_2.10/1390607428495/sbt-0-13-1_2.10-1390607428495.jar
    [info]  published sbt-0-13-1_2.10 to /Users/jacek/sandbox/so/sbt-0.13.1/target/xxx/default/sbt-0-13-1_2.10/1390607428495/sbt-0-13-1_2.10-1390607428495-sources.jar
    [info]  published sbt-0-13-1_2.10 to /Users/jacek/sandbox/so/sbt-0.13.1/target/xxx/default/sbt-0-13-1_2.10/1390607428495/sbt-0-13-1_2.10-1390607428495-javadoc.jar
    [success] Total time: 1 s, completed Jan 25, 2014 12:50:34 AM
    
  • Дайте окончательную команду go - +, чтобы войти в сцену.

    [sbt-0-13-1]> + setStampAsVersionAndPublish
    [info] Setting version to 2.9.3
    [info] Set current project to sbt-0-13-1 (in build file:/Users/jacek/sandbox/so/sbt-0.13.1/)
    [info] Retrieving version from /Users/jacek/sandbox/so/sbt-0.13.1/target/timestamp: 1390607428495 [scalaVersion: 2.9.3]
    [info] scalaVersion: 2.9.3
    [info] Set current project to sbt-0-13-1 (in build file:/Users/jacek/sandbox/so/sbt-0.13.1/)
    [info] 2.9.3
    [info] Packaging /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.9.3/sbt-0-13-1_2.9.3-1390607428495-sources.jar ...
    [info] Done packaging.
    [info] Updating {file:/Users/jacek/sandbox/so/sbt-0.13.1/}sbt-0-13-1...
    [info] Wrote /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.9.3/sbt-0-13-1_2.9.3-1390607428495.pom
    [info] Resolving org.fusesource.jansi#jansi;1.4 ...
    [info] Done updating.
    [info] :: delivering :: default#sbt-0-13-1_2.9.3;1390607428495 :: 1390607428495 :: release :: Sat Jan 25 00:50:51 CET 2014
    [info] Compiling 1 Scala source to /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.9.3/classes...
    [info]  delivering ivy file to /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.9.3/ivy-1390607428495.xml
    [info] Main Scala API documentation to /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.9.3/api...
    model contains 2 documentable templates
    [info] Main Scala API documentation successful.
    [info] Packaging /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.9.3/sbt-0-13-1_2.9.3-1390607428495-javadoc.jar ...
    [info] Done packaging.
    [info] Packaging /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.9.3/sbt-0-13-1_2.9.3-1390607428495.jar ...
    [info] Done packaging.
    [info]  published sbt-0-13-1_2.9.3 to /Users/jacek/sandbox/so/sbt-0.13.1/target/xxx/default/sbt-0-13-1_2.9.3/1390607428495/sbt-0-13-1_2.9.3-1390607428495.pom
    [info]  published sbt-0-13-1_2.9.3 to /Users/jacek/sandbox/so/sbt-0.13.1/target/xxx/default/sbt-0-13-1_2.9.3/1390607428495/sbt-0-13-1_2.9.3-1390607428495.jar
    [info]  published sbt-0-13-1_2.9.3 to /Users/jacek/sandbox/so/sbt-0.13.1/target/xxx/default/sbt-0-13-1_2.9.3/1390607428495/sbt-0-13-1_2.9.3-1390607428495-sources.jar
    [info]  published sbt-0-13-1_2.9.3 to /Users/jacek/sandbox/so/sbt-0.13.1/target/xxx/default/sbt-0-13-1_2.9.3/1390607428495/sbt-0-13-1_2.9.3-1390607428495-javadoc.jar
    [success] Total time: 4 s, completed Jan 25, 2014 12:50:54 AM
    [info] Setting version to 2.10.3
    [info] Set current project to sbt-0-13-1 (in build file:/Users/jacek/sandbox/so/sbt-0.13.1/)
    [info] Retrieving version from /Users/jacek/sandbox/so/sbt-0.13.1/target/timestamp: 1390607428495 [scalaVersion: 2.10.3]
    [info] scalaVersion: 2.10.3
    [info] Set current project to sbt-0-13-1 (in build file:/Users/jacek/sandbox/so/sbt-0.13.1/)
    [info] 2.10.3
    [info] Packaging /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/sbt-0-13-1_2.10-1390607428495-sources.jar ...
    [info] Done packaging.
    [info] Updating {file:/Users/jacek/sandbox/so/sbt-0.13.1/}sbt-0-13-1...
    [info] Wrote /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/sbt-0-13-1_2.10-1390607428495.pom
    [info] Resolving org.fusesource.jansi#jansi;1.4 ...
    [info] Done updating.
    [info] :: delivering :: default#sbt-0-13-1_2.10;1390607428495 :: 1390607428495 :: release :: Sat Jan 25 00:50:55 CET 2014
    [info]  delivering ivy file to /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/ivy-1390607428495.xml
    [info] Compiling 1 Scala source to /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/classes...
    [info] Main Scala API documentation to /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/api...
    model contains 2 documentable templates
    [info] Main Scala API documentation successful.
    [info] Packaging /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/sbt-0-13-1_2.10-1390607428495-javadoc.jar ...
    [info] Done packaging.
    [info] Packaging /Users/jacek/sandbox/so/sbt-0.13.1/target/scala-2.10/sbt-0-13-1_2.10-1390607428495.jar ...
    [info] Done packaging.
    [info]  published sbt-0-13-1_2.10 to /Users/jacek/sandbox/so/sbt-0.13.1/target/xxx/default/sbt-0-13-1_2.10/1390607428495/sbt-0-13-1_2.10-1390607428495.pom
    [info]  published sbt-0-13-1_2.10 to /Users/jacek/sandbox/so/sbt-0.13.1/target/xxx/default/sbt-0-13-1_2.10/1390607428495/sbt-0-13-1_2.10-1390607428495.jar
    [info]  published sbt-0-13-1_2.10 to /Users/jacek/sandbox/so/sbt-0.13.1/target/xxx/default/sbt-0-13-1_2.10/1390607428495/sbt-0-13-1_2.10-1390607428495-sources.jar
    [info]  published sbt-0-13-1_2.10 to /Users/jacek/sandbox/so/sbt-0.13.1/target/xxx/default/sbt-0-13-1_2.10/1390607428495/sbt-0-13-1_2.10-1390607428495-javadoc.jar
    [success] Total time: 2 s, completed Jan 25, 2014 12:50:56 AM
    [info] Setting version to 2.10.3
    [info] Set current project to sbt-0-13-1 (in build file:/Users/jacek/sandbox/so/sbt-0.13.1/)
    
  • Отобразить основную информацию о sbt и сборке с помощью about.

    [sbt-0-13-1]> about
    [info] This is sbt 0.13.1
    [info] The current project is {file:/Users/jacek/sandbox/so/sbt-0.13.1/}sbt-0-13-1 0.1-SNAPSHOT
    [info] The current project is built against Scala 2.10.3
    [info] Available Plugins: com.typesafe.sbt.SbtGit, com.typesafe.sbt.SbtProguard, growl.GrowlingTests, np.Plugin, com.timushev.sbt.updates.UpdatesPlugin
    [info] sbt, sbt plugins, and build definitions are using Scala 2.10.3