using System;
using System.IO;
using System.Reflection;
namespace OpenNest
{
///
/// Where a post keeps its own settings: %APPDATA%\OpenNest\Posts\<post assembly>.json.
/// The install folder holds only the shipped defaults, because an update replaces it and
/// would silently reset every edit saved there. The shipped JSON is read until the first save.
///
public static class PostSettingsFile
{
/// Replaces , so test runs never read or write the user's settings.
public static string DirectoryOverride { get; set; }
public static string Directory => DirectoryOverride ?? Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "OpenNest", "Posts");
public static string PathFor(Assembly post) =>
Path.Combine(Directory, Path.GetFileNameWithoutExtension(post.Location) + ".json");
/// The defaults deployed beside the post's assembly.
public static string ShippedPathFor(Assembly post) => Path.ChangeExtension(post.Location, ".json");
/// The saved settings, else the shipped defaults, else null.
public static string Read(Assembly post)
{
var saved = PathFor(post);
if (File.Exists(saved))
return File.ReadAllText(saved);
var shipped = ShippedPathFor(post);
return File.Exists(shipped) ? File.ReadAllText(shipped) : null;
}
///
/// Saves through a temporary file, so a failed write leaves the previous settings intact.
///
public static void Write(Assembly post, string json)
{
var path = PathFor(post);
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(path));
var temp = path + ".tmp";
File.WriteAllText(temp, json);
File.Move(temp, path, overwrite: true);
}
}
}