diff --git a/ModuleManager/Collections/KeyValueCache.cs b/ModuleManager/Collections/KeyValueCache.cs index 0aaee61b..e59f6627 100644 --- a/ModuleManager/Collections/KeyValueCache.cs +++ b/ModuleManager/Collections/KeyValueCache.cs @@ -25,5 +25,25 @@ public TValue Fetch(TKey key, Func createValue) } } } + + // Takes the key as an argument so that callers can pass a delegate that captures nothing, + // which the compiler caches, instead of allocating a closure on every call. + public TValue FetchWithKey(TKey key, Func createValue) + { + if (createValue == null) throw new ArgumentNullException(nameof(createValue)); + lock(lockObject) + { + if (dict.TryGetValue(key, out TValue value)) + { + return value; + } + else + { + TValue newValue = createValue(key); + dict.Add(key, newValue); + return newValue; + } + } + } } } diff --git a/ModuleManager/ConfigFileHasher.cs b/ModuleManager/ConfigFileHasher.cs new file mode 100644 index 00000000..648781f5 --- /dev/null +++ b/ModuleManager/ConfigFileHasher.cs @@ -0,0 +1,168 @@ +using System; +using System.IO; +using System.Runtime.ExceptionServices; +using System.Security.Cryptography; +using System.Threading; + +namespace ModuleManager +{ + // Computes each file's SHA256 on worker threads, while the caller uses them in order. + // WaitForHash(i) gives file i's hash once ready, or throws what reading it threw. + // + // The workers stay at most ReadAhead files ahead of the caller. If a worker thread dies (an abort), the file it was on is marked as failed + // with that exception; if every worker is gone, the caller reads the files it waits for itself. + public sealed class ConfigFileHasher : IDisposable + { + private const int ReadAhead = 64; + + private readonly string[] paths; + private readonly string[] hashes; + private readonly Exception[] errors; + private readonly bool[] ready; + private readonly Thread[] workers; + private readonly object lockObject = new object(); + private int next = -1; + private int waitingFor; + private int liveWorkers; + private bool stopping; + private int readCount; + + // How many files the workers have read so far + public int ReadCount + { + get { lock (lockObject) return readCount; } + } + + public ConfigFileHasher(string[] paths) + { + this.paths = paths ?? throw new ArgumentNullException(nameof(paths)); + hashes = new string[paths.Length]; + errors = new Exception[paths.Length]; + ready = new bool[paths.Length]; + + int count = Math.Max(1, Math.Min(Environment.ProcessorCount - 1, 8)); + if (count > paths.Length) count = Math.Max(1, paths.Length); + workers = new Thread[count]; + liveWorkers = count; + for (int i = 0; i < count; i++) + { + workers[i] = new Thread(Work) { IsBackground = true, Name = "ModuleManager file hasher " + i }; + workers[i].Start(); + } + } + + public string WaitForHash(int i) + { + bool readHere = false; + lock (lockObject) + { + waitingFor = i; + Monitor.PulseAll(lockObject); + while (!ready[i]) + { + if (liveWorkers == 0) + { + // Nobody is left to read it: claim it if no worker has + if (i > next) next = i; + readHere = true; + break; + } + Monitor.Wait(lockObject); + } + } + if (readHere) Read(i, null); + + if (errors[i] != null) + ExceptionDispatchInfo.Capture(errors[i]).Throw(); + return hashes[i]; + } + + private void Read(int i, SHA256 sha) + { + try + { + using FileStream stream = new FileStream(paths[i], FileMode.Open, FileAccess.Read, FileShare.Read, 65536); + if (sha == null) + { + using SHA256 own = SHA256.Create(); + hashes[i] = BitConverter.ToString(own.ComputeHash(stream)); + } + else + { + hashes[i] = BitConverter.ToString(sha.ComputeHash(stream)); + } + } + catch (Exception e) + { + errors[i] = e; + } + } + + private void Work() + { + int current = -1; + try + { + using SHA256 sha = SHA256.Create(); + while (true) + { + lock (lockObject) + { + while (!stopping && next + 1 < paths.Length && next + 1 > waitingFor + ReadAhead) + Monitor.Wait(lockObject); + if (stopping || next + 1 >= paths.Length) return; + current = ++next; + } + + Read(current, sha); + + lock (lockObject) + { + ready[current] = true; + readCount++; + current = -1; + Monitor.PulseAll(lockObject); + } + } + } + catch (Exception e) + { + lock (lockObject) + { + if (current >= 0 && !ready[current]) + { + errors[current] = e; + ready[current] = true; + } + } + // Not rethrown: a worker that cannot start (SHA256.Create) leaves its files to + // the others, or to the caller, which then meets the same error itself + } + finally + { + lock (lockObject) + { + // An abort that hit between two lines above still leaves no file half done + if (current >= 0 && !ready[current]) + { + errors[current] = errors[current] ?? new ThreadInterruptedException("ModuleManager file hasher stopped while reading " + paths[current]); + ready[current] = true; + } + liveWorkers--; + Monitor.PulseAll(lockObject); + } + } + } + + public void Dispose() + { + lock (lockObject) + { + stopping = true; + Monitor.PulseAll(lockObject); + } + foreach (Thread worker in workers) + worker.Join(); + } + } +} diff --git a/ModuleManager/ConfigNodeWriter.cs b/ModuleManager/ConfigNodeWriter.cs new file mode 100644 index 00000000..955ec66a --- /dev/null +++ b/ModuleManager/ConfigNodeWriter.cs @@ -0,0 +1,170 @@ +using System; +using System.IO; + +namespace ModuleManager +{ + // Writes a ConfigNode to a file exactly as ConfigNode.Save(path) does, without the flush + // ConfigNode.Save does at the end of every node, which costs more than the writing for the + // cache's hundred thousand nodes. + public static class ConfigNodeWriter + { + public static void Save(ConfigNode node, string path) + { + if (node == null) throw new ArgumentNullException(nameof(node)); + if (path == null) throw new ArgumentNullException(nameof(path)); + + using StreamWriter writer = Open(path); + Save(node, writer); + } + + // The encoding a StreamWriter uses by default, as ConfigNode.Save's does + private static StreamWriter Open(string path) => new StreamWriter(File.Open(path, FileMode.Create), new System.Text.UTF8Encoding(false, true), 1 << 16); + + // Writes the cache node: its values and its UrlConfig nodes as they are, and the nodes in + // each UrlConfig node as their DeepCopy would be written once escaped with + // EscapeValuesRecursive, without making that copy (see WriteCopy). + public static void SaveCache(ConfigNode cache, string path) + { + if (cache == null) throw new ArgumentNullException(nameof(cache)); + if (path == null) throw new ArgumentNullException(nameof(path)); + + using StreamWriter writer = Open(path); + SaveCache(cache, writer); + } + + public static void SaveCache(ConfigNode cache, TextWriter writer) + { + if (cache == null) throw new ArgumentNullException(nameof(cache)); + if (writer == null) throw new ArgumentNullException(nameof(writer)); + WriteValues(writer, cache, ""); + for (int i = 0; i < cache.nodes.Count; i++) + { + ConfigNode urlConfig = cache.nodes[i]; + WriteHeader(writer, urlConfig, urlConfig.name, ""); + WriteValues(writer, urlConfig, "\t"); + for (int j = 0; j < urlConfig.nodes.Count; j++) + WriteCopy(writer, urlConfig.nodes[j], "\t"); + writer.WriteLine("}"); + } + } + + // Same text as ConfigNode.Save: UTF-8 without a byte order mark, and + // name // comment + // { + // key = value // comment + // ... + // } + // with the comments only where there are some. + public static void Save(ConfigNode node, TextWriter writer) + { + if (node == null) throw new ArgumentNullException(nameof(node)); + if (writer == null) throw new ArgumentNullException(nameof(writer)); + WriteValues(writer, node, ""); + for (int i = 0; i < node.nodes.Count; i++) + WriteNode(writer, node.nodes[i], ""); + } + + private static void WriteValues(TextWriter writer, ConfigNode node, string indent) + { + ConfigNode.ValueList values = node.values; + for (int i = 0; i < values.Count; i++) + { + ConfigNode.Value value = values[i]; + writer.Write(indent); + writer.Write(value.name); + writer.Write(" = "); + writer.Write(value.value); + if (!string.IsNullOrEmpty(value.comment)) + { + writer.Write(" // "); + writer.Write(value.comment); + } + writer.WriteLine(); + } + } + + private static void WriteNode(TextWriter writer, ConfigNode node, string indent) + { + WriteHeader(writer, node, node.name, indent); + + string inner = indent + "\t"; + WriteValues(writer, node, inner); + for (int i = 0; i < node.nodes.Count; i++) + WriteNode(writer, node.nodes[i], inner); + + writer.Write(indent); + writer.WriteLine("}"); + } + + private static void WriteHeader(TextWriter writer, ConfigNode node, string name, string indent) + { + writer.Write(indent); + writer.Write(name); + if (!string.IsNullOrEmpty(node.comment)) + { + writer.Write(" // "); + writer.Write(node.comment); + } + writer.WriteLine(); + writer.Write(indent); + writer.WriteLine("{"); + } + + // Characters that the ConfigNode(string) constructor removes or splits the name on + private static readonly char[] nameCleanupChars = { '\n', '\r', '\t', '(', ')', ' ' }; + private static readonly char[] escapedChars = { '\n', '\r', '\t' }; + + // Writes node as DeepCopy(node), then EscapeValuesRecursive, would give it: + // - the name as the ConfigNode(string) constructor makes it (DeepCopy skips that when it + // has nothing to do), and no comment; + // - each value as ConfigNode.ValueList.Add sanitizes it ({ and } become [ and ], and = in + // names becomes -), then with newlines, returns and tabs escaped, and no comment. + private static void WriteCopy(TextWriter writer, ConfigNode node, string indent) + { + string name = node.name; + if (name == null || name.IndexOfAny(nameCleanupChars) >= 0) + name = new ConfigNode(name).name; + writer.Write(indent); + writer.WriteLine(name); + writer.Write(indent); + writer.WriteLine("{"); + + string inner = indent + "\t"; + ConfigNode.ValueList values = node.values; + for (int i = 0; i < values.Count; i++) + { + ConfigNode.Value value = values[i]; + string valueName = Sanitize(value.name, true); + string text = Sanitize(value.value, false); + if (text.IndexOfAny(escapedChars) >= 0) + text = text.Replace("\n", "\\n").Replace("\r", "\\r").Replace("\t", "\\t"); + writer.Write(inner); + writer.Write(valueName); + writer.Write(" = "); + writer.Write(text); + writer.WriteLine(); + } + for (int i = 0; i < node.nodes.Count; i++) + WriteCopy(writer, node.nodes[i], inner); + + writer.Write(indent); + writer.WriteLine("}"); + } + + // ConfigNode.Value.Sanitize, for one string: throws on null as it does + private static string Sanitize(string s, bool isName) + { + for (int i = s.Length - 1; i >= 0; i--) + { + char c = s[i]; + if (c == '{' || c == '}' || (isName && c == '=')) + { + s = s.Replace('{', '[').Replace('}', ']'); + if (isName) s = s.Replace('=', '-'); + break; + } + } + return s; + } + } +} diff --git a/ModuleManager/Extensions/ConfigNodeExtensions.cs b/ModuleManager/Extensions/ConfigNodeExtensions.cs index 9f552566..c175d601 100644 --- a/ModuleManager/Extensions/ConfigNodeExtensions.cs +++ b/ModuleManager/Extensions/ConfigNodeExtensions.cs @@ -8,26 +8,80 @@ public static class ConfigNodeExtensions public static void ShallowCopyFrom(this ConfigNode toNode, ConfigNode fromeNode) { toNode.ClearData(); - foreach (ConfigNode.Value value in fromeNode.values) - toNode.values.Add(value); - foreach (ConfigNode node in fromeNode.nodes) - toNode.nodes.Add(node); + ConfigNode.ValueList values = fromeNode.values; + for (int i = 0; i < values.Count; i++) + toNode.values.Add(values[i]); + ConfigNode.ConfigNodeList nodes = fromeNode.nodes; + for (int i = 0; i < nodes.Count; i++) + toNode.nodes.Add(nodes[i]); } + // Characters that the ConfigNode(string) constructor removes or splits the name on + private static readonly char[] nameCleanupChars = { '\n', '\r', '\t', '(', ')', ' ' }; + // KSP implementation of ConfigNode.CreateCopy breaks with badly formed nodes (nodes with a blank name) public static ConfigNode DeepCopy(this ConfigNode from) { - ConfigNode to = new ConfigNode(from.name); - foreach (ConfigNode.Value value in from.values) - to.AddValueSafe(value.name, value.value); - foreach (ConfigNode node in from.nodes) + // ConfigNode(name) strips newlines and tabs from the name and splits an id off it at + // '(', ')' or ' '. A name with none of those comes out unchanged, so skip that work. + string name = from.name; + ConfigNode to; + if (name != null && name.IndexOfAny(nameCleanupChars) < 0) + to = new ConfigNode { name = name }; + else + to = new ConfigNode(name); + + // Indexed loops: the lists' enumerators are non-generic and allocate. + ConfigNode.ValueList values = from.values; + ConfigNode.ValueList toValues = to.values; + for (int i = 0; i < values.Count; i++) + { + ConfigNode.Value value = values[i]; + toValues.Add(new ConfigNode.Value(value.name, value.value)); + } + ConfigNode.ConfigNodeList nodes = from.nodes; + ConfigNode.ConfigNodeList toNodes = to.nodes; + for (int i = 0; i < nodes.Count; i++) + toNodes.Add(DeepCopy(nodes[i])); + return to; + } + + // DeepCopy of the node itself (its name and values), with the same subnodes, not copies + public static ConfigNode CopySharingSubnodes(this ConfigNode from) + { + string name = from.name; + ConfigNode to; + if (name != null && name.IndexOfAny(nameCleanupChars) < 0) + to = new ConfigNode { name = name }; + else + to = new ConfigNode(name); + + ConfigNode.ValueList values = from.values; + ConfigNode.ValueList toValues = to.values; + for (int i = 0; i < values.Count; i++) { - ConfigNode newNode = DeepCopy(node); - to.nodes.Add(newNode); + ConfigNode.Value value = values[i]; + toValues.Add(new ConfigNode.Value(value.name, value.value)); } + ConfigNode.ConfigNodeList nodes = from.nodes; + ConfigNode.ConfigNodeList toNodes = to.nodes; + for (int i = 0; i < nodes.Count; i++) + toNodes.Add(nodes[i]); return to; } + // Puts newChild in place of oldChild, at the same position + public static void ReplaceNode(this ConfigNode parent, ConfigNode oldChild, ConfigNode newChild) + { + ConfigNode.ConfigNodeList nodes = parent.nodes; + ConfigNode[] all = new ConfigNode[nodes.Count]; + for (int i = 0; i < all.Length; i++) + all[i] = nodes[i]; + nodes.Clear(); + for (int i = 0; i < all.Length; i++) + nodes.Add(ReferenceEquals(all[i], oldChild) ? newChild : all[i]); + } + public static void PrettyPrint(this ConfigNode node, ref StringBuilder sb, string indent) { if (sb == null) throw new ArgumentNullException(nameof(sb)); @@ -89,15 +143,21 @@ public static void EscapeValuesRecursive(this ConfigNode theNode) } } + // Only values with a backslash can hold an escape: the others are left as they are public static void UnescapeValuesRecursive(this ConfigNode theNode) { - foreach (ConfigNode subNode in theNode.nodes) + ConfigNode.ConfigNodeList nodes = theNode.nodes; + for (int i = 0; i < nodes.Count; i++) { - subNode.UnescapeValuesRecursive(); + nodes[i].UnescapeValuesRecursive(); } - foreach (ConfigNode.Value value in theNode.values) + ConfigNode.ValueList values = theNode.values; + for (int i = 0; i < values.Count; i++) { + ConfigNode.Value value = values[i]; + if (value.value.IndexOf('\\') < 0) + continue; value.value = value.value.Replace("\\n", "\n"); value.value = value.value.Replace("\\r", "\r"); value.value = value.value.Replace("\\t", "\t"); diff --git a/ModuleManager/Logging/QueueLogRunner.cs b/ModuleManager/Logging/QueueLogRunner.cs index f78cf611..293d5482 100644 --- a/ModuleManager/Logging/QueueLogRunner.cs +++ b/ModuleManager/Logging/QueueLogRunner.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Threading; using ModuleManager.Collections; @@ -15,7 +16,8 @@ private enum State Stopped, } - private State state = State.Initialized; + private volatile State state = State.Initialized; + private readonly object stopLock = new object(); private readonly IMessageQueue logQueue; private readonly long timeToWaitForLogsMs; @@ -30,7 +32,12 @@ public void RequestStop() { if (state == State.StopRequested || state == State.Stopped) return; if (state != State.Running) throw new InvalidOperationException($"Cannot request stop from {state} state"); - state = State.StopRequested; + lock (stopLock) + { + state = State.StopRequested; + // Wakes Run if it waits for more messages: it then writes the last ones at once + Monitor.PulseAll(stopLock); + } } public void Run(IBasicLogger logger) @@ -52,7 +59,13 @@ public void Run(IBasicLogger logger) long timeRemaining = timeToWaitForLogsMs - stopwatch.ElapsedMilliseconds; if (timeRemaining > 0) - System.Threading.Thread.Sleep((int)timeRemaining); + { + lock (stopLock) + { + if (state == State.Running) + Monitor.Wait(stopLock, (int)timeRemaining); + } + } stopwatch.Reset(); } diff --git a/ModuleManager/MMPatchLoader.cs b/ModuleManager/MMPatchLoader.cs index 5278758b..5aff4bea 100644 --- a/ModuleManager/MMPatchLoader.cs +++ b/ModuleManager/MMPatchLoader.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -203,9 +203,10 @@ public IEnumerable Run() logRunner.RequestStop(); + // The log thread writes its last messages as soon as asked to stop while (loggingThreadStatus.IsRunning) { - System.Threading.Thread.Sleep(100); + System.Threading.Thread.Sleep(2); } if (loggingThreadStatus.IsExitedWithError) @@ -282,30 +283,34 @@ private bool IsCacheUpToDate() sw.Start(); using System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create(); - using System.Security.Cryptography.SHA256 filesha = System.Security.Cryptography.SHA256.Create(); UrlDir.UrlFile[] files = GameDatabase.Instance.root.AllConfigFiles.ToArray(); filesSha.Clear(); - for (int i = 0; i < files.Length; i++) + // Worker threads hash each file, while this thread hashes the paths and the files' + // hashes all together, in order, as they become ready. + using (ConfigFileHasher hasher = new ConfigFileHasher(files.Select(file => file.fullPath).ToArray())) { - string url = files[i].GetUrlWithExtension(); - // Hash the file path so the checksum change if files are moved - byte[] pathBytes = Encoding.UTF8.GetBytes(url); - sha.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0); + for (int i = 0; i < files.Length; i++) + { + string url = files[i].GetUrlWithExtension(); + // Hash the file path so the checksum change if files are moved + byte[] pathBytes = Encoding.UTF8.GetBytes(url); + sha.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0); - // hash the file content - byte[] contentBytes = File.ReadAllBytes(files[i].fullPath); - sha.TransformBlock(contentBytes, 0, contentBytes.Length, contentBytes, 0); + // hash the file content, through its own hash + string fileHash = hasher.WaitForHash(i); + byte[] hashBytes = Encoding.ASCII.GetBytes(fileHash); + sha.TransformBlock(hashBytes, 0, hashBytes.Length, hashBytes, 0); - filesha.ComputeHash(contentBytes); - if (!filesSha.ContainsKey(url)) - { - filesSha.Add(url, BitConverter.ToString(filesha.Hash)); - } - else - { - logger.Warning("Duplicate fileSha key. This should not append. The key is " + url); + if (!filesSha.ContainsKey(url)) + { + filesSha.Add(url, fileHash); + } + else + { + logger.Warning("Duplicate fileSha key. This should not append. The key is " + url); + } } } @@ -328,7 +333,6 @@ private bool IsCacheUpToDate() configSha = BitConverter.ToString(sha.Hash); sha.Clear(); - filesha.Clear(); sw.Stop(); @@ -366,10 +370,27 @@ private bool CheckFilesChange(UrlDir.UrlFile[] files, ConfigNode shaConfigNode) changes.Append("Changes :\n"); + // The FILE nodes by filename, each list in node order: the first one is what a search + // of the nodes for that filename finds + ConfigNode.ConfigNodeList nodes = shaConfigNode.nodes; + Dictionary> fileNodes = new Dictionary>(); + for (int i = 0; i < nodes.Count; i++) + { + ConfigNode file = nodes[i]; + if (file.name != "FILE" || !(file.GetValue("filename") is string filename)) continue; + if (!fileNodes.TryGetValue(filename, out Queue queue)) + { + queue = new Queue(1); + fileNodes.Add(filename, queue); + } + queue.Enqueue(file); + } + + string[] urls = new string[files.Length]; for (int i = 0; i < files.Length; i++) { - string url = files[i].GetUrlWithExtension(); - ConfigNode fileNode = GetFileNode(shaConfigNode, url); + string url = urls[i] = files[i].GetUrlWithExtension(); + ConfigNode fileNode = fileNodes.TryGetValue(url, out Queue queue) ? queue.Peek() : null; string fileSha = fileNode?.GetValue("SHA"); if (fileNode == null) @@ -381,20 +402,28 @@ private bool CheckFilesChange(UrlDir.UrlFile[] files, ConfigNode shaConfigNode) noChange = false; } } + + // Each file takes the first FILE node of its name not yet taken; the rest are deleted + HashSet taken = new HashSet(); for (int i = 0; i < files.Length; i++) { - string url = files[i].GetUrlWithExtension(); - ConfigNode fileNode = GetFileNode(shaConfigNode, url); + string url = urls[i]; + ConfigNode fileNode = fileNodes.TryGetValue(url, out Queue queue) && queue.Count > 0 ? queue.Dequeue() : null; if (fileNode == null) { changes.Append("Added : " + url + "\n"); noChange = false; } - shaConfigNode.RemoveNode(fileNode); + else + { + taken.Add(fileNode); + } } - foreach (ConfigNode fileNode in shaConfigNode.GetNodes()) + for (int i = 0; i < nodes.Count; i++) { + ConfigNode fileNode = nodes[i]; + if (taken.Contains(fileNode)) continue; changes.Append("Deleted : " + fileNode.GetValue("filename") + "\n"); noChange = false; } @@ -403,17 +432,6 @@ private bool CheckFilesChange(UrlDir.UrlFile[] files, ConfigNode shaConfigNode) return noChange; } - private ConfigNode GetFileNode(ConfigNode shaConfigNode, string filename) - { - for (int i = 0; i < shaConfigNode.nodes.Count; i++) - { - ConfigNode file = shaConfigNode.nodes[i]; - if (file.name == "FILE" && file.GetValue("filename") == filename) - return file; - } - return null; - } - private void CreateCache(IEnumerable databaseConfigs, int patchedNodeCount) { @@ -432,10 +450,8 @@ private void CreateCache(IEnumerable databaseConfigs, int patch ConfigNode node = cache.AddNode("UrlConfig"); node.AddValue("parentUrl", urlConfig.UrlFile.GetUrlWithExtension()); - ConfigNode urlNode = urlConfig.Node.DeepCopy(); - urlNode.EscapeValuesRecursive(); - - node.AddNode(urlNode); + // Written as a copy with its values sanitized and escaped would be, without the copy + node.AddNode(urlConfig.Node); } foreach (var file in GameDatabase.Instance.root.AllConfigFiles) @@ -455,7 +471,7 @@ private void CreateCache(IEnumerable databaseConfigs, int patch try { - shaConfigNode.Save(shaPath); + ConfigNodeWriter.Save(shaConfigNode, shaPath); } catch (Exception e) { @@ -463,7 +479,7 @@ private void CreateCache(IEnumerable databaseConfigs, int patch } try { - cache.Save(cachePath); + ConfigNodeWriter.SaveCache(cache, cachePath); return; } catch (NullReferenceException e) @@ -525,11 +541,22 @@ private IEnumerable LoadCache() List databaseConfigs = new List(cache.nodes.Count); + // Most files hold several nodes: each file is looked up once + Dictionary parents = new Dictionary(); foreach (ConfigNode node in cache.nodes) { string parentUrl = node.GetValue("parentUrl"); - UrlDir.UrlFile parent = gameDataDir.Find(parentUrl); + UrlDir.UrlFile parent; + if (parentUrl == null) + { + parent = gameDataDir.Find(parentUrl); + } + else if (!parents.TryGetValue(parentUrl, out parent)) + { + parent = gameDataDir.Find(parentUrl); + parents.Add(parentUrl, parent); + } if (parent != null) { node.nodes[0].UnescapeValuesRecursive(); @@ -569,13 +596,204 @@ private void StatusUpdate(IPatchProgress progress, string activity = null) // Name is group 1, index is group 2, vector related filed is group 3, vector separator is group 4, operator is group 5 private static readonly Regex parseValue = new Regex(@"([\w\&\-\.\?\*\#+/^!\(\) ]+(?:,[^*\d][\w\&\-\.\?\*\(\) ]*)*)(?:,(-?[0-9\*]+))?(?:\[((?:[0-9\*]+)+)(?:,(.))?\])?"); + // What ModifyNode reads from a patch value's name (@key,1[2, ] *= ...). It depends on the + // name alone and is the same for every node the patch applies to, so it is parsed once + // per name. The errors it can lead to are still reported each time. + private sealed class ValueCommand + { + public Command cmd; + public Operator op; + public string opValName; // the name without its command and operator + public bool matchSuccess; // parseValue matched opValName + public string name; // group 1 + public bool hasIndex; // group 2 + public bool isStar; + public int index; + public bool indexBad; + public bool hasPosition; // group 3 + public bool isPosStar; + public int position; + public bool positionBad; + public char seperator; // group 4 + public bool hasGroup5; + } + + private static readonly KeyValueCache valueCommandCache = new KeyValueCache(); + private static readonly Func parseValueCommand = ParseValueCommand; + + private static ValueCommand ParseValueCommand(string modValName) + { + ValueCommand parsed = new ValueCommand(); + parsed.cmd = CommandParser.Parse(modValName, out string valName); + + if (valName.Length > 2 && valName[valName.Length - 2] == ',') + parsed.op = Operator.Assign; + else + parsed.op = OperatorParser.Parse(valName, out valName); + parsed.opValName = valName; + + if (parsed.cmd == Command.Special) + return parsed; + + Match match = parseValue.Match(valName); + parsed.matchSuccess = match.Success; + if (!match.Success) + return parsed; + + parsed.name = match.Groups[1].Value; + + parsed.hasPosition = match.Groups[3].Success; + if (parsed.hasPosition) + { + if (match.Groups[3].Value == "*") + parsed.isPosStar = true; + else if (!int.TryParse(match.Groups[3].Value, out parsed.position)) + parsed.positionBad = true; + } + + parsed.seperator = match.Groups[4].Success ? match.Groups[4].Value[0] : ','; + + parsed.hasIndex = match.Groups[2].Success; + if (parsed.hasIndex) + { + if (match.Groups[2].Value == "*") + parsed.isStar = true; + else if (!int.TryParse(match.Groups[2].Value, out parsed.index)) + parsed.indexBad = true; + } + + parsed.hasGroup5 = match.Groups[5].Success; + return parsed; + } + + // What ModifyNode reads from a patch subnode's name (@MODULE[foo],1:HAS[...]) when it + // edits, copies, deletes or replaces existing subnodes. Parsed once per name. + private sealed class SubNodeCommand + { + public string constraints; + public string tag; + public int index; + public string nodeType; + public string nodeName; + } + + private static readonly KeyValueCache subNodeCommandCache = new KeyValueCache(); + private static readonly Func parseSubNodeCommand = ParseSubNodeCommand; + + private static SubNodeCommand ParseSubNodeCommand(string subName) + { + string constraints = ""; + string tag = ""; + string nodeType, nodeName; + int index = 0; + + // three ways to specify: + // NODE,n will match the nth node (NODE is the same as NODE,0) + // NODE,* will match ALL nodes + // NODE:HAS[condition] will match ALL nodes with condition + if (subName.Contains(":HAS[", out int hasStart)) + { + constraints = subName.Substring(hasStart + 5, subName.LastIndexOf(']') - hasStart - 5); + subName = subName.Substring(0, hasStart); + } + + if (subName.Contains(",")) + { + tag = subName.Split(',')[1]; + subName = subName.Split(',')[0]; + int.TryParse(tag, out index); + } + + if (subName.Contains("[")) + { + // format @NODETYPE[Name] {...} + // or @NODETYPE[Name, index] {...} + nodeType = subName.Substring(1).Split('[')[0]; + nodeName = subName.Split('[')[1].Replace("]", ""); + } + else + { + // format @NODETYPE {...} or ! instead of @ + nodeType = subName.Substring(1); + nodeName = null; + } + + return new SubNodeCommand { constraints = constraints, tag = tag, index = index, nodeType = nodeType, nodeName = nodeName }; + } + + // A patch subnode's name with its whitespace removed + private static readonly KeyValueCache removeWSCache = new KeyValueCache(); + private static readonly Func removeWS = s => s.RemoveWS(); + + private static readonly char[] braces = { '{', '}' }; + // Characters that the ConfigNode(string) constructor removes or splits a name on + private static readonly char[] nameCleanupChars = { '\n', '\r', '\t', '(', ')', ' ' }; + + // Set when something is written that a whole copy of its root would change, and that + // a subnode shared instead of copied would keep: a special command (*@PART[foo]/bar = x) + // writing a value with a brace, which the copy sanitizes, or a rename (|_ = A B) to a + // name with a space, a parenthesis or a newline, which the copy cleans. From then on + // edits copy whole roots again. PatchApplier clears it at the start of a run. + public static volatile bool NeedWholeCopies; + // ModifyNode applies the ConfigNode mod as a 'patch' to ConfigNode original, then returns the patched ConfigNode. // it uses FindConfigNodeIn(src, nodeType, nodeName, nodeTag) to recurse. public static ConfigNode ModifyNode(NodeStack original, ConfigNode mod, PatchContext context) { - ConfigNode newNode = original.value.DeepCopy(); + return ModifyNode(original, mod, context, false); + } + + // Same as ModifyNode, but the new node shares the subnodes the patch leaves alone with + // original, instead of being a whole copy: a subnode is copied when the patch first edits + // (@) or replaces (%) it, at the same position, and edited there as ModifyNode would edit + // its copy. original must not be used afterwards but to read it, as the old version of a + // root an edit patch replaces. Nothing else writes into an existing subnode but special + // commands (*@PART[foo]/bar = x): the patch must have none, nor pastes, which can carry + // them, and nothing must have needed whole copies since (NeedWholeCopies). + public static ConfigNode ModifyNodeSharingSubnodes(NodeStack original, ConfigNode mod, PatchContext context) + { + return ModifyNode(original, mod, context, true); + } + + private sealed class ReferenceComparer : IEqualityComparer + { + public static readonly ReferenceComparer Instance = new ReferenceComparer(); + public bool Equals(ConfigNode x, ConfigNode y) => ReferenceEquals(x, y); + public int GetHashCode(ConfigNode obj) => System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj); + } + + private static ConfigNode ModifyNode(NodeStack original, ConfigNode mod, PatchContext context, bool shareSubnodes) + { + ConfigNode newNode; + HashSet sharedSubnodes = null; + Dictionary subnodeCopies = null; + if (shareSubnodes) + { + newNode = original.value.CopySharingSubnodes(); + sharedSubnodes = new HashSet(ReferenceComparer.Instance); + for (int i = 0; i < newNode.nodes.Count; i++) + sharedSubnodes.Add(newNode.nodes[i]); + subnodeCopies = new Dictionary(ReferenceComparer.Instance); + } + else + { + newNode = original.value.DeepCopy(); + } NodeStack nodeStack = original.ReplaceValue(newNode); + // The subnode to write into: a shared one is first replaced by its copy. A subnode + // can be listed twice (negative indexes); the second time it resolves to the copy. + ConfigNode Own(ConfigNode subNode) + { + if (sharedSubnodes == null) return subNode; + if (subnodeCopies.TryGetValue(subNode, out ConfigNode copy)) return copy; + if (!sharedSubnodes.Contains(subNode)) return subNode; + copy = subNode.DeepCopy(); + newNode.ReplaceNode(subNode, copy); + subnodeCopies.Add(subNode, copy); + return copy; + } + #region Values #if LOGSPAM @@ -587,13 +805,10 @@ public static ConfigNode ModifyNode(NodeStack original, ConfigNode mod, PatchCon vals += "\n " + modVal.name + "= " + modVal.value; #endif - Command cmd = CommandParser.Parse(modVal.name, out string valName); - - Operator op; - if (valName.Length > 2 && valName[valName.Length - 2] == ',') - op = Operator.Assign; - else - op = OperatorParser.Parse(valName, out valName); + ValueCommand parsed = valueCommandCache.FetchWithKey(modVal.name, parseValueCommand); + Command cmd = parsed.cmd; + Operator op = parsed.op; + string valName = parsed.opValName; if (cmd == Command.Special) { @@ -605,6 +820,10 @@ public static ConfigNode ModifyNode(NodeStack original, ConfigNode mod, PatchCon continue; } + // The value may be the name of a node in the database, which its index looks nodes up by + if (val.name == "name") + PatchTypeIndex.NameWritten(); + if (op != Operator.Assign) { if (double.TryParse(modVal.value, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out double s) @@ -637,64 +856,46 @@ public static ConfigNode ModifyNode(NodeStack original, ConfigNode mod, PatchCon else { val.value = modVal.value; + // Stock sanitizes such a value when its root is next copied whole + if (val.value != null && val.value.IndexOfAny(braces) >= 0) + NeedWholeCopies = true; } continue; } - Match match = parseValue.Match(valName); - if (!match.Success) + if (!parsed.matchSuccess) { context.progress.Error(context.patchUrl, "Error - Cannot parse value modifying command: " + valName); continue; } // Get the bits and pieces from the regexp - valName = match.Groups[1].Value; + valName = parsed.name; // Get a position for editing a vector - int position = 0; - bool isPosStar = false; - if (match.Groups[3].Success) + int position = parsed.position; + bool isPosStar = parsed.isPosStar; + if (parsed.positionBad) { - if (match.Groups[3].Value == "*") - isPosStar = true; - else if (!int.TryParse(match.Groups[3].Value, out position)) - { - context.progress.Error(context.patchUrl, "Error - Unable to parse number as number. Very odd."); - continue; - } - } - char seperator = ','; - if (match.Groups[4].Success) - { - seperator = match.Groups[4].Value[0]; + context.progress.Error(context.patchUrl, "Error - Unable to parse number as number. Very odd."); + continue; } + char seperator = parsed.seperator; // In this case insert the value at position index (with the same node names) - int index = 0; - bool isStar = false; - if (match.Groups[2].Success) + int index = parsed.index; + bool isStar = parsed.isStar; + if (parsed.indexBad) { - if (match.Groups[2].Value == "*") - isStar = true; - // can have "node,n *" (for *= ect) - else if (!int.TryParse(match.Groups[2].Value, out index)) - { - context.progress.Error(context.patchUrl, "Error - Unable to parse number as number. Very odd."); - continue; - } + context.progress.Error(context.patchUrl, "Error - Unable to parse number as number. Very odd."); + continue; } - int valCount = 0; - for (int i=0; i= 0) + NeedWholeCopies = true; break; case Command.Create: - if (match.Groups[2].Success || match.Groups[5].Success || valName.Contains('*') + if (parsed.hasIndex || parsed.hasGroup5 || valName.Contains('*') || valName.Contains('?')) { - if (match.Groups[2].Success) + if (parsed.hasIndex) context.progress.Error(context.patchUrl, "Error - Cannot use index with create (&) value: " + mod.name); - if (match.Groups[5].Success) + if (parsed.hasGroup5) context.progress.Error(context.patchUrl, "Error - Cannot use operators with create (&) value: " + mod.name); if (valName.Contains('*') || valName.Contains('?')) context.progress.Error(context.patchUrl, "Error - Cannot use wildcards (* or ?) with create (&) value: " + mod.name); @@ -870,7 +1082,7 @@ public static ConfigNode ModifyNode(NodeStack original, ConfigNode mod, PatchCon foreach (ConfigNode subMod in mod.nodes) { - subMod.name = subMod.name.RemoveWS(); + subMod.name = removeWSCache.FetchWithKey(subMod.name, removeWS); if (!subMod.name.IsBracketBalanced()) { @@ -933,61 +1145,22 @@ public static ConfigNode ModifyNode(NodeStack original, ConfigNode mod, PatchCon } else { - string constraints = ""; - string tag = ""; - string nodeType, nodeName; - int index = 0; + SubNodeCommand subCommand = subNodeCommandCache.FetchWithKey(subName, parseSubNodeCommand); + string constraints = subCommand.constraints; + string tag = subCommand.tag; + string nodeType = subCommand.nodeType, nodeName = subCommand.nodeName; + int index = subCommand.index; #if LOGSPAM string msg = ""; #endif List subNodes = new List(); - // three ways to specify: - // NODE,n will match the nth node (NODE is the same as NODE,0) - // NODE,* will match ALL nodes - // NODE:HAS[condition] will match ALL nodes with condition - if (subName.Contains(":HAS[", out int hasStart)) - { - constraints = subName.Substring(hasStart + 5, subName.LastIndexOf(']') - hasStart - 5); - subName = subName.Substring(0, hasStart); - } - - if (subName.Contains(",")) - { - tag = subName.Split(',')[1]; - subName = subName.Split(',')[0]; - int.TryParse(tag, out index); - } - - if (subName.Contains("[")) - { - // format @NODETYPE[Name] {...} - // or @NODETYPE[Name, index] {...} - nodeType = subName.Substring(1).Split('[')[0]; - nodeName = subName.Split('[')[1].Replace("]", ""); - } - else - { - // format @NODETYPE {...} or ! instead of @ - nodeType = subName.Substring(1); - nodeName = null; - } - if (tag == "*" || constraints.Length > 0) { // get ALL nodes if (command != Command.Replace) { - ConfigNode n, last = null; - while (true) - { - n = FindConfigNodeIn(newNode, nodeType, nodeName, index++); - if (n == last || n == null) - break; - if (CheckConstraints(n, constraints)) - subNodes.Add(n); - last = n; - } + FindConfigNodesFrom(newNode, nodeType, nodeName, index, GetParsedConstraints(constraints), false, subNodes); } #if LOGSPAM else @@ -1010,9 +1183,10 @@ public static ConfigNode ModifyNode(NodeStack original, ConfigNode mod, PatchCon #if LOGSPAM msg += " Applying subnode " + subMod.name + "\n"; #endif - ConfigNode newSubNode = ModifyNode(nodeStack.Push(subNodes[0]), subMod, context); - subNodes[0].ShallowCopyFrom(newSubNode); - subNodes[0].name = newSubNode.name; + ConfigNode target = Own(subNodes[0]); + ConfigNode newSubNode = ModifyNode(nodeStack.Push(target), subMod, context); + target.ShallowCopyFrom(newSubNode); + target.name = newSubNode.name; } else { @@ -1066,9 +1240,10 @@ public static ConfigNode ModifyNode(NodeStack original, ConfigNode mod, PatchCon case Command.Edit: // Edit in place - newSubNode = ModifyNode(nodeStack.Push(subNode), subMod, context); - subNode.ShallowCopyFrom(newSubNode); - subNode.name = newSubNode.name; + ConfigNode target = Own(subNode); + newSubNode = ModifyNode(nodeStack.Push(target), subMod, context); + target.ShallowCopyFrom(newSubNode); + target.name = newSubNode.name; break; case Command.Delete: @@ -1156,21 +1331,9 @@ private static ConfigNode RecurseNodeSearch(string path, NodeStack nodeStack, Pa // @XXXXX if (root) { - bool foundNodeType = false; - foreach (IProtoUrlConfig urlConfig in context.databaseConfigs) - { - ConfigNode node = urlConfig.Node; - - if (node.name != nodeType) continue; - - foundNodeType = true; - - if (nodeName == null || (node.GetValue("name") is string testNodeName && WildcardMatch(testNodeName, nodeName))) - { - nodeStack = new NodeStack(node); - break; - } - } + ConfigNode rootNode = FindRootNode(context, nodeType, nodeName, out bool foundNodeType); + if (rootNode != null) + nodeStack = new NodeStack(rootNode); if (!foundNodeType) context.logger.Warning("Can't find nodeType:" + nodeType); if (nodeStack == null) return null; @@ -1180,22 +1343,8 @@ private static ConfigNode RecurseNodeSearch(string path, NodeStack nodeStack, Pa if (constraint.Length > 0) { // get the first one matching - ConfigNode last = null; - while (true) - { - ConfigNode n = FindConfigNodeIn(nodeStack.value, nodeType, nodeName, index++); - if (n == last || n == null) - { - nodeStack = null; - break; - } - if (CheckConstraints(n, constraint)) - { - nodeStack = nodeStack.Push(n); - break; - } - last = n; - } + ConfigNode n = FindConfigNodesFrom(nodeStack.value, nodeType, nodeName, index, GetParsedConstraints(constraint), true, null); + nodeStack = n != null ? nodeStack.Push(n) : null; } else { @@ -1215,6 +1364,55 @@ private static ConfigNode RecurseNodeSearch(string path, NodeStack nodeStack, Pa return nodeStack.value; } + // The first root node in the database of type nodeType whose name value matches nodeName + // (any node of that type if null), and whether there is any node of that type + private static ConfigNode FindRootNode(PatchContext context, string nodeType, string nodeName, out bool foundNodeType) + { + PatchTypeIndex index = context.typeIndex; + if (index == null) + { + foundNodeType = false; + foreach (IProtoUrlConfig urlConfig in context.databaseConfigs) + { + ConfigNode node = urlConfig.Node; + + if (node.name != nodeType) continue; + + foundNodeType = true; + + if (nodeName == null || (node.GetValue("name") is string testNodeName && WildcardMatch(testNodeName, nodeName))) + return node; + } + return null; + } + + // The same nodes in the same order: those of the type, in list order + List> nodes = index.NodesOfType(nodeType); + foundNodeType = nodes.Count > 0; + if (nodeName == null) + return foundNodeType ? nodes[0].Value.Node : null; + + if (nodeName.IndexOfAny(wildcardChars) < 0) + { + // A name without wildcards matches itself or itself followed by a newline: the + // index has their positions, and the first of either is the first match + List exact = index.PositionsNamed(nodeType, nodeName); + List newline = index.PositionsNamed(nodeType, nodeName + "\n"); + int first = int.MaxValue; + if (exact.Count > 0) first = exact[0]; + if (newline.Count > 0 && newline[0] < first) first = newline[0]; + return first != int.MaxValue ? nodes[first].Value.Node : null; + } + + for (int i = 0; i < nodes.Count; i++) + { + ConfigNode node = nodes[i].Value.Node; + if (node.GetValue("name") is string testNodeName && WildcardMatch(testNodeName, nodeName)) + return node; + } + return null; + } + // KeyName is group 1, index is group 2, value index is group 3, value separator is group 4 private static readonly Regex parseVarKey = new Regex(@"([\w\&\-\.]+)(?:,((?:[0-9]+)+))?(?:\[((?:[0-9]+)+)(?:,(.))?\])?"); @@ -1252,20 +1450,9 @@ private static ConfigNode.Value RecurseVariableSearch(string path, NodeStack nod nodeName = null; } - bool foundNodeType = false; - foreach (IProtoUrlConfig urlConfig in context.databaseConfigs) - { - ConfigNode node = urlConfig.Node; - - if (node.name != nodeType) continue; - - foundNodeType = true; - - if (nodeName == null || (node.GetValue("name") is string testNodeName && WildcardMatch(testNodeName, nodeName))) - { - return RecurseVariableSearch(path.Substring(nextSep + 1), new NodeStack(node), context); - } - } + ConfigNode rootNode = FindRootNode(context, nodeType, nodeName, out bool foundNodeType); + if (rootNode != null) + return RecurseVariableSearch(path.Substring(nextSep + 1), new NodeStack(rootNode), context); if (!foundNodeType) context.logger.Warning("Can't find nodeType:" + nodeType); @@ -1318,16 +1505,9 @@ private static ConfigNode.Value RecurseVariableSearch(string path, NodeStack nod if (constraint.Length > 0) { // get the first one matching - ConfigNode last = null; - while (true) - { - ConfigNode n = FindConfigNodeIn(nodeStack.value, nodeType, nodeName, index++); - if (n == last || n == null) - break; - if (CheckConstraints(n, constraint)) - return RecurseVariableSearch(path.Substring(nextSep + 1), nodeStack.Push(n), context); - last = n; - } + ConfigNode n = FindConfigNodesFrom(nodeStack.value, nodeType, nodeName, index, GetParsedConstraints(constraint), true, null); + if (n != null) + return RecurseVariableSearch(path.Substring(nextSep + 1), nodeStack.Push(n), context); return null; } else @@ -1535,116 +1715,191 @@ public static List SplitConstraints(string condition) static readonly char[] contraintSeparators = { '[', ']' }; - public static bool CheckConstraints(ConfigNode node, string constraints) + // CheckConstraints is called for every node a patch might apply to, with the same few + // constraint strings, so each string is parsed once. The constraints it nests are looked + // up when first checked, as the strings were parsed when first checked, and then kept, so + // checking them again needs no lookup. + public sealed class ParsedConstraints + { + internal bool empty; + internal List list; + internal char op; + internal string type; + internal string name; + internal string remaining; + internal bool compare; + internal double compareValue; + // type and name have no wildcard: WildcardMatch is then a plain comparison + internal bool typeLiteral; + internal bool nameLiteral; + + private ParsedConstraints[] listParsed; + private ParsedConstraints remainingParsed; + + internal ParsedConstraints ListItem(int i) + { + if (listParsed == null) listParsed = new ParsedConstraints[list.Count]; + return listParsed[i] ?? (listParsed[i] = GetParsedConstraints(list[i])); + } + + internal ParsedConstraints Remaining => remainingParsed ?? (remainingParsed = GetParsedConstraints(remaining)); + } + + private static readonly KeyValueCache constraintsCache = new KeyValueCache(); + private static readonly Func parseConstraints = ParseConstraints; + + public static ParsedConstraints GetParsedConstraints(string constraints) + { + if (constraints == null) throw new ArgumentNullException("input"); + return constraintsCache.FetchWithKey(constraints, parseConstraints); + } + + private static ParsedConstraints ParseConstraints(string constraints) { + ParsedConstraints parsed = new ParsedConstraints(); constraints = constraints.RemoveWS(); if (constraints.Length == 0) - return true; + { + parsed.empty = true; + return parsed; + } List constraintList = SplitConstraints(constraints); - if (constraintList.Count == 1) + if (constraintList.Count != 1) { - constraints = constraintList[0]; + parsed.list = constraintList; + return parsed; + } - string remainingConstraints = ""; - if (constraints.Contains(":HAS[", out int hasStart)) - { - hasStart += 5; - remainingConstraints = constraints.Substring(hasStart, constraintList[0].LastIndexOf(']') - hasStart); - constraints = constraints.Substring(0, hasStart - 5); - } + constraints = constraintList[0]; + + string remainingConstraints = ""; + if (constraints.Contains(":HAS[", out int hasStart)) + { + hasStart += 5; + remainingConstraints = constraints.Substring(hasStart, constraintList[0].LastIndexOf(']') - hasStart); + constraints = constraints.Substring(0, hasStart - 5); + } + + string[] splits = constraints.Split(contraintSeparators, 3); + parsed.type = splits[0].Substring(1); + parsed.name = splits.Length > 1 ? splits[1] : null; + parsed.op = constraints[0]; + parsed.remaining = remainingConstraints; + parsed.compare = ParseCompare(parsed.name, out parsed.compareValue); + parsed.typeLiteral = parsed.type.IndexOfAny(wildcardChars) < 0; + parsed.nameLiteral = parsed.name != null && parsed.name.IndexOfAny(wildcardChars) < 0; + return parsed; + } + + public static bool CheckConstraints(ConfigNode node, string constraints) + { + return CheckConstraints(node, GetParsedConstraints(constraints)); + } - string[] splits = constraints.Split(contraintSeparators, 3); - string type = splits[0].Substring(1); - string name = splits.Length > 1 ? splits[1] : null; + public static bool CheckConstraints(ConfigNode node, ParsedConstraints parsed) + { + if (parsed.empty) + return true; - switch (constraints[0]) + if (parsed.list != null) + { + // Like ret = ret && Check(...) over the list: once one fails, the rest are not checked + int count = parsed.list.Count; + for (int i = 0; i < count; i++) { - case '@': - case '!': + if (!CheckConstraints(node, parsed.ListItem(i))) + return false; + } + return true; + } - // @MODULE[ModuleAlternator] or !MODULE[ModuleAlternator] - bool not = (constraints[0] == '!'); + string type = parsed.type; + string name = parsed.name; - bool any = false; - int index = 0; - ConfigNode last = null; - while (true) - { - ConfigNode subNode = FindConfigNodeIn(node, type, name, index++); - if (subNode == last || subNode == null) - break; - any = any || CheckConstraints(subNode, remainingConstraints); - last = subNode; - } - if (last != null) - { - //print("CheckConstraints: " + constraints + " " + (not ^ any)); - return not ^ any; - } - //print("CheckConstraints: " + constraints + " " + (not ^ false)); - return not ^ false; + switch (parsed.op) + { + case '@': + case '!': - case '#': + // @MODULE[ModuleAlternator] or !MODULE[ModuleAlternator] + bool not = (parsed.op == '!'); - // #module[Winglet] - if (node.HasValue(type) && WildcardMatchValues(node, type, name)) - { - bool ret2 = CheckConstraints(node, remainingConstraints); - //print("CheckConstraints: " + constraints + " " + ret2); - return ret2; - } - //print("CheckConstraints: " + constraints + " false"); - return false; + // Each subnode FindConfigNodeIn (node, type, name, index) returns for index = 0, 1, ... + // until it repeats one, in a single pass. + bool any = false; + ConfigNode last = null; + int c = node.nodes.Count; + for (int i = 0; i < c && !any; ++i) + { + ConfigNode subNode = node.nodes[i]; + string subType = subNode.name; + if (parsed.typeLiteral && subType != null ? !LiteralMatch(subType, type) : !WildcardMatch(subType, type)) + continue; + if (name != null && !(subNode.GetValue("name") is string subName && (parsed.nameLiteral ? LiteralMatch(subName, name) : WildcardMatch(subName, name)))) + continue; + if (subNode == last) + break; + any = CheckConstraints(subNode, parsed.Remaining); + last = subNode; + } + if (last != null) + return not ^ any; + return not ^ false; - case '~': + case '#': - // ~breakingForce[] breakingForce is not present - // or: ~breakingForce[100] will be true if it's present but not 100, too. - if (name == "" && node.HasValue(type)) - { - //print("CheckConstraints: " + constraints + " false"); - return false; - } - if (name != "" && WildcardMatchValues(node, type, name)) - { - //print("CheckConstraints: " + constraints + " false"); - return false; - } - bool ret = CheckConstraints(node, remainingConstraints); - //print("CheckConstraints: " + constraints + " " + ret); - return ret; + // #module[Winglet]. No value of that name means no match, as HasValue(type) was checked first. + if (WildcardMatchValues(node, type, name, parsed.compare, parsed.compareValue)) + return CheckConstraints(node, parsed.Remaining); + return false; - default: - //print("CheckConstraints: " + constraints + " false"); + case '~': + + // ~breakingForce[] breakingForce is not present + // or: ~breakingForce[100] will be true if it's present but not 100, too. + if (name == "" && node.HasValue(type)) return false; - } - } + if (name != "" && WildcardMatchValues(node, type, name, parsed.compare, parsed.compareValue)) + return false; + return CheckConstraints(node, parsed.Remaining); - bool ret3 = true; - foreach (string constraint in constraintList) - { - ret3 = ret3 && CheckConstraints(node, constraint); + default: + return false; } - //print("CheckConstraints: " + constraints + " " + ret3); - return ret3; } - public static bool WildcardMatchValues(ConfigNode node, string type, string value) + // Whether value is a number comparison (<10, >0.5) and its number + private static bool ParseCompare(string value, out double val) { - double val = 0; + val = 0; bool compare = value != null && value.Length > 1 && (value[0] == '<' || value[0] == '>'); - compare = compare && double.TryParse(value.Substring(1), NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out val); + return compare && double.TryParse(value.Substring(1), NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out val); + } - string[] values = node.GetValues(type); - for (int i = 0; i < values.Length; i++) + public static bool WildcardMatchValues(ConfigNode node, string type, string value) + { + bool compare = ParseCompare(value, out double val); + return WildcardMatchValues(node, type, value, compare, val); + } + + // Walks the values once, in order, instead of collecting them with GetValues(type) + private static bool WildcardMatchValues(ConfigNode node, string type, string value, bool compare, double val) + { + ConfigNode.ValueList values = node.values; + int count = values.Count; + for (int i = 0; i < count; i++) { - if (!compare && WildcardMatch(values[i], value)) + ConfigNode.Value v = values[i]; + if (v.name != type) + continue; + + if (!compare && WildcardMatch(v.value, value)) return true; - if (compare && double.TryParse(values[i], NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out double val2) + if (compare && double.TryParse(v.value, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out double val2) && ((value[0] == '<' && val2 < val) || (value[0] == '>' && val2 > val))) { return true; @@ -1653,19 +1908,72 @@ public static bool WildcardMatchValues(ConfigNode node, string type, string valu return false; } + private static readonly KeyValueCache wildcardRegexCache = new KeyValueCache(); + private static readonly char[] wildcardChars = { '*', '?' }; + public static bool WildcardMatch(string s, string wildcard) { if (wildcard == null) return true; - string pattern = "^" + Regex.Escape(wildcard).Replace(@"\*", ".*").Replace(@"\?", ".") + "$"; + if (s == null) + throw new ArgumentNullException("input"); - Regex regex = regexCache.Fetch(pattern, delegate - { - return new Regex(pattern); - }); + if (wildcard.IndexOfAny(wildcardChars) < 0) + return LiteralMatch(s, wildcard); + + // The pattern is the regex ^...$ with * as .* and ? as ., where . is any character but + // a newline. Without a newline in s that is a plain glob match. + if (s.IndexOf('\n') < 0) + return GlobMatch(s, wildcard); + + Regex regex = wildcardRegexCache.FetchWithKey(wildcard, w => + new Regex("^" + Regex.Escape(w).Replace(@"\*", ".*").Replace(@"\?", ".") + "$")); return regex.IsMatch(s); } + // WildcardMatch for a pattern without wildcards, whose regex is ^literal$: $ also matches + // before a final newline. s must not be null. + private static bool LiteralMatch(string s, string literal) + { + return s == literal + || (s.Length == literal.Length + 1 && s[literal.Length] == '\n' && string.CompareOrdinal(s, 0, literal, 0, literal.Length) == 0); + } + + // Whole-string match of s against a pattern where * is any run of characters and ? any one + // character, compared ordinally. Backtracks only to the last *, which is enough for *. + private static bool GlobMatch(string s, string pattern) + { + int si = 0, pi = 0; + int starPi = -1, starSi = 0; + int sLen = s.Length, pLen = pattern.Length; + while (si < sLen) + { + if (pi < pLen) + { + char pc = pattern[pi]; + if (pc == '*') + { + starPi = pi++; + starSi = si; + continue; + } + if (pc == '?' || pc == s[si]) + { + si++; + pi++; + continue; + } + } + if (starPi < 0) + return false; + pi = starPi + 1; + si = ++starSi; + } + while (pi < pLen && pattern[pi] == '*') + pi++; + return pi == pLen; + } + #endregion Condition checking #region Config Node Utilities @@ -1689,6 +1997,16 @@ private static void InsertNode(ConfigNode newNode, ConfigNode subMod, int index) newNode.AddNode(subMod); } + private static int CountValues(ConfigNode node, string name) + { + ConfigNode.ValueList values = node.values; + int count = 0; + for (int i = 0; i < values.Count; i++) + if (values[i].name == name) + count++; + return count; + } + private static void InsertValue(ConfigNode newNode, int index, string name, string value) { string[] oldValues = newNode.GetValues(name); @@ -1715,41 +2033,59 @@ public static ConfigNode FindConfigNodeIn( string nodeName = null, int index = 0) { - List nodes = new List(); + // Among the subnodes whose type matches nodeType: without nodeName, the index-th (from + // the end if negative, clamped to the first or last); with nodeName, the index-th of + // those whose name matches, or the last one checked if there are fewer than that. int c = src.nodes.Count; - for(int i = 0; i < c; ++i) - { - if (WildcardMatch(src.nodes[i].name, nodeType)) - nodes.Add(src.nodes[i]); - } - int nodeCount = nodes.Count; - if (nodeCount == 0) - return null; + ConfigNode last = null; if (nodeName == null) { if (index >= 0) - return nodes[Math.Min(index, nodeCount - 1)]; - return nodes[Math.Max(0, nodeCount + index)]; + { + for (int i = 0; i < c; ++i) + { + ConfigNode n = src.nodes[i]; + if (WildcardMatch(n.name, nodeType)) + { + last = n; + if (index-- == 0) + return n; + } + } + return last; + } + for (int i = c - 1; i >= 0; --i) + { + ConfigNode n = src.nodes[i]; + if (WildcardMatch(n.name, nodeType)) + { + last = n; + if (++index == 0) + return n; + } + } + return last; } - ConfigNode last = null; if (index >= 0) { - for (int i = 0; i < nodeCount; ++i) + for (int i = 0; i < c; ++i) { - if (nodes[i].HasValue("name") && WildcardMatch(nodes[i].GetValue("name"), nodeName)) + ConfigNode n = src.nodes[i]; + if (WildcardMatch(n.name, nodeType) && n.GetValue("name") is string name && WildcardMatch(name, nodeName)) { - last = nodes[i]; + last = n; if (--index < 0) return last; } } return last; } - for (int i = nodeCount - 1; i >= 0; --i) + for (int i = c - 1; i >= 0; --i) { - if (nodes[i].HasValue("name") && WildcardMatch(nodes[i].GetValue("name"), nodeName)) + ConfigNode n = src.nodes[i]; + if (WildcardMatch(n.name, nodeType) && n.GetValue("name") is string name && WildcardMatch(name, nodeName)) { - last = nodes[i]; + last = n; if (++index >= 0) return last; } @@ -1757,6 +2093,67 @@ public static ConfigNode FindConfigNodeIn( return last; } + // Walks the nodes FindConfigNodeIn(src, nodeType, nodeName, i) returns for i = index, + // index + 1, ... until it returns null or the node it returned before, and keeps those + // that pass the constraints: all of them in into, or only the first, which it returns. + // From an index of 0 or more those are the matching subnodes from that index on, or the + // last one if there are no more than index, found here in one pass. + private static ConfigNode FindConfigNodesFrom( + ConfigNode src, + string nodeType, + string nodeName, + int index, + ParsedConstraints constraints, + bool firstOnly, + List into) + { + if (index < 0) + { + // From the end then on from the start: rare, so as it always was + ConfigNode n, last = null; + while (true) + { + n = FindConfigNodeIn(src, nodeType, nodeName, index++); + if (n == last || n == null) + return null; + if (CheckConstraints(n, constraints)) + { + if (firstOnly) return n; + into.Add(n); + } + last = n; + } + } + + int matched = 0; + ConfigNode lastMatch = null; + int c = src.nodes.Count; + for (int i = 0; i < c; ++i) + { + ConfigNode n = src.nodes[i]; + if (!WildcardMatch(n.name, nodeType)) + continue; + if (nodeName != null && !(n.GetValue("name") is string name && WildcardMatch(name, nodeName))) + continue; + lastMatch = n; + if (matched++ < index) + continue; + if (CheckConstraints(n, constraints)) + { + if (firstOnly) return n; + into.Add(n); + } + } + + // Fewer matches than index: FindConfigNodeIn gave the last one, once + if (matched > 0 && matched <= index && CheckConstraints(lastMatch, constraints)) + { + if (firstOnly) return lastMatch; + into.Add(lastMatch); + } + return null; + } + private static ConfigNode.Value FindValueIn(ConfigNode newNode, string valName, int index) { ConfigNode.Value v = null; diff --git a/ModuleManager/ModuleManager.csproj b/ModuleManager/ModuleManager.csproj index 20fe0da1..b45d601b 100644 --- a/ModuleManager/ModuleManager.csproj +++ b/ModuleManager/ModuleManager.csproj @@ -79,6 +79,9 @@ + + + diff --git a/ModuleManager/NeedsChecker.cs b/ModuleManager/NeedsChecker.cs index 94f2ad29..654d7907 100644 --- a/ModuleManager/NeedsChecker.cs +++ b/ModuleManager/NeedsChecker.cs @@ -32,10 +32,21 @@ public NeedsChecker(IEnumerable mods, UrlDir gameData, IPatchProgress pr this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); } + // Every patch's NEEDS asks about the same few hundred mods: the mod list as a set, taken + // when first needed, and each expression's answer. Neither the mod list nor GameData's + // directories change while patches are extracted. + private HashSet modSet; + private readonly Dictionary expressionResults = new Dictionary(); + public bool CheckNeeds(string mod) { if (mod == null) throw new ArgumentNullException(nameof(mod)); if (mod == string.Empty) throw new ArgumentException("can't be empty", nameof(mod)); + if (modSet == null) modSet = new HashSet(mods, StringComparer.InvariantCultureIgnoreCase); + if (modSet.Contains(mod)) return true; + // A hit is an equality the comparer agreed to; a miss could come from hash codes that + // do not agree with its equality, which nothing promises on every runtime: a miss is + // checked the way it always was. Each NEEDS expression is evaluated once anyway. return mods.Contains(mod, StringComparer.InvariantCultureIgnoreCase); } @@ -44,6 +55,16 @@ public bool CheckNeedsExpression(string needsExpression) if (needsExpression == null) throw new ArgumentNullException(nameof(needsExpression)); if (needsExpression == string.Empty) throw new ArgumentException("can't be empty", nameof(needsExpression)); + if (!expressionResults.TryGetValue(needsExpression, out bool result)) + { + result = EvaluateNeedsExpression(needsExpression); + expressionResults.Add(needsExpression, result); + } + return result; + } + + private bool EvaluateNeedsExpression(string needsExpression) + { foreach (string andDependencies in needsExpression.Split(',', '&')) { bool orMatch = false; diff --git a/ModuleManager/NodeMatcher.cs b/ModuleManager/NodeMatcher.cs index 8777de97..a80c85bb 100644 --- a/ModuleManager/NodeMatcher.cs +++ b/ModuleManager/NodeMatcher.cs @@ -13,6 +13,14 @@ public class NodeMatcher : INodeMatcher private readonly string type; private readonly string[] namePatterns = null; private readonly string constraints = ""; + private MMPatchLoader.ParsedConstraints parsedConstraints; + + // Only nodes of this type can match: ConfigNode.name is the type (e.g. PART), not the name value. + public string Type => type; + + // The name patterns if none has a wildcard, else null. A node can match only if its + // name value is one of them, or one of them followed by a newline. + public string[] LiteralNames { get; } public NodeMatcher(string type, string name, string constraints) { @@ -22,7 +30,12 @@ public NodeMatcher(string type, string name, string constraints) if (name == string.Empty) throw new ArgumentException("can't be empty (null allowed)", nameof(name)); if (constraints == string.Empty) throw new ArgumentException("can't be empty (null allowed)", nameof(constraints)); - if (name != null) namePatterns = name.Split(',', '|'); + if (name != null) + { + namePatterns = name.Split(',', '|'); + if (Array.TrueForAll(namePatterns, pattern => pattern.IndexOfAny(new[] { '*', '?' }) < 0)) + LiteralNames = namePatterns; + } if (constraints != null) { if (!constraints.IsBracketBalanced()) throw new ArgumentException("is not bracket balanced: " + constraints, nameof(constraints)); @@ -33,10 +46,24 @@ public NodeMatcher(string type, string name, string constraints) public bool IsMatch(ConfigNode node) { if (node.name != type) return false; + return IsNameAndConstraintsMatch(node, namePatterns != null ? node.GetValue("name") : null); + } + + // Same as IsMatch(protoConfig.Node), but takes the name value a ProtoUrlConfig already read. + public bool IsMatch(IProtoUrlConfig protoConfig) + { + ConfigNode node = protoConfig.Node; + if (node.name != type) return false; + string name = null; + if (namePatterns != null) + name = protoConfig is ProtoUrlConfig known ? known.NameValue : node.GetValue("name"); + return IsNameAndConstraintsMatch(node, name); + } + private bool IsNameAndConstraintsMatch(ConfigNode node, string name) + { if (namePatterns != null) { - string name = node.GetValue("name"); if (name == null) return false; bool match = false; @@ -52,7 +79,20 @@ public bool IsMatch(ConfigNode node) if (!match) return false; } - return MMPatchLoader.CheckConstraints(node, constraints); + // Looked up on first use, so a constraint that does not parse still throws when checked + if (parsedConstraints == null) parsedConstraints = MMPatchLoader.GetParsedConstraints(constraints); + return MMPatchLoader.CheckConstraints(node, parsedConstraints); + } + } + + public static class NodeMatcherExtensions + { + // Uses NodeMatcher.IsMatch(IProtoUrlConfig) when available, so patches can match a config + // without looking up its name again. Other matchers get the node. + public static bool IsMatch(this INodeMatcher nodeMatcher, IProtoUrlConfig protoConfig) + { + if (nodeMatcher is NodeMatcher matcher) return matcher.IsMatch(protoConfig); + return nodeMatcher.IsMatch(protoConfig.Node); } } } diff --git a/ModuleManager/PatchApplier.cs b/ModuleManager/PatchApplier.cs index adaade88..3536cb82 100644 --- a/ModuleManager/PatchApplier.cs +++ b/ModuleManager/PatchApplier.cs @@ -23,16 +23,18 @@ public IEnumerable ApplyPatches(IEnumerable patches) if (patches == null) throw new ArgumentNullException(nameof(patches)); LinkedList databaseConfigs = new LinkedList(); + MMPatchLoader.NeedWholeCopies = false; + PatchTypeIndex index = new PatchTypeIndex(databaseConfigs); foreach (IPass pass in patches) { - ApplyPatches(databaseConfigs, pass); + ApplyPatches(databaseConfigs, index, pass); } return databaseConfigs; } - private void ApplyPatches(LinkedList databaseConfigs, IPass pass) + private void ApplyPatches(LinkedList databaseConfigs, PatchTypeIndex index, IPass pass) { progress.PassStarted(pass); @@ -40,7 +42,35 @@ private void ApplyPatches(LinkedList databaseConfigs, IPass pas { try { - patch.Apply(databaseConfigs, progress, logger); + // Edit, copy and delete patches, nearly all of them, need only the nodes of one + // type, and keep the index up to date themselves. Inserts add one node of + // their type, after which the index rebuilds that group when next needed. + if (patch is EditPatch editPatch) + { + editPatch.Apply(databaseConfigs, index, progress, logger); + } + else if (patch is CopyPatch copyPatch) + { + copyPatch.Apply(databaseConfigs, index, progress, logger); + } + else if (patch is DeletePatch deletePatch) + { + deletePatch.Apply(databaseConfigs, index, progress, logger); + } + else + { + InvalidateFor(index, patch); + try + { + patch.Apply(databaseConfigs, progress, logger); + } + finally + { + // If anything reads the index while the patch is still adding or + // removing nodes, the stale group is rebuilt half way: mark it again. + InvalidateFor(index, patch); + } + } if (patch.CountsAsPatch) progress.PatchApplied(); } catch (Exception e) @@ -50,5 +80,13 @@ private void ApplyPatches(LinkedList databaseConfigs, IPass pas } } } + + private static void InvalidateFor(PatchTypeIndex index, IPatch patch) + { + if (patch is InsertPatch insertPatch) + index.Invalidate(insertPatch.NodeType); + else + index.Invalidate(); + } } } diff --git a/ModuleManager/PatchContext.cs b/ModuleManager/PatchContext.cs index 09e2f441..d45ad85d 100644 --- a/ModuleManager/PatchContext.cs +++ b/ModuleManager/PatchContext.cs @@ -12,12 +12,22 @@ public struct PatchContext public readonly IBasicLogger logger; public readonly IPatchProgress progress; + // The type index of databaseConfigs, if it stays valid while the patch runs, for lookups + // of root nodes (#$@PART[foo]/mass$). Null to search databaseConfigs. + public readonly PatchTypeIndex typeIndex; + public PatchContext(UrlDir.UrlConfig patchUrl, IEnumerable databaseConfigs, IBasicLogger logger, IPatchProgress progress) + : this(patchUrl, databaseConfigs, logger, progress, null) + { + } + + public PatchContext(UrlDir.UrlConfig patchUrl, IEnumerable databaseConfigs, IBasicLogger logger, IPatchProgress progress, PatchTypeIndex typeIndex) { this.patchUrl = patchUrl; this.databaseConfigs = databaseConfigs; this.logger = logger; this.progress = progress; + this.typeIndex = typeIndex; } } } diff --git a/ModuleManager/PatchTypeIndex.cs b/ModuleManager/PatchTypeIndex.cs new file mode 100644 index 00000000..a896cc56 --- /dev/null +++ b/ModuleManager/PatchTypeIndex.cs @@ -0,0 +1,177 @@ +using System; +using System.Collections.Generic; +using System.Threading; + +namespace ModuleManager +{ + // The nodes of a config list grouped by node type, each group in list order. Built on first + // use; whoever adds or removes nodes from the list must call Invalidate, with the type of the + // nodes if they are all of one type, so that only that group is rebuilt. + // + // Each group can also be looked up by the nodes' name value, giving the positions in the + // group of the nodes with that name. Whoever changes the name of a node in the list must call + // NamesChanged with its type. A special command can write a name value in place, in any node: + // it calls NameWritten, after which every name lookup is rebuilt. + public class PatchTypeIndex + { + private static readonly List> none = new List>(); + private static readonly List noPositions = new List(); + + private static int nameWrites; + + // Counts the name values written in place, by any patching run + public static int NameWrites => Volatile.Read(ref nameWrites); + public static void NameWritten() => Interlocked.Increment(ref nameWrites); + + private readonly LinkedList configs; + private Dictionary>> byType; + private readonly HashSet staleTypes = new HashSet(); + + private readonly Dictionary>> byName = new Dictionary>>(); + private int byNameWrites; + + public PatchTypeIndex(LinkedList configs) + { + this.configs = configs ?? throw new ArgumentNullException(nameof(configs)); + } + + // The name value NodeMatcher matches a config's name patterns against + public static string NameOf(IProtoUrlConfig config) => config is ProtoUrlConfig known ? known.NameValue : config.Node.GetValue("name"); + + public List> NodesOfType(string type) + { + if (type == null) throw new ArgumentNullException(nameof(type)); + if (byType == null) Build(); + else if (staleTypes.Remove(type)) Rebuild(type); + return byType.TryGetValue(type, out List> nodes) ? nodes : none; + } + + // The positions in NodesOfType(type), in order, of the nodes whose name value is name + public List PositionsNamed(string type, string name) + { + if (name == null) throw new ArgumentNullException(nameof(name)); + List> nodes = NodesOfType(type); + int writes = NameWrites; + if (byNameWrites != writes) + { + byName.Clear(); + byNameWrites = writes; + } + if (!byName.TryGetValue(type, out Dictionary> names)) + { + names = new Dictionary>(); + for (int i = 0; i < nodes.Count; i++) + { + string nodeName = NameOf(nodes[i].Value); + if (nodeName == null) continue; + if (!names.TryGetValue(nodeName, out List positions)) + { + positions = new List(1); + names.Add(nodeName, positions); + } + positions.Add(i); + } + byName.Add(type, names); + } + return names.TryGetValue(name, out List found) ? found : noPositions; + } + + // The positions of the nodes named one of names (or one followed by a newline, which + // WildcardMatch also accepts), in order. The list may be the index's own: don't change it. + public List PositionsNamed(string type, string[] names) + { + List result = null; + bool merged = false; + foreach (string name in names) + { + foreach (List positions in new[] { PositionsNamed(type, name), PositionsNamed(type, name + "\n") }) + { + if (positions.Count == 0) continue; + if (result == null) + { + result = positions; + continue; + } + if (!merged) + { + result = new List(result); + merged = true; + } + result.AddRange(positions); + } + } + if (result == null) return new List(); + if (merged) + { + result.Sort(); + int count = 0; + for (int i = 0; i < result.Count; i++) + if (count == 0 || result[count - 1] != result[i]) result[count++] = result[i]; + result.RemoveRange(count, result.Count - count); + } + return result; + } + + // Whoever removes nodes of one type from the list can call this instead of Invalidate: + // the type's group drops the removed nodes and keeps its order + public void NodesRemoved(string type) + { + if (type == null) throw new ArgumentNullException(nameof(type)); + if (byType != null && !staleTypes.Contains(type) && byType.TryGetValue(type, out List> nodes)) + { + nodes.RemoveAll(node => node.List == null); + if (nodes.Count == 0) byType.Remove(type); + } + byName.Remove(type); + } + + public void NamesChanged(string type) + { + if (type == null) throw new ArgumentNullException(nameof(type)); + byName.Remove(type); + } + + public void Invalidate() + { + byType = null; + staleTypes.Clear(); + byName.Clear(); + } + + public void Invalidate(string type) + { + if (type == null) throw new ArgumentNullException(nameof(type)); + if (byType != null) staleTypes.Add(type); + byName.Remove(type); + } + + private void Rebuild(string type) + { + List> nodes = new List>(); + for (LinkedListNode listNode = configs.First; listNode != null; listNode = listNode.Next) + { + if (listNode.Value.Node.name == type) nodes.Add(listNode); + } + if (nodes.Count > 0) byType[type] = nodes; + else byType.Remove(type); + byName.Remove(type); + } + + private void Build() + { + byType = new Dictionary>>(); + byName.Clear(); + for (LinkedListNode listNode = configs.First; listNode != null; listNode = listNode.Next) + { + string type = listNode.Value.Node.name; + if (type == null) continue; + if (!byType.TryGetValue(type, out List> nodes)) + { + nodes = new List>(); + byType.Add(type, nodes); + } + nodes.Add(listNode); + } + } + } +} diff --git a/ModuleManager/Patches/CopyPatch.cs b/ModuleManager/Patches/CopyPatch.cs index 45ee09fe..dd8d504e 100644 --- a/ModuleManager/Patches/CopyPatch.cs +++ b/ModuleManager/Patches/CopyPatch.cs @@ -32,26 +32,99 @@ public void Apply(LinkedList databaseConfigs, IPatchProgress pr for (LinkedListNode listNode = databaseConfigs.First; listNode != null; listNode = listNode.Next) { - IProtoUrlConfig protoConfig = listNode.Value; + CopyFrom(ref listNode, databaseConfigs, context, progress); + } + } + + // Same as Apply, visiting only the nodes the index lists under the matcher's type, or + // with one of its names when they have no wildcard. The clones go right after their + // source, which Apply then skips too, so the nodes to visit are the ones listed before the + // patch. Root lookups in the patch (#$@PART[foo]/mass$) scan the list, which has the + // clones made so far. If a special command writes a name value in place, a node not + // reached yet may now match: from there on it visits every node of the type. + public void Apply(LinkedList databaseConfigs, PatchTypeIndex index, IPatchProgress progress, IBasicLogger logger) + { + if (index == null) throw new ArgumentNullException(nameof(index)); + if (!(NodeMatcher is NodeMatcher nodeMatcher)) + { try { - if (!NodeMatcher.IsMatch(protoConfig.Node)) continue; + Apply(databaseConfigs, progress, logger); + } + finally + { + index.Invalidate(); + } + return; + } + if (databaseConfigs == null) throw new ArgumentNullException(nameof(databaseConfigs)); + if (progress == null) throw new ArgumentNullException(nameof(progress)); + if (logger == null) throw new ArgumentNullException(nameof(logger)); - ConfigNode clone = MMPatchLoader.ModifyNode(new NodeStack(protoConfig.Node), UrlConfig.config, context); - if (protoConfig.Node.GetValue("name") is string name && name == clone.GetValue("name")) - { - progress.Error(UrlConfig, $"Error - when applying copy {UrlConfig.SafeUrl()} to {protoConfig.FullUrl} - the copy needs to have a different name than the parent (use @name = xxx)"); - } - else + string type = nodeMatcher.Type; + PatchContext context = new PatchContext(UrlConfig, databaseConfigs, logger, progress); + List> nodes = new List>(index.NodesOfType(type)); + int count = databaseConfigs.Count; + bool otherType = false; + try + { + int start = 0; + if (nodeMatcher.LiteralNames != null) + { + int writes = PatchTypeIndex.NameWrites; + List positions = new List(index.PositionsNamed(type, nodeMatcher.LiteralNames)); + start = nodes.Count; + for (int i = 0; i < positions.Count; i++) { - progress.ApplyingCopy(protoConfig, UrlConfig); - listNode = databaseConfigs.AddAfter(listNode, new ProtoUrlConfig(protoConfig.UrlFile, clone)); + int position = positions[i]; + otherType |= Visit(nodes[position], type, databaseConfigs, context, progress); + if (PatchTypeIndex.NameWrites != writes) + { + start = position + 1; + break; + } } } - catch (Exception ex) + + for (int i = start; i < nodes.Count; i++) + otherType |= Visit(nodes[i], type, databaseConfigs, context, progress); + } + finally + { + if (otherType) index.Invalidate(); + else if (databaseConfigs.Count != count) index.Invalidate(type); + } + } + + // Copies the node if it matches; tells whether the clone is of another type than the source + private bool Visit(LinkedListNode listNode, string type, LinkedList databaseConfigs, PatchContext context, IPatchProgress progress) + { + LinkedListNode source = listNode; + CopyFrom(ref listNode, databaseConfigs, context, progress); + return listNode != source && listNode.Value.Node.name != type; + } + + private void CopyFrom(ref LinkedListNode listNode, LinkedList databaseConfigs, PatchContext context, IPatchProgress progress) + { + IProtoUrlConfig protoConfig = listNode.Value; + try + { + if (!NodeMatcher.IsMatch(protoConfig)) return; + + ConfigNode clone = MMPatchLoader.ModifyNode(new NodeStack(protoConfig.Node), UrlConfig.config, context); + if (protoConfig.Node.GetValue("name") is string name && name == clone.GetValue("name")) { - progress.Exception(UrlConfig, $"Exception while applying copy {UrlConfig.SafeUrl()} to {protoConfig.FullUrl}", ex); + progress.Error(UrlConfig, $"Error - when applying copy {UrlConfig.SafeUrl()} to {protoConfig.FullUrl} - the copy needs to have a different name than the parent (use @name = xxx)"); } + else + { + progress.ApplyingCopy(protoConfig, UrlConfig); + listNode = databaseConfigs.AddAfter(listNode, new ProtoUrlConfig(protoConfig.UrlFile, clone)); + } + } + catch (Exception ex) + { + progress.Exception(UrlConfig, $"Exception while applying copy {UrlConfig.SafeUrl()} to {protoConfig.FullUrl}", ex); } } } diff --git a/ModuleManager/Patches/DeletePatch.cs b/ModuleManager/Patches/DeletePatch.cs index 46d46a94..b66476ca 100644 --- a/ModuleManager/Patches/DeletePatch.cs +++ b/ModuleManager/Patches/DeletePatch.cs @@ -34,7 +34,7 @@ public void Apply(LinkedList databaseConfigs, IPatchProgress pr try { LinkedListNode nextNode = currentNode.Next; - if (NodeMatcher.IsMatch(protoConfig.Node)) + if (NodeMatcher.IsMatch(protoConfig)) { progress.ApplyingDelete(protoConfig, UrlConfig); databaseConfigs.Remove(currentNode); @@ -47,5 +47,59 @@ public void Apply(LinkedList databaseConfigs, IPatchProgress pr } } } + + // Same as Apply, visiting only the nodes the index lists under the matcher's type, or + // with one of its names when they have no wildcard. Matching changes nothing, so the + // candidates stay the same while the patch runs; the index then drops the deleted nodes. + public void Apply(LinkedList databaseConfigs, PatchTypeIndex index, IPatchProgress progress, IBasicLogger logger) + { + if (index == null) throw new ArgumentNullException(nameof(index)); + if (!(NodeMatcher is NodeMatcher nodeMatcher)) + { + try + { + Apply(databaseConfigs, progress, logger); + } + finally + { + index.Invalidate(); + } + return; + } + if (databaseConfigs == null) throw new ArgumentNullException(nameof(databaseConfigs)); + if (progress == null) throw new ArgumentNullException(nameof(progress)); + if (logger == null) throw new ArgumentNullException(nameof(logger)); + + string type = nodeMatcher.Type; + List> nodes = index.NodesOfType(type); + List positions = nodeMatcher.LiteralNames != null ? index.PositionsNamed(type, nodeMatcher.LiteralNames) : null; + int count = positions?.Count ?? nodes.Count; + bool removed = false; + try + { + for (int i = 0; i < count; i++) + { + LinkedListNode listNode = nodes[positions == null ? i : positions[i]]; + IProtoUrlConfig protoConfig = listNode.Value; + try + { + if (NodeMatcher.IsMatch(protoConfig)) + { + progress.ApplyingDelete(protoConfig, UrlConfig); + databaseConfigs.Remove(listNode); + removed = true; + } + } + catch (Exception ex) + { + progress.Exception(UrlConfig, $"Exception while applying delete {UrlConfig.SafeUrl()} to {protoConfig.FullUrl}", ex); + } + } + } + finally + { + if (removed) index.NodesRemoved(type); + } + } } } diff --git a/ModuleManager/Patches/EditPatch.cs b/ModuleManager/Patches/EditPatch.cs index 91613879..5bc1ed6d 100644 --- a/ModuleManager/Patches/EditPatch.cs +++ b/ModuleManager/Patches/EditPatch.cs @@ -12,6 +12,13 @@ public class EditPatch : IPatch { private readonly bool loop; + // Whether edits may share the subnodes they leave alone with the node they replace (see + // MMPatchLoader.ModifyNodeSharingSubnodes): the patch has no special command and no paste + private readonly bool canShareSubnodes; + + // For tests: false makes every edit copy whole nodes + public static bool ShareSubnodes = true; + public UrlDir.UrlConfig UrlConfig { get; } public INodeMatcher NodeMatcher { get; } public IPassSpecifier PassSpecifier { get; } @@ -24,6 +31,21 @@ public EditPatch(UrlDir.UrlConfig urlConfig, INodeMatcher nodeMatcher, IPassSpec PassSpecifier = passSpecifier ?? throw new ArgumentNullException(nameof(passSpecifier)); loop = urlConfig.config.HasNode("MM_PATCH_LOOP"); + canShareSubnodes = !HasSpecialOrPaste(urlConfig.config); + } + + private static bool HasSpecialOrPaste(ConfigNode node) + { + for (int i = 0; i < node.values.Count; i++) + if (CommandParser.Parse(node.values[i].name, out _) == Command.Special) + return true; + for (int i = 0; i < node.nodes.Count; i++) + { + ConfigNode subnode = node.nodes[i]; + if (CommandParser.Parse(subnode.name, out _) == Command.Paste || HasSpecialOrPaste(subnode)) + return true; + } + return false; } public void Apply(LinkedList databaseConfigs, IPatchProgress progress, IBasicLogger logger) @@ -35,25 +57,119 @@ public void Apply(LinkedList databaseConfigs, IPatchProgress pr PatchContext context = new PatchContext(UrlConfig, databaseConfigs, logger, progress); for (LinkedListNode listNode = databaseConfigs.First; listNode != null; listNode = listNode.Next) { - IProtoUrlConfig protoConfig = listNode.Value; - try - { - if (!NodeMatcher.IsMatch(protoConfig.Node)) continue; - if (loop) logger.Info($"Looping on {UrlConfig.SafeUrl()} to {protoConfig.FullUrl}"); + ApplyTo(listNode, context, progress, logger); + } + } - do - { - progress.ApplyingUpdate(protoConfig, UrlConfig); - listNode.Value = protoConfig = new ProtoUrlConfig(protoConfig.UrlFile, MMPatchLoader.ModifyNode(new NodeStack(protoConfig.Node), UrlConfig.config, context)); - } while (loop && NodeMatcher.IsMatch(protoConfig.Node)); + // Same as Apply, visiting only the nodes the index lists under the matcher's type, which + // are the only ones it can match. An edit replaces each node's value in place and keeps + // its type, so the index stays valid; if a type does change, the index is invalidated, + // and if a name changes, the type's name lookup is. + // + // When the matcher's names have no wildcard, only nodes with one of those names (or one + // followed by a newline, which WildcardMatch also accepts) can match, and the index finds + // them by name. If a special command writes a name value in place while the patch runs, + // a node it has not reached yet may now match: from there on it visits every node again. + public void Apply(LinkedList databaseConfigs, PatchTypeIndex index, IPatchProgress progress, IBasicLogger logger) + { + if (index == null) throw new ArgumentNullException(nameof(index)); + if (!(NodeMatcher is NodeMatcher nodeMatcher)) + { + Apply(databaseConfigs, progress, logger); + index.Invalidate(); + return; + } + if (databaseConfigs == null) throw new ArgumentNullException(nameof(databaseConfigs)); + if (progress == null) throw new ArgumentNullException(nameof(progress)); + if (logger == null) throw new ArgumentNullException(nameof(logger)); - if (loop) protoConfig.Node.RemoveNodes("MM_PATCH_LOOP"); - } - catch (Exception ex) + string type = nodeMatcher.Type; + bool typeChanged = false; + // Lookups of root nodes (#$@PART[foo]/mass$) go through the index, which stays valid: + // ApplyTo updates it as soon as a node's name or type changes. + PatchContext context = new PatchContext(UrlConfig, databaseConfigs, logger, progress, index); + List> nodes = index.NodesOfType(type); + + int start = 0; + string[] literalNames = nodeMatcher.LiteralNames; + if (literalNames != null) + { + int writes = PatchTypeIndex.NameWrites; + List positions = index.PositionsNamed(type, literalNames); + start = nodes.Count; + for (int i = 0; i < positions.Count; i++) { - progress.Exception(UrlConfig, $"Exception while applying update {UrlConfig.SafeUrl()} to {protoConfig.FullUrl}", ex); + int position = positions[i]; + ApplyTo(nodes[position], type, index, context, progress, logger, ref typeChanged); + if (PatchTypeIndex.NameWrites != writes) + { + start = position + 1; + break; + } } } + + for (int i = start; i < nodes.Count; i++) + ApplyTo(nodes[i], type, index, context, progress, logger, ref typeChanged); + + if (typeChanged) index.Invalidate(); + } + + private void ApplyTo(LinkedListNode listNode, string type, PatchTypeIndex index, PatchContext context, IPatchProgress progress, IBasicLogger logger, ref bool typeChanged) + { + IProtoUrlConfig before = listNode.Value; + string nameBefore = PatchTypeIndex.NameOf(before); + ApplyTo(listNode, context, progress, logger, index, type); + IProtoUrlConfig after = listNode.Value; + if (after == before) return; + if (after.Node.name != type) + { + // The rest of this patch still visits the nodes it listed before + typeChanged = true; + index.Invalidate(); + } + else if (PatchTypeIndex.NameOf(after) != nameBefore) + { + index.NamesChanged(type); + } + } + + // With an index, a loop that renames the node updates the index after each pass, since + // the next pass's root lookups (#$@PART[foo]/mass$) read it + private void ApplyTo(LinkedListNode listNode, PatchContext context, IPatchProgress progress, IBasicLogger logger, PatchTypeIndex index = null, string type = null) + { + IProtoUrlConfig protoConfig = listNode.Value; + string name = index != null && loop ? PatchTypeIndex.NameOf(protoConfig) : null; + try + { + if (!NodeMatcher.IsMatch(protoConfig)) return; + if (loop) logger.Info($"Looping on {UrlConfig.SafeUrl()} to {protoConfig.FullUrl}"); + + do + { + progress.ApplyingUpdate(protoConfig, UrlConfig); + // The node replaced is not used again, so the new one can share its subnodes + ConfigNode newNode = canShareSubnodes && ShareSubnodes && !MMPatchLoader.NeedWholeCopies + ? MMPatchLoader.ModifyNodeSharingSubnodes(new NodeStack(protoConfig.Node), UrlConfig.config, context) + : MMPatchLoader.ModifyNode(new NodeStack(protoConfig.Node), UrlConfig.config, context); + listNode.Value = protoConfig = new ProtoUrlConfig(protoConfig.UrlFile, newNode); + if (index != null && loop) + { + string newName = PatchTypeIndex.NameOf(protoConfig); + if (newName != name) + { + index.NamesChanged(type); + name = newName; + } + } + } while (loop && NodeMatcher.IsMatch(protoConfig)); + + if (loop) protoConfig.Node.RemoveNodes("MM_PATCH_LOOP"); + } + catch (Exception ex) + { + progress.Exception(UrlConfig, $"Exception while applying update {UrlConfig.SafeUrl()} to {protoConfig.FullUrl}", ex); + } } } } diff --git a/ModuleManager/ProtoUrlConfig.cs b/ModuleManager/ProtoUrlConfig.cs index 71f39df3..e4e89aee 100644 --- a/ModuleManager/ProtoUrlConfig.cs +++ b/ModuleManager/ProtoUrlConfig.cs @@ -23,6 +23,13 @@ public class ProtoUrlConfig : IProtoUrlConfig public string NodeType => Node.name; public string FullUrl { get; } + // The node's name value, or null if it had none when this was created, so that NodeMatcher + // need not look it up again for every patch. Holds the Value object because a special + // command (*@PART[foo]/name = bar) writes to it in place. Edit and copy patches can add or + // remove name values, but they modify a copy and wrap it in a new ProtoUrlConfig. + private readonly ConfigNode.Value nameValue; + public string NameValue => nameValue?.value; + public ProtoUrlConfig(UrlDir.UrlFile urlFile, ConfigNode node) { UrlFile = urlFile ?? throw new ArgumentNullException(nameof(urlFile)); @@ -30,8 +37,17 @@ public ProtoUrlConfig(UrlDir.UrlFile urlFile, ConfigNode node) FileUrl = UrlFile.url + '.' + urlFile.fileExtension; FullUrl = FileUrl + '/' + Node.name; - if (node.GetValue("name") is string nameValue) - FullUrl += '[' + nameValue + ']'; + for (int i = 0; i < node.values.Count; ++i) + { + if (node.values[i].name == "name") + { + nameValue = node.values[i]; + break; + } + } + + if (NameValue != null) + FullUrl += '[' + NameValue + ']'; } } } diff --git a/ModuleManagerTests/CheckFilesChangeTest.cs b/ModuleManagerTests/CheckFilesChangeTest.cs new file mode 100644 index 00000000..65fb939d --- /dev/null +++ b/ModuleManagerTests/CheckFilesChangeTest.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; +using Xunit; +using NSubstitute; +using TestUtils; +using ModuleManager; +using ModuleManager.Extensions; +using ModuleManager.Logging; + +namespace ModuleManagerTests +{ + public class CheckFilesChangeTest + { + // What CheckFilesChange did before it indexed the FILE nodes: search them for every file + private static bool OldCheckFilesChange(UrlDir.UrlFile[] files, ConfigNode shaConfigNode, Dictionary filesSha, StringBuilder changes) + { + ConfigNode GetFileNode(string filename) + { + for (int i = 0; i < shaConfigNode.nodes.Count; i++) + { + ConfigNode file = shaConfigNode.nodes[i]; + if (file.name == "FILE" && file.GetValue("filename") == filename) + return file; + } + return null; + } + + bool noChange = true; + changes.Append("Changes :\n"); + for (int i = 0; i < files.Length; i++) + { + string url = files[i].GetUrlWithExtension(); + ConfigNode fileNode = GetFileNode(url); + string fileSha = fileNode?.GetValue("SHA"); + if (fileNode == null) + continue; + if (fileSha == null || filesSha[url] != fileSha) + { + changes.Append("Changed : " + fileNode.GetValue("filename") + ".cfg\n"); + noChange = false; + } + } + for (int i = 0; i < files.Length; i++) + { + string url = files[i].GetUrlWithExtension(); + ConfigNode fileNode = GetFileNode(url); + if (fileNode == null) + { + changes.Append("Added : " + url + "\n"); + noChange = false; + } + shaConfigNode.RemoveNode(fileNode); + } + foreach (ConfigNode fileNode in shaConfigNode.GetNodes()) + { + changes.Append("Deleted : " + fileNode.GetValue("filename") + "\n"); + noChange = false; + } + return noChange; + } + + private static ConfigNode File(string filename, string sha) + { + ConfigNode node = new ConfigNode("FILE"); + if (filename != null) node.AddValue("filename", filename); + if (sha != null) node.AddValue("SHA", sha); + return node; + } + + private static ConfigNode MakeShaNode(bool withChanges) + { + ConfigNode node = new ConfigNode("FilesSHA"); + node.AddNode(File("abc/a.cfg", "A")); + node.AddNode(File("abc/b.cfg", withChanges ? "B-old" : "B")); + node.AddNode(File("abc/c.cfg", "C")); + if (withChanges) + { + node.AddNode(File("abc/gone.cfg", "G")); + node.AddNode(File("abc/a.cfg", "A-dup")); + node.AddNode(File("abc/c.cfg", null)); + node.AddNode(File(null, "nameless")); + node.AddNode(new ConfigNode("NOT_A_FILE")); + } + return node; + } + + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(true, true)] + public void TestCheckFilesChange(bool withChanges, bool duplicateFile) + { + UrlDir gameData = UrlBuilder.CreateGameData(); + List fileList = new List + { + UrlBuilder.CreateFile("abc/a.cfg", gameData), + UrlBuilder.CreateFile("abc/b.cfg", gameData), + UrlBuilder.CreateFile("abc/c.cfg", gameData), + }; + if (withChanges) fileList.Add(UrlBuilder.CreateFile("abc/new.cfg", gameData)); + if (duplicateFile) fileList.Add(fileList[0]); + UrlDir.UrlFile[] files = fileList.ToArray(); + + Dictionary filesSha = new Dictionary + { + { "abc/a.cfg", "A" }, { "abc/b.cfg", "B" }, { "abc/c.cfg", "C" }, { "abc/new.cfg", "N" }, + }; + + StringBuilder expectedChanges = new StringBuilder(); + bool expected = OldCheckFilesChange(files, MakeShaNode(withChanges), filesSha, expectedChanges); + + IBasicLogger logger = Substitute.For(); + MMPatchLoader loader = new MMPatchLoader(new ModListGenerator.ModAddedByAssembly[0], logger); + Dictionary loaderFilesSha = (Dictionary)typeof(MMPatchLoader) + .GetField("filesSha", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(loader); + foreach (KeyValuePair pair in filesSha) loaderFilesSha.Add(pair.Key, pair.Value); + MethodInfo checkFilesChange = typeof(MMPatchLoader).GetMethod("CheckFilesChange", BindingFlags.NonPublic | BindingFlags.Instance); + + bool result = (bool)checkFilesChange.Invoke(loader, new object[] { files, MakeShaNode(withChanges) }); + + Assert.Equal(expected, result); + Assert.Equal(!withChanges, result); + if (expected) + logger.AssertNoInfo(); + else + logger.AssertInfo(expectedChanges.ToString()); + } + } +} diff --git a/ModuleManagerTests/ConfigFileHasherTest.cs b/ModuleManagerTests/ConfigFileHasherTest.cs new file mode 100644 index 00000000..6ac0ec06 --- /dev/null +++ b/ModuleManagerTests/ConfigFileHasherTest.cs @@ -0,0 +1,97 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using Xunit; +using ModuleManager; + +namespace ModuleManagerTests +{ + public class ConfigFileHasherTest : IDisposable + { + private readonly string dir = Path.Combine(Path.GetTempPath(), "ConfigFileHasherTest-" + Guid.NewGuid().ToString("N")); + + public ConfigFileHasherTest() + { + Directory.CreateDirectory(dir); + } + + public void Dispose() + { + Directory.Delete(dir, true); + } + + [Fact] + public void TestWaitForHash() + { + string[] paths = new string[200]; + for (int i = 0; i < paths.Length; i++) + { + paths[i] = Path.Combine(dir, i + ".cfg"); + File.WriteAllText(paths[i], new string('x', i * 37) + i); + } + + using SHA256 sha = SHA256.Create(); + using (ConfigFileHasher hasher = new ConfigFileHasher(paths)) + { + for (int i = 0; i < paths.Length; i++) + { + Assert.Equal(BitConverter.ToString(sha.ComputeHash(File.ReadAllBytes(paths[i]))), hasher.WaitForHash(i)); + } + } + } + + [Fact] + public void TestWaitForHash__Missing() + { + string[] paths = { Path.Combine(dir, "a.cfg"), Path.Combine(dir, "missing.cfg"), Path.Combine(dir, "b.cfg") }; + File.WriteAllText(paths[0], "a"); + File.WriteAllText(paths[2], "b"); + + using ConfigFileHasher hasher = new ConfigFileHasher(paths); + Assert.Equal(Hash("a"), hasher.WaitForHash(0)); + Assert.Throws(() => hasher.WaitForHash(1)); + } + + [Fact] + public void TestReadAhead() + { + // The workers stop a bounded number of files ahead of the caller, and Dispose wakes + // them while they wait + string[] paths = new string[300]; + for (int i = 0; i < paths.Length; i++) + { + paths[i] = Path.Combine(dir, i + ".cfg"); + File.WriteAllText(paths[i], i.ToString()); + } + + using (ConfigFileHasher hasher = new ConfigFileHasher(paths)) + { + System.Threading.Thread.Sleep(300); + Assert.InRange(hasher.ReadCount, 1, 65); + for (int i = 0; i < 100; i++) + Assert.Equal(Hash(i.ToString()), hasher.WaitForHash(i)); + System.Threading.Thread.Sleep(300); + Assert.InRange(hasher.ReadCount, 100, 165); + } + + using (ConfigFileHasher hasher = new ConfigFileHasher(paths)) + { + for (int i = 0; i < paths.Length; i++) + Assert.Equal(Hash(i.ToString()), hasher.WaitForHash(i)); + } + } + + private static string Hash(string text) + { + using SHA256 sha = SHA256.Create(); + return BitConverter.ToString(sha.ComputeHash(Encoding.UTF8.GetBytes(text))); + } + + [Fact] + public void TestWaitForHash__Empty() + { + using ConfigFileHasher hasher = new ConfigFileHasher(new string[0]); + } + } +} diff --git a/ModuleManagerTests/ConfigNodeWriterTest.cs b/ModuleManagerTests/ConfigNodeWriterTest.cs new file mode 100644 index 00000000..99b9bd00 --- /dev/null +++ b/ModuleManagerTests/ConfigNodeWriterTest.cs @@ -0,0 +1,135 @@ +using System; +using System.IO; +using Xunit; +using TestUtils; +using ModuleManager; + +namespace ModuleManagerTests +{ + public class ConfigNodeWriterTest : IDisposable + { + private readonly string dir = Path.Combine(Path.GetTempPath(), "ConfigNodeWriterTest-" + Guid.NewGuid().ToString("N")); + + public ConfigNodeWriterTest() + { + Directory.CreateDirectory(dir); + } + + public void Dispose() + { + Directory.Delete(dir, true); + } + + [Fact] + public void TestSave__SameAsConfigNodeSave() + { + ConfigNode node = new TestConfigNode("ROOT") + { + { "patchedNodeCount", "12" }, + { "unicode", "café 中文 \U0001F680" }, + { "empty", "" }, + new TestConfigNode("UrlConfig") + { + { "parentUrl", "abc/def.cfg" }, + new TestConfigNode("PART") + { + { "name", "foo" }, + { "escaped", "a\\nb\\tc" }, + new TestConfigNode("MODULE") + { + { "name", "ModuleThing" }, + new TestConfigNode("EMPTY"), + }, + }, + }, + new TestConfigNode("UrlConfig"), + }; + node.values[0].comment = "a comment"; + node.nodes[0].comment = "node comment"; + node.nodes[0].nodes[0].values[1].comment = ""; + + string expectedPath = Path.Combine(dir, "expected.cfg"); + string actualPath = Path.Combine(dir, "actual.cfg"); + node.Save(expectedPath); + File.WriteAllText(actualPath, "something longer that must be overwritten, something longer that must be overwritten"); + ConfigNodeWriter.Save(node, actualPath); + + Assert.Equal(File.ReadAllBytes(expectedPath), File.ReadAllBytes(actualPath)); + } + + [Fact] + public void TestSaveCache__SameAsCopyEscapeAndSave() + { + // Nodes as patches can leave them: values with braces, = in names, newlines and tabs, + // which adding them to a ConfigNode would have sanitized; names the ConfigNode(string) + // constructor cleans up; comments + ConfigNode part = new TestConfigNode("PART") + { + { "name", "foo" }, + { "braces", "x" }, + { "eq", "y" }, + { "escaped", "z" }, + { "plain", "café" }, + new TestConfigNode("MODULE") + { + { "name", "ModuleThing" }, + new TestConfigNode("EMPTY"), + }, + new TestConfigNode("X"), + new TestConfigNode("Y"), + new TestConfigNode("Z"), + }; + part.values[1].value = "a{b}c"; + part.values[2].name = "k=e{y}"; + part.values[2].value = "v=1"; + part.values[3].value = "line1\nline2\r\tend\\n"; + part.values[4].comment = "comment"; + part.comment = "node comment"; + part.nodes[1].name = "SPLIT (id)"; + part.nodes[2].name = "TAB\tBED"; + part.nodes[3].name = "NEW\nLINE"; + ConfigNode other = new TestConfigNode("RESOURCE_DEFINITION") { { "name", "LiquidFuel" } }; + + ConfigNode[] roots = { part, other }; + string[] urls = { "abc/def.cfg", "ghi/jkl.cfg" }; + + ConfigNode expected = new ConfigNode(); + expected.AddValue("patchedNodeCount", "2"); + ConfigNode actual = new ConfigNode(); + actual.AddValue("patchedNodeCount", "2"); + for (int i = 0; i < roots.Length; i++) + { + ConfigNode expectedUrl = expected.AddNode("UrlConfig"); + expectedUrl.AddValue("parentUrl", urls[i]); + ConfigNode copy = ModuleManager.Extensions.ConfigNodeExtensions.DeepCopy(roots[i]); + ModuleManager.Extensions.ConfigNodeExtensions.EscapeValuesRecursive(copy); + expectedUrl.AddNode(copy); + + ConfigNode actualUrl = actual.AddNode("UrlConfig"); + actualUrl.AddValue("parentUrl", urls[i]); + actualUrl.AddNode(roots[i]); + } + + string expectedPath = Path.Combine(dir, "expected.cfg"); + string actualPath = Path.Combine(dir, "actual.cfg"); + ConfigNodeWriter.Save(expected, expectedPath); + ConfigNodeWriter.SaveCache(actual, actualPath); + + Assert.Equal(File.ReadAllText(expectedPath), File.ReadAllText(actualPath)); + Assert.Equal(File.ReadAllBytes(expectedPath), File.ReadAllBytes(actualPath)); + Assert.Equal("a{b}c", part.values[1].value); + Assert.Contains("SPLIT", File.ReadAllText(actualPath)); + } + + [Fact] + public void TestSave__Empty() + { + string expectedPath = Path.Combine(dir, "expected.cfg"); + string actualPath = Path.Combine(dir, "actual.cfg"); + new ConfigNode().Save(expectedPath); + ConfigNodeWriter.Save(new ConfigNode(), actualPath); + + Assert.Equal(File.ReadAllBytes(expectedPath), File.ReadAllBytes(actualPath)); + } + } +} diff --git a/ModuleManagerTests/Extensions/ConfigNodeExtensionsTest.cs b/ModuleManagerTests/Extensions/ConfigNodeExtensionsTest.cs index 471be9cb..77c3748e 100644 --- a/ModuleManagerTests/Extensions/ConfigNodeExtensionsTest.cs +++ b/ModuleManagerTests/Extensions/ConfigNodeExtensionsTest.cs @@ -79,6 +79,45 @@ public void TestShallowCopyFrom() Assert.Empty(innerNode2.nodes[0].nodes); } + [Theory] + [InlineData("PART")] + [InlineData("")] + [InlineData("@PART[foo]:HAS[#bar]")] + [InlineData("NODE (id)")] + [InlineData("NODE id")] + [InlineData("(NODE) (id)")] + [InlineData("NODE\tWITH TAB")] + [InlineData("NODE\r\nNEWLINE")] + [InlineData(" NODE ")] + public void TestDeepCopy__NameCleanup(string name) + { + // Names keep what the ConfigNode(string) constructor makes of them + ConfigNode fromNode = new ConfigNode() { name = name }; + fromNode.AddNode(new ConfigNode() { name = name }); + ConfigNode expected = new ConfigNode(name); + + ConfigNode toNode = fromNode.DeepCopy(); + + Assert.Equal(expected.name, toNode.name); + Assert.Equal(expected.id, toNode.id); + Assert.Equal(expected.name, toNode.nodes[0].name); + Assert.Equal(expected.id, toNode.nodes[0].id); + } + + [Fact] + public void TestDeepCopy__SanitizesValues() + { + // A value written in place can hold braces; the copy sanitizes it as AddValue does + ConfigNode fromNode = new ConfigNode("NODE"); + fromNode.AddValue("abc", "def"); + fromNode.values[0].value = "{x}"; + fromNode.values[0].name = "a=b{c}"; + + ConfigNode toNode = fromNode.DeepCopy(); + + AssertValue("a-b[c]", "[x]", toNode.values[0]); + } + [Fact] public void TestDeepCopy() { diff --git a/ModuleManagerTests/MMPatchLoaderTest.cs b/ModuleManagerTests/MMPatchLoaderTest.cs index b0617fe8..bf78775f 100644 --- a/ModuleManagerTests/MMPatchLoaderTest.cs +++ b/ModuleManagerTests/MMPatchLoaderTest.cs @@ -149,6 +149,62 @@ public void TestModifyNode__ReplaceNode__SpecialCharacters() }, c3); } + [Theory] + [InlineData("@MOD,*", null, "")] + [InlineData("@MOD[b*],*", "b*", "")] + [InlineData("@MOD[nope],*", "nope", "")] + [InlineData("@MOD:HAS[#x[1]]", null, "#x[1]")] + [InlineData("@MOD[b*]:HAS[#x[1]]", "b*", "#x[1]")] + [InlineData("@MOD,{0}:HAS[#x[1]]", null, "#x[1]")] + [InlineData("@MOD,{0}:HAS[#x]", null, "#x")] + [InlineData("@MOD[b*],{0}:HAS[#x]", "b*", "#x")] + [InlineData("@MOD[b*],{0}:HAS[~x[]]", "b*", "~x[]")] + public void TestModifyNode__EditSubnodesFromIndex(string subName, string nodeName, string constraints) + { + ConfigNode Make() => new TestConfigNode("NODE") + { + new TestConfigNode("MOD") { { "name", "a1" }, { "x", "1" } }, + new TestConfigNode("OTHER") { { "name", "b0" }, { "x", "1" } }, + new TestConfigNode("MOD") { { "name", "b1" } }, + new TestConfigNode("MOD") { { "name", "b2" }, { "x", "1" } }, + new TestConfigNode("MOD") { { "name", "a2" }, { "x", "2" } }, + new TestConfigNode("MOD") { { "name", "b3" }, { "x", "1" } }, + }; + + for (int index = -7; index <= 7; index++) + { + // The nodes the old loop over FindConfigNodeIn picked + ConfigNode c1 = Make(); + bool[] expected = new bool[c1.nodes.Count]; + int i = subName.Contains("{0}") ? index : 0; + ConfigNode n, last = null; + while (true) + { + n = MMPatchLoader.FindConfigNodeIn(c1, "MOD", nodeName, i++); + if (n == last || n == null) + break; + if (MMPatchLoader.CheckConstraints(n, constraints)) + { + for (int j = 0; j < c1.nodes.Count; j++) + if (c1.nodes[j] == n) expected[j] = true; + } + last = n; + } + + UrlDir.UrlConfig c2u = UrlBuilder.CreateConfig("abc/def", new TestConfigNode("@NODE") + { + new TestConfigNode(string.Format(subName, index)) { { "marked", "true" } }, + }); + PatchContext context = new PatchContext(c2u, Enumerable.Empty(), logger, progress); + + ConfigNode c3 = MMPatchLoader.ModifyNode(new NodeStack(c1), c2u.config, context); + + for (int j = 0; j < expected.Length; j++) + Assert.True(expected[j] == c3.nodes[j].HasValue("marked"), $"{subName} index {index}: node {j}"); + } + EnsureNoErrors(); + } + private void AssertConfigNodesEqual(ConfigNode expected, ConfigNode observed) { Assert.Equal(expected.ToString(), observed.ToString()); diff --git a/ModuleManagerTests/ModuleManagerTests.csproj b/ModuleManagerTests/ModuleManagerTests.csproj index f3afbbf5..357c0cb1 100644 --- a/ModuleManagerTests/ModuleManagerTests.csproj +++ b/ModuleManagerTests/ModuleManagerTests.csproj @@ -83,7 +83,11 @@ + + + + @@ -108,6 +112,8 @@ + + diff --git a/ModuleManagerTests/NeedsCheckerTest.cs b/ModuleManagerTests/NeedsCheckerTest.cs index 4d3540b9..180b00a2 100644 --- a/ModuleManagerTests/NeedsCheckerTest.cs +++ b/ModuleManagerTests/NeedsCheckerTest.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using Xunit; using NSubstitute; using TestUtils; @@ -181,6 +182,16 @@ public void TestCheckNeeds() Assert.False(needsChecker.CheckNeeds("ghi/jkl")); } + [Fact] + public void TestCheckNeeds__NonAscii() + { + // Every answer is the culture comparer's, as with a linear search + string[] mods = { "mod1", "Ünïcode", "straße", "Dž" }; + NeedsChecker checker = new NeedsChecker(mods, gameData, progress, logger); + foreach (string mod in new[] { "mod1", "MOD1", "ünïcode", "ÜNÏCODE", "STRASSE", "strasse", "straße", "DŽ", "dž", "x", "Unicode" }) + Assert.Equal(mods.Contains(mod, StringComparer.InvariantCultureIgnoreCase), checker.CheckNeeds(mod)); + } + [Fact] public void TestCheckNeeds__Null() { diff --git a/ModuleManagerTests/NodeMatcherTest.cs b/ModuleManagerTests/NodeMatcherTest.cs index 866c69fc..49e60d67 100644 --- a/ModuleManagerTests/NodeMatcherTest.cs +++ b/ModuleManagerTests/NodeMatcherTest.cs @@ -1,5 +1,6 @@ using System; using Xunit; +using NSubstitute; using TestUtils; using ModuleManager; @@ -329,5 +330,54 @@ public void TestIsMatch__Constraints_Open() } #endregion + + [Fact] + public void TestIsMatch__ProtoUrlConfig() + { + NodeMatcher matcher = new NodeMatcher("NODE", "blah", null); + UrlDir.UrlFile file = UrlBuilder.CreateFile("abc/def.cfg"); + + Assert.True(matcher.IsMatch(new ProtoUrlConfig(file, new TestConfigNode("NODE") { { "name", "blah" } }))); + Assert.False(matcher.IsMatch(new ProtoUrlConfig(file, new TestConfigNode("NODE") { { "name", "bleh" } }))); + Assert.False(matcher.IsMatch(new ProtoUrlConfig(file, new ConfigNode("NODE")))); + Assert.False(matcher.IsMatch(new ProtoUrlConfig(file, new TestConfigNode("PART") { { "name", "blah" } }))); + } + + [Fact] + public void TestIsMatch__ProtoUrlConfig__NameChangedInPlace() + { + NodeMatcher matcher = new NodeMatcher("NODE", "blah", null); + ConfigNode node = new TestConfigNode("NODE") { { "name", "bleh" } }; + ProtoUrlConfig protoConfig = new ProtoUrlConfig(UrlBuilder.CreateFile("abc/def.cfg"), node); + + Assert.False(matcher.IsMatch(protoConfig)); + + node.SetValue("name", "blah"); + + Assert.True(matcher.IsMatch(protoConfig)); + Assert.True(matcher.IsMatch(node)); + } + + [Fact] + public void TestIsMatch__ProtoUrlConfig__Constraints() + { + NodeMatcher matcher = new NodeMatcher("NODE", null, "@INNER"); + UrlDir.UrlFile file = UrlBuilder.CreateFile("abc/def.cfg"); + + Assert.True(matcher.IsMatch(new ProtoUrlConfig(file, new TestConfigNode("NODE") { new ConfigNode("INNER") }))); + Assert.False(matcher.IsMatch(new ProtoUrlConfig(file, new ConfigNode("NODE")))); + } + + [Fact] + public void TestIsMatch__Extension__OtherMatcher() + { + INodeMatcher matcher = NSubstitute.Substitute.For(); + ConfigNode node = new ConfigNode("NODE"); + IProtoUrlConfig protoConfig = NSubstitute.Substitute.For(); + protoConfig.Node.Returns(node); + matcher.IsMatch(node).Returns(true); + + Assert.True(NodeMatcherExtensions.IsMatch(matcher, protoConfig)); + } } } diff --git a/ModuleManagerTests/PatchApplierRenameTest.cs b/ModuleManagerTests/PatchApplierRenameTest.cs new file mode 100644 index 00000000..5471410d --- /dev/null +++ b/ModuleManagerTests/PatchApplierRenameTest.cs @@ -0,0 +1,90 @@ +using System.Linq; +using Xunit; +using NSubstitute; +using TestUtils; +using ModuleManager; +using ModuleManager.Collections; +using ModuleManager.Logging; +using ModuleManager.Patches; +using ModuleManager.Patches.PassSpecifiers; +using ModuleManager.Progress; + +namespace ModuleManagerTests +{ + public class PatchApplierRenameTest + { + [Fact] + public void TestApplyPatches__Rename() + { + // Patches that change a node's name value are matched by its new name afterward, + // through the name value each new ProtoUrlConfig stores. + IPatchProgress progress = Substitute.For(); + PatchApplier patchApplier = new PatchApplier(progress, Substitute.For()); + IPassSpecifier passSpecifier = Substitute.For(); + + IPatch Insert(string name) => new InsertPatch( + UrlBuilder.CreateConfig("abc/" + name, new TestConfigNode("PART") { { "name", name } }), "PART", passSpecifier); + IPatch Edit(string url, string name, string key, string value) => new EditPatch( + UrlBuilder.CreateConfig(url, new TestConfigNode("@PART[" + name + "]") { { key, value } }), new NodeMatcher("PART", name, null), passSpecifier); + + IPass pass1 = Substitute.For(); + pass1.GetEnumerator().Returns(new ArrayEnumerator(Insert("a"), Insert("other"))); + + IPass pass2 = Substitute.For(); + pass2.GetEnumerator().Returns(new ArrayEnumerator( + Edit("ghi/e1", "a", "@name", "b"), + Edit("ghi/e2", "b", "x", "1"), + Edit("ghi/e3", "a", "y", "2"), + new CopyPatch(UrlBuilder.CreateConfig("ghi/c1", new TestConfigNode("+PART[b]") { { "@name", "c" } }), new NodeMatcher("PART", "b", null), passSpecifier), + Edit("ghi/e4", "c", "z", "3"), + Edit("ghi/e5", "b", "w", "4"), + new DeletePatch(UrlBuilder.CreateConfig("ghi/d1", new ConfigNode("!PART[other]")), new NodeMatcher("PART", "other", null), passSpecifier) + )); + + IProtoUrlConfig[] configs = patchApplier.ApplyPatches(new[] { pass1, pass2 }).ToArray(); + + progress.DidNotReceiveWithAnyArgs().Error(null, null); + progress.DidNotReceiveWithAnyArgs().Exception(null, null); + progress.DidNotReceiveWithAnyArgs().Exception(null, null, null); + + Assert.Equal(2, configs.Length); + Assert.Equal(new TestConfigNode("PART") { { "name", "b" }, { "x", "1" }, { "w", "4" } }.ToString(), configs[0].Node.ToString()); + Assert.Equal(new TestConfigNode("PART") { { "name", "c" }, { "x", "1" }, { "z", "3" } }.ToString(), configs[1].Node.ToString()); + } + + [Fact] + public void TestApplyPatches__Rename__SpecialCommand() + { + // A special command writes to another root node's name value in place, with no new + // ProtoUrlConfig, and patches match that node by its new name afterward. + IPatchProgress progress = Substitute.For(); + PatchApplier patchApplier = new PatchApplier(progress, Substitute.For()); + IPassSpecifier passSpecifier = Substitute.For(); + + IPatch Insert(string name) => new InsertPatch( + UrlBuilder.CreateConfig("abc/" + name, new TestConfigNode("PART") { { "name", name } }), "PART", passSpecifier); + IPatch Edit(string url, string name, string key, string value) => new EditPatch( + UrlBuilder.CreateConfig(url, new TestConfigNode("@PART[" + name + "]") { { key, value } }), new NodeMatcher("PART", name, null), passSpecifier); + + IPass pass1 = Substitute.For(); + pass1.GetEnumerator().Returns(new ArrayEnumerator(Insert("source"), Insert("target"))); + + IPass pass2 = Substitute.For(); + pass2.GetEnumerator().Returns(new ArrayEnumerator( + Edit("ghi/e1", "source", "*@PART[target]/name", "renamed"), + Edit("ghi/e2", "renamed", "x", "1"), + Edit("ghi/e3", "target", "y", "2") + )); + + IProtoUrlConfig[] configs = patchApplier.ApplyPatches(new[] { pass1, pass2 }).ToArray(); + + progress.DidNotReceiveWithAnyArgs().Error(null, null); + progress.DidNotReceiveWithAnyArgs().Exception(null, null); + progress.DidNotReceiveWithAnyArgs().Exception(null, null, null); + + Assert.Equal(2, configs.Length); + Assert.Equal(new TestConfigNode("PART") { { "name", "source" } }.ToString(), configs[0].Node.ToString()); + Assert.Equal(new TestConfigNode("PART") { { "name", "renamed" }, { "x", "1" } }.ToString(), configs[1].Node.ToString()); + } + } +} diff --git a/ModuleManagerTests/PatchApplierTest.cs b/ModuleManagerTests/PatchApplierTest.cs index d54ac286..af8d2a30 100644 --- a/ModuleManagerTests/PatchApplierTest.cs +++ b/ModuleManagerTests/PatchApplierTest.cs @@ -1,12 +1,15 @@ using System; using System.Collections.Generic; +using System.Linq; using Xunit; using NSubstitute; using UnityEngine; +using TestUtils; using ModuleManager; using ModuleManager.Collections; using ModuleManager.Logging; using ModuleManager.Patches; +using ModuleManager.Patches.PassSpecifiers; using ModuleManager.Progress; namespace ModuleManagerTests @@ -115,5 +118,406 @@ public void TestApplyPatches() progress.PatchApplied(); }); } + + [Fact] + public void TestApplyPatches__TypeIndex() + { + // Edit patches visit nodes through a per-type index; copies, deletes, and inserts + // between them must be seen by the edits that follow. + IBasicLogger logger = Substitute.For(); + IPatchProgress progress = Substitute.For(); + PatchApplier patchApplier = new PatchApplier(progress, logger); + IPassSpecifier passSpecifier = Substitute.For(); + + IPatch Insert(string type, string name) => new InsertPatch( + UrlBuilder.CreateConfig("abc/" + name, new TestConfigNode(type) { { "name", name } }), type, passSpecifier); + UrlDir.UrlConfig Config(string url, ConfigNode node) => UrlBuilder.CreateConfig(url, node); + + IPass pass1 = Substitute.For(); + pass1.GetEnumerator().Returns(new ArrayEnumerator( + Insert("PART", "a"), + Insert("PROP", "p"), + Insert("PART", "b") + )); + + IPass pass2 = Substitute.For(); + pass2.GetEnumerator().Returns(new ArrayEnumerator( + new EditPatch(Config("ghi/e1", new TestConfigNode("@PART[*]") { { "x", "1" } }), new NodeMatcher("PART", "*", null), passSpecifier), + new CopyPatch(Config("ghi/c1", new TestConfigNode("+PART[a]") { { "@name", "c" } }), new NodeMatcher("PART", "a", null), passSpecifier), + new EditPatch(Config("ghi/e2", new TestConfigNode("@PART[*]") { { "y", "2" } }), new NodeMatcher("PART", "*", null), passSpecifier), + new DeletePatch(Config("ghi/d1", new ConfigNode("!PART[b]")), new NodeMatcher("PART", "b", null), passSpecifier), + new EditPatch(Config("ghi/e3", new TestConfigNode("@PART[*]") { { "z", "3" } }), new NodeMatcher("PART", "*", null), passSpecifier), + Insert("PART", "d"), + new EditPatch(Config("ghi/e4", new TestConfigNode("@PART[d]") { { "w", "4" } }), new NodeMatcher("PART", "d", null), passSpecifier) + )); + + IProtoUrlConfig[] configs = patchApplier.ApplyPatches(new[] { pass1, pass2 }).ToArray(); + + progress.DidNotReceiveWithAnyArgs().Error(null, null); + progress.DidNotReceiveWithAnyArgs().Exception(null, null); + progress.DidNotReceiveWithAnyArgs().Exception(null, null, null); + + Assert.Equal(new[] { "PART", "PART", "PROP", "PART" }, configs.Select(c => c.Node.name)); + AssertNodesEqual(new TestConfigNode("PART") { { "name", "a" }, { "x", "1" }, { "y", "2" }, { "z", "3" } }, configs[0].Node); + AssertNodesEqual(new TestConfigNode("PART") { { "name", "c" }, { "x", "1" }, { "y", "2" }, { "z", "3" } }, configs[1].Node); + AssertNodesEqual(new TestConfigNode("PROP") { { "name", "p" } }, configs[2].Node); + AssertNodesEqual(new TestConfigNode("PART") { { "name", "d" }, { "w", "4" } }, configs[3].Node); + } + + [Fact] + public void TestApplyPatches__NameIndex() + { + // Edits whose names have no wildcard find nodes by name; renames by edits and by + // special commands must be seen by the patches that follow, and by the same patch. + IBasicLogger logger = Substitute.For(); + IPatchProgress progress = Substitute.For(); + PatchApplier patchApplier = new PatchApplier(progress, logger); + IPassSpecifier passSpecifier = Substitute.For(); + + IPatch Insert(string type, string name) => new InsertPatch( + UrlBuilder.CreateConfig("abc/" + name, new TestConfigNode(type) { { "name", name } }), type, passSpecifier); + IPatch Edit(string url, string name, ConfigNode node) => new EditPatch(UrlBuilder.CreateConfig(url, node), new NodeMatcher("PART", name, null), passSpecifier); + + IPass pass1 = Substitute.For(); + pass1.GetEnumerator().Returns(new ArrayEnumerator( + Insert("PART", "a"), + Insert("PART", "b"), + Insert("PART", "c"), + Insert("PART", "r") + )); + + IPass pass2 = Substitute.For(); + pass2.GetEnumerator().Returns(new ArrayEnumerator( + Edit("ghi/e1", "a", new TestConfigNode("@PART[a]") { { "x", "1" } }), + // rename b to a: the next edit of a sees both + Edit("ghi/e2", "b", new TestConfigNode("@PART[b]") { { "@name", "a" } }), + Edit("ghi/e3", "a", new TestConfigNode("@PART[a]") { { "y", "2" } }), + Edit("ghi/e4", "a,c", new TestConfigNode("@PART[a,c]") { { "z", "3" } }), + // renames r to w in place while it runs: then w matches too, after c + Edit("ghi/e5", "c|w", new TestConfigNode("@PART[c|w]") { { "*@PART[r]/name", "w" }, { "w", "4" } }), + Edit("ghi/e6", "w", new TestConfigNode("@PART[w]") { { "v", "5" } }), + Edit("ghi/e7", "r", new TestConfigNode("@PART[r]") { { "u", "6" } }) + )); + + IProtoUrlConfig[] configs = patchApplier.ApplyPatches(new[] { pass1, pass2 }).ToArray(); + + // e5 on w cannot find PART[r] any more + progress.ReceivedWithAnyArgs(1).Error(null, null); + progress.DidNotReceiveWithAnyArgs().Exception(null, null); + progress.DidNotReceiveWithAnyArgs().Exception(null, null, null); + + Assert.Equal(4, configs.Length); + AssertNodesEqual(new TestConfigNode("PART") { { "name", "a" }, { "x", "1" }, { "y", "2" }, { "z", "3" } }, configs[0].Node); + AssertNodesEqual(new TestConfigNode("PART") { { "name", "a" }, { "y", "2" }, { "z", "3" } }, configs[1].Node); + AssertNodesEqual(new TestConfigNode("PART") { { "name", "c" }, { "z", "3" }, { "w", "4" } }, configs[2].Node); + AssertNodesEqual(new TestConfigNode("PART") { { "name", "w" }, { "w", "4" }, { "v", "5" } }, configs[3].Node); + } + + [Fact] + public void TestApplyPatches__RootLookups() + { + // #$@TYPE[name]/key$ finds the first root node of that type and name, in list order, + // as the database stands when the value is read, renames included + IBasicLogger logger = Substitute.For(); + IPatchProgress progress = Substitute.For(); + PatchApplier patchApplier = new PatchApplier(progress, logger); + IPassSpecifier passSpecifier = Substitute.For(); + + IPatch Insert(string name, string x) => new InsertPatch( + UrlBuilder.CreateConfig("abc/" + name, new TestConfigNode("PART") { { "name", name }, { "x", x } }), "PART", passSpecifier); + IPatch Edit(string url, string name, ConfigNode node) => new EditPatch(UrlBuilder.CreateConfig(url, node), new NodeMatcher("PART", name, null), passSpecifier); + + IPass pass1 = Substitute.For(); + pass1.GetEnumerator().Returns(new ArrayEnumerator( + Insert("a", "1"), + Insert("b", "2"), + Insert("c", "3") + )); + + IPass pass2 = Substitute.For(); + pass2.GetEnumerator().Returns(new ArrayEnumerator( + Edit("ghi/e1", "c", new TestConfigNode("@PART[c]") { { "fromB", "#$@PART[b]/x$" }, { "fromAny", "#$@PART[?]/x$" } }), + // a is renamed b while the patch runs: c, after it, reads the renamed node + Edit("ghi/e2", "a|c", new TestConfigNode("@PART[a|c]") { { "@name", "b" }, { "fromB2", "#$@PART[b]/x$" } }), + Edit("ghi/e3", "b", new TestConfigNode("@PART[b]") { { "fromB3", "#$@PART[b*]/x$" } }) + )); + + IProtoUrlConfig[] configs = patchApplier.ApplyPatches(new[] { pass1, pass2 }).ToArray(); + + progress.DidNotReceiveWithAnyArgs().Error(null, null); + progress.DidNotReceiveWithAnyArgs().Exception(null, null); + progress.DidNotReceiveWithAnyArgs().Exception(null, null, null); + + AssertNodesEqual(new TestConfigNode("PART") { { "name", "b" }, { "x", "1" }, { "fromB2", "2" }, { "fromB3", "1" } }, configs[0].Node); + AssertNodesEqual(new TestConfigNode("PART") { { "name", "b" }, { "x", "2" }, { "fromB3", "1" } }, configs[1].Node); + AssertNodesEqual(new TestConfigNode("PART") { { "name", "b" }, { "x", "3" }, { "fromB", "2" }, { "fromAny", "1" }, { "fromB2", "1" }, { "fromB3", "1" } }, configs[2].Node); + } + + [Fact] + public void TestApplyPatches__LoopRenameRootLookups() + { + // An MM_PATCH_LOOP pass that renames the node is seen by the root lookups of the next + // pass, and by the patches after the loop, even when a later pass renames it back + IBasicLogger logger = Substitute.For(); + IPatchProgress progress = Substitute.For(); + PatchApplier patchApplier = new PatchApplier(progress, logger); + IPassSpecifier passSpecifier = Substitute.For(); + + IPatch Insert(ConfigNode node) => new InsertPatch(UrlBuilder.CreateConfig("abc/" + node.GetValue("name"), node), "PART", passSpecifier); + IPatch Edit(string url, string name, string constraints, ConfigNode node) => new EditPatch(UrlBuilder.CreateConfig(url, node), new NodeMatcher("PART", name, constraints), passSpecifier); + + IPass pass1 = Substitute.For(); + pass1.GetEnumerator().Returns(new ArrayEnumerator( + Insert(new TestConfigNode("PART") { { "name", "a" }, { "n", "0" } }), + Insert(new TestConfigNode("PART") { { "name", "b" }, { "n", "0" }, { "alt", "d" } }) + )); + + IPass pass2 = Substitute.For(); + pass2.GetEnumerator().Returns(new ArrayEnumerator( + // first pass: reads a (itself) and renames it c; second pass: there is no a any more + Edit("ghi/l1", "a|c", "#n[<2]", new TestConfigNode("@PART[a|c]:HAS[#n[<2]]") + { + { "@n +", "1" }, + { "%seen", "#$@PART[a]/n$" }, + { "@name", "c" }, + new ConfigNode("MM_PATCH_LOOP"), + }), + // first pass renames b to d; the second looks up a root while the node is d, + // then renames it back to b + Edit("ghi/l2", "b|d", "#n[<2]", new TestConfigNode("@PART[b|d]:HAS[#n[<2]]") + { + new TestConfigNode("@MARK") { { "%v", "#$@PART[c]/n$" } }, + new ConfigNode("%MARK"), + { "@n +", "1" }, + { "%tmp", "#$name$" }, + { "@name", "#$alt$" }, + { "@alt", "#$tmp$" }, + new ConfigNode("MM_PATCH_LOOP"), + }), + Edit("ghi/e1", "b", null, new TestConfigNode("@PART[b]") { { "after", "1" } }), + Edit("ghi/e2", "a", null, new TestConfigNode("@PART[a]") { { "after", "2" } }) + )); + + IProtoUrlConfig[] configs = patchApplier.ApplyPatches(new[] { pass1, pass2 }).ToArray(); + + // l1's second pass cannot find PART[a] + progress.ReceivedWithAnyArgs(1).Error(null, null); + progress.DidNotReceiveWithAnyArgs().Exception(null, null); + progress.DidNotReceiveWithAnyArgs().Exception(null, null, null); + + AssertNodesEqual(new TestConfigNode("PART") { { "name", "c" }, { "n", "2" }, { "seen", "0" } }, configs[0].Node); + Assert.Equal("b", configs[1].Node.GetValue("name")); + Assert.Equal("2", configs[1].Node.GetValue("n")); + Assert.Equal("2", configs[1].Node.GetNode("MARK").GetValue("v")); + Assert.Equal("1", configs[1].Node.GetValue("after")); + } + + [Fact] + public void TestApplyPatches__IndexedMatchesPlain() + { + // Copies, deletes and edits through the index give the same nodes, in the same order, + // with the same errors, as each patch's plain Apply over the whole list + IPassSpecifier passSpecifier = Substitute.For(); + + IPatch[] MakePatches() + { + IPatch Insert(string type, string name, string x) => new InsertPatch( + UrlBuilder.CreateConfig("abc/" + name, new TestConfigNode(type) { { "name", name }, { "x", x } }), type, passSpecifier); + IPatch Copy(string url, string name, string constraints, ConfigNode node) => new CopyPatch(UrlBuilder.CreateConfig(url, node), new NodeMatcher("PART", name, constraints), passSpecifier); + IPatch Delete(string url, string name, string constraints) => new DeletePatch(UrlBuilder.CreateConfig(url, new ConfigNode("!PART")), new NodeMatcher("PART", name, constraints), passSpecifier); + IPatch Edit(string url, string name, string constraints, ConfigNode node) => new EditPatch(UrlBuilder.CreateConfig(url, node), new NodeMatcher("PART", name, constraints), passSpecifier); + + return new[] + { + Insert("PART", "a", "1"), + Insert("PROP", "a", "2"), + Insert("PART", "b", "3"), + Insert("PART", "a", "4"), + Insert("PART", "c", "5"), + Insert("PART", "d", "6"), + Copy("ghi/c1", "a", null, new TestConfigNode("+PART[a]") { { "@name", "a2" }, { "@x", "#$x$0" } }), + Copy("ghi/c2", "b,c", null, new TestConfigNode("+PART[b,c]") { { "@name", "#$name$_copy" }, { "fromA2", "#$@PART[a2]/x$" } }), + // fails: same name as the source + Copy("ghi/c3", "d", null, new TestConfigNode("+PART[d]") { { "y", "1" } }), + Edit("ghi/e1", "a2", null, new TestConfigNode("@PART[a2]") { { "edited", "1" } }), + // renames d to e in place while copying c: e, not yet reached, is then copied too + Copy("ghi/c4", "c|e", null, new TestConfigNode("+PART[c|e]") { { "*@PART[d]/name", "e" }, { "@name", "#$name$_c4" } }), + Delete("ghi/d1", "a2", null), + Delete("ghi/d2", "*", "#x[5*]"), + Delete("ghi/d3", "nothere", null), + Copy("ghi/c5", "*_copy", null, new TestConfigNode("+PART[*_copy]") { { "@name ^", ":_copy$:_again:" } }), + Edit("ghi/e2", "*", null, new TestConfigNode("@PART[*]") { { "last", "#$name$" } }), + Delete("ghi/d4", "b", null), + Edit("ghi/e3", "b|e", null, new TestConfigNode("@PART[b|e]") { { "after", "1" } }), + }; + } + + string Describe(NSubstitute.Core.ICall call) => call.GetMethodInfo().Name + ":" + string.Join("|", call.GetArguments().Select(a => a is IProtoUrlConfig p ? p.Node.ToString() : a?.ToString())); + + IPatchProgress plainProgress = Substitute.For(); + LinkedList plain = new LinkedList(); + foreach (IPatch patch in MakePatches()) + patch.Apply(plain, plainProgress, Substitute.For()); + + IPatchProgress progress = Substitute.For(); + PatchApplier patchApplier = new PatchApplier(progress, Substitute.For()); + IPass pass = Substitute.For(); + pass.GetEnumerator().Returns(new ArrayEnumerator(MakePatches())); + IProtoUrlConfig[] configs = patchApplier.ApplyPatches(new[] { pass }).ToArray(); + + Assert.Equal(plain.Select(c => c.Node.ToString()).ToArray(), configs.Select(c => c.Node.ToString()).ToArray()); + Assert.Equal( + plainProgress.ReceivedCalls().Select(Describe).ToArray(), + progress.ReceivedCalls().Where(c => c.GetMethodInfo().Name != "PatchApplied" && c.GetMethodInfo().Name != "PassStarted").Select(Describe).ToArray()); + Assert.Equal(1, configs.Count(c => c.Node.name == "PROP")); + Assert.Contains(configs, c => c.Node.GetValue("name") == "e_c4"); + Assert.Contains(configs, c => c.Node.GetValue("name") == "b_again"); + } + + // Records the text of every root node, and checks that the ones the patch before replaced + // are as they were: edits must not change the versions they replace. (Later, a special + // command can write into a subnode a replaced version shares with the live one, which + // nothing reads.) + private class Snapshots + { + // the root nodes in the list at the last snapshot, and their text + public readonly List> Seen = new List>(); + public int Checked; + } + + private class SnapshotPatch : IPatch + { + private readonly Snapshots snapshots; + public SnapshotPatch(Snapshots snapshots) { this.snapshots = snapshots; } + public UrlDir.UrlConfig UrlConfig { get; } = UrlBuilder.CreateConfig("snap/shot", new ConfigNode("SNAPSHOT")); + public IPassSpecifier PassSpecifier => null; + public bool CountsAsPatch => false; + public void Apply(LinkedList configs, IPatchProgress progress, IBasicLogger logger) + { + HashSet live = new HashSet(configs.Select(c => c.Node)); + foreach (KeyValuePair pair in snapshots.Seen) + { + if (live.Contains(pair.Key)) continue; + Assert.Equal(pair.Value, pair.Key.ToString()); + snapshots.Checked++; + } + snapshots.Seen.Clear(); + foreach (IProtoUrlConfig config in configs) + snapshots.Seen.Add(new KeyValuePair(config.Node, config.Node.ToString())); + } + } + + [Fact] + public void TestApplyPatches__SharedSubnodesMatchCopies() + { + // Edits that share the subnodes they leave alone with the node they replace give the + // same nodes and errors as edits of whole copies, and never change a replaced node + IPassSpecifier passSpecifier = Substitute.For(); + + IPatch[] MakePatches(Snapshots snapshots) + { + IPatch Insert(ConfigNode node) => new InsertPatch(UrlBuilder.CreateConfig("abc/" + node.GetValue("name"), node), "PART", passSpecifier); + IPatch Edit(string url, string name, string constraints, ConfigNode node) => new EditPatch(UrlBuilder.CreateConfig(url, node), new NodeMatcher("PART", name, constraints), passSpecifier); + + List patches = new List + { + Insert(new TestConfigNode("PART") + { + { "name", "a" }, { "mass", "1" }, + new TestConfigNode("MODULE") { { "name", "M1" }, { "x", "1" }, new TestConfigNode("SUB") { { "y", "1" } } }, + new TestConfigNode("MODULE") { { "name", "M2" }, { "x", "2" } }, + new TestConfigNode("MODULE") { { "name", "M3" }, { "x", "3" } }, + new TestConfigNode("RES") { { "name", "R" }, { "amount", "5" } }, + }), + Insert(new TestConfigNode("PART") + { + { "name", "b" }, + new TestConfigNode("MODULE") { { "name", "M1" }, { "x", "10" } }, + new TestConfigNode("MODULE") { { "name", "M1" }, { "x", "11" } }, + }), + Insert(new TestConfigNode("PART") { { "name", "c" }, { "foo", "1" } }), + // a nested edit + Edit("e/1", "a", null, new TestConfigNode("@PART[a]") { new TestConfigNode("@MODULE[M1]") { { "@x", "5" }, new TestConfigNode("@SUB") { { "y", "2" } } } }), + // the same subnode edited twice in one patch + Edit("e/2", "a", null, new TestConfigNode("@PART[a]") { new TestConfigNode("@MODULE[M1]") { { "@x +", "1" } }, new TestConfigNode("@MODULE[M1]") { { "z", "1" } } }), + // every MODULE of every part that has an M1 + Edit("e/3", "*", "@MODULE[M1]", new TestConfigNode("@PART[*]:HAS[@MODULE[M1]]") { new TestConfigNode("@MODULE,*") { { "touched", "#$name$" } } }), + // replace an existing subnode and a missing one + Edit("e/4", "a", null, new TestConfigNode("@PART[a]") { new TestConfigNode("%MODULE[M2]") { { "%x", "9" } }, new TestConfigNode("%MODULE[M9]") { { "x", "1" } } }), + // delete and copy + Edit("e/5", "a", null, new TestConfigNode("@PART[a]") { new TestConfigNode("!MODULE[M3]"), new TestConfigNode("+MODULE[M1]") { { "@name", "M1copy" } } }), + // a negative index lists the last subnode twice + Edit("e/6", "b", null, new TestConfigNode("@PART[b]") { new TestConfigNode("@MODULE,-1") { { "last +", "1" } } }), + // a subnode inserted, then edited + Edit("e/7", "c", null, new TestConfigNode("@PART[c]") { new TestConfigNode("MODULE") { { "name", "New" }, { "edited", "0" } }, new TestConfigNode("@MODULE[New]") { { "@edited +", "1" } } }), + // a loop + Edit("e/8", "c", "#foo[<3]", new TestConfigNode("@PART[c]:HAS[#foo[<3]]") { { "@foo +", "1" }, new TestConfigNode("@MODULE[New]") { { "@edited +", "1" } }, new ConfigNode("MM_PATCH_LOOP") }), + // a special command, writing into another part's subnode + Edit("e/9", "a", null, new TestConfigNode("@PART[a]") { { "*@PART[b]/MODULE[M1]/x", "99" }, new TestConfigNode("@MODULE[M2]") { { "s", "1" } } }), + Edit("e/10", "b", null, new TestConfigNode("@PART[b]") { new TestConfigNode("@MODULE[M1]") { { "after", "1" } } }), + // fails part way: the regex does not parse + Edit("e/11", "b", null, new TestConfigNode("@PART[b]") { new TestConfigNode("@MODULE[M1]") { { "mid", "1" } }, new TestConfigNode("@MODULE[M1]") { { "@x ^", ":(:z:" } } }), + // a paste + Edit("e/12", "c", null, new TestConfigNode("@PART[c]") { new ConfigNode("#@PART[a]/RES[R]") }), + // a rename a whole copy cleans (DEEP (x) -> DEEP), two levels down, then a + // match on the cleaned name; and the same one level down + Edit("e/15", "a", null, new TestConfigNode("@PART[a]") { new TestConfigNode("@MODULE[M1]") { new TestConfigNode("@SUB") { { "|_", "DEEP (x)" } } } }), + Edit("e/16", "a", null, new TestConfigNode("@PART[a]") { { "touch", "1" } }), + Edit("e/17", "a", "@MODULE[M1]:HAS[@DEEP]", new TestConfigNode("@PART[a]:HAS[@MODULE[M1]:HAS[@DEEP]]") { { "foundDeep", "1" } }), + Edit("e/18", "a", null, new TestConfigNode("@PART[a]") { new TestConfigNode("@MODULE[M2]") { { "|_", "OLD MODULE" } } }), + Edit("e/19", "a", null, new TestConfigNode("@PART[a]") { new TestConfigNode("@OLD") { { "gotIt", "1" } } }), + // a special command writing a brace into a subnode, then an edit of its part + Edit("e/13", "c", null, new TestConfigNode("@PART[c]") { { "*@PART[a]/RES[R]/amount", "{q}" } }), + Edit("e/14", "a", null, new TestConfigNode("@PART[a]") { new TestConfigNode("@MODULE[M1]") { { "after", "1" } } }), + }; + List withSnapshots = new List(); + foreach (IPatch patch in patches) + { + withSnapshots.Add(new SnapshotPatch(snapshots)); + withSnapshots.Add(patch); + } + return withSnapshots.ToArray(); + } + + // As the patch log has them: a node by its URL, taken when it was put in the list + string Describe(NSubstitute.Core.ICall call) => call.GetMethodInfo().Name + ":" + string.Join("|", call.GetArguments().Select(a => a is IProtoUrlConfig p ? p.FullUrl : a is Exception e ? e.GetType().Name : a?.ToString())); + + (string[] nodes, string[] calls, int checkedVersions) Run(bool share) + { + bool before = EditPatch.ShareSubnodes; + EditPatch.ShareSubnodes = share; + try + { + Snapshots snapshots = new Snapshots(); + IPatchProgress progress = Substitute.For(); + PatchApplier patchApplier = new PatchApplier(progress, Substitute.For()); + IPass pass = Substitute.For(); + pass.GetEnumerator().Returns(new ArrayEnumerator(MakePatches(snapshots).Concat(new[] { new SnapshotPatch(snapshots) }).ToArray())); + IProtoUrlConfig[] configs = patchApplier.ApplyPatches(new[] { pass }).ToArray(); + return (configs.Select(c => c.Node.ToString()).ToArray(), progress.ReceivedCalls().Where(c => c.GetMethodInfo().Name != "PassStarted").Select(Describe).ToArray(), snapshots.Checked); + } + finally + { + EditPatch.ShareSubnodes = before; + } + } + + var copies = Run(false); + var shared = Run(true); + + Assert.Equal(copies.nodes, shared.nodes); + Assert.Equal(copies.calls, shared.calls); + Assert.Contains(copies.calls, c => c.StartsWith("Exception:")); + Assert.Contains("M1copy", shared.nodes[0]); + Assert.Contains("[q]", shared.nodes[0]); + Assert.Contains("foundDeep", shared.nodes[0]); + Assert.Contains("gotIt", shared.nodes[0]); + Assert.True(shared.checkedVersions > 10); + } + + private void AssertNodesEqual(ConfigNode expected, ConfigNode actual) + { + Assert.Equal(expected.ToString(), actual.ToString()); + } } } diff --git a/ModuleManagerTests/PatchTypeIndexTest.cs b/ModuleManagerTests/PatchTypeIndexTest.cs new file mode 100644 index 00000000..2c714028 --- /dev/null +++ b/ModuleManagerTests/PatchTypeIndexTest.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using Xunit; +using TestUtils; +using ModuleManager; + +namespace ModuleManagerTests +{ + public class PatchTypeIndexTest + { + private readonly UrlDir.UrlFile file = UrlBuilder.CreateFile("abc/def.cfg"); + + [Fact] + public void TestConstructor__ConfigsNull() + { + ArgumentNullException ex = Assert.Throws(delegate + { + new PatchTypeIndex(null); + }); + + Assert.Equal("configs", ex.ParamName); + } + + [Fact] + public void TestNodesOfType__TypeNull() + { + PatchTypeIndex index = new PatchTypeIndex(new LinkedList()); + ArgumentNullException ex = Assert.Throws(delegate + { + index.NodesOfType(null); + }); + + Assert.Equal("type", ex.ParamName); + } + + [Fact] + public void TestNodesOfType() + { + LinkedList configs = new LinkedList(); + LinkedListNode a1 = configs.AddLast(new ProtoUrlConfig(file, new ConfigNode("A"))); + LinkedListNode b1 = configs.AddLast(new ProtoUrlConfig(file, new ConfigNode("B"))); + LinkedListNode a2 = configs.AddLast(new ProtoUrlConfig(file, new ConfigNode("A"))); + configs.AddLast(new ProtoUrlConfig(file, new ConfigNode("a"))); + + PatchTypeIndex index = new PatchTypeIndex(configs); + + Assert.Equal(new[] { a1, a2 }, index.NodesOfType("A")); + Assert.Equal(new[] { b1 }, index.NodesOfType("B")); + Assert.Empty(index.NodesOfType("C")); + } + + [Fact] + public void TestInvalidate() + { + LinkedList configs = new LinkedList(); + LinkedListNode a1 = configs.AddLast(new ProtoUrlConfig(file, new ConfigNode("A"))); + LinkedListNode a2 = configs.AddLast(new ProtoUrlConfig(file, new ConfigNode("A"))); + + PatchTypeIndex index = new PatchTypeIndex(configs); + Assert.Equal(new[] { a1, a2 }, index.NodesOfType("A")); + + LinkedListNode a3 = configs.AddAfter(a1, new ProtoUrlConfig(file, new ConfigNode("A"))); + configs.Remove(a2); + + // Not seen until invalidated + Assert.Equal(new[] { a1, a2 }, index.NodesOfType("A")); + + index.Invalidate(); + Assert.Equal(new[] { a1, a3 }, index.NodesOfType("A")); + } + + [Fact] + public void TestInvalidate__Type() + { + LinkedList configs = new LinkedList(); + LinkedListNode a1 = configs.AddLast(new ProtoUrlConfig(file, new ConfigNode("A"))); + LinkedListNode b1 = configs.AddLast(new ProtoUrlConfig(file, new ConfigNode("B"))); + + PatchTypeIndex index = new PatchTypeIndex(configs); + List> bNodes = index.NodesOfType("B"); + + LinkedListNode a2 = configs.AddFirst(new ProtoUrlConfig(file, new ConfigNode("A"))); + LinkedListNode c1 = configs.AddLast(new ProtoUrlConfig(file, new ConfigNode("C"))); + index.Invalidate("A"); + index.Invalidate("C"); + + Assert.Equal(new[] { a2, a1 }, index.NodesOfType("A")); + Assert.Equal(new[] { c1 }, index.NodesOfType("C")); + Assert.Same(bNodes, index.NodesOfType("B")); + + configs.Remove(c1); + index.Invalidate("C"); + Assert.Empty(index.NodesOfType("C")); + } + + [Fact] + public void TestInvalidate__TypeNull() + { + PatchTypeIndex index = new PatchTypeIndex(new LinkedList()); + ArgumentNullException ex = Assert.Throws(delegate + { + index.Invalidate(null); + }); + + Assert.Equal("type", ex.ParamName); + } + } +} diff --git a/ModuleManagerTests/ProtoUrlConfigTest.cs b/ModuleManagerTests/ProtoUrlConfigTest.cs index f16cd1bd..1b85e882 100644 --- a/ModuleManagerTests/ProtoUrlConfigTest.cs +++ b/ModuleManagerTests/ProtoUrlConfigTest.cs @@ -1,4 +1,4 @@ -using System; +using System; using Xunit; using TestUtils; using ModuleManager; @@ -83,5 +83,26 @@ public void TestFullUrl__NameValue() Assert.Equal("abc/def.cfg/SOME_NODE[some_value]", protoUrlConfig.FullUrl); } + + [Fact] + public void TestNameValue() + { + ConfigNode node = new TestConfigNode("SOME_NODE") + { + { "name", "some_value" }, + }; + + ProtoUrlConfig protoUrlConfig = new ProtoUrlConfig(UrlBuilder.CreateFile("abc/def.cfg"), node); + + Assert.Equal("some_value", protoUrlConfig.NameValue); + } + + [Fact] + public void TestNameValue__None() + { + ProtoUrlConfig protoUrlConfig = new ProtoUrlConfig(UrlBuilder.CreateFile("abc/def.cfg"), new ConfigNode("SOME_NODE")); + + Assert.Null(protoUrlConfig.NameValue); + } } } diff --git a/ModuleManagerTests/WildcardMatchTest.cs b/ModuleManagerTests/WildcardMatchTest.cs new file mode 100644 index 00000000..90d5b341 --- /dev/null +++ b/ModuleManagerTests/WildcardMatchTest.cs @@ -0,0 +1,138 @@ +using System; +using System.Text; +using System.Text.RegularExpressions; +using Xunit; +using TestUtils; +using ModuleManager; + +namespace ModuleManagerTests +{ + public class WildcardMatchTest + { + // What WildcardMatch did with a regex for every pattern + private static bool RegexMatch(string s, string wildcard) + { + if (wildcard == null) return true; + return new Regex("^" + Regex.Escape(wildcard).Replace(@"\*", ".*").Replace(@"\?", ".") + "$").IsMatch(s); + } + + [Theory] + [InlineData("abc", "abc")] + [InlineData("abc", "a*")] + [InlineData("abc", "*c")] + [InlineData("abc", "*b*")] + [InlineData("abc", "a?c")] + [InlineData("abc", "a?")] + [InlineData("abc", "*")] + [InlineData("", "*")] + [InlineData("", "?")] + [InlineData("", "")] + [InlineData("abc\n", "a*")] + [InlineData("abc\n", "abc")] + [InlineData("abc\n\n", "a*")] + [InlineData("a\nc", "a?c")] + [InlineData("a\nc", "a*c")] + [InlineData("a\nc", "a*")] + [InlineData("a\nc", "*c")] + [InlineData("a.c", "a.c")] + [InlineData("abc", "a.c")] + [InlineData("a+b", "a+*")] + [InlineData("ABC", "a*")] + [InlineData("a\\b", "a\\*")] + [InlineData("a\\*", "a\\*")] + [InlineData("aaa", "a*a*a")] + [InlineData("aa", "a*a*a")] + [InlineData("mississippi", "m*iss*p?i")] + [InlineData("a(b)", "a(*)")] + [InlineData("a[b]", "a[?]")] + [InlineData("a b", "a?b")] + [InlineData("a\rb", "a?b")] + public void TestWildcardMatch__SameAsRegex(string s, string wildcard) + { + Assert.Equal(RegexMatch(s, wildcard), MMPatchLoader.WildcardMatch(s, wildcard)); + } + + [Fact] + public void TestWildcardMatch__Random() + { + Random random = new Random(1234); + const string chars = "ab*?\n.\\"; + string Make(int maxLength) + { + StringBuilder sb = new StringBuilder(); + int length = random.Next(maxLength + 1); + for (int i = 0; i < length; i++) sb.Append(chars[random.Next(chars.Length)]); + return sb.ToString(); + } + + for (int i = 0; i < 20000; i++) + { + string wildcard = Make(6); + string s = Make(8).Replace("*", "a").Replace("?", "b"); + Assert.True(RegexMatch(s, wildcard) == MMPatchLoader.WildcardMatch(s, wildcard), $"s = \"{s}\", wildcard = \"{wildcard}\""); + } + } + + [Fact] + public void TestWildcardMatch__Null() + { + Assert.True(MMPatchLoader.WildcardMatch("abc", null)); + Assert.Throws(() => MMPatchLoader.WildcardMatch(null, "a*")); + Assert.Throws(() => MMPatchLoader.WildcardMatch(null, "abc")); + } + + [Theory] + [InlineData("#foo", true)] + [InlineData("#foo[1]", true)] + [InlineData("#foo[2]", true)] + [InlineData("#foo[3]", false)] + [InlineData("#foo[>1.5]", true)] + [InlineData("#foo[<1]", false)] + [InlineData("#bar", false)] + [InlineData("~bar[]", true)] + [InlineData("~foo[]", false)] + [InlineData("~foo[3]", true)] + [InlineData("~foo[2]", false)] + [InlineData("#foo[1],#foo[2]", true)] + [InlineData("#foo[1],#bar", false)] + [InlineData("#foo[1]&@INNER[x]", true)] + [InlineData("@INNER[x]:HAS[#v[1]]", true)] + [InlineData("@INNER[x]:HAS[#v[2]]", false)] + [InlineData("@INNER:HAS[#v[2]]", true)] + [InlineData("!INNER:HAS[#v[3]]", true)] + [InlineData("@INNER[*]:HAS[@DEEP:HAS[#w[a*]]]", true)] + [InlineData("@INNER[*]:HAS[@DEEP:HAS[#w[b*]]]", false)] + [InlineData("@INNER[y]", true)] + [InlineData("@INNER[Y]", false)] + [InlineData("@INNE", false)] + [InlineData("@INNER[x],@INNER[y]:HAS[#v[2]]", true)] + // a type or name followed by a newline matches the literal, as ^literal$ does + [InlineData("@LINE", true)] + [InlineData("@LINE[z]", true)] + [InlineData("@LINE[z]:HAS[#v[9]]", true)] + [InlineData("@LINE[zz]", false)] + [InlineData("!LINE[z]", false)] + [InlineData("@LIN?[z*]", true)] + public void TestCheckConstraints(string constraints, bool expected) + { + ConfigNode node = new TestConfigNode("PART") + { + { "foo", "1" }, + { "foo", "2" }, + new TestConfigNode("INNER") { { "name", "x" }, { "v", "1" } }, + new TestConfigNode("INNER") { { "name", "y" }, { "v", "2" }, new TestConfigNode("DEEP") { { "w", "abc" } } }, + }; + ConfigNode line = new ConfigNode(); + line.name = "LINE\n"; + line.AddValue("name", "z"); + line.values[0].value = "z\n"; + line.AddValue("v", "9"); + node.AddNode(line); + Assert.Equal("LINE\n", node.nodes[2].name); + + // twice: the second time takes the parsed constraints from the cache + Assert.Equal(expected, MMPatchLoader.CheckConstraints(node, constraints)); + Assert.Equal(expected, MMPatchLoader.CheckConstraints(node, constraints)); + } + } +}