Files
NexusLobby/src/main/java/de/nexuslobby/utils/ConfigUpdater.java
2026-02-05 22:44:21 +01:00

85 lines
3.4 KiB
Java

package de.nexuslobby.utils;
import de.nexuslobby.NexusLobby;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class ConfigUpdater {
public static void updateConfig(String fileName) {
NexusLobby plugin = NexusLobby.getInstance();
File configFile = new File(plugin.getDataFolder(), fileName);
if (!configFile.exists()) {
plugin.saveResource(fileName, false);
return;
}
FileConfiguration serverConfig = YamlConfiguration.loadConfiguration(configFile);
List<String> newFileContent = new ArrayList<>();
InputStream resourceStream = plugin.getResource(fileName);
if (resourceStream == null) {
plugin.getLogger().severe("Config-Update fehlgeschlagen: Resource fehlt: " + fileName);
return;
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceStream, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
String trimmed = line.trim();
// 1. Kommentare, Leerzeilen und Listen-Elemente direkt übernehmen
if (trimmed.startsWith("#") || trimmed.isEmpty() || trimmed.startsWith("-")) {
newFileContent.add(line);
continue;
}
// 2. Prüfen ob es ein Key ist
if (trimmed.contains(":") && !trimmed.startsWith("-")) {
String key = trimmed.split(":")[0];
// WICHTIG: Nur wenn der Key KEINE Sektion ist, darf er überschrieben werden
if (serverConfig.contains(key) && !serverConfig.isConfigurationSection(key)) {
String indentation = line.substring(0, line.indexOf(trimmed));
Object value = serverConfig.get(key);
newFileContent.add(indentation + key + ": " + formatValue(value));
} else {
// Es ist eine Sektion oder ein neuer Key -> Original aus JAR übernehmen
newFileContent.add(line);
}
} else {
newFileContent.add(line);
}
}
} catch (IOException e) {
Bukkit.getLogger().severe("Fehler beim Config-Update: " + e.getMessage());
}
// 3. Datei sauber speichern
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(configFile), StandardCharsets.UTF_8))) {
for (String outputLine : newFileContent) {
writer.write(outputLine);
writer.newLine();
}
} catch (IOException e) {
plugin.getLogger().severe("Konnte " + fileName + " nicht speichern!");
}
}
private static String formatValue(Object value) {
if (value == null) return "";
if (value instanceof String) {
// Verhindert das "Zerschießen" der Config durch Sonderzeichen
String s = (String) value;
return "\"" + s.replace("\"", "\\\"") + "\"";
}
return value.toString();
}
}