diff options
author | nea <romangraef@gmail.com> | 2022-10-22 00:34:22 +0200 |
---|---|---|
committer | nea <romangraef@gmail.com> | 2022-10-22 00:34:22 +0200 |
commit | f85c449ed586c7ced780423943e55bfa5abaeb0f (patch) | |
tree | 0c5f59c73cc9e5fcb07de6e3f1f102e2413def27 /src/main/kotlin/moe/nea/notenoughupdates/util/data/DataHolder.kt | |
parent | c98d4693f1fc9dcae8d78cb33e6233629f4cb2e7 (diff) | |
download | firmament-f85c449ed586c7ced780423943e55bfa5abaeb0f.tar.gz firmament-f85c449ed586c7ced780423943e55bfa5abaeb0f.tar.bz2 firmament-f85c449ed586c7ced780423943e55bfa5abaeb0f.zip |
rudimentary config gui (again)
Diffstat (limited to 'src/main/kotlin/moe/nea/notenoughupdates/util/data/DataHolder.kt')
-rw-r--r-- | src/main/kotlin/moe/nea/notenoughupdates/util/data/DataHolder.kt | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/data/DataHolder.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/data/DataHolder.kt new file mode 100644 index 0000000..6c9d8e8 --- /dev/null +++ b/src/main/kotlin/moe/nea/notenoughupdates/util/data/DataHolder.kt @@ -0,0 +1,60 @@ +package moe.nea.notenoughupdates.util.data + +import java.nio.file.Path +import kotlinx.serialization.KSerializer +import kotlin.io.path.exists +import kotlin.io.path.readText +import kotlin.io.path.writeText +import moe.nea.notenoughupdates.NotEnoughUpdates + +abstract class DataHolder<T>( + val serializer: KSerializer<T>, + val name: String, + val default: () -> T +) : IDataHolder<T> { + + + final override var data: T + private set + + init { + data = readValueOrDefault() + IDataHolder.putDataHolder(this::class, this) + } + + private val file: Path get() = NotEnoughUpdates.CONFIG_DIR.resolve("$name.json") + + protected fun readValueOrDefault(): T { + if (file.exists()) + try { + return NotEnoughUpdates.json.decodeFromString( + serializer, + file.readText() + ) + } catch (e: Exception) {/* Expecting IOException and SerializationException, but Kotlin doesn't allow multi catches*/ + IDataHolder.badLoads.add(name) + NotEnoughUpdates.logger.error( + "Exception during loading of config file $name. This will reset this config.", + e + ) + } + return default() + } + + private fun writeValue(t: T) { + file.writeText(NotEnoughUpdates.json.encodeToString(serializer, t)) + } + + override fun save() { + writeValue(data) + } + + override fun load() { + data = readValueOrDefault() + } + + override fun markDirty() { + IDataHolder.markDirty(this::class) + } + +} |