feat: improved loading and saving logic, made Json loader ignore unknown keys

Signed-off-by: moonleay <contact@moonleay.net>
This commit is contained in:
moonleay 2024-05-11 03:06:01 +02:00
parent 302f486f1c
commit 7325798098
Signed by: moonleay
GPG key ID: 82667543CCD715FB

View file

@ -30,27 +30,30 @@ class ClientConfigHolder(private val path: Path) {
private set private set
init { init {
config = load() this.config = load()
} }
fun updateConfig(new: GimbalClientConfig) { fun updateConfig(new: GimbalClientConfig) {
config = new this.config = new
save(config) this.save(config)
} }
@OptIn(ExperimentalSerializationApi::class) @OptIn(ExperimentalSerializationApi::class)
fun load(): GimbalClientConfig { fun load(): GimbalClientConfig {
if (!path.isReadable()) if (!path.isReadable())
save(GimbalClientConfig()) save(GimbalClientConfig())
return path.inputStream().use { val iStream = path.inputStream()
Json.decodeFromStream(it) val gimbalClientConfig: GimbalClientConfig = iStream.use {
Json {
ignoreUnknownKeys = true
}.decodeFromStream<GimbalClientConfig>(it)
} }
iStream.close()
return gimbalClientConfig
} }
// TODO: Support incomplete config files
@OptIn(ExperimentalSerializationApi::class) @OptIn(ExperimentalSerializationApi::class)
fun save(conf: GimbalClientConfig) { fun save(conf: GimbalClientConfig) {
if (!path.isWritable()) {
if (!path.parent.exists()) { if (!path.parent.exists()) {
path.parent.createDirectory() path.parent.createDirectory()
} }
@ -62,10 +65,13 @@ class ClientConfigHolder(private val path: Path) {
if (!path.isWritable()) { if (!path.isWritable()) {
throw Exception("Path (${path.pathString}) exists, but is not writable.") throw Exception("Path (${path.pathString}) exists, but is not writable.")
} }
val oStream = path.outputStream()
oStream.use {
Json {
ignoreUnknownKeys = true
}.encodeToStream<GimbalClientConfig>(conf, it)
} }
path.outputStream().use { oStream.close()
Json.encodeToStream(conf, it)
}
} }
} }