From 7325798098cdbf4789bd84d04b9c0f527eca777a Mon Sep 17 00:00:00 2001 From: moonleay Date: Sat, 11 May 2024 03:06:01 +0200 Subject: [PATCH] feat: improved loading and saving logic, made Json loader ignore unknown keys Signed-off-by: moonleay --- .../client/config/ClientConfigHolder.kt | 44 +++++++++++-------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/src/main/java/net/moonleay/gimbal/client/config/ClientConfigHolder.kt b/src/main/java/net/moonleay/gimbal/client/config/ClientConfigHolder.kt index b4d38ba..0b7769e 100644 --- a/src/main/java/net/moonleay/gimbal/client/config/ClientConfigHolder.kt +++ b/src/main/java/net/moonleay/gimbal/client/config/ClientConfigHolder.kt @@ -30,42 +30,48 @@ class ClientConfigHolder(private val path: Path) { private set init { - config = load() + this.config = load() } fun updateConfig(new: GimbalClientConfig) { - config = new - save(config) + this.config = new + this.save(config) } @OptIn(ExperimentalSerializationApi::class) fun load(): GimbalClientConfig { if (!path.isReadable()) save(GimbalClientConfig()) - return path.inputStream().use { - Json.decodeFromStream(it) + val iStream = path.inputStream() + val gimbalClientConfig: GimbalClientConfig = iStream.use { + Json { + ignoreUnknownKeys = true + }.decodeFromStream(it) } + iStream.close() + return gimbalClientConfig } - // TODO: Support incomplete config files @OptIn(ExperimentalSerializationApi::class) fun save(conf: GimbalClientConfig) { + if (!path.parent.exists()) { + path.parent.createDirectory() + } + if (!path.parent.isWritable()) { + throw Exception("Parent of path ${path.parent.pathString} is not writable.") + } + if (!path.exists()) + path.createFile() if (!path.isWritable()) { - if (!path.parent.exists()) { - path.parent.createDirectory() - } - if (!path.parent.isWritable()) { - throw Exception("Parent of path ${path.parent.pathString} is not writable.") - } - if (!path.exists()) - path.createFile() - if (!path.isWritable()) { - throw Exception("Path (${path.pathString}) exists, but is not writable.") - } + throw Exception("Path (${path.pathString}) exists, but is not writable.") } - path.outputStream().use { - Json.encodeToStream(conf, it) + val oStream = path.outputStream() + oStream.use { + Json { + ignoreUnknownKeys = true + }.encodeToStream(conf, it) } + oStream.close() } }