diff --git a/tests/Aetheria.Shared.Tests/BootedCatalogReadToolsTests.cs b/tests/Aetheria.Shared.Tests/BootedCatalogReadToolsTests.cs new file mode 100644 index 000000000..b29fe35ce --- /dev/null +++ b/tests/Aetheria.Shared.Tests/BootedCatalogReadToolsTests.cs @@ -0,0 +1,89 @@ +using System; +using System.IO; +using Xunit; + +// Every AetherDb read tool answers for the catalog the game boots (campaign aetheria-living-world, follow-up aetherdb-booted-catalog): +// the shipped GameData/Aetheria.cc with the first-party packages in GameData/Mods composed, through the one AetherDb.ComposeBooted. +// The station hulls besides Zenith are packages', so a tool that opened the shipped file alone answered wrong with exit 0. +[Collection("process working directory")] +public sealed class BootedCatalogReadToolsTests : IDisposable +{ + private readonly string _previous = Environment.CurrentDirectory; + private readonly TempDirectory _broken = new TempDirectory(); + private readonly string _repo = AetherDb.FindRoot(); + + public void Dispose() + { + Environment.CurrentDirectory = _previous; + _broken.Dispose(); + } + + // The Seized Refinery's hull, read from its package: a hull the shipped catalog does not hold. + private string SeizedRefineryHull() + { + var (hull, _, _) = ShipAuthoringStore.Load(Path.Combine(_repo, "GameData", "Mods", "aetheria.seized-refinery", "ship.cc")); + return hull.Name; + } + + private string Run(params string[] args) + { + Environment.CurrentDirectory = _repo; + // The exit code counts the tool's own findings (loadout's hulls with no loadout), not whether it ran; the answer is the text. + return ConsoleProbe.WrittenBy(() => Program.Main(args)); + } + + // A game folder with the shipped catalog and one package the compose refuses. + private string BrokenRoot() + { + Directory.CreateDirectory(Path.Combine(_broken.Path, "GameData", "Mods", "mod.broken")); + File.Copy(Path.Combine(_repo, "GameData", "Aetheria.cc"), Path.Combine(_broken.Path, "GameData", "Aetheria.cc")); + File.WriteAllBytes(Path.Combine(_broken.Path, "GameData", "Mods", "mod.broken", "ship.cc"), new byte[] { 1, 2, 3 }); + return _broken.Path; + } + + // Zenith, plus the Pirates' and Zhestokost's package hulls: three station hulls, not the shipped one. + [Fact] + public void CensusCountsThePackageStationHulls() => Assert.Matches(@"Hull/Station\s+3\b", Run("census")); + + [Fact] + public void StationFitChecksThePackageHulls() + { + var output = Run("station-fit"); + Assert.Contains("Arsenal Depot:", output); + Assert.Contains(SeizedRefineryHull() + ":", output); + } + + [Fact] + public void LoadoutListsThePackageStationHulls() + { + var output = Run("loadout", "2"); + Assert.Contains("Arsenal Depot", output); + Assert.Contains(SeizedRefineryHull(), output); + } + + // economy report and economy balance print no hull, so the pin is the compose itself: a package the game would skip is a throw + // that names it, and only a tool that composes the packages can throw it. The same holds for every other read tool. + [Theory] + [InlineData("census")] + [InlineData("station-fit")] + [InlineData("loadout", "2")] + [InlineData("hardpoint-fit")] + [InlineData("factions")] + [InlineData("weapon-ammo")] + [InlineData("economy", "report")] + [InlineData("economy", "balance")] + public void AReadToolThrowsNamingAnExcludedPackage(params string[] args) + { + Environment.CurrentDirectory = BrokenRoot(); + var error = Assert.Throws(() => ConsoleProbe.WrittenBy(() => Program.Main(args))); + Assert.Contains("mod.broken", error.Message); + } + + [Fact] + public void ComposeBootedThrowsNamingAnExcludedPackage() + { + var scratch = Directory.CreateDirectory(Path.Combine(_broken.Path, "scratch")).FullName; + var error = Assert.Throws(() => AetherDb.ComposeBooted(BrokenRoot(), scratch)); + Assert.Contains("mod.broken", error.Message); + } +} diff --git a/tests/Aetheria.Shared.Tests/HardpointFitTests.cs b/tests/Aetheria.Shared.Tests/HardpointFitTests.cs index 5877671c1..26657ee00 100644 --- a/tests/Aetheria.Shared.Tests/HardpointFitTests.cs +++ b/tests/Aetheria.Shared.Tests/HardpointFitTests.cs @@ -32,8 +32,7 @@ public sealed class HardpointFitTests public void TheCensusReadsThePackagesTheGameBoots() { var root = RunStartTests.FindRepoRoot(); - using (var db = AetherDb.Open(root: root, withMods: true)) + using (var db = AetherDb.OpenBooted(root: root)) Assert.Contains(db.Cache.GetAll(), hull => hull.Name == "Nakovalnya"); - Assert.Throws(() => AetherDb.Open(catalogWritable: true, root: root, withMods: true)); } } diff --git a/tools/AetherDb/AetherDb.cs b/tools/AetherDb/AetherDb.cs index 810a9e980..0d7dd6035 100644 --- a/tools/AetherDb/AetherDb.cs +++ b/tools/AetherDb/AetherDb.cs @@ -3,8 +3,8 @@ using System.IO; using System.Linq; using GameCult.Caching; -// Opens GameData/Aetheria.cc through AetheriaStores, the game's own store composition. The catalog attaches read-only -// unless a command writes it, so a command that only reads cannot write. A station hull with no kind does not lock the +// Opens the catalog through AetheriaStores, the game's own store composition: OpenBooted for a read tool (the catalog the game boots), +// Open for the shipped GameData/Aetheria.cc alone, which attaches read-only unless a command writes it, so a command that only reads cannot write. A station hull with no kind does not lock the // catalog: it is named to warn (stderr by default) and the commands that repair it stay reachable. public sealed class AetherDb : IDisposable { @@ -20,26 +20,16 @@ public sealed class AetherDb : IDisposable if (_composed != null) try { Directory.Delete(_composed, true); } catch (IOException) { } } - private AetherDb(string root, bool catalogWritable, bool withRun, bool withMods, Action warn) + private AetherDb(string root, bool booted, bool withRun, Action warn, bool catalogWritable) { Root = root; var gameData = Path.Combine(root, "GameData"); var catalog = Path.Combine(gameData, "Aetheria.cc"); - if (withMods) + if (booted) { - // The catalog the game boots: ShipModCatalog.ResolveCatalog over GameData/Mods. It is derived and read-only, so a write - // through it would land in a temp file, never in Aetheria.cc; the one writable open stays the shipped file alone. - if (catalogWritable) throw new ArgumentException("A catalog composed with packages is read-only; a write opens the shipped file alone.", nameof(withMods)); + // Derived and read-only, so a write through it would land in a temp file, never in Aetheria.cc: a write opens the shipped file alone. _composed = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-mods-" + Guid.NewGuid().ToString("N"))).FullName; - try - { - var (resolved, excluded) = ShipModCatalog.ResolveCatalog(catalog, Path.Combine(_composed, "derived.cc"), Path.Combine(gameData, "Mods")); - // The game skips a broken package so a player still boots; a census of the shipped game does not. - if (excluded.Length > 0) - throw new InvalidOperationException("First-party packages were excluded from the catalog: " + - string.Join("; ", excluded.Select(entry => entry.Package + ": " + entry.Reason))); - catalog = resolved; - } + try { catalog = ComposeBooted(root, _composed); } catch { try { Directory.Delete(_composed, true); } catch (IOException) { } throw; } } try @@ -53,10 +43,30 @@ public sealed class AetherDb : IDisposable catch { if (_composed != null) try { Directory.Delete(_composed, true); } catch (IOException) { } throw; } } - // With no root given, walks up from the working directory to the game folder: the first folder whose GameData holds Aetheria.cc - // withMods composes the packages in GameData/Mods as the game boots them, read-only (see the constructor). - public static AetherDb Open(bool catalogWritable = false, bool withRun = false, string root = null, Action warn = null, bool withMods = false) => - new AetherDb(root ?? FindRoot(), catalogWritable, withRun, withMods, warn); + // The one owner of "the catalog the game boots": the first-party packages in GameData/Mods composed (ShipModCatalog.ResolveCatalog) + // over a scratch copy of GameData/Aetheria.cc, inside the caller's scratch directory, which the caller owns and removes. Returns + // the path of the composed catalog to open read-only; the shipped file is never written. The game skips a broken package so a + // player still boots; a tool reading the catalog does not, so a package left out throws, naming it. + public static string ComposeBooted(string root, string scratch) + { + var copy = Path.Combine(scratch, "Aetheria.cc"); + File.Copy(Path.Combine(root, "GameData", "Aetheria.cc"), copy); + new FileInfo(copy).IsReadOnly = false; + var (composed, excluded) = ShipModCatalog.ResolveCatalog(copy, Path.Combine(scratch, "derived.cc"), Path.Combine(root, "GameData", "Mods")); + if (excluded.Length > 0) + throw new InvalidOperationException("First-party packages were excluded from the catalog: " + + string.Join("; ", excluded.Select(entry => entry.Package + ": " + entry.Reason))); + return composed; + } + + // The shipped GameData/Aetheria.cc alone, which is what an apply path (and its dry run) reads and writes. With no root given, walks up + // from the working directory to the game folder: the first folder whose GameData holds Aetheria.cc. + public static AetherDb Open(bool catalogWritable = false, bool withRun = false, string root = null, Action warn = null) => + new AetherDb(root ?? FindRoot(), false, withRun, warn, catalogWritable); + + // The catalog the game boots (see ComposeBooted), read-only: every read tool opens this. + public static AetherDb OpenBooted(bool withRun = false, string root = null, Action warn = null) => + new AetherDb(root ?? FindRoot(), true, withRun, warn, false); public static string FindRoot() { diff --git a/tools/AetherDb/EconomyCommand.cs b/tools/AetherDb/EconomyCommand.cs index 7c7a2a849..9555919a2 100644 --- a/tools/AetherDb/EconomyCommand.cs +++ b/tools/AetherDb/EconomyCommand.cs @@ -77,13 +77,13 @@ public static class EconomyCommand { if (args.Length > 0 && args[0] == "report") { - using var db = AetherDb.Open(); + using var db = AetherDb.OpenBooted(); return Report(db.Cache, output); } if (args.Length > 0 && args[0] == "prices") return EconomyPrices.Run(args.Skip(1).ToArray(), output); if (args.Length > 0 && args[0] == "balance") { - using var db = AetherDb.Open(); + using var db = AetherDb.OpenBooted(); var settings = AuthoredSettings.Load(db.Root).Read("GameplaySettings"); var rest = args.Skip(1).ToList(); var cap = EconomyLoop.DefaultCap; diff --git a/tools/AetherDb/EconomyLoop.cs b/tools/AetherDb/EconomyLoop.cs index f7b2f0c12..0924f9711 100644 --- a/tools/AetherDb/EconomyLoop.cs +++ b/tools/AetherDb/EconomyLoop.cs @@ -117,14 +117,8 @@ public static class EconomyLoop var scratch = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-loop-" + Guid.NewGuid().ToString("N"))).FullName; try { - var catalog = Path.Combine(scratch, "Aetheria.cc"); - File.Copy(Path.Combine(root, "GameData", "Aetheria.cc"), catalog); - new FileInfo(catalog).IsReadOnly = false; - // The catalog the game boots: the first-party packages in GameData/Mods composed over the copy (the Pirates' station hulls - // are a package's), read from a derived file in the scratch, never written back to the shipped one. - var (composed, excluded) = ShipModCatalog.ResolveCatalog(catalog, Path.Combine(scratch, "derived.cc"), Path.Combine(root, "GameData", "Mods")); - if (excluded.Length > 0) - throw new InvalidOperationException("First-party packages were excluded from the catalog: " + string.Join("; ", excluded.Select(entry => entry.Package + ": " + entry.Reason))); + // The catalog the game boots (the Pirates' station hulls are a package's), composed in the scratch, never written back. + var composed = AetherDb.ComposeBooted(root, scratch); using var cache = AetheriaStores.Open(composed, runPath: Path.Combine(scratch, "run.cc")); var authored = AuthoredSettings.Load(root); var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); diff --git a/tools/AetherDb/EconomyPrices.cs b/tools/AetherDb/EconomyPrices.cs index ef1fb7870..03b8dc73d 100644 --- a/tools/AetherDb/EconomyPrices.cs +++ b/tools/AetherDb/EconomyPrices.cs @@ -22,6 +22,8 @@ public static class EconomyPrices else if (other == null && !args[i].StartsWith("--", StringComparison.Ordinal)) other = args[i]; else { output.WriteLine(Usage); return 1; } } + // The shipped file alone, on purpose: a package's hull price is read from its ship.cc below, so a composed catalog would list the + // same hull twice, and the second catalog an old side is compared against is a shipped file. using var db = AetherDb.Open(); var now = Read(db.Cache, mods ?? Path.Combine(db.Root, "GameData", "Mods")); if (other == null) diff --git a/tools/AetherDb/LoadoutCommitCommand.cs b/tools/AetherDb/LoadoutCommitCommand.cs index 46913b4c5..34c110cb0 100644 --- a/tools/AetherDb/LoadoutCommitCommand.cs +++ b/tools/AetherDb/LoadoutCommitCommand.cs @@ -12,7 +12,7 @@ using GameCult.Caching; // loadout-commit [,,,[@]]... [--group ,...]... [--replace] [--boss-of ] // (aetheria-release, cut loadout-commit; rulings boss-loadouts-agent-authored, catalog-is-a-package-stack): writes one Loadout // record into GameData/Aetheria.cc through Loadouts.Commit, the only writer, and with --boss-of makes it that faction's boss in -// the same commit. Names resolve exactly against the catalog the game boots: ShipModCatalog.ResolveCatalog over the shipped +// the same commit. Names resolve exactly against the catalog the game boots: AetherDb.ComposeBooted over the shipped // file and GameData/Mods, composed into a scratch file that is never committed. So a loadout may name a package's hull, // design or product (one hull product, one design per slot, one product where a slot names one, a rotation by its // ItemRotation name, a faction by Name or ShortName). The loadout is then built once on a throwaway ItemManager with @@ -69,13 +69,12 @@ public static class LoadoutCommitCommand var scratch = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-loadout-commit-" + Guid.NewGuid().ToString("N"))).FullName; try { - var (composed, excluded) = ShipModCatalog.ResolveCatalog(catalogPath, Path.Combine(scratch, "derived.cc"), Path.Combine(root, "GameData", "Mods")); - foreach (var exclusion in excluded) output.WriteLine($"package left out, as at boot: {exclusion}"); + var composed = AetherDb.ComposeBooted(root, scratch); Loadout loadout; CultRecordRef bossOf = default; string summary; - // Disposed before the commit: with no package composed, this is the shipped file itself. + // Disposed before the commit; the commit opens the shipped file alone (it is the one writer, and a composed catalog is derived). using (var cache = AetheriaStores.Open(composed)) { loadout = Build(cache, positional[0], positional[1], positional.Skip(2).ToArray(), groups); @@ -94,6 +93,7 @@ public static class LoadoutCommitCommand (bossOf.IsSet() ? $", boss of {cache.Get(bossOf).Name}" : ""); } + // Shipped file alone, on purpose: the commit writes GameData/Aetheria.cc, never the composed catalog. if (!Loadouts.Commit(catalogPath, loadout, replace, bossOf)) throw new InvalidOperationException("the catalog changed since it was read; nothing was written"); output.WriteLine(summary); diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index 51b45ef45..9a44b9690 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -96,6 +96,7 @@ public static class Program { if (args.Length < 2 || args[1] != "resave") { Console.WriteLine("catalog resave [apply]"); return 1; } var apply = args.Contains("apply"); + // Shipped file alone, on purpose: a resave restamps GameData/Aetheria.cc itself, so a composed catalog would write the packages into it. using var db = AetherDb.Open(catalogWritable: apply); return CatalogResaveCommand.Run(db.Cache, apply, Console.Out); } @@ -111,7 +112,7 @@ public static class Program // Designs by kind and manufacturer, designs no product sells, and products with authored role quality. private static int Census() { - var db = AetherDb.Open(); + var db = AetherDb.OpenBooted(); var items = db.Cache.GetAll().ToArray(); var products = db.Cache.GetAll() .OrderBy(p => db.Cache.RefOf(p).Key.Value, StringComparer.Ordinal).ToArray(); @@ -534,7 +535,7 @@ public static class Program // generation equips hardpoint gear first and only the first of those is guaranteed. private static int StationFit() { - var db = AetherDb.Open(); + var db = AetherDb.OpenBooted(); var bays = db.Cache.GetAll().ToArray(); var failures = 0; foreach (var hull in db.Cache.GetAll().Where(h => h.HullType == HullType.Station)) @@ -564,7 +565,7 @@ public static class Program // cannot place; the count is UnfillableHardpoints', and so is the exit code. private static int HardpointFit() { - using var db = AetherDb.Open(withMods: true); + using var db = AetherDb.OpenBooted(); var designs = db.Cache.GetAll().ToArray(); var sold = SoldDesigns(db.Cache.GetAll()); foreach (var hull in db.Cache.GetAll().OrderBy(h => h.HullType).ThenBy(h => h.Name, StringComparer.Ordinal)) @@ -768,7 +769,7 @@ public static class Program // Galaxy.NamePlaces falls back to catalogue designations for a faction without one. private static int Factions() { - var db = AetherDb.Open(); + var db = AetherDb.OpenBooted(); var products = db.Cache.GetAll().ToArray(); Console.WriteLine($"{"faction",-26} {"short",-13} {"places",-22} {"boss loadout",-14} {"influence",-9} {"doctrine",-10} products"); var broken = 0; @@ -800,7 +801,7 @@ public static class Program AetherDb db; try { - db = AetherDb.Open(withRun: true); + db = AetherDb.OpenBooted(withRun: true); } catch (Exception e) { @@ -857,7 +858,7 @@ public static class Program private static int Loadout(string[] args) { var seed = uint.TryParse(args.FirstOrDefault(), out var parsed) ? parsed : 1u; - var db = AetherDb.Open(); + var db = AetherDb.OpenBooted(); var settings = new GameplaySettings { DefaultEntitySettings = new EntitySettings(), @@ -1170,7 +1171,7 @@ public static class Program // against the catalog and not against names. private static int WeaponAmmo() { - var db = AetherDb.Open(); + var db = AetherDb.OpenBooted(); Console.WriteLine($"{"weapon",-28} {"behaviour",-20} {"energy",-11} {"mag",5} {"reload",6} ammo"); foreach (var item in db.Cache.GetAll().OrderBy(i => i.Name, StringComparer.Ordinal)) foreach (var w in item.Behaviors.OfType()) diff --git a/tools/AetherDb/ShipAuthoringCommands.cs b/tools/AetherDb/ShipAuthoringCommands.cs index ce4a14a54..4d7aff2e6 100644 --- a/tools/AetherDb/ShipAuthoringCommands.cs +++ b/tools/AetherDb/ShipAuthoringCommands.cs @@ -221,6 +221,7 @@ public static class ShipAuthoringCommands var judged = model != null && File.Exists(model) ? "records and model" : "records only, no model yet"; ShipAuthoringStore.ValidateLoaded(hull, ship, products); if (judged == "records and model") ShipModCatalog.Bind(hull, ship, products, Path.GetDirectoryName(full), full); + // Shipped file alone, on purpose: a package is judged against the shipped catalog it will be composed over, never against itself. // Compose's verdict on a package's bins and its offered hull's schematic; the author sees it here, before compose. using var catalog = products.Length > 0 || hull.HullType == HullType.Station ? AetherDb.Open().Cache : null; if (ShipModCatalog.MarketFault(catalog, ship, products) is { } fault) throw new InvalidOperationException(fault); @@ -233,6 +234,7 @@ public static class ShipAuthoringCommands // A shipped faction by record key, name or short name, from GameData/Aetheria.cc opened read-only: exactly one, or refused. internal static (CultRecordKey Key, string Name) ShippedFaction(string text) { + // Shipped file alone, on purpose: this resolves a shipped faction, the one a package names by key. using var catalog = AetherDb.Open().Cache; var matches = catalog.GetAll() .Where(faction => string.Equals(faction.Name, text, StringComparison.Ordinal) || @@ -246,6 +248,7 @@ public static class ShipAuthoringCommands // A shipped hull by name, from GameData/Aetheria.cc opened read-only, of one of the types allowed. private static HullData ShippedHull(string name, params HullType[] allowed) { + // Shipped file alone, on purpose: --like copies a shipped hull, not a package's. using var catalog = AetherDb.Open().Cache; var hull = catalog.GetAll().FirstOrDefault(candidate => candidate.Name == name) ?? throw new InvalidOperationException($"--like: the shipped catalog has no hull named '{name}'."); diff --git a/tools/AetherDb/ShipAuthoringPush.cs b/tools/AetherDb/ShipAuthoringPush.cs index cbea54503..b43ced165 100644 --- a/tools/AetherDb/ShipAuthoringPush.cs +++ b/tools/AetherDb/ShipAuthoringPush.cs @@ -361,6 +361,7 @@ public static class ShipAuthoringPush // A kind is judged whenever the request or the stored hull names one, so an invalid stored kind is never passed as fine; a // kindless draft that stays kindless is not, so it still takes stats and price (and needs no catalog). if (derived.Kind.IsSet() || held.Kind.IsSet()) + // Shipped file alone, on purpose: a station kind is the shipped catalog's, the rule Compose applies to a package. using (var catalog = AetherDb.Open().Cache) if (StationKinds.HullKindFault(catalog, derived) is { } fault) throw new InvalidOperationException($"{shipId}: {fault}"); FlatDiff(lines, key, HullFields(held), HullFields(derived)); diff --git a/tools/AetherDb/VerseGrammarCommand.cs b/tools/AetherDb/VerseGrammarCommand.cs index 883fe840d..c1ee102c0 100644 --- a/tools/AetherDb/VerseGrammarCommand.cs +++ b/tools/AetherDb/VerseGrammarCommand.cs @@ -52,6 +52,7 @@ public static class VerseGrammarCommand public static int Run(bool apply, string root = null) { + // Shipped file alone, on purpose: the grammar is authored into GameData/Aetheria.cc, and the dry run reads what apply would write. var catalogPath = Path.Combine(root ?? AetherDb.FindRoot(), "GameData", "Aetheria.cc"); using var cache = new CultCache(); cache.AddBackingStore(new SingleFileMessagePackBackingStore(catalogPath, !apply), AetheriaStores.CatalogTypes);