rimworld-blax-defaults/Source/BlaxDefaults/DefaultsFile.cs

614 lines
28 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Verse;
namespace BlaxDefaults
{
/// <summary>
/// A default in the file whose class this version doesn't have, such as a kind of default a later release
/// adds. Kept as the XML of its &lt;li&gt; and written back unchanged.
/// </summary>
public sealed class UnknownEntry
{
/// <summary>Its &lt;key&gt;, or null when it has none.</summary>
public string Key;
/// <summary>Its Class attribute, or null when it has none.</summary>
public string ClassName;
/// <summary>The &lt;li&gt; node's OuterXml, as read (no whitespace between nodes).</summary>
public string Xml;
}
/// <summary>What DefaultsFile.Read found in one file that loaded.</summary>
public sealed class FileContent
{
public List<DefaultsEntry> Entries = new List<DefaultsEntry>();
public List<UnknownEntry> Unknown = new List<UnknownEntry>();
/// <summary>The formatVersion in the root node, 0 when there is none.</summary>
public int Version;
}
/// <summary>
/// The defaults file, Config/BlaxDefaults/Defaults.xml under the game's save data folder, with a .bak.
/// Work package "file" (design.md: "Defaults library, a file of names" and the tests of "Defaults library
/// and settings page").
///
/// Write, in this order: Scribe.saver.InitSaving on Defaults.xml.tmp with the library inside a try (on an
/// exception ForceStop, delete the .tmp, one error, both files untouched); read the .tmp back and compare
/// every entry's Fingerprint with the library (on a mismatch delete the .tmp, one error, both files
/// untouched); only then File.Replace(tmp, file, file + ".bak"), or File.Move(tmp, file) when there is no
/// main file.
///
/// Load: main file, then .bak. A file that fails to load is renamed at once to
/// Defaults.broken-&lt;yyyyMMdd-HHmmss&gt;.xml (main) or Defaults.bak.broken-&lt;yyyyMMdd-HHmmss&gt;.xml (backup),
/// with "-2", "-3" appended when that name exists; the main file is renamed even when the .bak loads.
/// Both failed: an empty library and one warning. Renaming is the only file operation at load.
/// The root node carries DefaultsLibrary.FormatVersion.
///
/// Entries of a class this version doesn't have (a later release's new kind of default) don't fail the
/// file: Read takes their &lt;li&gt; out before Scribe sees it and keeps its XML as an UnknownEntry, Load warns
/// once, and Write puts them back into the .tmp, so a newer version's defaults survive an older one. A
/// load that leaves a file unread in place (the Scribe was busy, an exception, a broken file that could
/// not be renamed) lists it in LoadResult.Unread; DefaultsLibrary retries the read and moves such a file
/// aside before its first write, so the write's rotation into .bak can never drop it.
///
/// File layout (what Scribe_Collections.Look with LookMode.Deep reads):
/// &lt;BlaxDefaults&gt;&lt;formatVersion&gt;1&lt;/formatVersion&gt;&lt;entries&gt;&lt;li Class="BlaxDefaults.StorageTemplate"&gt;...&lt;/li&gt;&lt;/entries&gt;&lt;/BlaxDefaults&gt;
/// </summary>
public static class DefaultsFile
{
public const string RootNode = "BlaxDefaults";
private const string VersionNode = "formatVersion";
private const string EntriesNode = "entries";
private const string LogPrefix = "[Blax Defaults] ";
public static string FolderPath => Path.Combine(GenFilePaths.ConfigFolderPath, "BlaxDefaults");
public static string FilePath => Path.Combine(FolderPath, "Defaults.xml");
public static string BackupPath => FilePath + ".bak";
public static string TempPath => FilePath + ".tmp";
// ---- load -------------------------------------------------------------------------
/// <summary>Reads the main file, then the backup, renaming broken files as described above. Never throws.</summary>
public static LoadResult Load()
{
var result = new LoadResult();
try
{
LoadInto(result);
}
catch (Exception e)
{
result.Entries = new List<DefaultsEntry>();
result.Unknown = new List<UnknownEntry>();
result.LoadedFrom = null;
Log.Warning(LogPrefix + "Reading the defaults file failed, so Blax Defaults starts with no defaults for now: " + OneLine(e.Message));
}
MarkUnread(result);
return result;
}
private static void LoadInto(LoadResult result)
{
if (Scribe.mode != LoadSaveMode.Inactive)
{
// Reading now would break the game's own save or load, and calling the files broken would be wrong.
// The file stays as it is; DefaultsLibrary reads it again once the game is done.
Log.Warning(LogPrefix + "The defaults file was not read because the game was saving or loading. It is read again when Blax Defaults first needs it.");
return;
}
DateTime now = DateTime.Now;
var problems = new List<string>();
if (File.Exists(FilePath))
{
FileContent main = Read(FilePath, out string why);
if (main != null)
{
Loaded(result, main, FilePath);
return;
}
// Renamed even when the .bak loads: the next write must not rotate this file into .bak.
problems.Add(SetAside(FilePath, why, now, result));
}
if (File.Exists(BackupPath))
{
FileContent backup = Read(BackupPath, out string why);
if (backup != null)
{
if (problems.Count > 0)
Log.Warning(LogPrefix + problems[0] + " Your defaults were loaded from the backup, " + BackupPath + ".");
Loaded(result, backup, BackupPath);
return;
}
problems.Add(SetAside(BackupPath, why, now, result));
}
if (problems.Count > 0)
{
// Every file there was failed: the library starts empty, and nothing is written until the
// player saves or forgets a default.
result.BothFailed = true;
Log.Warning(LogPrefix + string.Join(" ", problems) + " Blax Defaults starts with no defaults and writes nothing until you save or forget a default.");
}
}
/// <summary>Fills the result from a file that loaded, with one warning for a newer format or entries this version skips.</summary>
private static void Loaded(LoadResult result, FileContent content, string path)
{
result.Entries = content.Entries;
result.Unknown = content.Unknown;
result.FormatVersion = content.Version;
result.LoadedFrom = path;
var notes = new List<string>();
if (content.Version > DefaultsLibrary.FormatVersion)
notes.Add("The defaults file " + path + " was made by a newer version of Blax Defaults (format " + content.Version + ", this version reads format "
+ DefaultsLibrary.FormatVersion + "). Your defaults are loaded, but this version does not change the file: defaults you save or forget now work until you quit.");
if (content.Unknown.Count > 0)
notes.Add(content.Unknown.Count + " " + (content.Unknown.Count == 1 ? "default" : "defaults") + " in " + path
+ " come from a newer version of Blax Defaults (" + string.Join(", ", content.Unknown.Select(u => u.ClassName ?? "no class").Distinct())
+ "). This version skips them and keeps them in the file.");
if (notes.Count > 0)
Log.Warning(LogPrefix + string.Join(" ", notes));
}
/// <summary>
/// The defaults files still in place that no entries came from: both when nothing loaded (the read was
/// skipped, failed, or a broken file could not be renamed), the main file when the .bak loaded and the
/// main file could not be renamed. Never the .bak next to a main file that loaded: rotating it is normal.
/// </summary>
private static void MarkUnread(LoadResult result)
{
try
{
result.Unread.Clear();
if (result.LoadedFrom == FilePath)
return;
if (File.Exists(FilePath))
result.Unread.Add(FilePath);
if (result.LoadedFrom == null && File.Exists(BackupPath))
result.Unread.Add(BackupPath);
}
catch (Exception)
{
// File.Exists doesn't throw; this only keeps Load's "never throws".
}
}
/// <summary>Renames a file that failed to load to its broken copy and returns the sentence for the warning.</summary>
private static string SetAside(string path, string why, DateTime now, LoadResult result)
{
string what = path == BackupPath ? "The backup of the defaults file" : "The defaults file";
string reason = why.NullOrEmpty() ? "" : " (" + why + ")";
try
{
string copy = BrokenCopyPath(path, now);
File.Move(path, copy);
result.BrokenCopies.Add(copy);
return what + " could not be read" + reason + " and was kept as " + copy + ".";
}
catch (Exception e)
{
return what + " could not be read" + reason + ", and renaming it failed (" + OneLine(e.Message) + "): " + path + ".";
}
}
/// <summary>The free name for a broken copy of this file: Defaults.broken-&lt;stamp&gt;.xml, then -2, -3.</summary>
public static string BrokenCopyPath(string path, DateTime now) => AsidePath(path, now, "broken");
/// <summary>The free name for an unread file moved aside: Defaults.unread-&lt;stamp&gt;.xml, then -2, -3.</summary>
public static string UnreadCopyPath(string path, DateTime now) => AsidePath(path, now, "unread");
private static string AsidePath(string path, DateTime now, string tag)
{
if (path.NullOrEmpty())
return null;
string folder = Path.GetDirectoryName(path) ?? "";
string name = Path.GetFileName(path);
// Defaults.xml -> Defaults, Defaults.xml.bak -> Defaults.bak
string stem = name.EndsWith(".bak", StringComparison.OrdinalIgnoreCase)
? Path.GetFileNameWithoutExtension(name.Substring(0, name.Length - 4)) + ".bak"
: Path.GetFileNameWithoutExtension(name);
string stamp = now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
string candidate = Path.Combine(folder, stem + "." + tag + "-" + stamp + ".xml");
for (int n = 2; File.Exists(candidate) || Directory.Exists(candidate); n++)
candidate = Path.Combine(folder, stem + "." + tag + "-" + stamp + "-" + n.ToString(CultureInfo.InvariantCulture) + ".xml");
return candidate;
}
/// <summary>
/// Moves a defaults file the load left unread to Defaults.unread-&lt;stamp&gt;.xml (Defaults.bak.unread-... for
/// the backup) and returns the new path; null with one error when that fails. DefaultsLibrary calls this
/// before its first write, so the write's rotation into .bak can't lose a file nobody read.
/// </summary>
public static string SetAsideUnread(string path)
{
try
{
string copy = UnreadCopyPath(path, DateTime.Now);
File.Move(path, copy);
return copy;
}
catch (Exception e)
{
Log.Error(LogPrefix + "The defaults file " + path + " was not read this session and could not be moved aside (" + OneLine(e.Message)
+ "), so it is not overwritten: your change works until you quit.");
return null;
}
}
// ---- read -------------------------------------------------------------------------
/// <summary>
/// Reads one file into entries without renaming anything. Null when it fails to load (missing root,
/// truncated XML, an entry that doesn't load). Entries of a class this version doesn't have are left
/// out; Read returns them too.
/// </summary>
public static List<DefaultsEntry> ReadFile(string path) => ReadFile(path, out _);
/// <summary>ReadFile with the reason a file failed, for the load warning and the write error.</summary>
public static List<DefaultsEntry> ReadFile(string path, out string problem) => Read(path, out problem)?.Entries;
/// <summary>
/// Reads one file without renaming anything: the entries, the entries of classes this version doesn't
/// have (as their XML) and the format version. Null when it fails to load. Used by Load and Write's read-back.
/// </summary>
public static FileContent Read(string path, out string problem)
{
problem = null;
var content = new FileContent();
XmlDocument doc;
try
{
if (path.NullOrEmpty() || !File.Exists(path))
{
problem = "the file does not exist";
return null;
}
if (Scribe.mode != LoadSaveMode.Inactive)
{
problem = "the game was saving or loading";
return null;
}
// Parsed here first: Scribe.loader.InitLoading logs an error of its own for XML that isn't well
// formed, and a broken file is a case Load handles with one warning.
doc = ParseXml(path);
if (doc.DocumentElement == null || doc.DocumentElement.Name != RootNode)
{
problem = "the root node is not <" + RootNode + ">";
return null;
}
// An entry whose class this version doesn't have would fail in Scribe with two errors and fail
// the whole file (ScribeExtractor.SaveableFromNode falls back to the abstract DefaultsEntry).
// Out it goes before Scribe sees it, kept as XML for the next write.
content.Unknown = TakeUnknownEntries(doc.DocumentElement[EntriesNode]);
}
catch (Exception e)
{
problem = OneLine(e.Message);
return null;
}
int version = 0;
List<DefaultsEntry> list = null;
try
{
// Scribe.loader.InitLoading(path) without reading the file again: the document minus the
// unknown entries. InitLoading does exactly this after its checks (Verse/ScribeLoader.cs:36-45).
Scribe.loader.curParent = null;
Scribe.loader.curPathRelToParent = null;
Scribe.loader.curXmlParent = doc.DocumentElement;
Scribe.mode = LoadSaveMode.LoadingVars;
Scribe_Values.Look(ref version, VersionNode);
Scribe_Collections.Look(ref list, EntriesNode, LookMode.Deep);
Scribe.loader.FinalizeLoading();
}
catch (Exception e)
{
StopLoading();
problem = OneLine(e.Message);
return null;
}
if (list == null)
{
problem = "it has no <" + EntriesNode + "> node";
return null;
}
for (int i = 0; i < list.Count; i++)
{
if (list[i] == null)
{
problem = "entry " + (i + 1) + " did not load";
return null;
}
if (list[i].key.NullOrEmpty())
{
problem = "entry " + (i + 1) + " has no key";
return null;
}
}
content.Entries = list;
content.Version = version;
return content;
}
private static XmlDocument ParseXml(string path)
{
var doc = new XmlDocument();
using (var input = new StreamReader(path))
using (var reader = new XmlTextReader(input))
doc.Load(reader);
return doc;
}
/// <summary>
/// Removes every &lt;li&gt; of the entries node whose Class this version can't load (no DefaultsEntry
/// subclass of that name, or no Class at all) and returns them in file order.
/// </summary>
private static List<UnknownEntry> TakeUnknownEntries(XmlElement entriesNode)
{
var unknown = new List<UnknownEntry>();
if (entriesNode == null)
return unknown;
var items = new List<XmlElement>();
foreach (XmlNode n in entriesNode.ChildNodes)
{
if (n is XmlElement e && e.Name == "li")
items.Add(e);
}
foreach (XmlElement li in items)
{
if (string.Equals(li.GetAttribute("IsNull"), "true", StringComparison.OrdinalIgnoreCase))
continue;
string className = li.HasAttribute("Class") ? li.GetAttribute("Class") : null;
if (IsEntryClass(className))
continue;
unknown.Add(new UnknownEntry { Key = li["key"]?.InnerText, ClassName = className, Xml = li.OuterXml });
entriesNode.RemoveChild(li);
}
return unknown;
}
/// <summary>True when Scribe can make an entry of this class: a DefaultsEntry subclass that isn't abstract.</summary>
public static bool IsEntryClass(string className)
{
if (className.NullOrEmpty())
return false;
Type t = GenTypes.GetTypeInAnyAssembly(className);
return t != null && typeof(DefaultsEntry).IsAssignableFrom(t) && !t.IsAbstract;
}
// ---- write ------------------------------------------------------------------------
/// <summary>
/// Writes these entries (DefaultsLibrary.All) through .tmp, read-back and File.Replace. Returns false
/// and leaves both files untouched when anything fails, with one error in the log. Never throws.
/// </summary>
public static bool Write(IReadOnlyList<DefaultsEntry> entries) => Write(entries, null);
/// <summary>
/// Write with the entries of a newer version this version skipped at load (DefaultsLibrary.UnknownEntries):
/// they go into the .tmp after the library's entries, exactly as they were read, and are checked in the
/// read-back too.
/// </summary>
public static bool Write(IReadOnlyList<DefaultsEntry> entries, IReadOnlyList<UnknownEntry> unknown)
{
try
{
entries ??= Array.Empty<DefaultsEntry>();
unknown ??= Array.Empty<UnknownEntry>();
if (Scribe.mode != LoadSaveMode.Inactive)
{
// InitSaving would force-stop the game's own save or load.
Log.Error(LogPrefix + "The defaults file was not written because the game was saving or loading. The previous file is kept.");
return false;
}
Directory.CreateDirectory(FolderPath);
// 1. The library into the .tmp.
try
{
Scribe.saver.InitSaving(TempPath, RootNode);
int version = DefaultsLibrary.FormatVersion;
Scribe_Values.Look(ref version, VersionNode, 0, forceSave: true);
SaveEntries(entries);
Scribe.saver.FinalizeSaving();
}
catch (Exception e)
{
StopSaving();
DeleteTemp();
Log.Error(LogPrefix + "Writing the defaults file failed, so the previous file is kept: " + e);
return false;
}
// 1b. The entries of a newer version, back in as they were read.
if (unknown.Count > 0)
{
try
{
AppendUnknown(TempPath, unknown);
}
catch (Exception e)
{
DeleteTemp();
Log.Error(LogPrefix + "Writing the defaults of a newer version back into the defaults file failed, so the previous file is kept: " + e);
return false;
}
}
// 2. The .tmp read back and compared with the library.
string mismatch = CompareReadBack(entries, unknown);
if (mismatch != null)
{
DeleteTemp();
Log.Error(LogPrefix + "The new defaults file did not read back as written (" + mismatch + "), so the previous file is kept.");
return false;
}
// 3. Only now the swap. The previous main file becomes the .bak.
try
{
if (File.Exists(FilePath))
File.Replace(TempPath, FilePath, BackupPath, ignoreMetadataErrors: true);
else
File.Move(TempPath, FilePath);
}
catch (Exception e)
{
DeleteTemp();
Log.Error(LogPrefix + "Replacing the defaults file failed, so the previous file is kept: " + e);
return false;
}
return true;
}
catch (Exception e)
{
// Only reached outside the three steps (the folder could not be made, for one), so the Scribe
// is not ours to stop here.
DeleteTemp();
Log.Error(LogPrefix + "Writing the defaults file failed, so the previous file is kept: " + e);
return false;
}
}
/// <summary>
/// The entries as Scribe_Collections.Look(LookMode.Deep) writes them, one &lt;li Class="..."&gt; each, but
/// without Scribe_Deep's catch: Scribe_Deep logs an exception from an entry's ExposeData and carries on
/// (Verse/Scribe_Deep.cs:61-63), which would log a second error and leave a well-formed file without
/// the entry. Here the exception ends the write with the one error Write logs.
/// </summary>
private static void SaveEntries(IReadOnlyList<DefaultsEntry> entries)
{
if (!Scribe.EnterNode(EntriesNode))
throw new InvalidOperationException("could not open the <" + EntriesNode + "> node");
for (int i = 0; i < entries.Count; i++)
{
DefaultsEntry entry = entries[i];
if (entry == null)
throw new InvalidOperationException("entry " + (i + 1) + " is null");
if (!Scribe.EnterNode("li"))
throw new InvalidOperationException("could not open the node of " + entry);
Scribe.saver.WriteAttribute("Class", GenTypes.GetTypeNameWithoutIgnoredNamespaces(entry.GetType()));
entry.ExposeData();
Scribe.ExitNode();
}
Scribe.ExitNode();
}
/// <summary>Adds the unknown entries' &lt;li&gt; nodes to the entries node of the file, indented as Scribe writes.</summary>
private static void AppendUnknown(string path, IReadOnlyList<UnknownEntry> unknown)
{
XmlDocument doc = ParseXml(path);
XmlElement list = doc.DocumentElement?[EntriesNode] ?? throw new InvalidOperationException("the new file has no <" + EntriesNode + "> node");
foreach (UnknownEntry u in unknown)
{
XmlDocumentFragment fragment = doc.CreateDocumentFragment();
fragment.InnerXml = u.Xml;
list.AppendChild(fragment);
}
var settings = new XmlWriterSettings { Indent = true, IndentChars = "\t" };
using (XmlWriter writer = XmlWriter.Create(path, settings))
doc.Save(writer);
}
/// <summary>Null when the .tmp holds exactly these entries and unknown entries, in this order; otherwise what differs.</summary>
private static string CompareReadBack(IReadOnlyList<DefaultsEntry> entries, IReadOnlyList<UnknownEntry> unknown)
{
FileContent content = Read(TempPath, out string problem);
if (content == null)
return "it could not be read: " + problem;
if (content.Unknown.Count != unknown.Count)
return "it holds " + content.Unknown.Count + " defaults of a newer version instead of " + unknown.Count;
for (int i = 0; i < unknown.Count; i++)
{
if (!string.Equals(unknown[i].Xml, content.Unknown[i].Xml, StringComparison.Ordinal))
return "the default " + unknown[i].Key + " of a newer version reads back changed";
}
List<DefaultsEntry> back = content.Entries;
if (back.Count != entries.Count)
return "it holds " + back.Count + " entries instead of " + entries.Count;
for (int i = 0; i < entries.Count; i++)
{
string expected, actual;
try
{
expected = entries[i].Fingerprint();
actual = back[i].Fingerprint();
}
catch (Exception e)
{
return "comparing " + entries[i] + " failed: " + OneLine(e.Message);
}
if (!string.Equals(expected, actual, StringComparison.Ordinal))
return entries[i] + " reads back with other values";
}
return null;
}
// ---- helpers ----------------------------------------------------------------------
private static void StopSaving()
{
try
{
Scribe.saver.ForceStop();
}
catch (Exception)
{
// ForceStop closes the writer first; if that throws, at least give the game its Scribe back.
}
if (Scribe.mode == LoadSaveMode.Saving)
Scribe.mode = LoadSaveMode.Inactive;
}
private static void StopLoading()
{
try
{
Scribe.loader.ForceStop();
}
catch (Exception)
{
// Nothing more to undo.
}
if (Scribe.mode == LoadSaveMode.LoadingVars || Scribe.mode == LoadSaveMode.ResolvingCrossRefs || Scribe.mode == LoadSaveMode.PostLoadInit)
Scribe.mode = LoadSaveMode.Inactive;
}
private static void DeleteTemp()
{
try
{
if (File.Exists(TempPath))
File.Delete(TempPath);
}
catch (Exception)
{
// A .tmp left behind is harmless: the next write truncates it, and loading never reads it.
}
}
private static string OneLine(string text)
{
if (text == null)
return "";
var sb = new StringBuilder(text.Length);
foreach (char c in text)
sb.Append(c == '\r' || c == '\n' ? ' ' : c);
return sb.ToString().Trim();
}
}
}