diff --git a/RPGModder.Core/Merge/AddedIdIndex.cs b/RPGModder.Core/Merge/AddedIdIndex.cs new file mode 100644 index 0000000..7c52c94 --- /dev/null +++ b/RPGModder.Core/Merge/AddedIdIndex.cs @@ -0,0 +1,55 @@ +using Newtonsoft.Json.Linq; + +namespace RPGModder.Core.Merge; + +/// +/// The ids a change set adds, by kind and scope (GR-R2, GR-R3). An op the builder writes for a record vanilla does +/// not have is the only kind of added id: a map event is an AddRecord on event:n of a vanilla map; a +/// map is a whole new MapNNN.json, its MapInfos record, or both. Step 1 lists these two kinds only. +/// +internal static class AddedIdIndex +{ + public static IReadOnlyList Of(ModChangeSet changeSet) + { + var events = new List(); + var maps = new SortedDictionary(); + foreach (ChangeOp op in changeSet.Ops) + { + if (op.Kind != ChangeKind.AddRecord || op.Path.Length != 0 || op.Value is null) + { + continue; + } + + if (op.Key.IsWholeFile && RpgDataSchema.TryGetMapId(op.Key.File, out int mapId)) + { + maps[mapId] = (op.Value, maps.GetValueOrDefault(mapId).Info); + } + else if (op.Key.File == RpgDataSchema.MapInfosKey && RecordKey.TryGetIndex(op.Key.Record, out int infoId) && infoId > 0) + { + maps[infoId] = (maps.GetValueOrDefault(infoId).File, op.Value); + } + else if (RpgDataSchema.IsMapFile(op.Key.File) && RecordKey.TryGetEvent(op.Key.Record, out int eventId) && eventId > 0) + { + events.Add(new AddedId(IdKind.MapEvent, op.Key.File, eventId, op.Value)); + } + } + + var result = new List(events); + foreach ((int id, (JToken? file, JToken? info)) in maps) + { + // Both halves are the content, cloned so no op gains a parent; two mods that add one map with one tree entry are one map (GR-R3). + result.Add(new AddedId(IdKind.Map, "", id, new JArray(file?.DeepClone() ?? JValue.CreateNull(), info?.DeepClone() ?? JValue.CreateNull()))); + } + + return result; + } + + /// True when the change set still adds 's old id; otherwise the entry is inactive (GR-R12). + public static bool IsActive(IdRemap remap, IReadOnlyList added) + { + return added.Any(item => item.Kind == remap.Kind && item.Scope == remap.Scope && item.Id == remap.FromId); + } +} + +/// One added id and the content that decides whether two mods add the same thing. +internal sealed record AddedId(IdKind Kind, string Scope, int Id, JToken Content); diff --git a/RPGModder.Core/Merge/BaseFile.cs b/RPGModder.Core/Merge/BaseFile.cs new file mode 100644 index 0000000..955aedd --- /dev/null +++ b/RPGModder.Core/Merge/BaseFile.cs @@ -0,0 +1,10 @@ +namespace RPGModder.Core.Merge; + +/// +/// A vanilla file, or the live config save (GR-M10). Text is set when +/// is not ; Sha256 is lower-case hex. +/// +public sealed record BaseFile( + string Path, + string? Text, + string Sha256); diff --git a/RPGModder.Core/Merge/BaseFileSet.cs b/RPGModder.Core/Merge/BaseFileSet.cs new file mode 100644 index 0000000..52a0d64 --- /dev/null +++ b/RPGModder.Core/Merge/BaseFileSet.cs @@ -0,0 +1,37 @@ +namespace RPGModder.Core.Merge; + +/// +/// The base files of one plan, looked up by key. A path with no entry means vanilla does not have the file (GR-M9). +/// +public sealed class BaseFileSet +{ + private readonly Dictionary _byKey; + + private BaseFileSet(Dictionary byKey) + { + _byKey = byKey; + } + + /// Two entries with one key are a caller bug, because the plan would depend on which one wins. + public static BaseFileSet From(IEnumerable files) + { + ArgumentNullException.ThrowIfNull(files); + + var byKey = new Dictionary(StringComparer.Ordinal); + foreach (BaseFile file in files) + { + string key = MergePath.ToKey(file.Path); + if (!byKey.TryAdd(key, file)) + { + throw new ArgumentException($"Two base files share the key {key}.", nameof(files)); + } + } + + return new BaseFileSet(byKey); + } + + public BaseFile? Find(string path) + { + return _byKey.GetValueOrDefault(MergePath.ToKey(path)); + } +} diff --git a/RPGModder.Core/Merge/ChangeKind.cs b/RPGModder.Core/Merge/ChangeKind.cs new file mode 100644 index 0000000..c44670e --- /dev/null +++ b/RPGModder.Core/Merge/ChangeKind.cs @@ -0,0 +1,12 @@ +namespace RPGModder.Core.Merge; + +public enum ChangeKind +{ + SetLeaf, + RemoveLeaf, + AddRecord, + RemoveRecord, + EditSequence, + EditCommands, + ReplaceFile +} diff --git a/RPGModder.Core/Merge/ChangeOp.cs b/RPGModder.Core/Merge/ChangeOp.cs new file mode 100644 index 0000000..74cdd4d --- /dev/null +++ b/RPGModder.Core/Merge/ChangeOp.cs @@ -0,0 +1,15 @@ +using Newtonsoft.Json.Linq; + +namespace RPGModder.Core.Merge; + +/// +/// One change a mod makes against vanilla (GR-M1). Value is null for the remove kinds; a leaf +/// set to JSON null holds a of type null instead. +/// +public sealed record ChangeOp( + string ModId, + RecordKey Key, + string Path, + ChangeKind Kind, + JToken? Value, + string? SourceFile); diff --git a/RPGModder.Core/Merge/ChangeSetBuilder.cs b/RPGModder.Core/Merge/ChangeSetBuilder.cs new file mode 100644 index 0000000..0dc9544 --- /dev/null +++ b/RPGModder.Core/Merge/ChangeSetBuilder.cs @@ -0,0 +1,522 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace RPGModder.Core.Merge; + +/// +/// Turns one mod into ops against vanilla (guide 3.1, first step). A whole-file mod and a json_patches mod +/// go through the same walker, so they give the same kind of ops (GR-M4). Bad mod content is a diagnostic, +/// never an exception and never a fallback (GR-C5, GR-M8). +/// +public static class ChangeSetBuilder +{ + public static ModChangeSet Build(ModSource mod, BaseFileSet baseFiles) + { + ArgumentNullException.ThrowIfNull(mod); + ArgumentNullException.ThrowIfNull(baseFiles); + + var ops = new List(); + var diagnostics = new List(); + + foreach (TargetEdits target in CollectTargets(mod)) + { + switch (RpgDataSchema.KindOf(target.Key)) + { + case MergeFileKind.Data: + BuildDataFile(mod.ModId, target, baseFiles, ops, diagnostics); + break; + case MergeFileKind.PluginList: + BuildPluginList(mod, target, baseFiles, ops, diagnostics); + break; + case MergeFileKind.ConfigSave: + BuildConfigSave(mod.ModId, target, baseFiles, ops, diagnostics); + break; + case MergeFileKind.Opaque: + BuildOpaqueFile(mod.ModId, target, baseFiles, ops, diagnostics); + break; + default: + throw new UnreachableException($"KindOf returned a kind the builder does not know for {target.Key}."); + } + } + + ops.Sort(CompareOps); + return new ModChangeSet(mod.ModId, mod.Priority, ops, diagnostics); + } + + internal static int CompareOps(ChangeOp left, ChangeOp right) + { + int result = string.CompareOrdinal(left.Key.File, right.Key.File); + if (result == 0) + { + result = string.CompareOrdinal(left.Key.Record, right.Key.Record); + } + + if (result == 0) + { + result = string.CompareOrdinal(left.Path, right.Path); + } + + return result; + } + + private static void BuildDataFile( + string modId, + TargetEdits target, + BaseFileSet baseFiles, + List ops, + List diagnostics) + { + BaseFile? baseFile = baseFiles.Find(target.Key); + if (baseFile is null) + { + BuildNewDataFile(modId, target, ops, diagnostics); + return; + } + + if (!TryReadBase(baseFile, out JToken? vanilla, out OperationDiagnostic? baseProblem)) + { + diagnostics.Add(baseProblem); + return; + } + + // Vanilla is cloned only for a patch-only mod; a mod that ships the file is read instead. + JToken? modded; + if (target.File is null) + { + modded = vanilla.DeepClone(); + } + else if (!TryReadModData(modId, target, target.File, out modded, diagnostics)) + { + return; + } + + if (!TryApplyPatches(modId, target, modded, diagnostics)) + { + return; + } + + if (RpgDataSchema.ShapeOf(target.Key, vanilla) == RootShape.Map && + RpgDataSchema.IsEventList(vanilla[RpgDataSchema.EventsProperty]) && + modded is JObject map && + map[RpgDataSchema.EventsProperty] is not JArray) + { + // Vanilla's events are records other mods edit one by one; a mod without an events list would + // replace them all with no collision, so it is refused like a root of the wrong shape. + diagnostics.Add(Error( + DiagnosticCodes.MergeRootShapeMismatch, + $"Mod {modId} gives {target.Key} an events value that is not a list.", + modId)); + return; + } + + ops.AddRange(DataDiff.Compare(modId, target.Key, target.File?.Source, vanilla, modded)); + } + + /// + /// GR-M9: a data file vanilla lacks is one AddRecord on *, never merged from an empty base. Its + /// source stays on the op so the writer copies the mod's bytes, unless a patch changed the content. + /// + private static void BuildNewDataFile(string modId, TargetEdits target, List ops, List diagnostics) + { + if (target.File is null) + { + diagnostics.Add(Error( + DiagnosticCodes.MergePatchTargetMissing, + $"Mod {modId} patches {target.Key}, which the game does not have.", + modId)); + return; + } + + if (!TryReadModData(modId, target, target.File, out JToken? content, diagnostics) || + !TryApplyPatches(modId, target, content, diagnostics)) + { + return; + } + + string? source = target.Patches.Count == 0 ? target.File.Source : null; + ops.Add(new ChangeOp(modId, new RecordKey(target.Key, RecordKey.WholeFile), "", ChangeKind.AddRecord, content, source)); + } + + /// + /// Bytes are compared by hash only (guide 3.3): a file equal to vanilla is no change, anything else replaces + /// the whole file. A patch cannot apply to bytes. + /// + private static void BuildOpaqueFile( + string modId, + TargetEdits target, + BaseFileSet baseFiles, + List ops, + List diagnostics) + { + if (!RejectPatches(modId, target, diagnostics) || target.File is null) + { + return; + } + + string hash = target.File.Sha256.ToLowerInvariant(); + if (string.Equals(baseFiles.Find(target.Key)?.Sha256, hash, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + ops.Add(new ChangeOp( + modId, + new RecordKey(target.Key, RecordKey.WholeFile), + "", + ChangeKind.ReplaceFile, + new JValue(hash), + target.File.Source)); + } + + /// + /// The mod's list is its own plugins.js, or vanilla's when it ships none, with its + /// plugins_registry applied on top (seam 11.1). No vanilla plugins.js is an empty list. + /// + private static void BuildPluginList( + ModSource mod, + TargetEdits target, + BaseFileSet baseFiles, + List ops, + List diagnostics) + { + string modId = mod.ModId; + if (!RejectPatches(modId, target, diagnostics)) + { + return; + } + + PluginListText? vanilla = PluginListText.Empty(); + BaseFile? baseFile = baseFiles.Find(target.Key); + if (baseFile is not null && !PluginListText.TryParse(baseFile.Text, out vanilla, out string? baseError)) + { + diagnostics.Add(Error(DiagnosticCodes.MergeBaseParseFailed, $"The game file {target.Key} cannot be read: {baseError}.", target.Key)); + return; + } + + JArray list; + if (target.File is null) + { + list = (JArray)vanilla.Entries.DeepClone(); + } + else if (PluginListText.TryParse(target.File.Text, out PluginListText? own, out string? modError)) + { + list = own.Entries; + } + else + { + diagnostics.Add(Error( + DiagnosticCodes.MergeParseFailed, + $"Mod {modId} file {target.File.Source} for {target.Key} cannot be read: {modError}.", + modId)); + return; + } + + var named = new List(mod.Plugins.Count); + for (int index = 0; index < mod.Plugins.Count; index++) + { + PluginEntry? plugin = mod.Plugins[index]; + if (string.IsNullOrEmpty(plugin?.Name)) + { + // A nameless entry has no record to merge, and a silent whole-list fallback would hide the fault. + diagnostics.Add(Error( + DiagnosticCodes.MergeParseFailed, + $"Mod {modId} plugins_registry entry {index} has no name.", + modId)); + continue; + } + + named.Add(plugin); + } + + PluginListDiff.ApplyRegistry(list, named); + ops.AddRange(PluginListDiff.Compare(modId, target.File?.Source, vanilla.Entries, list)); + } + + /// + /// GR-M10: the base is the live file (or {}), and each top-level key the mod sets to another value is + /// one op. A key the mod lacks is the player's and is never removed. + /// + private static void BuildConfigSave( + string modId, + TargetEdits target, + BaseFileSet baseFiles, + List ops, + List diagnostics) + { + if (!RpgDataSchema.IsDecodedConfigSave(target.Key)) + { + diagnostics.Add(Error( + DiagnosticCodes.MergeConfigSaveUnsupported, + $"Mod {modId} changes {target.Key}, a config save form this version cannot read yet.", + modId)); + return; + } + + if (!TryReadConfigBase(baseFiles.Find(target.Key), target.Key, out JObject? live, out OperationDiagnostic? baseProblem)) + { + diagnostics.Add(baseProblem); + return; + } + + JObject? modded = (JObject)live.DeepClone(); + if (target.File is not null && !ConfigSaveText.TryDecode(target.Key, target.File.Text, out modded, out string? modError)) + { + diagnostics.Add(Error( + DiagnosticCodes.MergeParseFailed, + $"Mod {modId} file {target.File.Source} for {target.Key} cannot be read: {modError}.", + modId)); + return; + } + + foreach (ModPatch patch in target.Patches) + { + ApplyPatch(modded, patch.MergeData); + } + + foreach (JProperty property in modded.Properties()) + { + JToken? current = live.Property(property.Name, StringComparison.Ordinal)?.Value; + if (current is null || !JToken.DeepEquals(current, property.Value)) + { + ops.Add(new ChangeOp( + modId, + new RecordKey(target.Key, RecordKey.WholeFile), + MergePath.Child("", property.Name), + ChangeKind.SetLeaf, + property.Value.DeepClone(), + target.File?.Source)); + } + } + } + + /// The live config save, or an empty object when the player has none yet (GR-M10). + internal static bool TryReadConfigBase( + BaseFile? baseFile, + string key, + [NotNullWhen(true)] out JObject? live, + [NotNullWhen(false)] out OperationDiagnostic? problem) + { + problem = null; + if (baseFile is null) + { + live = new JObject(); + return true; + } + + if (ConfigSaveText.TryDecode(key, baseFile.Text, out live, out string? error)) + { + return true; + } + + problem = Error(DiagnosticCodes.MergeBaseParseFailed, $"The config save {key} cannot be read: {error}.", key); + return false; + } + + private static bool TryReadModData( + string modId, + TargetEdits target, + ModFile file, + [NotNullWhen(true)] out JToken? content, + List diagnostics) + { + if (!TryParse(file.Text, out content, out string? modError)) + { + diagnostics.Add(Error( + DiagnosticCodes.MergeParseFailed, + $"Mod {modId} file {file.Source} for {target.Key} is not valid JSON ({modError}).", + modId)); + return false; + } + + if (RpgDataSchema.ExpectedRootOf(target.Key) is JTokenType expected && content.Type != expected) + { + diagnostics.Add(Error( + DiagnosticCodes.MergeRootShapeMismatch, + $"Mod {modId} file {file.Source} for {target.Key} has {Describe(content.Type)} at its root, but the game reads {Describe(expected)}.", + modId)); + content = null; + return false; + } + + return true; + } + + private static bool TryApplyPatches(string modId, TargetEdits target, JToken content, List diagnostics) + { + foreach (ModPatch patch in target.Patches) + { + if (content is not JObject root) + { + diagnostics.Add(Error( + DiagnosticCodes.MergePatchShapeMismatch, + $"Mod {modId} patches {target.Key} with an object, but the file's root is not an object.", + modId)); + return false; + } + + ApplyPatch(root, patch.MergeData); + } + + return true; + } + + /// json_patches apply to JSON data and to config saves; on a plugin list or bytes they are a shape mismatch. + private static bool RejectPatches(string modId, TargetEdits target, List diagnostics) + { + if (target.Patches.Count == 0) + { + return true; + } + + diagnostics.Add(Error( + DiagnosticCodes.MergePatchShapeMismatch, + $"Mod {modId} patches {target.Key} with an object, but that file is not a JSON data file.", + modId)); + return false; + } + + /// + /// Groups a mod's edits by file key, in key order. When file_ops names one target twice the later entry + /// wins, as the copy order does; patches apply after the file, in manifest order. A mod that registers plugins + /// changes the plugin list even when it ships no plugins.js. + /// + private static IEnumerable CollectTargets(ModSource mod) + { + var targets = new SortedDictionary(StringComparer.Ordinal); + foreach (ModFile file in mod.Files) + { + TargetEdits target = GetTarget(targets, file.Target); + target.File = file; + } + + foreach (ModPatch patch in mod.Patches) + { + GetTarget(targets, patch.Target).Patches.Add(patch); + } + + if (mod.Plugins.Count > 0) + { + GetTarget(targets, RpgDataSchema.PluginListKey); + } + + return targets.Values; + } + + private static TargetEdits GetTarget(SortedDictionary targets, string path) + { + string key = MergePath.ToKey(path); + if (!targets.TryGetValue(key, out TargetEdits? target)) + { + target = new TargetEdits(key); + targets.Add(key, target); + } + + return target; + } + + /// The json_patches rule of 1.x: objects merge property by property, anything else replaces. + private static void ApplyPatch(JObject target, JObject patch) + { + foreach (JProperty property in patch.Properties()) + { + JProperty? existing = target.Property(property.Name, StringComparison.Ordinal); + if (existing is null) + { + target.Add(property.Name, property.Value.DeepClone()); + } + else if (existing.Value is JObject existingObject && property.Value is JObject patchObject) + { + ApplyPatch(existingObject, patchObject); + } + else + { + existing.Value = property.Value.DeepClone(); + } + } + } + + /// + /// Reads a game file the way every step reads it, so the same fault always gives the same diagnostic and + /// can fold the copies (seam section 11). The subject is the file key. + /// + internal static bool TryReadBase( + BaseFile baseFile, + [NotNullWhen(true)] out JToken? root, + [NotNullWhen(false)] out OperationDiagnostic? problem) + { + string key = MergePath.ToKey(baseFile.Path); + problem = null; + if (!TryParse(baseFile.Text, out root, out string? error)) + { + problem = Error(DiagnosticCodes.MergeBaseParseFailed, $"The game file {key} is not valid JSON ({error}).", key); + return false; + } + + if (RpgDataSchema.ExpectedRootOf(key) is JTokenType expected && root.Type != expected) + { + problem = Error( + DiagnosticCodes.MergeRootShapeMismatch, + $"The game file {key} has {Describe(root.Type)} at its root, but the game reads {Describe(expected)}.", + key); + root = null; + return false; + } + + return true; + } + + private static string Describe(JTokenType type) + { + return type switch + { + JTokenType.Object => "an object", + JTokenType.Array => "an array", + _ => "a value of type " + type.ToString().ToLowerInvariant() + }; + } + + private static bool TryParse(string? text, [NotNullWhen(true)] out JToken? token, out string? error) + { + token = null; + if (text is null) + { + error = "no text"; + return false; + } + + try + { + token = MergeJson.Parse(text); + error = null; + return true; + } + catch (JsonReaderException exception) + { + error = $"line {exception.LineNumber}, position {exception.LinePosition}"; + return false; + } + } + + private static OperationDiagnostic Error(string code, string message, string subject) + { + return new OperationDiagnostic(code, message, DiagnosticSeverity.Error, subject); + } + + private sealed class TargetEdits + { + public TargetEdits(string key) + { + Key = key; + } + + public string Key { get; } + + public ModFile? File { get; set; } + + public List Patches { get; } = new(); + } +} diff --git a/RPGModder.Core/Merge/Collision.cs b/RPGModder.Core/Merge/Collision.cs new file mode 100644 index 0000000..1ddd96d --- /dev/null +++ b/RPGModder.Core/Merge/Collision.cs @@ -0,0 +1,15 @@ +namespace RPGModder.Core.Merge; + +/// +/// Two or more mods that cannot both have their way. Id hashes the place and the mods but no value +/// (GR-X1), so a stored choice survives a mod update; Fingerprint hashes the values (GR-X2). +/// +public sealed record Collision( + string Id, + CollisionKind Kind, + RecordKey Key, + string Path, + IReadOnlyList ModIds, + bool Blocking, + IReadOnlyList Allowed, + string Fingerprint); diff --git a/RPGModder.Core/Merge/CollisionKind.cs b/RPGModder.Core/Merge/CollisionKind.cs new file mode 100644 index 0000000..2461116 --- /dev/null +++ b/RPGModder.Core/Merge/CollisionKind.cs @@ -0,0 +1,17 @@ +namespace RPGModder.Core.Merge; + +public enum CollisionKind +{ + ValueClash, + DeleteVersusEdit, + IdClash, + SequenceClash, + LogicClash, + PageClash, + FileClash, + PluginOrderClash, + OrderAmbiguous, + BaseMismatch, + SwitchBandConflict, + StateIdOverlap +} diff --git a/RPGModder.Core/Merge/CollisionOutcome.cs b/RPGModder.Core/Merge/CollisionOutcome.cs new file mode 100644 index 0000000..6947ec5 --- /dev/null +++ b/RPGModder.Core/Merge/CollisionOutcome.cs @@ -0,0 +1,7 @@ +namespace RPGModder.Core.Merge; + +public sealed record CollisionOutcome( + string CollisionId, + ResolutionSource Source, + ResolutionKind? Kind, + string? ModId); diff --git a/RPGModder.Core/Merge/Composer.cs b/RPGModder.Core/Merge/Composer.cs new file mode 100644 index 0000000..4039bcd --- /dev/null +++ b/RPGModder.Core/Merge/Composer.cs @@ -0,0 +1,668 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using System.Diagnostics; +using System.Globalization; + +namespace RPGModder.Core.Merge; + +/// +/// Composes the change sets of every enabled mod into one plan (guide 3.4) and applies the stored choices +/// (guide 3.5). The result does not depend on the order of the inputs (GR-C4); priority is read only by the two +/// plugin order defaults, which name profile order. Nothing is merged by text, pattern or load order (GR-C11). +/// +public static class Composer +{ + /// + /// The plan, when lane A ran : an IdClash one of its offers settles lists + /// and carries rules.remap_unchecked (GR-R11), and its diagnostics join + /// the plan's. + /// + public static MergePlan Compose( + IReadOnlyList changeSets, + IReadOnlyList resolutions, + BaseFileSet baseFiles, + RemapPlan? remapPlan = null) + { + ArgumentNullException.ThrowIfNull(changeSets); + ArgumentNullException.ThrowIfNull(resolutions); + ArgumentNullException.ThrowIfNull(baseFiles); + + List ordered = changeSets.OrderBy(set => set.ModId, StringComparer.Ordinal).ToList(); + for (int index = 1; index < ordered.Count; index++) + { + if (ordered[index].ModId == ordered[index - 1].ModId) + { + throw new ArgumentException($"Two change sets share the mod id {ordered[index].ModId}.", nameof(changeSets)); + } + } + + var diagnostics = new List(); + foreach (ModChangeSet set in ordered) + { + diagnostics.AddRange(set.Diagnostics); + } + + diagnostics.AddRange(remapPlan?.Diagnostics ?? []); + + // The writer stamps versionId into System.json (C-7), so a broken one must stop the plan here, not there. + BaseFile? system = baseFiles.Find(RpgDataSchema.SystemFileKey); + if (system is not null && !ChangeSetBuilder.TryReadBase(system, out _, out OperationDiagnostic? systemProblem)) + { + diagnostics.Add(systemProblem); + } + + var priorities = ordered.ToDictionary(set => set.ModId, set => set.Priority, StringComparer.Ordinal); + + // One lookup for the whole plan: a large map repaint can give tens of thousands of collisions and choices. + ILookup choices = resolutions.ToLookup(item => item.CollisionId, StringComparer.Ordinal); + var ops = new List(); + var collisions = new List<(Collision Collision, CollisionOutcome Outcome)>(); + IReadOnlyList offers = remapPlan?.Offers ?? []; + foreach (List cluster in Cluster(Group(ordered))) + { + ComposeCluster(cluster, choices, priorities, offers, ops, collisions, diagnostics); + } + + ComposePluginOrder(ops, choices, priorities, collisions, diagnostics); + + ops.Sort((left, right) => ChangeSetBuilder.CompareOps(left.Op, right.Op)); + collisions.Sort((left, right) => string.CompareOrdinal(left.Collision.Id, right.Collision.Id)); + + List allDiagnostics = diagnostics + .Distinct() + .OrderBy(item => item.Code, StringComparer.Ordinal) + .ThenBy(item => item.Subject ?? "", StringComparer.Ordinal) + .ThenBy(item => item.Message, StringComparer.Ordinal) + .ThenBy(item => item.Severity) + .ToList(); + + List outcomes = collisions.Select(item => item.Outcome).ToList(); + bool deployable = allDiagnostics.All(item => item.Severity != DiagnosticSeverity.Error) && + collisions.All(item => !item.Collision.Blocking || item.Outcome.Source != ResolutionSource.Unresolved); + + return new MergePlan( + ops, + collisions.Select(item => item.Collision).ToList(), + outcomes, + allDiagnostics, + deployable, + Hash(ops, outcomes)); + } + + /// GR-C1: ops on one key and path, with equal ops folded into one variant. + private static List Group(List ordered) + { + var groups = new Dictionary<(string File, string Record, string Path), OpGroup>(); + foreach (ModChangeSet set in ordered) + { + foreach (ChangeOp op in set.Ops) + { + var key = (op.Key.File, op.Key.Record, op.Path); + if (!groups.TryGetValue(key, out OpGroup? group)) + { + group = new OpGroup(op.Key, op.Path); + groups.Add(key, group); + } + + group.Add(op, set.ModId); + } + } + + return groups.Values.ToList(); + } + + /// + /// GR-C2: a group joins the outermost group whose place contains it: a whole-file value, else the shortest + /// ancestor path in the same record. The head comes first in each cluster, the rest follow in place order. + /// + private static List> Cluster(IReadOnlyList groups) + { + var byPlace = new Dictionary<(string File, string Record, string Path), OpGroup>(); + foreach (OpGroup group in groups) + { + byPlace.Add((group.Key.File, group.Key.Record, group.Path), group); + } + + var clusters = new List>(); + var clusterOfHead = new Dictionary>(); + IEnumerable inPlaceOrder = groups + .OrderBy(group => group.Key.File, StringComparer.Ordinal) + .ThenBy(group => group.Key.Record, StringComparer.Ordinal) + .ThenBy(group => group.Path, StringComparer.Ordinal); + foreach (OpGroup group in inPlaceOrder) + { + OpGroup head = HeadOf(group, byPlace); + if (!clusterOfHead.TryGetValue(head, out List? cluster)) + { + cluster = [head]; + clusterOfHead.Add(head, cluster); + clusters.Add(cluster); + } + + if (!ReferenceEquals(group, head)) + { + cluster.Add(group); + } + } + + return clusters; + } + + private static OpGroup HeadOf(OpGroup group, Dictionary<(string File, string Record, string Path), OpGroup> byPlace) + { + if (byPlace.TryGetValue((group.Key.File, RecordKey.WholeFile, ""), out OpGroup? wholeFile)) + { + return wholeFile; + } + + foreach (string ancestor in MergePath.Ancestors(group.Path)) + { + if (byPlace.TryGetValue((group.Key.File, group.Key.Record, ancestor), out OpGroup? found)) + { + return found; + } + } + + return group; + } + + private static void ComposeCluster( + List cluster, + ILookup choices, + Dictionary priorities, + IReadOnlyList offers, + List ops, + List<(Collision, CollisionOutcome)> collisions, + List diagnostics) + { + List mods = cluster + .SelectMany(group => group.Variants) + .SelectMany(variant => variant.ModIds) + .Distinct() + .OrderBy(id => id, StringComparer.Ordinal) + .ToList(); + + bool clash = cluster.Count == 1 ? cluster[0].Variants.Count > 1 : mods.Count > 1; + if (!clash) + { + foreach (OpGroup group in cluster) + { + ops.AddRange(group.Variants.Select(variant => variant.ToMergedOp())); + } + + return; + } + + Collision collision = OfferRemaps(MakeCollision(cluster, mods), offers, diagnostics); + CollisionOutcome outcome = Decide(collision, choices, diagnostics); + collisions.Add((collision, outcome)); + + ResolutionKind? kind = outcome.Source == ResolutionSource.Unresolved ? null : outcome.Kind; + switch (kind) + { + case null: + case ResolutionKind.PickVanilla: + // Unresolved: the plan is not deployable and the clashing ops are described by the collision. + break; + case ResolutionKind.PickMod when cluster.Count > 1 && !IsHeadMod(cluster[0], outcome.ModId!): + // Choosing a change inside the head keeps every inner change: only the head is dropped, and the + // inner ops are composed again, so a clash among them becomes a collision of its own (seam 11). + foreach (List inner in Cluster(cluster.Skip(1).ToList())) + { + ComposeCluster(inner, choices, priorities, offers, ops, collisions, diagnostics); + } + + break; + case ResolutionKind.KeepBothInProfileOrder when collision.Kind == CollisionKind.PluginOrderClash: + // The anchors apply in profile order, so the last one wins (seam 11.1). An OrderAmbiguous + // collision is composed after the clusters, by ComposePluginOrder. + ops.Add(LatestInProfileOrder(cluster[0], priorities).ToMergedOp()); + break; + case ResolutionKind.PickMod: + foreach (OpGroup group in cluster) + { + ops.AddRange(group.Variants + .Where(variant => variant.ModIds.Contains(outcome.ModId!, StringComparer.Ordinal)) + .Select(variant => variant.ToMergedOp())); + } + + break; + default: + // Decide accepts only kinds in Allowed, and no cluster kind of 2a allows another choice. + throw new UnreachableException($"Resolution {kind} is not applied to {collision.Kind}."); + } + } + + /// The variant of the mod latest in profile order; equal priorities fall back to the mod id that sorts last. + private static Variant LatestInProfileOrder(OpGroup group, Dictionary priorities) + { + return group.Variants + .OrderByDescending(variant => variant.ModIds.Max(id => priorities[id])) + .ThenByDescending(variant => variant.ModIds.Max(StringComparer.Ordinal), StringComparer.Ordinal) + .First(); + } + + /// + /// GR-C10: entries from more than one mod behind one anchor are an OrderAmbiguous collision (seam 11.1), + /// settled here, after every cluster, because the anchors are only final once each PluginOrderClash is. + /// The chosen order is written back as a chain, so each @after names the entry placed right before it. + /// A null anchor sends a new entry to the end and a moved entry to the front, so each forms its own group: + /// @after on * for the end, @first on * for the front. + /// + private static void ComposePluginOrder( + List ops, + ILookup choices, + Dictionary priorities, + List<(Collision, CollisionOutcome)> collisions, + List diagnostics) + { + var added = new HashSet(StringComparer.Ordinal); + foreach (MergedOp merged in ops) + { + ChangeOp op = merged.Op; + if (op.Key.File == RpgDataSchema.PluginListKey && op.Kind == ChangeKind.AddRecord && !op.Key.IsWholeFile) + { + added.Add(op.Key.Record); + } + } + + var byAnchor = new SortedDictionary<(string Record, string Path), List>(Comparer<(string Record, string Path)>.Create( + (left, right) => + { + int byRecord = string.CompareOrdinal(left.Record, right.Record); + return byRecord != 0 ? byRecord : string.CompareOrdinal(left.Path, right.Path); + })); + var afterOps = new List(); + for (int index = 0; index < ops.Count; index++) + { + ChangeOp op = ops[index].Op; + if (op.Key.File != RpgDataSchema.PluginListKey || op.Path != MergePath.AfterLeaf) + { + continue; + } + + afterOps.Add(index); + + string? anchor = op.Value?.Type == JTokenType.String ? op.Value.Value() : null; + (string Record, string Path) place = anchor is not null + ? (RecordKey.ForPlugin(anchor), MergePath.AfterLeaf) + : (RecordKey.WholeFile, added.Contains(op.Key.Record) ? MergePath.AfterLeaf : MergePath.FirstLeaf); + if (!byAnchor.TryGetValue(place, out List? entries)) + { + entries = new List(); + byAnchor.Add(place, entries); + } + + entries.Add(index); + } + + foreach (((string anchorRecord, string path), List entries) in byAnchor) + { + List mods = entries + .SelectMany(index => ops[index].ModIds) + .Distinct() + .OrderBy(id => id, StringComparer.Ordinal) + .ToList(); + if (entries.Count < 2 || mods.Count < 2) + { + continue; + } + + var key = new RecordKey(RpgDataSchema.PluginListKey, anchorRecord); + string id = CollisionId(CollisionKind.OrderAmbiguous, key, path, mods); + var collision = new Collision( + id, + CollisionKind.OrderAmbiguous, + key, + path, + mods, + IsBlocking(CollisionKind.OrderAmbiguous), + AllowedFor(CollisionKind.OrderAmbiguous), + OrderFingerprint(ops, entries)); + CollisionOutcome outcome = Decide(collision, choices, diagnostics); + collisions.Add((collision, outcome)); + + string? first = outcome.Kind == ResolutionKind.PickMod ? outcome.ModId : null; + List placed = entries + .OrderBy(index => first is not null && ops[index].ModIds.Contains(first, StringComparer.Ordinal) ? 0 : 1) + .ThenBy(index => ops[index].ModIds.Min(mod => priorities[mod])) + .ThenBy(index => ops[index].Op.Key.Record, StringComparer.Ordinal) + .ToList(); + + for (int position = 1; position < placed.Count; position++) + { + MergedOp merged = ops[placed[position]]; + string before = RunTail(ops, afterOps, ops[placed[position - 1]]); + ops[placed[position]] = merged with { Op = merged.Op with { Value = new JValue(before) } }; + } + } + } + + /// + /// The last entry of the run that starts at : each next entry is anchored on the one + /// before and comes from the same mods, so a mod's own run of plugins is never split by another mod's. + /// + private static string RunTail(List ops, List afterOps, MergedOp start) + { + RecordKey.TryGetPlugin(start.Op.Key.Record, out string tail); + var seen = new HashSet(StringComparer.Ordinal) { tail }; + while (true) + { + MergedOp? next = afterOps.Select(index => ops[index]).FirstOrDefault(merged => + merged.Op.Value?.Type == JTokenType.String && + merged.Op.Value.Value() == tail && + merged.ModIds.SequenceEqual(start.ModIds, StringComparer.Ordinal)); + if (next is null || !RecordKey.TryGetPlugin(next.Op.Key.Record, out string name) || !seen.Add(name)) + { + return tail; + } + + tail = name; + } + } + + /// GR-X2 for an order collision: the entries behind the anchor and their mods, by record. + private static string OrderFingerprint(List ops, List entries) + { + var items = new JArray(); + foreach (MergedOp merged in entries.Select(index => ops[index]).OrderBy(item => item.Op.Key.Record, StringComparer.Ordinal)) + { + items.Add(new JArray(merged.Op.Key.Record, new JArray(merged.ModIds.ToArray()))); + } + + return MergeJson.Sha256Hex(MergeJson.Write(items)); + } + + /// + /// GR-R11: an IdClash an offer settles lists Remap, stays blocking and has no default, and each + /// offer carries the warning once, though a map offer settles two collisions (its file and its tree record). + /// Lane A carries a chosen Remap out by recording the offer (seam 4.3). + /// + private static Collision OfferRemaps(Collision collision, IReadOnlyList offers, List diagnostics) + { + List settling = offers.Where(offer => RemapPlaces.Settles(offer, collision)).ToList(); + if (settling.Count == 0) + { + return collision; + } + + foreach (IdRemap offer in settling) + { + diagnostics.Add(new OperationDiagnostic( + DiagnosticCodes.RulesRemapUnchecked, + string.Create( + CultureInfo.InvariantCulture, + $"Mod {offer.ModId}: {offer.Kind} {offer.FromId}{(offer.Kind == IdKind.MapEvent ? " in " + offer.Scope : "")} can move to {offer.ToId} to settle its id clash, but a plugin file the mod ships contains that number."), + DiagnosticSeverity.Warning, + offer.ModId)); + } + + // Declaration order, so Remap sits between the choices the collision already allows. + return collision with { Allowed = collision.Allowed.Append(ResolutionKind.Remap).Distinct().Order().ToList() }; + } + + private static bool IsHeadMod(OpGroup head, string modId) + { + return head.Variants.Any(variant => variant.ModIds.Contains(modId, StringComparer.Ordinal)); + } + + private static Collision MakeCollision(List cluster, List mods) + { + OpGroup head = cluster[0]; + List all = cluster.SelectMany(group => group.Variants).Select(variant => variant.Op).ToList(); + + CollisionKind kind; + if (all.All(op => op.Kind == ChangeKind.ReplaceFile)) + { + kind = CollisionKind.FileClash; + } + else if (all.Any(op => op.Kind == ChangeKind.RemoveRecord)) + { + kind = CollisionKind.DeleteVersusEdit; + } + else if (all.All(op => op.Kind == ChangeKind.AddRecord)) + { + kind = CollisionKind.IdClash; + } + else if (cluster.Count == 1 && head.Path == MergePath.AfterLeaf) + { + kind = CollisionKind.PluginOrderClash; + } + else if (RpgDataSchema.IsPageSetting(head.Key, head.Path)) + { + kind = CollisionKind.PageClash; + } + else if (cluster.Count == 1 && all.All(op => op.Kind == ChangeKind.EditSequence)) + { + kind = CollisionKind.SequenceClash; + } + else if (cluster.Count == 1 && all.All(op => op.Kind == ChangeKind.EditCommands)) + { + kind = CollisionKind.LogicClash; + } + else + { + kind = CollisionKind.ValueClash; + } + + // A mod with two variants of one place clashes with itself: a recorded remap moved an id onto one the mod now + // adds as well. Picking that mod would keep both ops, so it is not a choice (seam 11.2). + IReadOnlyList allowed = AllowedFor(kind); + if (cluster.Any(group => group.Variants.SelectMany(variant => variant.ModIds).GroupBy(modId => modId, StringComparer.Ordinal).Any(ids => ids.Count() > 1))) + { + allowed = allowed.Where(item => item != ResolutionKind.PickMod).ToList(); + } + + string id = CollisionId(kind, head.Key, head.Path, mods); + return new Collision(id, kind, head.Key, head.Path, mods, IsBlocking(kind), allowed, Fingerprint(cluster)); + } + + /// + /// GR-X1: the first 16 hex characters of SHA-256 over the kind, file, record, path and sorted mod ids, one per + /// line. No value takes part, so a mod update keeps the player's choice. + /// + internal static string CollisionId(CollisionKind kind, RecordKey key, string path, IReadOnlyList sortedModIds) + { + var lines = new List { kind.ToString(), key.File, key.Record, path }; + lines.AddRange(sortedModIds); + return MergeJson.Sha256Hex(string.Join('\n', lines))[..16]; + } + + /// GR-X2: a hash of every colliding value, by place and by mod. + private static string Fingerprint(List cluster) + { + var entries = new JArray(); + foreach (OpGroup group in cluster.OrderBy(item => item.Key.Record, StringComparer.Ordinal).ThenBy(item => item.Path, StringComparer.Ordinal)) + { + foreach (Variant variant in group.Variants) + { + entries.Add(new JArray( + group.Key.Record, + group.Path, + variant.Op.Kind.ToString(), + variant.Op.Value is null ? new JArray() : new JArray(variant.Op.Value.DeepClone()), + new JArray(variant.ModIds.ToArray()))); + } + } + + return MergeJson.Sha256Hex(MergeJson.Write(entries)); + } + + private static CollisionOutcome Decide(Collision collision, ILookup choices, List diagnostics) + { + Resolution? stored = choices[collision.Id] + .Where(item => IsApplicable(item, collision)) + .OrderBy(item => item.Kind) + .ThenBy(item => item.ModId ?? "", StringComparer.Ordinal) + .ThenBy(item => item.Fingerprint ?? "", StringComparer.Ordinal) + .FirstOrDefault(); + + if (stored is not null) + { + string? modId = stored.Kind == ResolutionKind.PickMod ? stored.ModId : null; + + // A choice stored without a fingerprint cannot be checked against the content, so it is taken as made. + if (stored.Fingerprint is null || stored.Fingerprint == collision.Fingerprint) + { + return new CollisionOutcome(collision.Id, ResolutionSource.Profile, stored.Kind, modId); + } + + diagnostics.Add(new OperationDiagnostic( + DiagnosticCodes.RulesResolutionReused, + $"A stored choice for collision {collision.Id} was applied to content that changed since it was made.", + DiagnosticSeverity.Info, + collision.Id)); + return new CollisionOutcome(collision.Id, ResolutionSource.ProfileReused, stored.Kind, modId); + } + + ResolutionKind? fallback = DefaultFor(collision.Kind); + return fallback is null + ? new CollisionOutcome(collision.Id, ResolutionSource.Unresolved, null, null) + : new CollisionOutcome(collision.Id, ResolutionSource.Default, fallback, null); + } + + /// + /// A stored choice applies when its kind is allowed for the collision and Compose carries it out (seam 4.3), + /// and a PickMod names one of the collision's mods. Anything else leaves the collision unresolved, so the + /// player chooses again. + /// + private static bool IsApplicable(Resolution resolution, Collision collision) + { + if (resolution.Kind is ResolutionKind.DisableMod or ResolutionKind.Remap || + !collision.Allowed.Contains(resolution.Kind)) + { + return false; + } + + return resolution.Kind != ResolutionKind.PickMod || + (resolution.ModId is not null && collision.ModIds.Contains(resolution.ModId, StringComparer.Ordinal)); + } + + /// The "Blocks deploy until resolved" column of guide 3.5, for slice 2a. + private static bool IsBlocking(CollisionKind kind) + { + return kind switch + { + CollisionKind.ValueClash or CollisionKind.DeleteVersusEdit or CollisionKind.IdClash or CollisionKind.SequenceClash + or CollisionKind.LogicClash or CollisionKind.PageClash or CollisionKind.FileClash + or CollisionKind.BaseMismatch => true, + CollisionKind.PluginOrderClash or CollisionKind.OrderAmbiguous + or CollisionKind.SwitchBandConflict or CollisionKind.StateIdOverlap => false, + _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "A collision kind guide 3.5 does not list.") + }; + } + + /// + /// The "Allowed resolutions" column of guide 3.5 for slice 2a, in declaration order. Remap is added by + /// (2r) and Gate comes with 2c; a SwitchBandConflict is settled by moving the band, never by a choice. + /// + private static IReadOnlyList AllowedFor(CollisionKind kind) + { + return kind switch + { + CollisionKind.ValueClash or CollisionKind.DeleteVersusEdit or CollisionKind.SequenceClash + or CollisionKind.LogicClash or CollisionKind.PageClash => [ResolutionKind.PickMod, ResolutionKind.PickVanilla], + CollisionKind.IdClash => [ResolutionKind.PickMod, ResolutionKind.DisableMod], + CollisionKind.FileClash => [ResolutionKind.PickMod], + CollisionKind.PluginOrderClash or CollisionKind.OrderAmbiguous => [ResolutionKind.PickMod, ResolutionKind.KeepBothInProfileOrder], + CollisionKind.BaseMismatch => [ResolutionKind.Accept, ResolutionKind.DisableMod], + CollisionKind.SwitchBandConflict => [], + CollisionKind.StateIdOverlap => [ResolutionKind.Accept], + _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "A collision kind guide 3.5 does not list.") + }; + } + + /// + /// The "Default" column of guide 3.5 for slice 2a. Only the order kinds and StateIdOverlap have one; a + /// BaseMismatch waits for the player to accept that mod (owner decision, 2026-11-12). + /// + private static ResolutionKind? DefaultFor(CollisionKind kind) + { + return kind switch + { + CollisionKind.PluginOrderClash or CollisionKind.OrderAmbiguous => ResolutionKind.KeepBothInProfileOrder, + CollisionKind.StateIdOverlap => ResolutionKind.Accept, + _ => null + }; + } + + /// Lane B's half of GR-C9 and TST-5: SHA-256 over a canonical form of the ops and the outcomes. + private static string Hash(List ops, List outcomes) + { + var opEntries = new JArray(); + foreach (MergedOp merged in ops) + { + ChangeOp op = merged.Op; + opEntries.Add(new JArray( + op.Key.File, + op.Key.Record, + op.Path, + op.Kind.ToString(), + op.Value is null ? new JArray() : new JArray(op.Value.DeepClone()), + Text(op.SourceFile), + new JArray(merged.ModIds.ToArray()))); + } + + var outcomeEntries = new JArray(); + foreach (CollisionOutcome outcome in outcomes) + { + outcomeEntries.Add(new JArray( + outcome.CollisionId, + outcome.Source.ToString(), + Text(outcome.Kind?.ToString()), + Text(outcome.ModId))); + } + + var root = new JArray(RpgDataSchema.SchemaVersion.ToString(CultureInfo.InvariantCulture), opEntries, outcomeEntries); + return MergeJson.Sha256Hex(MergeJson.Write(root)); + } + + private static JValue Text(string? value) + { + return value is null ? JValue.CreateNull() : new JValue(value); + } + + private sealed class OpGroup + { + public OpGroup(RecordKey key, string path) + { + Key = key; + Path = path; + } + + public RecordKey Key { get; } + + public string Path { get; } + + public List Variants { get; } = new(); + + /// Ops arrive in mod id order, so each variant's op is the one of the mod whose id sorts first. + public void Add(ChangeOp op, string modId) + { + foreach (Variant variant in Variants) + { + if (variant.Op.Kind == op.Kind && ValuesEqual(variant.Op.Value, op.Value)) + { + variant.ModIds.Add(modId); + return; + } + } + + Variants.Add(new Variant(op, [modId])); + } + + private static bool ValuesEqual(JToken? left, JToken? right) + { + return left is null ? right is null : right is not null && JToken.DeepEquals(left, right); + } + } + + private sealed record Variant(ChangeOp Op, List ModIds) + { + public MergedOp ToMergedOp() + { + return new MergedOp(Op, ModIds.ToList()); + } + } +} diff --git a/RPGModder.Core/Merge/ConfigSaveText.cs b/RPGModder.Core/Merge/ConfigSaveText.cs new file mode 100644 index 0000000..5345209 --- /dev/null +++ b/RPGModder.Core/Merge/ConfigSaveText.cs @@ -0,0 +1,121 @@ +using LZStringCSharp; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System.Diagnostics.CodeAnalysis; +using System.IO.Compression; +using System.Text; + +namespace RPGModder.Core.Merge; + +/// +/// The config saves 2a decodes (GR-M10), each holding one JSON object in the form the game's +/// StorageManager writes: +/// +/// MV config.rpgsave: LZ-String base64 of the JSON text. +/// MZ config.rmmzsave: the zlib deflate of the UTF-8 JSON, each byte one character (pako's binary +/// string), and that text stored as UTF-8. Checked against the MZ editor's new-project scripts. +/// +/// Input that does not decode is refused, never guessed, so the text is checked before and after each step. +/// +internal static class ConfigSaveText +{ + private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + + /// A key accepts; it picks the form. + public static bool TryDecode(string fileKey, string? text, [NotNullWhen(true)] out JObject? config, [NotNullWhen(false)] out string? error) + { + config = null; + string? json = RpgDataSchema.IsMzConfigSave(fileKey) ? InflateMz(text, out error) : DecompressMv(text, out error); + if (json is null) + { + error ??= "it does not decode"; + return false; + } + + try + { + config = MergeJson.Parse(json) as JObject; + } + catch (JsonReaderException exception) + { + error = $"it decodes to text that is not valid JSON (line {exception.LineNumber}, position {exception.LinePosition})"; + return false; + } + + error = config is null ? "it decodes to JSON that is not an object" : null; + return config is not null; + } + + public static string Encode(string fileKey, JObject config) + { + string json = MergeJson.Write(config); + if (!RpgDataSchema.IsMzConfigSave(fileKey)) + { + return LZString.CompressToBase64(json); + } + + using var buffer = new MemoryStream(); + using (var zlib = new ZLibStream(buffer, CompressionLevel.Fastest, leaveOpen: true)) + { + zlib.Write(StrictUtf8.GetBytes(json)); + } + + // Latin-1 maps byte n to character n, the binary string pako's deflate returns. + return Encoding.Latin1.GetString(buffer.ToArray()); + } + + private static string? DecompressMv(string? text, out string? error) + { + error = null; + string encoded = text?.Trim() ?? ""; + if (encoded.Length == 0 || !encoded.All(IsBase64Char)) + { + error = "it is not LZ-String base64"; + return null; + } + + try + { + string? json = LZString.DecompressFromBase64(encoded); + return string.IsNullOrEmpty(json) ? null : json; + } + catch (Exception exception) when (exception is IndexOutOfRangeException or KeyNotFoundException) + { + // The library's own faults on a truncated or foreign text; both mean "does not decode". + return null; + } + } + + private static string? InflateMz(string? text, out string? error) + { + error = null; + if (string.IsNullOrEmpty(text) || text.Any(current => current > byte.MaxValue)) + { + error = "it is not a zlib byte string"; + return null; + } + + try + { + using var input = new MemoryStream(Encoding.Latin1.GetBytes(text)); + using var zlib = new ZLibStream(input, CompressionMode.Decompress); + using var output = new MemoryStream(); + zlib.CopyTo(output); + return output.Length == 0 ? null : StrictUtf8.GetString(output.ToArray()); + } + catch (InvalidDataException) + { + return null; + } + catch (DecoderFallbackException) + { + error = "it decodes to bytes that are not UTF-8"; + return null; + } + } + + private static bool IsBase64Char(char current) + { + return char.IsAsciiLetterOrDigit(current) || current is '+' or '/' or '='; + } +} diff --git a/RPGModder.Core/Merge/DataDiff.cs b/RPGModder.Core/Merge/DataDiff.cs new file mode 100644 index 0000000..e117481 --- /dev/null +++ b/RPGModder.Core/Merge/DataDiff.cs @@ -0,0 +1,240 @@ +using Newtonsoft.Json.Linq; + +namespace RPGModder.Core.Merge; + +/// +/// The schema-driven walker: compares one mod's version of a data file with vanilla and returns the ops +/// (GR-M1, guide 3.3). Every decision about a file or a path comes from . +/// +internal sealed class DataDiff +{ + private readonly string _modId; + private readonly string _fileKey; + private readonly string? _sourceFile; + private readonly List _ops = new(); + + private DataDiff(string modId, string fileKey, string? sourceFile) + { + _modId = modId; + _fileKey = fileKey; + _sourceFile = sourceFile; + } + + public static IReadOnlyList Compare(string modId, string fileKey, string? sourceFile, JToken vanilla, JToken modded) + { + var diff = new DataDiff(modId, fileKey, sourceFile); + diff.CompareRoot(vanilla, modded); + return diff._ops; + } + + /// The leaves of one record that lives outside a data file: a $plugins entry. + public static IReadOnlyList CompareRecord(string modId, string fileKey, string? sourceFile, string record, JObject vanilla, JObject modded) + { + var diff = new DataDiff(modId, fileKey, sourceFile); + diff.CompareObject(record, "", vanilla, modded); + return diff._ops; + } + + private void CompareRoot(JToken vanilla, JToken modded) + { + if (JToken.DeepEquals(vanilla, modded)) + { + return; + } + + if (vanilla.Type != modded.Type) + { + // A root of another type has no record to line up with vanilla: one value for the whole file. + Add(RecordKey.WholeFile, "", ChangeKind.SetLeaf, modded); + return; + } + + switch (RpgDataSchema.ShapeOf(_fileKey, vanilla)) + { + case RootShape.Records: + CompareRecords((JArray)vanilla, (JArray)modded, RecordKey.ForIndex); + break; + case RootShape.Map: + CompareMap((JObject)vanilla, (JObject)modded); + break; + case RootShape.Object: + CompareObject(RecordKey.WholeFile, "", (JObject)vanilla, (JObject)modded); + break; + default: + Add(RecordKey.WholeFile, "", ChangeKind.SetLeaf, modded); + break; + } + } + + /// + /// A map is an object whose events are records of their own (guide 3.3). When vanilla's events are not + /// a record list, events is one more map-level value. The builder refuses a mod whose events are not a + /// list while vanilla's are; the second test below only keeps a direct call safe. + /// + private void CompareMap(JObject vanilla, JObject modded) + { + JToken? vanillaEvents = vanilla[RpgDataSchema.EventsProperty]; + if (!RpgDataSchema.IsEventList(vanillaEvents) || modded[RpgDataSchema.EventsProperty] is not JArray moddedEvents) + { + CompareObject(RecordKey.WholeFile, "", vanilla, modded); + return; + } + + CompareObject(RecordKey.WholeFile, "", vanilla, modded, RpgDataSchema.EventsProperty); + CompareRecords((JArray)vanillaEvents!, moddedEvents, RecordKey.ForEvent); + } + + private void CompareRecords(JArray vanilla, JArray modded, Func recordOf) + { + int count = Math.Max(vanilla.Count, modded.Count); + for (int index = 0; index < count; index++) + { + JToken? before = RecordAt(vanilla, index); + JToken? after = RecordAt(modded, index); + string record = recordOf(index); + + if (before is null && after is null) + { + continue; + } + + if (before is null) + { + Add(record, "", ChangeKind.AddRecord, after); + } + else if (after is null) + { + Add(record, "", ChangeKind.RemoveRecord, null); + } + else if (before is JObject beforeRecord && after is JObject afterRecord) + { + CompareObject(record, "", beforeRecord, afterRecord); + } + else if (!JToken.DeepEquals(before, after)) + { + // A record that is not an object has no leaves: it is one value. + Add(record, "", ChangeKind.SetLeaf, after); + } + } + } + + /// names a property compared elsewhere, as a map's events. + private void CompareObject(string record, string path, JObject vanilla, JObject modded, string? skipped = null) + { + foreach (JProperty property in modded.Properties()) + { + if (property.Name == skipped || RpgDataSchema.IsVolatile(_fileKey, path, property.Name)) + { + continue; + } + + string child = MergePath.Child(path, property.Name); + JProperty? original = vanilla.Property(property.Name, StringComparison.Ordinal); + if (original is null) + { + Add(record, child, ChangeKind.SetLeaf, property.Value); + } + else + { + CompareValue(record, child, original.Value, property.Value); + } + } + + foreach (JProperty property in vanilla.Properties()) + { + if (property.Name == skipped || + RpgDataSchema.IsVolatile(_fileKey, path, property.Name) || + modded.Property(property.Name, StringComparison.Ordinal) is not null) + { + continue; + } + + Add(record, MergePath.Child(path, property.Name), ChangeKind.RemoveLeaf, null); + } + } + + private void CompareValue(string record, string path, JToken vanilla, JToken modded) + { + if (JToken.DeepEquals(vanilla, modded)) + { + return; + } + + if (vanilla is JObject vanillaObject && modded is JObject moddedObject && !RpgDataSchema.IsAtomicObject(_fileKey, path)) + { + CompareObject(record, path, vanillaObject, moddedObject); + return; + } + + if (vanilla is JArray vanillaArray && modded is JArray moddedArray) + { + CompareArray(record, path, vanillaArray, moddedArray); + return; + } + + Add(record, path, ChangeKind.SetLeaf, modded); + } + + private void CompareArray(string record, string path, JArray vanilla, JArray modded) + { + switch (RpgDataSchema.PolicyOf(_fileKey, path)) + { + case ArrayPolicy.Sequence: + Add(record, path, ChangeKind.EditSequence, modded); + break; + case ArrayPolicy.Commands: + Add(record, path, ChangeKind.EditCommands, modded); + break; + case ArrayPolicy.Positional when vanilla.Count == modded.Count: + for (int index = 0; index < vanilla.Count; index++) + { + CompareValue(record, MergePath.Index(path, index), vanilla[index], modded[index]); + } + + break; + case ArrayPolicy.Keyed: + CompareKeyed(record, path, vanilla, modded); + break; + default: + // Atomic, and a Positional array whose length changed (one value until GR-K4 in 2b). + Add(record, path, ChangeKind.SetLeaf, modded); + break; + } + } + + private void CompareKeyed(string record, string path, JArray vanilla, JArray modded) + { + int count = Math.Max(vanilla.Count, modded.Count); + for (int index = 0; index < count; index++) + { + string child = MergePath.Index(path, index); + if (index >= modded.Count) + { + Add(record, child, ChangeKind.RemoveLeaf, null); + } + else if (index >= vanilla.Count) + { + Add(record, child, ChangeKind.SetLeaf, modded[index]); + } + else + { + CompareValue(record, child, vanilla[index], modded[index]); + } + } + } + + private void Add(string record, string path, ChangeKind kind, JToken? value) + { + _ops.Add(new ChangeOp(_modId, new RecordKey(_fileKey, record), path, kind, value?.DeepClone(), _sourceFile)); + } + + private static JToken? RecordAt(JArray array, int index) + { + if (index >= array.Count || array[index].Type == JTokenType.Null) + { + return null; + } + + return array[index]; + } +} diff --git a/RPGModder.Core/Merge/IdKind.cs b/RPGModder.Core/Merge/IdKind.cs new file mode 100644 index 0000000..e77da9d --- /dev/null +++ b/RPGModder.Core/Merge/IdKind.cs @@ -0,0 +1,22 @@ +namespace RPGModder.Core.Merge; + +/// The kinds of id a mod can add and a remap can move (guide 3.11). Step 1 moves MapEvent and Map. +public enum IdKind +{ + MapEvent, + Map, + Item, + Weapon, + Armor, + Skill, + State, + Enemy, + Troop, + CommonEvent, + Actor, + Class, + Animation, + Tileset, + Switch, + Variable +} diff --git a/RPGModder.Core/Merge/IdRemap.cs b/RPGModder.Core/Merge/IdRemap.cs new file mode 100644 index 0000000..b75187b --- /dev/null +++ b/RPGModder.Core/Merge/IdRemap.cs @@ -0,0 +1,12 @@ +namespace RPGModder.Core.Merge; + +/// +/// One mod's added id moved to another (guide 3.11). Scope is the map file key for +/// (data/map012.json) and empty for every other kind. The profile keeps these append-only (GR-R12). +/// +public sealed record IdRemap( + string ModId, + IdKind Kind, + string Scope, + int FromId, + int ToId); diff --git a/RPGModder.Core/Merge/IdRemapPlanner.cs b/RPGModder.Core/Merge/IdRemapPlanner.cs new file mode 100644 index 0000000..8faae1b --- /dev/null +++ b/RPGModder.Core/Merge/IdRemapPlanner.cs @@ -0,0 +1,366 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using RPGModder.Core.Services; +using System.Globalization; + +namespace RPGModder.Core.Merge; + +/// +/// Decides which added ids move before composition (guide 3.11, GR-R3 to GR-R12). Step 1 plans the +/// and kinds. The result does not depend on the order of any +/// input. +/// +public static class IdRemapPlanner +{ + /// Every installed mod, enabled or not, once each. + /// The profile's Remaps, every entry, active or not. + /// The profile's DeployedMods (GR-R4). + /// + /// Vanilla's files, for the ids vanilla uses (GR-R5): the map file of every map that gets an event, and, when a + /// mod adds a map, data/MapInfos.json and every vanilla map file, listed in the tree or not. A clash whose + /// base file is missing cannot move, and a map id whose file vanilla has is never a target and never moves. + /// + /// + /// The game's engine, which sets the highest map id a move may give (GR-R6): 2000 for MZ, 999 for MV and for an + /// unknown engine (null). + /// + public static RemapPlan Plan( + IReadOnlyList installed, + IReadOnlyList recorded, + IReadOnlyCollection deployedMods, + BaseFileSet baseFiles, + RpgMakerEngine? engine) + { + ArgumentNullException.ThrowIfNull(installed); + ArgumentNullException.ThrowIfNull(recorded); + ArgumentNullException.ThrowIfNull(deployedMods); + ArgumentNullException.ThrowIfNull(baseFiles); + + List mods = installed.OrderBy(mod => mod.ChangeSet.ModId, StringComparer.Ordinal).ToList(); + for (int index = 1; index < mods.Count; index++) + { + if (mods[index].ChangeSet.ModId == mods[index - 1].ChangeSet.ModId) + { + throw new ArgumentException($"Two installed mods share the mod id {mods[index].ChangeSet.ModId}.", nameof(installed)); + } + } + + var added = mods.ToDictionary(mod => mod.ChangeSet.ModId, mod => AddedIdIndex.Of(mod.ChangeSet), StringComparer.Ordinal); + var deployed = new HashSet(deployedMods, StringComparer.Ordinal); + var diagnostics = new List(); + Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int> pins = Pins(mods, added, recorded, baseFiles, diagnostics); + + var claims = new List(); + foreach (RemapMod mod in mods.Where(item => item.Enabled)) + { + string modId = mod.ChangeSet.ModId; + foreach (AddedId id in added[modId]) + { + bool pinned = pins.TryGetValue((modId, id.Kind, id.Scope, id.Id), out int toId); + claims.Add(new Claim(mod, id, pinned ? toId : id.Id, pinned, deployed.Contains(modId))); + } + } + + var targets = new Targets(added.Values.SelectMany(list => list).ToList(), recorded, baseFiles, engine); + var references = new Dictionary(StringComparer.Ordinal); + var moves = new List(); + var offers = new List(); + IEnumerable> groups = claims + .GroupBy(claim => (Kind: claim.Added.Kind, Scope: claim.Added.Scope, Id: claim.Effective)) + .OrderBy(group => group.Key.Kind) + .ThenBy(group => group.Key.Scope, StringComparer.Ordinal) + .ThenBy(group => group.Key.Id); + foreach (IGrouping<(IdKind Kind, string Scope, int Id), Claim> group in groups) + { + List parties = Partition(group); + if (parties.Count < 2) + { + continue; + } + + (IdKind kind, string scope, _) = group.Key; + foreach (Party party in parties) + { + party.Classify(kind, claim => ReferencesOf(claim.Mod, references), claim => IsVanillaMapFile(kind, claim.Added.Id, baseFiles)); + } + + // GR-R4 and GR-R10: the parties that cannot move stay; when every party can, the first in order stays. + List staying = parties.Where(party => !party.CanMove).ToList(); + if (staying.Count == 0) + { + staying.Add(parties[0]); + } + else if (staying.All(party => party.IsUnchecked)) + { + // GR-R4 before GR-R11 (the owner, 2026-11-12): a party in DeployedMods does not move to make room + // for parties only a plugin file holds. It stays too, and the player is offered their move. + staying.AddRange(parties.Except(staying).Where(party => party.Rank == 1)); + } + + foreach (Party party in parties.Except(staying).ToList()) + { + int? target = targets.Take(kind, scope); + if (target is null) + { + // GR-R6: past the editor's limit, or vanilla's ids are unknown; the clash stays a choice. + staying.Add(party); + continue; + } + + moves.AddRange(party.Claims.Select(claim => new IdRemap(claim.Mod.ChangeSet.ModId, kind, scope, claim.Added.Id, target.Value))); + } + + if (staying.Count < 2) + { + continue; + } + + // GR-R11: a party held only by a number in a shipped plugin file is offered a move of its own. + foreach (Party party in staying.Where(item => item.IsUnchecked)) + { + int? target = targets.Take(kind, scope); + if (target is not null) + { + offers.AddRange(party.Claims.Select(claim => new IdRemap(claim.Mod.ChangeSet.ModId, kind, scope, claim.Added.Id, target.Value))); + } + } + } + + List remaps = pins + .Select(pin => new IdRemap(pin.Key.ModId, pin.Key.Kind, pin.Key.Scope, pin.Key.FromId, pin.Value)) + .Concat(moves) + .ToList(); + return new RemapPlan(Sorted(remaps), Sorted(moves), Sorted(offers), diagnostics); + } + + /// + /// GR-R12: a recorded entry stands while its mod is enabled and still adds the old id. Two entries for one old + /// id cannot both stand; the one with the lowest target does, so the input order never decides. An entry whose + /// target vanilla now uses (a game update filled a hole) stands no more: the old id is planned again, and when no + /// other entry stands for it the plan carries rules.remap_target_taken (the owner, 2026-11-12). + /// + private static Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int> Pins( + List mods, + Dictionary> added, + IReadOnlyList recorded, + BaseFileSet baseFiles, + List diagnostics) + { + var taken = new List(); + var enabled = new HashSet(mods.Where(mod => mod.Enabled).Select(mod => mod.ChangeSet.ModId), StringComparer.Ordinal); + var pins = new Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int>(); + var targets = new HashSet<(string ModId, IdKind Kind, string Scope, int ToId)>(); + foreach (IdRemap remap in Sorted(recorded)) + { + (string ModId, IdKind Kind, string Scope, int FromId) from = (remap.ModId, remap.Kind, remap.Scope, remap.FromId); + if (remap.Kind is not (IdKind.MapEvent or IdKind.Map) || remap.ToId <= 0 || !enabled.Contains(remap.ModId) || + !AddedIdIndex.IsActive(remap, added[remap.ModId]) || pins.ContainsKey(from) || + !targets.Add((remap.ModId, remap.Kind, remap.Scope, remap.ToId))) + { + // Only a standing entry holds its target, so a losing duplicate leaves the next entry free. + continue; + } + + if (VanillaUses(remap.Kind, remap.Scope, remap.ToId, baseFiles)) + { + taken.Add(remap); + continue; + } + + pins.Add(from, remap.ToId); + } + + foreach (IdRemap remap in taken.Where(item => !pins.ContainsKey((item.ModId, item.Kind, item.Scope, item.FromId))) + .DistinctBy(item => (item.ModId, item.Kind, item.Scope, item.FromId))) + { + string where = remap.Kind == IdKind.MapEvent ? " in " + remap.Scope : ""; + diagnostics.Add(new OperationDiagnostic( + DiagnosticCodes.RulesRemapTargetTaken, + string.Create( + CultureInfo.InvariantCulture, + $"Mod {remap.ModId}: {remap.Kind} {remap.FromId}{where} was recorded as moved to {remap.ToId}, which vanilla now uses, so the entry no longer applies and the id is planned again."), + DiagnosticSeverity.Warning, + remap.ModId)); + } + + return pins; + } + + /// True when vanilla has a record at : a map file or tree record, or a map's event. + private static bool VanillaUses(IdKind kind, string scope, int id, BaseFileSet baseFiles) + { + if (kind == IdKind.Map && baseFiles.Find(RpgDataSchema.MapKey(id)) is not null) + { + return true; + } + + return VanillaList(kind, scope, baseFiles) is JArray list && id < list.Count && list[id].Type != JTokenType.Null; + } + + /// Vanilla's list for a kind and scope, holes included: the map tree for maps, a map's events for events. + private static JArray? VanillaList(IdKind kind, string scope, BaseFileSet baseFiles) + { + string file = kind == IdKind.Map ? RpgDataSchema.MapInfosKey : scope; + BaseFile? baseFile = baseFiles.Find(file); + if (baseFile is null || !ChangeSetBuilder.TryReadBase(baseFile, out JToken? root, out _)) + { + return null; + } + + return (kind == IdKind.Map ? root : (root as JObject)?[RpgDataSchema.EventsProperty]) as JArray; + } + + /// GR-R3: claims with equal content are one party, because their ops fold into one. + private static List Partition(IEnumerable claims) + { + var parties = new List(); + foreach (Claim claim in claims) + { + Party? party = parties.FirstOrDefault(item => JToken.DeepEquals(item.Claims[0].Added.Content, claim.Added.Content)); + if (party is null) + { + parties.Add(new Party(claim)); + } + else + { + party.Claims.Add(claim); + } + } + + return parties + .OrderBy(party => party.Rank) + .ThenBy(party => party.Claims.Min(claim => claim.Mod.ChangeSet.Priority)) + .ThenBy(party => party.Claims.Select(claim => claim.Mod.ChangeSet.ModId).Order(StringComparer.Ordinal).First(), StringComparer.Ordinal) + .ToList(); + } + + /// + /// A map vanilla ships a file for, though its tree lacks the record: a mod that adds only the record edits that + /// file in place, and a remap cannot rename vanilla's file. + /// + private static bool IsVanillaMapFile(IdKind kind, int id, BaseFileSet baseFiles) + { + return kind == IdKind.Map && baseFiles.Find(RpgDataSchema.MapKey(id)) is not null; + } + + private static ModReferences ReferencesOf(RemapMod mod, Dictionary cache) + { + if (!cache.TryGetValue(mod.ChangeSet.ModId, out ModReferences? found)) + { + found = ReferenceMap.Scan(mod.ChangeSet, mod.PluginScripts); + cache.Add(mod.ChangeSet.ModId, found); + } + + return found; + } + + private static List Sorted(IEnumerable remaps) + { + return remaps + .OrderBy(remap => remap.ModId, StringComparer.Ordinal) + .ThenBy(remap => remap.Kind) + .ThenBy(remap => remap.Scope, StringComparer.Ordinal) + .ThenBy(remap => remap.FromId) + .ThenBy(remap => remap.ToId) + .ToList(); + } + + /// One enabled mod's added id, at the id it has after its recorded entry. + private sealed record Claim(RemapMod Mod, AddedId Added, int Effective, bool Pinned, bool Deployed); + + /// The mods of one clash that add equal content, so they keep or move together. + private sealed class Party + { + public Party(Claim first) + { + Claims = [first]; + } + + public List Claims { get; } + + /// GR-R4: a recorded entry, then a mod in DeployedMods, then the rest. + public int Rank => Claims.Any(claim => claim.Pinned) ? 0 : Claims.Any(claim => claim.Deployed) ? 1 : 2; + + public bool CanMove { get; private set; } + + public bool IsUnchecked { get; private set; } + + /// + /// A party moves only when no member is pinned, no member's id is fixed in vanilla's files and no member's + /// change set names the id where a remap cannot follow it (GR-R9). A number found only in a shipped plugin + /// file makes the move an offer (GR-R11). + /// + public void Classify(IdKind kind, Func referencesOf, Func isFixed) + { + bool pinned = Claims.Any(claim => claim.Pinned); + bool blocked = !pinned && Claims.Any(claim => isFixed(claim) || referencesOf(claim).Blocks(kind, claim.Added.Id)); + IsUnchecked = !pinned && !blocked && Claims.Any(claim => referencesOf(claim).IsUnchecked(claim.Added.Id)); + CanMove = !pinned && !blocked && !IsUnchecked; + } + } + + /// GR-R5: the next free id per kind and scope, above vanilla, every installed mod and every entry. + private sealed class Targets + { + private readonly List _added; + private readonly IReadOnlyList _recorded; + private readonly BaseFileSet _baseFiles; + private readonly RpgMakerEngine? _engine; + private readonly Dictionary<(IdKind Kind, string Scope), int?> _next = new(); + + public Targets(List added, IReadOnlyList recorded, BaseFileSet baseFiles, RpgMakerEngine? engine) + { + _added = added; + _recorded = recorded; + _baseFiles = baseFiles; + _engine = engine; + } + + public int? Take(IdKind kind, string scope) + { + if (!_next.TryGetValue((kind, scope), out int? next)) + { + next = First(kind, scope); + } + + // A vanilla map file outside the tree still owns its id. + while (next is not null && kind == IdKind.Map && _baseFiles.Find(RpgDataSchema.MapKey(next.Value)) is not null) + { + next++; + } + + int? limit = RpgDataSchema.RemapLimit(kind, _engine); + if (next is null || limit is null || next > limit) + { + _next[(kind, scope)] = next; + return null; + } + + _next[(kind, scope)] = next + 1; + return next; + } + + private int? First(IdKind kind, string scope) + { + JArray? vanilla = VanillaList(kind, scope, _baseFiles); + if (vanilla is null) + { + return null; + } + + int used = Math.Max(0, vanilla.Count - 1); + foreach (AddedId id in _added.Where(item => item.Kind == kind && item.Scope == scope)) + { + used = Math.Max(used, id.Id); + } + + foreach (IdRemap remap in _recorded.Where(item => item.Kind == kind && item.Scope == scope)) + { + used = Math.Max(used, Math.Max(remap.FromId, remap.ToId)); + } + + return used + 1; + } + } +} diff --git a/RPGModder.Core/Merge/IdRemapper.cs b/RPGModder.Core/Merge/IdRemapper.cs new file mode 100644 index 0000000..9e1dcc0 --- /dev/null +++ b/RPGModder.Core/Merge/IdRemapper.cs @@ -0,0 +1,91 @@ +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using System.Globalization; + +namespace RPGModder.Core.Merge; + +/// +/// The only code that changes an id (GR-K3, GR-R1). It runs after and before +/// , one mod at a time, and returns a new change set. +/// +public static class IdRemapper +{ + /// + /// Applies the entries of that name this mod and an id it still adds; the others are + /// inactive and change nothing (GR-R12). All moves of one mod apply in one pass, so an id moved onto another + /// moved id is not moved twice. Each applied entry adds rules.remap_applied (GR-R13). Step 1 applies the + /// and kinds and ignores the others. + /// + public static ModChangeSet Apply(ModChangeSet changeSet, IReadOnlyList remaps) + { + ArgumentNullException.ThrowIfNull(changeSet); + ArgumentNullException.ThrowIfNull(remaps); + + if (!remaps.Any(remap => remap.ModId == changeSet.ModId)) + { + return changeSet; + } + + IReadOnlyList added = AddedIdIndex.Of(changeSet); + List active = remaps + .Where(remap => remap.ModId == changeSet.ModId && remap.Kind is IdKind.MapEvent or IdKind.Map && AddedIdIndex.IsActive(remap, added)) + .Distinct() + .OrderBy(remap => remap.Kind) + .ThenBy(remap => remap.Scope, StringComparer.Ordinal) + .ThenBy(remap => remap.FromId) + .ToList(); + + var table = new RemapTable(); + foreach (IdRemap remap in active) + { + Dictionary moves = remap.Kind == IdKind.Map ? table.Maps : EventMoves(table, remap.Scope); + if (remap.ToId <= 0 || moves.ContainsValue(remap.ToId) || !moves.TryAdd(remap.FromId, remap.ToId)) + { + // The planner gives each old id one positive target of its own; anything else is a caller bug. + throw new ArgumentException( + $"The remaps for mod {changeSet.ModId} do not give {remap.Kind} {remap.FromId} a single target of its own.", + nameof(remaps)); + } + } + + if (table.IsEmpty) + { + return changeSet; + } + + // A stable sort: two ops can share a place when a recorded move lands on an id the mod now adds too. + List ops = changeSet.Ops + .Select(op => ReferenceMap.Rewrite(op, table)) + .OrderBy(op => op, Comparer.Create(ChangeSetBuilder.CompareOps)) + .ToList(); + + var diagnostics = changeSet.Diagnostics.ToList(); + diagnostics.AddRange(active.Select(remap => new OperationDiagnostic( + DiagnosticCodes.RulesRemapApplied, + Describe(remap), + DiagnosticSeverity.Info, + remap.ModId))); + + return changeSet with { Ops = ops, Diagnostics = diagnostics }; + } + + /// The mod, kind, old id and new id GR-R13 asks for, with the map file of an event. + private static string Describe(IdRemap remap) + { + string where = remap.Kind == IdKind.MapEvent ? " in " + remap.Scope : ""; + return string.Create( + CultureInfo.InvariantCulture, + $"Mod {remap.ModId}: {remap.Kind} {remap.FromId}{where} moved to {remap.ToId}."); + } + + private static Dictionary EventMoves(RemapTable table, string scope) + { + if (!table.Events.TryGetValue(scope, out Dictionary? moves)) + { + moves = new Dictionary(); + table.Events.Add(scope, moves); + } + + return moves; + } +} diff --git a/RPGModder.Core/Merge/MergeFileKind.cs b/RPGModder.Core/Merge/MergeFileKind.cs new file mode 100644 index 0000000..5daf748 --- /dev/null +++ b/RPGModder.Core/Merge/MergeFileKind.cs @@ -0,0 +1,9 @@ +namespace RPGModder.Core.Merge; + +public enum MergeFileKind +{ + Data, + PluginList, + ConfigSave, + Opaque +} diff --git a/RPGModder.Core/Merge/MergeJson.cs b/RPGModder.Core/Merge/MergeJson.cs new file mode 100644 index 0000000..a3f7dbc --- /dev/null +++ b/RPGModder.Core/Merge/MergeJson.cs @@ -0,0 +1,92 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System.Security.Cryptography; +using System.Text; +using StrictJsonException = System.Text.Json.JsonException; +using StrictReader = System.Text.Json.Utf8JsonReader; +using StrictReaderOptions = System.Text.Json.JsonReaderOptions; +using StrictTokenType = System.Text.Json.JsonTokenType; + +namespace RPGModder.Core.Merge; + +/// +/// The one reader and the one writer of game data inside the merge (GR-M7, seam 4.1). The reader accepts what the +/// game's JSON.parse accepts and nothing more, so a file the engine reads is a file the game can load. A +/// string that looks like a date stays a string. +/// +internal static class MergeJson +{ + private const int MaxDepth = 128; + private const char ByteOrderMark = ''; + private const byte LineFeed = (byte)'\n'; + + /// + /// Throws , with the line and position, when is not + /// exactly one strict JSON value: no comment, single quote, bare name, trailing comma, undefined, + /// NaN, constructor, or number too large for a double. + /// + public static JToken Parse(string text) + { + if (text.Length > 0 && text[0] == ByteOrderMark) + { + text = text[1..]; + } + + Validate(text); + + using var reader = new JsonTextReader(new StringReader(text)) + { + DateParseHandling = DateParseHandling.None, + FloatParseHandling = FloatParseHandling.Double, + MaxDepth = MaxDepth + }; + + return JToken.ReadFrom(reader, new JsonLoadSettings { LineInfoHandling = LineInfoHandling.Ignore }); + } + + /// Compact text: no indentation, property order as held, so equal trees give equal bytes. + public static string Write(JToken token) + { + return token.ToString(Formatting.None); + } + + public static string Sha256Hex(string text) + { + return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text))); + } + + /// Newtonsoft repairs loose input, so a strict reader checks the text first. + private static void Validate(string text) + { + byte[] bytes = Encoding.UTF8.GetBytes(text); + var reader = new StrictReader(bytes, new StrictReaderOptions { MaxDepth = MaxDepth }); + try + { + while (reader.Read()) + { + if (reader.TokenType == StrictTokenType.Number && + (!reader.TryGetDouble(out double number) || !double.IsFinite(number))) + { + throw Rejected("A number is too large for the game to read.", bytes, (int)reader.TokenStartIndex); + } + } + } + catch (StrictJsonException exception) + { + throw new JsonReaderException( + exception.Message, + "", + (int)(exception.LineNumber ?? 0) + 1, + (int)(exception.BytePositionInLine ?? 0) + 1, + exception); + } + } + + private static JsonReaderException Rejected(string message, byte[] bytes, int byteIndex) + { + int lineStart = byteIndex == 0 ? 0 : Array.LastIndexOf(bytes, LineFeed, byteIndex - 1) + 1; + int line = bytes.AsSpan(0, lineStart).Count(LineFeed) + 1; + int position = Encoding.UTF8.GetCharCount(bytes, lineStart, byteIndex - lineStart) + 1; + return new JsonReaderException(message, "", line, position, null); + } +} diff --git a/RPGModder.Core/Merge/MergePath.cs b/RPGModder.Core/Merge/MergePath.cs new file mode 100644 index 0000000..e9686b4 --- /dev/null +++ b/RPGModder.Core/Merge/MergePath.cs @@ -0,0 +1,254 @@ +using System.Globalization; +using System.Text; + +namespace RPGModder.Core.Merge; + +/// +/// File keys (GR-M2) and the leaf paths inside a record. A leaf path joins property names with . and +/// writes indexes as [n]: pages[2].conditions.switch1Id. A property name that is not a plain +/// identifier is written ['the name'], so a path never reads two ways. The empty path is the record itself. +/// +public static class MergePath +{ + /// + /// The order pseudo-leaf of a plugin record (seam 11.1): not a property of the entry but its place in the list. + /// A pseudo-leaf starts with @, which never writes bare, so it cannot be mistaken + /// for a real property (a property named @after is written ['@after']). + /// + internal const string AfterLeaf = "@after"; + + /// + /// The place of an OrderAmbiguous collision among entries that more than one mod moves to the front of + /// the list (seam 11.1). No op carries it: it only names that collision apart from the one for new entries. + /// + internal const string FirstLeaf = "@first"; + + internal static bool IsPseudoLeaf(string path) + { + return path.Length > 0 && path[0] == '@'; + } + + /// Back slashes become forward slashes, a leading ./ or / is removed, the result is lower case. + public static string ToKey(string path) + { + ArgumentNullException.ThrowIfNull(path); + + string key = path.Replace('\\', '/'); + while (true) + { + if (key.StartsWith("./", StringComparison.Ordinal)) + { + key = key[2..]; + } + else if (key.StartsWith('/')) + { + key = key[1..]; + } + else + { + break; + } + } + + return key.ToLowerInvariant(); + } + + internal static string Child(string parent, string propertyName) + { + string segment = IsIdentifier(propertyName) + ? propertyName + : "['" + propertyName.Replace("\\", "\\\\").Replace("'", "\\'") + "']"; + + if (parent.Length == 0) + { + return segment; + } + + return segment[0] == '[' ? parent + segment : parent + "." + segment; + } + + internal static string Index(string parent, int index) + { + return parent + "[" + index.ToString(CultureInfo.InvariantCulture) + "]"; + } + + /// + /// Every path that contains , shortest first: the empty path, then each longer prefix, + /// without the path itself. A pseudo-leaf has none, so it never joins its record's cluster. + /// + internal static IEnumerable Ancestors(string path) + { + if (path.Length == 0 || IsPseudoLeaf(path)) + { + yield break; + } + + IReadOnlyList segments = Parse(path); + string prefix = ""; + yield return prefix; + for (int index = 0; index < segments.Count - 1; index++) + { + prefix = Append(prefix, segments[index]); + yield return prefix; + } + } + + /// The path with every index replaced by [*], the form keys its policies by. + internal static string Pattern(string path) + { + var builder = new StringBuilder(); + foreach (PathSegment segment in Parse(path)) + { + if (segment.Name is null) + { + builder.Append("[*]"); + } + else + { + builder.Append(builder.Length == 0 ? "" : ".").Append(segment.Name); + } + } + + return builder.ToString(); + } + + /// Reads a path written by and . Throws for anything else. + internal static IReadOnlyList Parse(string path) + { + var segments = new List(); + int position = 0; + while (position < path.Length) + { + char current = path[position]; + if (current == '[' && position + 1 < path.Length && path[position + 1] == '\'') + { + position = ReadQuotedName(path, position + 2, segments); + } + else if (current == '[') + { + position = ReadIndex(path, position + 1, segments); + } + else + { + if (segments.Count > 0) + { + if (current != '.') + { + throw new FormatException($"Unexpected character in leaf path: {path}"); + } + + position++; + } + + position = ReadIdentifier(path, position, segments); + } + } + + return segments; + } + + internal static string Format(IEnumerable segments) + { + string path = ""; + foreach (PathSegment segment in segments) + { + path = Append(path, segment); + } + + return path; + } + + private static string Append(string parent, PathSegment segment) + { + return segment.Name is null ? Index(parent, segment.Index) : Child(parent, segment.Name); + } + + private static int ReadQuotedName(string path, int position, List segments) + { + var name = new StringBuilder(); + while (position < path.Length) + { + char current = path[position]; + if (current == '\\' && position + 1 < path.Length) + { + name.Append(path[position + 1]); + position += 2; + } + else if (current == '\'' && position + 1 < path.Length && path[position + 1] == ']') + { + segments.Add(PathSegment.Property(name.ToString())); + return position + 2; + } + else + { + name.Append(current); + position++; + } + } + + throw new FormatException($"Unterminated name in leaf path: {path}"); + } + + private static int ReadIndex(string path, int position, List segments) + { + int end = path.IndexOf(']', position); + if (end < 0 || + !int.TryParse(path.AsSpan(position, end - position), NumberStyles.None, CultureInfo.InvariantCulture, out int index)) + { + throw new FormatException($"Bad index in leaf path: {path}"); + } + + segments.Add(PathSegment.At(index)); + return end + 1; + } + + private static int ReadIdentifier(string path, int position, List segments) + { + int start = position; + while (position < path.Length && path[position] is not ('.' or '[')) + { + position++; + } + + string name = path[start..position]; + if (!IsIdentifier(name)) + { + throw new FormatException($"Bad property name in leaf path: {path}"); + } + + segments.Add(PathSegment.Property(name)); + return position; + } + + private static bool IsIdentifier(string name) + { + if (name.Length == 0 || !(char.IsAsciiLetter(name[0]) || name[0] is '_' or '$')) + { + return false; + } + + foreach (char current in name) + { + if (!(char.IsAsciiLetterOrDigit(current) || current is '_' or '$')) + { + return false; + } + } + + return true; + } +} + +/// One step of a leaf path: a property name, or an array index when Name is null. +internal readonly record struct PathSegment(string? Name, int Index) +{ + public static PathSegment Property(string name) + { + return new PathSegment(name, -1); + } + + public static PathSegment At(int index) + { + return new PathSegment(null, index); + } +} diff --git a/RPGModder.Core/Merge/MergePlan.cs b/RPGModder.Core/Merge/MergePlan.cs new file mode 100644 index 0000000..49acc92 --- /dev/null +++ b/RPGModder.Core/Merge/MergePlan.cs @@ -0,0 +1,15 @@ +using RPGModder.Core.Models; + +namespace RPGModder.Core.Merge; + +/// +/// The result of . Ops is sorted by file, record and path; Collisions +/// by id; Outcomes follows Collisions. MergeHash covers Ops and Outcomes. +/// +public sealed record MergePlan( + IReadOnlyList Ops, + IReadOnlyList Collisions, + IReadOnlyList Outcomes, + IReadOnlyList Diagnostics, + bool IsDeployable, + string MergeHash); diff --git a/RPGModder.Core/Merge/MergedFile.cs b/RPGModder.Core/Merge/MergedFile.cs new file mode 100644 index 0000000..b46f5f5 --- /dev/null +++ b/RPGModder.Core/Merge/MergedFile.cs @@ -0,0 +1,14 @@ +namespace RPGModder.Core.Merge; + +/// +/// One file a deploy writes. Text is written as UTF-8 without a byte order mark; ModFile means copy +/// SourceFile of mod ModId. DiskPath is set only for a name the engine generates (from 2r). +/// +public sealed record MergedFile( + string File, + MergedFileSource Source, + string? Text, + string? ModId, + string? SourceFile, + IReadOnlyList ModIds, + string? DiskPath = null); diff --git a/RPGModder.Core/Merge/MergedFileSource.cs b/RPGModder.Core/Merge/MergedFileSource.cs new file mode 100644 index 0000000..f53741a --- /dev/null +++ b/RPGModder.Core/Merge/MergedFileSource.cs @@ -0,0 +1,7 @@ +namespace RPGModder.Core.Merge; + +public enum MergedFileSource +{ + Text, + ModFile +} diff --git a/RPGModder.Core/Merge/MergedFileWriter.cs b/RPGModder.Core/Merge/MergedFileWriter.cs new file mode 100644 index 0000000..fa94258 --- /dev/null +++ b/RPGModder.Core/Merge/MergedFileWriter.cs @@ -0,0 +1,479 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Models; + +namespace RPGModder.Core.Merge; + +/// +/// Renders a deployable plan into the files a deploy writes. Only touched files are listed; every other file +/// stays vanilla and is copied by lane A (GR-M6). Every touched data file goes through one serializer (GR-M7); +/// a whole file a mod supplies unchanged is listed as a copy of the mod's file. +/// +public static class MergedFileWriter +{ + public static IReadOnlyList Write(MergePlan plan, BaseFileSet baseFiles, int? systemVersionId) + { + ArgumentNullException.ThrowIfNull(plan); + ArgumentNullException.ThrowIfNull(baseFiles); + + if (!plan.IsDeployable) + { + throw new InvalidOperationException("Only a deployable plan can be written."); + } + + var files = new SortedDictionary>(StringComparer.Ordinal); + foreach (MergedOp merged in plan.Ops) + { + if (!files.TryGetValue(merged.Op.Key.File, out List? fileOps)) + { + fileOps = new List(); + files.Add(merged.Op.Key.File, fileOps); + } + + fileOps.Add(merged); + } + + if (systemVersionId is not null) + { + if (baseFiles.Find(RpgDataSchema.SystemFileKey) is null) + { + throw new ArgumentException("A versionId needs data/System.json among the base files.", nameof(baseFiles)); + } + + files.TryAdd(RpgDataSchema.SystemFileKey, new List()); + } + + var result = new List(); + foreach ((string file, List fileOps) in files) + { + List modIds = fileOps + .SelectMany(merged => merged.ModIds) + .Distinct() + .OrderBy(id => id, StringComparer.Ordinal) + .ToList(); + + result.Add(RpgDataSchema.KindOf(file) switch + { + MergeFileKind.Opaque => Copy(file, fileOps, modIds), + MergeFileKind.PluginList => new MergedFile(file, MergedFileSource.Text, RenderPluginList(file, fileOps, baseFiles), null, null, modIds), + MergeFileKind.ConfigSave => new MergedFile(file, MergedFileSource.Text, RenderConfigSave(file, fileOps, baseFiles), null, null, modIds), + _ => WriteDataFile(file, fileOps, baseFiles, systemVersionId, modIds) + }); + } + + return result; + } + + private static MergedFile WriteDataFile(string file, List fileOps, BaseFileSet baseFiles, int? systemVersionId, List modIds) + { + BaseFile? baseFile = baseFiles.Find(file); + if (baseFile is null) + { + // GR-M9: a new file is one AddRecord on *, copied as the mod shipped it unless a patch or a remap changed + // it. Written as text, it names its mod so lane A takes the casing of that mod's file (seam 4.2 step 2); + // a map gets the casing the game loads instead (step 0), because a remapped one has no mod file name. + ChangeOp added = SingleOp(fileOps, ChangeKind.AddRecord); + return added.SourceFile is null + ? new MergedFile(file, MergedFileSource.Text, MergeJson.Write(Value(added)), added.ModId, null, modIds, RpgDataSchema.DiskPathOf(file)) + : new MergedFile(file, MergedFileSource.ModFile, null, added.ModId, added.SourceFile, modIds); + } + + JToken root = Render(file, baseFile, fileOps); + if (file == RpgDataSchema.SystemFileKey && systemVersionId is not null) + { + SetVersionId(root, systemVersionId.Value); + } + + return new MergedFile(file, MergedFileSource.Text, MergeJson.Write(root), null, null, modIds); + } + + /// A replaced opaque file is the bytes of the mod whose id sorts first among those that ship them. + private static MergedFile Copy(string file, List fileOps, List modIds) + { + ChangeOp replaced = SingleOp(fileOps, ChangeKind.ReplaceFile); + return new MergedFile( + file, + MergedFileSource.ModFile, + null, + replaced.ModId, + replaced.SourceFile ?? throw new InvalidOperationException($"The ReplaceFile op for {file} names no source file."), + modIds); + } + + private static ChangeOp SingleOp(List fileOps, ChangeKind kind) + { + if (fileOps.Count != 1 || fileOps[0].Op.Kind != kind || !fileOps[0].Op.Key.IsWholeFile || fileOps[0].Op.Path.Length != 0) + { + throw new InvalidOperationException($"{fileOps[0].Op.Key.File} needs exactly one whole-file {kind} op."); + } + + return fileOps[0].Op; + } + + private static JToken Render(string file, BaseFile baseFile, List fileOps) + { + JToken root = MergeJson.Parse(baseFile.Text + ?? throw new ArgumentException($"The base file {file} has no text.", nameof(baseFile))); + + var removals = new List(); + foreach (MergedOp merged in fileOps) + { + ChangeOp op = merged.Op; + if (op.Kind is ChangeKind.RemoveLeaf or ChangeKind.RemoveRecord) + { + removals.Add(op); + } + else if (op.Key.IsWholeFile && op.Path.Length == 0) + { + root = Value(op); + } + else + { + Set(root, op); + } + } + + // Removals run last and from the highest index down, so an index still names the element it named in vanilla. + removals.Sort(CompareDescending); + var removedRecords = new Dictionary>(ReferenceEqualityComparer.Instance); + foreach (ChangeOp op in removals) + { + if (op.Kind == ChangeKind.RemoveRecord) + { + RemoveRecord(root, op, removedRecords); + } + else + { + RemoveLeaf(RecordOf(root, op.Key), op); + } + } + + // Removed records at the end of their list are cut off, as the editor does: database files and map events. + foreach ((JArray records, HashSet removed) in removedRecords) + { + while (records.Count > 0 && removed.Contains(records.Count - 1)) + { + records.RemoveAt(records.Count - 1); + } + } + + return root; + } + + /// + /// Vanilla's list with the ops applied: leaf edits in place, removals, new entries, then every entry with an + /// @after placed by . Prefix and suffix are vanilla's (seam 11.1). + /// + private static string RenderPluginList(string file, List fileOps, BaseFileSet baseFiles) + { + PluginListText? vanilla = PluginListText.Empty(); + BaseFile? baseFile = baseFiles.Find(file); + if (baseFile is not null && !PluginListText.TryParse(baseFile.Text, out vanilla, out string? error)) + { + throw new ArgumentException($"The base file {file} cannot be read: {error}.", nameof(baseFiles)); + } + + if (fileOps.FirstOrDefault(merged => merged.Op.Key.IsWholeFile) is { } whole) + { + // A whole list clusters with every other op of the file, so nothing else survives beside it. + return (vanilla with { Entries = Value(whole.Op) as JArray ?? throw Misfit(whole.Op) }).Render(); + } + + var order = new List(); + var entries = new Dictionary(StringComparer.Ordinal); + foreach (JToken element in vanilla.Entries) + { + string name = (element is JObject entry ? PluginListDiff.NameOf(entry) : null) + ?? throw new InvalidOperationException($"{file} has an entry without a name, so only whole-list ops fit it."); + if (!entries.TryAdd(name, (JObject)element.DeepClone())) + { + throw new InvalidOperationException($"{file} names {name} twice, so only whole-list ops fit it."); + } + + order.Add(name); + } + + var added = new HashSet(StringComparer.Ordinal); + var anchors = new Dictionary(StringComparer.Ordinal); + foreach (MergedOp merged in fileOps) + { + ChangeOp op = merged.Op; + if (!RecordKey.TryGetPlugin(op.Key.Record, out string name)) + { + throw Misfit(op); + } + + if (op.Kind == ChangeKind.AddRecord) + { + entries[name] = Value(op) as JObject ?? throw Misfit(op); + added.Add(name); + } + else if (op.Kind == ChangeKind.RemoveRecord) + { + entries.Remove(name); + } + else if (op.Path == MergePath.AfterLeaf) + { + anchors[name] = Value(op).Type == JTokenType.String ? Value(op).Value() : null; + } + else if (!entries.TryGetValue(name, out JObject? entry)) + { + throw Misfit(op); + } + else if (op.Kind == ChangeKind.SetLeaf) + { + IReadOnlyList segments = MergePath.Parse(op.Path); + Put(Find(entry, segments, op), segments[^1], Value(op)); + } + else if (op.Kind == ChangeKind.RemoveLeaf) + { + RemoveLeaf(entry, op); + } + else + { + throw Misfit(op); + } + } + + // An anchor for an entry that is gone (removed by one mod, moved by another) has nothing to place. + var present = new HashSet(entries.Keys, StringComparer.Ordinal); + Dictionary live = anchors.Where(pair => present.Contains(pair.Key)).ToDictionary(StringComparer.Ordinal); + var list = new JArray(); + foreach (string name in PluginPlacement.Place(order, present, added, live)) + { + list.Add(entries[name]); + } + + return (vanilla with { Entries = list }).Render(); + } + + /// GR-M10: the live save (or {}) with each top-level value set, encoded as the game reads it. + private static string RenderConfigSave(string file, List fileOps, BaseFileSet baseFiles) + { + if (!ChangeSetBuilder.TryReadConfigBase(baseFiles.Find(file), file, out JObject? live, out OperationDiagnostic? problem)) + { + throw new ArgumentException(problem.Message, nameof(baseFiles)); + } + + foreach (MergedOp merged in fileOps) + { + if (merged.Op.Kind != ChangeKind.SetLeaf || !merged.Op.Key.IsWholeFile) + { + throw Misfit(merged.Op); + } + + Set(live, merged.Op); + } + + return ConfigSaveText.Encode(file, live); + } + + private static void Set(JToken root, ChangeOp op) + { + IReadOnlyList segments = MergePath.Parse(op.Path); + if (segments.Count == 0) + { + // A whole record: AddRecord, or a record that is not an object. + (JArray records, int index) = SlotOf(root, op.Key); + Put(records, PathSegment.At(index), Value(op)); + return; + } + + JToken container = Find(RecordOf(root, op.Key), segments, op); + Put(container, segments[^1], Value(op)); + } + + private static void RemoveRecord(JToken root, ChangeOp op, Dictionary> removedRecords) + { + _ = RecordOf(root, op.Key); + (JArray records, int index) = SlotOf(root, op.Key); + records[index] = JValue.CreateNull(); + if (!removedRecords.TryGetValue(records, out HashSet? removed)) + { + removed = new HashSet(); + removedRecords.Add(records, removed); + } + + removed.Add(index); + } + + private static void RemoveLeaf(JToken record, ChangeOp op) + { + IReadOnlyList segments = MergePath.Parse(op.Path); + if (segments.Count == 0) + { + throw Misfit(op); + } + + JToken container = Find(record, segments, op); + PathSegment last = segments[^1]; + if (container is JObject parent && last.Name is not null && parent.Remove(last.Name)) + { + return; + } + + if (container is JArray array && last.Name is null && last.Index < array.Count) + { + // Cutting the tail keeps the list short, as the mod left it; a hole in the middle keeps later indexes. + if (last.Index == array.Count - 1) + { + array.RemoveAt(last.Index); + } + else + { + array[last.Index] = JValue.CreateNull(); + } + + return; + } + + throw Misfit(op); + } + + /// The container of the last segment. Every step must exist: the walker only names places vanilla has. + private static JToken Find(JToken record, IReadOnlyList segments, ChangeOp op) + { + JToken container = record; + for (int index = 0; index < segments.Count - 1; index++) + { + container = Get(container, segments[index]) ?? throw Misfit(op); + } + + return container; + } + + private static void SetVersionId(JToken root, int versionId) + { + if (root is not JObject system) + { + throw new InvalidOperationException("data/System.json has no object root to carry a versionId."); + } + + Put(system, PathSegment.Property(RpgDataSchema.VersionIdField), new JValue(versionId)); + } + + private static JToken RecordOf(JToken root, RecordKey key) + { + if (key.IsWholeFile) + { + return root; + } + + (JArray records, int index) = SlotOf(root, key); + return index < records.Count && records[index].Type != JTokenType.Null + ? records[index] + : throw new InvalidOperationException($"{key.File} has no record {key.Record}."); + } + + /// The list that holds a record and its index there: the root for id:, a map's events for event:. + private static (JArray Records, int Index) SlotOf(JToken root, RecordKey key) + { + if (RecordKey.TryGetIndex(key.Record, out int index)) + { + return (root as JArray ?? throw new InvalidOperationException($"A record op on {key.File} needs a file whose root is an array."), index); + } + + if (RecordKey.TryGetEvent(key.Record, out index)) + { + return (root[RpgDataSchema.EventsProperty] as JArray + ?? throw new InvalidOperationException($"An event op on {key.File} needs a map with an events list."), index); + } + + throw new InvalidOperationException($"{key.Record} is not a record of {key.File}."); + } + + private static InvalidOperationException Misfit(ChangeOp op) + { + return new InvalidOperationException($"The {op.Kind} op at {op.Key.File} {op.Key.Record} {op.Path} does not fit the file."); + } + + private static JToken? Get(JToken container, PathSegment segment) + { + if (segment.Name is not null) + { + return container is JObject parent ? parent.Property(segment.Name, StringComparison.Ordinal)?.Value : null; + } + + return container is JArray array && segment.Index < array.Count ? array[segment.Index] : null; + } + + /// An existing property keeps its place; a new one goes at the end (GR-M7). An index past the end pads with null. + private static void Put(JToken container, PathSegment segment, JToken value) + { + if (segment.Name is not null && container is JObject parent) + { + JProperty? existing = parent.Property(segment.Name, StringComparison.Ordinal); + if (existing is null) + { + parent.Add(segment.Name, value); + } + else + { + existing.Value = value; + } + + return; + } + + if (segment.Name is null && container is JArray array) + { + while (array.Count <= segment.Index) + { + array.Add(JValue.CreateNull()); + } + + array[segment.Index] = value; + return; + } + + throw new InvalidOperationException("A merged value does not fit the shape of its file."); + } + + /// A copy of the op's value. A JSON null is a value; only a missing one (the remove kinds) throws. + private static JToken Value(ChangeOp op) + { + return op.Value?.DeepClone() ?? throw new InvalidOperationException($"A {op.Kind} op carries no value."); + } + + private static int CompareDescending(ChangeOp left, ChangeOp right) + { + int result = CompareRecords(right.Key.Record, left.Key.Record); + if (result != 0) + { + return result; + } + + IReadOnlyList leftSegments = MergePath.Parse(left.Path); + IReadOnlyList rightSegments = MergePath.Parse(right.Path); + for (int index = 0; index < Math.Min(leftSegments.Count, rightSegments.Count); index++) + { + result = CompareSegments(rightSegments[index], leftSegments[index]); + if (result != 0) + { + return result; + } + } + + return rightSegments.Count.CompareTo(leftSegments.Count); + } + + private static int CompareRecords(string left, string right) + { + if ((RecordKey.TryGetIndex(left, out int leftIndex) && RecordKey.TryGetIndex(right, out int rightIndex)) || + (RecordKey.TryGetEvent(left, out leftIndex) && RecordKey.TryGetEvent(right, out rightIndex))) + { + return leftIndex.CompareTo(rightIndex); + } + + return string.CompareOrdinal(left, right); + } + + private static int CompareSegments(PathSegment left, PathSegment right) + { + if (left.Name is null && right.Name is null) + { + return left.Index.CompareTo(right.Index); + } + + return string.CompareOrdinal(left.Name ?? "", right.Name ?? ""); + } +} diff --git a/RPGModder.Core/Merge/MergedOp.cs b/RPGModder.Core/Merge/MergedOp.cs new file mode 100644 index 0000000..70c7288 --- /dev/null +++ b/RPGModder.Core/Merge/MergedOp.cs @@ -0,0 +1,9 @@ +namespace RPGModder.Core.Merge; + +/// +/// An op that survives composition. Op is the contribution of the mod whose id sorts first; +/// ModIds lists every mod that contributed an equal op, sorted (GR-C8). +/// +public sealed record MergedOp( + ChangeOp Op, + IReadOnlyList ModIds); diff --git a/RPGModder.Core/Merge/ModChangeSet.cs b/RPGModder.Core/Merge/ModChangeSet.cs new file mode 100644 index 0000000..925836d --- /dev/null +++ b/RPGModder.Core/Merge/ModChangeSet.cs @@ -0,0 +1,9 @@ +using RPGModder.Core.Models; + +namespace RPGModder.Core.Merge; + +public sealed record ModChangeSet( + string ModId, + int Priority, + IReadOnlyList Ops, + IReadOnlyList Diagnostics); diff --git a/RPGModder.Core/Merge/ModChangeSetSerializer.cs b/RPGModder.Core/Merge/ModChangeSetSerializer.cs new file mode 100644 index 0000000..bb2f575 --- /dev/null +++ b/RPGModder.Core/Merge/ModChangeSetSerializer.cs @@ -0,0 +1,262 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using RPGModder.Core.Models; +using System.Diagnostics.CodeAnalysis; + +namespace RPGModder.Core.Merge; + +/// +/// The stable text form of a change set for lane A's cache (GR-M11). The text holds no priority, because the +/// priority belongs to the profile; takes the current one. +/// +public static class ModChangeSetSerializer +{ + public static string Serialize(ModChangeSet changeSet) + { + ArgumentNullException.ThrowIfNull(changeSet); + + var ops = new JArray(); + foreach (ChangeOp op in changeSet.Ops) + { + var entry = new JObject + { + ["file"] = op.Key.File, + ["record"] = op.Key.Record, + ["path"] = op.Path, + ["kind"] = op.Kind.ToString() + }; + + // An absent "value" is a C# null (the remove kinds); a JSON null leaf is written as null. + if (op.Value is not null) + { + entry["value"] = op.Value.DeepClone(); + } + + if (op.SourceFile is not null) + { + entry["source"] = op.SourceFile; + } + + ops.Add(entry); + } + + var diagnostics = new JArray(); + foreach (OperationDiagnostic diagnostic in changeSet.Diagnostics) + { + var entry = new JObject + { + ["code"] = diagnostic.Code, + ["message"] = diagnostic.Message, + ["severity"] = diagnostic.Severity.ToString() + }; + + if (diagnostic.Subject is not null) + { + entry["subject"] = diagnostic.Subject; + } + + diagnostics.Add(entry); + } + + var root = new JObject + { + ["schema"] = RpgDataSchema.SchemaVersion, + ["mod"] = changeSet.ModId, + ["ops"] = ops, + ["diagnostics"] = diagnostics + }; + + return MergeJson.Write(root); + } + + /// + /// Returns null for malformed text, for text written under another , + /// and for any op could not have written, so a damaged cache is rebuilt, not deployed. + /// + public static ModChangeSet? Deserialize(string text, int priority) + { + if (string.IsNullOrEmpty(text)) + { + return null; + } + + try + { + return Read(MergeJson.Parse(text), priority); + } + catch (JsonException) + { + // The cache is a speed-up only: unreadable text means "rebuild", which the null return tells lane A. + return null; + } + } + + private static ModChangeSet? Read(JToken token, int priority) + { + if (token is not JObject root || + root["schema"] is not JValue { Type: JTokenType.Integer, Value: long schema } || + schema != RpgDataSchema.SchemaVersion || + !TryString(root["mod"], out string? modId) || + root["ops"] is not JArray opsArray || + root["diagnostics"] is not JArray diagnosticsArray) + { + return null; + } + + var ops = new List(); + foreach (JToken item in opsArray) + { + ChangeOp? op = ReadOp(item, modId); + if (op is null) + { + return null; + } + + ops.Add(op); + } + + var diagnostics = new List(); + foreach (JToken item in diagnosticsArray) + { + if (item is not JObject entry || + !TryString(entry["code"], out string? code) || + !TryString(entry["message"], out string? message) || + !TryEnum(entry["severity"], out DiagnosticSeverity severity) || + !TryOptionalString(entry, "subject", out string? subject)) + { + return null; + } + + diagnostics.Add(new OperationDiagnostic(code, message, severity, subject)); + } + + return new ModChangeSet(modId, priority, ops, diagnostics); + } + + private static ChangeOp? ReadOp(JToken item, string modId) + { + if (item is not JObject entry || + !TryString(entry["file"], out string? file) || + !TryString(entry["record"], out string? record) || + !TryString(entry["path"], out string? path) || + !TryEnum(entry["kind"], out ChangeKind kind) || + !TryOptionalString(entry, "source", out string? source)) + { + return null; + } + + JToken? value = entry.TryGetValue("value", StringComparison.Ordinal, out JToken? stored) ? stored.DeepClone() : null; + var op = new ChangeOp(modId, new RecordKey(file, record), path, kind, value, source); + return IsWellFormed(op) ? op : null; + } + + /// + /// The shapes the builder writes: a canonical file key and path, a record form the file's family uses, and a + /// kind and value that fit both (seam 11.1). + /// + private static bool IsWellFormed(ChangeOp op) + { + if (MergePath.ToKey(op.Key.File) != op.Key.File) + { + return false; + } + + MergeFileKind family = RpgDataSchema.KindOf(op.Key.File); + bool whole = op.Key.IsWholeFile; + bool isPlugin = RecordKey.TryGetPlugin(op.Key.Record, out _); + bool isRecord = family switch + { + MergeFileKind.Data when RpgDataSchema.IsMapFile(op.Key.File) => RecordKey.TryGetEvent(op.Key.Record, out _), + MergeFileKind.Data => RecordKey.TryGetIndex(op.Key.Record, out _), + MergeFileKind.PluginList => isPlugin, + _ => false + }; + + if (!isRecord && !whole) + { + return false; + } + + if (op.Path == MergePath.AfterLeaf) + { + // The order pseudo-leaf: only on a plugin entry, naming the entry before it or nothing. + return isPlugin && op.Kind == ChangeKind.SetLeaf && op.Value?.Type is JTokenType.String or JTokenType.Null; + } + + if (!IsCanonicalPath(op.Path)) + { + return false; + } + + bool wholePlace = op.Path.Length == 0; + return family switch + { + MergeFileKind.Opaque => + op.Kind == ChangeKind.ReplaceFile && wholePlace && op.Value?.Type == JTokenType.String && op.SourceFile is not null, + + // One value per top-level key of the config object. + MergeFileKind.ConfigSave => op.Kind == ChangeKind.SetLeaf && op.Value is not null && MergePath.Parse(op.Path).Count == 1, + + // The whole list as one value on *, or an entry's own record ops. + MergeFileKind.PluginList when whole => op.Kind == ChangeKind.SetLeaf && wholePlace && op.Value is JArray, + MergeFileKind.PluginList => op.Kind switch + { + ChangeKind.AddRecord => wholePlace && op.Value is JObject, + ChangeKind.RemoveRecord => wholePlace && op.Value is null, + ChangeKind.SetLeaf => !wholePlace && op.Value is not null, + ChangeKind.RemoveLeaf => !wholePlace && op.Value is null, + _ => false + }, + + _ => op.Kind switch + { + // A whole file with no vanilla counterpart is an AddRecord on * (GR-M9). + ChangeKind.AddRecord => wholePlace && op.Value is not null, + ChangeKind.RemoveRecord => isRecord && wholePlace && op.Value is null, + ChangeKind.RemoveLeaf => !wholePlace && op.Value is null, + ChangeKind.SetLeaf => op.Value is not null, + ChangeKind.EditSequence or ChangeKind.EditCommands => !wholePlace && op.Value is JArray, + _ => false + } + }; + } + + private static bool IsCanonicalPath(string path) + { + try + { + return MergePath.Format(MergePath.Parse(path)) == path; + } + catch (FormatException) + { + return false; + } + } + + private static bool TryString(JToken? token, [NotNullWhen(true)] out string? value) + { + value = token is JValue { Type: JTokenType.String } text ? text.Value() : null; + return value is not null; + } + + private static bool TryOptionalString(JObject entry, string name, out string? value) + { + value = null; + if (!entry.TryGetValue(name, StringComparison.Ordinal, out JToken? token) || token.Type == JTokenType.Null) + { + return true; + } + + return TryString(token, out value); + } + + /// Only a member's exact name: no number, no comma list of flags, no spaces, no other case. + private static bool TryEnum(JToken? token, out TEnum value) + where TEnum : struct, Enum + { + value = default; + return TryString(token, out string? text) && + Enum.GetNames().Contains(text, StringComparer.Ordinal) && + Enum.TryParse(text, ignoreCase: false, out value); + } +} diff --git a/RPGModder.Core/Merge/ModFile.cs b/RPGModder.Core/Merge/ModFile.cs new file mode 100644 index 0000000..4ce0548 --- /dev/null +++ b/RPGModder.Core/Merge/ModFile.cs @@ -0,0 +1,8 @@ +namespace RPGModder.Core.Merge; + +/// One file_ops entry. Source is returned untouched so the caller can copy the file. +public sealed record ModFile( + string Target, + string Source, + string? Text, + string Sha256); diff --git a/RPGModder.Core/Merge/ModPatch.cs b/RPGModder.Core/Merge/ModPatch.cs new file mode 100644 index 0000000..aa94646 --- /dev/null +++ b/RPGModder.Core/Merge/ModPatch.cs @@ -0,0 +1,8 @@ +using Newtonsoft.Json.Linq; + +namespace RPGModder.Core.Merge; + +/// One json_patches entry. +public sealed record ModPatch( + string Target, + JObject MergeData); diff --git a/RPGModder.Core/Merge/ModReferences.cs b/RPGModder.Core/Merge/ModReferences.cs new file mode 100644 index 0000000..f432a32 --- /dev/null +++ b/RPGModder.Core/Merge/ModReferences.cs @@ -0,0 +1,40 @@ +namespace RPGModder.Core.Merge; + +/// What found in one mod: the numbers a remap cannot rewrite. +internal sealed class ModReferences +{ + /// Whole numbers in the change set's free text (GR-R9). + public HashSet FreeTextNumbers { get; } = new(); + + /// Event ids named by event commands in a common event or a troop, which act on any map (3.11). + public HashSet AmbiguousEventIds { get; } = new(); + + /// Constants Control Variables assigns; with a transfer by variable, one of them may be a map id. + public HashSet VariableConstants { get; } = new(); + + /// Whole numbers in the plugin files the mod ships (GR-R11). + public HashSet PluginScriptNumbers { get; } = new(); + + /// + /// True when the mod sends the player or a vehicle to a map named by a variable (201 with p[0] 1, 202 with + /// p[1] 1). + /// + public bool UsesVariableTransfer { get; set; } + + /// True when the change set refers to where a remap cannot follow it (GR-R9). + public bool Blocks(IdKind kind, int id) + { + return FreeTextNumbers.Contains(id) || kind switch + { + IdKind.MapEvent => AmbiguousEventIds.Contains(id), + IdKind.Map => UsesVariableTransfer && VariableConstants.Contains(id), + _ => true + }; + } + + /// True when appears in a shipped plugin file, so a move is only offered (GR-R11). + public bool IsUnchecked(int id) + { + return PluginScriptNumbers.Contains(id); + } +} diff --git a/RPGModder.Core/Merge/ModSource.cs b/RPGModder.Core/Merge/ModSource.cs new file mode 100644 index 0000000..a9a36d6 --- /dev/null +++ b/RPGModder.Core/Merge/ModSource.cs @@ -0,0 +1,11 @@ +using RPGModder.Core.Models; + +namespace RPGModder.Core.Merge; + +/// One enabled mod. ModId is the folder name (GR-M3). +public sealed record ModSource( + string ModId, + int Priority, + IReadOnlyList Files, + IReadOnlyList Patches, + IReadOnlyList Plugins); diff --git a/RPGModder.Core/Merge/PluginListDiff.cs b/RPGModder.Core/Merge/PluginListDiff.cs new file mode 100644 index 0000000..6547a61 --- /dev/null +++ b/RPGModder.Core/Merge/PluginListDiff.cs @@ -0,0 +1,201 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Models; + +namespace RPGModder.Core.Merge; + +/// +/// Compares one mod's $plugins list with vanilla's (guide 3.3, seam 11.1). Entries are records named by +/// their plugin name; where an entry sits is the @after pseudo-leaf, never its index (GR-C10). +/// +internal static class PluginListDiff +{ + private const string NameProperty = "name"; + + public static IReadOnlyList Compare(string modId, string? sourceFile, JArray vanilla, JArray modded) + { + var ops = new List(); + if (JToken.DeepEquals(vanilla, modded)) + { + return ops; + } + + if (!TryNames(vanilla, out List vanillaNames) || !TryNames(modded, out List moddedNames)) + { + // Repeated or missing names leave no record to line up: the mod's list is one value. + ops.Add(Op(modId, RecordKey.WholeFile, "", ChangeKind.SetLeaf, modded, sourceFile)); + return ops; + } + + var vanillaIndex = new Dictionary(StringComparer.Ordinal); + for (int index = 0; index < vanillaNames.Count; index++) + { + vanillaIndex.Add(vanillaNames[index], index); + } + + var moddedSet = new HashSet(moddedNames, StringComparer.Ordinal); + var common = new HashSet(moddedNames.Where(vanillaIndex.ContainsKey), StringComparer.Ordinal); + HashSet kept = LongestCommonOrder(vanillaNames.Where(common.Contains).ToList(), moddedNames.Where(common.Contains).ToList()); + + foreach (string name in vanillaNames.Where(name => !moddedSet.Contains(name))) + { + ops.Add(Op(modId, RecordKey.ForPlugin(name), "", ChangeKind.RemoveRecord, null, sourceFile)); + } + + for (int index = 0; index < moddedNames.Count; index++) + { + string name = moddedNames[index]; + string record = RecordKey.ForPlugin(name); + var entry = (JObject)modded[index]; + JToken after = index == 0 ? JValue.CreateNull() : new JValue(moddedNames[index - 1]); + + if (!vanillaIndex.TryGetValue(name, out int vanillaPosition)) + { + ops.Add(Op(modId, record, "", ChangeKind.AddRecord, entry, sourceFile)); + ops.Add(Op(modId, record, MergePath.AfterLeaf, ChangeKind.SetLeaf, after, sourceFile)); + continue; + } + + ops.AddRange(DataDiff.CompareRecord(modId, RpgDataSchema.PluginListKey, sourceFile, record, (JObject)vanilla[vanillaPosition], entry)); + + // The entries both lists keep, in the longest order both agree on, stay where they are; every other + // kept entry moved. A removal or an insertion next to an entry does not move it, and a moved block + // carries an anchor on each of its entries, so it is placed whole. + if (!kept.Contains(name)) + { + ops.Add(Op(modId, record, MergePath.AfterLeaf, ChangeKind.SetLeaf, after, sourceFile)); + } + } + + return ops; + } + + /// + /// Applies a mod's plugins_registry after its own plugins.js (seam 11.1): an entry whose name is + /// listed replaces it where it is, a new name is appended. + /// + public static void ApplyRegistry(JArray list, IReadOnlyList registry) + { + foreach (PluginEntry plugin in registry) + { + JObject entry = EntryOf(plugin); + int existing = -1; + for (int index = 0; index < list.Count && existing < 0; index++) + { + if (list[index] is JObject listed && NameOf(listed) == plugin.Name) + { + existing = index; + } + } + + if (existing < 0) + { + list.Add(entry); + } + else + { + list[existing] = entry; + } + } + } + + /// The editor's property order: name, status, description, parameters, then anything else the entry carries. + internal static JObject EntryOf(PluginEntry plugin) + { + var parameters = new JObject(); + foreach ((string key, string value) in plugin.Parameters ?? new Dictionary()) + { + parameters[key] = value; + } + + var entry = new JObject + { + [NameProperty] = plugin.Name, + ["status"] = plugin.Status, + ["description"] = plugin.Description, + ["parameters"] = parameters + }; + + foreach ((string key, JToken value) in plugin.ExtensionData ?? new Dictionary()) + { + if (entry.Property(key, StringComparison.Ordinal) is null) + { + entry.Add(key, value.DeepClone()); + } + } + + return entry; + } + + internal static string? NameOf(JObject entry) + { + return entry.Property(NameProperty, StringComparison.Ordinal)?.Value is JValue { Type: JTokenType.String } name + ? name.Value() + : null; + } + + /// Every entry an object with a non-empty name, and no name twice. + private static bool TryNames(JArray list, out List names) + { + names = new List(list.Count); + var seen = new HashSet(StringComparer.Ordinal); + foreach (JToken element in list) + { + string? name = element is JObject entry ? NameOf(entry) : null; + if (string.IsNullOrEmpty(name) || !seen.Add(name)) + { + return false; + } + + names.Add(name); + } + + return true; + } + + /// + /// The entries of one longest common subsequence of two orders of the same names. On a tie the vanilla entry + /// is the one dropped, so a swap of two neighbours moves the one vanilla had first. + /// + private static HashSet LongestCommonOrder(List vanilla, List modded) + { + // suffix[i, j] is the length for vanilla[i..] and modded[j..]. + var suffix = new int[vanilla.Count + 1, modded.Count + 1]; + for (int i = vanilla.Count - 1; i >= 0; i--) + { + for (int j = modded.Count - 1; j >= 0; j--) + { + suffix[i, j] = vanilla[i] == modded[j] + ? suffix[i + 1, j + 1] + 1 + : Math.Max(suffix[i + 1, j], suffix[i, j + 1]); + } + } + + var kept = new HashSet(StringComparer.Ordinal); + int left = 0; + int right = 0; + while (left < vanilla.Count && right < modded.Count) + { + if (vanilla[left] == modded[right]) + { + kept.Add(vanilla[left]); + left++; + right++; + } + else if (suffix[left + 1, right] >= suffix[left, right + 1]) + { + left++; + } + else + { + right++; + } + } + + return kept; + } + + private static ChangeOp Op(string modId, string record, string path, ChangeKind kind, JToken? value, string? sourceFile) + { + return new ChangeOp(modId, new RecordKey(RpgDataSchema.PluginListKey, record), path, kind, value?.DeepClone(), sourceFile); + } +} diff --git a/RPGModder.Core/Merge/PluginListText.cs b/RPGModder.Core/Merge/PluginListText.cs new file mode 100644 index 0000000..ac37567 --- /dev/null +++ b/RPGModder.Core/Merge/PluginListText.cs @@ -0,0 +1,191 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System.Diagnostics.CodeAnalysis; +using System.Text; + +namespace RPGModder.Core.Merge; + +/// +/// The text form of js/plugins.js (seam 11.1): a prefix that names $plugins and ends with =, +/// one strict JSON array, then only white space and an optional ;. The array is read as JSON, never as +/// script and never line by line (GR-C11); prefix and suffix are kept byte for byte. +/// +internal sealed record PluginListText(string Prefix, JArray Entries, string Suffix) +{ + /// What the editor writes, used when vanilla has no plugins.js at all. + internal const string DefaultPrefix = "// Generated by RPG Maker.\n// Do not edit this file directly.\nvar $plugins =\n"; + + internal const string DefaultSuffix = ";\n"; + + private const string ListName = "$plugins"; + + public static PluginListText Empty() + { + return new PluginListText(DefaultPrefix, new JArray(), DefaultSuffix); + } + + public static bool TryParse(string? text, [NotNullWhen(true)] out PluginListText? list, [NotNullWhen(false)] out string? error) + { + list = null; + if (text is null) + { + error = "no text"; + return false; + } + + if (!TryFindListStart(text, out int start, out error)) + { + return false; + } + + int end = FindListEnd(text, start); + if (end < 0) + { + error = "the list is not closed"; + return false; + } + + string suffix = text[(end + 1)..]; + if (!IsPlainSuffix(suffix)) + { + error = "something other than ; follows the list"; + return false; + } + + try + { + if (MergeJson.Parse(text[start..(end + 1)]) is JArray entries) + { + list = new PluginListText(text[..start], entries, suffix); + error = null; + return true; + } + } + catch (JsonReaderException exception) + { + error = $"the list is not valid JSON (line {exception.LineNumber}, position {exception.LinePosition})"; + return false; + } + + error = "the list is not a JSON array"; + return false; + } + + /// + /// The [ of the first $plugins = [, so a mention of the name in a comment before it is skipped. + /// The error names what follows the first mention when no mention is the declaration. + /// + private static bool TryFindListStart(string text, out int start, [NotNullWhen(false)] out string? error) + { + start = -1; + error = "it does not name " + ListName; + bool first = true; + for (int name = text.IndexOf(ListName, StringComparison.Ordinal); + name >= 0; + name = text.IndexOf(ListName, name + ListName.Length, StringComparison.Ordinal)) + { + int position = SkipWhiteSpace(text, name + ListName.Length); + string? problem = null; + if (position >= text.Length || text[position] != '=') + { + problem = ListName + " is not followed by ="; + } + else + { + position = SkipWhiteSpace(text, position + 1); + if (position >= text.Length || text[position] != '[') + { + problem = ListName + " is not set to a list"; + } + } + + if (problem is null) + { + start = position; + error = null; + return true; + } + + if (first) + { + error = problem; + first = false; + } + } + + return false; + } + + /// + /// [, a line end, each entry compact, joined by , and a line end, a line end, ]. The line + /// end is the prefix's own, so a file the editor saved on Windows stays CRLF. + /// + public string Render() + { + if (Entries.Count == 0) + { + return Prefix + "[]" + Suffix; + } + + string lineEnd = Prefix.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n"; + var builder = new StringBuilder(Prefix).Append('[').Append(lineEnd); + for (int index = 0; index < Entries.Count; index++) + { + builder.Append(index == 0 ? "" : "," + lineEnd).Append(MergeJson.Write(Entries[index])); + } + + return builder.Append(lineEnd).Append(']').Append(Suffix).ToString(); + } + + private static int SkipWhiteSpace(string text, int position) + { + while (position < text.Length && char.IsWhiteSpace(text[position])) + { + position++; + } + + return position; + } + + /// The index of the ] that closes the list at , skipping brackets inside strings. + private static int FindListEnd(string text, int start) + { + int depth = 0; + bool inString = false; + for (int position = start; position < text.Length; position++) + { + char current = text[position]; + if (inString) + { + if (current == '\\') + { + position++; + } + else if (current == '"') + { + inString = false; + } + } + else if (current == '"') + { + inString = true; + } + else if (current is '[' or '{') + { + depth++; + } + else if (current is ']' or '}' && --depth == 0) + { + return current == ']' ? position : -1; + } + } + + return -1; + } + + private static bool IsPlainSuffix(string suffix) + { + string rest = suffix.Trim(); + return rest.Length == 0 || rest == ";"; + } +} diff --git a/RPGModder.Core/Merge/PluginPlacement.cs b/RPGModder.Core/Merge/PluginPlacement.cs new file mode 100644 index 0000000..f4c895c --- /dev/null +++ b/RPGModder.Core/Merge/PluginPlacement.cs @@ -0,0 +1,104 @@ +namespace RPGModder.Core.Merge; + +/// +/// Places the entries of the merged $plugins list by their @after anchors (GR-C10, seam 11.1). +/// Vanilla entries with no anchor keep their order; nothing is placed by index. +/// +internal static class PluginPlacement +{ + /// Every vanilla name, in vanilla's order, removed ones included (for the fallback). + /// Every name of the merged list. + /// The names vanilla does not have. + /// The @after of each entry that has one; null means "no entry before it". + public static List Place( + IReadOnlyList vanillaOrder, + IReadOnlySet present, + IReadOnlySet added, + IReadOnlyDictionary anchors) + { + var placed = vanillaOrder.Where(name => present.Contains(name) && !anchors.ContainsKey(name)).ToList(); + var pending = new SortedSet(present.Where(name => !placed.Contains(name)), StringComparer.Ordinal); + var lastAfter = new Dictionary(StringComparer.Ordinal); + int front = 0; + + while (pending.Count > 0) + { + bool progress = false; + foreach (string name in pending.ToList()) + { + string? anchor = anchors.GetValueOrDefault(name); + if (anchor is null) + { + // A new entry with nothing before it goes to the end (GR-C10); a moved one goes first. + if (added.Contains(name) || !anchors.ContainsKey(name)) + { + placed.Add(name); + } + else + { + placed.Insert(front++, name); + } + } + else if (placed.Contains(anchor)) + { + InsertAfter(placed, lastAfter, anchor, name); + } + else if (pending.Contains(anchor)) + { + continue; + } + else if (NearestPlacedBefore(vanillaOrder, placed, anchor) is string fallback) + { + InsertAfter(placed, lastAfter, fallback, name); + } + else + { + placed.Add(name); + } + + pending.Remove(name); + progress = true; + } + + if (!progress) + { + // A cycle of anchors, and whatever waits on it: the end of the list, by name. + placed.AddRange(pending); + break; + } + } + + return placed; + } + + /// Right after the anchor, or after the entry last placed there, so entries behind one anchor keep their placing order. + private static void InsertAfter(List placed, Dictionary lastAfter, string anchor, string name) + { + string target = lastAfter.TryGetValue(anchor, out string? last) && placed.Contains(last) ? last : anchor; + placed.Insert(placed.IndexOf(target) + 1, name); + lastAfter[anchor] = name; + } + + /// The anchor's nearest preceding vanilla entry that is in the list; null when the anchor is not a vanilla entry or none precedes it. + private static string? NearestPlacedBefore(IReadOnlyList vanillaOrder, List placed, string anchor) + { + int position = -1; + for (int index = 0; index < vanillaOrder.Count && position < 0; index++) + { + if (vanillaOrder[index] == anchor) + { + position = index; + } + } + + for (int index = position - 1; index >= 0; index--) + { + if (placed.Contains(vanillaOrder[index])) + { + return vanillaOrder[index]; + } + } + + return null; + } +} diff --git a/RPGModder.Core/Merge/RecordKey.cs b/RPGModder.Core/Merge/RecordKey.cs new file mode 100644 index 0000000..7d1172c --- /dev/null +++ b/RPGModder.Core/Merge/RecordKey.cs @@ -0,0 +1,62 @@ +using System.Globalization; + +namespace RPGModder.Core.Merge; + +/// +/// The identity of one record of one file (GR-M2): File is the key from , +/// Record is id:<n> for a database record, event:<n> for a map event, +/// plugin:<name> for a $plugins entry, or * for whole-file and root-level ops. +/// +public sealed record RecordKey(string File, string Record) +{ + /// The record of a whole-file op, and of every op in a file whose root is not a record list. + internal const string WholeFile = "*"; + + private const string RecordPrefix = "id:"; + private const string EventPrefix = "event:"; + private const string PluginPrefix = "plugin:"; + + internal bool IsWholeFile => Record == WholeFile; + + internal static string ForIndex(int index) + { + return RecordPrefix + index.ToString(CultureInfo.InvariantCulture); + } + + internal static string ForEvent(int index) + { + return EventPrefix + index.ToString(CultureInfo.InvariantCulture); + } + + internal static string ForPlugin(string name) + { + return PluginPrefix + name; + } + + /// Reads id:<n> in the one form writes: no sign, no leading zero. + internal static bool TryGetIndex(string record, out int index) + { + return TryGetNumber(record, RecordPrefix, out index); + } + + /// Reads event:<n> in the one form writes. + internal static bool TryGetEvent(string record, out int index) + { + return TryGetNumber(record, EventPrefix, out index); + } + + /// Reads plugin:<name>; the name is never empty. + internal static bool TryGetPlugin(string record, out string name) + { + name = record.StartsWith(PluginPrefix, StringComparison.Ordinal) ? record[PluginPrefix.Length..] : ""; + return name.Length > 0; + } + + private static bool TryGetNumber(string record, string prefix, out int index) + { + index = -1; + return record.StartsWith(prefix, StringComparison.Ordinal) && + int.TryParse(record.AsSpan(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out index) && + prefix + index.ToString(CultureInfo.InvariantCulture) == record; + } +} diff --git a/RPGModder.Core/Merge/ReferenceMap.cs b/RPGModder.Core/Merge/ReferenceMap.cs new file mode 100644 index 0000000..dd03786 --- /dev/null +++ b/RPGModder.Core/Merge/ReferenceMap.cs @@ -0,0 +1,429 @@ +using Newtonsoft.Json.Linq; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; + +namespace RPGModder.Core.Merge; + +/// +/// Where an id is referenced (guide 3.11, reference table), for the two kinds of step 1. reads a +/// change set's free text and the references the table cannot rewrite (GR-R9); moves every +/// reference the table lists. p[n] below is parameters[n] of an event or route command; only values +/// above 0 are ids. Every position was checked against the MV and MZ core scripts. +/// +internal static class ReferenceMap +{ + // Route command (inside a moveRoute list): Script. + private const int RouteScript = 45; + + // Event commands. + private const int ConditionalBranch = 111; + private const int ControlVariables = 122; + private const int TransferPlayer = 201; + private const int SetVehicleLocation = 202; + private const int SetEventLocation = 203; + private const int SetMovementRoute = 205; + private const int ShowAnimation = 212; + private const int ShowBalloon = 213; + private const int GetLocationInfo = 285; + private const int Script = 355; + private const int PluginCommandMv = 356; + private const int PluginCommandMz = 357; + private const int ScriptMore = 655; + + // 111 p[0], 122 p[3] and p[4], 201 p[0], 202 p[1], 203 p[1], 285 p[2]: the operand forms the table names. + private const int BranchCharacter = 6; + private const int BranchScript = 12; + private const int OperandConstant = 0; + private const int OperandGameData = 3; + private const int OperandScript = 4; + private const int GameDataCharacter = 5; + private const int DesignationDirect = 0; + private const int DesignationByVariable = 1; + private const int EventLocationExchange = 2; + private const int LocationByCharacter = 2; + + private const string NoteProperty = "note"; + private const string DamageProperty = "damage"; + private const string FormulaProperty = "formula"; + private const string ParentIdProperty = "parentId"; + private const string IdProperty = "id"; + private const string ParametersProperty = "parameters"; + private const string CodeProperty = "code"; + + /// The System.json places that hold a map id. + private static readonly HashSet StartMapPaths = new(StringComparer.Ordinal) + { + "startMapId", + "boat.startMapId", + "ship.startMapId", + "airship.startMapId" + }; + + /// What in one mod's change set stops a move (GR-R9) or makes it unchecked (GR-R11). + public static ModReferences Scan(ModChangeSet changeSet, IReadOnlyList pluginScripts) + { + var references = new ModReferences(); + foreach (ChangeOp op in changeSet.Ops) + { + if (op.Value is null || MergePath.IsPseudoLeaf(op.Path)) + { + continue; + } + + IReadOnlyList segments = MergePath.Parse(op.Path); + string? name = segments.Count > 0 ? segments[^1].Name : null; + string? parent = segments.Count > 1 ? segments[^2].Name : null; + bool isPluginList = op.Key.File == RpgDataSchema.PluginListKey; + var context = new ScanContext(references, RpgDataSchema.IsMapFile(op.Key.File), isPluginList); + + // Plugin parameters the mod sets are free text (GR-R9), whether the op names one or the whole entry. + bool inParameters = isPluginList && segments.Count > 0 && segments[0].Name == ParametersProperty; + Visit(op.Value, name, parent, inParameters, context); + } + + foreach (string script in pluginScripts) + { + AddNumbers(script, references.PluginScriptNumbers); + } + + return references; + } + + /// + /// with every listed reference moved by , or the op itself when + /// nothing moved. A whole new file whose content changed loses its source file, so it is written as text. + /// + public static ChangeOp Rewrite(ChangeOp op, RemapTable table) + { + RecordKey key = op.Key; + JToken? value = op.Value?.DeepClone(); + if (op.Kind == ChangeKind.AddRecord && op.Path.Length == 0) + { + if (key.IsWholeFile && RpgDataSchema.TryGetMapId(key.File, out int mapId) && table.Maps.TryGetValue(mapId, out int newMap)) + { + key = new RecordKey(RpgDataSchema.MapKey(newMap), RecordKey.WholeFile); + } + else if (key.File == RpgDataSchema.MapInfosKey && RecordKey.TryGetIndex(key.Record, out int infoId) && + table.Maps.TryGetValue(infoId, out int newInfo)) + { + key = key with { Record = RecordKey.ForIndex(newInfo) }; + SetOwnId(value, infoId, newInfo); + } + else if (table.Events.TryGetValue(key.File, out Dictionary? moved) && RecordKey.TryGetEvent(key.Record, out int eventId) && + moved.TryGetValue(eventId, out int newEvent)) + { + key = key with { Record = RecordKey.ForEvent(newEvent) }; + SetOwnId(value, eventId, newEvent); + } + } + + if (value is not null && !MergePath.IsPseudoLeaf(op.Path)) + { + // Event references are scoped to the map file the commands sit in, so the op's own file decides. + Dictionary? events = table.Events.GetValueOrDefault(op.Key.File); + VisitCommands(value, command => RewriteCommand(command, table.Maps, events)); + if (op.Key.File == RpgDataSchema.MapInfosKey && !op.Key.IsWholeFile) + { + // A map's parent, in the moved map's own record or in a vanilla map the mod hangs under it. + value = RewriteAt(value, op.Path, path => path == ParentIdProperty, table.Maps); + } + else if (op.Key.File == RpgDataSchema.SystemFileKey) + { + value = RewriteAt(value, op.Path, StartMapPaths.Contains, table.Maps); + } + } + + bool changed = key != op.Key || !JToken.DeepEquals(value, op.Value); + if (!changed) + { + return op; + } + + string? source = op.Kind == ChangeKind.AddRecord && op.Key.IsWholeFile ? null : op.SourceFile; + return op with { Key = key, Value = value, SourceFile = source }; + } + + private static void Visit(JToken token, string? name, string? parent, bool inParameters, ScanContext context) + { + if (inParameters) + { + AddNumbers(token, context.References.FreeTextNumbers); + return; + } + + switch (token) + { + case JObject item: + if (TryCommand(item, out int code, out JArray? parameters)) + { + ScanCommand(code, parameters, context); + } + + foreach (JProperty property in item.Properties()) + { + bool pluginParameters = context.IsPluginList && property.Name == ParametersProperty; + Visit(property.Value, property.Name, name, pluginParameters, context); + } + + break; + case JArray list: + foreach (JToken element in list) + { + Visit(element, null, name, false, context); + } + + break; + case JValue { Type: JTokenType.String } text when name == NoteProperty || (name == FormulaProperty && parent == DamageProperty): + AddNumbers(text, context.References.FreeTextNumbers); + break; + } + } + + private static void ScanCommand(int code, JArray parameters, ScanContext context) + { + ModReferences references = context.References; + switch (code) + { + case Script or ScriptMore or PluginCommandMv or RouteScript: + AddNumbers(At(parameters, 0), references.FreeTextNumbers); + break; + case PluginCommandMz: + AddNumbers(At(parameters, 3), references.FreeTextNumbers); + break; + case ConditionalBranch when Is(parameters, 0, BranchScript): + AddNumbers(At(parameters, 1), references.FreeTextNumbers); + break; + case ControlVariables when Is(parameters, 3, OperandScript): + AddNumbers(At(parameters, 4), references.FreeTextNumbers); + break; + case ControlVariables when Is(parameters, 3, OperandConstant): + AddId(At(parameters, 4), references.VariableConstants); + break; + case TransferPlayer when Is(parameters, 0, DesignationByVariable): + case SetVehicleLocation when Is(parameters, 1, DesignationByVariable): + references.UsesVariableTransfer = true; + break; + } + + if (context.IsMapFile) + { + return; + } + + // Outside a map the event commands act on whatever map is loaded, so their ids cannot be rewritten (3.11). + foreach (int index in EventPositions(code, parameters)) + { + AddId(At(parameters, index), references.AmbiguousEventIds); + } + } + + private static void RewriteCommand(JObject command, Dictionary maps, Dictionary? events) + { + if (!TryCommand(command, out int code, out JArray? parameters)) + { + return; + } + + if (maps.Count > 0) + { + if (code == TransferPlayer && Is(parameters, 0, DesignationDirect)) + { + Move(parameters, 1, maps); + } + else if (code == SetVehicleLocation && Is(parameters, 1, DesignationDirect)) + { + Move(parameters, 2, maps); + } + } + + if (events is not null) + { + foreach (int index in EventPositions(code, parameters)) + { + Move(parameters, index, events); + } + } + } + + /// The positions of a command that hold an event id of the current map, from the reference table. + private static IEnumerable EventPositions(int code, JArray parameters) + { + switch (code) + { + case SetEventLocation: + yield return 0; + if (Is(parameters, 1, EventLocationExchange)) + { + yield return 2; + } + + break; + case SetMovementRoute or ShowAnimation or ShowBalloon: + yield return 0; + break; + case ConditionalBranch when Is(parameters, 0, BranchCharacter): + yield return 1; + break; + case ControlVariables when Is(parameters, 3, OperandGameData) && Is(parameters, 4, GameDataCharacter): + yield return 5; + break; + case GetLocationInfo when Is(parameters, 2, LocationByCharacter): + yield return 3; + break; + } + } + + /// Every command object in , including route commands inside a move route. + private static void VisitCommands(JToken token, Action visit) + { + switch (token) + { + case JObject item: + visit(item); + foreach (JProperty property in item.Properties()) + { + VisitCommands(property.Value, visit); + } + + break; + case JArray list: + foreach (JToken element in list) + { + VisitCommands(element, visit); + } + + break; + } + } + + /// + /// Moves the map ids at the places accepts, walking down + /// from its own path (relative to the record, as op paths are). + /// + private static JToken RewriteAt(JToken token, string path, Func isPlace, Dictionary maps) + { + if (isPlace(path)) + { + return token is JValue value && TryId(value, out int id) && maps.TryGetValue(id, out int moved) ? new JValue(moved) : token; + } + + if (token is not JObject item) + { + return token; + } + + foreach (JProperty property in item.Properties().ToList()) + { + property.Value = RewriteAt(property.Value, MergePath.Child(path, property.Name), isPlace, maps); + } + + return item; + } + + private static void SetOwnId(JToken? value, int oldId, int newId) + { + if (value is JObject record && record[IdProperty] is JValue id && TryId(id, out int current) && current == oldId) + { + record[IdProperty] = newId; + } + } + + private static void Move(JArray parameters, int index, Dictionary moves) + { + if (At(parameters, index) is JValue value && TryId(value, out int id) && moves.TryGetValue(id, out int moved)) + { + parameters[index] = moved; + } + } + + private static bool TryCommand(JObject item, out int code, [NotNullWhen(true)] out JArray? parameters) + { + parameters = item[ParametersProperty] as JArray; + code = 0; + return parameters is not null && item[CodeProperty] is JValue { Type: JTokenType.Integer } value && TryInt(value, out code); + } + + private static JToken? At(JArray parameters, int index) + { + return index < parameters.Count ? parameters[index] : null; + } + + private static bool Is(JArray parameters, int index, int expected) + { + return At(parameters, index) is JValue value && TryInt(value, out int actual) && actual == expected; + } + + /// An id is a whole number above 0 (reference table). + private static bool TryId(JValue value, out int id) + { + return TryInt(value, out id) && id > 0; + } + + private static bool TryInt(JValue value, out int number) + { + number = 0; + if (value.Type != JTokenType.Integer || value.Value is not long whole || whole is < int.MinValue or > int.MaxValue) + { + return false; + } + + number = (int)whole; + return true; + } + + private static void AddId(JToken? token, HashSet ids) + { + if (token is JValue value && TryId(value, out int id)) + { + ids.Add(id); + } + } + + /// Every whole number in : each run of ASCII digits in its text, and each integer. + private static void AddNumbers(JToken? token, HashSet numbers) + { + switch (token) + { + case JValue { Type: JTokenType.String } text: + AddNumbers(text.Value() ?? "", numbers); + break; + case JValue { Type: JTokenType.Integer, Value: long whole }: + numbers.Add(whole); + break; + case JContainer container: + foreach (JToken child in container.Children()) + { + AddNumbers(child is JProperty property ? property.Value : child, numbers); + } + + break; + } + } + + private static void AddNumbers(string text, HashSet numbers) + { + int index = 0; + while (index < text.Length) + { + if (!char.IsAsciiDigit(text[index])) + { + index++; + continue; + } + + int start = index; + while (index < text.Length && char.IsAsciiDigit(text[index])) + { + index++; + } + + // A run too long for a long names no id; "003" is 3, so a padded map name counts. + if (long.TryParse(text.AsSpan(start, index - start), NumberStyles.None, CultureInfo.InvariantCulture, out long number)) + { + numbers.Add(number); + } + } + } + + private sealed record ScanContext(ModReferences References, bool IsMapFile, bool IsPluginList); +} diff --git a/RPGModder.Core/Merge/RemapMod.cs b/RPGModder.Core/Merge/RemapMod.cs new file mode 100644 index 0000000..74991f6 --- /dev/null +++ b/RPGModder.Core/Merge/RemapMod.cs @@ -0,0 +1,11 @@ +namespace RPGModder.Core.Merge; + +/// +/// One installed mod as sees it. A disabled mod still reserves its ids (GR-R5). +/// PluginScripts holds the text of every js/plugins/*.js file the mod ships; a number found only there +/// makes a remap an explicit choice (GR-R11). +/// +public sealed record RemapMod( + ModChangeSet ChangeSet, + bool Enabled, + IReadOnlyList PluginScripts); diff --git a/RPGModder.Core/Merge/RemapPlaces.cs b/RPGModder.Core/Merge/RemapPlaces.cs new file mode 100644 index 0000000..9a46a41 --- /dev/null +++ b/RPGModder.Core/Merge/RemapPlaces.cs @@ -0,0 +1,26 @@ +namespace RPGModder.Core.Merge; + +/// The places an added id occupies in a change set, so an offer can be matched to its IdClash. +internal static class RemapPlaces +{ + /// + /// True when moves the id is about: a map event is the + /// record event:n of its map; a map is its file on * and its MapInfos record. + /// + public static bool Settles(IdRemap remap, Collision collision) + { + if (collision.Kind != CollisionKind.IdClash || !collision.ModIds.Contains(remap.ModId, StringComparer.Ordinal)) + { + return false; + } + + RecordKey key = collision.Key; + return remap.Kind switch + { + IdKind.MapEvent => key.File == remap.Scope && key.Record == RecordKey.ForEvent(remap.FromId), + IdKind.Map => (key.File == RpgDataSchema.MapKey(remap.FromId) && key.IsWholeFile) || + (key.File == RpgDataSchema.MapInfosKey && key.Record == RecordKey.ForIndex(remap.FromId)), + _ => false + }; + } +} diff --git a/RPGModder.Core/Merge/RemapPlan.cs b/RPGModder.Core/Merge/RemapPlan.cs new file mode 100644 index 0000000..513bea1 --- /dev/null +++ b/RPGModder.Core/Merge/RemapPlan.cs @@ -0,0 +1,27 @@ +using RPGModder.Core.Models; + +namespace RPGModder.Core.Merge; + +/// +/// What decided. Remaps is every entry to apply this plan: the recorded ones +/// still in force and the new ones. NewEntries is the part lane A appends to the profile when the plan is +/// deployed (GR-R12). Offers are moves the planner did not make because the old id appears in a plugin file +/// the mod ships (GR-R11); lane A passes them to and appends one when the player +/// chooses . Diagnostics holds rules.remap_target_taken, one per +/// recorded entry whose target vanilla now uses; carries them into the plan. +/// +public sealed record RemapPlan( + IReadOnlyList Remaps, + IReadOnlyList NewEntries, + IReadOnlyList Offers, + IReadOnlyList Diagnostics) +{ + /// The offer that settles by moving , if there is one. + public IdRemap? OfferFor(Collision collision, string modId) + { + ArgumentNullException.ThrowIfNull(collision); + ArgumentNullException.ThrowIfNull(modId); + + return Offers.FirstOrDefault(offer => offer.ModId == modId && RemapPlaces.Settles(offer, collision)); + } +} diff --git a/RPGModder.Core/Merge/RemapTable.cs b/RPGModder.Core/Merge/RemapTable.cs new file mode 100644 index 0000000..db03ba6 --- /dev/null +++ b/RPGModder.Core/Merge/RemapTable.cs @@ -0,0 +1,12 @@ +namespace RPGModder.Core.Merge; + +/// One mod's moves, old id to new id, applied together so no move feeds another. +internal sealed class RemapTable +{ + public Dictionary Maps { get; } = new(); + + /// Event moves by map file key. + public Dictionary> Events { get; } = new(StringComparer.Ordinal); + + public bool IsEmpty => Maps.Count == 0 && Events.Count == 0; +} diff --git a/RPGModder.Core/Merge/Resolution.cs b/RPGModder.Core/Merge/Resolution.cs new file mode 100644 index 0000000..93a586e --- /dev/null +++ b/RPGModder.Core/Merge/Resolution.cs @@ -0,0 +1,11 @@ +namespace RPGModder.Core.Merge; + +/// +/// A player's stored choice. Fingerprint is the collision's fingerprint when the choice was made; it lets +/// tell a reused choice from an exact one (GR-X2). null means "not recorded". +/// +public sealed record Resolution( + string CollisionId, + ResolutionKind Kind, + string? ModId, + string? Fingerprint = null); diff --git a/RPGModder.Core/Merge/ResolutionKind.cs b/RPGModder.Core/Merge/ResolutionKind.cs new file mode 100644 index 0000000..33b42b3 --- /dev/null +++ b/RPGModder.Core/Merge/ResolutionKind.cs @@ -0,0 +1,12 @@ +namespace RPGModder.Core.Merge; + +public enum ResolutionKind +{ + PickMod, + PickVanilla, + KeepBothInProfileOrder, + Gate, + Remap, + Accept, + DisableMod +} diff --git a/RPGModder.Core/Merge/ResolutionSource.cs b/RPGModder.Core/Merge/ResolutionSource.cs new file mode 100644 index 0000000..7d03145 --- /dev/null +++ b/RPGModder.Core/Merge/ResolutionSource.cs @@ -0,0 +1,9 @@ +namespace RPGModder.Core.Merge; + +public enum ResolutionSource +{ + Unresolved, + Profile, + ProfileReused, + Default +} diff --git a/RPGModder.Core/Merge/RpgDataSchema.cs b/RPGModder.Core/Merge/RpgDataSchema.cs new file mode 100644 index 0000000..25d2413 --- /dev/null +++ b/RPGModder.Core/Merge/RpgDataSchema.cs @@ -0,0 +1,446 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Services; +using System.Globalization; + +namespace RPGModder.Core.Merge; + +/// +/// The only place that maps a file or a path to a policy (GR-K1). The tables follow guide 3.3; an array the +/// tables do not name is Atomic and an object they do not name is compared leaf by leaf (GR-K2). +/// +public static class RpgDataSchema +{ + /// Raised whenever a table change makes an old change set mean something else (GR-M11). + public const int SchemaVersion = 1; + + /// The file that carries (C-7). + internal const string SystemFileKey = "data/system.json"; + + /// The field the game reads to tell its saves apart; the writer stamps it (C-7). + internal const string VersionIdField = "versionId"; + + /// The plugin list (guide 3.3). + internal const string PluginListKey = "js/plugins.js"; + + /// The map property that holds the events (guide 3.3). + internal const string EventsProperty = "events"; + + /// The map tree, whose record index is the map id (guide 3.11). + internal const string MapInfosKey = "data/mapinfos.json"; + + /// + /// The highest map id the MV editor gives (GR-R6). Also used when the engine is unknown, because it is the lower + /// of the two. + /// + private const int MvMapIdLimit = 999; + + /// The highest map id the MZ 1.10.0 editor gives (GR-R6; its map tree's maxMapId). + private const int MzMapIdLimit = 2000; + + /// + /// The highest event id per map (GR-R6). The MZ 1.10.0 editor refuses event 1000 ("Cannot create any more + /// events."); MV's limit is taken to be the same. + /// + private const int MapEventIdLimit = 999; + + /// The config save forms 2a decodes (GR-M10); config.save gives merge.config_save_unsupported. + private const string MvConfigSave = "config.rpgsave"; + + private const string MzConfigSave = "config.rmmzsave"; + + private const string SystemFile = "system.json"; + private const string MapInfosFile = "mapinfos.json"; + private const string MapPrefix = "data/map"; + private const string JsonSuffix = ".json"; + + /// The policy table name every MapNNN.json shares; no real file name has angle brackets. + private const string MapTable = ""; + + private const string PagesPath = "pages"; + + private static readonly HashSet ConfigSaveNames = new(StringComparer.Ordinal) + { + MvConfigSave, + MzConfigSave, + "config.save" + }; + + /// The database files of guide 3.3: an array whose index is the record id. + private static readonly HashSet RecordFiles = new(StringComparer.Ordinal) + { + "actors.json", + "classes.json", + "skills.json", + "items.json", + "weapons.json", + "armors.json", + "enemies.json", + "states.json", + "animations.json", + "tilesets.json", + "troops.json", + "commonevents.json", + MapInfosFile + }; + + /// Array policies by file name and by path pattern relative to the record (or to the root of an object file). + private static readonly Dictionary> Policies = new(StringComparer.Ordinal) + { + [MapTable] = new(StringComparer.Ordinal) + { + // Map-level, on record *. + ["data"] = ArrayPolicy.Positional, + ["encounterList"] = ArrayPolicy.Sequence, + + // Event-level, relative to event:. + [PagesPath] = ArrayPolicy.Positional, + ["pages[*].list"] = ArrayPolicy.Commands + }, + ["actors.json"] = new(StringComparer.Ordinal) + { + ["traits"] = ArrayPolicy.Sequence + }, + ["classes.json"] = new(StringComparer.Ordinal) + { + ["params"] = ArrayPolicy.Positional, + ["params[*]"] = ArrayPolicy.Positional, + ["learnings"] = ArrayPolicy.Sequence, + ["traits"] = ArrayPolicy.Sequence + }, + ["skills.json"] = new(StringComparer.Ordinal) + { + ["effects"] = ArrayPolicy.Sequence + }, + ["items.json"] = new(StringComparer.Ordinal) + { + ["effects"] = ArrayPolicy.Sequence + }, + ["weapons.json"] = new(StringComparer.Ordinal) + { + ["traits"] = ArrayPolicy.Sequence + }, + ["armors.json"] = new(StringComparer.Ordinal) + { + ["traits"] = ArrayPolicy.Sequence + }, + ["enemies.json"] = new(StringComparer.Ordinal) + { + ["actions"] = ArrayPolicy.Sequence, + ["dropItems"] = ArrayPolicy.Positional, + ["traits"] = ArrayPolicy.Sequence + }, + ["states.json"] = new(StringComparer.Ordinal) + { + ["traits"] = ArrayPolicy.Sequence + }, + ["tilesets.json"] = new(StringComparer.Ordinal) + { + ["flags"] = ArrayPolicy.Positional + }, + ["troops.json"] = new(StringComparer.Ordinal) + { + ["members"] = ArrayPolicy.Sequence, + ["pages"] = ArrayPolicy.Positional, + ["pages[*].list"] = ArrayPolicy.Commands + }, + ["commonevents.json"] = new(StringComparer.Ordinal) + { + ["list"] = ArrayPolicy.Commands + }, + [SystemFile] = new(StringComparer.Ordinal) + { + ["switches"] = ArrayPolicy.Keyed, + ["variables"] = ArrayPolicy.Keyed, + ["elements"] = ArrayPolicy.Keyed, + ["skillTypes"] = ArrayPolicy.Keyed, + ["weaponTypes"] = ArrayPolicy.Keyed, + ["armorTypes"] = ArrayPolicy.Keyed, + ["equipTypes"] = ArrayPolicy.Keyed, + ["terms.basic"] = ArrayPolicy.Positional, + ["terms.commands"] = ArrayPolicy.Positional, + ["terms.params"] = ArrayPolicy.Positional, + ["sounds"] = ArrayPolicy.Positional + } + }; + + /// Objects that are one value, by table and path pattern (guide 3.3: an event page's moveRoute). + private static readonly Dictionary> AtomicObjects = new(StringComparer.Ordinal) + { + [MapTable] = new(StringComparer.Ordinal) { "pages[*].moveRoute" } + }; + + /// + /// Editor and display fields of System.json that never produce ops (GR-M5), at any depth, because MZ + /// moves the screen fields into advanced. + /// + private static readonly HashSet SystemVolatile = new(StringComparer.Ordinal) + { + VersionIdField, + "editMapId", + "screenWidth", + "screenHeight", + "uiAreaWidth", + "uiAreaHeight", + "windowLineWidth", + "locale", + "title1Name", + "title2Name" + }; + + /// Editor tree state of MapInfos.json records that never produces ops (GR-M5). + private static readonly HashSet MapInfosVolatile = new(StringComparer.Ordinal) + { + "scrollX", + "scrollY", + "expanded" + }; + + /// + /// Whether lane A reads a file's text. A .json file directly inside data/ is data, + /// js/plugins.js is the plugin list, a config save is a config save, everything else is bytes. + /// + public static MergeFileKind KindOf(string path) + { + string key = MergePath.ToKey(path); + if (key == PluginListKey) + { + return MergeFileKind.PluginList; + } + + int slash = key.LastIndexOf('/'); + string name = slash < 0 ? key : key[(slash + 1)..]; + if (ConfigSaveNames.Contains(name)) + { + return MergeFileKind.ConfigSave; + } + + if (slash == "data".Length && key.StartsWith("data/", StringComparison.Ordinal) && name.EndsWith(JsonSuffix, StringComparison.Ordinal)) + { + return MergeFileKind.Data; + } + + return MergeFileKind.Opaque; + } + + /// The root shape of a data file, from the table and, for a file the table does not name, from vanilla's own shape. + internal static RootShape ShapeOf(string fileKey, JToken vanillaRoot) + { + string name = FileName(fileKey); + if (RecordFiles.Contains(name) && vanillaRoot is JArray) + { + return RootShape.Records; + } + + if (IsMapFile(fileKey) && vanillaRoot is JObject) + { + return RootShape.Map; + } + + if (vanillaRoot is JArray array && LooksLikeRecords(array)) + { + return RootShape.Records; + } + + return vanillaRoot is JObject ? RootShape.Object : RootShape.Atomic; + } + + /// + /// The root type the game needs for a file the table names: an object for System.json and a map, an + /// array for a database file. null for any other file, whose root may be anything. + /// + internal static JTokenType? ExpectedRootOf(string fileKey) + { + string name = FileName(fileKey); + if (name == SystemFile || IsMapFile(fileKey)) + { + return JTokenType.Object; + } + + return RecordFiles.Contains(name) ? JTokenType.Array : null; + } + + internal static ArrayPolicy PolicyOf(string fileKey, string path) + { + if (Policies.TryGetValue(TableOf(fileKey), out Dictionary? table) && + table.TryGetValue(MergePath.Pattern(path), out ArrayPolicy policy)) + { + return policy; + } + + return ArrayPolicy.Atomic; + } + + /// True when the object at is one value, not compared leaf by leaf. + internal static bool IsAtomicObject(string fileKey, string path) + { + return AtomicObjects.TryGetValue(TableOf(fileKey), out HashSet? paths) && paths.Contains(MergePath.Pattern(path)); + } + + /// data/MapNNN.json: map, then one or more digits. + internal static bool IsMapFile(string fileKey) + { + if (!fileKey.StartsWith(MapPrefix, StringComparison.Ordinal) || + !fileKey.EndsWith(JsonSuffix, StringComparison.Ordinal) || + fileKey.Length <= MapPrefix.Length + JsonSuffix.Length) + { + return false; + } + + foreach (char current in fileKey.AsSpan(MapPrefix.Length, fileKey.Length - MapPrefix.Length - JsonSuffix.Length)) + { + if (!char.IsAsciiDigit(current)) + { + return false; + } + } + + return true; + } + + /// + /// The map id of data/mapNNN.json in the one form the game loads: at least three digits, no extra + /// leading zero, an id from 1 up. + /// + internal static bool TryGetMapId(string fileKey, out int id) + { + id = 0; + return IsMapFile(fileKey) && + int.TryParse(fileKey.AsSpan(MapPrefix.Length, fileKey.Length - MapPrefix.Length - JsonSuffix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out id) && + id > 0 && + MapKey(id) == fileKey; + } + + /// The key of map , the name DataManager.loadMapData builds, lower-cased. + internal static string MapKey(int id) + { + return MapPrefix + id.ToString("D3", CultureInfo.InvariantCulture) + JsonSuffix; + } + + /// The casing the game asks for, for a map file lane B renders as text (seam 3.3, DiskPath). + internal static string? DiskPathOf(string fileKey) + { + return TryGetMapId(fileKey, out int id) ? "data/Map" + id.ToString("D3", CultureInfo.InvariantCulture) + JsonSuffix : null; + } + + /// + /// The highest id a remap may give, or null for a kind step 1 does not remap (GR-R6). A null + /// engine gets MV's limits. + /// + internal static int? RemapLimit(IdKind kind, RpgMakerEngine? engine) + { + return kind switch + { + IdKind.Map => engine == RpgMakerEngine.MZ ? MzMapIdLimit : MvMapIdLimit, + IdKind.MapEvent => MapEventIdLimit, + _ => null + }; + } + + /// + /// A page setting of a map event (seam 11.1): the pages list itself, or anything under one page except + /// its command list, which is a LogicClash place. + /// + internal static bool IsPageSetting(RecordKey key, string path) + { + if (!IsMapFile(key.File) || !RecordKey.TryGetEvent(key.Record, out _) || MergePath.IsPseudoLeaf(path)) + { + return false; + } + + IReadOnlyList segments = MergePath.Parse(path); + if (segments.Count == 0 || segments[0].Name != PagesPath) + { + return false; + } + + return segments.Count < 3 || segments[1].Name is not null || segments[2].Name != "list"; + } + + /// The config save forms 2a decodes. Only files are asked. + internal static bool IsDecodedConfigSave(string fileKey) + { + string name = FileName(fileKey); + return name is MvConfigSave or MzConfigSave; + } + + /// The MZ form, a zlib byte string; picks its codec by this. + internal static bool IsMzConfigSave(string fileKey) + { + return FileName(fileKey) == MzConfigSave; + } + + /// + /// The events list of a map is a record list when every entry is null or an object whose id is + /// its index (seam 11.1); a list of only null counts, because a map without events is still a map. + /// + internal static bool IsEventList(JToken? events) + { + return events is JArray array && (array.All(element => element.Type == JTokenType.Null) || LooksLikeRecords(array)); + } + + /// True when the property under never produces an op. + internal static bool IsVolatile(string fileKey, string parentPath, string propertyName) + { + string name = FileName(fileKey); + if (name == SystemFile) + { + return SystemVolatile.Contains(propertyName); + } + + return name == MapInfosFile && parentPath.Length == 0 && MapInfosVolatile.Contains(propertyName); + } + + /// Guide 3.3, last data row: elements that are null or objects whose id equals their index. + private static bool LooksLikeRecords(JArray array) + { + bool anyRecord = false; + for (int index = 0; index < array.Count; index++) + { + JToken element = array[index]; + if (element.Type == JTokenType.Null) + { + continue; + } + + // An id too large for a long is held as a BigInteger; it matches no index, so the array is not records. + if (element is not JObject record || + record["id"] is not JValue { Type: JTokenType.Integer, Value: long id } || + id != index) + { + return false; + } + + anyRecord = true; + } + + return anyRecord; + } + + private static string TableOf(string fileKey) + { + return IsMapFile(fileKey) ? MapTable : FileName(fileKey); + } + + private static string FileName(string fileKey) + { + int slash = fileKey.LastIndexOf('/'); + return slash < 0 ? fileKey : fileKey[(slash + 1)..]; + } +} + +internal enum RootShape +{ + Records, + Map, + Object, + Atomic +} + +internal enum ArrayPolicy +{ + Keyed, + Positional, + Sequence, + Commands, + Atomic +} diff --git a/RPGModder.Core/Operations/DiagnosticCodes.cs b/RPGModder.Core/Operations/DiagnosticCodes.cs index 772bac4..1e0bc4a 100644 --- a/RPGModder.Core/Operations/DiagnosticCodes.cs +++ b/RPGModder.Core/Operations/DiagnosticCodes.cs @@ -39,11 +39,15 @@ public static class DiagnosticCodes public const string MergeParseFailed = "merge.parse_failed"; public const string MergeBaseParseFailed = "merge.base_parse_failed"; public const string MergePatchTargetMissing = "merge.patch_target_missing"; + public const string MergePatchShapeMismatch = "merge.patch_shape_mismatch"; + public const string MergeRootShapeMismatch = "merge.root_shape_mismatch"; + public const string MergeConfigSaveUnsupported = "merge.config_save_unsupported"; public const string RulesResolutionReused = "rules.resolution_reused"; public const string RulesScopeReduced = "rules.scope_reduced"; public const string RulesRemapApplied = "rules.remap_applied"; public const string RulesRemapUnchecked = "rules.remap_unchecked"; + public const string RulesRemapTargetTaken = "rules.remap_target_taken"; public const string RulesSwitchBandMoved = "rules.switch_band_moved"; public const string RulesSwitchBandExhausted = "rules.switch_band_exhausted"; diff --git a/RPGModder.Tests/Merge/ChangeSetBuilderTests.cs b/RPGModder.Tests/Merge/ChangeSetBuilderTests.cs new file mode 100644 index 0000000..20aa53a --- /dev/null +++ b/RPGModder.Tests/Merge/ChangeSetBuilderTests.cs @@ -0,0 +1,450 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using static RPGModder.Tests.Merge.MergeTestKit; + +namespace RPGModder.Tests.Merge; + +public sealed class ChangeSetBuilderTests +{ + private static string[] Ops(ModSource mod, BaseFileSet bases) + { + ModChangeSet set = Build(mod, bases); + Assert.Empty(set.Diagnostics); + return set.Ops.Select(Describe).ToArray(); + } + + [Fact] + public void LeafEdit_IsOneSetLeafOnTheRecord() + { + string text = EditItems(items => items[2]!["price"] = 250); + + Assert.Equal( + ["data/items.json|id:2|price|SetLeaf|250"], + Ops(FileMod("a-mod", Items, text), Bases(Base(Items, VanillaItems)))); + } + + [Fact] + public void NewRecord_IsAddRecordWithTheWholeRecord() + { + string text = EditItems(items => items.Add(JObject.Parse("{\"id\":3,\"name\":\"Elixir\"}"))); + + Assert.Equal( + ["data/items.json|id:3||AddRecord|{\"id\":3,\"name\":\"Elixir\"}"], + Ops(FileMod("a-mod", Items, text), Bases(Base(Items, VanillaItems)))); + } + + [Fact] + public void RecordSetToNullOrCutOff_IsRemoveRecord() + { + string nulled = EditItems(items => items[1] = JValue.CreateNull()); + string cut = EditItems(items => items.RemoveAt(2)); + BaseFileSet bases = Bases(Base(Items, VanillaItems)); + + Assert.Equal(["data/items.json|id:1||RemoveRecord|-"], Ops(FileMod("a-mod", Items, nulled), bases)); + Assert.Equal(["data/items.json|id:2||RemoveRecord|-"], Ops(FileMod("a-mod", Items, cut), bases)); + } + + [Fact] + public void SequenceArray_IsOneEditSequenceWithTheWholeList() + { + string text = EditItems(items => ((JArray)items[1]!["effects"]!).Add(JObject.Parse("{\"code\":21}"))); + + string[] ops = Ops(FileMod("a-mod", Items, text), Bases(Base(Items, VanillaItems))); + + Assert.Single(ops); + Assert.StartsWith("data/items.json|id:1|effects|EditSequence|[", ops[0]); + } + + [Fact] + public void RemovedProperty_IsRemoveLeaf() + { + string text = EditItems(items => ((JObject)items[2]!).Remove("note")); + + Assert.Equal( + ["data/items.json|id:2|note|RemoveLeaf|-"], + Ops(FileMod("a-mod", Items, text), Bases(Base(Items, VanillaItems)))); + } + + [Fact] + public void PositionalArrays_AreComparedPerIndex_AndALengthChangeIsOneValue() + { + const string vanilla = "[null,{\"id\":1,\"params\":[[1,2,3],[4,5,6]],\"learnings\":[],\"traits\":[]}]"; + string edited = vanilla.Replace("[4,5,6]", "[4,9,6]"); + string resized = vanilla.Replace("[4,5,6]", "[4,5,6,7]"); + BaseFileSet bases = Bases(Base(Classes, vanilla)); + + Assert.Equal(["data/classes.json|id:1|params[1][1]|SetLeaf|9"], Ops(FileMod("a-mod", Classes, edited), bases)); + Assert.Equal(["data/classes.json|id:1|params[1]|SetLeaf|[4,5,6,7]"], Ops(FileMod("a-mod", Classes, resized), bases)); + } + + [Fact] + public void ArrayTheSchemaDoesNotName_IsAtomic() + { + const string vanilla = "[null,{\"id\":1,\"equips\":[1,1,2,3,0]}]"; + string edited = vanilla.Replace("[1,1,2,3,0]", "[1,1,2,3,4]"); + + Assert.Equal( + ["data/actors.json|id:1|equips|SetLeaf|[1,1,2,3,4]"], + Ops(FileMod("a-mod", "data/Actors.json", edited), Bases(Base("data/Actors.json", vanilla)))); + } + + [Fact] + public void CommandLists_AreOneEditCommands_InCommonEventsAndTroopPages() + { + const string events = "[null,{\"id\":1,\"name\":\"E\",\"list\":[{\"code\":0,\"indent\":0,\"parameters\":[]}]}]"; + const string troops = "[null,{\"id\":1,\"members\":[{\"enemyId\":1}],\"pages\":[{\"span\":0,\"list\":[{\"code\":0}]}]}]"; + string eventsEdited = events.Replace("\"list\":[", "\"list\":[{\"code\":101},"); + string troopsEdited = troops.Replace("\"list\":[", "\"list\":[{\"code\":101},").Replace("\"enemyId\":1", "\"enemyId\":2"); + + Assert.Equal( + ["data/commonevents.json|id:1|list|EditCommands|[{\"code\":101},{\"code\":0,\"indent\":0,\"parameters\":[]}]"], + Ops(FileMod("a-mod", "data/CommonEvents.json", eventsEdited), Bases(Base("data/CommonEvents.json", events)))); + Assert.Equal( + [ + "data/troops.json|id:1|members|EditSequence|[{\"enemyId\":2}]", + "data/troops.json|id:1|pages[0].list|EditCommands|[{\"code\":101},{\"code\":0}]" + ], + Ops(FileMod("a-mod", "data/Troops.json", troopsEdited), Bases(Base("data/Troops.json", troops)))); + } + + [Fact] + public void SystemNameArrays_AreKeyedPerIndex_AndTermsArePositional() + { + string text = EditSystem(system => + { + ((JArray)system["switches"]!).Add("Bridge"); + system["switches"]![1] = "Gate"; + system["terms"]!["basic"]![1] = "LV"; + }); + + Assert.Equal( + [ + "data/system.json|*|switches[1]|SetLeaf|\"Gate\"", + "data/system.json|*|switches[3]|SetLeaf|\"Bridge\"", + "data/system.json|*|terms.basic[1]|SetLeaf|\"LV\"" + ], + Ops(FileMod("a-mod", SystemFile, text), Bases(Base(SystemFile, VanillaSystem)))); + } + + [Fact] + public void ShortenedNameArray_RemovesTheMissingIndexes() + { + string text = EditSystem(system => ((JArray)system["switches"]!).RemoveAt(2)); + + Assert.Equal( + ["data/system.json|*|switches[2]|RemoveLeaf|-"], + Ops(FileMod("a-mod", SystemFile, text), Bases(Base(SystemFile, VanillaSystem)))); + } + + [Fact] + public void VolatileFields_GiveNoOps_EvenNestedAndThroughPatches() + { + string text = EditSystem(system => + { + system["versionId"] = 99; + system["editMapId"] = 7; + system["screenWidth"] = 1280; + system["advanced"] = null; + }); + string withAdvanced = VanillaSystem.Replace("\"partyMembers\"", "\"advanced\":{\"screenWidth\":816,\"fontSize\":26},\"partyMembers\""); + BaseFileSet advancedBases = Bases(Base(SystemFile, withAdvanced)); + + Assert.Equal( + ["data/system.json|*|advanced|SetLeaf|null"], + Ops(FileMod("a-mod", SystemFile, text), Bases(Base(SystemFile, VanillaSystem)))); + Assert.Empty(Ops(PatchMod("a-mod", SystemFile, "{\"advanced\":{\"screenWidth\":1280},\"versionId\":3}"), advancedBases)); + } + + [Fact] + public void MapInfosEditorState_GivesNoOps() + { + const string vanilla = "[null,{\"id\":1,\"expanded\":false,\"name\":\"Town\",\"scrollX\":0,\"scrollY\":0}]"; + const string edited = "[null,{\"id\":1,\"expanded\":true,\"name\":\"Town\",\"scrollX\":500,\"scrollY\":40}]"; + + Assert.Empty(Ops(FileMod("a-mod", "data/MapInfos.json", edited), Bases(Base("data/MapInfos.json", vanilla)))); + } + + [Fact] + public void UnknownDataFile_IsDetectedFromVanillaShape() + { + const string records = "[null,{\"id\":1,\"label\":\"x\",\"rows\":[1,2]}]"; + const string other = "[1,2,3]"; + BaseFileSet bases = Bases(Base("data/Quests.json", records), Base("data/Table.json", other)); + + Assert.Equal( + ["data/quests.json|id:1|rows|SetLeaf|[1,3]"], + Ops(FileMod("a-mod", "data/Quests.json", records.Replace("[1,2]", "[1,3]")), bases)); + Assert.Equal( + ["data/table.json|*||SetLeaf|[1,2,4]"], + Ops(FileMod("a-mod", "data/Table.json", "[1,2,4]"), bases)); + } + + [Fact] + public void RootOfAnotherType_InAFileTheTableDoesNotName_IsOneValueForTheWholeFile() + { + Assert.Equal( + ["data/quests.json|*||SetLeaf|{\"quests\":[]}"], + Ops(FileMod("a-mod", Quests, "{\"quests\":[]}"), Bases(Base(Quests, VanillaQuests)))); + } + + [Fact] + public void PatchAndWholeFile_GiveTheSameOps() + { + string text = EditSystem(system => + { + system["currencyUnit"] = "Coins"; + system["terms"]!["messages"]!["victory"] = "Done"; + }); + BaseFileSet bases = Bases(Base(SystemFile, VanillaSystem)); + + ModChangeSet whole = Build(FileMod("a-mod", SystemFile, text), bases); + ModChangeSet patch = Build(PatchMod("a-mod", SystemFile, "{\"currencyUnit\":\"Coins\",\"terms\":{\"messages\":{\"victory\":\"Done\"}}}"), bases); + + Assert.Equal( + whole.Ops.Select(op => Describe(op)), + patch.Ops.Select(op => Describe(op))); + Assert.All(patch.Ops, op => Assert.Null(op.SourceFile)); + Assert.All(whole.Ops, op => Assert.Equal("files/System.json", op.SourceFile)); + } + + [Fact] + public void PatchesApplyAfterTheModsOwnFile_InManifestOrder() + { + string text = EditSystem(system => system["currencyUnit"] = "Coins"); + var mod = new ModSource( + "a-mod", + 0, + [new ModFile(SystemFile, "System.json", text, Hash(text))], + [ + new ModPatch(SystemFile, JObject.Parse("{\"gameTitle\":\"One\"}")), + new ModPatch("DATA\\system.json", JObject.Parse("{\"gameTitle\":\"Two\"}")) + ], + []); + + Assert.Equal( + [ + "data/system.json|*|currencyUnit|SetLeaf|\"Coins\"", + "data/system.json|*|gameTitle|SetLeaf|\"Two\"" + ], + Ops(mod, Bases(Base(SystemFile, VanillaSystem)))); + } + + [Fact] + public void BrokenModFile_GivesParseFailedWithTheModId_AndNoOpForThatFile() + { + string good = EditSystem(system => system["currencyUnit"] = "Coins"); + var mod = new ModSource( + "a-mod", + 0, + [ + new ModFile(Items, "Items.json", "[null,{\"id\":1,", Hash("x")), + new ModFile(SystemFile, "System.json", good, Hash(good)) + ], + [], + []); + + ModChangeSet set = Build(mod, Bases(Base(Items, VanillaItems), Base(SystemFile, VanillaSystem))); + + OperationDiagnostic diagnostic = Assert.Single(set.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeParseFailed, diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); + Assert.Equal("a-mod", diagnostic.Subject); + Assert.Contains("Items.json", diagnostic.Message); + Assert.Equal(["data/system.json|*|currencyUnit|SetLeaf|\"Coins\""], set.Ops.Select(Describe)); + } + + [Theory] + [InlineData("[1,2] trailing")] + [InlineData("")] + public void TextAfterTheRootOrNoText_IsAParseFailure(string text) + { + ModChangeSet set = Build(FileMod("a-mod", Items, text), Bases(Base(Items, VanillaItems))); + + Assert.Equal(DiagnosticCodes.MergeParseFailed, Assert.Single(set.Diagnostics).Code); + Assert.Empty(set.Ops); + } + + [Fact] + public void BrokenBaseFile_GivesBaseParseFailedWithTheFile() + { + ModChangeSet set = Build(FileMod("a-mod", Items, VanillaItems), Bases(Base(Items, "{oops"))); + + OperationDiagnostic diagnostic = Assert.Single(set.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeBaseParseFailed, diagnostic.Code); + Assert.Equal("data/items.json", diagnostic.Subject); + Assert.Empty(set.Ops); + } + + [Fact] + public void PatchOfAFileVanillaDoesNotHave_GivesPatchTargetMissing() + { + ModChangeSet set = Build(PatchMod("a-mod", "data/Missing.json", "{\"a\":1}"), Bases()); + + OperationDiagnostic diagnostic = Assert.Single(set.Diagnostics); + Assert.Equal(DiagnosticCodes.MergePatchTargetMissing, diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); + Assert.Equal("a-mod", diagnostic.Subject); + } + + [Fact] + public void PatchOfAnArrayFile_GivesPatchShapeMismatch() + { + ModChangeSet set = Build(PatchMod("a-mod", Items, "{\"1\":{\"price\":1}}"), Bases(Base(Items, VanillaItems))); + + Assert.Equal(DiagnosticCodes.MergePatchShapeMismatch, Assert.Single(set.Diagnostics).Code); + Assert.Empty(set.Ops); + } + + [Fact] + public void DateLikeStrings_StayStrings() + { + string text = EditItems(items => items[1]!["note"] = "2024-01-02T03:04:05Z"); + + ModChangeSet set = Build(FileMod("a-mod", Items, text), Bases(Base(Items, VanillaItems))); + + Assert.Equal(JTokenType.String, Assert.Single(set.Ops).Value!.Type); + } + + [Fact] + public void SameInput_GivesEqualOutput() + { + string text = EditItems(items => + { + items[1]!["price"] = 1; + items.Add(JObject.Parse("{\"id\":3}")); + }); + ModSource mod = FileMod("a-mod", Items, text); + BaseFileSet bases = Bases(Base(Items, VanillaItems)); + + Assert.Equal( + ModChangeSetSerializer.Serialize(Build(mod, bases)), + ModChangeSetSerializer.Serialize(Build(mod, bases))); + } + + [Fact] + public void OddPropertyNames_AreQuotedInThePath() + { + const string vanilla = "{\"a.b\":1,\"it's\":1}"; + const string edited = "{\"a.b\":2,\"it's\":2}"; + + Assert.Equal( + ["data/odd.json|*|['a.b']|SetLeaf|2", "data/odd.json|*|['it\\'s']|SetLeaf|2"], + Ops(FileMod("a-mod", "data/Odd.json", edited), Bases(Base("data/Odd.json", vanilla)))); + } + + [Theory] + [InlineData(Items, "{\"items\":[]}")] + [InlineData(SystemFile, "[]")] + [InlineData(SystemFile, "null")] + public void ModRootOfAnotherType_InAFileTheGameReads_IsRootShapeMismatchOnTheMod(string file, string text) + { + BaseFileSet bases = Bases(Base(Items, VanillaItems), Base(SystemFile, VanillaSystem)); + + ModChangeSet set = Build(FileMod("a-mod", file, text), bases); + + Assert.Empty(set.Ops); + OperationDiagnostic diagnostic = Assert.Single(set.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeRootShapeMismatch, diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); + Assert.Equal("a-mod", diagnostic.Subject); + } + + [Fact] + public void GameRootOfAnotherType_IsRootShapeMismatchOnTheFile() + { + ModChangeSet set = Build(FileMod("a-mod", Items, VanillaItems), Bases(Base(Items, "{\"id\":1}"))); + + Assert.Empty(set.Ops); + OperationDiagnostic diagnostic = Assert.Single(set.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeRootShapeMismatch, diagnostic.Code); + Assert.Equal("data/items.json", diagnostic.Subject); + } + + [Theory] + [InlineData("[null,{\"id\":1,\"price\":undefined}]")] + [InlineData("[null,{\"id\":1,\"price\":new Date(5)}]")] + [InlineData("[null,{\"id\":1,\"price\":NaN}]")] + [InlineData("[null,{\"id\":1,\"price\":1e999}]")] + [InlineData("[null,{'id':1}]")] + [InlineData("[null,{id:1}]")] + [InlineData("[null,{\"id\":1},]")] + [InlineData("[null,{\"id\":0x10}]")] + [InlineData("[null,{\"id\":1} /* note */]")] + [InlineData("[null,{\"id\":1}] []")] + public void TextTheGameCannotParse_IsParseFailed_WithNoOp(string text) + { + ModChangeSet set = Build(FileMod("a-mod", Items, text), Bases(Base(Items, VanillaItems))); + + Assert.Empty(set.Ops); + OperationDiagnostic diagnostic = Assert.Single(set.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeParseFailed, diagnostic.Code); + Assert.Contains("line 1, position", diagnostic.Message); + } + + [Fact] + public void LeadingByteOrderMark_IsRead() + { + string text = "\uFEFF" + EditItems(items => items[2]!["price"] = 250); + + Assert.Equal( + ["data/items.json|id:2|price|SetLeaf|250"], + Ops(FileMod("a-mod", Items, text), Bases(Base(Items, VanillaItems)))); + } + + [Fact] + public void IdTooLargeForALong_InAFileTheTableDoesNotName_IsOneValue() + { + Assert.Equal( + ["data/quests.json|*||SetLeaf|[{\"id\":1}]"], + Ops(FileMod("a-mod", Quests, "[{\"id\":1}]"), Bases(Base(Quests, "[{\"id\":99999999999999999999}]")))); + } + + [Fact] + public void FileOpsNamingOneTargetTwice_TheLaterEntryWins() + { + string first = EditItems(items => items[2]!["price"] = 1); + string second = EditItems(items => items[2]!["price"] = 2); + var mod = new ModSource( + "a-mod", + 0, + [new ModFile(Items, "files/first.json", first, Hash(first)), new ModFile(Items, "files/second.json", second, Hash(second))], + [], + []); + + ChangeOp op = Assert.Single(Build(mod, Bases(Base(Items, VanillaItems))).Ops); + + Assert.Equal("data/items.json|id:2|price|SetLeaf|2", Describe(op)); + Assert.Equal("files/second.json", op.SourceFile); + } + + [Theory] + [InlineData("data/Tilesets.json", "flags", "[0,16,15]", "[0,16,9]", "flags[2]|SetLeaf|9")] + [InlineData("data/Tilesets.json", "tilesetNames", "[\"A\",\"B\"]", "[\"A\",\"C\"]", "tilesetNames|SetLeaf|[\"A\",\"C\"]")] + [InlineData("data/Enemies.json", "dropItems", "[{\"kind\":0},{\"kind\":1}]", "[{\"kind\":0},{\"kind\":2}]", "dropItems[1].kind|SetLeaf|2")] + [InlineData("data/Enemies.json", "actions", "[{\"skillId\":1}]", "[{\"skillId\":1},{\"skillId\":2}]", "actions|EditSequence|[{\"skillId\":1},{\"skillId\":2}]")] + [InlineData("data/Classes.json", "learnings", "[{\"level\":1,\"skillId\":3}]", "[]", "learnings|EditSequence|[]")] + public void RecordFileArrays_FollowTheSchemaTable(string file, string field, string before, string after, string expected) + { + string vanilla = $"[null,{{\"id\":1,\"{field}\":{before}}}]"; + string modded = $"[null,{{\"id\":1,\"{field}\":{after}}}]"; + + Assert.Equal( + [$"{MergePath.ToKey(file)}|id:1|{expected}"], + Ops(FileMod("a-mod", file, modded), Bases(Base(file, vanilla)))); + } + + [Theory] + [InlineData("{\"sounds\":[{\"name\":\"A\"},{\"name\":\"B\"}]}", "{\"sounds\":[{\"name\":\"A\"},{\"name\":\"C\"}]}", "sounds[1].name|SetLeaf|\"C\"")] + [InlineData("{\"terms\":{\"commands\":[\"Fight\",\"Escape\"]}}", "{\"terms\":{\"commands\":[\"Fight\",\"Run\"]}}", "terms.commands[1]|SetLeaf|\"Run\"")] + [InlineData("{\"terms\":{\"params\":[\"HP\",\"MP\"]}}", "{\"terms\":{\"params\":[\"HP\",\"SP\"]}}", "terms.params[1]|SetLeaf|\"SP\"")] + [InlineData("{\"elements\":[\"\",\"Fire\"]}", "{\"elements\":[\"\",\"Fire\",\"Ice\"]}", "elements[2]|SetLeaf|\"Ice\"")] + [InlineData("{\"partyMembers\":[1]}", "{\"partyMembers\":[1,2]}", "partyMembers|SetLeaf|[1,2]")] + public void SystemArrays_FollowTheSchemaTable(string vanilla, string modded, string expected) + { + Assert.Equal( + [$"data/system.json|*|{expected}"], + Ops(FileMod("a-mod", SystemFile, modded), Bases(Base(SystemFile, vanilla)))); + } +} diff --git a/RPGModder.Tests/Merge/ComposerTests.cs b/RPGModder.Tests/Merge/ComposerTests.cs new file mode 100644 index 0000000..588b13d --- /dev/null +++ b/RPGModder.Tests/Merge/ComposerTests.cs @@ -0,0 +1,512 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using System.Security.Cryptography; +using System.Text; +using static RPGModder.Tests.Merge.MergeTestKit; + +namespace RPGModder.Tests.Merge; + +public sealed class ComposerTests +{ + private static readonly BaseFileSet ItemBases = Bases(Base(Items, VanillaItems)); + + private static ModSource Price(string modId, int itemId, int price) + { + return FileMod(modId, Items, EditItems(items => items[itemId]!["price"] = price)); + } + + private static ModSource Name(string modId, int itemId, string name) + { + return FileMod(modId, Items, EditItems(items => items[itemId]!["name"] = name)); + } + + private static ModSource Removal(string modId, int itemId) + { + return FileMod(modId, Items, EditItems(items => items[itemId] = JValue.CreateNull())); + } + + private static string[] OpsOf(MergePlan plan) + { + return plan.Ops.Select(merged => Describe(merged.Op)).ToArray(); + } + + [Fact] + public void DifferentFieldsOfOneRecord_BothApply() + { + MergePlan plan = Compose( + ItemBases, + Price("a-tin", 1, 60), + FileMod("b-oak", Items, EditItems(items => items[1]!["name"] = "Big Tonic"))); + + Assert.True(plan.IsDeployable); + Assert.Empty(plan.Collisions); + Assert.Equal( + ["data/items.json|id:1|name|SetLeaf|\"Big Tonic\"", "data/items.json|id:1|price|SetLeaf|60"], + plan.Ops.Select(merged => Describe(merged.Op))); + } + + [Fact] + public void EqualEdits_AreOneOpWithEveryMod() + { + MergePlan plan = Compose(ItemBases, Price("b-oak", 1, 60), Price("a-tin", 1, 60)); + + MergedOp merged = Assert.Single(plan.Ops); + Assert.Equal(["a-tin", "b-oak"], merged.ModIds); + Assert.Equal("a-tin", merged.Op.ModId); + Assert.Empty(plan.Collisions); + } + + [Fact] + public void DifferentValues_AreABlockingValueClash() + { + MergePlan plan = Compose(ItemBases, Price("a-tin", 2, 1), Price("b-oak", 2, 2)); + + Collision collision = Assert.Single(plan.Collisions); + Assert.Equal(CollisionKind.ValueClash, collision.Kind); + Assert.Equal(new RecordKey("data/items.json", "id:2"), collision.Key); + Assert.Equal("price", collision.Path); + Assert.Equal(["a-tin", "b-oak"], collision.ModIds); + Assert.True(collision.Blocking); + Assert.Equal([ResolutionKind.PickMod, ResolutionKind.PickVanilla], collision.Allowed); + Assert.Equal(ResolutionSource.Unresolved, Assert.Single(plan.Outcomes).Source); + Assert.False(plan.IsDeployable); + Assert.Empty(plan.Ops); + } + + [Fact] + public void CollisionId_IsTheDocumentedHash() + { + MergePlan plan = Compose(ItemBases, Price("a-tin", 2, 1), Price("b-oak", 2, 2)); + + string expected = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes( + "ValueClash\ndata/items.json\nid:2\nprice\na-tin\nb-oak")))[..16]; + Assert.Equal(expected, Assert.Single(plan.Collisions).Id); + } + + [Fact] + public void CollisionId_IgnoresValues_ButFingerprintDoesNot() + { + Collision first = Assert.Single(Compose(ItemBases, Price("a-tin", 2, 1), Price("b-oak", 2, 2)).Collisions); + Collision second = Assert.Single(Compose(ItemBases, Price("a-tin", 2, 1), Price("b-oak", 2, 3)).Collisions); + + Assert.Equal(first.Id, second.Id); + Assert.NotEqual(first.Fingerprint, second.Fingerprint); + } + + [Fact] + public void RemoveAgainstEdit_IsDeleteVersusEditOnTheRecord() + { + MergePlan plan = Compose( + ItemBases, + FileMod("a-tin", Items, EditItems(items => items[2] = JValue.CreateNull())), + Price("b-oak", 2, 9)); + + Collision collision = Assert.Single(plan.Collisions); + Assert.Equal(CollisionKind.DeleteVersusEdit, collision.Kind); + Assert.Equal("id:2", collision.Key.Record); + Assert.Equal("", collision.Path); + Assert.Equal([ResolutionKind.PickMod, ResolutionKind.PickVanilla], collision.Allowed); + } + + [Fact] + public void DifferentNewRecordsAtOneId_AreAnIdClash_AndEqualOnesAreOneOp() + { + ModSource Add(string modId, string name) + { + return FileMod(modId, Items, EditItems(items => items.Add(new JObject { ["id"] = 3, ["name"] = name }))); + } + + MergePlan clash = Compose(ItemBases, Add("a-tin", "Rope"), Add("b-oak", "Lamp")); + MergePlan same = Compose(ItemBases, Add("a-tin", "Rope"), Add("b-oak", "Rope")); + + Collision collision = Assert.Single(clash.Collisions); + Assert.Equal(CollisionKind.IdClash, collision.Kind); + Assert.True(collision.Blocking); + Assert.Equal([ResolutionKind.PickMod, ResolutionKind.DisableMod], collision.Allowed); + Assert.Empty(same.Collisions); + Assert.Equal(["a-tin", "b-oak"], Assert.Single(same.Ops).ModIds); + } + + [Fact] + public void DifferentSequences_AreASequenceClash_AndDifferentCommandLists_ALogicClash() + { + ModSource Effects(string modId, int code) + { + return FileMod(modId, Items, EditItems(items => items[2]!["effects"] = new JArray(new JObject { ["code"] = code }))); + } + + const string events = "[null,{\"id\":1,\"list\":[{\"code\":0}]}]"; + BaseFileSet eventBases = Bases(Base("data/CommonEvents.json", events)); + + Collision sequence = Assert.Single(Compose(ItemBases, Effects("a-tin", 11), Effects("b-oak", 12)).Collisions); + Collision logic = Assert.Single(Compose( + eventBases, + FileMod("a-tin", "data/CommonEvents.json", events.Replace("[{", "[{\"code\":101},{")), + FileMod("b-oak", "data/CommonEvents.json", events.Replace("[{", "[{\"code\":102},{"))).Collisions); + + Assert.Equal(CollisionKind.SequenceClash, sequence.Kind); + Assert.Equal(CollisionKind.LogicClash, logic.Kind); + Assert.True(sequence.Blocking); + Assert.True(logic.Blocking); + } + + [Fact] + public void PathInsideAnotherModsValue_IsAValueClashOnTheShorterPath() + { + const string vanilla = "[null,{\"id\":1,\"params\":[[1,2,3],[4,5,6]]}]"; + BaseFileSet bases = Bases(Base(Classes, vanilla)); + + MergePlan plan = Compose( + bases, + FileMod("a-tin", Classes, vanilla.Replace("[4,5,6]", "[4,5,6,7]")), + FileMod("b-oak", Classes, vanilla.Replace("[4,5,6]", "[4,9,6]"))); + + Collision collision = Assert.Single(plan.Collisions); + Assert.Equal(CollisionKind.ValueClash, collision.Kind); + Assert.Equal("params[1]", collision.Path); + Assert.Equal(["a-tin", "b-oak"], collision.ModIds); + } + + [Fact] + public void WholeFileValue_ClashesWithAnyRecordEdit() + { + BaseFileSet bases = Bases(Base(Quests, VanillaQuests)); + MergePlan plan = Compose( + bases, + FileMod("a-tin", Quests, "{\"x\":1}"), + FileMod("b-oak", Quests, EditArray(VanillaQuests, quests => quests[1]!["reward"] = 2))); + + Collision collision = Assert.Single(plan.Collisions); + Assert.Equal(new RecordKey("data/quests.json", "*"), collision.Key); + Assert.Equal("", collision.Path); + } + + [Fact] + public void PickMod_KeepsThatModsOps_AndRecordsTheOutcome() + { + MergePlan open = Compose(ItemBases, Price("a-tin", 2, 1), Price("b-oak", 2, 2)); + Collision collision = Assert.Single(open.Collisions); + + MergePlan plan = Compose( + ItemBases, + [new Resolution(collision.Id, ResolutionKind.PickMod, "b-oak", collision.Fingerprint)], + Price("a-tin", 2, 1), + Price("b-oak", 2, 2)); + + Assert.True(plan.IsDeployable); + Assert.Equal(["data/items.json|id:2|price|SetLeaf|2"], plan.Ops.Select(merged => Describe(merged.Op))); + Assert.Equal(new CollisionOutcome(collision.Id, ResolutionSource.Profile, ResolutionKind.PickMod, "b-oak"), Assert.Single(plan.Outcomes)); + Assert.Empty(plan.Diagnostics); + } + + [Fact] + public void PickVanilla_DropsEveryOpOfTheCollision() + { + Collision collision = Assert.Single(Compose(ItemBases, Price("a-tin", 2, 1), Price("b-oak", 2, 2)).Collisions); + + MergePlan plan = Compose( + ItemBases, + [new Resolution(collision.Id, ResolutionKind.PickVanilla, null, collision.Fingerprint)], + Price("a-tin", 2, 1), + Price("b-oak", 2, 2)); + + Assert.True(plan.IsDeployable); + Assert.Empty(plan.Ops); + } + + [Fact] + public void StaleFingerprint_ReusesTheChoice_WithAnInfoDiagnostic() + { + Collision old = Assert.Single(Compose(ItemBases, Price("a-tin", 2, 1), Price("b-oak", 2, 2)).Collisions); + + MergePlan plan = Compose( + ItemBases, + [new Resolution(old.Id, ResolutionKind.PickMod, "a-tin", old.Fingerprint)], + Price("a-tin", 2, 5), + Price("b-oak", 2, 2)); + + Assert.Equal(ResolutionSource.ProfileReused, Assert.Single(plan.Outcomes).Source); + OperationDiagnostic diagnostic = Assert.Single(plan.Diagnostics); + Assert.Equal(DiagnosticCodes.RulesResolutionReused, diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Info, diagnostic.Severity); + Assert.Equal(old.Id, diagnostic.Subject); + Assert.True(plan.IsDeployable); + Assert.Equal(["data/items.json|id:2|price|SetLeaf|5"], plan.Ops.Select(merged => Describe(merged.Op))); + } + + [Theory] + [InlineData(ResolutionKind.PickMod, "c-elm")] + [InlineData(ResolutionKind.PickMod, null)] + [InlineData(ResolutionKind.DisableMod, "a-tin")] + [InlineData(ResolutionKind.Accept, null)] + public void ChoiceThatDoesNotFit_LeavesTheCollisionUnresolved(ResolutionKind kind, string? modId) + { + Collision collision = Assert.Single(Compose(ItemBases, Price("a-tin", 2, 1), Price("b-oak", 2, 2)).Collisions); + + MergePlan plan = Compose(ItemBases, [new Resolution(collision.Id, kind, modId)], Price("a-tin", 2, 1), Price("b-oak", 2, 2)); + + Assert.Equal(ResolutionSource.Unresolved, Assert.Single(plan.Outcomes).Source); + Assert.False(plan.IsDeployable); + } + + [Fact] + public void ErrorDiagnostic_MakesThePlanNotDeployable() + { + MergePlan plan = Compose(ItemBases, FileMod("a-tin", Items, "{broken")); + + Assert.False(plan.IsDeployable); + Assert.Equal(DiagnosticCodes.MergeParseFailed, Assert.Single(plan.Diagnostics).Code); + } + + [Fact] + public void ShuffledInputs_GiveTheSamePlan() + { + ModSource[] mods = + [ + Price("a-tin", 2, 1), + Price("b-oak", 2, 2), + FileMod("c-elm", Items, EditItems(items => items[1]!["name"] = "Draught")), + Price("d-ash", 1, 70) + ]; + List sets = mods.Select(mod => Build(mod, ItemBases)).ToList(); + Collision collision = Assert.Single(Composer.Compose(sets, [], ItemBases).Collisions); + Resolution[] resolutions = + [ + new Resolution(collision.Id, ResolutionKind.PickMod, "b-oak"), + new Resolution(collision.Id, ResolutionKind.PickMod, "a-tin"), + new Resolution("0000000000000000", ResolutionKind.PickVanilla, null) + ]; + + MergePlan expected = Composer.Compose(sets, resolutions, ItemBases); + var random = new Random(20261111); + for (int round = 0; round < 20; round++) + { + List shuffledSets = sets.OrderBy(_ => random.Next()).ToList(); + List shuffledResolutions = resolutions.OrderBy(_ => random.Next()).ToList(); + + MergePlan plan = Composer.Compose(shuffledSets, shuffledResolutions, ItemBases); + + Assert.Equal(expected.MergeHash, plan.MergeHash); + Assert.Equal(expected.Collisions.Select(item => item.Id), plan.Collisions.Select(item => item.Id)); + Assert.Equal(expected.Outcomes, plan.Outcomes); + Assert.Equal(expected.Ops.Select(merged => Describe(merged.Op)), plan.Ops.Select(merged => Describe(merged.Op))); + } + + Assert.Equal("a-tin", Assert.Single(expected.Outcomes).ModId); + Assert.Matches("^[0-9a-f]{64}$", expected.MergeHash); + } + + [Fact] + public void MergeHash_ChangesWithTheOps() + { + Assert.NotEqual( + Compose(ItemBases, Price("a-tin", 2, 1)).MergeHash, + Compose(ItemBases, Price("a-tin", 2, 3)).MergeHash); + } + + [Fact] + public void TwoChangeSetsWithOneModId_AreACallerBug() + { + ModChangeSet set = Build(Price("a-tin", 2, 1), ItemBases); + + Assert.Throws(() => Composer.Compose([set, set], [], ItemBases)); + } + + [Fact] + public void DeleteVersusEdit_PickingAnEditor_KeepsTheRecordWithEveryEdit() + { + ModSource[] mods = [Removal("a-tin", 2), Price("b-oak", 2, 9), Name("c-elm", 2, "Mist")]; + Collision collision = Assert.Single(Compose(ItemBases, mods).Collisions); + + MergePlan plan = Compose(ItemBases, [new Resolution(collision.Id, ResolutionKind.PickMod, "b-oak")], mods); + + Assert.Equal(["a-tin", "b-oak", "c-elm"], collision.ModIds); + Assert.True(plan.IsDeployable); + Assert.Equal(["data/items.json|id:2|name|SetLeaf|\"Mist\"", "data/items.json|id:2|price|SetLeaf|9"], OpsOf(plan)); + } + + [Fact] + public void DeleteVersusEdit_PickingTheRemover_RemovesTheRecord() + { + ModSource[] mods = [Removal("a-tin", 2), Price("b-oak", 2, 9), Name("c-elm", 2, "Mist")]; + Collision collision = Assert.Single(Compose(ItemBases, mods).Collisions); + + MergePlan plan = Compose(ItemBases, [new Resolution(collision.Id, ResolutionKind.PickMod, "a-tin")], mods); + + Assert.True(plan.IsDeployable); + Assert.Equal(["data/items.json|id:2||RemoveRecord|-"], OpsOf(plan)); + } + + [Fact] + public void DeleteVersusEdit_KeptRecord_ReportsTheEditorsOwnClash() + { + ModSource[] mods = [Removal("a-tin", 2), Price("b-oak", 2, 9), Price("c-elm", 2, 8)]; + Collision outer = Assert.Single(Compose(ItemBases, mods).Collisions); + var keep = new Resolution(outer.Id, ResolutionKind.PickMod, "c-elm"); + + MergePlan kept = Compose(ItemBases, [keep], mods); + Collision inner = Assert.Single(kept.Collisions, collision => collision.Id != outer.Id); + MergePlan done = Compose(ItemBases, [keep, new Resolution(inner.Id, ResolutionKind.PickMod, "b-oak")], mods); + + Assert.False(kept.IsDeployable); + Assert.Equal(CollisionKind.ValueClash, inner.Kind); + Assert.Equal("price", inner.Path); + Assert.Equal(["b-oak", "c-elm"], inner.ModIds); + Assert.True(done.IsDeployable); + Assert.Equal(2, done.Outcomes.Count); + Assert.Equal(["data/items.json|id:2|price|SetLeaf|9"], OpsOf(done)); + } + + [Fact] + public void WholeFileValue_PickingARecordEditor_KeepsEveryRecordEdit() + { + BaseFileSet bases = Bases(Base(Quests, VanillaQuests)); + ModSource[] mods = + [ + FileMod("a-tin", Quests, "{\"x\":1}"), + FileMod("b-oak", Quests, EditArray(VanillaQuests, quests => quests[1]!["reward"] = 6)), + FileMod("c-elm", Quests, EditArray(VanillaQuests, quests => quests[2]!["name"] = "Carry")) + ]; + Collision collision = Assert.Single(Compose(bases, mods).Collisions); + + MergePlan plan = Compose(bases, [new Resolution(collision.Id, ResolutionKind.PickMod, "c-elm")], mods); + + Assert.True(plan.IsDeployable); + Assert.Equal(["data/quests.json|id:1|reward|SetLeaf|6", "data/quests.json|id:2|name|SetLeaf|\"Carry\""], OpsOf(plan)); + } + + [Fact] + public void ShuffledInputs_WithNestedCollisionsAndDiagnostics_GiveTheSamePlan() + { + ModSource[] mods = + [ + Removal("a-tin", 2), + Price("b-oak", 2, 9), + Price("c-elm", 2, 8), + Name("d-ash", 1, "Draught"), + FileMod("e-fir", Items, "{broken"), + PatchMod("f-yew", "data/Nothing.json", "{\"a\":1}") + ]; + List sets = mods.Select(mod => Build(mod, ItemBases)).ToList(); + Collision outer = Assert.Single(Composer.Compose(sets, [], ItemBases).Collisions); + var keep = new Resolution(outer.Id, ResolutionKind.PickMod, "c-elm"); + Collision inner = Assert.Single(Composer.Compose(sets, [keep], ItemBases).Collisions, collision => collision.Id != outer.Id); + Resolution[] resolutions = [keep, new Resolution(inner.Id, ResolutionKind.PickMod, "b-oak")]; + + MergePlan expected = Composer.Compose(sets, resolutions, ItemBases); + var random = new Random(20261112); + for (int round = 0; round < 20; round++) + { + MergePlan plan = Composer.Compose( + sets.OrderBy(_ => random.Next()).ToList(), + resolutions.OrderBy(_ => random.Next()).ToList(), + ItemBases); + + Assert.Equal(expected.MergeHash, plan.MergeHash); + Assert.Equal(expected.Collisions, plan.Collisions, CollisionsEqual); + Assert.Equal(expected.Outcomes, plan.Outcomes); + Assert.Equal(expected.Diagnostics, plan.Diagnostics); + Assert.Equal(OpsOf(expected), OpsOf(plan)); + } + + Assert.Equal( + [DiagnosticCodes.MergeParseFailed, DiagnosticCodes.MergePatchTargetMissing], + expected.Diagnostics.Select(diagnostic => diagnostic.Code)); + } + + [Fact] + public void MergeHash_CoversTheOutcomes() + { + ModSource[] mods = [Price("a-tin", 2, 1), Price("b-oak", 2, 2)]; + Collision collision = Assert.Single(Compose(ItemBases, mods).Collisions); + + MergePlan open = Compose(ItemBases, mods); + MergePlan vanilla = Compose(ItemBases, [new Resolution(collision.Id, ResolutionKind.PickVanilla, null)], mods); + + Assert.Empty(open.Ops); + Assert.Empty(vanilla.Ops); + Assert.NotEqual(open.MergeHash, vanilla.MergeHash); + } + + [Fact] + public void ChoiceWithoutAFingerprint_IsTakenAsMade() + { + ModSource[] mods = [Price("a-tin", 2, 1), Price("b-oak", 2, 2)]; + Collision collision = Assert.Single(Compose(ItemBases, mods).Collisions); + + MergePlan plan = Compose(ItemBases, [new Resolution(collision.Id, ResolutionKind.PickMod, "b-oak")], mods); + + Assert.Equal(ResolutionSource.Profile, Assert.Single(plan.Outcomes).Source); + Assert.Empty(plan.Diagnostics); + } + + [Fact] + public void Diagnostics_AreFoldedAndSortedByCode() + { + BaseFileSet bases = Bases(Base(Items, "{broken"), Base(Classes, "[null]")); + + MergePlan plan = Compose( + bases, + FileMod("b-oak", Items, VanillaItems), + FileMod("c-elm", Classes, "{broken"), + FileMod("a-tin", Items, VanillaItems)); + + Assert.Equal( + [DiagnosticCodes.MergeBaseParseFailed, DiagnosticCodes.MergeParseFailed], + plan.Diagnostics.Select(diagnostic => diagnostic.Code)); + Assert.Equal("data/items.json", plan.Diagnostics[0].Subject); + } + + [Theory] + [InlineData("{broken", DiagnosticCodes.MergeBaseParseFailed)] + [InlineData("[]", DiagnosticCodes.MergeRootShapeMismatch)] + public void BrokenSystemAmongTheBases_MakesThePlanNotDeployable(string systemText, string code) + { + BaseFileSet bases = Bases(Base(Items, VanillaItems), Base(SystemFile, systemText)); + + MergePlan plan = Compose(bases, Price("a-tin", 2, 1)); + + Assert.False(plan.IsDeployable); + OperationDiagnostic diagnostic = Assert.Single(plan.Diagnostics); + Assert.Equal(code, diagnostic.Code); + Assert.Equal("data/system.json", diagnostic.Subject); + } + + [Fact] + public void ManyOps_AreComposedWithoutAScanPerOp() + { + const int records = 10_000; + var first = new List(); + var second = new List(); + for (int index = 1; index <= records; index++) + { + var key = new RecordKey("data/items.json", "id:" + index); + first.Add(new ChangeOp("a-tin", key, "price", ChangeKind.SetLeaf, new JValue(index), null)); + second.Add(new ChangeOp("b-oak", key, "name", ChangeKind.SetLeaf, new JValue("n" + index), null)); + } + + ModChangeSet[] sets = [new ModChangeSet("a-tin", 0, first, []), new ModChangeSet("b-oak", 1, second, [])]; + var watch = System.Diagnostics.Stopwatch.StartNew(); + MergePlan plan = Composer.Compose(sets, [], ItemBases); + watch.Stop(); + + Assert.Equal(2 * records, plan.Ops.Count); + Assert.Empty(plan.Collisions); + + // About 0.3 s on a desktop today. A pairwise scan is 2 x 10^8 path checks here, so the loose bound still catches one. + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(5), $"Compose took {watch.Elapsed}."); + } + + private static bool CollisionsEqual(Collision left, Collision right) + { + return left.Id == right.Id && + left.Kind == right.Kind && + left.Key == right.Key && + left.Path == right.Path && + left.Fingerprint == right.Fingerprint && + left.ModIds.SequenceEqual(right.ModIds) && + left.Allowed.SequenceEqual(right.Allowed); + } +} diff --git a/RPGModder.Tests/Merge/FileFamilyMergeTests.cs b/RPGModder.Tests/Merge/FileFamilyMergeTests.cs new file mode 100644 index 0000000..62832a9 --- /dev/null +++ b/RPGModder.Tests/Merge/FileFamilyMergeTests.cs @@ -0,0 +1,283 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using static RPGModder.Tests.Merge.MergeTestKit; + +namespace RPGModder.Tests.Merge; + +/// New data files, opaque files and the config save (seam 11.1). +public sealed class FileFamilyMergeTests +{ + private const string Extra = "data/Extra.json"; + private const string Logo = "img/pictures/Logo.png"; + private const string Config = "save/config.rpgsave"; + private const string MzConfig = "save/config.rmmzsave"; + + private static string EncodeConfig(string json, string key = Config) + { + return ConfigSaveText.Encode(key, JObject.Parse(json)); + } + + private static JObject DecodeWritten(BaseFileSet bases, MergePlan plan, string key = Config) + { + MergedFile file = Assert.Single(MergedFileWriter.Write(plan, bases, null)); + Assert.Equal(MergedFileSource.Text, file.Source); + Assert.True(ConfigSaveText.TryDecode(key, file.Text, out JObject? config, out _)); + return config; + } + + [Fact] + public void Write_NewDataFile_CopiesTheModsFile() + { + BaseFileSet bases = Bases(); + ModSource mod = FileMod("a-tin", Extra, "[null,{\"id\":1}]"); + + ChangeOp op = Assert.Single(Build(mod, bases).Ops); + MergedFile file = Assert.Single(MergedFileWriter.Write(Compose(bases, mod), bases, null)); + + Assert.Equal("data/extra.json|*||AddRecord|[null,{\"id\":1}]", Describe(op)); + Assert.Equal(MergedFileSource.ModFile, file.Source); + Assert.Equal("a-tin", file.ModId); + Assert.Equal("files/Extra.json", file.SourceFile); + } + + [Fact] + public void Compose_SameNewDataFileWithOtherWhiteSpace_IsOneOp() + { + BaseFileSet bases = Bases(); + ModSource first = FileMod("a-tin", Extra, "[null,{\"id\":1}]"); + ModSource second = FileMod("b-oak", Extra, "[\n null,\n { \"id\": 1 }\n]"); + + MergePlan plan = Compose(bases, first, second); + + Assert.Empty(plan.Collisions); + Assert.Equal(["a-tin", "b-oak"], Assert.Single(plan.Ops).ModIds); + } + + [Fact] + public void Compose_DifferentNewDataFiles_AreAnIdClashThatPickModSettles() + { + BaseFileSet bases = Bases(); + ModSource first = FileMod("a-tin", Extra, "[null,{\"id\":1}]"); + ModSource second = FileMod("b-oak", Extra, "[null,{\"id\":2}]"); + Collision collision = Assert.Single(Compose(bases, first, second).Collisions); + + MergePlan plan = Compose(bases, [new Resolution(collision.Id, ResolutionKind.PickMod, "b-oak", collision.Fingerprint)], first, second); + MergedFile file = Assert.Single(MergedFileWriter.Write(plan, bases, null)); + + Assert.Equal(CollisionKind.IdClash, collision.Kind); + Assert.True(collision.Blocking); + Assert.Equal("b-oak", file.ModId); + Assert.Equal(MergedFileSource.ModFile, file.Source); + } + + [Fact] + public void Write_NewDataFileWithAPatch_IsWrittenAsText() + { + BaseFileSet bases = Bases(); + var mod = new ModSource( + "a-tin", + 0, + [new ModFile(Extra, "files/Extra.json", "{\"a\":1}", Hash("{\"a\":1}"))], + [new ModPatch(Extra, JObject.Parse("{\"b\":2}"))], + []); + + ChangeOp op = Assert.Single(Build(mod, bases).Ops); + MergedFile file = Assert.Single(MergedFileWriter.Write(Compose(bases, mod), bases, null)); + + Assert.Null(op.SourceFile); + Assert.Equal(MergedFileSource.Text, file.Source); + Assert.Equal(MergeJson.Write(JObject.Parse("{\"a\":1,\"b\":2}")), file.Text); + } + + [Fact] + public void Build_PatchOnAFileTheGameLacks_IsATargetMissing() + { + ModChangeSet set = Build(PatchMod("a-tin", Extra, "{\"b\":2}"), Bases()); + + Assert.Empty(set.Ops); + Assert.Equal(DiagnosticCodes.MergePatchTargetMissing, Assert.Single(set.Diagnostics).Code); + } + + [Fact] + public void Build_OpaqueFileEqualToVanilla_IsNoChange() + { + Assert.Empty(Build(FileMod("a-tin", Logo, "pixels"), Bases(Base(Logo, "pixels"))).Ops); + } + + [Fact] + public void Write_OpaqueFileThatDiffers_ReplacesTheFileByHash() + { + BaseFileSet bases = Bases(Base(Logo, "pixels")); + ModSource mod = FileMod("a-tin", Logo, "other pixels"); + + ChangeOp op = Assert.Single(Build(mod, bases).Ops); + MergedFile file = Assert.Single(MergedFileWriter.Write(Compose(bases, mod), bases, null)); + + Assert.Equal("img/pictures/logo.png|*||ReplaceFile|\"" + Hash("other pixels") + "\"", Describe(op)); + Assert.Equal(MergedFileSource.ModFile, file.Source); + Assert.Equal("files/Logo.png", file.SourceFile); + } + + [Fact] + public void Compose_TwoDifferentOpaqueFiles_AreAFileClashOnlyPickModSettles() + { + BaseFileSet bases = Bases(Base(Logo, "pixels")); + ModSource first = FileMod("a-tin", Logo, "tin pixels"); + ModSource second = FileMod("b-oak", Logo, "oak pixels"); + Collision collision = Assert.Single(Compose(bases, first, second).Collisions); + + MergePlan plan = Compose(bases, [new Resolution(collision.Id, ResolutionKind.PickMod, "a-tin", collision.Fingerprint)], first, second); + + Assert.Equal(CollisionKind.FileClash, collision.Kind); + Assert.True(collision.Blocking); + Assert.Equal([ResolutionKind.PickMod], collision.Allowed); + Assert.Equal("a-tin", Assert.Single(MergedFileWriter.Write(plan, bases, null)).ModId); + } + + [Fact] + public void Compose_TwoEqualOpaqueFiles_AreOneCopy() + { + BaseFileSet bases = Bases(); + MergePlan plan = Compose(bases, FileMod("a-tin", Logo, "pixels"), FileMod("b-oak", Logo, "pixels")); + + Assert.Empty(plan.Collisions); + Assert.Equal(["a-tin", "b-oak"], Assert.Single(MergedFileWriter.Write(plan, bases, null)).ModIds); + } + + [Fact] + public void Build_PatchOnAnOpaqueFile_IsRejected() + { + ModChangeSet set = Build(PatchMod("a-tin", Logo, "{\"a\":1}"), Bases(Base(Logo, "pixels"))); + + Assert.Empty(set.Ops); + Assert.Equal(DiagnosticCodes.MergePatchShapeMismatch, Assert.Single(set.Diagnostics).Code); + } + + [Theory] + [InlineData(Config)] + [InlineData(MzConfig)] + public void ConfigSaveText_EncodeThenDecode_RoundTrips(string key) + { + var config = JObject.Parse("{\"alwaysDash\":true,\"bgmVolume\":80,\"name\":\"Caf\u00e9 \u65e5\u672c\"}"); + + Assert.True(ConfigSaveText.TryDecode(key, ConfigSaveText.Encode(key, config), out JObject? read, out _)); + Assert.True(JToken.DeepEquals(config, read)); + } + + [Fact] + public void ConfigSaveText_MzForm_IsAZlibByteString() + { + string text = EncodeConfig("{\"alwaysDash\":true}", MzConfig); + + // One character per byte, starting with the zlib header byte 0x78. + Assert.All(text, current => Assert.True(current <= byte.MaxValue)); + Assert.Equal((char)0x78, text[0]); + } + + [Theory] + [InlineData(Config, "")] + [InlineData(Config, "not base64 at all!")] + [InlineData(Config, "AAAA")] + [InlineData(MzConfig, "")] + [InlineData(MzConfig, "x\u009c not deflate")] + [InlineData(MzConfig, "\u65e5\u672c")] + public void ConfigSaveText_TextThatIsNotAnEncodedObject_FailsToDecode(string key, string text) + { + Assert.False(ConfigSaveText.TryDecode(key, text, out _, out string? error)); + Assert.False(string.IsNullOrEmpty(error)); + } + + [Theory] + [InlineData(Config, MzConfig)] + [InlineData(MzConfig, Config)] + public void ConfigSaveText_TheOtherFormsText_FailsToDecode(string key, string other) + { + Assert.False(ConfigSaveText.TryDecode(key, EncodeConfig("{\"alwaysDash\":true}", other), out _, out _)); + } + + [Theory] + [InlineData(Config)] + [InlineData(MzConfig)] + public void Write_ConfigKeyChanged_KeepsTheKeysTheModLeftOut(string key) + { + BaseFileSet bases = Bases(Base(key, EncodeConfig("{\"alwaysDash\":false,\"bgmVolume\":100}", key))); + ModSource mod = FileMod("a-tin", key, EncodeConfig("{\"alwaysDash\":true}", key)); + + ChangeOp op = Assert.Single(Build(mod, bases).Ops); + JObject written = DecodeWritten(bases, Compose(bases, mod), key); + + Assert.Equal($"{key}|*|alwaysDash|SetLeaf|true", Describe(op)); + Assert.True(JToken.DeepEquals(JObject.Parse("{\"alwaysDash\":true,\"bgmVolume\":100}"), written)); + } + + [Theory] + [InlineData(Config)] + [InlineData(MzConfig)] + public void Write_NoLiveConfig_StartsFromAnEmptyObject(string key) + { + BaseFileSet bases = Bases(); + + JObject written = DecodeWritten(bases, Compose(bases, FileMod("a-tin", key, EncodeConfig("{\"alwaysDash\":true}", key))), key); + + Assert.True(JToken.DeepEquals(JObject.Parse("{\"alwaysDash\":true}"), written)); + } + + [Theory] + [InlineData(Config)] + [InlineData(MzConfig)] + public void Build_ConfigPatch_IsALeafPerTopLevelKey(string key) + { + BaseFileSet bases = Bases(Base(key, EncodeConfig("{\"alwaysDash\":false,\"bgmVolume\":100}", key))); + + ChangeOp op = Assert.Single(Build(PatchMod("a-tin", key, "{\"bgmVolume\":50}"), bases).Ops); + + Assert.Equal($"{key}|*|bgmVolume|SetLeaf|50", Describe(op)); + } + + [Fact] + public void Compose_ConfigKeySetTwoWays_IsAValueClash() + { + BaseFileSet bases = Bases(Base(Config, EncodeConfig("{\"bgmVolume\":100}"))); + ModSource first = PatchMod("a-tin", Config, "{\"bgmVolume\":50}"); + ModSource second = PatchMod("b-oak", Config, "{\"bgmVolume\":20}"); + + Assert.Equal(CollisionKind.ValueClash, Assert.Single(Compose(bases, first, second).Collisions).Kind); + } + + [Fact] + public void Build_ConfigFormThisVersionCannotRead_IsUnsupported() + { + ModChangeSet set = Build(FileMod("a-tin", "save/config.save", "opaque"), Bases()); + + OperationDiagnostic diagnostic = Assert.Single(set.Diagnostics); + Assert.Empty(set.Ops); + Assert.Equal(DiagnosticCodes.MergeConfigSaveUnsupported, diagnostic.Code); + Assert.Equal("a-tin", diagnostic.Subject); + } + + [Theory] + [InlineData(Config)] + [InlineData(MzConfig)] + public void Build_ModConfigThatDoesNotDecode_IsAParseFailureOnTheMod(string key) + { + ModChangeSet set = Build(FileMod("a-tin", key, "not base64 at all!"), Bases()); + + OperationDiagnostic diagnostic = Assert.Single(set.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeParseFailed, diagnostic.Code); + Assert.Equal("a-tin", diagnostic.Subject); + } + + [Theory] + [InlineData(Config)] + [InlineData(MzConfig)] + public void Build_LiveConfigThatDoesNotDecode_IsABaseFaultOnTheFile(string key) + { + ModChangeSet set = Build(PatchMod("a-tin", key, "{\"bgmVolume\":50}"), Bases(Base(key, "not base64 at all!"))); + + OperationDiagnostic diagnostic = Assert.Single(set.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeBaseParseFailed, diagnostic.Code); + Assert.Equal(key, diagnostic.Subject); + } +} diff --git a/RPGModder.Tests/Merge/Golden/01-disjoint-fields/a-ash/data/Items.json b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/a-ash/data/Items.json new file mode 100644 index 0000000..a73a93f --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/a-ash/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":75,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/01-disjoint-fields/a-ash/mod.json b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/a-ash/mod.json new file mode 100644 index 0000000..6925b7e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/a-ash/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "a-ash", + "name": "Ash Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Items.json", + "target": "data/Items.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/01-disjoint-fields/b-birch/data/Items.json b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/b-birch/data/Items.json new file mode 100644 index 0000000..2d20daa --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/b-birch/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"bitter","effects":[]}, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/01-disjoint-fields/b-birch/mod.json b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/b-birch/mod.json new file mode 100644 index 0000000..b3e279f --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/b-birch/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "b-birch", + "name": "Birch Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Items.json", + "target": "data/Items.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/01-disjoint-fields/expected/collisions.json b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/expected/collisions.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/expected/collisions.json @@ -0,0 +1 @@ +[] diff --git a/RPGModder.Tests/Merge/Golden/01-disjoint-fields/expected/files/data/items.json b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/expected/files/data/items.json new file mode 100644 index 0000000..7847f42 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/expected/files/data/items.json @@ -0,0 +1 @@ +[null,{"id":1,"name":"Herb","price":75,"note":"bitter","effects":[]},{"id":2,"name":"Tonic","price":120,"note":"","effects":[]}] \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/01-disjoint-fields/vanilla/data/Items.json b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/vanilla/data/Items.json new file mode 100644 index 0000000..3a9e6d7 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/01-disjoint-fields/vanilla/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/02-identical-edits/a-ash/data/Items.json b/RPGModder.Tests/Merge/Golden/02-identical-edits/a-ash/data/Items.json new file mode 100644 index 0000000..09e472d --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/02-identical-edits/a-ash/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":90,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/02-identical-edits/a-ash/mod.json b/RPGModder.Tests/Merge/Golden/02-identical-edits/a-ash/mod.json new file mode 100644 index 0000000..6925b7e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/02-identical-edits/a-ash/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "a-ash", + "name": "Ash Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Items.json", + "target": "data/Items.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/02-identical-edits/b-birch/data/Items.json b/RPGModder.Tests/Merge/Golden/02-identical-edits/b-birch/data/Items.json new file mode 100644 index 0000000..09e472d --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/02-identical-edits/b-birch/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":90,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/02-identical-edits/b-birch/mod.json b/RPGModder.Tests/Merge/Golden/02-identical-edits/b-birch/mod.json new file mode 100644 index 0000000..b3e279f --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/02-identical-edits/b-birch/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "b-birch", + "name": "Birch Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Items.json", + "target": "data/Items.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/02-identical-edits/expected/collisions.json b/RPGModder.Tests/Merge/Golden/02-identical-edits/expected/collisions.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/02-identical-edits/expected/collisions.json @@ -0,0 +1 @@ +[] diff --git a/RPGModder.Tests/Merge/Golden/02-identical-edits/expected/files/data/items.json b/RPGModder.Tests/Merge/Golden/02-identical-edits/expected/files/data/items.json new file mode 100644 index 0000000..15f8830 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/02-identical-edits/expected/files/data/items.json @@ -0,0 +1 @@ +[null,{"id":1,"name":"Herb","price":50,"note":"","effects":[]},{"id":2,"name":"Tonic","price":90,"note":"","effects":[]}] \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/02-identical-edits/vanilla/data/Items.json b/RPGModder.Tests/Merge/Golden/02-identical-edits/vanilla/data/Items.json new file mode 100644 index 0000000..3a9e6d7 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/02-identical-edits/vanilla/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/a-tin/data/Items.json b/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/a-tin/data/Items.json new file mode 100644 index 0000000..4266413 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/a-tin/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":80,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/a-tin/mod.json b/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/a-tin/mod.json new file mode 100644 index 0000000..33b7e16 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/a-tin/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "a-tin", + "name": "Tin Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Items.json", + "target": "data/Items.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/b-oak/data/Items.json b/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/b-oak/data/Items.json new file mode 100644 index 0000000..90a1411 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/b-oak/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":150,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/b-oak/mod.json b/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/b-oak/mod.json new file mode 100644 index 0000000..985c216 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/b-oak/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "b-oak", + "name": "Oak Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Items.json", + "target": "data/Items.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/expected/collisions.json b/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/expected/collisions.json new file mode 100644 index 0000000..3ff263e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/expected/collisions.json @@ -0,0 +1,18 @@ +[ + { + "id": "6405909de5ee88d1", + "kind": "ValueClash", + "file": "data/items.json", + "record": "id:2", + "path": "price", + "mods": [ + "a-tin", + "b-oak" + ], + "blocking": true, + "allowed": [ + "PickMod", + "PickVanilla" + ] + } +] diff --git a/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/vanilla/data/Items.json b/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/vanilla/data/Items.json new file mode 100644 index 0000000..3a9e6d7 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03a-value-clash-unresolved/vanilla/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/a-tin/data/Items.json b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/a-tin/data/Items.json new file mode 100644 index 0000000..4266413 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/a-tin/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":80,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/a-tin/mod.json b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/a-tin/mod.json new file mode 100644 index 0000000..33b7e16 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/a-tin/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "a-tin", + "name": "Tin Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Items.json", + "target": "data/Items.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/b-oak/data/Items.json b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/b-oak/data/Items.json new file mode 100644 index 0000000..90a1411 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/b-oak/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":150,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/b-oak/mod.json b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/b-oak/mod.json new file mode 100644 index 0000000..985c216 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/b-oak/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "b-oak", + "name": "Oak Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Items.json", + "target": "data/Items.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/expected/collisions.json b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/expected/collisions.json new file mode 100644 index 0000000..3ff263e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/expected/collisions.json @@ -0,0 +1,18 @@ +[ + { + "id": "6405909de5ee88d1", + "kind": "ValueClash", + "file": "data/items.json", + "record": "id:2", + "path": "price", + "mods": [ + "a-tin", + "b-oak" + ], + "blocking": true, + "allowed": [ + "PickMod", + "PickVanilla" + ] + } +] diff --git a/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/expected/files/data/items.json b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/expected/files/data/items.json new file mode 100644 index 0000000..ceb9f02 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/expected/files/data/items.json @@ -0,0 +1 @@ +[null,{"id":1,"name":"Herb","price":50,"note":"","effects":[]},{"id":2,"name":"Tonic","price":150,"note":"","effects":[]}] \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/resolutions.json b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/resolutions.json new file mode 100644 index 0000000..f7cbebf --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/resolutions.json @@ -0,0 +1,7 @@ +[ + { + "id": "6405909de5ee88d1", + "kind": "PickMod", + "mod": "b-oak" + } +] diff --git a/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/vanilla/data/Items.json b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/vanilla/data/Items.json new file mode 100644 index 0000000..3a9e6d7 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/03b-value-clash-resolved/vanilla/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/a-ash/data/Items.json b/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/a-ash/data/Items.json new file mode 100644 index 0000000..6039a69 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/a-ash/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +null, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/a-ash/mod.json b/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/a-ash/mod.json new file mode 100644 index 0000000..6925b7e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/a-ash/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "a-ash", + "name": "Ash Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Items.json", + "target": "data/Items.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/b-birch/data/Items.json b/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/b-birch/data/Items.json new file mode 100644 index 0000000..c83d257 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/b-birch/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":60,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/b-birch/mod.json b/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/b-birch/mod.json new file mode 100644 index 0000000..b3e279f --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/b-birch/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "b-birch", + "name": "Birch Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Items.json", + "target": "data/Items.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/expected/collisions.json b/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/expected/collisions.json new file mode 100644 index 0000000..cd62e4d --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/expected/collisions.json @@ -0,0 +1,18 @@ +[ + { + "id": "823a86e9e08b7435", + "kind": "DeleteVersusEdit", + "file": "data/items.json", + "record": "id:1", + "path": "", + "mods": [ + "a-ash", + "b-birch" + ], + "blocking": true, + "allowed": [ + "PickMod", + "PickVanilla" + ] + } +] diff --git a/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/vanilla/data/Items.json b/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/vanilla/data/Items.json new file mode 100644 index 0000000..3a9e6d7 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/04-delete-versus-edit/vanilla/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/05-id-clash/a-ash/data/Items.json b/RPGModder.Tests/Merge/Golden/05-id-clash/a-ash/data/Items.json new file mode 100644 index 0000000..a5d1278 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/05-id-clash/a-ash/data/Items.json @@ -0,0 +1,6 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]}, +{"id":3,"name":"Amber","price":200,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/05-id-clash/a-ash/mod.json b/RPGModder.Tests/Merge/Golden/05-id-clash/a-ash/mod.json new file mode 100644 index 0000000..6925b7e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/05-id-clash/a-ash/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "a-ash", + "name": "Ash Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Items.json", + "target": "data/Items.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/05-id-clash/b-birch/data/Items.json b/RPGModder.Tests/Merge/Golden/05-id-clash/b-birch/data/Items.json new file mode 100644 index 0000000..cc1465e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/05-id-clash/b-birch/data/Items.json @@ -0,0 +1,6 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]}, +{"id":3,"name":"Quartz","price":300,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/05-id-clash/b-birch/mod.json b/RPGModder.Tests/Merge/Golden/05-id-clash/b-birch/mod.json new file mode 100644 index 0000000..b3e279f --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/05-id-clash/b-birch/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "b-birch", + "name": "Birch Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Items.json", + "target": "data/Items.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/05-id-clash/expected/collisions.json b/RPGModder.Tests/Merge/Golden/05-id-clash/expected/collisions.json new file mode 100644 index 0000000..ddb6ef5 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/05-id-clash/expected/collisions.json @@ -0,0 +1,18 @@ +[ + { + "id": "cbc010b0587cd952", + "kind": "IdClash", + "file": "data/items.json", + "record": "id:3", + "path": "", + "mods": [ + "a-ash", + "b-birch" + ], + "blocking": true, + "allowed": [ + "PickMod", + "DisableMod" + ] + } +] diff --git a/RPGModder.Tests/Merge/Golden/05-id-clash/vanilla/data/Items.json b/RPGModder.Tests/Merge/Golden/05-id-clash/vanilla/data/Items.json new file mode 100644 index 0000000..3a9e6d7 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/05-id-clash/vanilla/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/06-volatile-fields-ignored/a-ash/data/System.json b/RPGModder.Tests/Merge/Golden/06-volatile-fields-ignored/a-ash/data/System.json new file mode 100644 index 0000000..3385cf0 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/06-volatile-fields-ignored/a-ash/data/System.json @@ -0,0 +1 @@ +{"gameTitle":"SampleProject","versionId":205,"editMapId":4,"screenWidth":1280,"screenHeight":624,"currencyUnit":"G"} diff --git a/RPGModder.Tests/Merge/Golden/06-volatile-fields-ignored/a-ash/mod.json b/RPGModder.Tests/Merge/Golden/06-volatile-fields-ignored/a-ash/mod.json new file mode 100644 index 0000000..8afa361 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/06-volatile-fields-ignored/a-ash/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "a-ash", + "name": "Ash Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/System.json", + "target": "data/System.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/06-volatile-fields-ignored/expected/collisions.json b/RPGModder.Tests/Merge/Golden/06-volatile-fields-ignored/expected/collisions.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/06-volatile-fields-ignored/expected/collisions.json @@ -0,0 +1 @@ +[] diff --git a/RPGModder.Tests/Merge/Golden/06-volatile-fields-ignored/vanilla/data/System.json b/RPGModder.Tests/Merge/Golden/06-volatile-fields-ignored/vanilla/data/System.json new file mode 100644 index 0000000..14e587e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/06-volatile-fields-ignored/vanilla/data/System.json @@ -0,0 +1 @@ +{"gameTitle":"SampleProject","versionId":100,"editMapId":1,"screenWidth":816,"screenHeight":624,"currencyUnit":"G"} diff --git a/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/a-ash/data/Items.json b/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/a-ash/data/Items.json new file mode 100644 index 0000000..2dc6464 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/a-ash/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":65,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/a-ash/mod.json b/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/a-ash/mod.json new file mode 100644 index 0000000..6925b7e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/a-ash/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "a-ash", + "name": "Ash Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Items.json", + "target": "data/Items.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} diff --git a/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/expected/collisions.json b/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/expected/collisions.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/expected/collisions.json @@ -0,0 +1 @@ +[] diff --git a/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/expected/files/data/items.json b/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/expected/files/data/items.json new file mode 100644 index 0000000..2f2401c --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/expected/files/data/items.json @@ -0,0 +1 @@ +[null,{"id":1,"name":"Herb","price":65,"note":"","effects":[]},{"id":2,"name":"Tonic","price":120,"note":"","effects":[]}] \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/vanilla/data/Items.json b/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/vanilla/data/Items.json new file mode 100644 index 0000000..3a9e6d7 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/vanilla/data/Items.json @@ -0,0 +1,5 @@ +[ +null, +{"id":1,"name":"Herb","price":50,"note":"","effects":[]}, +{"id":2,"name":"Tonic","price":120,"note":"","effects":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/vanilla/data/Weapons.json b/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/vanilla/data/Weapons.json new file mode 100644 index 0000000..2a17c58 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/07-untouched-file-omitted/vanilla/data/Weapons.json @@ -0,0 +1,4 @@ +[ +null, +{"id":1,"name":"Bronze Sword","price":100,"note":"","traits":[]} +] diff --git a/RPGModder.Tests/Merge/Golden/08-map-different-events/a-ash/data/Map001.json b/RPGModder.Tests/Merge/Golden/08-map-different-events/a-ash/data/Map001.json new file mode 100644 index 0000000..3607b91 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/08-map-different-events/a-ash/data/Map001.json @@ -0,0 +1,15 @@ +{ +"autoplayBgm":false,"autoplayBgs":false,"battleback1Name":"","battleback2Name":"", +"bgm":{"name":"","pan":0,"pitch":100,"volume":90}, +"bgs":{"name":"","pan":0,"pitch":100,"volume":90}, +"disableDashing":false,"displayName":"Meadow","encounterList":[],"encounterStep":30, +"height":2,"note":"","parallaxLoopX":false,"parallaxLoopY":false,"parallaxName":"", +"parallaxShow":true,"parallaxSx":0,"parallaxSy":0,"scrollType":0,"specifyBattleback":false, +"tilesetId":1,"width":2, +"data":[0,0,0,0], +"events":[ +null, +{"id":1,"name":"Signpost","note":"","pages":[{"conditions":{"actorId":1,"actorValid":false,"itemId":1,"itemValid":false,"selfSwitchCh":"A","selfSwitchValid":false,"switch1Id":1,"switch1Valid":false,"switch2Id":1,"switch2Valid":false,"variableId":1,"variableValid":false,"variableValue":0},"directionFix":false,"image":{"characterIndex":0,"characterName":"","direction":2,"pattern":0,"tileId":0},"list":[{"code":0,"indent":0,"parameters":[]}],"moveFrequency":3,"moveRoute":{"list":[{"code":0,"parameters":[]}],"repeat":true,"skippable":false,"wait":false},"moveSpeed":3,"moveType":0,"priorityType":0,"stepAnime":false,"through":false,"trigger":1,"walkAnime":true}],"x":1,"y":0}, +{"id":2,"name":"Lantern","note":"","pages":[{"conditions":{"actorId":1,"actorValid":false,"itemId":1,"itemValid":false,"selfSwitchCh":"A","selfSwitchValid":false,"switch1Id":1,"switch1Valid":false,"switch2Id":1,"switch2Valid":false,"variableId":1,"variableValid":false,"variableValue":0},"directionFix":false,"image":{"characterIndex":0,"characterName":"","direction":2,"pattern":0,"tileId":0},"list":[{"code":0,"indent":0,"parameters":[]}],"moveFrequency":3,"moveRoute":{"list":[{"code":0,"parameters":[]}],"repeat":true,"skippable":false,"wait":false},"moveSpeed":3,"moveType":0,"priorityType":0,"stepAnime":false,"through":false,"trigger":0,"walkAnime":true}],"x":1,"y":1} +] +} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/08-map-different-events/a-ash/mod.json b/RPGModder.Tests/Merge/Golden/08-map-different-events/a-ash/mod.json new file mode 100644 index 0000000..a56ee68 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/08-map-different-events/a-ash/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "a-ash", + "name": "Ash Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Map001.json", + "target": "data/Map001.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/08-map-different-events/b-birch/data/Map001.json b/RPGModder.Tests/Merge/Golden/08-map-different-events/b-birch/data/Map001.json new file mode 100644 index 0000000..9d55ad3 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/08-map-different-events/b-birch/data/Map001.json @@ -0,0 +1,15 @@ +{ +"autoplayBgm":false,"autoplayBgs":false,"battleback1Name":"","battleback2Name":"", +"bgm":{"name":"","pan":0,"pitch":100,"volume":90}, +"bgs":{"name":"","pan":0,"pitch":100,"volume":90}, +"disableDashing":false,"displayName":"Meadow","encounterList":[],"encounterStep":30, +"height":2,"note":"","parallaxLoopX":false,"parallaxLoopY":false,"parallaxName":"", +"parallaxShow":true,"parallaxSx":0,"parallaxSy":0,"scrollType":0,"specifyBattleback":false, +"tilesetId":1,"width":2, +"data":[0,0,0,0], +"events":[ +null, +{"id":1,"name":"Signpost","note":"","pages":[{"conditions":{"actorId":1,"actorValid":false,"itemId":1,"itemValid":false,"selfSwitchCh":"A","selfSwitchValid":false,"switch1Id":1,"switch1Valid":false,"switch2Id":1,"switch2Valid":false,"variableId":1,"variableValid":false,"variableValue":0},"directionFix":false,"image":{"characterIndex":0,"characterName":"","direction":2,"pattern":0,"tileId":0},"list":[{"code":0,"indent":0,"parameters":[]}],"moveFrequency":3,"moveRoute":{"list":[{"code":0,"parameters":[]}],"repeat":true,"skippable":false,"wait":false},"moveSpeed":3,"moveType":0,"priorityType":0,"stepAnime":false,"through":false,"trigger":0,"walkAnime":true}],"x":0,"y":0}, +{"id":2,"name":"Beacon","note":"","pages":[{"conditions":{"actorId":1,"actorValid":false,"itemId":1,"itemValid":false,"selfSwitchCh":"A","selfSwitchValid":false,"switch1Id":1,"switch1Valid":false,"switch2Id":1,"switch2Valid":false,"variableId":1,"variableValid":false,"variableValue":0},"directionFix":false,"image":{"characterIndex":0,"characterName":"","direction":2,"pattern":0,"tileId":0},"list":[{"code":0,"indent":0,"parameters":[]}],"moveFrequency":3,"moveRoute":{"list":[{"code":0,"parameters":[]}],"repeat":true,"skippable":false,"wait":false},"moveSpeed":3,"moveType":0,"priorityType":0,"stepAnime":false,"through":false,"trigger":0,"walkAnime":true}],"x":1,"y":1} +] +} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/08-map-different-events/b-birch/mod.json b/RPGModder.Tests/Merge/Golden/08-map-different-events/b-birch/mod.json new file mode 100644 index 0000000..976bbce --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/08-map-different-events/b-birch/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "b-birch", + "name": "Birch Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "data/Map001.json", + "target": "data/Map001.json" + } + ], + "json_patches": [], + "plugins_registry": [] +} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/08-map-different-events/expected/collisions.json b/RPGModder.Tests/Merge/Golden/08-map-different-events/expected/collisions.json new file mode 100644 index 0000000..0637a08 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/08-map-different-events/expected/collisions.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/08-map-different-events/expected/files/data/map001.json b/RPGModder.Tests/Merge/Golden/08-map-different-events/expected/files/data/map001.json new file mode 100644 index 0000000..6162976 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/08-map-different-events/expected/files/data/map001.json @@ -0,0 +1 @@ +{"autoplayBgm":false,"autoplayBgs":false,"battleback1Name":"","battleback2Name":"","bgm":{"name":"","pan":0,"pitch":100,"volume":90},"bgs":{"name":"","pan":0,"pitch":100,"volume":90},"disableDashing":false,"displayName":"Meadow","encounterList":[],"encounterStep":30,"height":2,"note":"","parallaxLoopX":false,"parallaxLoopY":false,"parallaxName":"","parallaxShow":true,"parallaxSx":0,"parallaxSy":0,"scrollType":0,"specifyBattleback":false,"tilesetId":1,"width":2,"data":[0,0,0,0],"events":[null,{"id":1,"name":"Signpost","note":"","pages":[{"conditions":{"actorId":1,"actorValid":false,"itemId":1,"itemValid":false,"selfSwitchCh":"A","selfSwitchValid":false,"switch1Id":1,"switch1Valid":false,"switch2Id":1,"switch2Valid":false,"variableId":1,"variableValid":false,"variableValue":0},"directionFix":false,"image":{"characterIndex":0,"characterName":"","direction":2,"pattern":0,"tileId":0},"list":[{"code":0,"indent":0,"parameters":[]}],"moveFrequency":3,"moveRoute":{"list":[{"code":0,"parameters":[]}],"repeat":true,"skippable":false,"wait":false},"moveSpeed":3,"moveType":0,"priorityType":0,"stepAnime":false,"through":false,"trigger":1,"walkAnime":true}],"x":1,"y":0},{"id":2,"name":"Beacon","note":"","pages":[{"conditions":{"actorId":1,"actorValid":false,"itemId":1,"itemValid":false,"selfSwitchCh":"A","selfSwitchValid":false,"switch1Id":1,"switch1Valid":false,"switch2Id":1,"switch2Valid":false,"variableId":1,"variableValid":false,"variableValue":0},"directionFix":false,"image":{"characterIndex":0,"characterName":"","direction":2,"pattern":0,"tileId":0},"list":[{"code":0,"indent":0,"parameters":[]}],"moveFrequency":3,"moveRoute":{"list":[{"code":0,"parameters":[]}],"repeat":true,"skippable":false,"wait":false},"moveSpeed":3,"moveType":0,"priorityType":0,"stepAnime":false,"through":false,"trigger":0,"walkAnime":true}],"x":1,"y":1}]} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/08-map-different-events/vanilla/data/Map001.json b/RPGModder.Tests/Merge/Golden/08-map-different-events/vanilla/data/Map001.json new file mode 100644 index 0000000..19dc704 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/08-map-different-events/vanilla/data/Map001.json @@ -0,0 +1,15 @@ +{ +"autoplayBgm":false,"autoplayBgs":false,"battleback1Name":"","battleback2Name":"", +"bgm":{"name":"","pan":0,"pitch":100,"volume":90}, +"bgs":{"name":"","pan":0,"pitch":100,"volume":90}, +"disableDashing":false,"displayName":"Meadow","encounterList":[],"encounterStep":30, +"height":2,"note":"","parallaxLoopX":false,"parallaxLoopY":false,"parallaxName":"", +"parallaxShow":true,"parallaxSx":0,"parallaxSy":0,"scrollType":0,"specifyBattleback":false, +"tilesetId":1,"width":2, +"data":[0,0,0,0], +"events":[ +null, +{"id":1,"name":"Signpost","note":"","pages":[{"conditions":{"actorId":1,"actorValid":false,"itemId":1,"itemValid":false,"selfSwitchCh":"A","selfSwitchValid":false,"switch1Id":1,"switch1Valid":false,"switch2Id":1,"switch2Valid":false,"variableId":1,"variableValid":false,"variableValue":0},"directionFix":false,"image":{"characterIndex":0,"characterName":"","direction":2,"pattern":0,"tileId":0},"list":[{"code":0,"indent":0,"parameters":[]}],"moveFrequency":3,"moveRoute":{"list":[{"code":0,"parameters":[]}],"repeat":true,"skippable":false,"wait":false},"moveSpeed":3,"moveType":0,"priorityType":0,"stepAnime":false,"through":false,"trigger":0,"walkAnime":true}],"x":0,"y":0}, +{"id":2,"name":"Lantern","note":"","pages":[{"conditions":{"actorId":1,"actorValid":false,"itemId":1,"itemValid":false,"selfSwitchCh":"A","selfSwitchValid":false,"switch1Id":1,"switch1Valid":false,"switch2Id":1,"switch2Valid":false,"variableId":1,"variableValid":false,"variableValue":0},"directionFix":false,"image":{"characterIndex":0,"characterName":"","direction":2,"pattern":0,"tileId":0},"list":[{"code":0,"indent":0,"parameters":[]}],"moveFrequency":3,"moveRoute":{"list":[{"code":0,"parameters":[]}],"repeat":true,"skippable":false,"wait":false},"moveSpeed":3,"moveType":0,"priorityType":0,"stepAnime":false,"through":false,"trigger":0,"walkAnime":true}],"x":1,"y":1} +] +} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/09-same-new-file/a-ash/js/plugins/SharedHelper.js b/RPGModder.Tests/Merge/Golden/09-same-new-file/a-ash/js/plugins/SharedHelper.js new file mode 100644 index 0000000..7bff55e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/09-same-new-file/a-ash/js/plugins/SharedHelper.js @@ -0,0 +1,4 @@ +// SharedHelper +(function() { + window.SharedHelper = { version: 1 }; +})(); diff --git a/RPGModder.Tests/Merge/Golden/09-same-new-file/a-ash/mod.json b/RPGModder.Tests/Merge/Golden/09-same-new-file/a-ash/mod.json new file mode 100644 index 0000000..265910c --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/09-same-new-file/a-ash/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "a-ash", + "name": "Ash Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "js/plugins/SharedHelper.js", + "target": "js/plugins/SharedHelper.js" + } + ], + "json_patches": [], + "plugins_registry": [] +} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/09-same-new-file/b-birch/js/plugins/SharedHelper.js b/RPGModder.Tests/Merge/Golden/09-same-new-file/b-birch/js/plugins/SharedHelper.js new file mode 100644 index 0000000..7bff55e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/09-same-new-file/b-birch/js/plugins/SharedHelper.js @@ -0,0 +1,4 @@ +// SharedHelper +(function() { + window.SharedHelper = { version: 1 }; +})(); diff --git a/RPGModder.Tests/Merge/Golden/09-same-new-file/b-birch/mod.json b/RPGModder.Tests/Merge/Golden/09-same-new-file/b-birch/mod.json new file mode 100644 index 0000000..b79e5bb --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/09-same-new-file/b-birch/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "b-birch", + "name": "Birch Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "js/plugins/SharedHelper.js", + "target": "js/plugins/SharedHelper.js" + } + ], + "json_patches": [], + "plugins_registry": [] +} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/09-same-new-file/expected/collisions.json b/RPGModder.Tests/Merge/Golden/09-same-new-file/expected/collisions.json new file mode 100644 index 0000000..0637a08 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/09-same-new-file/expected/collisions.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/09-same-new-file/expected/files/js/plugins/sharedhelper.js b/RPGModder.Tests/Merge/Golden/09-same-new-file/expected/files/js/plugins/sharedhelper.js new file mode 100644 index 0000000..7bff55e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/09-same-new-file/expected/files/js/plugins/sharedhelper.js @@ -0,0 +1,4 @@ +// SharedHelper +(function() { + window.SharedHelper = { version: 1 }; +})(); diff --git a/RPGModder.Tests/Merge/Golden/09-same-new-file/vanilla/js/plugins.js b/RPGModder.Tests/Merge/Golden/09-same-new-file/vanilla/js/plugins.js new file mode 100644 index 0000000..04d5b05 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/09-same-new-file/vanilla/js/plugins.js @@ -0,0 +1,5 @@ +// Generated by RPG Maker. +// Do not edit this file directly. +var $plugins = +[ +]; diff --git a/RPGModder.Tests/Merge/Golden/09b-new-file-clash/a-ash/js/plugins/SharedHelper.js b/RPGModder.Tests/Merge/Golden/09b-new-file-clash/a-ash/js/plugins/SharedHelper.js new file mode 100644 index 0000000..7bff55e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/09b-new-file-clash/a-ash/js/plugins/SharedHelper.js @@ -0,0 +1,4 @@ +// SharedHelper +(function() { + window.SharedHelper = { version: 1 }; +})(); diff --git a/RPGModder.Tests/Merge/Golden/09b-new-file-clash/a-ash/mod.json b/RPGModder.Tests/Merge/Golden/09b-new-file-clash/a-ash/mod.json new file mode 100644 index 0000000..265910c --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/09b-new-file-clash/a-ash/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "a-ash", + "name": "Ash Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "js/plugins/SharedHelper.js", + "target": "js/plugins/SharedHelper.js" + } + ], + "json_patches": [], + "plugins_registry": [] +} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/09b-new-file-clash/b-birch/js/plugins/SharedHelper.js b/RPGModder.Tests/Merge/Golden/09b-new-file-clash/b-birch/js/plugins/SharedHelper.js new file mode 100644 index 0000000..3640c48 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/09b-new-file-clash/b-birch/js/plugins/SharedHelper.js @@ -0,0 +1,4 @@ +// SharedHelper +(function() { + window.SharedHelper = { version: 2 }; +})(); diff --git a/RPGModder.Tests/Merge/Golden/09b-new-file-clash/b-birch/mod.json b/RPGModder.Tests/Merge/Golden/09b-new-file-clash/b-birch/mod.json new file mode 100644 index 0000000..b79e5bb --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/09b-new-file-clash/b-birch/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "b-birch", + "name": "Birch Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "js/plugins/SharedHelper.js", + "target": "js/plugins/SharedHelper.js" + } + ], + "json_patches": [], + "plugins_registry": [] +} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/09b-new-file-clash/expected/collisions.json b/RPGModder.Tests/Merge/Golden/09b-new-file-clash/expected/collisions.json new file mode 100644 index 0000000..f73a220 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/09b-new-file-clash/expected/collisions.json @@ -0,0 +1,17 @@ +[ + { + "id": "7355101970aee977", + "kind": "FileClash", + "file": "js/plugins/sharedhelper.js", + "record": "*", + "path": "", + "mods": [ + "a-ash", + "b-birch" + ], + "blocking": true, + "allowed": [ + "PickMod" + ] + } +] \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/09b-new-file-clash/vanilla/js/plugins.js b/RPGModder.Tests/Merge/Golden/09b-new-file-clash/vanilla/js/plugins.js new file mode 100644 index 0000000..04d5b05 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/09b-new-file-clash/vanilla/js/plugins.js @@ -0,0 +1,5 @@ +// Generated by RPG Maker. +// Do not edit this file directly. +var $plugins = +[ +]; diff --git a/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/a-ash/js/plugins.js b/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/a-ash/js/plugins.js new file mode 100644 index 0000000..25e9719 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/a-ash/js/plugins.js @@ -0,0 +1,7 @@ +// Generated by RPG Maker. +// Do not edit this file directly. +var $plugins = +[ +{"name":"CompassHud","status":true,"description":"Draws a compass.","parameters":{"scale":"2","offsetX":"10"}}, +{"name":"WeatherTint","status":true,"description":"Tints the screen.","parameters":{"strength":"5"}} +]; diff --git a/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/a-ash/mod.json b/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/a-ash/mod.json new file mode 100644 index 0000000..1fc51ba --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/a-ash/mod.json @@ -0,0 +1,17 @@ +{ + "schema_version": 2, + "metadata": { + "id": "a-ash", + "name": "Ash Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [ + { + "source": "js/plugins.js", + "target": "js/plugins.js" + } + ], + "json_patches": [], + "plugins_registry": [] +} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/b-birch/mod.json b/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/b-birch/mod.json new file mode 100644 index 0000000..f600964 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/b-birch/mod.json @@ -0,0 +1,22 @@ +{ + "schema_version": 2, + "metadata": { + "id": "b-birch", + "name": "Birch Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [], + "json_patches": [], + "plugins_registry": [ + { + "name": "CompassHud", + "status": true, + "description": "Draws a compass.", + "parameters": { + "scale": "1", + "offsetX": "24" + } + } + ] +} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/expected/collisions.json b/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/expected/collisions.json new file mode 100644 index 0000000..0637a08 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/expected/collisions.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/expected/files/js/plugins.js b/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/expected/files/js/plugins.js new file mode 100644 index 0000000..9b93cb3 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/expected/files/js/plugins.js @@ -0,0 +1,7 @@ +// Generated by RPG Maker. +// Do not edit this file directly. +var $plugins = +[ +{"name":"CompassHud","status":true,"description":"Draws a compass.","parameters":{"scale":"2","offsetX":"24"}}, +{"name":"WeatherTint","status":true,"description":"Tints the screen.","parameters":{"strength":"5"}} +]; diff --git a/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/vanilla/js/plugins.js b/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/vanilla/js/plugins.js new file mode 100644 index 0000000..7694e34 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/10-plugin-parameter-edits/vanilla/js/plugins.js @@ -0,0 +1,7 @@ +// Generated by RPG Maker. +// Do not edit this file directly. +var $plugins = +[ +{"name":"CompassHud","status":true,"description":"Draws a compass.","parameters":{"scale":"1","offsetX":"10"}}, +{"name":"WeatherTint","status":true,"description":"Tints the screen.","parameters":{"strength":"5"}} +]; diff --git a/RPGModder.Tests/Merge/Golden/11-plugin-order/a-ash/mod.json b/RPGModder.Tests/Merge/Golden/11-plugin-order/a-ash/mod.json new file mode 100644 index 0000000..4052866 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/11-plugin-order/a-ash/mod.json @@ -0,0 +1,21 @@ +{ + "schema_version": 2, + "metadata": { + "id": "a-ash", + "name": "Ash Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [], + "json_patches": [], + "plugins_registry": [ + { + "name": "AshExtra", + "status": true, + "description": "Added by ash.", + "parameters": { + "mode": "fast" + } + } + ] +} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/11-plugin-order/b-birch/mod.json b/RPGModder.Tests/Merge/Golden/11-plugin-order/b-birch/mod.json new file mode 100644 index 0000000..bcbf37e --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/11-plugin-order/b-birch/mod.json @@ -0,0 +1,21 @@ +{ + "schema_version": 2, + "metadata": { + "id": "b-birch", + "name": "Birch Mod", + "author": "Zorkats", + "version": "1.0" + }, + "file_ops": [], + "json_patches": [], + "plugins_registry": [ + { + "name": "BirchExtra", + "status": true, + "description": "Added by birch.", + "parameters": { + "mode": "safe" + } + } + ] +} \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/11-plugin-order/expected/collisions.json b/RPGModder.Tests/Merge/Golden/11-plugin-order/expected/collisions.json new file mode 100644 index 0000000..14f7cb5 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/11-plugin-order/expected/collisions.json @@ -0,0 +1,18 @@ +[ + { + "id": "43788bd637f69b68", + "kind": "OrderAmbiguous", + "file": "js/plugins.js", + "record": "plugin:Omega", + "path": "@after", + "mods": [ + "a-ash", + "b-birch" + ], + "blocking": false, + "allowed": [ + "PickMod", + "KeepBothInProfileOrder" + ] + } +] \ No newline at end of file diff --git a/RPGModder.Tests/Merge/Golden/11-plugin-order/expected/files/js/plugins.js b/RPGModder.Tests/Merge/Golden/11-plugin-order/expected/files/js/plugins.js new file mode 100644 index 0000000..2a1fed3 --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/11-plugin-order/expected/files/js/plugins.js @@ -0,0 +1,9 @@ +// Generated by RPG Maker. +// Do not edit this file directly. +var $plugins = +[ +{"name":"Alpha","status":true,"description":"First base plugin.","parameters":{}}, +{"name":"Omega","status":true,"description":"Second base plugin.","parameters":{}}, +{"name":"AshExtra","status":true,"description":"Added by ash.","parameters":{"mode":"fast"}}, +{"name":"BirchExtra","status":true,"description":"Added by birch.","parameters":{"mode":"safe"}} +]; diff --git a/RPGModder.Tests/Merge/Golden/11-plugin-order/vanilla/js/plugins.js b/RPGModder.Tests/Merge/Golden/11-plugin-order/vanilla/js/plugins.js new file mode 100644 index 0000000..de7783d --- /dev/null +++ b/RPGModder.Tests/Merge/Golden/11-plugin-order/vanilla/js/plugins.js @@ -0,0 +1,7 @@ +// Generated by RPG Maker. +// Do not edit this file directly. +var $plugins = +[ +{"name":"Alpha","status":true,"description":"First base plugin.","parameters":{}}, +{"name":"Omega","status":true,"description":"Second base plugin.","parameters":{}} +]; diff --git a/RPGModder.Tests/Merge/IdRemapTests.cs b/RPGModder.Tests/Merge/IdRemapTests.cs new file mode 100644 index 0000000..5007c3a --- /dev/null +++ b/RPGModder.Tests/Merge/IdRemapTests.cs @@ -0,0 +1,893 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using RPGModder.Core.Services; +using static RPGModder.Tests.Merge.MergeTestKit; + +namespace RPGModder.Tests.Merge; + +/// TST-15, step 1: map events and maps. Content is invented (TST-2). +public sealed class IdRemapTests +{ + private const string MapKey = "data/map001.json"; + private const string MapInfos = "data/MapInfos.json"; + private const string CommonEvents = "data/CommonEvents.json"; + private const string NewMap = "data/Map002.json"; + + private const string VanillaMapInfos = + "[null,{\"id\":1,\"expanded\":false,\"name\":\"Field\",\"order\":1,\"parentId\":0,\"scrollX\":0,\"scrollY\":0}]"; + + private const string VanillaCommonEvents = + "[null,{\"id\":1,\"list\":[{\"code\":0,\"indent\":0,\"parameters\":[]}],\"name\":\"Rest\",\"switchId\":1,\"trigger\":0}]"; + + private static readonly BaseFileSet MapBases = Bases(Base(Map, VanillaMap)); + + private static JObject Command(int code, params object[] parameters) + { + return new JObject { ["code"] = code, ["indent"] = 0, ["parameters"] = new JArray(parameters) }; + } + + private static JObject NewEvent(int id, string name, params JToken[] commands) + { + var list = new JArray(commands.Select(command => command.DeepClone())); + list.Add(Command(0)); + return new JObject + { + ["id"] = id, + ["name"] = name, + ["note"] = "", + ["x"] = 1, + ["y"] = 0, + ["pages"] = new JArray(new JObject + { + ["conditions"] = new JObject { ["switch1Id"] = 1, ["switch1Valid"] = false }, + ["trigger"] = 0, + ["moveRoute"] = new JObject { ["list"] = new JArray(Command(0)), ["repeat"] = true }, + ["list"] = list + }) + }; + } + + /// Vanilla's map with appended to its events and applied. + private static string MapWith(JObject? added, Action? edit = null) + { + return EditMap(map => + { + if (added is not null) + { + ((JArray)map["events"]!).Add(added); + } + + edit?.Invoke(map); + }); + } + + private static JArray FirstList(JObject map, int eventId) + { + return (JArray)map["events"]![eventId]!["pages"]![0]!["list"]!; + } + + private static ModSource Mod(string modId, int priority, params (string Target, string Text)[] files) + { + return new ModSource( + modId, + priority, + files.Select(file => new ModFile(file.Target, "files/" + Path.GetFileName(file.Target), file.Text, Hash(file.Text))).ToList(), + [], + []); + } + + private static RemapMod Installed(ModSource mod, BaseFileSet bases, bool enabled = true, params string[] scripts) + { + return new RemapMod(ChangeSetBuilder.Build(mod, bases), enabled, scripts); + } + + private static RemapPlan Plan(BaseFileSet bases, params RemapMod[] mods) + { + return Plan(null, bases, mods); + } + + private static RemapPlan Plan(RpgMakerEngine? engine, BaseFileSet bases, params RemapMod[] mods) + { + return IdRemapPlanner.Plan(mods, [], [], bases, engine); + } + + /// The order lane A runs: plan, apply per enabled mod, then compose with the offers. + private static MergePlan ComposeRemapped(RemapPlan plan, BaseFileSet bases, params RemapMod[] mods) + { + List sets = mods + .Where(mod => mod.Enabled) + .Select(mod => IdRemapper.Apply(mod.ChangeSet, plan.Remaps)) + .ToList(); + return Composer.Compose(sets, [], bases, plan); + } + + private static string Entry(IdRemap remap) + { + return $"{remap.ModId}|{remap.Kind}|{remap.Scope}|{remap.FromId}>{remap.ToId}"; + } + + private static ModChangeSet ApplyOwn(RemapPlan plan, RemapMod mod) + { + return IdRemapper.Apply(mod.ChangeSet, plan.Remaps); + } + + [Fact] + public void Plan_TwoModsAddingDifferentEventsAtOneId_MovesTheLaterModAndBothDeploy() + { + RemapMod first = Installed(FileMod("a-tin", Map, MapWith(NewEvent(3, "Guard")), 0), MapBases); + RemapMod second = Installed(FileMod("b-oak", Map, MapWith(NewEvent(3, "Merchant")), 1), MapBases); + + string before = string.Join('\n', second.ChangeSet.Ops.Select(op => op.Value?.ToString())); + + RemapPlan plan = Plan(MapBases, first, second); + MergePlan merged = ComposeRemapped(plan, MapBases, first, second); + + Assert.Equal(before, string.Join('\n', second.ChangeSet.Ops.Select(op => op.Value?.ToString()))); + Assert.Equal(["b-oak|MapEvent|data/map001.json|3>4"], plan.NewEntries.Select(Entry)); + Assert.Equal(plan.NewEntries, plan.Remaps); + Assert.Empty(plan.Offers); + Assert.True(merged.IsDeployable); + Assert.Empty(merged.Collisions); + MergedOp moved = Assert.Single(merged.Ops, item => item.Op.Key.Record == "event:4"); + Assert.Equal(["b-oak"], moved.ModIds); + Assert.Equal(4, moved.Op.Value!["id"]!.Value()); + Assert.Equal("Guard", merged.Ops.Single(item => item.Op.Key.Record == "event:3").Op.Value!["name"]!.Value()); + OperationDiagnostic applied = Assert.Single(merged.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapApplied); + Assert.Equal(DiagnosticSeverity.Info, applied.Severity); + Assert.Equal("b-oak", applied.Subject); + Assert.Contains("MapEvent 3", applied.Message, StringComparison.Ordinal); + Assert.Contains("moved to 4", applied.Message, StringComparison.Ordinal); + } + + public static TheoryData EventReferenceRows => new() + { + { 203, "[3,0,0,0,0]", "[4,0,0,0,0]" }, + { 203, "[1,2,3,0]", "[1,2,4,0]" }, + { 205, "[3,{\"list\":[{\"code\":0}],\"repeat\":false,\"skippable\":false,\"wait\":true}]", "[4,{\"list\":[{\"code\":0}],\"repeat\":false,\"skippable\":false,\"wait\":true}]" }, + { 212, "[3,1,false]", "[4,1,false]" }, + { 213, "[3,1,false]", "[4,1,false]" }, + { 111, "[6,3,2]", "[6,4,2]" }, + { 122, "[1,1,0,3,5,3,0]", "[1,1,0,3,5,4,0]" }, + { 285, "[7,0,2,3,0]", "[7,0,2,4,0]" }, + + // Same codes, other forms: the 3 is a switch, a constant, a variable, an actor, a tile or this event. + { 111, "[0,3,0]", "[0,3,0]" }, + { 122, "[1,1,0,0,3]", "[1,1,0,0,3]" }, + { 122, "[1,1,0,3,3,3,0]", "[1,1,0,3,3,3,0]" }, + { 203, "[1,1,3,0,0]", "[1,1,3,0,0]" }, + { 203, "[0,0,3,0,0]", "[0,0,3,0,0]" }, + { 285, "[7,0,0,3,0]", "[7,0,0,3,0]" } + }; + + [Theory] + [MemberData(nameof(EventReferenceRows))] + public void Apply_MovedEvent_RewritesEveryEventRowOfTheReferenceTable(int code, string before, string after) + { + JObject reference = Command(code, JArray.Parse(before).ToArray()); + RemapMod first = Installed(FileMod("a-tin", Map, MapWith(NewEvent(3, "Guard")), 0), MapBases); + RemapMod second = Installed( + FileMod("b-oak", Map, MapWith(NewEvent(3, "Merchant", reference), map => FirstList(map, 1).Insert(0, reference.DeepClone())), 1), + MapBases); + + RemapPlan plan = Plan(MapBases, first, second); + ModChangeSet moved = ApplyOwn(plan, second); + + Assert.Equal(["b-oak|MapEvent|data/map001.json|3>4"], plan.NewEntries.Select(Entry)); + ChangeOp added = Assert.Single(moved.Ops, op => op.Kind == ChangeKind.AddRecord); + Assert.Equal("event:4", added.Key.Record); + Assert.Equal(after, added.Value!["pages"]![0]!["list"]![0]!["parameters"]!.ToString(Newtonsoft.Json.Formatting.None)); + ChangeOp edited = Assert.Single(moved.Ops, op => op.Key.Record == "event:1"); + Assert.Equal(after, edited.Value![0]!["parameters"]!.ToString(Newtonsoft.Json.Formatting.None)); + } + + [Fact] + public void Apply_MovedMap_RewritesEveryMapRowOfTheReferenceTableAndWritesTheNewFile() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap), Base(MapInfos, VanillaMapInfos), Base(SystemFile, VanillaSystem)); + string Infos(string name, int parentOfField) => EditArray(VanillaMapInfos, infos => + { + infos[1]!["parentId"] = parentOfField; + infos.Add(new JObject { ["id"] = 2, ["expanded"] = false, ["name"] = name, ["order"] = 2, ["parentId"] = 0, ["scrollX"] = 0, ["scrollY"] = 0 }); + }); + string NewMapText(string name, params JToken[] commands) => EditMap(map => + { + map["displayName"] = name; + map["events"] = new JArray(JValue.CreateNull(), NewEvent(1, "Exit", commands)); + }); + + ModSource first = Mod("a-tin", 0, (NewMap, NewMapText("Cave")), (MapInfos, Infos("Cave", 0))); + ModSource second = Mod( + "b-oak", + 1, + (NewMap, NewMapText("Tower", Command(201, 0, 2, 1, 1, 0, 0))), + (MapInfos, Infos("Tower", 2)), + (SystemFile, EditSystem(system => + { + system["startMapId"] = 2; + system["boat"] = new JObject { ["bgm"] = new JObject { ["name"] = "Sea" }, ["startMapId"] = 2 }; + system["ship"] = new JObject { ["startMapId"] = 2 }; + system["airship"] = new JObject { ["startMapId"] = 2 }; + })), + (Map, MapWith(null, map => + { + FirstList(map, 1).Insert(0, Command(201, 0, 2, 0, 0, 2, 0)); + FirstList(map, 1).Insert(0, Command(202, 1, 0, 2, 3, 3)); + FirstList(map, 1).Insert(0, Command(201, 1, 2, 3, 4, 0, 0)); + }))); + RemapMod a = Installed(first, bases); + RemapMod b = Installed(second, bases); + + RemapPlan plan = Plan(bases, a, b); + MergePlan merged = ComposeRemapped(plan, bases, a, b); + IReadOnlyList files = MergedFileWriter.Write(merged, bases, null); + + Assert.Equal(["b-oak|Map||2>3"], plan.NewEntries.Select(Entry)); + Assert.True(merged.IsDeployable); + Assert.Empty(merged.Collisions); + + MergedFile kept = Assert.Single(files, file => file.File == "data/map002.json"); + Assert.Equal(MergedFileSource.ModFile, kept.Source); + Assert.Equal("a-tin", kept.ModId); + + MergedFile renamed = Assert.Single(files, file => file.File == "data/map003.json"); + Assert.Equal(MergedFileSource.Text, renamed.Source); + Assert.Equal("data/Map003.json", renamed.DiskPath); + var tower = JObject.Parse(renamed.Text!); + Assert.Equal("Tower", tower["displayName"]!.Value()); + Assert.Equal("[0,3,1,1,0,0]", FirstList(tower, 1)[0]!["parameters"]!.ToString(Newtonsoft.Json.Formatting.None)); + + var infos = JArray.Parse(files.Single(file => file.File == "data/mapinfos.json").Text!); + Assert.Equal("Cave", infos[2]!["name"]!.Value()); + Assert.Equal(3, infos[3]!["id"]!.Value()); + Assert.Equal("Tower", infos[3]!["name"]!.Value()); + Assert.Equal(3, infos[1]!["parentId"]!.Value()); + + var system = JObject.Parse(files.Single(file => file.File == "data/system.json").Text!); + Assert.Equal(3, system["startMapId"]!.Value()); + Assert.Equal(3, system["boat"]!["startMapId"]!.Value()); + Assert.Equal(3, system["ship"]!["startMapId"]!.Value()); + Assert.Equal(3, system["airship"]!["startMapId"]!.Value()); + + var field = JObject.Parse(files.Single(file => file.File == "data/map001.json").Text!); + JArray list = FirstList(field, 1); + Assert.Equal("[1,2,3,4,0,0]", list[0]!["parameters"]!.ToString(Newtonsoft.Json.Formatting.None)); + Assert.Equal("[1,0,3,3,3]", list[1]!["parameters"]!.ToString(Newtonsoft.Json.Formatting.None)); + Assert.Equal("[0,3,0,0,2,0]", list[2]!["parameters"]!.ToString(Newtonsoft.Json.Formatting.None)); + } + + [Fact] + public void Plan_SecondRunWithTheRecordedEntry_ReusesItAndRecordsNothingNew() + { + RemapMod first = Installed(FileMod("a-tin", Map, MapWith(NewEvent(3, "Guard")), 0), MapBases); + RemapMod second = Installed(FileMod("b-oak", Map, MapWith(NewEvent(3, "Merchant")), 1), MapBases); + RemapPlan firstRun = Plan(MapBases, first, second); + + RemapPlan secondRun = IdRemapPlanner.Plan([first, second], firstRun.NewEntries, ["a-tin", "b-oak"], MapBases, null); + + Assert.Empty(secondRun.NewEntries); + Assert.Equal(firstRun.Remaps, secondRun.Remaps); + Assert.True(ComposeRemapped(secondRun, MapBases, first, second).IsDeployable); + } + + [Fact] + public void Plan_ModInDeployedMods_KeepsItsIdOverProfileOrder() + { + RemapMod first = Installed(FileMod("a-tin", Map, MapWith(NewEvent(3, "Guard")), 0), MapBases); + RemapMod second = Installed(FileMod("b-oak", Map, MapWith(NewEvent(3, "Merchant")), 1), MapBases); + + RemapPlan plan = IdRemapPlanner.Plan([first, second], [], ["b-oak"], MapBases, null); + + Assert.Equal(["a-tin|MapEvent|data/map001.json|3>4"], plan.NewEntries.Select(Entry)); + } + + public static TheoryData FreeTextHits => new() + { + "script", + "note", + "formula", + "plugin parameter", + "script line", + "plugin command", + "plugin command args", + "route script", + "branch script", + "variable script" + }; + + /// The event command that holds the number 3 in free text, for the that name one. + private static JObject? FreeTextCommand(string? where) + { + return where switch + { + "script" => Command(355, "$gameMap.event(3).erase();"), + "script line" => Command(655, "$gameMap.event(3).erase();"), + "plugin command" => Command(356, "Follow 3"), + "plugin command args" => Command(357, "Alpha", "follow", "", new JObject { ["target"] = "3" }), + "branch script" => Command(111, 12, "$gameMap.event(3).x > 0"), + "variable script" => Command(122, 1, 1, 0, 4, "$gameMap.event(3).x"), + _ => null + }; + } + + /// Mod adding event 3, with the number 3 in the free text names. + private static ModSource FreeTextMod(string modId, string name, int priority, string? where) + { + JObject? command = FreeTextCommand(where); + JObject added = NewEvent(3, name, command is null ? [] : [command]); + if (where == "note") + { + added["note"] = ""; + } + + if (where == "route script") + { + ((JArray)added["pages"]![0]!["moveRoute"]!["list"]!).Insert(0, Command(45, "this.jump(3, 0);")); + } + + var files = new List<(string, string)> { (Map, MapWith(added)) }; + if (where == "formula") + { + files.Add((Items, EditItems(items => items[1]!["damage"] = new JObject { ["formula"] = "a.atk * 3", ["type"] = 1 }))); + } + + if (where == "plugin parameter") + { + files.Add((PluginList, PluginsJs(Plugin("Alpha", "{\"speed\":\"3\",\"Font Size\":\"20\"}"), Plugin("Omega")))); + } + + return Mod(modId, priority, files.ToArray()); + } + + [Theory] + [MemberData(nameof(FreeTextHits))] + public void Plan_OldIdInFreeTextOfTheLaterMod_MovesTheEarlierModInstead(string where) + { + BaseFileSet bases = Bases(Base(Map, VanillaMap), Base(Items, VanillaItems), Base(PluginList, VanillaPlugins)); + RemapMod first = Installed(FreeTextMod("a-tin", "Guard", 0, null), bases); + RemapMod second = Installed(FreeTextMod("b-oak", "Merchant", 1, where), bases); + + RemapPlan plan = Plan(bases, first, second); + + Assert.Equal(["a-tin|MapEvent|data/map001.json|3>4"], plan.NewEntries.Select(Entry)); + } + + [Theory] + [MemberData(nameof(FreeTextHits))] + public void Plan_OldIdInFreeTextOfBothMods_KeepsTheClashBlocking(string where) + { + BaseFileSet bases = Bases(Base(Map, VanillaMap), Base(Items, VanillaItems), Base(PluginList, VanillaPlugins)); + RemapMod first = Installed(FreeTextMod("a-tin", "Guard", 0, where), bases); + RemapMod second = Installed(FreeTextMod("b-oak", "Merchant", 1, where), bases); + + RemapPlan plan = Plan(bases, first, second); + MergePlan merged = ComposeRemapped(plan, bases, first, second); + + Assert.Empty(plan.Remaps); + Assert.Empty(plan.Offers); + Assert.False(merged.IsDeployable); + Collision clash = Assert.Single(merged.Collisions, item => item.Kind == CollisionKind.IdClash); + Assert.Equal("event:3", clash.Key.Record); + Assert.True(clash.Blocking); + Assert.Equal([ResolutionKind.PickMod, ResolutionKind.DisableMod], clash.Allowed); + } + + [Fact] + public void Plan_OldIdOnlyInAShippedPluginFile_OffersRemapWithAWarningAndNeverPicksIt() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap), Base(Items, VanillaItems), Base(PluginList, VanillaPlugins)); + RemapMod first = Installed(FreeTextMod("a-tin", "Guard", 0, "script"), bases); + RemapMod second = Installed(FreeTextMod("b-oak", "Merchant", 1, null), bases, scripts: "var step = 3;"); + + RemapPlan plan = Plan(bases, first, second); + MergePlan merged = ComposeRemapped(plan, bases, first, second); + + Assert.Empty(plan.Remaps); + Assert.Equal(["b-oak|MapEvent|data/map001.json|3>4"], plan.Offers.Select(Entry)); + Collision clash = Assert.Single(merged.Collisions); + Assert.Equal(CollisionKind.IdClash, clash.Kind); + Assert.True(clash.Blocking); + Assert.Equal([ResolutionKind.PickMod, ResolutionKind.Remap, ResolutionKind.DisableMod], clash.Allowed); + Assert.Equal(ResolutionSource.Unresolved, Assert.Single(merged.Outcomes).Source); + Assert.False(merged.IsDeployable); + OperationDiagnostic warning = Assert.Single(merged.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapUnchecked); + Assert.Equal(DiagnosticSeverity.Warning, warning.Severity); + Assert.Equal("b-oak", warning.Subject); + Assert.Null(plan.OfferFor(clash, "a-tin")); + + // The player chooses Remap: lane A records the offer, and the next plan applies it. + IdRemap chosen = plan.OfferFor(clash, "b-oak")!; + RemapPlan next = IdRemapPlanner.Plan([first, second], [chosen], [], bases, null); + Assert.Empty(next.NewEntries); + Assert.Equal([chosen], next.Remaps); + Assert.True(ComposeRemapped(next, bases, first, second).IsDeployable); + } + + [Fact] + public void Plan_EntryWhoseOldIdIsNoLongerAdded_StaysInactiveAndChangesNothing() + { + RemapMod mod = Installed(FileMod("b-oak", Map, MapWith(NewEvent(3, "Merchant")), 0), MapBases); + var stale = new IdRemap("b-oak", IdKind.MapEvent, MapKey, 5, 9); + + RemapPlan plan = IdRemapPlanner.Plan([mod], [stale], [], MapBases, null); + + Assert.Empty(plan.Remaps); + Assert.Empty(plan.NewEntries); + Assert.Same(mod.ChangeSet, IdRemapper.Apply(mod.ChangeSet, [stale])); + } + + [Fact] + public void Plan_Target_SitsAboveDisabledModsAndEveryRecordedEntry() + { + RemapMod first = Installed(FileMod("a-tin", Map, MapWith(NewEvent(3, "Guard")), 0), MapBases); + RemapMod second = Installed(FileMod("b-oak", Map, MapWith(NewEvent(3, "Merchant")), 1), MapBases); + RemapMod disabled = Installed( + FileMod("c-elm", Map, MapWith(null, map => + { + var events = (JArray)map["events"]!; + events.Add(JValue.CreateNull()); + events.Add(JValue.CreateNull()); + events.Add(JValue.CreateNull()); + events.Add(NewEvent(6, "Sage")); + })), + MapBases, + enabled: false); + var stale = new IdRemap("c-elm", IdKind.MapEvent, MapKey, 4, 9); + + RemapPlan plan = IdRemapPlanner.Plan([first, second, disabled], [stale], [], MapBases, null); + + Assert.Equal(["b-oak|MapEvent|data/map001.json|3>10"], plan.NewEntries.Select(Entry)); + } + + [Fact] + public void Plan_EqualContentAtOneId_IsNoClash() + { + RemapMod first = Installed(FileMod("a-tin", Map, MapWith(NewEvent(3, "Guard")), 0), MapBases); + RemapMod second = Installed(FileMod("b-oak", Map, MapWith(NewEvent(3, "Guard")), 1), MapBases); + + RemapPlan plan = Plan(MapBases, first, second); + MergePlan merged = ComposeRemapped(plan, MapBases, first, second); + + Assert.Empty(plan.Remaps); + Assert.True(merged.IsDeployable); + Assert.Equal(["a-tin", "b-oak"], Assert.Single(merged.Ops).ModIds); + } + + [Theory] + [InlineData(null)] + [InlineData(RpgMakerEngine.MV)] + [InlineData(RpgMakerEngine.MZ)] + public void Plan_TargetPastTheEditorLimit_RefusesTheMove(RpgMakerEngine? engine) + { + string wide = EditMap(map => + { + var events = (JArray)map["events"]!; + while (events.Count < 999) + { + events.Add(JValue.CreateNull()); + } + }); + BaseFileSet bases = Bases(Base(Map, wide)); + string Adding(string name) => EditMapText(wide, map => ((JArray)map["events"]!).Add(NewEvent(999, name))); + RemapMod first = Installed(FileMod("a-tin", Map, Adding("Guard"), 0), bases); + RemapMod second = Installed(FileMod("b-oak", Map, Adding("Merchant"), 1), bases); + + RemapPlan plan = Plan(engine, bases, first, second); + + Assert.Empty(plan.Remaps); + Assert.False(ComposeRemapped(plan, bases, first, second).IsDeployable); + } + + private static string EditMapText(string text, Action edit) + { + var map = JObject.Parse(text); + edit(map); + return map.ToString(); + } + + public static TheoryData MapsByVariable => new() + { + "[201,1,5,6,7,0,0]", + "[202,0,1,5,6,7]" + }; + + [Theory] + [MemberData(nameof(MapsByVariable))] + public void Plan_MapByVariableWithTheOldMapIdAsAConstant_RefusesThatModsMove(string transfer) + { + int[] parts = JArray.Parse(transfer).Values().ToArray(); + JObject byVariable = Command(parts[0], parts.Skip(1).Cast().ToArray()); + BaseFileSet bases = Bases(Base(Map, VanillaMap), Base(MapInfos, VanillaMapInfos)); + string NewMapText(string name) => EditMap(map => map["displayName"] = name); + ModSource first = Mod("a-tin", 0, (NewMap, NewMapText("Cave"))); + ModSource second = Mod( + "b-oak", + 1, + (NewMap, NewMapText("Tower")), + (Map, MapWith(null, map => + { + FirstList(map, 1).Insert(0, byVariable); + FirstList(map, 1).Insert(0, Command(122, 5, 5, 0, 0, 2)); + }))); + + RemapPlan plan = Plan(bases, Installed(first, bases), Installed(second, bases)); + + Assert.Equal(["a-tin|Map||2>3"], plan.NewEntries.Select(Entry)); + } + + public static TheoryData CommonEventReferences => new() + { + { 213, "[3,1,false]" }, + { 285, "[7,0,2,3,0]" } + }; + + [Theory] + [MemberData(nameof(CommonEventReferences))] + public void Plan_EventCommandInACommonEvent_IsAmbiguousAndRefusesThatModsMove(int code, string parameters) + { + BaseFileSet bases = Bases(Base(Map, VanillaMap), Base(CommonEvents, VanillaCommonEvents)); + string events = EditArray(VanillaCommonEvents, list => list.Add(new JObject + { + ["id"] = 2, + ["list"] = new JArray(Command(code, JArray.Parse(parameters).ToArray()), Command(0)), + ["name"] = "Wave", + ["switchId"] = 1, + ["trigger"] = 0 + })); + RemapMod first = Installed(FileMod("a-tin", Map, MapWith(NewEvent(3, "Guard")), 0), bases); + RemapMod second = Installed(Mod("b-oak", 1, (Map, MapWith(NewEvent(3, "Merchant"))), (CommonEvents, events)), bases); + + RemapPlan plan = Plan(bases, first, second); + + Assert.Equal(["a-tin|MapEvent|data/map001.json|3>4"], plan.NewEntries.Select(Entry)); + } + + [Fact] + public void Plan_MissingVanillaMapInfos_LeavesTheMapClashBlocking() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + ModSource first = Mod("a-tin", 0, (NewMap, EditMap(map => map["displayName"] = "Cave"))); + ModSource second = Mod("b-oak", 1, (NewMap, EditMap(map => map["displayName"] = "Tower"))); + RemapMod a = Installed(first, bases); + RemapMod b = Installed(second, bases); + + RemapPlan plan = Plan(bases, a, b); + + Assert.Empty(plan.Remaps); + Assert.Equal(CollisionKind.IdClash, Assert.Single(ComposeRemapped(plan, bases, a, b).Collisions).Kind); + } + + [Fact] + public void Plan_ShuffledInputs_GiveTheSamePlan() + { + RemapMod[] mods = + [ + Installed(FileMod("a-tin", Map, MapWith(NewEvent(3, "Guard")), 0), MapBases), + Installed(FileMod("b-oak", Map, MapWith(NewEvent(3, "Merchant")), 1), MapBases), + Installed(FileMod("c-elm", Map, MapWith(NewEvent(3, "Sage")), 2), MapBases) + ]; + IdRemap[] recorded = [new IdRemap("z-old", IdKind.MapEvent, MapKey, 3, 7), new IdRemap("y-old", IdKind.MapEvent, MapKey, 3, 8)]; + + RemapPlan forward = IdRemapPlanner.Plan(mods, recorded, ["c-elm"], MapBases, null); + RemapPlan backward = IdRemapPlanner.Plan(mods.Reverse().ToList(), recorded.Reverse().ToList(), ["c-elm"], MapBases, null); + + Assert.Equal(["a-tin|MapEvent|data/map001.json|3>9", "b-oak|MapEvent|data/map001.json|3>10"], forward.NewEntries.Select(Entry)); + Assert.Equal(forward.Remaps, backward.Remaps); + Assert.Equal(forward.NewEntries, backward.NewEntries); + } + + [Fact] + public void Apply_TwoTargetsForOneOldId_IsACallerBug() + { + RemapMod mod = Installed(FileMod("b-oak", Map, MapWith(NewEvent(3, "Merchant"))), MapBases); + + Assert.Throws(() => IdRemapper.Apply( + mod.ChangeSet, + [new IdRemap("b-oak", IdKind.MapEvent, MapKey, 3, 4), new IdRemap("b-oak", IdKind.MapEvent, MapKey, 3, 5)])); + } + + /// Vanilla's map with events added at ids 3 and up, in order; a null leaves a hole. + private static string MapAdding(params JObject?[] added) + { + return MapWith(null, map => + { + var events = (JArray)map["events"]!; + while (events.Count < 3) + { + events.Add(JValue.CreateNull()); + } + + foreach (JObject? item in added) + { + events.Add(item is null ? JValue.CreateNull() : item); + } + }); + } + + [Fact] + public void Plan_RecordedMoveOntoAnIdTheModNowAddsThatCannotMove_IsABlockingClashWithoutPickMod() + { + RemapMod first = Installed(FileMod("a-tin", Map, MapWith(NewEvent(3, "Guard")), 0), MapBases); + RemapMod updated = Installed( + FileMod("b-oak", Map, MapAdding(NewEvent(3, "Merchant"), NewEvent(4, "Smith", Command(355, "$gameMap.event(4).erase();"))), 1), + MapBases); + var recorded = new IdRemap("b-oak", IdKind.MapEvent, MapKey, 3, 4); + + RemapPlan plan = IdRemapPlanner.Plan([first, updated], [recorded], ["a-tin", "b-oak"], MapBases, null); + MergePlan merged = ComposeRemapped(plan, MapBases, first, updated); + MergePlan picked = Composer.Compose( + [first.ChangeSet, IdRemapper.Apply(updated.ChangeSet, plan.Remaps)], + [new Resolution(Assert.Single(merged.Collisions).Id, ResolutionKind.PickMod, "b-oak")], + MapBases, + plan); + + Assert.Equal([recorded], plan.Remaps); + Assert.Empty(plan.NewEntries); + Collision clash = Assert.Single(merged.Collisions); + Assert.Equal(CollisionKind.IdClash, clash.Kind); + Assert.Equal("event:4", clash.Key.Record); + Assert.Equal(["b-oak"], clash.ModIds); + Assert.Equal([ResolutionKind.DisableMod], clash.Allowed); + Assert.False(merged.IsDeployable); + Assert.False(picked.IsDeployable); + } + + [Fact] + public void Plan_RecordedMoveOntoAnIdTheModNowAddsThatCanMove_MovesThatIdOnward() + { + RemapMod first = Installed(FileMod("a-tin", Map, MapWith(NewEvent(3, "Guard")), 0), MapBases); + RemapMod updated = Installed( + FileMod("b-oak", Map, MapAdding(NewEvent(3, "Merchant", Command(213, 4, 1, false)), NewEvent(4, "Smith", Command(213, 3, 1, false))), 1), + MapBases); + var recorded = new IdRemap("b-oak", IdKind.MapEvent, MapKey, 3, 4); + + RemapPlan plan = IdRemapPlanner.Plan([first, updated], [recorded], ["a-tin", "b-oak"], MapBases, null); + MergePlan merged = ComposeRemapped(plan, MapBases, first, updated); + + Assert.Equal(["b-oak|MapEvent|data/map001.json|3>4", "b-oak|MapEvent|data/map001.json|4>5"], plan.Remaps.Select(Entry)); + Assert.True(merged.IsDeployable); + JToken merchant = merged.Ops.Single(item => item.Op.Key.Record == "event:4").Op.Value!; + JToken smith = merged.Ops.Single(item => item.Op.Key.Record == "event:5").Op.Value!; + Assert.Equal("Merchant", merchant["name"]!.Value()); + Assert.Equal(5, merchant["pages"]![0]!["list"]![0]!["parameters"]![0]!.Value()); + Assert.Equal("Smith", smith["name"]!.Value()); + Assert.Equal(4, smith["pages"]![0]!["list"]![0]!["parameters"]![0]!.Value()); + } + + [Fact] + public void Plan_DuplicateRecordedEntries_OnlyTheStandingOneHoldsItsTarget() + { + RemapMod mod = Installed(FileMod("b-oak", Map, MapAdding(NewEvent(3, "Merchant"), null, null, NewEvent(6, "Smith"))), MapBases); + IdRemap[] recorded = + [ + new IdRemap("b-oak", IdKind.MapEvent, MapKey, 3, 8), + new IdRemap("b-oak", IdKind.MapEvent, MapKey, 6, 8), + new IdRemap("b-oak", IdKind.MapEvent, MapKey, 3, 7) + ]; + + RemapPlan plan = IdRemapPlanner.Plan([mod], recorded, ["b-oak"], MapBases, null); + + Assert.Equal(["b-oak|MapEvent|data/map001.json|3>7", "b-oak|MapEvent|data/map001.json|6>8"], plan.Remaps.Select(Entry)); + } + + private static string Tree(params (int Id, string Name)[] added) + { + return EditArray(VanillaMapInfos, infos => + { + foreach ((int id, string name) in added) + { + while (infos.Count < id) + { + infos.Add(JValue.CreateNull()); + } + + infos.Add(new JObject { ["id"] = id, ["expanded"] = false, ["name"] = name, ["order"] = id, ["parentId"] = 0, ["scrollX"] = 0, ["scrollY"] = 0 }); + } + }); + } + + [Fact] + public void Plan_VanillaMapFileOutsideTheTree_IsNeverATarget() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap), Base(MapInfos, VanillaMapInfos), Base("data/Map003.json", VanillaMap)); + RemapMod a = Installed(Mod("a-tin", 0, (NewMap, EditMap(map => map["displayName"] = "Cave")), (MapInfos, Tree((2, "Cave")))), bases); + RemapMod b = Installed(Mod("b-oak", 1, (NewMap, EditMap(map => map["displayName"] = "Tower")), (MapInfos, Tree((2, "Tower")))), bases); + + RemapPlan plan = Plan(bases, a, b); + + Assert.Equal(["b-oak|Map||2>4"], plan.NewEntries.Select(Entry)); + } + + [Fact] + public void Plan_TreeRecordForAVanillaMapFile_CannotMove() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap), Base(MapInfos, VanillaMapInfos), Base(NewMap, VanillaMap)); + RemapMod a = Installed(Mod("a-tin", 0, (MapInfos, Tree((2, "Cave")))), bases); + RemapMod b = Installed(Mod("b-oak", 1, (MapInfos, Tree((2, "Tower")))), bases); + + RemapPlan plan = Plan(bases, a, b); + MergePlan merged = ComposeRemapped(plan, bases, a, b); + + Assert.Empty(plan.Remaps); + Assert.Empty(plan.Offers); + Collision clash = Assert.Single(merged.Collisions); + Assert.Equal(CollisionKind.IdClash, clash.Kind); + Assert.False(merged.IsDeployable); + } + + [Theory] + [InlineData(null)] + [InlineData(RpgMakerEngine.MV)] + public void Plan_MapPastTheEditorLimit_RefusesTheMove(RpgMakerEngine? engine) + { + (BaseFileSet bases, RemapMod a, RemapMod b) = MapClashAt(999); + + RemapPlan plan = Plan(engine, bases, a, b); + + Assert.Empty(plan.Remaps); + Assert.False(ComposeRemapped(plan, bases, a, b).IsDeployable); + } + + [Fact] + public void Plan_MzMapPast999_MovesTo1000() + { + (BaseFileSet bases, RemapMod a, RemapMod b) = MapClashAt(999); + + RemapPlan plan = Plan(RpgMakerEngine.MZ, bases, a, b); + MergePlan merged = ComposeRemapped(plan, bases, a, b); + IReadOnlyList files = MergedFileWriter.Write(merged, bases, null); + + Assert.Equal(["b-oak|Map||999>1000"], plan.NewEntries.Select(Entry)); + Assert.True(merged.IsDeployable); + MergedFile moved = Assert.Single(files, file => file.File == "data/map1000.json"); + Assert.Equal("data/Map1000.json", moved.DiskPath); + Assert.Equal("Tower", JObject.Parse(moved.Text!)["displayName"]!.Value()); + } + + [Fact] + public void Plan_MzMapPastTheEditorLimit_RefusesTheMove() + { + (BaseFileSet bases, RemapMod a, RemapMod b) = MapClashAt(2000); + + RemapPlan plan = Plan(RpgMakerEngine.MZ, bases, a, b); + + Assert.Empty(plan.Remaps); + Assert.False(ComposeRemapped(plan, bases, a, b).IsDeployable); + } + + /// Two mods add map to a tree whose highest id is the one below it. + private static (BaseFileSet Bases, RemapMod A, RemapMod B) MapClashAt(int id) + { + string tree = EditArray(VanillaMapInfos, infos => + { + while (infos.Count < id) + { + infos.Add(JValue.CreateNull()); + } + }); + BaseFileSet bases = Bases(Base(MapInfos, tree)); + string file = "data/Map" + id.ToString("D3", System.Globalization.CultureInfo.InvariantCulture) + ".json"; + RemapMod a = Installed(Mod("a-tin", 0, (file, EditMap(map => map["displayName"] = "Cave"))), bases); + RemapMod b = Installed(Mod("b-oak", 1, (file, EditMap(map => map["displayName"] = "Tower"))), bases); + return (bases, a, b); + } + + [Fact] + public void Plan_MapOfferOnlyInAPluginFile_SettlesBothCollisionsWithOneWarning() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap), Base(MapInfos, VanillaMapInfos)); + RemapMod a = Installed( + Mod("a-tin", 0, (NewMap, EditMap(map => { map["displayName"] = "Cave"; map["note"] = ""; })), (MapInfos, Tree((2, "Cave")))), + bases); + RemapMod b = Installed( + Mod("b-oak", 1, (NewMap, EditMap(map => map["displayName"] = "Tower")), (MapInfos, Tree((2, "Tower")))), + bases, + scripts: "var floor = 2;"); + + RemapPlan plan = Plan(bases, a, b); + MergePlan merged = ComposeRemapped(plan, bases, a, b); + + Assert.Equal(["b-oak|Map||2>3"], plan.Offers.Select(Entry)); + Assert.Equal(2, merged.Collisions.Count); + Assert.All(merged.Collisions, clash => + { + Assert.Equal([ResolutionKind.PickMod, ResolutionKind.Remap, ResolutionKind.DisableMod], clash.Allowed); + Assert.Equal(plan.Offers[0], plan.OfferFor(clash, "b-oak")); + }); + Assert.Single(merged.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapUnchecked); + } + + [Fact] + public void Apply_RewrittenNewDataFile_NamesItsModForTheCasing() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap), Base(MapInfos, VanillaMapInfos)); + const string Cutscenes = "data/Cutscenes.json"; + RemapMod a = Installed(Mod("a-tin", 0, (NewMap, EditMap(map => map["displayName"] = "Cave")), (MapInfos, Tree((2, "Cave")))), bases); + RemapMod b = Installed( + Mod( + "b-oak", + 1, + (NewMap, EditMap(map => map["displayName"] = "Tower")), + (MapInfos, Tree((2, "Tower"))), + (Cutscenes, new JArray(Command(201, 0, 2, 1, 1, 0, 0)).ToString())), + bases); + + RemapPlan plan = Plan(bases, a, b); + IReadOnlyList files = MergedFileWriter.Write(ComposeRemapped(plan, bases, a, b), bases, null); + + Assert.Equal(["b-oak|Map||2>3"], plan.NewEntries.Select(Entry)); + MergedFile cutscenes = Assert.Single(files, file => file.File == "data/cutscenes.json"); + Assert.Equal(MergedFileSource.Text, cutscenes.Source); + Assert.Equal("b-oak", cutscenes.ModId); + Assert.Null(cutscenes.DiskPath); + Assert.Equal("[0,3,1,1,0,0]", JArray.Parse(cutscenes.Text!)[0]!["parameters"]!.ToString(Newtonsoft.Json.Formatting.None)); + } + + [Fact] + public void Plan_DeployedModAgainstANewcomerHeldOnlyByAPluginFile_StaysAndOffersTheNewcomerAMove() + { + RemapMod deployed = Installed(FileMod("a-tin", Map, MapWith(NewEvent(3, "Guard")), 0), MapBases); + RemapMod newcomer = Installed(FileMod("b-oak", Map, MapWith(NewEvent(3, "Merchant")), 1), MapBases, scripts: "var step = 3;"); + + RemapPlan plan = IdRemapPlanner.Plan([deployed, newcomer], [], ["a-tin"], MapBases, null); + MergePlan merged = ComposeRemapped(plan, MapBases, deployed, newcomer); + + Assert.Empty(plan.Remaps); + Assert.Equal(["b-oak|MapEvent|data/map001.json|3>4"], plan.Offers.Select(Entry)); + Collision clash = Assert.Single(merged.Collisions); + Assert.True(clash.Blocking); + Assert.Equal([ResolutionKind.PickMod, ResolutionKind.Remap, ResolutionKind.DisableMod], clash.Allowed); + Assert.Single(merged.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapUnchecked); + Assert.False(merged.IsDeployable); + } + + /// Vanilla's map after a game update: a new event 4 fills what was a hole. + private static readonly string UpdatedMap = EditMapText(VanillaMap, map => + { + var events = (JArray)map["events"]!; + events.Add(JValue.CreateNull()); + events.Add(NewEvent(4, "Well")); + }); + + private static string UpdatedMapAdding(string name) + { + return EditMapText(UpdatedMap, map => map["events"]![3] = NewEvent(3, name)); + } + + [Fact] + public void Plan_RecordedTargetVanillaNowUses_PlansTheIdAgainWithAWarningOnce() + { + BaseFileSet bases = Bases(Base(Map, UpdatedMap)); + RemapMod first = Installed(FileMod("a-tin", Map, UpdatedMapAdding("Guard"), 0), bases); + RemapMod second = Installed(FileMod("b-oak", Map, UpdatedMapAdding("Merchant"), 1), bases); + var recorded = new IdRemap("b-oak", IdKind.MapEvent, MapKey, 3, 4); + + RemapPlan plan = IdRemapPlanner.Plan([first, second], [recorded], ["a-tin", "b-oak"], bases, null); + MergePlan merged = ComposeRemapped(plan, bases, first, second); + RemapPlan next = IdRemapPlanner.Plan([first, second], [recorded, .. plan.NewEntries], ["a-tin", "b-oak"], bases, null); + + Assert.Equal(["b-oak|MapEvent|data/map001.json|3>5"], plan.NewEntries.Select(Entry)); + Assert.Equal(plan.NewEntries, plan.Remaps); + OperationDiagnostic warning = Assert.Single(merged.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapTargetTaken); + Assert.Equal(DiagnosticSeverity.Warning, warning.Severity); + Assert.Equal("b-oak", warning.Subject); + Assert.True(merged.IsDeployable); + Assert.DoesNotContain(merged.Ops, item => item.Op.Key.Record == "event:4"); + Assert.Empty(next.NewEntries); + Assert.Empty(next.Diagnostics); + Assert.Equal(plan.Remaps, next.Remaps); + } + + [Fact] + public void Plan_RecordedTargetVanillaNowUsesWithNoClash_LeavesTheIdWhereTheModPutIt() + { + BaseFileSet bases = Bases(Base(Map, UpdatedMap)); + RemapMod mod = Installed(FileMod("b-oak", Map, UpdatedMapAdding("Merchant"), 0), bases); + + RemapPlan plan = IdRemapPlanner.Plan([mod], [new IdRemap("b-oak", IdKind.MapEvent, MapKey, 3, 4)], ["b-oak"], bases, null); + + Assert.Empty(plan.Remaps); + Assert.Equal(DiagnosticCodes.RulesRemapTargetTaken, Assert.Single(plan.Diagnostics).Code); + } +} diff --git a/RPGModder.Tests/Merge/MapMergeTests.cs b/RPGModder.Tests/Merge/MapMergeTests.cs new file mode 100644 index 0000000..cc43bb5 --- /dev/null +++ b/RPGModder.Tests/Merge/MapMergeTests.cs @@ -0,0 +1,290 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using static RPGModder.Tests.Merge.MergeTestKit; + +namespace RPGModder.Tests.Merge; + +public sealed class MapMergeTests +{ + private static JObject Event(JObject map, int id) + { + return (JObject)map["events"]![id]!; + } + + private static JObject Page(JObject map, int id) + { + return (JObject)Event(map, id)["pages"]![0]!; + } + + [Fact] + public void Build_MapEdit_GivesMapLevelOpsOnStarAndEventOpsOnTheEvent() + { + ModSource mod = FileMod("a-tin", Map, EditMap(map => + { + map["displayName"] = "Meadow"; + map["data"]![2] = 9; + Event(map, 1)["x"] = 1; + Page(map, 1)["trigger"] = 1; + })); + + ModChangeSet set = Build(mod, Bases(Base(Map, VanillaMap))); + + Assert.Empty(set.Diagnostics); + Assert.Equal( + [ + "data/map001.json|*|data[2]|SetLeaf|9", + "data/map001.json|*|displayName|SetLeaf|\"Meadow\"", + "data/map001.json|event:1|pages[0].trigger|SetLeaf|1", + "data/map001.json|event:1|x|SetLeaf|1" + ], + set.Ops.Select(Describe)); + } + + [Fact] + public void Build_MoveRouteChange_IsOneValue() + { + ModSource mod = FileMod("a-tin", Map, EditMap(map => Page(map, 1)["moveRoute"]!["repeat"] = false)); + + ChangeOp op = Assert.Single(Build(mod, Bases(Base(Map, VanillaMap))).Ops); + + Assert.Equal("pages[0].moveRoute", op.Path); + Assert.Equal(ChangeKind.SetLeaf, op.Kind); + Assert.False(op.Value!["repeat"]!.Value()); + } + + [Fact] + public void Build_CommandListChange_IsOneEditCommands() + { + ModSource mod = FileMod("a-tin", Map, EditMap(map => Page(map, 2)["list"]![0]!["indent"] = 1)); + + ChangeOp op = Assert.Single(Build(mod, Bases(Base(Map, VanillaMap))).Ops); + + Assert.Equal("event:2", op.Key.Record); + Assert.Equal("pages[0].list", op.Path); + Assert.Equal(ChangeKind.EditCommands, op.Kind); + } + + [Fact] + public void Build_PageCountChange_IsOneValueAtPages() + { + ModSource mod = FileMod("a-tin", Map, EditMap(map => ((JArray)Event(map, 1)["pages"]!).Add(Page(map, 1).DeepClone()))); + + ChangeOp op = Assert.Single(Build(mod, Bases(Base(Map, VanillaMap))).Ops); + + Assert.Equal("event:1|pages", op.Key.Record + "|" + op.Path); + Assert.Equal(2, ((JArray)op.Value!).Count); + } + + [Fact] + public void Build_NewAndRemovedEvents_AreRecordOps() + { + ModSource mod = FileMod("a-tin", Map, EditMap(map => + { + map["events"]![1] = JValue.CreateNull(); + ((JArray)map["events"]!).Add(new JObject { ["id"] = 3, ["name"] = "Well" }); + })); + + Assert.Equal( + ["data/map001.json|event:1||RemoveRecord|-", "data/map001.json|event:3||AddRecord|{\"id\":3,\"name\":\"Well\"}"], + Build(mod, Bases(Base(Map, VanillaMap))).Ops.Select(Describe)); + } + + [Fact] + public void Build_EventsThatAreNotRecords_AreOneMapLevelValue() + { + string vanilla = EditMap(map => map["events"] = new JArray(JValue.CreateNull(), new JObject { ["id"] = 5 })); + ModSource mod = FileMod("a-tin", Map, EditMap(map => map["events"] = new JArray(JValue.CreateNull(), new JObject { ["id"] = 6 }))); + + ChangeOp op = Assert.Single(Build(mod, Bases(Base(Map, vanilla))).Ops); + + Assert.Equal("*|events", op.Key.Record + "|" + op.Path); + } + + [Fact] + public void Build_MapWithOnlyNullEvents_StillTakesEventRecords() + { + string vanilla = EditMap(map => map["events"] = new JArray(JValue.CreateNull())); + ModSource mod = FileMod("a-tin", Map, EditMap(map => map["events"] = new JArray(JValue.CreateNull(), new JObject { ["id"] = 1 }))); + + ChangeOp op = Assert.Single(Build(mod, Bases(Base(Map, vanilla))).Ops); + + Assert.Equal("event:1", op.Key.Record); + Assert.Equal(ChangeKind.AddRecord, op.Kind); + } + + [Fact] + public void Build_MapWithAnArrayRoot_IsRootShapeMismatch() + { + ModChangeSet set = Build(FileMod("a-tin", Map, "[]"), Bases(Base(Map, VanillaMap))); + + Assert.Empty(set.Ops); + Assert.Equal(DiagnosticCodes.MergeRootShapeMismatch, Assert.Single(set.Diagnostics).Code); + } + + [Theory] + [InlineData("null")] + [InlineData("{}")] + [InlineData("\"x\"")] + [InlineData("missing")] + public void Compose_ModEventsThatAreNotAList_AreRefusedNotMergedOverAnEventEdit(string events) + { + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + ModSource broken = FileMod("a-tin", Map, EditMap(map => + { + if (events == "missing") + { + map.Remove("events"); + } + else + { + map["events"] = JToken.Parse(events); + } + })); + ModSource editor = FileMod("b-oak", Map, EditMap(map => Event(map, 1)["x"] = 9)); + + MergePlan plan = Compose(bases, broken, editor); + + OperationDiagnostic diagnostic = Assert.Single(plan.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeRootShapeMismatch, diagnostic.Code); + Assert.Equal("a-tin", diagnostic.Subject); + Assert.False(plan.IsDeployable); + Assert.All(plan.Ops, op => Assert.Equal(["b-oak"], op.ModIds)); + } + + [Fact] + public void Build_PatchThatTurnsEventsIntoAnObject_IsRefused() + { + ModChangeSet set = Build(PatchMod("a-tin", Map, "{\"events\":{\"1\":{}}}"), Bases(Base(Map, VanillaMap))); + + Assert.Empty(set.Ops); + Assert.Equal(DiagnosticCodes.MergeRootShapeMismatch, Assert.Single(set.Diagnostics).Code); + } + + [Theory] + [InlineData("data/map001.json", true)] + [InlineData("data/map1.json", true)] + [InlineData("data/mapinfos.json", false)] + [InlineData("data/map.json", false)] + [InlineData("data/map1a.json", false)] + [InlineData("data/sub/map001.json", false)] + public void IsMapFile_TakesOnlyMapAndDigits(string key, bool expected) + { + Assert.Equal(expected, RpgDataSchema.IsMapFile(key)); + } + + [Fact] + public void Compose_PageCountChangedByTwoMods_IsAPageClash() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + ModSource first = FileMod("a-tin", Map, EditMap(map => ((JArray)Event(map, 1)["pages"]!).Add(Page(map, 1).DeepClone()))); + ModSource second = FileMod("b-oak", Map, EditMap(map => Event(map, 1)["pages"] = new JArray())); + + Collision collision = Assert.Single(Compose(bases, first, second).Collisions); + + Assert.Equal(CollisionKind.PageClash, collision.Kind); + Assert.Equal("pages", collision.Path); + Assert.True(collision.Blocking); + Assert.Equal([ResolutionKind.PickMod, ResolutionKind.PickVanilla], collision.Allowed); + } + + [Fact] + public void Compose_PageSettingChangedByTwoMods_IsAPageClash() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + ModSource first = FileMod("a-tin", Map, EditMap(map => Page(map, 1)["trigger"] = 3)); + ModSource second = FileMod("b-oak", Map, EditMap(map => Page(map, 1)["trigger"] = 4)); + + Collision collision = Assert.Single(Compose(bases, first, second).Collisions); + + Assert.Equal(CollisionKind.PageClash, collision.Kind); + Assert.Equal("pages[0].trigger", collision.Path); + } + + [Fact] + public void Compose_PageSettingAndCommandEditOnOnePage_MergeWithoutACollision() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + ModSource first = FileMod("a-tin", Map, EditMap(map => Page(map, 1)["trigger"] = 3)); + ModSource second = FileMod("b-oak", Map, EditMap(map => Page(map, 1)["list"]![0]!["indent"] = 1)); + + MergePlan plan = Compose(bases, first, second); + + Assert.Empty(plan.Collisions); + Assert.Equal(2, plan.Ops.Count); + } + + [Fact] + public void Compose_TwoCommandEditsOnOnePage_AreALogicClash() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + ModSource first = FileMod("a-tin", Map, EditMap(map => Page(map, 1)["list"]![0]!["indent"] = 1)); + ModSource second = FileMod("b-oak", Map, EditMap(map => Page(map, 1)["list"]![0]!["indent"] = 2)); + + Assert.Equal(CollisionKind.LogicClash, Assert.Single(Compose(bases, first, second).Collisions).Kind); + } + + [Fact] + public void Compose_NewEventAtOneIdFromTwoMods_IsAnIdClash() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + ModSource first = FileMod("a-tin", Map, EditMap(map => ((JArray)map["events"]!).Add(new JObject { ["id"] = 3, ["name"] = "Well" }))); + ModSource second = FileMod("b-oak", Map, EditMap(map => ((JArray)map["events"]!).Add(new JObject { ["id"] = 3, ["name"] = "Tree" }))); + + Collision collision = Assert.Single(Compose(bases, first, second).Collisions); + + Assert.Equal(CollisionKind.IdClash, collision.Kind); + Assert.Equal("event:3", collision.Key.Record); + } + + [Fact] + public void Write_EventEditsFromTwoMods_LandInTheirEvents() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + ModSource first = FileMod("a-tin", Map, EditMap(map => Event(map, 1)["x"] = 1)); + ModSource second = FileMod("b-oak", Map, EditMap(map => Event(map, 2)["name"] = "Crate")); + MergePlan plan = Compose(bases, first, second); + + MergedFile file = Assert.Single(MergedFileWriter.Write(plan, bases, null)); + + JObject expected = JObject.Parse(EditMap(map => + { + Event(map, 1)["x"] = 1; + Event(map, 2)["name"] = "Crate"; + })); + Assert.Equal(MergeJson.Write(expected), file.Text); + Assert.Equal(["a-tin", "b-oak"], file.ModIds); + } + + [Fact] + public void Write_RemovedLastEvent_IsCutAndAnEarlierOneBecomesNull() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + ModSource last = FileMod("a-tin", Map, EditMap(map => ((JArray)map["events"]!).RemoveAt(2))); + ModSource middle = FileMod("a-tin", Map, EditMap(map => map["events"]![1] = JValue.CreateNull())); + + JArray cut = (JArray)JObject.Parse(Assert.Single(MergedFileWriter.Write(Compose(bases, last), bases, null)).Text!)["events"]!; + JArray hole = (JArray)JObject.Parse(Assert.Single(MergedFileWriter.Write(Compose(bases, middle), bases, null)).Text!)["events"]!; + + Assert.Equal(2, cut.Count); + Assert.Equal(3, hole.Count); + Assert.Equal(JTokenType.Null, hole[1].Type); + } + + [Fact] + public void Write_NewEventPastTheEnd_PadsWithNull() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + ModSource mod = FileMod("a-tin", Map, EditMap(map => + { + ((JArray)map["events"]!).Add(JValue.CreateNull()); + ((JArray)map["events"]!).Add(new JObject { ["id"] = 4 }); + })); + + JArray events = (JArray)JObject.Parse(Assert.Single(MergedFileWriter.Write(Compose(bases, mod), bases, null)).Text!)["events"]!; + + Assert.Equal(5, events.Count); + Assert.Equal(JTokenType.Null, events[3].Type); + } +} diff --git a/RPGModder.Tests/Merge/MergeSurfaceTests.cs b/RPGModder.Tests/Merge/MergeSurfaceTests.cs new file mode 100644 index 0000000..632f2cc --- /dev/null +++ b/RPGModder.Tests/Merge/MergeSurfaceTests.cs @@ -0,0 +1,163 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using static RPGModder.Tests.Merge.MergeTestKit; + +namespace RPGModder.Tests.Merge; + +public sealed class MergeSurfaceTests +{ + [Theory] + [InlineData("data\\Items.json", "data/items.json")] + [InlineData("./data/Items.json", "data/items.json")] + [InlineData("/js/plugins.js", "js/plugins.js")] + [InlineData("img/Faces/Hero.png", "img/faces/hero.png")] + public void ToKey_NormalizesSlashesPrefixAndCase(string path, string key) + { + Assert.Equal(key, MergePath.ToKey(path)); + } + + [Theory] + [InlineData("data/Items.json", MergeFileKind.Data)] + [InlineData("data\\Map001.json", MergeFileKind.Data)] + [InlineData("data/sub/Extra.json", MergeFileKind.Opaque)] + [InlineData("js/plugins.js", MergeFileKind.PluginList)] + [InlineData("js/plugins/Tool.js", MergeFileKind.Opaque)] + [InlineData("save/config.rpgsave", MergeFileKind.ConfigSave)] + [InlineData("save/config.rmmzsave", MergeFileKind.ConfigSave)] + [InlineData("save/file1.rpgsave", MergeFileKind.Opaque)] + [InlineData("img/pictures/Logo.png", MergeFileKind.Opaque)] + public void KindOf_FollowsTheFileTable(string path, MergeFileKind kind) + { + Assert.Equal(kind, RpgDataSchema.KindOf(path)); + } + + [Fact] + public void BaseFileSet_FindsByKey_AndRejectsTwoEntriesForOneKey() + { + BaseFile items = Base("data/Items.json", VanillaItems); + BaseFileSet set = Bases(items); + + Assert.Same(items, set.Find("DATA\\items.json")); + Assert.Null(set.Find("data/Skills.json")); + Assert.Throws(() => BaseFileSet.From([items, Base("data/items.json", "[]")])); + } + + [Fact] + public void Serializer_RoundTripsOpsAndDiagnostics_WithTheNewPriority() + { + var set = new ModChangeSet( + "a-tin", + 4, + [ + new ChangeOp("a-tin", new RecordKey("data/items.json", "id:1"), "note", ChangeKind.SetLeaf, JValue.CreateNull(), "Items.json"), + new ChangeOp("a-tin", new RecordKey("data/items.json", "id:2"), "", ChangeKind.RemoveRecord, null, null), + new ChangeOp("a-tin", new RecordKey("data/system.json", "*"), "['a.b'][2]", ChangeKind.SetLeaf, new JArray(1, 2), null) + ], + [new OperationDiagnostic(DiagnosticCodes.MergeParseFailed, "Broken.", DiagnosticSeverity.Error, "a-tin")]); + + string text = ModChangeSetSerializer.Serialize(set); + ModChangeSet? read = ModChangeSetSerializer.Deserialize(text, 9); + + Assert.NotNull(read); + Assert.Equal(["schema", "mod", "ops", "diagnostics"], JObject.Parse(text).Properties().Select(property => property.Name)); + Assert.Equal(9, read.Priority); + Assert.Equal("a-tin", read.ModId); + Assert.Equal(set.Ops.Select(Describe), read.Ops.Select(Describe)); + Assert.Equal(set.Ops.Select(op => op.SourceFile), read.Ops.Select(op => op.SourceFile)); + Assert.Equal(JTokenType.Null, read.Ops[0].Value!.Type); + Assert.Null(read.Ops[1].Value); + Assert.Equal(set.Diagnostics, read.Diagnostics); + Assert.Equal(text, ModChangeSetSerializer.Serialize(read)); + } + + [Fact] + public void Serializer_RoundTripsTheFileFamilyShapes() + { + var set = new ModChangeSet( + "a-tin", + 0, + [ + new ChangeOp("a-tin", new RecordKey("data/map001.json", "event:3"), "pages[0].list", ChangeKind.EditCommands, new JArray(), "Map001.json"), + new ChangeOp("a-tin", new RecordKey("js/plugins.js", "plugin:Font Tool"), "", ChangeKind.AddRecord, new JObject { ["name"] = "Font Tool" }, null), + new ChangeOp("a-tin", new RecordKey("js/plugins.js", "plugin:Font Tool"), "@after", ChangeKind.SetLeaf, JValue.CreateNull(), null), + new ChangeOp("a-tin", new RecordKey("js/plugins.js", "plugin:Omega"), "@after", ChangeKind.SetLeaf, new JValue("Alpha"), null), + new ChangeOp("a-tin", new RecordKey("img/a.png", "*"), "", ChangeKind.ReplaceFile, new JValue("ab"), "a.png"), + new ChangeOp("a-tin", new RecordKey("data/extra.json", "*"), "", ChangeKind.AddRecord, new JArray(), "Extra.json") + ], + []); + + string text = ModChangeSetSerializer.Serialize(set); + ModChangeSet? read = ModChangeSetSerializer.Deserialize(text, 0); + + Assert.NotNull(read); + Assert.Equal(set.Ops.Select(Describe), read.Ops.Select(Describe)); + Assert.Equal(set.Ops.Select(op => op.SourceFile), read.Ops.Select(op => op.SourceFile)); + Assert.Equal(text, ModChangeSetSerializer.Serialize(read)); + } + + [Theory] + [InlineData("")] + [InlineData("not json")] + [InlineData("[]")] + [InlineData("{\"schema\":2,\"mod\":\"a\",\"ops\":[],\"diagnostics\":[]}")] + [InlineData("{\"schema\":1,\"mod\":\"a\",\"ops\":[{\"file\":\"f\",\"record\":\"*\",\"path\":\"x\",\"kind\":\"Explode\"}],\"diagnostics\":[]}")] + [InlineData("{\"schema\":1,\"mod\":\"a\",\"ops\":[{\"file\":\"f\",\"record\":\"*\",\"path\":\"x[\",\"kind\":\"SetLeaf\"}],\"diagnostics\":[]}")] + [InlineData("{\"schema\":1,\"mod\":\"a\",\"ops\":[],\"diagnostics\":[{\"code\":\"c\",\"message\":\"m\",\"severity\":\"7\"}]}")] + public void Deserialize_ReturnsNullForTextItCannotTrust(string text) + { + Assert.Null(ModChangeSetSerializer.Deserialize(text, 0)); + } + + [Theory] + [InlineData("{\"file\":\"data/system.json\",\"record\":\"*\",\"path\":\"x\",\"kind\":\"SetLeaf,RemoveLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"data/system.json\",\"record\":\"*\",\"path\":\"x\",\"kind\":\" SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"data/system.json\",\"record\":\"*\",\"path\":\"x\",\"kind\":\"SetLeaf\"}")] + [InlineData("{\"file\":\"data/system.json\",\"record\":\"*\",\"path\":\"\",\"kind\":\"RemoveLeaf\"}")] + [InlineData("{\"file\":\"data/system.json\",\"record\":\"*\",\"path\":\"x\",\"kind\":\"RemoveLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"data/items.json\",\"record\":\"banana\",\"path\":\"x\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"data/items.json\",\"record\":\"id:01\",\"path\":\"x\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"data/items.json\",\"record\":\"*\",\"path\":\"\",\"kind\":\"RemoveRecord\"}")] + [InlineData("{\"file\":\"data/items.json\",\"record\":\"id:3\",\"path\":\"x\",\"kind\":\"AddRecord\",\"value\":{}}")] + [InlineData("{\"file\":\"data/items.json\",\"record\":\"id:3\",\"path\":\"effects\",\"kind\":\"EditSequence\",\"value\":1}")] + [InlineData("{\"file\":\"data/system.json\",\"record\":\"*\",\"path\":\"a[01]\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"data/system.json\",\"record\":\"*\",\"path\":\"['a']\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"data/System.json\",\"record\":\"*\",\"path\":\"x\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"data/items.json\",\"record\":\"id:1\",\"path\":\"x\",\"kind\":\"ReplaceFile\",\"value\":1}")] + [InlineData("{\"file\":\"img/a.png\",\"record\":\"*\",\"path\":\"\",\"kind\":\"ReplaceFile\",\"value\":\"ab\"}")] + [InlineData("{\"file\":\"img/a.png\",\"record\":\"*\",\"path\":\"\",\"kind\":\"ReplaceFile\",\"value\":1,\"source\":\"a.png\"}")] + [InlineData("{\"file\":\"img/a.png\",\"record\":\"id:1\",\"path\":\"\",\"kind\":\"ReplaceFile\",\"value\":\"ab\",\"source\":\"a.png\"}")] + [InlineData("{\"file\":\"js/plugins.js\",\"record\":\"plugin:\",\"path\":\"status\",\"kind\":\"SetLeaf\",\"value\":true}")] + [InlineData("{\"file\":\"js/plugins.js\",\"record\":\"id:1\",\"path\":\"@after\",\"kind\":\"SetLeaf\",\"value\":\"A\"}")] + [InlineData("{\"file\":\"js/plugins.js\",\"record\":\"plugin:B\",\"path\":\"@after\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"js/plugins.js\",\"record\":\"plugin:B\",\"path\":\"@after\",\"kind\":\"RemoveLeaf\"}")] + [InlineData("{\"file\":\"js/plugins.js\",\"record\":\"plugin:B\",\"path\":\"@before\",\"kind\":\"SetLeaf\",\"value\":\"A\"}")] + [InlineData("{\"file\":\"data/map001.json\",\"record\":\"event:01\",\"path\":\"x\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"data/items.json\",\"record\":\"*\",\"path\":\"\",\"kind\":\"ReplaceFile\",\"value\":\"abc\",\"source\":\"Items.json\"}")] + [InlineData("{\"file\":\"data/items.json\",\"record\":\"event:1\",\"path\":\"x\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"data/items.json\",\"record\":\"plugin:A\",\"path\":\"x\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"data/items.json\",\"record\":\"plugin:A\",\"path\":\"@after\",\"kind\":\"SetLeaf\",\"value\":null}")] + [InlineData("{\"file\":\"data/map001.json\",\"record\":\"id:1\",\"path\":\"x\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"img/a.png\",\"record\":\"*\",\"path\":\"\",\"kind\":\"AddRecord\",\"value\":{}}")] + [InlineData("{\"file\":\"img/a.png\",\"record\":\"*\",\"path\":\"x\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"js/plugins.js\",\"record\":\"id:1\",\"path\":\"x\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"js/plugins.js\",\"record\":\"plugin:A\",\"path\":\"list\",\"kind\":\"EditCommands\",\"value\":[]}")] + [InlineData("{\"file\":\"js/plugins.js\",\"record\":\"*\",\"path\":\"x\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"js/plugins.js\",\"record\":\"*\",\"path\":\"\",\"kind\":\"SetLeaf\",\"value\":{}}")] + [InlineData("{\"file\":\"save/config.rpgsave\",\"record\":\"*\",\"path\":\"x\",\"kind\":\"RemoveLeaf\"}")] + [InlineData("{\"file\":\"save/config.rpgsave\",\"record\":\"*\",\"path\":\"a.b\",\"kind\":\"SetLeaf\",\"value\":1}")] + [InlineData("{\"file\":\"save/config.rpgsave\",\"record\":\"*\",\"path\":\"\",\"kind\":\"SetLeaf\",\"value\":{}}")] + public void Deserialize_ReturnsNullForAnOpTheBuilderCannotWrite(string op) + { + string text = "{\"schema\":1,\"mod\":\"a\",\"ops\":[" + op + "],\"diagnostics\":[]}"; + + Assert.Null(ModChangeSetSerializer.Deserialize(text, 0)); + } + + [Fact] + public void Deserialize_ReturnsNullForASchemaTooLargeForALong() + { + Assert.Null(ModChangeSetSerializer.Deserialize("{\"schema\":99999999999999999999,\"mod\":\"a\",\"ops\":[],\"diagnostics\":[]}", 0)); + } +} diff --git a/RPGModder.Tests/Merge/MergeTestKit.cs b/RPGModder.Tests/Merge/MergeTestKit.cs new file mode 100644 index 0000000..8d7047b --- /dev/null +++ b/RPGModder.Tests/Merge/MergeTestKit.cs @@ -0,0 +1,156 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using System.Security.Cryptography; +using System.Text; + +namespace RPGModder.Tests.Merge; + +/// Small builders for the merge unit tests. Content is invented (TST-2). +internal static class MergeTestKit +{ + public const string Items = "data/Items.json"; + public const string Classes = "data/Classes.json"; + public const string SystemFile = "data/System.json"; + + /// A data file the schema table does not name; its records are found from vanilla's own shape. + public const string Quests = "data/Quests.json"; + + public const string VanillaItems = + "[\nnull,\n" + + "{\"id\":1,\"name\":\"Tonic\",\"price\":50,\"note\":\"\",\"effects\":[{\"code\":11,\"dataId\":0,\"value1\":0,\"value2\":100}]},\n" + + "{\"id\":2,\"name\":\"Ether\",\"price\":200,\"note\":\"\",\"effects\":[]}\n" + + "]"; + + public const string VanillaSystem = + "{\"gameTitle\":\"Sample\",\"versionId\":11,\"editMapId\":1,\"screenWidth\":816,\"currencyUnit\":\"G\"," + + "\"switches\":[\"\",\"Door\",\"Lever\"],\"terms\":{\"basic\":[\"Level\",\"Lv\"],\"messages\":{\"victory\":\"%1 won!\"}}," + + "\"partyMembers\":[1]}"; + + public const string VanillaQuests = + "[null,{\"id\":1,\"name\":\"Find\",\"reward\":5},{\"id\":2,\"name\":\"Bring\",\"reward\":9}]"; + + public const string Map = "data/Map001.json"; + public const string PluginList = "js/plugins.js"; + + /// A 2 by 2 map with two events; each has one page with a command list and a move route. + public const string VanillaMap = + "{\"displayName\":\"Field\",\"width\":2,\"height\":2,\"bgm\":{\"name\":\"Theme\",\"volume\":90},\"data\":[1,2,3,4]," + + "\"encounterList\":[],\"events\":[null," + + "{\"id\":1,\"name\":\"Door\",\"note\":\"\",\"x\":0,\"y\":0,\"pages\":[{\"conditions\":{\"switch1Id\":1,\"switch1Valid\":false}," + + "\"trigger\":0,\"moveRoute\":{\"list\":[{\"code\":0}],\"repeat\":true}," + + "\"list\":[{\"code\":101,\"indent\":0,\"parameters\":[\"\",0,0,2]},{\"code\":0,\"indent\":0,\"parameters\":[]}]}]}," + + "{\"id\":2,\"name\":\"Chest\",\"note\":\"\",\"x\":1,\"y\":1,\"pages\":[{\"conditions\":{\"switch1Id\":1,\"switch1Valid\":false}," + + "\"trigger\":0,\"moveRoute\":{\"list\":[{\"code\":0}],\"repeat\":true},\"list\":[{\"code\":0,\"indent\":0,\"parameters\":[]}]}]}" + + "]}"; + + public static readonly string VanillaPlugins = PluginsJs( + Plugin("Alpha", "{\"speed\":\"1\",\"Font Size\":\"20\"}"), + Plugin("Omega")); + + public static string EditMap(Action edit) + { + var map = JObject.Parse(VanillaMap); + edit(map); + return map.ToString(); + } + + /// A plugins.js in the editor's own layout, with LF line ends. + public static string PluginsJs(params string[] entries) + { + string list = entries.Length == 0 ? "[]" : "[\n" + string.Join(",\n", entries) + "\n]"; + return PluginListText.DefaultPrefix + list + ";\n"; + } + + public static string Plugin(string name, string parameters = "{}") + { + return "{\"name\":\"" + name + "\",\"status\":true,\"description\":\"\",\"parameters\":" + parameters + "}"; + } + + public static PluginEntry Entry(string name, params (string Key, string Value)[] parameters) + { + return new PluginEntry + { + Name = name, + Parameters = parameters.ToDictionary(pair => pair.Key, pair => pair.Value) + }; + } + + public static ModSource RegistryMod(string modId, int priority, params PluginEntry[] plugins) + { + return new ModSource(modId, priority, [], [], plugins); + } + + public static BaseFile Base(string path, string text) + { + return new BaseFile(path, text, Hash(text)); + } + + public static BaseFileSet Bases(params BaseFile[] files) + { + return BaseFileSet.From(files); + } + + public static ModSource FileMod(string modId, string target, string text, int priority = 0) + { + return new ModSource( + modId, + priority, + [new ModFile(target, "files/" + Path.GetFileName(target), text, Hash(text))], + [], + []); + } + + public static ModSource PatchMod(string modId, string target, string mergeData, int priority = 0) + { + return new ModSource(modId, priority, [], [new ModPatch(target, JObject.Parse(mergeData))], []); + } + + /// Vanilla items with one item edited through . + public static string EditItems(Action edit) + { + var items = JArray.Parse(VanillaItems); + edit(items); + return items.ToString(); + } + + public static string EditArray(string json, Action edit) + { + var array = JArray.Parse(json); + edit(array); + return array.ToString(); + } + + public static string EditSystem(Action edit) + { + var system = JObject.Parse(VanillaSystem); + edit(system); + return system.ToString(); + } + + public static ModChangeSet Build(ModSource mod, BaseFileSet bases) + { + return ChangeSetBuilder.Build(mod, bases); + } + + public static MergePlan Compose(BaseFileSet bases, IReadOnlyList resolutions, params ModSource[] mods) + { + return Composer.Compose(mods.Select(mod => ChangeSetBuilder.Build(mod, bases)).ToList(), resolutions, bases); + } + + public static MergePlan Compose(BaseFileSet bases, params ModSource[] mods) + { + return Compose(bases, [], mods); + } + + public static string Describe(ChangeOp op) + { + string value = op.Value is null ? "-" : op.Value.ToString(Newtonsoft.Json.Formatting.None); + return $"{op.Key.File}|{op.Key.Record}|{op.Path}|{op.Kind}|{value}"; + } + + public static string Hash(string text) + { + return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text))); + } +} diff --git a/RPGModder.Tests/Merge/MergedFileWriterTests.cs b/RPGModder.Tests/Merge/MergedFileWriterTests.cs new file mode 100644 index 0000000..32f670e --- /dev/null +++ b/RPGModder.Tests/Merge/MergedFileWriterTests.cs @@ -0,0 +1,244 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using static RPGModder.Tests.Merge.MergeTestKit; + +namespace RPGModder.Tests.Merge; + +public sealed class MergedFileWriterTests +{ + private static IReadOnlyList Write(BaseFileSet bases, int? versionId, params ModSource[] mods) + { + MergePlan plan = Compose(bases, mods); + Assert.True(plan.IsDeployable); + return MergedFileWriter.Write(plan, bases, versionId); + } + + [Fact] + public void TouchedFile_IsCompactWithVanillaOrder_AndNewPropertiesLast() + { + BaseFileSet bases = Bases(Base(Items, VanillaItems), Base(SystemFile, VanillaSystem)); + ModSource mod = FileMod("a-tin", Items, EditItems(items => + { + items[1]!["price"] = 60; + items[1]!["iconIndex"] = 176; + })); + + MergedFile file = Assert.Single(Write(bases, null, mod)); + + Assert.Equal("data/items.json", file.File); + Assert.Equal(MergedFileSource.Text, file.Source); + Assert.Equal(["a-tin"], file.ModIds); + Assert.Null(file.DiskPath); + Assert.Equal( + "[null,{\"id\":1,\"name\":\"Tonic\",\"price\":60,\"note\":\"\",\"effects\":[{\"code\":11,\"dataId\":0,\"value1\":0,\"value2\":100}],\"iconIndex\":176}," + + "{\"id\":2,\"name\":\"Ether\",\"price\":200,\"note\":\"\",\"effects\":[]}]", + file.Text); + } + + [Fact] + public void RemovedRecords_BecomeNull_AndATrailingRunIsCut() + { + const string vanilla = "[null,{\"id\":1},{\"id\":2},{\"id\":3}]"; + BaseFileSet bases = Bases(Base("data/Weapons.json", vanilla)); + + MergedFile middle = Assert.Single(Write(bases, null, FileMod("a-tin", "data/Weapons.json", "[null,{\"id\":1},null,{\"id\":3}]"))); + MergedFile tail = Assert.Single(Write(bases, null, FileMod("a-tin", "data/Weapons.json", "[null,{\"id\":1}]"))); + + Assert.Equal("[null,{\"id\":1},null,{\"id\":3}]", middle.Text); + Assert.Equal("[null,{\"id\":1}]", tail.Text); + } + + [Fact] + public void NewRecordsFromTwoMods_AreBothWritten_EvenPastAGap() + { + BaseFileSet bases = Bases(Base(Items, VanillaItems)); + ModSource first = FileMod("a-tin", Items, EditItems(items => items.Add(new JObject { ["id"] = 3 }))); + ModSource second = FileMod("b-oak", Items, EditItems(items => + { + items.Add(JValue.CreateNull()); + items.Add(new JObject { ["id"] = 4 }); + })); + + MergedFile file = Assert.Single(Write(bases, null, first, second)); + + Assert.EndsWith("{\"id\":3},{\"id\":4}]", file.Text); + Assert.Equal(["a-tin", "b-oak"], file.ModIds); + } + + [Fact] + public void KeyedNames_GrowAndShrinkFromTheEnd() + { + BaseFileSet bases = Bases(Base(SystemFile, VanillaSystem)); + ModSource grow = FileMod("a-tin", SystemFile, EditSystem(system => + { + ((JArray)system["switches"]!).Add("Bridge"); + ((JArray)system["switches"]!).Add("Tower"); + })); + ModSource shrink = FileMod("a-tin", SystemFile, EditSystem(system => system["switches"] = new JArray(""))); + + JObject grown = JObject.Parse(Assert.Single(Write(bases, null, grow)).Text!); + JObject shrunk = JObject.Parse(Assert.Single(Write(bases, null, shrink)).Text!); + + Assert.Equal(new JArray("", "Door", "Lever", "Bridge", "Tower"), grown["switches"]); + Assert.Equal(new JArray(""), shrunk["switches"]); + } + + [Fact] + public void WholeFileValue_ReplacesTheRoot() + { + MergedFile file = Assert.Single(Write(Bases(Base(Quests, VanillaQuests)), null, FileMod("a-tin", Quests, "{ \"x\" : 1 }"))); + + Assert.Equal("{\"x\":1}", file.Text); + } + + [Fact] + public void RemovedLeaf_IsGone() + { + MergedFile file = Assert.Single(Write( + Bases(Base(Items, VanillaItems)), + null, + FileMod("a-tin", Items, EditItems(items => ((JObject)items[2]!).Remove("note"))))); + + Assert.Contains("{\"id\":2,\"name\":\"Ether\",\"price\":200,\"effects\":[]}", file.Text); + } + + [Fact] + public void VersionId_ListsSystemEvenWhenNoModTouchedIt() + { + BaseFileSet bases = Bases(Base(Items, VanillaItems), Base(SystemFile, VanillaSystem)); + + IReadOnlyList files = Write(bases, 123456, FileMod("a-tin", Items, EditItems(items => items[1]!["price"] = 1))); + + Assert.Equal(["data/items.json", "data/system.json"], files.Select(file => file.File)); + MergedFile system = files[1]; + Assert.Empty(system.ModIds); + Assert.Equal(VanillaSystem.Replace("\"versionId\":11", "\"versionId\":123456"), system.Text); + } + + [Fact] + public void WithoutVersionId_SystemKeepsVanillasVersionId() + { + BaseFileSet bases = Bases(Base(SystemFile, VanillaSystem)); + + MergedFile system = Assert.Single(Write(bases, null, FileMod("a-tin", SystemFile, EditSystem(item => item["currencyUnit"] = "C")))); + + Assert.Contains("\"versionId\":11", system.Text); + Assert.Empty(Write(Bases(Base(Items, VanillaItems), Base(SystemFile, VanillaSystem)), null)); + } + + [Fact] + public void VersionIdWithoutSystemBase_IsACallerBug() + { + BaseFileSet bases = Bases(Base(Items, VanillaItems)); + MergePlan plan = Compose(bases, FileMod("a-tin", Items, EditItems(items => items[1]!["price"] = 1))); + + Assert.Throws(() => MergedFileWriter.Write(plan, bases, 5)); + } + + [Fact] + public void FileWhoseOpsWereAllDropped_IsNotListed() + { + BaseFileSet bases = Bases(Base(Items, VanillaItems)); + ModSource first = FileMod("a-tin", Items, EditItems(items => items[2]!["price"] = 1)); + ModSource second = FileMod("b-oak", Items, EditItems(items => items[2]!["price"] = 2)); + Collision collision = Assert.Single(Compose(bases, first, second).Collisions); + + MergePlan plan = Compose(bases, [new Resolution(collision.Id, ResolutionKind.PickVanilla, null)], first, second); + + Assert.Empty(MergedFileWriter.Write(plan, bases, null)); + } + + [Fact] + public void PlanThatIsNotDeployable_Throws() + { + BaseFileSet bases = Bases(Base(Items, VanillaItems)); + MergePlan plan = Compose( + bases, + FileMod("a-tin", Items, EditItems(items => items[2]!["price"] = 1)), + FileMod("b-oak", Items, EditItems(items => items[2]!["price"] = 2))); + + Assert.Throws(() => MergedFileWriter.Write(plan, bases, null)); + } + + [Fact] + public void EqualPlans_GiveEqualBytes() + { + BaseFileSet bases = Bases(Base(Items, VanillaItems)); + ModSource mod = FileMod("a-tin", Items, EditItems(items => items[1]!["note"] = "héllo \"quoted\"")); + + string first = Assert.Single(Write(bases, null, mod)).Text!; + string second = Assert.Single(Write(bases, null, mod)).Text!; + + Assert.Equal(first, second); + Assert.Contains("\"note\":\"héllo \\\"quoted\\\"\"", first); + } + + [Fact] + public void KeyedList_ShrinkingPastTen_CutsInNumberOrder() + { + var names = new JArray(Enumerable.Range(0, 12).Select(index => (object)("S" + index)).ToArray()); + string vanilla = EditSystem(system => system["switches"] = names); + BaseFileSet bases = Bases(Base(SystemFile, vanilla)); + ModSource shrink = FileMod("a-tin", SystemFile, EditSystem(system => system["switches"] = new JArray(names.Take(8)))); + + JObject written = JObject.Parse(Assert.Single(Write(bases, null, shrink)).Text!); + + Assert.Equal(new JArray(names.Take(8)), written["switches"]); + } + + [Fact] + public void KeyedList_TailCutByOneModAndGrownByAnother_LeavesAHole() + { + BaseFileSet bases = Bases(Base(SystemFile, VanillaSystem)); + ModSource cut = FileMod("a-tin", SystemFile, EditSystem(system => system["switches"] = new JArray("", "Door"))); + ModSource grow = FileMod("b-oak", SystemFile, EditSystem(system => ((JArray)system["switches"]!).Add("Bridge"))); + + JObject written = JObject.Parse(Assert.Single(Write(bases, null, cut, grow)).Text!); + + Assert.Equal(new JArray("", "Door", JValue.CreateNull(), "Bridge"), written["switches"]); + } + + [Fact] + public void VersionId_WithAModChangeToSystem_CarriesBoth() + { + BaseFileSet bases = Bases(Base(SystemFile, VanillaSystem)); + + MergedFile system = Assert.Single(Write(bases, 77, FileMod("a-tin", SystemFile, EditSystem(item => item["currencyUnit"] = "C")))); + + Assert.Equal(VanillaSystem.Replace("\"versionId\":11", "\"versionId\":77").Replace("\"currencyUnit\":\"G\"", "\"currencyUnit\":\"C\""), system.Text); + Assert.Equal(["a-tin"], system.ModIds); + } + + [Fact] + public void RemovedRecordBeforeAnAddedOne_StaysAsNull() + { + BaseFileSet bases = Bases(Base(Items, VanillaItems)); + ModSource removal = FileMod("a-tin", Items, EditItems(items => items[2] = JValue.CreateNull())); + ModSource addition = FileMod("b-oak", Items, EditItems(items => items.Add(new JObject { ["id"] = 3 }))); + + JArray written = JArray.Parse(Assert.Single(Write(bases, null, removal, addition)).Text!); + + Assert.Equal(4, written.Count); + Assert.Equal(JTokenType.Null, written[2].Type); + Assert.Equal(new JObject { ["id"] = 3 }, written[3]); + } + + [Fact] + public void DeleteVersusEdit_KeptRecord_IsWrittenWithEveryEdit() + { + BaseFileSet bases = Bases(Base(Items, VanillaItems)); + ModSource[] mods = + [ + FileMod("a-tin", Items, EditItems(items => items[2] = JValue.CreateNull())), + FileMod("b-oak", Items, EditItems(items => items[2]!["price"] = 9)), + FileMod("c-elm", Items, EditItems(items => items[2]!["name"] = "Mist")) + ]; + Collision collision = Assert.Single(Compose(bases, mods).Collisions); + MergePlan plan = Compose(bases, [new Resolution(collision.Id, ResolutionKind.PickMod, "c-elm")], mods); + + MergedFile file = Assert.Single(MergedFileWriter.Write(plan, bases, null)); + + Assert.Contains("{\"id\":2,\"name\":\"Mist\",\"price\":9,\"note\":\"\",\"effects\":[]}", file.Text); + Assert.Equal(["b-oak", "c-elm"], file.ModIds); + } +} diff --git a/RPGModder.Tests/Merge/PluginListMergeTests.cs b/RPGModder.Tests/Merge/PluginListMergeTests.cs new file mode 100644 index 0000000..05e6368 --- /dev/null +++ b/RPGModder.Tests/Merge/PluginListMergeTests.cs @@ -0,0 +1,469 @@ +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using static RPGModder.Tests.Merge.MergeTestKit; + +namespace RPGModder.Tests.Merge; + +public sealed class PluginListMergeTests +{ + private const string AlphaParameters = "{\"speed\":\"1\",\"Font Size\":\"20\"}"; + + private static readonly string Alpha = Plugin("Alpha", AlphaParameters); + private static readonly string Omega = Plugin("Omega"); + + private static string WriteText(BaseFileSet bases, MergePlan plan) + { + MergedFile file = Assert.Single(MergedFileWriter.Write(plan, bases, null)); + Assert.Equal(MergedFileSource.Text, file.Source); + return file.Text!; + } + + [Fact] + public void Build_ParameterEdits_AreLeavesOnThePluginRecord() + { + ModSource mod = FileMod("a-tin", PluginList, PluginsJs(Plugin("Alpha", "{\"speed\":\"2\",\"Font Size\":\"24\"}"), Omega)); + + ModChangeSet set = Build(mod, Bases(Base(PluginList, VanillaPlugins))); + + Assert.Empty(set.Diagnostics); + Assert.Equal( + [ + "js/plugins.js|plugin:Alpha|parameters.speed|SetLeaf|\"2\"", + "js/plugins.js|plugin:Alpha|parameters['Font Size']|SetLeaf|\"24\"" + ], + set.Ops.Select(Describe).Order(StringComparer.Ordinal)); + Assert.All(set.Ops, op => Assert.Equal("files/plugins.js", op.SourceFile)); + } + + [Fact] + public void Build_RegistryAdd_IsARecordAndAnAnchorWithNoSourceFile() + { + ModChangeSet set = Build(RegistryMod("a-tin", 0, Entry("Gamma", ("x", "1"))), Bases(Base(PluginList, VanillaPlugins))); + + Assert.Equal( + [ + "js/plugins.js|plugin:Gamma||AddRecord|{\"name\":\"Gamma\",\"status\":true,\"description\":\"\",\"parameters\":{\"x\":\"1\"}}", + "js/plugins.js|plugin:Gamma|@after|SetLeaf|\"Omega\"" + ], + set.Ops.Select(Describe)); + Assert.All(set.Ops, op => Assert.Null(op.SourceFile)); + } + + [Fact] + public void Write_RegistryAdd_AppendsInTheEditorLayout() + { + BaseFileSet bases = Bases(Base(PluginList, VanillaPlugins)); + + string text = WriteText(bases, Compose(bases, RegistryMod("a-tin", 0, Entry("Gamma", ("x", "1"))))); + + Assert.Equal(PluginsJs(Alpha, Omega, Plugin("Gamma", "{\"x\":\"1\"}")), text); + } + + [Fact] + public void Build_RegistryEntryForAListedName_ReplacesItWhereItIs() + { + ModChangeSet set = Build(RegistryMod("a-tin", 0, Entry("Alpha", ("speed", "3"))), Bases(Base(PluginList, VanillaPlugins))); + + Assert.Equal( + [ + "js/plugins.js|plugin:Alpha|parameters.speed|SetLeaf|\"3\"", + "js/plugins.js|plugin:Alpha|parameters['Font Size']|RemoveLeaf|-" + ], + set.Ops.Select(Describe).Order(StringComparer.Ordinal)); + } + + [Fact] + public void Build_Swap_MovesTheEntryVanillaHadFirst() + { + ModChangeSet set = Build(FileMod("a-tin", PluginList, PluginsJs(Omega, Alpha)), Bases(Base(PluginList, VanillaPlugins))); + + Assert.Equal(["js/plugins.js|plugin:Alpha|@after|SetLeaf|\"Omega\""], set.Ops.Select(Describe)); + } + + [Theory] + [InlineData("V0,V4,V5,V1,V2,V3")] + [InlineData("V2,V3,V4,V0,V1,V5")] + [InlineData("V5,V4,V3,V2,V1,V0")] + public void Write_BlockMoveInOneMod_KeepsTheModsOrder(string order) + { + BaseFileSet bases = Bases(Base(PluginList, PluginsJs(Names("V0,V1,V2,V3,V4,V5")))); + ModSource mod = FileMod("a-tin", PluginList, PluginsJs(Names(order))); + + Assert.Equal(PluginsJs(Names(order)), WriteText(bases, Compose(bases, mod))); + } + + [Fact] + public void Write_EveryOrderOfOneMod_IsWrittenAsTheModListsIt() + { + string[] vanilla = ["A", "B", "C", "D", "E"]; + BaseFileSet bases = Bases(Base(PluginList, PluginsJs(vanilla.Select(name => Plugin(name)).ToArray()))); + + // E is removed and N is new; a new entry first in a mod's list goes to the end (GR-C10), so N never leads. + foreach (List order in Permutations(["A", "B", "C", "D", "N"]).Where(order => order[0] != "N")) + { + string text = PluginsJs(order.Select(name => Plugin(name)).ToArray()); + + Assert.Equal(text, WriteText(bases, Compose(bases, FileMod("a-tin", PluginList, text)))); + } + } + + [Fact] + public void Compose_OneModsRunOfNewEntries_IsNotSplitByAnotherMod() + { + BaseFileSet bases = Bases(Base(PluginList, VanillaPlugins)); + ModSource zinc = RegistryMod("a-zinc", 0, Entry("Zinc_Core"), Entry("Zinc_Battle")); + ModSource fig = RegistryMod("b-fig", 1, Entry("Fig")); + + MergePlan plan = Compose(bases, zinc, fig); + + Assert.Equal(CollisionKind.OrderAmbiguous, Assert.Single(plan.Collisions).Kind); + Assert.Equal( + PluginsJs(Alpha, Omega, Plugin("Zinc_Core"), Plugin("Zinc_Battle"), Plugin("Fig")), + WriteText(bases, plan)); + } + + [Fact] + public void Build_RegistryEntryWithNoName_IsAnErrorAndTheOthersStillMerge() + { + ModSource mod = RegistryMod("a-tin", 0, Entry(""), Entry("Gamma")); + + ModChangeSet set = Build(mod, Bases(Base(PluginList, VanillaPlugins))); + + OperationDiagnostic diagnostic = Assert.Single(set.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeParseFailed, diagnostic.Code); + Assert.Equal("a-tin", diagnostic.Subject); + Assert.All(set.Ops, op => Assert.Equal("plugin:Gamma", op.Key.Record)); + } + + [Fact] + public void Write_NameMentionedInACommentFirst_FindsTheDeclaration() + { + string vanilla = "// The $plugins list of this game.\n" + VanillaPlugins; + BaseFileSet bases = Bases(Base(PluginList, vanilla)); + + string text = WriteText(bases, Compose(bases, RegistryMod("a-tin", 0, Entry("Gamma")))); + + Assert.Equal("// The $plugins list of this game.\n" + PluginsJs(Alpha, Omega, Plugin("Gamma")), text); + } + + private static string[] Names(string order) + { + return order.Split(',').Select(name => Plugin(name)).ToArray(); + } + + private static IEnumerable> Permutations(List items) + { + if (items.Count <= 1) + { + yield return [.. items]; + yield break; + } + + foreach (string item in items) + { + foreach (List rest in Permutations(items.Where(other => other != item).ToList())) + { + rest.Insert(0, item); + yield return rest; + } + } + } + + [Fact] + public void Write_Swap_PutsTheMovedFirstEntryInFront() + { + BaseFileSet bases = Bases(Base(PluginList, VanillaPlugins)); + + string text = WriteText(bases, Compose(bases, FileMod("a-tin", PluginList, PluginsJs(Omega, Alpha)))); + + Assert.Equal(PluginsJs(Omega, Alpha), text); + } + + [Fact] + public void Build_Removal_DoesNotMoveTheNeighbour() + { + ModChangeSet set = Build(FileMod("a-tin", PluginList, PluginsJs(Omega)), Bases(Base(PluginList, VanillaPlugins))); + + Assert.Equal(["js/plugins.js|plugin:Alpha||RemoveRecord|-"], set.Ops.Select(Describe)); + } + + [Fact] + public void Write_Insertion_LandsAfterItsAnchorAndMovesNothingElse() + { + BaseFileSet bases = Bases(Base(PluginList, VanillaPlugins)); + ModSource mod = FileMod("a-tin", PluginList, PluginsJs(Alpha, Plugin("Beta"), Omega)); + + ModChangeSet set = Build(mod, bases); + string text = WriteText(bases, Compose(bases, mod)); + + Assert.Equal(2, set.Ops.Count); + Assert.Equal(PluginsJs(Alpha, Plugin("Beta"), Omega), text); + } + + [Fact] + public void Write_RepeatedNames_ReplaceTheWholeList() + { + BaseFileSet bases = Bases(Base(PluginList, VanillaPlugins)); + ModSource mod = FileMod("a-tin", PluginList, PluginsJs(Omega, Omega)); + + ChangeOp op = Assert.Single(Build(mod, bases).Ops); + string text = WriteText(bases, Compose(bases, mod)); + + Assert.Equal("*|", op.Key.Record + "|" + op.Path); + Assert.Equal(PluginsJs(Omega, Omega), text); + } + + [Fact] + public void Write_EveryEntryRemoved_IsAnEmptyList() + { + BaseFileSet bases = Bases(Base(PluginList, VanillaPlugins)); + + string text = WriteText(bases, Compose(bases, FileMod("a-tin", PluginList, PluginsJs()))); + + Assert.Equal(PluginsJs(), text); + } + + [Fact] + public void Write_NoVanillaPluginList_UsesTheEditorPrefix() + { + BaseFileSet bases = Bases(); + + string text = WriteText(bases, Compose(bases, RegistryMod("a-tin", 0, Entry("Gamma")))); + + Assert.Equal(PluginsJs(Plugin("Gamma")), text); + } + + [Fact] + public void Write_CrlfVanilla_KeepsCrlf() + { + BaseFileSet bases = Bases(Base(PluginList, VanillaPlugins.Replace("\n", "\r\n", StringComparison.Ordinal))); + + string text = WriteText(bases, Compose(bases, RegistryMod("a-tin", 0, Entry("Gamma")))); + + Assert.Equal(PluginsJs(Alpha, Omega, Plugin("Gamma")).Replace("\n", "\r\n", StringComparison.Ordinal), text); + } + + [Theory] + [InlineData("var $other = [];\n")] + [InlineData("var $plugins = {};\n")] + [InlineData("var $plugins = [];\nalert(1);\n")] + [InlineData("var $plugins = [{\"name\":\"A\"}\n")] + public void Build_ModListThatIsNotTheEditorForm_IsAParseFailure(string text) + { + ModChangeSet set = Build(FileMod("a-tin", PluginList, text), Bases(Base(PluginList, VanillaPlugins))); + + OperationDiagnostic diagnostic = Assert.Single(set.Diagnostics); + Assert.Empty(set.Ops); + Assert.Equal(DiagnosticCodes.MergeParseFailed, diagnostic.Code); + Assert.Equal("a-tin", diagnostic.Subject); + } + + [Fact] + public void Build_BrokenVanillaList_IsABaseFaultOnTheFile() + { + ModChangeSet set = Build(RegistryMod("a-tin", 0, Entry("Gamma")), Bases(Base(PluginList, "window.$plugins = 1;"))); + + OperationDiagnostic diagnostic = Assert.Single(set.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeBaseParseFailed, diagnostic.Code); + Assert.Equal(PluginList, diagnostic.Subject); + } + + [Fact] + public void Build_PatchOnThePluginList_IsRejected() + { + ModChangeSet set = Build(PatchMod("a-tin", PluginList, "{\"Alpha\":{}}"), Bases(Base(PluginList, VanillaPlugins))); + + Assert.Empty(set.Ops); + Assert.Equal(DiagnosticCodes.MergePatchShapeMismatch, Assert.Single(set.Diagnostics).Code); + } + + [Theory] + [InlineData(0, 1, "Omega")] + [InlineData(1, 0, "Alpha")] + public void Compose_OneNewEntryAtTwoPlaces_DefaultsToTheLatestModInProfileOrder(int tinPriority, int oakPriority, string winner) + { + BaseFileSet bases = Bases(Base(PluginList, VanillaPlugins)); + string gamma = Plugin("Gamma"); + ModSource tin = FileMod("a-tin", PluginList, PluginsJs(Alpha, gamma, Omega), tinPriority); + ModSource oak = FileMod("b-oak", PluginList, PluginsJs(Alpha, Omega, gamma), oakPriority); + + MergePlan plan = Compose(bases, tin, oak); + + Collision collision = Assert.Single(plan.Collisions); + Assert.Equal(CollisionKind.PluginOrderClash, collision.Kind); + Assert.Equal("plugin:Gamma|@after", collision.Key.Record + "|" + collision.Path); + Assert.False(collision.Blocking); + Assert.Equal(ResolutionSource.Default, Assert.Single(plan.Outcomes).Source); + string expected = winner == "Omega" ? PluginsJs(Alpha, Omega, gamma) : PluginsJs(Alpha, gamma, Omega); + Assert.Equal(expected, WriteText(bases, plan)); + } + + [Fact] + public void Compose_OneNewEntryAtTwoPlaces_PickModTakesThatModsPlace() + { + BaseFileSet bases = Bases(Base(PluginList, VanillaPlugins)); + string gamma = Plugin("Gamma"); + ModSource tin = FileMod("a-tin", PluginList, PluginsJs(Alpha, gamma, Omega), 0); + ModSource oak = FileMod("b-oak", PluginList, PluginsJs(Alpha, Omega, gamma), 1); + Collision collision = Assert.Single(Compose(bases, tin, oak).Collisions); + + MergePlan plan = Compose(bases, [new Resolution(collision.Id, ResolutionKind.PickMod, "a-tin", collision.Fingerprint)], tin, oak); + + Assert.Equal(ResolutionSource.Profile, Assert.Single(plan.Outcomes).Source); + Assert.Equal(PluginsJs(Alpha, gamma, Omega), WriteText(bases, plan)); + } + + [Theory] + [InlineData(0, 1, true)] + [InlineData(1, 0, false)] + public void Compose_TwoNewEntriesAfterOneAnchor_DefaultToProfileOrder(int ashPriority, int birchPriority, bool ashFirst) + { + BaseFileSet bases = Bases(Base(PluginList, VanillaPlugins)); + string ash = Plugin("Ash"); + string birch = Plugin("Birch"); + ModSource first = FileMod("a-ash", PluginList, PluginsJs(Alpha, Omega, ash), ashPriority); + ModSource second = FileMod("b-birch", PluginList, PluginsJs(Alpha, Omega, birch), birchPriority); + + MergePlan plan = Compose(bases, first, second); + + Collision collision = Assert.Single(plan.Collisions); + Assert.Equal(CollisionKind.OrderAmbiguous, collision.Kind); + Assert.Equal("plugin:Omega|@after", collision.Key.Record + "|" + collision.Path); + Assert.Equal(["a-ash", "b-birch"], collision.ModIds); + Assert.False(collision.Blocking); + Assert.Equal(ashFirst ? PluginsJs(Alpha, Omega, ash, birch) : PluginsJs(Alpha, Omega, birch, ash), WriteText(bases, plan)); + } + + [Fact] + public void Compose_TwoNewEntriesAfterOneAnchor_PickModPutsThatModFirst() + { + BaseFileSet bases = Bases(Base(PluginList, VanillaPlugins)); + string ash = Plugin("Ash"); + string birch = Plugin("Birch"); + ModSource first = FileMod("a-ash", PluginList, PluginsJs(Alpha, Omega, ash), 0); + ModSource second = FileMod("b-birch", PluginList, PluginsJs(Alpha, Omega, birch), 1); + Collision collision = Assert.Single(Compose(bases, first, second).Collisions); + + MergePlan plan = Compose(bases, [new Resolution(collision.Id, ResolutionKind.PickMod, "b-birch", collision.Fingerprint)], first, second); + + Assert.Equal(PluginsJs(Alpha, Omega, birch, ash), WriteText(bases, plan)); + } + + [Theory] + [InlineData(0, 1, "V2,V3,V0,V1")] + [InlineData(1, 0, "V3,V2,V0,V1")] + public void Compose_TwoModsMovingEntriesToTheFront_IsOrderAmbiguousInProfileOrder(int ashPriority, int birchPriority, string expected) + { + BaseFileSet bases = Bases(Base(PluginList, PluginsJs(Names("V0,V1,V2,V3")))); + ModSource ash = FileMod("a-ash", PluginList, PluginsJs(Names("V2,V0,V1,V3")), ashPriority); + ModSource birch = FileMod("b-birch", PluginList, PluginsJs(Names("V3,V0,V1,V2")), birchPriority); + + MergePlan plan = Compose(bases, ash, birch); + + Collision collision = Assert.Single(plan.Collisions); + Assert.Equal(CollisionKind.OrderAmbiguous, collision.Kind); + Assert.Equal("*|@first", collision.Key.Record + "|" + collision.Path); + Assert.Equal(["a-ash", "b-birch"], collision.ModIds); + Assert.Equal(PluginsJs(Names(expected)), WriteText(bases, plan)); + } + + [Fact] + public void Compose_TwoModsMovingEntriesToTheFront_PickModPutsThatModFirst() + { + BaseFileSet bases = Bases(Base(PluginList, PluginsJs(Names("V0,V1,V2,V3")))); + ModSource ash = FileMod("a-ash", PluginList, PluginsJs(Names("V2,V0,V1,V3")), 0); + ModSource birch = FileMod("b-birch", PluginList, PluginsJs(Names("V3,V0,V1,V2")), 1); + Collision collision = Assert.Single(Compose(bases, ash, birch).Collisions); + + MergePlan plan = Compose(bases, [new Resolution(collision.Id, ResolutionKind.PickMod, "b-birch", collision.Fingerprint)], ash, birch); + + Assert.Equal(PluginsJs(Names("V3,V2,V0,V1")), WriteText(bases, plan)); + } + + [Fact] + public void Compose_TwoModsMovingTheSameEntryToTheFront_IsNoCollision() + { + BaseFileSet bases = Bases(Base(PluginList, PluginsJs(Names("V0,V1,V2,V3")))); + string moved = PluginsJs(Names("V2,V0,V1,V3")); + + MergePlan plan = Compose(bases, FileMod("a-ash", PluginList, moved, 0), FileMod("b-birch", PluginList, moved, 1)); + + Assert.Empty(plan.Collisions); + Assert.Equal(moved, WriteText(bases, plan)); + } + + [Fact] + public void Compose_ModsMovingAnEntryToTheFrontAndAddingOneAtTheEnd_AreTwoSeparatePlaces() + { + // Both anchors are null: the moved V2 goes to the front, the new N (first in its mod's list) to the end. + BaseFileSet bases = Bases(Base(PluginList, PluginsJs(Names("V0,V1,V2,V3")))); + ModSource ash = FileMod("a-ash", PluginList, PluginsJs(Names("V2,V0,V1,V3")), 0); + ModSource birch = FileMod("b-birch", PluginList, PluginsJs(Names("N,V0,V1,V2,V3")), 1); + + MergePlan plan = Compose(bases, ash, birch); + + Assert.Empty(plan.Collisions); + Assert.Equal(PluginsJs(Names("V2,V0,V1,V3,N")), WriteText(bases, plan)); + } + + [Fact] + public void Place_AnchorCycle_GoesToTheEndByName() + { + List order = PluginPlacement.Place( + ["A", "B"], + new HashSet { "A", "B", "Y", "X" }, + new HashSet { "X", "Y" }, + new Dictionary { ["X"] = "Y", ["Y"] = "X" }); + + Assert.Equal(["A", "B", "X", "Y"], order); + } + + [Fact] + public void Place_AnchorOnARemovedVanillaEntry_FallsBackToTheNearestEarlierOne() + { + List order = PluginPlacement.Place( + ["A", "B", "C"], + new HashSet { "A", "C", "X" }, + new HashSet { "X" }, + new Dictionary { ["X"] = "B" }); + + Assert.Equal(["A", "X", "C"], order); + } + + [Fact] + public void Place_AnchorThatIsNowhere_GoesToTheEnd() + { + List order = PluginPlacement.Place( + ["A", "B"], + new HashSet { "A", "B", "X" }, + new HashSet { "X" }, + new Dictionary { ["X"] = "Zed" }); + + Assert.Equal(["A", "B", "X"], order); + } + + [Fact] + public void Place_MovedEntriesWithNoAnchor_GoFirstAndNewOnesLast() + { + List order = PluginPlacement.Place( + ["A", "B", "C"], + new HashSet { "A", "B", "C", "N" }, + new HashSet { "N" }, + new Dictionary { ["C"] = null, ["N"] = null }); + + Assert.Equal(["C", "A", "B", "N"], order); + } + + [Fact] + public void Place_TwoEntriesBehindOneAnchor_KeepTheirPlacingOrder() + { + List order = PluginPlacement.Place( + ["A", "B"], + new HashSet { "A", "B", "X", "Y" }, + new HashSet { "X", "Y" }, + new Dictionary { ["X"] = "A", ["Y"] = "A" }); + + Assert.Equal(["A", "X", "Y", "B"], order); + } +} diff --git a/RPGModder.Tests/MergeContract/ChangeSetBuilderContractTests.cs b/RPGModder.Tests/MergeContract/ChangeSetBuilderContractTests.cs new file mode 100644 index 0000000..b99f765 --- /dev/null +++ b/RPGModder.Tests/MergeContract/ChangeSetBuilderContractTests.cs @@ -0,0 +1,316 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using System.Security.Cryptography; +using System.Text; +using Xunit; + +namespace RPGModder.Tests.MergeContract; + +public sealed class ChangeSetBuilderContractTests +{ + [Fact] + public void Build_VolatileFieldsViaFileOps_GiveNoOps() + { + const string vanillaSystem = + "{\"gameTitle\":\"Sample\",\"versionId\":1,\"editMapId\":1,\"screenWidth\":816,\"screenHeight\":624," + + "\"uiAreaWidth\":816,\"uiAreaHeight\":624,\"windowLineWidth\":12,\"locale\":\"en_US\"," + + "\"title1Name\":\"Castle\",\"title2Name\":\"Gate\",\"currencyUnit\":\"G\"}"; + const string modSystem = + "{\"gameTitle\":\"Sample\",\"versionId\":99,\"editMapId\":5,\"screenWidth\":1280,\"screenHeight\":720," + + "\"uiAreaWidth\":1280,\"uiAreaHeight\":720,\"windowLineWidth\":16,\"locale\":\"ja_JP\"," + + "\"title1Name\":\"Tower\",\"title2Name\":\"Dawn\",\"currencyUnit\":\"G\"}"; + + const string vanillaMapInfos = + "[null,{\"id\":1,\"name\":\"Town\",\"parentId\":0,\"order\":1,\"expanded\":false,\"scrollX\":400,\"scrollY\":300}]"; + const string modMapInfos = + "[null,{\"id\":1,\"name\":\"Town\",\"parentId\":0,\"order\":1,\"expanded\":true,\"scrollX\":850,\"scrollY\":610}]"; + + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/System.json", vanillaSystem), + CreateBaseFile("data/MapInfos.json", vanillaMapInfos) + }); + + ModSource mod = new( + "a-volatile", + 0, + new[] + { + CreateModFile("data/System.json", "data/System.json", modSystem), + CreateModFile("data/MapInfos.json", "data/MapInfos.json", modMapInfos) + }, + Array.Empty(), + Array.Empty()); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + Assert.Empty(changeSet.Diagnostics); + Assert.Empty(changeSet.Ops); + } + + [Fact] + public void Build_VolatileFieldsViaJsonPatches_GiveNoOps() + { + const string vanillaSystem = + "{\"gameTitle\":\"Sample\",\"versionId\":1,\"editMapId\":1,\"screenWidth\":816,\"screenHeight\":624," + + "\"uiAreaWidth\":816,\"uiAreaHeight\":624,\"windowLineWidth\":12,\"locale\":\"en_US\"," + + "\"title1Name\":\"Castle\",\"title2Name\":\"Gate\",\"currencyUnit\":\"G\"}"; + + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/System.json", vanillaSystem) + }); + + JObject patchData = JObject.Parse( + "{\"versionId\":42,\"editMapId\":9,\"screenWidth\":1920,\"screenHeight\":1080," + + "\"uiAreaWidth\":1920,\"uiAreaHeight\":1080,\"windowLineWidth\":20,\"locale\":\"es_CL\"," + + "\"title1Name\":\"Alt1\",\"title2Name\":\"Alt2\"}"); + + ModSource mod = new( + "a-patch-volatile", + 0, + Array.Empty(), + new[] { new ModPatch("data/System.json", patchData) }, + Array.Empty()); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + Assert.Empty(changeSet.Diagnostics); + Assert.Empty(changeSet.Ops); + } + + [Fact] + public void Build_BrokenModJson_IsParseFailedOnTheModWithNoOp() + { + const string vanillaItems = "[null,{\"id\":1,\"name\":\"Herb\",\"price\":50}]"; + const string vanillaWeapons = "[null,{\"id\":1,\"name\":\"Short Sword\",\"price\":100}]"; + const string modWeapons = "[null,{\"id\":1,\"name\":\"Short Sword\",\"price\":140}]"; + + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Items.json", vanillaItems), + CreateBaseFile("data/Weapons.json", vanillaWeapons) + }); + + ModSource mod = new( + "a-broken", + 0, + new[] + { + CreateModFile("data/Items.json", "data/Items.json", "[null, {\"id\": 1, broken json"), + CreateModFile("data/Weapons.json", "data/Weapons.json", modWeapons) + }, + Array.Empty(), + Array.Empty()); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + OperationDiagnostic diag = Assert.Single(changeSet.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeParseFailed, diag.Code); + Assert.Equal(DiagnosticSeverity.Error, diag.Severity); + Assert.Equal("a-broken", diag.Subject); + + Assert.DoesNotContain(changeSet.Ops, op => op.Key.File == "data/items.json"); + ChangeOp weaponOp = Assert.Single(changeSet.Ops); + Assert.Equal(new RecordKey("data/weapons.json", "id:1"), weaponOp.Key); + Assert.Equal("price", weaponOp.Path); + } + + [Fact] + public void Build_PatchOnAMissingFile_IsPatchTargetMissing() + { + BaseFileSet baseFiles = BaseFileSet.From(Array.Empty()); + + ModSource mod = new( + "a-orphan-patch", + 0, + Array.Empty(), + new[] { new ModPatch("data/System.json", JObject.Parse("{\"currencyUnit\":\"Silver\"}")) }, + Array.Empty()); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + OperationDiagnostic diag = Assert.Single(changeSet.Diagnostics); + Assert.Equal(DiagnosticCodes.MergePatchTargetMissing, diag.Code); + Assert.Equal(DiagnosticSeverity.Error, diag.Severity); + Assert.Empty(changeSet.Ops); + } + + [Fact] + public void Build_ModFileRootShapeDiffersFromBase_IsRootShapeMismatch() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Items.json", "[null,{\"id\":1,\"name\":\"Herb\",\"price\":50}]") + }); + + ModSource mod = new( + "a-wrong-root", + 0, + new[] { CreateModFile("data/Items.json", "data/Items.json", "{\"id\":1,\"name\":\"Herb\"}") }, + Array.Empty(), + Array.Empty()); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + OperationDiagnostic diag = Assert.Single(changeSet.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeRootShapeMismatch, diag.Code); + Assert.Equal(DiagnosticSeverity.Error, diag.Severity); + Assert.Empty(changeSet.Ops); + } + + [Fact] + public void Build_PatchOnArrayRootFile_IsPatchShapeMismatch() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Items.json", "[null,{\"id\":1,\"name\":\"Herb\",\"price\":50}]") + }); + + ModSource mod = new( + "a-wrong-patch", + 0, + Array.Empty(), + new[] { new ModPatch("data/Items.json", JObject.Parse("{\"price\":99}")) }, + Array.Empty()); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + OperationDiagnostic diag = Assert.Single(changeSet.Diagnostics); + Assert.Equal(DiagnosticCodes.MergePatchShapeMismatch, diag.Code); + Assert.Equal(DiagnosticSeverity.Error, diag.Severity); + Assert.Empty(changeSet.Ops); + } + + [Fact] + public void Build_WholeFileAndEqualPatch_GiveTheSameOps() + { + const string vanillaSystem = + "{\"gameTitle\":\"Sample\",\"currencyUnit\":\"G\",\"testBattlers\":[],\"advanced\":{\"gameId\":10,\"Categ\":1}}"; + const string modSystem = + "{\"gameTitle\":\"SampleUpdated\",\"currencyUnit\":\"Coins\",\"testBattlers\":[],\"advanced\":{\"gameId\":25,\"Categ\":1}}"; + + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/System.json", vanillaSystem) + }); + + ModSource fileMod = new( + "a-mod", + 0, + new[] { CreateModFile("data/System.json", "data/System.json", modSystem) }, + Array.Empty(), + Array.Empty()); + + ModSource patchMod = new( + "a-mod", + 0, + Array.Empty(), + new[] + { + new ModPatch( + "data/System.json", + JObject.Parse("{\"gameTitle\":\"SampleUpdated\",\"currencyUnit\":\"Coins\",\"advanced\":{\"gameId\":25}}")) + }, + Array.Empty()); + + ModChangeSet fromFile = ChangeSetBuilder.Build(fileMod, baseFiles); + ModChangeSet fromPatch = ChangeSetBuilder.Build(patchMod, baseFiles); + + Assert.Empty(fromFile.Diagnostics); + Assert.Empty(fromPatch.Diagnostics); + Assert.Equal(fromFile.Ops.Count, fromPatch.Ops.Count); + + for (int i = 0; i < fromFile.Ops.Count; i++) + { + ChangeOp a = fromFile.Ops[i]; + ChangeOp b = fromPatch.Ops[i]; + Assert.Equal(a.ModId, b.ModId); + Assert.Equal(a.Key, b.Key); + Assert.Equal(a.Path, b.Path); + Assert.Equal(a.Kind, b.Kind); + Assert.True(JToken.DeepEquals(a.Value, b.Value)); + } + } + + [Fact] + public void Build_SequenceAndCommandArrays_GiveEditSequenceAndEditCommands() + { + const string vanillaItems = "[null,{\"id\":1,\"name\":\"Herb\",\"effects\":[{\"code\":11,\"dataId\":0,\"value1\":10,\"value2\":0}]}]"; + const string modItems = "[null,{\"id\":1,\"name\":\"Herb\",\"effects\":[{\"code\":11,\"dataId\":0,\"value1\":25,\"value2\":0}]}]"; + + const string vanillaCommonEvents = "[null,{\"id\":1,\"name\":\"Intro\",\"trigger\":0,\"switchId\":1,\"list\":[{\"code\":0,\"indent\":0,\"parameters\":[]}]}]"; + const string modCommonEvents = "[null,{\"id\":1,\"name\":\"Intro\",\"trigger\":0,\"switchId\":1,\"list\":[{\"code\":101,\"indent\":0,\"parameters\":[\"\",0,0,2]},{\"code\":0,\"indent\":0,\"parameters\":[]}]}]"; + + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Items.json", vanillaItems), + CreateBaseFile("data/CommonEvents.json", vanillaCommonEvents) + }); + + ModSource mod = new( + "a-seq", + 0, + new[] + { + CreateModFile("data/Items.json", "data/Items.json", modItems), + CreateModFile("data/CommonEvents.json", "data/CommonEvents.json", modCommonEvents) + }, + Array.Empty(), + Array.Empty()); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + Assert.Equal(2, changeSet.Ops.Count); + ChangeOp effectsOp = Assert.Single(changeSet.Ops, op => op.Key.File == "data/items.json"); + Assert.Equal(new RecordKey("data/items.json", "id:1"), effectsOp.Key); + Assert.Equal("effects", effectsOp.Path); + Assert.Equal(ChangeKind.EditSequence, effectsOp.Kind); + + ChangeOp listOp = Assert.Single(changeSet.Ops, op => op.Key.File == "data/commonevents.json"); + Assert.Equal(new RecordKey("data/commonevents.json", "id:1"), listOp.Key); + Assert.Equal("list", listOp.Path); + Assert.Equal(ChangeKind.EditCommands, listOp.Kind); + } + + [Fact] + public void Build_Twice_GivesEqualSerializedText() + { + const string vanillaItems = "[null,{\"id\":1,\"name\":\"Herb\",\"price\":50,\"note\":\"\"}]"; + const string modItems = "[null,{\"id\":1,\"name\":\"Herb\",\"price\":85,\"note\":\"mint\"},{\"id\":2,\"name\":\"Sap\",\"price\":120,\"note\":\"\"}]"; + + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Items.json", vanillaItems) + }); + + ModSource mod = new( + "a-repeat", + 2, + new[] { CreateModFile("data/Items.json", "data/Items.json", modItems) }, + Array.Empty(), + Array.Empty()); + + ModChangeSet first = ChangeSetBuilder.Build(mod, baseFiles); + ModChangeSet second = ChangeSetBuilder.Build(mod, baseFiles); + + string firstSerialized = ModChangeSetSerializer.Serialize(first); + string secondSerialized = ModChangeSetSerializer.Serialize(second); + + Assert.Equal(firstSerialized, secondSerialized); + } + + private static BaseFile CreateBaseFile(string path, string text) + { + string sha = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + return new BaseFile(path, text, sha); + } + + private static ModFile CreateModFile(string target, string source, string text) + { + string sha = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + return new ModFile(target, source, text, sha); + } +} diff --git a/RPGModder.Tests/MergeContract/CollisionIdentityAndResolutionContractTests.cs b/RPGModder.Tests/MergeContract/CollisionIdentityAndResolutionContractTests.cs new file mode 100644 index 0000000..747897f --- /dev/null +++ b/RPGModder.Tests/MergeContract/CollisionIdentityAndResolutionContractTests.cs @@ -0,0 +1,125 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using System.Security.Cryptography; +using System.Text; +using Xunit; + +namespace RPGModder.Tests.MergeContract; + +public sealed class CollisionIdentityAndResolutionContractTests +{ + [Fact] + public void Collision_ValuesChange_KeepsIdAndChangesFingerprint() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Items.json", "[null,{\"id\":1,\"name\":\"Herb\",\"price\":50},{\"id\":2,\"name\":\"Tonic\",\"price\":120}]") + }); + + RecordKey key = new("data/items.json", "id:2"); + + ModChangeSet csTinV1 = new( + "a-tin", + 0, + new[] { new ChangeOp("a-tin", key, "price", ChangeKind.SetLeaf, new JValue(80), "data/Items.json") }, + Array.Empty()); + ModChangeSet csOakV1 = new( + "b-oak", + 1, + new[] { new ChangeOp("b-oak", key, "price", ChangeKind.SetLeaf, new JValue(150), "data/Items.json") }, + Array.Empty()); + + ModChangeSet csTinV2 = new( + "a-tin", + 0, + new[] { new ChangeOp("a-tin", key, "price", ChangeKind.SetLeaf, new JValue(95), "data/Items.json") }, + Array.Empty()); + ModChangeSet csOakV2 = new( + "b-oak", + 1, + new[] { new ChangeOp("b-oak", key, "price", ChangeKind.SetLeaf, new JValue(175), "data/Items.json") }, + Array.Empty()); + + MergePlan planV1 = Composer.Compose(new[] { csTinV1, csOakV1 }, Array.Empty(), baseFiles); + MergePlan planV2 = Composer.Compose(new[] { csTinV2, csOakV2 }, Array.Empty(), baseFiles); + + Collision c1 = Assert.Single(planV1.Collisions); + Collision c2 = Assert.Single(planV2.Collisions); + + Assert.Equal("6405909de5ee88d1", c1.Id); + Assert.Equal(c1.Id, c2.Id); + Assert.NotEmpty(c1.Fingerprint); + Assert.NotEmpty(c2.Fingerprint); + Assert.NotEqual(c1.Fingerprint, c2.Fingerprint); + } + + [Fact] + public void Compose_StaleFingerprint_ReusesTheChoiceWithAnInfoDiagnostic() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Items.json", "[null,{\"id\":1,\"name\":\"Herb\",\"price\":50},{\"id\":2,\"name\":\"Tonic\",\"price\":120}]") + }); + + RecordKey key = new("data/items.json", "id:2"); + + ModChangeSet csTinV1 = new( + "a-tin", + 0, + new[] { new ChangeOp("a-tin", key, "price", ChangeKind.SetLeaf, new JValue(80), "data/Items.json") }, + Array.Empty()); + ModChangeSet csOakV1 = new( + "b-oak", + 1, + new[] { new ChangeOp("b-oak", key, "price", ChangeKind.SetLeaf, new JValue(150), "data/Items.json") }, + Array.Empty()); + + MergePlan initialPlan = Composer.Compose(new[] { csTinV1, csOakV1 }, Array.Empty(), baseFiles); + Collision initialCollision = Assert.Single(initialPlan.Collisions); + + Resolution storedResolution = new( + initialCollision.Id, + ResolutionKind.PickMod, + "b-oak", + initialCollision.Fingerprint); + + MergePlan matchingPlan = Composer.Compose(new[] { csTinV1, csOakV1 }, new[] { storedResolution }, baseFiles); + Assert.True(matchingPlan.IsDeployable); + CollisionOutcome matchingOutcome = Assert.Single(matchingPlan.Outcomes); + Assert.Equal(ResolutionSource.Profile, matchingOutcome.Source); + Assert.Equal(ResolutionKind.PickMod, matchingOutcome.Kind); + Assert.Equal("b-oak", matchingOutcome.ModId); + Assert.DoesNotContain(matchingPlan.Diagnostics, d => d.Code == DiagnosticCodes.RulesResolutionReused); + + ModChangeSet csOakV2 = new( + "b-oak", + 1, + new[] { new ChangeOp("b-oak", key, "price", ChangeKind.SetLeaf, new JValue(190), "data/Items.json") }, + Array.Empty()); + + MergePlan updatedPlan = Composer.Compose(new[] { csTinV1, csOakV2 }, new[] { storedResolution }, baseFiles); + + Assert.True(updatedPlan.IsDeployable); + CollisionOutcome reusedOutcome = Assert.Single(updatedPlan.Outcomes); + Assert.Equal(initialCollision.Id, reusedOutcome.CollisionId); + Assert.Equal(ResolutionSource.ProfileReused, reusedOutcome.Source); + Assert.Equal(ResolutionKind.PickMod, reusedOutcome.Kind); + Assert.Equal("b-oak", reusedOutcome.ModId); + + OperationDiagnostic reusedDiag = Assert.Single( + updatedPlan.Diagnostics, + d => d.Code == DiagnosticCodes.RulesResolutionReused); + Assert.Equal(DiagnosticSeverity.Info, reusedDiag.Severity); + + MergedOp winningOp = Assert.Single(updatedPlan.Ops); + Assert.Equal(190, winningOp.Op.Value!.Value()); + } + + private static BaseFile CreateBaseFile(string path, string text) + { + string sha = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + return new BaseFile(path, text, sha); + } +} diff --git a/RPGModder.Tests/MergeContract/ComposerContractTests.cs b/RPGModder.Tests/MergeContract/ComposerContractTests.cs new file mode 100644 index 0000000..1cbb3dc --- /dev/null +++ b/RPGModder.Tests/MergeContract/ComposerContractTests.cs @@ -0,0 +1,215 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using System.Security.Cryptography; +using System.Text; +using Xunit; + +namespace RPGModder.Tests.MergeContract; + +public sealed class ComposerContractTests +{ + [Fact] + public void Compose_EqualAddRecords_AreOneOpWithoutCollision() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Items.json", "[null,{\"id\":1,\"name\":\"Herb\",\"price\":50}]") + }); + + JObject newRecordA = JObject.Parse("{\"id\":2,\"name\":\"Elixir\",\"price\":500}"); + JObject newRecordB = JObject.Parse("{\"id\":2,\"name\":\"Elixir\",\"price\":500}"); + RecordKey key = new("data/items.json", "id:2"); + + ModChangeSet csA = new( + "a-mod", + 0, + new[] { new ChangeOp("a-mod", key, "", ChangeKind.AddRecord, newRecordA, "data/Items.json") }, + Array.Empty()); + ModChangeSet csB = new( + "b-mod", + 1, + new[] { new ChangeOp("b-mod", key, "", ChangeKind.AddRecord, newRecordB, "data/Items.json") }, + Array.Empty()); + + MergePlan plan = Composer.Compose(new[] { csA, csB }, Array.Empty(), baseFiles); + + Assert.True(plan.IsDeployable); + Assert.Empty(plan.Collisions); + MergedOp mergedOp = Assert.Single(plan.Ops); + Assert.Equal(ChangeKind.AddRecord, mergedOp.Op.Kind); + Assert.Equal(new[] { "a-mod", "b-mod" }, mergedOp.ModIds); + } + + [Fact] + public void Compose_DifferentSequenceAndCommandEdits_AreSequenceAndLogicClashes() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Items.json", "[null,{\"id\":1,\"name\":\"Herb\",\"effects\":[]}]"), + CreateBaseFile("data/CommonEvents.json", "[null,{\"id\":1,\"name\":\"Evt\",\"list\":[]}]") + }); + + RecordKey itemKey = new("data/items.json", "id:1"); + RecordKey eventKey = new("data/commonevents.json", "id:1"); + + ModChangeSet csA = new( + "a-mod", + 0, + new[] + { + new ChangeOp("a-mod", itemKey, "effects", ChangeKind.EditSequence, JArray.Parse("[{\"code\":11}]"), "data/Items.json"), + new ChangeOp("a-mod", eventKey, "list", ChangeKind.EditCommands, JArray.Parse("[{\"code\":101},{\"code\":0}]"), "data/CommonEvents.json") + }, + Array.Empty()); + + ModChangeSet csB = new( + "b-mod", + 1, + new[] + { + new ChangeOp("b-mod", itemKey, "effects", ChangeKind.EditSequence, JArray.Parse("[{\"code\":12}]"), "data/Items.json"), + new ChangeOp("b-mod", eventKey, "list", ChangeKind.EditCommands, JArray.Parse("[{\"code\":201},{\"code\":0}]"), "data/CommonEvents.json") + }, + Array.Empty()); + + MergePlan plan = Composer.Compose(new[] { csA, csB }, Array.Empty(), baseFiles); + + Assert.False(plan.IsDeployable); + Assert.Equal(2, plan.Collisions.Count); + + Collision seqClash = Assert.Single(plan.Collisions, c => c.Kind == CollisionKind.SequenceClash); + Assert.True(seqClash.Blocking); + Assert.Equal(new[] { ResolutionKind.PickMod, ResolutionKind.PickVanilla }, seqClash.Allowed); + + Collision logicClash = Assert.Single(plan.Collisions, c => c.Kind == CollisionKind.LogicClash); + Assert.True(logicClash.Blocking); + Assert.Equal(new[] { ResolutionKind.PickMod, ResolutionKind.PickVanilla }, logicClash.Allowed); + } + + [Fact] + public void Compose_PrefixPathsAcrossMods_AreAValueClashOnTheShorterPath() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/System.json", "{\"gameTitle\":\"Sample\",\"advanced\":{\"gameId\":1,\"screenWidth\":816}}") + }); + + RecordKey sysKey = new("data/system.json", "*"); + + ModChangeSet csA = new( + "a-mod", + 0, + new[] { new ChangeOp("a-mod", sysKey, "advanced", ChangeKind.SetLeaf, JObject.Parse("{\"gameId\":2}"), "data/System.json") }, + Array.Empty()); + + ModChangeSet csB = new( + "b-mod", + 1, + new[] { new ChangeOp("b-mod", sysKey, "advanced.gameId", ChangeKind.SetLeaf, new JValue(3), "data/System.json") }, + Array.Empty()); + + MergePlan plan = Composer.Compose(new[] { csA, csB }, Array.Empty(), baseFiles); + + Collision collision = Assert.Single(plan.Collisions); + Assert.Equal(CollisionKind.ValueClash, collision.Kind); + Assert.Equal("advanced", collision.Path); + Assert.False(plan.IsDeployable); + } + + [Fact] + public void Compose_ErrorDiagnostic_MakesThePlanNotDeployable() + { + BaseFileSet baseFiles = BaseFileSet.From(Array.Empty()); + + ModChangeSet cs = new( + "a-broken", + 0, + Array.Empty(), + new[] + { + new OperationDiagnostic( + DiagnosticCodes.MergeParseFailed, + "Broken JSON.", + DiagnosticSeverity.Error, + "a-broken") + }); + + MergePlan plan = Composer.Compose(new[] { cs }, Array.Empty(), baseFiles); + + Assert.False(plan.IsDeployable); + Assert.Contains(plan.Diagnostics, d => d.Code == DiagnosticCodes.MergeParseFailed); + } + + [Fact] + public void Compose_ShuffledInputs_GiveTheSamePlan() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile( + "data/Items.json", + "[null,{\"id\":1,\"name\":\"Herb\",\"price\":50,\"note\":\"\"},{\"id\":2,\"name\":\"Tonic\",\"price\":120,\"note\":\"\"}]") + }); + + RecordKey item1 = new("data/items.json", "id:1"); + RecordKey item2 = new("data/items.json", "id:2"); + + ModChangeSet csA = new( + "a-alpha", + 0, + new[] + { + new ChangeOp("a-alpha", item1, "price", ChangeKind.SetLeaf, new JValue(70), "data/Items.json"), + new ChangeOp("a-alpha", item2, "price", ChangeKind.SetLeaf, new JValue(140), "data/Items.json") + }, + Array.Empty()); + + ModChangeSet csB = new( + "b-beta", + 1, + new[] + { + new ChangeOp("b-beta", item1, "note", ChangeKind.SetLeaf, new JValue("fresh"), "data/Items.json"), + new ChangeOp("b-beta", item2, "price", ChangeKind.SetLeaf, new JValue(180), "data/Items.json") + }, + Array.Empty()); + + ModChangeSet csC = new( + "c-gamma", + 2, + new[] + { + new ChangeOp("c-gamma", item1, "price", ChangeKind.SetLeaf, new JValue(90), "data/Items.json"), + new ChangeOp("c-gamma", item1, "note", ChangeKind.SetLeaf, new JValue("fresh"), "data/Items.json") + }, + Array.Empty()); + + MergePlan unshuffledUnresolved = Composer.Compose(new[] { csA, csB, csC }, Array.Empty(), baseFiles); + Assert.Equal(2, unshuffledUnresolved.Collisions.Count); + + Resolution res1 = new(unshuffledUnresolved.Collisions[0].Id, ResolutionKind.PickMod, unshuffledUnresolved.Collisions[0].ModIds[0]); + Resolution res2 = new(unshuffledUnresolved.Collisions[1].Id, ResolutionKind.PickVanilla, null); + + MergePlan baseline = Composer.Compose(new[] { csA, csB, csC }, new[] { res1, res2 }, baseFiles); + MergePlan shuffled = Composer.Compose(new[] { csC, csA, csB }, new[] { res2, res1 }, baseFiles); + + Assert.Equal(baseline.MergeHash, shuffled.MergeHash); + Assert.Equal(baseline.IsDeployable, shuffled.IsDeployable); + Assert.Equal(baseline.Ops.Count, shuffled.Ops.Count); + + for (int i = 0; i < baseline.Ops.Count; i++) + { + Assert.Equal(baseline.Ops[i].Op.Key, shuffled.Ops[i].Op.Key); + Assert.Equal(baseline.Ops[i].Op.Path, shuffled.Ops[i].Op.Path); + Assert.Equal(baseline.Ops[i].ModIds, shuffled.Ops[i].ModIds); + Assert.True(JToken.DeepEquals(baseline.Ops[i].Op.Value, shuffled.Ops[i].Op.Value)); + } + } + + private static BaseFile CreateBaseFile(string path, string text) + { + string sha = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + return new BaseFile(path, text, sha); + } +} diff --git a/RPGModder.Tests/MergeContract/ConfigSaveMergeContractTests.cs b/RPGModder.Tests/MergeContract/ConfigSaveMergeContractTests.cs new file mode 100644 index 0000000..edcb923 --- /dev/null +++ b/RPGModder.Tests/MergeContract/ConfigSaveMergeContractTests.cs @@ -0,0 +1,93 @@ +using LZStringCSharp; +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using System.Security.Cryptography; +using System.Text; +using Xunit; + +namespace RPGModder.Tests.MergeContract; + +public sealed class ConfigSaveMergeContractTests +{ + [Fact] + public void Write_ConfigRpgsaveRoundTrip_UpdatesChangedTopLevelKeyAndPreservesMissingKeys() + { + const string liveConfigJson = "{\"alwaysDash\":false,\"commandRemember\":true,\"bgmVolume\":100,\"bgsVolume\":80}"; + const string modConfigJson = "{\"bgmVolume\":60}"; + + string liveEncoded = LZString.CompressToBase64(liveConfigJson); + string modEncoded = LZString.CompressToBase64(modConfigJson); + + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("save/config.rpgsave", liveEncoded) + }); + + ModSource mod = new( + "a-config", + 0, + new[] { CreateModFile("save/config.rpgsave", "save/config.rpgsave", modEncoded) }, + Array.Empty(), + Array.Empty()); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + Assert.Empty(changeSet.Diagnostics); + ChangeOp op = Assert.Single(changeSet.Ops); + Assert.Equal("save/config.rpgsave", op.Key.File); + Assert.Equal(ChangeKind.SetLeaf, op.Kind); + Assert.Equal(60, op.Value!.Value()); + + MergePlan plan = Composer.Compose(new[] { changeSet }, Array.Empty(), baseFiles); + Assert.True(plan.IsDeployable); + + IReadOnlyList written = MergedFileWriter.Write(plan, baseFiles, systemVersionId: null); + MergedFile mergedConfig = Assert.Single(written); + Assert.Equal("save/config.rpgsave", mergedConfig.File); + Assert.Equal(MergedFileSource.Text, mergedConfig.Source); + Assert.NotNull(mergedConfig.Text); + + string decompressed = LZString.DecompressFromBase64(mergedConfig.Text!); + JObject actualJson = JObject.Parse(decompressed); + JObject expectedJson = JObject.Parse("{\"alwaysDash\":false,\"commandRemember\":true,\"bgmVolume\":60,\"bgsVolume\":80}"); + Assert.True(JToken.DeepEquals(expectedJson, actualJson)); + } + + [Theory] + [InlineData("save/config.save")] + public void Build_UnsupportedConfigSaveFormat_IsConfigSaveUnsupportedWithNoOp(string targetPath) + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile(targetPath, "{\"bgmVolume\":100}") + }); + + ModSource mod = new( + "a-mz-config", + 0, + new[] { CreateModFile(targetPath, targetPath, "{\"bgmVolume\":50}") }, + Array.Empty(), + Array.Empty()); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + OperationDiagnostic diag = Assert.Single(changeSet.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeConfigSaveUnsupported, diag.Code); + Assert.Equal(DiagnosticSeverity.Error, diag.Severity); + Assert.Empty(changeSet.Ops); + } + + private static BaseFile CreateBaseFile(string path, string text) + { + string sha = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + return new BaseFile(path, text, sha); + } + + private static ModFile CreateModFile(string target, string source, string text) + { + string sha = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + return new ModFile(target, source, text, sha); + } +} diff --git a/RPGModder.Tests/MergeContract/GoldenCaseTests.cs b/RPGModder.Tests/MergeContract/GoldenCaseTests.cs new file mode 100644 index 0000000..f3d3888 --- /dev/null +++ b/RPGModder.Tests/MergeContract/GoldenCaseTests.cs @@ -0,0 +1,344 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using System.Security.Cryptography; +using System.Text; +using Xunit; + +namespace RPGModder.Tests.MergeContract; + +public sealed class GoldenCaseTests +{ + private static readonly JsonSerializerSettings ManifestJsonSettings = new() + { + DateParseHandling = DateParseHandling.None + }; + + public static TheoryData GoldenCases() + { + string goldenRoot = GetGoldenRoot(); + TheoryData data = new(); + if (!Directory.Exists(goldenRoot)) + { + throw new DirectoryNotFoundException($"The golden cases were not copied to {goldenRoot}."); + } + + string[] directories = Directory.GetDirectories(goldenRoot); + Array.Sort(directories, StringComparer.Ordinal); + foreach (string dir in directories) + { + data.Add(Path.GetFileName(dir)); + } + + return data; + } + + [Theory] + [MemberData(nameof(GoldenCases))] + public void GoldenCase_Composed_MatchesExpectedPlanAndFiles(string caseName) + { + string caseDir = Path.Combine(GetGoldenRoot(), caseName); + string vanillaDir = Path.Combine(caseDir, "vanilla"); + string expectedDir = Path.Combine(caseDir, "expected"); + + List modDirs = Directory.GetDirectories(caseDir) + .Select(Path.GetFileName) + .Where(name => !string.IsNullOrEmpty(name) + && !string.Equals(name, "vanilla", StringComparison.OrdinalIgnoreCase) + && !string.Equals(name, "expected", StringComparison.OrdinalIgnoreCase)) + .Select(name => name!) + .OrderBy(name => name, StringComparer.Ordinal) + .ToList(); + + List modSources = new(modDirs.Count); + HashSet requestedTargets = new(StringComparer.Ordinal); + + for (int priority = 0; priority < modDirs.Count; priority++) + { + string modId = modDirs[priority]; + string modDir = Path.Combine(caseDir, modId); + string manifestPath = Path.Combine(modDir, "mod.json"); + string manifestJson = File.ReadAllText(manifestPath, Encoding.UTF8); + ModManifest manifest = JsonConvert.DeserializeObject(manifestJson, ManifestJsonSettings) + ?? throw new InvalidOperationException($"Failed to deserialize mod.json for {modId}."); + + List modFiles = new(manifest.FileOps.Count); + foreach (FileOperation op in manifest.FileOps) + { + string sourcePath = Path.Combine(modDir, op.Source.Replace('/', Path.DirectorySeparatorChar)); + (string? text, string sha256) = ReadFilePayload(sourcePath, op.Target); + modFiles.Add(new ModFile(op.Target, op.Source, text, sha256)); + requestedTargets.Add(MergePath.ToKey(op.Target)); + } + + List modPatches = new(manifest.JsonPatches.Count); + foreach (JsonPatch patch in manifest.JsonPatches) + { + modPatches.Add(new ModPatch(patch.Target, patch.MergeData)); + requestedTargets.Add(MergePath.ToKey(patch.Target)); + } + + if (manifest.PluginsRegistry.Count > 0) + { + requestedTargets.Add(MergePath.ToKey("js/plugins.js")); + } + + modSources.Add(new ModSource(modId, priority, modFiles, modPatches, manifest.PluginsRegistry)); + } + + Dictionary vanillaFilesByKey = new(StringComparer.Ordinal); + if (Directory.Exists(vanillaDir)) + { + foreach (string filePath in Directory.GetFiles(vanillaDir, "*", SearchOption.AllDirectories)) + { + string relPath = Path.GetRelativePath(vanillaDir, filePath).Replace('\\', '/'); + string key = MergePath.ToKey(relPath); + vanillaFilesByKey[key] = filePath; + } + } + + List baseFileList = new(); + foreach (string targetKey in requestedTargets.OrderBy(k => k, StringComparer.Ordinal)) + { + if (vanillaFilesByKey.TryGetValue(targetKey, out string? fullVanillaPath)) + { + string relPath = Path.GetRelativePath(vanillaDir, fullVanillaPath).Replace('\\', '/'); + (string? text, string sha256) = ReadFilePayload(fullVanillaPath, relPath); + baseFileList.Add(new BaseFile(relPath, text, sha256)); + } + } + + BaseFileSet baseFiles = BaseFileSet.From(baseFileList); + + List changeSets = modSources + .Select(mod => ChangeSetBuilder.Build(mod, baseFiles)) + .ToList(); + + List resolutions = LoadResolutions(Path.Combine(caseDir, "resolutions.json")); + + MergePlan plan = Composer.Compose(changeSets, resolutions, baseFiles); + + string expectedCollisionsPath = Path.Combine(expectedDir, "collisions.json"); + JArray expectedCollisions = JsonConvert.DeserializeObject( + File.ReadAllText(expectedCollisionsPath, Encoding.UTF8), + ManifestJsonSettings) ?? new JArray(); + JArray actualCollisions = ProjectCollisions(plan.Collisions); + Assert.True( + JToken.DeepEquals(expectedCollisions, actualCollisions), + $"Collisions mismatch in case '{caseName}'.\nExpected: {expectedCollisions.ToString(Formatting.None)}\nActual: {actualCollisions.ToString(Formatting.None)}"); + + HashSet resolvedCollisionIds = resolutions + .Select(r => r.CollisionId) + .ToHashSet(StringComparer.Ordinal); + bool hasUnresolvedBlocking = expectedCollisions + .OfType() + .Any(c => (c["blocking"]?.Value() ?? false) + && !resolvedCollisionIds.Contains(c["id"]?.Value() ?? "")); + + string expectedFilesDir = Path.Combine(expectedDir, "files"); + Dictionary expectedFiles = new(StringComparer.Ordinal); + if (Directory.Exists(expectedFilesDir)) + { + foreach (string filePath in Directory.GetFiles(expectedFilesDir, "*", SearchOption.AllDirectories)) + { + string relPath = Path.GetRelativePath(expectedFilesDir, filePath).Replace('\\', '/'); + expectedFiles[MergePath.ToKey(relPath)] = File.ReadAllBytes(filePath); + } + } + + if (hasUnresolvedBlocking) + { + Assert.Empty(expectedFiles); + Assert.False(plan.IsDeployable); + Assert.Throws(() => MergedFileWriter.Write(plan, baseFiles, null)); + } + else + { + Assert.True(plan.IsDeployable); + IReadOnlyList writtenFiles = MergedFileWriter.Write(plan, baseFiles, null); + + List expectedKeys = expectedFiles.Keys.OrderBy(k => k, StringComparer.Ordinal).ToList(); + List actualKeys = writtenFiles.Select(f => f.File).ToList(); + Assert.Equal(expectedKeys, actualKeys); + + foreach (MergedFile mergedFile in writtenFiles) + { + byte[] expectedBytes = expectedFiles[mergedFile.File]; + byte[] actualBytes = GetMergedFileBytes(mergedFile, caseDir); + Assert.Equal(expectedBytes, actualBytes); + } + + foreach (string vanillaKey in vanillaFilesByKey.Keys) + { + if (!expectedFiles.ContainsKey(vanillaKey)) + { + Assert.DoesNotContain(writtenFiles, w => w.File == vanillaKey); + } + } + } + + foreach (IReadOnlyList csPerm in Permute(changeSets)) + { + foreach (IReadOnlyList resPerm in Permute(resolutions)) + { + MergePlan permPlan = Composer.Compose(csPerm, resPerm, baseFiles); + Assert.Equal(plan.MergeHash, permPlan.MergeHash); + AssertSameCollisions(plan.Collisions, permPlan.Collisions); + AssertSameMergedOps(plan.Ops, permPlan.Ops); + } + } + } + + private static string GetGoldenRoot() + { + return Path.Combine(AppContext.BaseDirectory, "Merge", "Golden"); + } + + private static (string? Text, string Sha256) ReadFilePayload(string fullPath, string targetPath) + { + byte[] bytes = File.ReadAllBytes(fullPath); + string sha256 = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); + if (RpgDataSchema.KindOf(targetPath) == MergeFileKind.Opaque) + { + return (null, sha256); + } + + int offset = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ? 3 : 0; + string text = Encoding.UTF8.GetString(bytes, offset, bytes.Length - offset); + return (text, sha256); + } + + private static List LoadResolutions(string path) + { + if (!File.Exists(path)) + { + return new List(); + } + + JArray array = JsonConvert.DeserializeObject( + File.ReadAllText(path, Encoding.UTF8), + ManifestJsonSettings) ?? new JArray(); + + List result = new(array.Count); + foreach (JObject item in array.OfType()) + { + string id = item["id"]?.Value() ?? ""; + string kindText = item["kind"]?.Value() ?? ""; + ResolutionKind kind = Enum.Parse(kindText, ignoreCase: false); + string? modId = item["mod"]?.Type == JTokenType.Null ? null : item["mod"]?.Value(); + string? fingerprint = item["fingerprint"]?.Type == JTokenType.Null ? null : item["fingerprint"]?.Value(); + result.Add(new Resolution(id, kind, modId, fingerprint)); + } + + return result; + } + + private static JArray ProjectCollisions(IReadOnlyList collisions) + { + JArray array = new(); + foreach (Collision c in collisions) + { + JObject obj = new() + { + ["id"] = c.Id, + ["kind"] = c.Kind.ToString(), + ["file"] = c.Key.File, + ["record"] = c.Key.Record, + ["path"] = c.Path, + ["mods"] = new JArray(c.ModIds), + ["blocking"] = c.Blocking, + ["allowed"] = new JArray(c.Allowed.Select(a => a.ToString())) + }; + array.Add(obj); + } + + return array; + } + + private static byte[] GetMergedFileBytes(MergedFile mergedFile, string caseDir) + { + if (mergedFile.Source == MergedFileSource.Text) + { + Assert.NotNull(mergedFile.Text); + return Encoding.UTF8.GetBytes(mergedFile.Text!); + } + + if (!string.IsNullOrEmpty(mergedFile.DiskPath) && File.Exists(mergedFile.DiskPath)) + { + return File.ReadAllBytes(mergedFile.DiskPath); + } + + Assert.NotNull(mergedFile.ModId); + Assert.NotNull(mergedFile.SourceFile); + string sourcePath = Path.Combine( + caseDir, + mergedFile.ModId!, + mergedFile.SourceFile!.Replace('/', Path.DirectorySeparatorChar)); + return File.ReadAllBytes(sourcePath); + } + + private static void AssertSameCollisions(IReadOnlyList expected, IReadOnlyList actual) + { + Assert.Equal(expected.Count, actual.Count); + for (int i = 0; i < expected.Count; i++) + { + Collision e = expected[i]; + Collision a = actual[i]; + Assert.Equal(e.Id, a.Id); + Assert.Equal(e.Kind, a.Kind); + Assert.Equal(e.Key, a.Key); + Assert.Equal(e.Path, a.Path); + Assert.Equal(e.ModIds, a.ModIds); + Assert.Equal(e.Blocking, a.Blocking); + Assert.Equal(e.Allowed, a.Allowed); + Assert.Equal(e.Fingerprint, a.Fingerprint); + } + } + + private static void AssertSameMergedOps(IReadOnlyList expected, IReadOnlyList actual) + { + Assert.Equal(expected.Count, actual.Count); + for (int i = 0; i < expected.Count; i++) + { + MergedOp e = expected[i]; + MergedOp a = actual[i]; + Assert.Equal(e.ModIds, a.ModIds); + Assert.Equal(e.Op.ModId, a.Op.ModId); + Assert.Equal(e.Op.Key, a.Op.Key); + Assert.Equal(e.Op.Path, a.Op.Path); + Assert.Equal(e.Op.Kind, a.Op.Kind); + Assert.Equal(e.Op.SourceFile, a.Op.SourceFile); + Assert.True(JToken.DeepEquals(e.Op.Value, a.Op.Value)); + } + } + + private static IEnumerable> Permute(IReadOnlyList items) + { + if (items.Count <= 1) + { + yield return items.ToList(); + yield break; + } + + for (int i = 0; i < items.Count; i++) + { + T first = items[i]; + List remaining = new(items.Count - 1); + for (int j = 0; j < items.Count; j++) + { + if (j != i) + { + remaining.Add(items[j]); + } + } + + foreach (IReadOnlyList tail in Permute(remaining)) + { + List combined = new(items.Count) { first }; + combined.AddRange(tail); + yield return combined; + } + } + } +} diff --git a/RPGModder.Tests/MergeContract/MapMergeContractTests.cs b/RPGModder.Tests/MergeContract/MapMergeContractTests.cs new file mode 100644 index 0000000..ccba3b2 --- /dev/null +++ b/RPGModder.Tests/MergeContract/MapMergeContractTests.cs @@ -0,0 +1,246 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using System.Security.Cryptography; +using System.Text; +using Xunit; + +namespace RPGModder.Tests.MergeContract; + +public sealed class MapMergeContractTests +{ + private const string VanillaMapJson = + "{" + + "\"autoplayBgm\":false,\"autoplayBgs\":false,\"battleback1Name\":\"\",\"battleback2Name\":\"\"," + + "\"bgm\":{\"name\":\"\",\"pan\":0,\"pitch\":100,\"volume\":90}," + + "\"bgs\":{\"name\":\"\",\"pan\":0,\"pitch\":100,\"volume\":90}," + + "\"disableDashing\":false,\"displayName\":\"Meadow\",\"encounterList\":[],\"encounterStep\":30," + + "\"height\":2,\"note\":\"\",\"parallaxLoopX\":false,\"parallaxLoopY\":false,\"parallaxName\":\"\"," + + "\"parallaxShow\":true,\"parallaxSx\":0,\"parallaxSy\":0,\"scrollType\":0,\"specifyBattleback\":false," + + "\"tilesetId\":1,\"width\":2,\"data\":[0,0,0,0]," + + "\"events\":[" + + "null," + + "{\"id\":1,\"name\":\"Signpost\",\"note\":\"\",\"pages\":[" + + "{\"conditions\":{\"actorId\":1,\"actorValid\":false,\"itemId\":1,\"itemValid\":false,\"selfSwitchCh\":\"A\",\"selfSwitchValid\":false,\"switch1Id\":1,\"switch1Valid\":false,\"switch2Id\":1,\"switch2Valid\":false,\"variableId\":1,\"variableValid\":false,\"variableValue\":0}," + + "\"directionFix\":false,\"image\":{\"characterIndex\":0,\"characterName\":\"\",\"direction\":2,\"pattern\":0,\"tileId\":0}," + + "\"list\":[{\"code\":0,\"indent\":0,\"parameters\":[]}],\"moveFrequency\":3," + + "\"moveRoute\":{\"list\":[{\"code\":0,\"parameters\":[]}],\"repeat\":true,\"skippable\":false,\"wait\":false}," + + "\"moveSpeed\":3,\"moveType\":0,\"priorityType\":0,\"stepAnime\":false,\"through\":false,\"trigger\":0,\"walkAnime\":true}" + + "],\"x\":0,\"y\":0}" + + "]" + + "}"; + + [Fact] + public void Build_MapEdit_GivesMapLevelOpsOnStarAndEventOpsOnEventId() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Map001.json", VanillaMapJson) + }); + + JObject modMap = JObject.Parse(VanillaMapJson); + modMap["displayName"] = "Sunlit Meadow"; + modMap["bgm"]!["volume"] = 65; + JObject event1 = (JObject)modMap["events"]![1]!; + event1["x"] = 1; + event1["pages"]![0]!["trigger"] = 2; + event1["pages"]![0]!["conditions"]!["switch1Id"] = 5; + + ModSource mod = new( + "a-map-edit", + 0, + new[] { CreateModFile("data/Map001.json", "data/Map001.json", modMap.ToString()) }, + Array.Empty(), + Array.Empty()); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + Assert.Empty(changeSet.Diagnostics); + + RecordKey mapRootKey = new("data/map001.json", "*"); + RecordKey event1Key = new("data/map001.json", "event:1"); + + ChangeOp displayNameOp = Assert.Single(changeSet.Ops, op => op.Key == mapRootKey && op.Path == "displayName"); + Assert.Equal(ChangeKind.SetLeaf, displayNameOp.Kind); + Assert.Equal("Sunlit Meadow", displayNameOp.Value!.Value()); + + ChangeOp bgmVolumeOp = Assert.Single(changeSet.Ops, op => op.Key == mapRootKey && op.Path == "bgm.volume"); + Assert.Equal(ChangeKind.SetLeaf, bgmVolumeOp.Kind); + Assert.Equal(65, bgmVolumeOp.Value!.Value()); + + ChangeOp xOp = Assert.Single(changeSet.Ops, op => op.Key == event1Key && op.Path == "x"); + Assert.Equal(ChangeKind.SetLeaf, xOp.Kind); + Assert.Equal(1, xOp.Value!.Value()); + + ChangeOp triggerOp = Assert.Single(changeSet.Ops, op => op.Key == event1Key && op.Path == "pages[0].trigger"); + Assert.Equal(ChangeKind.SetLeaf, triggerOp.Kind); + Assert.Equal(2, triggerOp.Value!.Value()); + + ChangeOp switchOp = Assert.Single(changeSet.Ops, op => op.Key == event1Key && op.Path == "pages[0].conditions.switch1Id"); + Assert.Equal(ChangeKind.SetLeaf, switchOp.Kind); + Assert.Equal(5, switchOp.Value!.Value()); + } + + [Fact] + public void Compose_PageCountChangeByTwoMods_IsAPageClash() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Map001.json", VanillaMapJson) + }); + + JObject modMapA = JObject.Parse(VanillaMapJson); + JArray pagesA = (JArray)modMapA["events"]![1]!["pages"]!; + JObject extraPageA = (JObject)pagesA[0].DeepClone(); + extraPageA["trigger"] = 1; + pagesA.Add(extraPageA); + + JObject modMapB = JObject.Parse(VanillaMapJson); + JArray pagesB = (JArray)modMapB["events"]![1]!["pages"]!; + JObject extraPageB = (JObject)pagesB[0].DeepClone(); + extraPageB["trigger"] = 3; + pagesB.Add(extraPageB); + + ModChangeSet csA = ChangeSetBuilder.Build( + new ModSource( + "a-ash", + 0, + new[] { CreateModFile("data/Map001.json", "data/Map001.json", modMapA.ToString()) }, + Array.Empty(), + Array.Empty()), + baseFiles); + + ModChangeSet csB = ChangeSetBuilder.Build( + new ModSource( + "b-birch", + 1, + new[] { CreateModFile("data/Map001.json", "data/Map001.json", modMapB.ToString()) }, + Array.Empty(), + Array.Empty()), + baseFiles); + + MergePlan plan = Composer.Compose(new[] { csA, csB }, Array.Empty(), baseFiles); + + Assert.False(plan.IsDeployable); + Collision clash = Assert.Single(plan.Collisions); + Assert.Equal(CollisionKind.PageClash, clash.Kind); + Assert.Equal(new RecordKey("data/map001.json", "event:1"), clash.Key); + Assert.Equal("pages", clash.Path); + Assert.True(clash.Blocking); + Assert.Equal(new[] { ResolutionKind.PickMod, ResolutionKind.PickVanilla }, clash.Allowed); + } + + [Fact] + public void Compose_MapEventPageSettingVersusListClash_DistinguishesPageClashFromLogicClash() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Map001.json", VanillaMapJson) + }); + + RecordKey event1Key = new("data/map001.json", "event:1"); + + ModChangeSet csA = new( + "a-ash", + 0, + new[] + { + new ChangeOp("a-ash", event1Key, "pages[0].trigger", ChangeKind.SetLeaf, new JValue(1), "data/Map001.json"), + new ChangeOp("a-ash", event1Key, "pages[0].list", ChangeKind.EditCommands, JArray.Parse("[{\"code\":101,\"indent\":0,\"parameters\":[\"\",0,0,2]},{\"code\":0,\"indent\":0,\"parameters\":[]}]"), "data/Map001.json") + }, + Array.Empty()); + + ModChangeSet csB = new( + "b-birch", + 1, + new[] + { + new ChangeOp("b-birch", event1Key, "pages[0].trigger", ChangeKind.SetLeaf, new JValue(2), "data/Map001.json"), + new ChangeOp("b-birch", event1Key, "pages[0].list", ChangeKind.EditCommands, JArray.Parse("[{\"code\":201,\"indent\":0,\"parameters\":[0,1,0,0,0,0]},{\"code\":0,\"indent\":0,\"parameters\":[]}]"), "data/Map001.json") + }, + Array.Empty()); + + MergePlan plan = Composer.Compose(new[] { csA, csB }, Array.Empty(), baseFiles); + + Assert.False(plan.IsDeployable); + Assert.Equal(2, plan.Collisions.Count); + + Collision pageClash = Assert.Single(plan.Collisions, c => c.Path == "pages[0].trigger"); + Assert.Equal(CollisionKind.PageClash, pageClash.Kind); + Assert.True(pageClash.Blocking); + Assert.Equal(new[] { ResolutionKind.PickMod, ResolutionKind.PickVanilla }, pageClash.Allowed); + + Collision logicClash = Assert.Single(plan.Collisions, c => c.Path == "pages[0].list"); + Assert.Equal(CollisionKind.LogicClash, logicClash.Kind); + Assert.True(logicClash.Blocking); + Assert.Equal(new[] { ResolutionKind.PickMod, ResolutionKind.PickVanilla }, logicClash.Allowed); + } + + [Fact] + public void Compose_NewEventAtSameIdWithDifferentContent_IsAnIdClash() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Map001.json", VanillaMapJson) + }); + + JObject modMapA = JObject.Parse(VanillaMapJson); + JObject newEventA = (JObject)modMapA["events"]![1]!.DeepClone(); + newEventA["id"] = 2; + newEventA["name"] = "ChestA"; + newEventA["x"] = 1; + ((JArray)modMapA["events"]!).Add(newEventA); + + JObject modMapB = JObject.Parse(VanillaMapJson); + JObject newEventB = (JObject)modMapB["events"]![1]!.DeepClone(); + newEventB["id"] = 2; + newEventB["name"] = "ChestB"; + newEventB["y"] = 1; + ((JArray)modMapB["events"]!).Add(newEventB); + + ModChangeSet csA = ChangeSetBuilder.Build( + new ModSource( + "a-ash", + 0, + new[] { CreateModFile("data/Map001.json", "data/Map001.json", modMapA.ToString()) }, + Array.Empty(), + Array.Empty()), + baseFiles); + + ModChangeSet csB = ChangeSetBuilder.Build( + new ModSource( + "b-birch", + 1, + new[] { CreateModFile("data/Map001.json", "data/Map001.json", modMapB.ToString()) }, + Array.Empty(), + Array.Empty()), + baseFiles); + + ChangeOp addOpA = Assert.Single(csA.Ops); + Assert.Equal(new RecordKey("data/map001.json", "event:2"), addOpA.Key); + Assert.Equal("", addOpA.Path); + Assert.Equal(ChangeKind.AddRecord, addOpA.Kind); + + MergePlan plan = Composer.Compose(new[] { csA, csB }, Array.Empty(), baseFiles); + + Assert.False(plan.IsDeployable); + Collision clash = Assert.Single(plan.Collisions); + Assert.Equal(CollisionKind.IdClash, clash.Kind); + Assert.Equal(new RecordKey("data/map001.json", "event:2"), clash.Key); + Assert.Equal("", clash.Path); + Assert.True(clash.Blocking); + Assert.Equal(new[] { ResolutionKind.PickMod, ResolutionKind.DisableMod }, clash.Allowed); + } + + private static BaseFile CreateBaseFile(string path, string text) + { + string sha = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + return new BaseFile(path, text, sha); + } + + private static ModFile CreateModFile(string target, string source, string text) + { + string sha = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + return new ModFile(target, source, text, sha); + } +} diff --git a/RPGModder.Tests/MergeContract/MergePathAndSchemaContractTests.cs b/RPGModder.Tests/MergeContract/MergePathAndSchemaContractTests.cs new file mode 100644 index 0000000..e109f34 --- /dev/null +++ b/RPGModder.Tests/MergeContract/MergePathAndSchemaContractTests.cs @@ -0,0 +1,53 @@ +using RPGModder.Core.Merge; +using Xunit; + +namespace RPGModder.Tests.MergeContract; + +public sealed class MergePathAndSchemaContractTests +{ + [Theory] + [InlineData("data/Items.json", "data/items.json")] + [InlineData(@"data\Items.json", "data/items.json")] + [InlineData("./data/Items.json", "data/items.json")] + [InlineData(@".\data\Items.json", "data/items.json")] + [InlineData("/data/System.json", "data/system.json")] + [InlineData(@"\js\plugins.js", "js/plugins.js")] + [InlineData("JS/Plugins.JS", "js/plugins.js")] + public void ToKey_AnyPathForm_GivesTheLowerCaseKey(string rawPath, string expectedKey) + { + string actual = MergePath.ToKey(rawPath); + Assert.Equal(expectedKey, actual); + } + + [Theory] + [InlineData("js/plugins.js", MergeFileKind.PluginList)] + [InlineData(@"JS\Plugins.js", MergeFileKind.PluginList)] + [InlineData("./js/plugins.js", MergeFileKind.PluginList)] + [InlineData("config.rpgsave", MergeFileKind.ConfigSave)] + [InlineData("save/config.rpgsave", MergeFileKind.ConfigSave)] + [InlineData("config.save", MergeFileKind.ConfigSave)] + [InlineData("config.rmmzsave", MergeFileKind.ConfigSave)] + [InlineData("data/Items.json", MergeFileKind.Data)] + [InlineData(@"data\System.json", MergeFileKind.Data)] + [InlineData("./data/Map001.json", MergeFileKind.Data)] + [InlineData("data/sub/extra.json", MergeFileKind.Opaque)] + [InlineData("data/notes.txt", MergeFileKind.Opaque)] + [InlineData("js/plugins/CustomHud.js", MergeFileKind.Opaque)] + [InlineData("img/pictures/banner.png", MergeFileKind.Opaque)] + public void KindOf_Path_FollowsTheFileTable(string path, MergeFileKind expectedKind) + { + MergeFileKind actual = RpgDataSchema.KindOf(path); + Assert.Equal(expectedKind, actual); + } + + [Fact] + public void BaseFileSet_Find_UsesTheNormalizedKey() + { + BaseFile itemFile = new("data/Items.json", "[null]", "00"); + BaseFileSet set = BaseFileSet.From(new[] { itemFile }); + + Assert.Same(itemFile, set.Find("data/items.json")); + Assert.Same(itemFile, set.Find(@"./DATA\Items.json")); + Assert.Null(set.Find("data/weapons.json")); + } +} diff --git a/RPGModder.Tests/MergeContract/MergedFileWriterContractTests.cs b/RPGModder.Tests/MergeContract/MergedFileWriterContractTests.cs new file mode 100644 index 0000000..3b22d42 --- /dev/null +++ b/RPGModder.Tests/MergeContract/MergedFileWriterContractTests.cs @@ -0,0 +1,159 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using System.Security.Cryptography; +using System.Text; +using Xunit; + +namespace RPGModder.Tests.MergeContract; + +public sealed class MergedFileWriterContractTests +{ + [Fact] + public void Write_PlanNotDeployable_Throws() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Items.json", "[null,{\"id\":1,\"name\":\"Herb\",\"price\":50}]") + }); + + RecordKey key = new("data/items.json", "id:1"); + + ModChangeSet csA = new( + "a-mod", + 0, + new[] { new ChangeOp("a-mod", key, "price", ChangeKind.SetLeaf, new JValue(60), "data/Items.json") }, + Array.Empty()); + ModChangeSet csB = new( + "b-mod", + 1, + new[] { new ChangeOp("b-mod", key, "price", ChangeKind.SetLeaf, new JValue(70), "data/Items.json") }, + Array.Empty()); + + MergePlan plan = Composer.Compose(new[] { csA, csB }, Array.Empty(), baseFiles); + + Assert.False(plan.IsDeployable); + Assert.Throws(() => MergedFileWriter.Write(plan, baseFiles, null)); + } + + [Fact] + public void Write_VersionId_ListsSystemOnlyWhenGiven() + { + const string vanillaSystem = "{\"gameTitle\":\"SampleProject\",\"versionId\":100,\"currencyUnit\":\"G\"}"; + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/System.json", vanillaSystem) + }); + + MergePlan emptyPlan = Composer.Compose( + Array.Empty(), + Array.Empty(), + baseFiles); + + Assert.True(emptyPlan.IsDeployable); + + IReadOnlyList withoutVersionId = MergedFileWriter.Write(emptyPlan, baseFiles, systemVersionId: null); + Assert.Empty(withoutVersionId); + + IReadOnlyList withVersionId = MergedFileWriter.Write(emptyPlan, baseFiles, systemVersionId: 777); + MergedFile systemFile = Assert.Single(withVersionId); + Assert.Equal("data/system.json", systemFile.File); + Assert.Equal(MergedFileSource.Text, systemFile.Source); + Assert.Equal("{\"gameTitle\":\"SampleProject\",\"versionId\":777,\"currencyUnit\":\"G\"}", systemFile.Text); + } + + [Fact] + public void Write_AllOpsDroppedByPickVanilla_OmitsTheFile() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Items.json", "[null,{\"id\":1,\"name\":\"Herb\",\"price\":50}]") + }); + + RecordKey key = new("data/items.json", "id:1"); + + ModChangeSet csA = new( + "a-mod", + 0, + new[] { new ChangeOp("a-mod", key, "price", ChangeKind.SetLeaf, new JValue(60), "data/Items.json") }, + Array.Empty()); + ModChangeSet csB = new( + "b-mod", + 1, + new[] { new ChangeOp("b-mod", key, "price", ChangeKind.SetLeaf, new JValue(70), "data/Items.json") }, + Array.Empty()); + + MergePlan unresolved = Composer.Compose(new[] { csA, csB }, Array.Empty(), baseFiles); + Collision collision = Assert.Single(unresolved.Collisions); + + MergePlan resolvedPlan = Composer.Compose( + new[] { csA, csB }, + new[] { new Resolution(collision.Id, ResolutionKind.PickVanilla, null, collision.Fingerprint) }, + baseFiles); + + Assert.True(resolvedPlan.IsDeployable); + IReadOnlyList written = MergedFileWriter.Write(resolvedPlan, baseFiles, systemVersionId: null); + Assert.Empty(written); + } + + [Fact] + public void Write_RemovedRecords_AreNullInsideAndCutAtTheEnd() + { + const string vanillaItems = + "[\nnull,\n{\"id\":1,\"name\":\"Herb\",\"price\":50},\n{\"id\":2,\"name\":\"Tonic\",\"price\":100},\n{\"id\":3,\"name\":\"Salve\",\"price\":150}\n]"; + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/Items.json", vanillaItems) + }); + + ModChangeSet cs = new( + "a-trim", + 0, + new[] + { + new ChangeOp("a-trim", new RecordKey("data/items.json", "id:1"), "", ChangeKind.RemoveRecord, null, "data/Items.json"), + new ChangeOp("a-trim", new RecordKey("data/items.json", "id:3"), "", ChangeKind.RemoveRecord, null, "data/Items.json") + }, + Array.Empty()); + + MergePlan plan = Composer.Compose(new[] { cs }, Array.Empty(), baseFiles); + IReadOnlyList written = MergedFileWriter.Write(plan, baseFiles, systemVersionId: null); + + MergedFile file = Assert.Single(written); + Assert.Equal("data/items.json", file.File); + Assert.Equal("[null,null,{\"id\":2,\"name\":\"Tonic\",\"price\":100}]", file.Text); + } + + [Fact] + public void Write_TouchedRecord_KeepsVanillaOrderAndAppendsNewProperties() + { + const string vanillaSystem = "{\"gameTitle\":\"Sample\",\"currencyUnit\":\"G\"}"; + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("data/System.json", vanillaSystem) + }); + + RecordKey sysKey = new("data/system.json", "*"); + ModChangeSet cs = new( + "a-order", + 0, + new[] + { + new ChangeOp("a-order", sysKey, "customTag", ChangeKind.SetLeaf, new JValue("extra"), "data/System.json"), + new ChangeOp("a-order", sysKey, "gameTitle", ChangeKind.SetLeaf, new JValue("Renamed"), "data/System.json") + }, + Array.Empty()); + + MergePlan plan = Composer.Compose(new[] { cs }, Array.Empty(), baseFiles); + IReadOnlyList written = MergedFileWriter.Write(plan, baseFiles, systemVersionId: null); + + MergedFile file = Assert.Single(written); + Assert.Equal("{\"gameTitle\":\"Renamed\",\"currencyUnit\":\"G\",\"customTag\":\"extra\"}", file.Text); + } + + private static BaseFile CreateBaseFile(string path, string text) + { + string sha = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + return new BaseFile(path, text, sha); + } +} diff --git a/RPGModder.Tests/MergeContract/ModChangeSetSerializerContractTests.cs b/RPGModder.Tests/MergeContract/ModChangeSetSerializerContractTests.cs new file mode 100644 index 0000000..37416a3 --- /dev/null +++ b/RPGModder.Tests/MergeContract/ModChangeSetSerializerContractTests.cs @@ -0,0 +1,165 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using Xunit; + +namespace RPGModder.Tests.MergeContract; + +public sealed class ModChangeSetSerializerContractTests +{ + [Fact] + public void Serializer_RoundTrip_KeepsOpsAndDiagnosticsAndTakesTheNewPriority() + { + ModChangeSet original = new( + "a-roundtrip", + 1, + new[] + { + new ChangeOp( + "a-roundtrip", + new RecordKey("data/items.json", "id:1"), + "price", + ChangeKind.SetLeaf, + new JValue(75), + "data/Items.json"), + new ChangeOp( + "a-roundtrip", + new RecordKey("data/items.json", "id:2"), + "", + ChangeKind.RemoveRecord, + null, + "data/Items.json") + }, + new[] + { + new OperationDiagnostic( + DiagnosticCodes.MergeParseFailed, + "Parse failed for broken file.", + DiagnosticSeverity.Error, + "a-roundtrip") + }); + + string text = ModChangeSetSerializer.Serialize(original); + ModChangeSet? restored = ModChangeSetSerializer.Deserialize(text, priority: 9); + + Assert.NotNull(restored); + Assert.Equal("a-roundtrip", restored!.ModId); + Assert.Equal(9, restored.Priority); + Assert.Equal(original.Ops.Count, restored.Ops.Count); + + for (int i = 0; i < original.Ops.Count; i++) + { + ChangeOp expectedOp = original.Ops[i]; + ChangeOp actualOp = restored.Ops[i]; + Assert.Equal(expectedOp.ModId, actualOp.ModId); + Assert.Equal(expectedOp.Key, actualOp.Key); + Assert.Equal(expectedOp.Path, actualOp.Path); + Assert.Equal(expectedOp.Kind, actualOp.Kind); + Assert.Equal(expectedOp.SourceFile, actualOp.SourceFile); + Assert.True(JToken.DeepEquals(expectedOp.Value, actualOp.Value)); + } + + OperationDiagnostic restoredDiag = Assert.Single(restored.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeParseFailed, restoredDiag.Code); + Assert.Equal("Parse failed for broken file.", restoredDiag.Message); + Assert.Equal(DiagnosticSeverity.Error, restoredDiag.Severity); + Assert.Equal("a-roundtrip", restoredDiag.Subject); + } + + [Fact] + public void Serializer_RoundTrip_PreservesReplaceFileEventAndPluginOpsAndAfterPath() + { + ModChangeSet original = new( + "a-b2-roundtrip", + 0, + new[] + { + new ChangeOp( + "a-b2-roundtrip", + new RecordKey("img/pictures/banner.png", "*"), + "", + ChangeKind.ReplaceFile, + new JValue("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"), + "img/pictures/banner.png"), + new ChangeOp( + "a-b2-roundtrip", + new RecordKey("data/map001.json", "event:1"), + "pages[0].trigger", + ChangeKind.SetLeaf, + new JValue(2), + "data/Map001.json"), + new ChangeOp( + "a-b2-roundtrip", + new RecordKey("js/plugins.js", "plugin:AshExtra"), + "", + ChangeKind.AddRecord, + JObject.Parse("{\"name\":\"AshExtra\",\"status\":true,\"description\":\"Extra\",\"parameters\":{\"mode\":\"fast\"}}"), + "js/plugins.js"), + new ChangeOp( + "a-b2-roundtrip", + new RecordKey("js/plugins.js", "plugin:AshExtra"), + "@after", + ChangeKind.SetLeaf, + new JValue("Omega"), + "js/plugins.js") + }, + Array.Empty()); + + string text = ModChangeSetSerializer.Serialize(original); + ModChangeSet? restored = ModChangeSetSerializer.Deserialize(text, priority: 4); + + Assert.NotNull(restored); + Assert.Equal("a-b2-roundtrip", restored!.ModId); + Assert.Equal(4, restored.Priority); + Assert.Equal(original.Ops.Count, restored.Ops.Count); + + for (int i = 0; i < original.Ops.Count; i++) + { + ChangeOp expectedOp = original.Ops[i]; + ChangeOp actualOp = restored.Ops[i]; + Assert.Equal(expectedOp.ModId, actualOp.ModId); + Assert.Equal(expectedOp.Key, actualOp.Key); + Assert.Equal(expectedOp.Path, actualOp.Path); + Assert.Equal(expectedOp.Kind, actualOp.Kind); + Assert.Equal(expectedOp.SourceFile, actualOp.SourceFile); + Assert.True(JToken.DeepEquals(expectedOp.Value, actualOp.Value)); + } + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("not valid json")] + [InlineData("{unclosed")] + [InlineData("[]")] + public void Deserialize_MalformedText_ReturnsNull(string garbage) + { + ModChangeSet? result = ModChangeSetSerializer.Deserialize(garbage, priority: 0); + Assert.Null(result); + } + + [Fact] + public void Deserialize_OtherSchemaVersion_ReturnsNull() + { + ModChangeSet original = new( + "a-ver", + 0, + Array.Empty(), + Array.Empty()); + + string text = ModChangeSetSerializer.Serialize(original); + JObject root = JObject.Parse(text); + + foreach (JProperty prop in root.Properties().ToList()) + { + if (prop.Value.Type == JTokenType.Integer && prop.Value.Value() == RpgDataSchema.SchemaVersion) + { + prop.Value = RpgDataSchema.SchemaVersion + 100; + } + } + + ModChangeSet? result = ModChangeSetSerializer.Deserialize(root.ToString(), priority: 0); + Assert.Null(result); + } +} diff --git a/RPGModder.Tests/MergeContract/OpaqueAndNewDataFileContractTests.cs b/RPGModder.Tests/MergeContract/OpaqueAndNewDataFileContractTests.cs new file mode 100644 index 0000000..df801df --- /dev/null +++ b/RPGModder.Tests/MergeContract/OpaqueAndNewDataFileContractTests.cs @@ -0,0 +1,190 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using System.Security.Cryptography; +using System.Text; +using Xunit; + +namespace RPGModder.Tests.MergeContract; + +public sealed class OpaqueAndNewDataFileContractTests +{ + [Fact] + public void Build_OpaqueFile_GivesNoOpWhenEqualToVanillaAndReplaceFileWhenDifferent() + { + const string vanillaHash = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"; + const string modHash = "ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100"; + + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + new BaseFile("img/pictures/title.png", null, vanillaHash), + new BaseFile("img/pictures/hud.png", null, vanillaHash) + }); + + ModSource mod = new( + "a-opaque", + 0, + new[] + { + new ModFile("img/pictures/title.png", "assets/title.png", null, vanillaHash), + new ModFile("img/pictures/hud.png", "assets/hud.png", null, modHash) + }, + Array.Empty(), + Array.Empty()); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + Assert.Empty(changeSet.Diagnostics); + ChangeOp op = Assert.Single(changeSet.Ops); + Assert.Equal(new RecordKey("img/pictures/hud.png", "*"), op.Key); + Assert.Equal("", op.Path); + Assert.Equal(ChangeKind.ReplaceFile, op.Kind); + Assert.Equal(modHash, op.Value!.Value()); + Assert.Equal("assets/hud.png", op.SourceFile); + } + + [Fact] + public void Compose_OpaqueFiles_MergesEqualHashesAndReportsFileClashOnDifferentHashes() + { + const string sharedHash = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const string clashHashA = "1111111111111111111111111111111111111111111111111111111111111111"; + const string clashHashB = "2222222222222222222222222222222222222222222222222222222222222222"; + + BaseFileSet baseFiles = BaseFileSet.From(Array.Empty()); + + ModChangeSet csEqualA = ChangeSetBuilder.Build( + new ModSource( + "a-ash", + 0, + new[] { new ModFile("js/plugins/Shared.js", "files/a_shared.js", null, sharedHash) }, + Array.Empty(), + Array.Empty()), + baseFiles); + + ModChangeSet csEqualB = ChangeSetBuilder.Build( + new ModSource( + "b-birch", + 1, + new[] { new ModFile("js/plugins/Shared.js", "files/b_shared.js", null, sharedHash) }, + Array.Empty(), + Array.Empty()), + baseFiles); + + MergePlan equalPlan = Composer.Compose(new[] { csEqualB, csEqualA }, Array.Empty(), baseFiles); + + Assert.True(equalPlan.IsDeployable); + Assert.Empty(equalPlan.Collisions); + MergedOp mergedOp = Assert.Single(equalPlan.Ops); + Assert.Equal(new[] { "a-ash", "b-birch" }, mergedOp.ModIds); + + IReadOnlyList written = MergedFileWriter.Write(equalPlan, baseFiles, systemVersionId: null); + MergedFile file = Assert.Single(written); + Assert.Equal("js/plugins/shared.js", file.File); + Assert.Equal(MergedFileSource.ModFile, file.Source); + Assert.Equal("a-ash", file.ModId); + Assert.Equal("files/a_shared.js", file.SourceFile); + + ModChangeSet csClashA = ChangeSetBuilder.Build( + new ModSource( + "a-ash", + 0, + new[] { new ModFile("js/plugins/Shared.js", "files/a_shared.js", null, clashHashA) }, + Array.Empty(), + Array.Empty()), + baseFiles); + + ModChangeSet csClashB = ChangeSetBuilder.Build( + new ModSource( + "b-birch", + 1, + new[] { new ModFile("js/plugins/Shared.js", "files/b_shared.js", null, clashHashB) }, + Array.Empty(), + Array.Empty()), + baseFiles); + + MergePlan clashPlan = Composer.Compose(new[] { csClashA, csClashB }, Array.Empty(), baseFiles); + + Assert.False(clashPlan.IsDeployable); + Collision clash = Assert.Single(clashPlan.Collisions); + Assert.Equal(CollisionKind.FileClash, clash.Kind); + Assert.Equal(new RecordKey("js/plugins/shared.js", "*"), clash.Key); + Assert.Equal("", clash.Path); + Assert.True(clash.Blocking); + Assert.Equal(new[] { ResolutionKind.PickMod }, clash.Allowed); + } + + [Fact] + public void BuildAndCompose_NewDataFile_GivesAddRecordOnStarAndHandlesWhitespaceEqualityAndIdClash() + { + BaseFileSet baseFiles = BaseFileSet.From(Array.Empty()); + + const string compactJson = "[null,{\"id\":1,\"name\":\"Relic\",\"price\":300}]"; + const string prettyJson = "[\n null,\n {\n \"id\": 1,\n \"name\": \"Relic\",\n \"price\": 300\n }\n]"; + const string differentJson = "[null,{\"id\":1,\"name\":\"Relic\",\"price\":450}]"; + + ModChangeSet csA = ChangeSetBuilder.Build( + new ModSource( + "a-ash", + 0, + new[] { CreateModFile("data/CustomRelics.json", "custom/a_relics.json", compactJson) }, + Array.Empty(), + Array.Empty()), + baseFiles); + + ModChangeSet csBEqual = ChangeSetBuilder.Build( + new ModSource( + "b-birch", + 1, + new[] { CreateModFile("data/CustomRelics.json", "custom/b_relics.json", prettyJson) }, + Array.Empty(), + Array.Empty()), + baseFiles); + + Assert.Empty(csA.Diagnostics); + ChangeOp opA = Assert.Single(csA.Ops); + Assert.Equal(new RecordKey("data/customrelics.json", "*"), opA.Key); + Assert.Equal("", opA.Path); + Assert.Equal(ChangeKind.AddRecord, opA.Kind); + Assert.Equal("custom/a_relics.json", opA.SourceFile); + Assert.True(JToken.DeepEquals(JArray.Parse(compactJson), opA.Value)); + + MergePlan equalPlan = Composer.Compose(new[] { csBEqual, csA }, Array.Empty(), baseFiles); + + Assert.True(equalPlan.IsDeployable); + Assert.Empty(equalPlan.Collisions); + MergedOp mergedOp = Assert.Single(equalPlan.Ops); + Assert.Equal(new[] { "a-ash", "b-birch" }, mergedOp.ModIds); + + IReadOnlyList written = MergedFileWriter.Write(equalPlan, baseFiles, systemVersionId: null); + MergedFile file = Assert.Single(written); + Assert.Equal("data/customrelics.json", file.File); + Assert.Equal(MergedFileSource.ModFile, file.Source); + Assert.Equal("a-ash", file.ModId); + Assert.Equal("custom/a_relics.json", file.SourceFile); + + ModChangeSet csBDiff = ChangeSetBuilder.Build( + new ModSource( + "b-birch", + 1, + new[] { CreateModFile("data/CustomRelics.json", "custom/b_relics.json", differentJson) }, + Array.Empty(), + Array.Empty()), + baseFiles); + + MergePlan clashPlan = Composer.Compose(new[] { csA, csBDiff }, Array.Empty(), baseFiles); + + Assert.False(clashPlan.IsDeployable); + Collision clash = Assert.Single(clashPlan.Collisions); + Assert.Equal(CollisionKind.IdClash, clash.Kind); + Assert.Equal(new RecordKey("data/customrelics.json", "*"), clash.Key); + Assert.Equal("", clash.Path); + Assert.True(clash.Blocking); + Assert.Equal(new[] { ResolutionKind.PickMod, ResolutionKind.DisableMod }, clash.Allowed); + } + + private static ModFile CreateModFile(string target, string source, string text) + { + string sha = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + return new ModFile(target, source, text, sha); + } +} diff --git a/RPGModder.Tests/MergeContract/PluginMergeContractTests.cs b/RPGModder.Tests/MergeContract/PluginMergeContractTests.cs new file mode 100644 index 0000000..7692af4 --- /dev/null +++ b/RPGModder.Tests/MergeContract/PluginMergeContractTests.cs @@ -0,0 +1,256 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using System.Security.Cryptography; +using System.Text; +using Xunit; + +namespace RPGModder.Tests.MergeContract; + +public sealed class PluginMergeContractTests +{ + private const string VanillaPluginsJs = + "// Generated by RPG Maker.\n" + + "// Do not edit this file directly.\n" + + "var $plugins =\n" + + "[\n" + + "{\"name\":\"Alpha\",\"status\":true,\"description\":\"First base plugin.\",\"parameters\":{\"fontSize\":\"16\",\"Font Size\":\"18\"}},\n" + + "{\"name\":\"Omega\",\"status\":true,\"description\":\"Second base plugin.\",\"parameters\":{}}\n" + + "];\n"; + + [Fact] + public void Build_PluginsJsWithUnparseableArray_IsParseFailedOnTheMod() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("js/plugins.js", VanillaPluginsJs) + }); + + const string brokenPluginsJs = + "// Generated by RPG Maker.\n" + + "var $plugins =\n" + + "[\n" + + "{\"name\":\"Alpha\", broken\n" + + "];\n"; + + ModSource mod = new( + "a-broken-plugins", + 0, + new[] { CreateModFile("js/plugins.js", "js/plugins.js", brokenPluginsJs) }, + Array.Empty(), + Array.Empty()); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + OperationDiagnostic diag = Assert.Single(changeSet.Diagnostics); + Assert.Equal(DiagnosticCodes.MergeParseFailed, diag.Code); + Assert.Equal(DiagnosticSeverity.Error, diag.Severity); + Assert.Equal("a-broken-plugins", diag.Subject); + Assert.Empty(changeSet.Ops); + } + + [Fact] + public void Build_PluginRegisteredThroughPluginsRegistry_GivesAddRecordAndAfterAnchor() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("js/plugins.js", VanillaPluginsJs) + }); + + PluginEntry entry = JsonConvert.DeserializeObject( + "{\"name\":\"AshExtra\",\"status\":true,\"description\":\"Added by ash.\",\"parameters\":{\"mode\":\"fast\"}}")!; + + ModSource mod = new( + "a-ash", + 0, + Array.Empty(), + Array.Empty(), + new[] { entry }); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + Assert.Empty(changeSet.Diagnostics); + RecordKey pluginKey = new("js/plugins.js", "plugin:AshExtra"); + + ChangeOp addOp = Assert.Single(changeSet.Ops, op => op.Key == pluginKey && op.Kind == ChangeKind.AddRecord); + Assert.Equal("", addOp.Path); + JObject expectedEntry = JObject.Parse( + "{\"name\":\"AshExtra\",\"status\":true,\"description\":\"Added by ash.\",\"parameters\":{\"mode\":\"fast\"}}"); + Assert.True(JToken.DeepEquals(expectedEntry, addOp.Value)); + Assert.Equal( + new[] { "name", "status", "description", "parameters" }, + ((JObject)addOp.Value!).Properties().Select(p => p.Name)); + + ChangeOp afterOp = Assert.Single(changeSet.Ops, op => op.Key == pluginKey && op.Path == "@after"); + Assert.Equal(ChangeKind.SetLeaf, afterOp.Kind); + Assert.Equal("Omega", afterOp.Value!.Value()); + } + + [Fact] + public void Build_PluginLeafEdits_UseIdentifierAndBracketParameterPaths() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("js/plugins.js", VanillaPluginsJs) + }); + + const string modPluginsJs = + "// Generated by RPG Maker.\n" + + "// Do not edit this file directly.\n" + + "var $plugins =\n" + + "[\n" + + "{\"name\":\"Alpha\",\"status\":false,\"description\":\"First base plugin.\",\"parameters\":{\"fontSize\":\"20\",\"Font Size\":\"24\"}},\n" + + "{\"name\":\"Omega\",\"status\":true,\"description\":\"Second base plugin.\",\"parameters\":{}}\n" + + "];\n"; + + ModSource mod = new( + "a-params", + 0, + new[] { CreateModFile("js/plugins.js", "js/plugins.js", modPluginsJs) }, + Array.Empty(), + Array.Empty()); + + ModChangeSet changeSet = ChangeSetBuilder.Build(mod, baseFiles); + + Assert.Empty(changeSet.Diagnostics); + RecordKey alphaKey = new("js/plugins.js", "plugin:Alpha"); + + Assert.Single(changeSet.Ops, op => op.Key == alphaKey && op.Path == "status" && op.Value!.Value() == false); + Assert.Single(changeSet.Ops, op => op.Key == alphaKey && op.Path == "parameters.fontSize" && op.Value!.Value() == "20"); + Assert.Single(changeSet.Ops, op => op.Key == alphaKey && op.Path == "parameters['Font Size']" && op.Value!.Value() == "24"); + } + + [Fact] + public void Compose_TwoModsGivingOneEntryDifferentAnchors_GivesNonBlockingPluginOrderClashWithDefaultApplied() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("js/plugins.js", VanillaPluginsJs) + }); + + const string modAPluginsJs = + "// Generated by RPG Maker.\n" + + "// Do not edit this file directly.\n" + + "var $plugins =\n" + + "[\n" + + "{\"name\":\"Alpha\",\"status\":true,\"description\":\"First base plugin.\",\"parameters\":{\"fontSize\":\"16\",\"Font Size\":\"18\"}},\n" + + "{\"name\":\"SharedPlugin\",\"status\":true,\"description\":\"Shared.\",\"parameters\":{}},\n" + + "{\"name\":\"Omega\",\"status\":true,\"description\":\"Second base plugin.\",\"parameters\":{}}\n" + + "];\n"; + + const string modBPluginsJs = + "// Generated by RPG Maker.\n" + + "// Do not edit this file directly.\n" + + "var $plugins =\n" + + "[\n" + + "{\"name\":\"Alpha\",\"status\":true,\"description\":\"First base plugin.\",\"parameters\":{\"fontSize\":\"16\",\"Font Size\":\"18\"}},\n" + + "{\"name\":\"Omega\",\"status\":true,\"description\":\"Second base plugin.\",\"parameters\":{}},\n" + + "{\"name\":\"SharedPlugin\",\"status\":true,\"description\":\"Shared.\",\"parameters\":{}}\n" + + "];\n"; + + ModChangeSet csA = ChangeSetBuilder.Build( + new ModSource( + "a-ash", + 0, + new[] { CreateModFile("js/plugins.js", "js/plugins.js", modAPluginsJs) }, + Array.Empty(), + Array.Empty()), + baseFiles); + + ModChangeSet csB = ChangeSetBuilder.Build( + new ModSource( + "b-birch", + 1, + new[] { CreateModFile("js/plugins.js", "js/plugins.js", modBPluginsJs) }, + Array.Empty(), + Array.Empty()), + baseFiles); + + MergePlan plan = Composer.Compose(new[] { csA, csB }, Array.Empty(), baseFiles); + + Assert.True(plan.IsDeployable); + Collision clash = Assert.Single(plan.Collisions); + Assert.Equal(CollisionKind.PluginOrderClash, clash.Kind); + Assert.Equal(new RecordKey("js/plugins.js", "plugin:SharedPlugin"), clash.Key); + Assert.Equal("@after", clash.Path); + Assert.False(clash.Blocking); + Assert.Equal(new[] { ResolutionKind.PickMod, ResolutionKind.KeepBothInProfileOrder }, clash.Allowed); + + CollisionOutcome outcome = Assert.Single(plan.Outcomes); + Assert.Equal(clash.Id, outcome.CollisionId); + Assert.Equal(ResolutionSource.Default, outcome.Source); + + IReadOnlyList written = MergedFileWriter.Write(plan, baseFiles, systemVersionId: null); + MergedFile pluginsFile = Assert.Single(written); + Assert.Equal("js/plugins.js", pluginsFile.File); + Assert.Equal(modBPluginsJs, pluginsFile.Text); + } + + [Fact] + public void Compose_OrderAmbiguousWithPickMod_PutsPickedModsEntriesFirst() + { + BaseFileSet baseFiles = BaseFileSet.From(new[] + { + CreateBaseFile("js/plugins.js", VanillaPluginsJs) + }); + + PluginEntry entryA = JsonConvert.DeserializeObject( + "{\"name\":\"AshExtra\",\"status\":true,\"description\":\"Added by ash.\",\"parameters\":{}}")!; + PluginEntry entryB = JsonConvert.DeserializeObject( + "{\"name\":\"BirchExtra\",\"status\":true,\"description\":\"Added by birch.\",\"parameters\":{}}")!; + + ModChangeSet csA = ChangeSetBuilder.Build( + new ModSource("a-ash", 0, Array.Empty(), Array.Empty(), new[] { entryA }), + baseFiles); + ModChangeSet csB = ChangeSetBuilder.Build( + new ModSource("b-birch", 1, Array.Empty(), Array.Empty(), new[] { entryB }), + baseFiles); + + MergePlan defaultPlan = Composer.Compose(new[] { csA, csB }, Array.Empty(), baseFiles); + Collision collision = Assert.Single(defaultPlan.Collisions); + Assert.Equal(CollisionKind.OrderAmbiguous, collision.Kind); + Assert.Equal(new RecordKey("js/plugins.js", "plugin:Omega"), collision.Key); + Assert.Equal("@after", collision.Path); + Assert.False(collision.Blocking); + + CollisionOutcome defaultOutcome = Assert.Single(defaultPlan.Outcomes); + Assert.Equal(ResolutionSource.Default, defaultOutcome.Source); + Assert.Equal(ResolutionKind.KeepBothInProfileOrder, defaultOutcome.Kind); + + MergePlan pickedPlan = Composer.Compose( + new[] { csA, csB }, + new[] { new Resolution(collision.Id, ResolutionKind.PickMod, "b-birch", collision.Fingerprint) }, + baseFiles); + + Assert.True(pickedPlan.IsDeployable); + IReadOnlyList written = MergedFileWriter.Write(pickedPlan, baseFiles, systemVersionId: null); + MergedFile file = Assert.Single(written); + + const string expectedPickedText = + "// Generated by RPG Maker.\n" + + "// Do not edit this file directly.\n" + + "var $plugins =\n" + + "[\n" + + "{\"name\":\"Alpha\",\"status\":true,\"description\":\"First base plugin.\",\"parameters\":{\"fontSize\":\"16\",\"Font Size\":\"18\"}},\n" + + "{\"name\":\"Omega\",\"status\":true,\"description\":\"Second base plugin.\",\"parameters\":{}},\n" + + "{\"name\":\"BirchExtra\",\"status\":true,\"description\":\"Added by birch.\",\"parameters\":{}},\n" + + "{\"name\":\"AshExtra\",\"status\":true,\"description\":\"Added by ash.\",\"parameters\":{}}\n" + + "];\n"; + + Assert.Equal(expectedPickedText, file.Text); + } + + private static BaseFile CreateBaseFile(string path, string text) + { + string sha = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + return new BaseFile(path, text, sha); + } + + private static ModFile CreateModFile(string target, string source, string text) + { + string sha = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + return new ModFile(target, source, text, sha); + } +}