Skip to content

Instantly share code, notes, and snippets.

@djspiewak
Created March 9, 2020 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save djspiewak/1827cf8b24545f3895be6a047f10b824 to your computer and use it in GitHub Desktop.
Save djspiewak/1827cf8b24545f3895be6a047f10b824 to your computer and use it in GitHub Desktop.
package slamdata
import sjsonnew.IsoString
import sjsonnew.shaded.scalajson.ast.unsafe.JValue
import sjsonnew.support.scalajson.unsafe.{Converter, Parser, PrettyPrinter}
import java.nio.file.Path
final class ManagedVersions private (path: Path) {
private[this] val store =
new FileBasedStore(
file,
Converter)(
IsoString.iso(PrettyPrinter.apply, Parser.parseUnsafe))
def apply(key: String): String = {
store.read() match {
case JObject(values) =>
values.find(_.field == key) match {
case Some(JField(_, JString(value))) => value
case _ => sys.error(s"unable to find string -> string mapping for key '$key'")
}
case _ =>
sys.error(s"unable to parse managed versions store at $path")
}
}
def update(key: String, version: String): Unit = {
store.read() match {
case JObject(values) =>
var i = 0
var done = false
while (i < values.length && !done) {
if (values(i).field == key) {
values(i) = JField(key, JString(version))
done = true
}
i += 1
}
val values2 = if (!done) {
val values2 = new Array[JField](values.length + 1)
System.arraycopy(values, 0, values2, 0, values.length)
values2(values.length) = JField(key, JString(version))
values2
} else {
values
}
store.write(JObject(values2))
case _ =>
sys.error(s"unable to parse managed versions store at $path")
}
}
}
object ManagedVersions {
def apply(path: Path): ManagedVersions =
new ManagedVersions(path)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment