-
-
Save dcsobral/6ef67a8b8c60813ac822c90b84d57d78 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
// I'd rather `collect { case JField(`key`, value } => ...`, though, of course, then you need to check for empty | |
// it's just a personal preference, but I don't like mix-matching case decomposition with method access | |
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