63 lines
2.4 KiB
Java
63 lines
2.4 KiB
Java
package games.dmg.spigotbase;
|
|
|
|
import java.io.IOException;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.file.AtomicMoveNotSupportedException;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
import java.nio.file.StandardCopyOption;
|
|
import java.util.function.Consumer;
|
|
import org.bukkit.plugin.IllegalPluginAccessException;
|
|
import org.bukkit.plugin.java.JavaPlugin;
|
|
|
|
/** Config persistence with observable failure; no Bukkit configuration objects cross threads. */
|
|
final class ConfigFileStore {
|
|
private final Path path;
|
|
|
|
ConfigFileStore(Path path) {
|
|
this.path = path.toAbsolutePath();
|
|
}
|
|
|
|
void save(String yaml) throws IOException {
|
|
if (Files.isDirectory(path)) {
|
|
throw new IOException("Config target is a directory");
|
|
}
|
|
Path temporary = Files.createTempFile(path.getParent(), "config-", ".yml.tmp");
|
|
try {
|
|
Files.writeString(temporary, yaml, StandardCharsets.UTF_8);
|
|
try {
|
|
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
|
} catch (AtomicMoveNotSupportedException exception) {
|
|
Files.move(temporary, path, StandardCopyOption.REPLACE_EXISTING);
|
|
}
|
|
} finally {
|
|
Files.deleteIfExists(temporary);
|
|
}
|
|
}
|
|
|
|
static void saveAsync(JavaPlugin plugin, String yaml, Consumer<Exception> completed) {
|
|
var scheduler = plugin.getServer().getScheduler();
|
|
Path path = plugin.getDataFolder().toPath().resolve("config.yml");
|
|
scheduler.runTaskAsynchronously(plugin, () -> {
|
|
Exception failure = null;
|
|
try {
|
|
new ConfigFileStore(path).save(yaml);
|
|
} catch (IOException | RuntimeException exception) {
|
|
failure = exception;
|
|
}
|
|
Exception result = failure;
|
|
if (plugin.isEnabled()) {
|
|
try {
|
|
scheduler.runTask(plugin, () -> completed.accept(result));
|
|
return;
|
|
} catch (IllegalPluginAccessException exception) {
|
|
// Disable raced completion: the file result is retained, never mutate disabled gameplay.
|
|
}
|
|
}
|
|
if (failure != null) {
|
|
plugin.getLogger().warning("Could not save configuration during disable: " + failure.getMessage());
|
|
}
|
|
});
|
|
}
|
|
}
|