53 lines
1.9 KiB
Java
53 lines
1.9 KiB
Java
package io.gitlab.jfronny.libjf.config.impl;
|
|
|
|
import io.gitlab.jfronny.gson.JsonElement;
|
|
import io.gitlab.jfronny.gson.JsonParser;
|
|
import io.gitlab.jfronny.gson.stream.JsonWriter;
|
|
import io.gitlab.jfronny.libjf.unsafe.JfLanguageAdapter;
|
|
import net.fabricmc.loader.api.FabricLoader;
|
|
import net.fabricmc.loader.impl.util.log.Log;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.BufferedWriter;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
|
|
/** Based on https://github.com/TeamMidnightDust/MidnightLib which is based on https://github.com/Minenash/TinyConfig
|
|
* Credits to TeamMidnightDust and Minenash */
|
|
public class ConfigInstanceRoot extends ConfigInstanceAbstract {
|
|
public final Path path;
|
|
|
|
public ConfigInstanceRoot(String modId, Class<?> config, AuxiliaryMetadata meta) {
|
|
super(modId, "", config, meta);
|
|
path = FabricLoader.getInstance().getConfigDir().resolve(modId + ".json");
|
|
load();
|
|
}
|
|
|
|
@Override
|
|
public void load() {
|
|
if (Files.exists(path)) {
|
|
try (BufferedReader br = Files.newBufferedReader(path)) {
|
|
JsonElement element = JsonParser.parseReader(br);
|
|
if (element.isJsonObject()) loadFrom(element.getAsJsonObject());
|
|
else Log.error(JfLanguageAdapter.LOG_CATEGORY, "Invalid config: Not a JSON object for " + modId);
|
|
}
|
|
catch (Exception e) {
|
|
Log.error(JfLanguageAdapter.LOG_CATEGORY, "Could not read config for " + modId, e);
|
|
}
|
|
}
|
|
write();
|
|
}
|
|
|
|
@Override
|
|
public void write() {
|
|
JfConfigWatchService.lock(path, () -> {
|
|
try (BufferedWriter bw = Files.newBufferedWriter(path);
|
|
JsonWriter jw = ConfigHolderImpl.GSON.newJsonWriter(bw)) {
|
|
writeTo(jw);
|
|
} catch (Exception e) {
|
|
Log.error(JfLanguageAdapter.LOG_CATEGORY, "Could not write config", e);
|
|
}
|
|
});
|
|
}
|
|
}
|