aboutsummaryrefslogtreecommitdiffziptar.gz
path: root/src/Godosa.Core/SettingsFile.cs
diff options
context:
space:
mode:
authorgodosa <godosa@godosa.eu>2026-10-06 23:39:36 +0200
committergodosa <godosa@godosa.eu>2026-10-06 23:39:36 +0200
commit39066900773e7857faf2d02e7ed51b71d219d97d (patch)
treeffab8e4ddd971626776c3b1f4ce1da2c186c2187 /src/Godosa.Core/SettingsFile.cs
downloadgodosa-engine-39066900773e7857faf2d02e7ed51b71d219d97d.tar.gz
godosa-engine-39066900773e7857faf2d02e7ed51b71d219d97d.zip
godosa-engine: initial public history
Diffstat (limited to 'src/Godosa.Core/SettingsFile.cs')
-rw-r--r--src/Godosa.Core/SettingsFile.cs49
1 files changed, 49 insertions, 0 deletions
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;
+
+/// <summary>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.
+/// <paramref name="report"/> receives those lines (default: stderr).</summary>
+public sealed class SettingsFile<T>(string path, Func<string, T> parse, Func<T, string> serialize, Func<T> defaults,
+ Action<string>? report = null)
+{
+ private readonly Action<string> _report = report ?? Console.Error.WriteLine;
+
+ public string Path => path;
+
+ /// <summary>The override variable's value when set, else
+ /// <c>ApplicationData/&lt;appFolder&gt;/settings.json</c>.</summary>
+ 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
+ }
+ }
+}