diff options
Diffstat (limited to 'src/Godosa.Core/SettingsFile.cs')
| -rw-r--r-- | src/Godosa.Core/SettingsFile.cs | 49 |
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/<appFolder>/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 + } + } +} |
