From 39066900773e7857faf2d02e7ed51b71d219d97d Mon Sep 17 00:00:00 2001 From: godosa Date: Tue, 6 Oct 2026 23:39:36 +0200 Subject: godosa-engine: initial public history --- src/Godosa.Core/SettingsFile.cs | 49 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/Godosa.Core/SettingsFile.cs (limited to 'src/Godosa.Core/SettingsFile.cs') diff --git a/src/Godosa.Core/SettingsFile.cs b/src/Godosa.Core/SettingsFile.cs new file mode 100644 index 0000000..6aca17e --- /dev/null +++ b/src/Godosa.Core/SettingsFile.cs @@ -0,0 +1,49 @@ +namespace Godosa.Core; + +/// A settings file on disk. Failures never stop the game: any load failure +/// (missing file excepted: plain defaults) → defaults + a stderr line; save failure → +/// stderr. Saves write a temp file then rename, so a crash never leaves half a file. +/// receives those lines (default: stderr). +public sealed class SettingsFile(string path, Func parse, Func serialize, Func defaults, + Action? report = null) +{ + private readonly Action _report = report ?? Console.Error.WriteLine; + + public string Path => path; + + /// The override variable's value when set, else + /// ApplicationData/<appFolder>/settings.json. + public static string DefaultPath(string environmentOverride, string appFolder) => + Environment.GetEnvironmentVariable(environmentOverride) is { Length: > 0 } overridden + ? overridden + : System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), appFolder, "settings.json"); + + public T Load() + { + try + { + return File.Exists(path) ? parse(File.ReadAllText(path)) : defaults(); + } + catch (Exception e) when (e is not OutOfMemoryException) + { + _report($"settings: load failed ({e.Message}); using defaults"); + return defaults(); + } + } + + public void Save(T value) + { + string temp = path + ".tmp"; + try + { + Directory.CreateDirectory(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(path))!); // a bare name: the working folder + File.WriteAllText(temp, serialize(value)); + File.Move(temp, path, overwrite: true); + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + _report($"settings: save failed ({e.Message})"); + try { File.Delete(temp); } catch (Exception) { } // best effort: don't leave the half-step behind + } + } +} -- cgit