Skip to content

Instantly share code, notes, and snippets.

@denisovlev
Last active March 23, 2020 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save denisovlev/6449672ea1de8d50fc4f7312a875c760 to your computer and use it in GitHub Desktop.
Save denisovlev/6449672ea1de8d50fc4f7312a875c760 to your computer and use it in GitHub Desktop.

Prefix migrations with timestamp SBT task

Run in sbt console prefixMigrations

// build.sbt
// ...
import PrefixMigrations._
prefixMigrationSettings
// project/PrefixMigrations.scala
import java.nio.file.Files
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import sbt._
import Keys._
object PrefixMigrations {
val prefixMigrations = taskKey[Unit]("Adds timestamp prefix to database schema migration files")
val prefixMigrationSettings = Seq[Setting[_]](
prefixMigrations := {
def isFilePrefixed(file: File): Boolean = {
file.name.matches("^V\\d+__.*\\.sql$")
}
val formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")
val dir = new File("schema-migration/src/main/resources/db/migration")
val files = dir.listFiles().toList
files.filterNot(isFilePrefixed).foreach { file =>
val timestamp = formatter.format(LocalDateTime.now())
val newName = s"V${timestamp}__${file.name}"
println(s"Renaming ${file.name} to ${newName}")
Files.move(file.toPath, file.toPath.resolveSibling(newName))
// Sleep for a moment to avoid prefix conflicts when renaming multiple files
Thread.sleep(1*1000)
}
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment