From fdd8676ce9a652718d7bbcfcd6335eec66d7ff6a Mon Sep 17 00:00:00 2001 From: Caoimhe Date: Fri, 14 Jul 2023 20:16:09 +0100 Subject: [PATCH] CompactChatClient: Migrate old `.json5` files to `.json` --- .../compactchat/CompactChatClient.java | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/main/java/dev/caoimhe/compactchat/CompactChatClient.java b/src/main/java/dev/caoimhe/compactchat/CompactChatClient.java index e89ddb3..a14c34a 100644 --- a/src/main/java/dev/caoimhe/compactchat/CompactChatClient.java +++ b/src/main/java/dev/caoimhe/compactchat/CompactChatClient.java @@ -4,9 +4,11 @@ import dev.caoimhe.compactchat.util.CollectionUtil; import dev.caoimhe.compactchat.util.FabricLoaderUtil; import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.loader.api.FabricLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.file.Files; import java.util.List; public class CompactChatClient implements ClientModInitializer { @@ -22,12 +24,41 @@ public class CompactChatClient implements ClientModInitializer { @Override public void onInitializeClient() { + this.migrateJson5Configuration(); + Configuration.register(); - // TODO: Migrate old .json5 config files to .json var message = CollectionUtil.randomFrom(STARTUP_MESSAGES); message = message.replace("{RANDOM_MOD}", FabricLoaderUtil.getRandomModName()); LOGGER.info(message + " (Compact Chat is ready!)"); } + + /** + * Migrates the old JSON5 configuration file to the new JSON configuration file. + * We can't really remove this, because it would break the configuration for users who are updating from 2.0.1 or below. + */ + private void migrateJson5Configuration() { + // Exceptions shouldn't really happen (apart from Files#move), but we don't want this to prevent the user from starting their game. + try { + var oldFile = FabricLoader.getInstance().getConfigDir().resolve("compact-chat.json5"); + if (!Files.exists(oldFile)) { + LOGGER.debug("No old configuration file found. Skipping automatic migration."); + return; + } + + var newFile = FabricLoader.getInstance().getConfigDir().resolve("compact-chat.json"); + if (Files.exists(newFile)) { + LOGGER.warn("Both an old (<=2.0.1) and new configuration file (>=2.1.0) exist. Skipping automatic migration."); + return; + } + + Files.move(oldFile, newFile); + LOGGER.info("Successfully migrated old configuration file."); + } catch (Exception e) { + LOGGER.error("Failed to migrate old configuration file!", e); + LOGGER.error("Please manually migrate your old configuration file (config/compact-chat.json5) to the new location (config/compact-chat.json)."); + LOGGER.error("If you don't do this, your configuration will be reset to the default values."); + } + } } \ No newline at end of file