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
}
}
}