mirror of
https://codeberg.org/moonleay/Gimbal.git
synced 2024-11-25 22:22:10 +00:00
feat: improved loading and saving logic, made Json loader ignore unknown keys
Signed-off-by: moonleay <contact@moonleay.net>
This commit is contained in:
parent
302f486f1c
commit
7325798098
1 changed files with 25 additions and 19 deletions
|
@ -30,42 +30,48 @@ 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.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.isWritable()) {
|
||||||
if (!path.parent.exists()) {
|
throw Exception("Path (${path.pathString}) exists, but is not writable.")
|
||||||
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.")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
path.outputStream().use {
|
val oStream = path.outputStream()
|
||||||
Json.encodeToStream(conf, it)
|
oStream.use {
|
||||||
|
Json {
|
||||||
|
ignoreUnknownKeys = true
|
||||||
|
}.encodeToStream<GimbalClientConfig>(conf, it)
|
||||||
}
|
}
|
||||||
|
oStream.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue