Skip to content

Commit

Permalink
Add config upgrading
Browse files Browse the repository at this point in the history
  • Loading branch information
Juuxel committed Sep 9, 2019
1 parent 78b3f1e commit 6102239
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/main/kotlin/juuxel/adorn/config/AdornConfigManager.kt
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package juuxel.adorn.config

import blue.endless.jankson.Jankson
import blue.endless.jankson.JsonObject
import net.fabricmc.loader.api.FabricLoader
import org.apache.logging.log4j.LogManager
import java.nio.file.Files

object AdornConfigManager {
private val JANKSON = Jankson.builder().build()
private val DEFAULT = JANKSON.toJson(AdornConfig()) as JsonObject
private val CONFIG_PATH = FabricLoader.getInstance().configDirectory.toPath().resolve("Adorn.json5")
private val LOGGER = LogManager.getLogger()

@get:JvmName("getConfig")
val CONFIG: AdornConfig by lazy {
Expand All @@ -15,7 +19,15 @@ object AdornConfigManager {
}

try {
JANKSON.fromJsonCarefully(Files.readAllLines(CONFIG_PATH).joinToString("\n"), AdornConfig::class.java)
val obj = JANKSON.load(Files.readAllLines(CONFIG_PATH).joinToString("\n"))
val config = JANKSON.fromJsonCarefully(obj, AdornConfig::class.java)

if (isMissingKeys(obj, DEFAULT)) {
LOGGER.info("[Adorn] Upgrading config...")
save(config)
}

config
} catch (e: Exception) {
throw RuntimeException("Failed to load Adorn config file!", e)
}
Expand All @@ -31,4 +43,16 @@ object AdornConfigManager {
private fun save(config: AdornConfig) {
Files.write(CONFIG_PATH, JANKSON.toJson(config).toJson(true, true).lines())
}

private fun isMissingKeys(config: JsonObject, defaults: JsonObject): Boolean {
for ((key, value) in defaults) {
if (!config.containsKey(key)) return true

if (value is JsonObject && isMissingKeys(config.get(JsonObject::class.java, key) ?: return true, value)) {
return true
}
}

return false
}
}

0 comments on commit 6102239

Please sign in to comment.