Skip to content

Commit

Permalink
fix NPE cause by empty config file, fixes #11
Browse files Browse the repository at this point in the history
  • Loading branch information
gliscowo committed Jun 16, 2022
1 parent 7358a61 commit fa4ff16
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 17 deletions.
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ minecraft_version=1.19
yarn_mappings=1.19+build.1
loader_version=0.14.7
# Mod Properties
mod_version=0.2.9
mod_version=0.2.10
maven_group=com.glisco
archives_base_name=deathlog
# Dependencies
Expand Down
42 changes: 26 additions & 16 deletions src/main/java/com/glisco/deathlog/client/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,40 +5,50 @@
import com.google.gson.GsonBuilder;
import net.fabricmc.loader.api.FabricLoader;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class Config {

private static Config INSTANCE = new Config();
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private static final String configFileName = "deathlog.json";

public boolean screenshotsEnabled = false;

public static void save() {
try (var writer = new FileWriter(FabricLoader.getInstance().getConfigDir().resolve(configFileName).toFile())) {
GSON.toJson(INSTANCE, writer);
public static void load() {
if (!Files.exists(configPath())) {
save();
return;
}

try (var input = Files.newInputStream(configPath())) {
INSTANCE = GSON.fromJson(new InputStreamReader(input, StandardCharsets.UTF_8), Config.class);
} catch (IOException e) {
BaseDeathLogStorage.LOGGER.warn("Could not save config", e);
BaseDeathLogStorage.LOGGER.warn("Could not load config", e);
}
}

public static void load() {
try (var reader = new FileReader(FabricLoader.getInstance().getConfigDir().resolve(configFileName).toFile())) {
INSTANCE = GSON.fromJson(reader, Config.class);
public static void save() {
try (var output = Files.newOutputStream(configPath()); var writer = new OutputStreamWriter(output, StandardCharsets.UTF_8)) {
GSON.toJson(INSTANCE, writer);
} catch (IOException e) {
if (e instanceof FileNotFoundException) {
save();
} else {
BaseDeathLogStorage.LOGGER.warn("Could not load config", e);
}
BaseDeathLogStorage.LOGGER.warn("Could not save config", e);
}
}

public static Config instance() {
if (INSTANCE == null) {
INSTANCE = new Config();
}

return INSTANCE;
}

private static Path configPath() {
return FabricLoader.getInstance().getConfigDir().resolve("deathlog.json");
}
}

0 comments on commit fa4ff16

Please sign in to comment.