From 08f954e289d515cb461a7f822b06705a11130251 Mon Sep 17 00:00:00 2001 From: bluefireoly Date: Sat, 31 Oct 2020 15:08:42 +0100 Subject: [PATCH] Added saveAfterLoad option --- .../net/axay/kspigot/config/ConfigManager.kt | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/src/main/kotlin/net/axay/kspigot/config/ConfigManager.kt b/src/main/kotlin/net/axay/kspigot/config/ConfigManager.kt index 5e621579..fc24879b 100644 --- a/src/main/kotlin/net/axay/kspigot/config/ConfigManager.kt +++ b/src/main/kotlin/net/axay/kspigot/config/ConfigManager.kt @@ -21,6 +21,9 @@ import kotlin.reflect.KProperty * * @param T The class type of the config. * @param file The path to the config. + * @param saveAfterLoad If true, the loaded config will be saved + * immediately. This is useful, if the config structure was changed + * and new default parameters were applied. * @param default Optional default config, which will be * used if there is no config file and a new one should * be created. @@ -29,8 +32,9 @@ import kotlin.reflect.KProperty */ inline fun kSpigotJsonConfig( file: File, + saveAfterLoad: Boolean, noinline default: (() -> T)? = null, -) = ConfigDelegate(T::class, file, default) +) = ConfigDelegate(T::class, file, saveAfterLoad, default) /** * @see kSpigotJsonConfig @@ -38,6 +42,7 @@ inline fun kSpigotJsonConfig( class ConfigDelegate( private val configClass: KClass, private val file: File, + private val saveAfterLoad: Boolean, private val defaultCallback: (() -> T)? ) { @@ -73,10 +78,20 @@ class ConfigDelegate( internalConfig = toSave } - private fun loadIt() = if (defaultCallback == null) - GsonConfigManager.loadConfig(file, configClass) - else - GsonConfigManager.loadOrCreateDefault(file, configClass, true, defaultCallback) + private fun loadIt(): T { + + val loaded = if (defaultCallback == null) + GsonConfigManager.loadConfig(file, configClass) + else + GsonConfigManager.loadOrCreateDefault(file, configClass, true, defaultCallback) + + + if (saveAfterLoad) + saveIt(loaded) + + return loaded + + } }