aboutsummaryrefslogtreecommitdiffziptar.gz
path: root/src/Godosa.Core/SettingsFile.cs
blob: 6aca17e754dbcf68886396a74102b0c7c3184540 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
        }
    }
}