Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Languages: translations travel with the content to the sim, the CLI and every player (#1618, step 2) (supersedes #1884) (#2124)

Eyal Golana024b938af0a
diff --git a/.gitignore b/.gitignore
index d794ab186..4b385293f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -59,6 +59,8 @@ unity-*.log
captures/
unity/Assets/StreamingAssets/content/
unity/Assets/StreamingAssets/content.meta
+unity/Assets/StreamingAssets/translations/
+unity/Assets/StreamingAssets/translations.meta
unity/Assets/StreamingAssets/golden/
unity/Assets/StreamingAssets/golden.meta
unity/Assets/StreamingAssets/collection/
diff --git a/changelog.d/1618-transport.md b/changelog.d/1618-transport.md
new file mode 100644
index 000000000..50ef03470
--- /dev/null
+++ b/changelog.d/1618-transport.md
@@ -0,0 +1,5 @@
+- Translations travel with the content (#1618, step 2; designed by Orel Moshe Weinstock, @moshewe, in #1884): the sim,
+ the CLI (`--translations DIR`) and every player load `translations/` and check each language against the content it
+ translates, and the web boot gets them in the same `bundle.json` as the content, with no extra request. A
+ `translations/he/` must match the inline Hebrew of the events and content, which is still what the game shows.
+ Translations stay outside the content hash, so saves and goldens do not move (`docs/translations.md`, "Loading").
diff --git a/docs/translations.md b/docs/translations.md
index 2ad37001a..8c610dc3f 100644
--- a/docs/translations.md
+++ b/docs/translations.md
@@ -5,8 +5,9 @@ it doesnt cause any bugs, degregations or gaps"). English stays the source of re
`unity/Assets/UI/strings.en.yaml`. This page fixes the files, their keys and their order, so the tools, the sim and Unity
read and write them the same way.
-**Status (step 1 of #1618):** the contract and its tests only. The game still reads Hebrew from the inline `*_he` fields
-and `strings.he.yaml`; nothing has moved. `Translations.InlineHebrew` (sim) reads today's inline Hebrew as these files,
+**Status (steps 1 and 2 of #1618):** the contract and its tests, and the transport that brings `translations/` to the
+sim, the CLI and every player (below, "Loading"). The game still shows Hebrew from the inline `*_he` fields and
+`strings.he.yaml`; nothing has moved. `Translations.InlineHebrew` (sim) reads today's inline Hebrew as these files,
and the tests prove every value comes back unchanged. The tools' side (`tools/translate.py`, from #1604) joins the same
fixture check once #1604 has merged.
@@ -95,9 +96,46 @@ the check: a `ui.yaml` copied from another language with its code left behind pa
`Parse` itself does not require the key, because it is also used to read a file's shape in isolation — the check is a
separate call, made where a language is adopted.
+## Loading
+
+`ContentLoader.Load` reads `translations/` with the content (#1618, step 2) and keeps each language in
+`Content.Translations`, for the language picker of #1606 and the later steps of #1618. Nothing shows them yet.
+
+- **Where:** the `translations/` beside a folder named `content` (`TranslationLoader.Beside`): the repository's in the
+ editor and the CLI, `StreamingAssets/translations` in a desktop player. A content folder with another name, such as a
+ test fixture, has none. The CLI's `--translations DIR` names another folder; `--preview` does not take it.
+- **Players:** before every player build `ContentSync` copies `translations/` to `StreamingAssets/translations`, and
+ `ContentManifest` lists the files in `manifest.json` and packs their texts into `bundle.json` beside the content's, so
+ the web boot makes no extra request. `ContentManifest.Verify` checks the lists, the packed texts and the copy (byte for
+ byte) against the source, and `ContentSync` then loads the copy as a player would and the source as the editor does
+ (`ContentManifest.CheckLoads`), so a broken translation fails the build rather than the player's boot. `Copy` marks the
+ translations folder it makes (`.contentmanifest-copy`) and refuses to replace one it did not make.
+- **The folder:** a language folder holds only `ui.yaml`, `events.yaml` and `content.yaml`. Any other file or folder there,
+ or a folder that is not a language code, is refused rather than skipped. Files at the top (this folder's `README.md`)
+ are not languages, and hidden names (`.DS_Store`) are ignored.
+- **The checks:** each language is parsed, must name itself (`CheckDeclaredLanguage`), may not translate the advisors or
+ How to play unless it is Hebrew, translates only events that exist (an event a ruleset leaves out counts) and every
+ option of each, and keys only fields that `Fields` offers. A read failure is reported with its file.
+- **A stale translation:** when an event or a record changes so that a translation no longer matches it, the load is
+ refused (owner, 1 November 2026: "Refuse + say how to fix (Recommended)"), so nothing stale ships. The error says how to
+ unblock without a translator: update the entry, or delete it from the language's file, and that text shows in English.
+ Not for `he/`, which must equal the inline Hebrew.
+- **Hebrew:** a `translations/he/` that is present must match the inline Hebrew of the events and the content exactly:
+ the same events, texts, options and review flags, and the same fields and flags, none missing and none extra.
+ `he/ui.yaml` is not compared with `strings.he.yaml` yet; that comes with the UI move (step 4).
+- **Files a player does not ship:** `map/localities_1948.yaml` is a tool input; players get its baked TSV. A key into it
+ is checked where the file can be read (the editor, the CLI and the build) and skipped in a player.
+- **The hash:** translations are display text, so they stay outside `Content.Hash`: saves, the goldens and replay hashes
+ are the same with or without them.
+
+The UI strings still come from `strings.en.yaml` and `strings.he.yaml`; which catalogue the UI shows is #1606's
+(`GameRoot.Strings()`).
+
## The implementations and their tests
- `sim/Statecraft.Sim/Translations.cs`: keys, parsing, writing, `Resolve` and `InlineHebrew`.
+- `sim/Statecraft.Sim/TranslationLoader.cs`: finds, lists and checks `translations/` ("Loading", above);
+ `TranslationLoaderTests` covers it, and `GameInputsTests` (Unity EditMode) the copy, the bundle and the web boot.
- `sim/Statecraft.Sim/HebrewOverlay.cs`: puts a Hebrew set on the sim's typed `*He` properties. Unity reads the Hebrew of
`map/localities_1948.yaml`, `map/settlements_1948.yaml` and `map/units_1948.yaml` itself
(`HebrewOverlay.UnityReads`).
diff --git a/sim/Statecraft.Cli/Program.cs b/sim/Statecraft.Cli/Program.cs
index 2d0470b39..12b110d17 100644
--- a/sim/Statecraft.Cli/Program.cs
+++ b/sim/Statecraft.Cli/Program.cs
@@ -3,7 +3,9 @@ using Statecraft.Cli;
using Statecraft.Sim;
// Text front end for the headless sim.
-// dotnet run --project Statecraft.Cli -- [--content DIR] [--seed N] [--auto historical --turns N]
+// dotnet run --project Statecraft.Cli -- [--content DIR] [--translations DIR] [--seed N] [--auto historical --turns N]
+// --translations: the translations folder to load and check (#1618; default: the translations/ beside a folder named
+// content). Not taken by --preview, which runs against the real content and its own translations.
// dotnet run --project Statecraft.Cli -- --preview [--until YYYY-MM-DD] [--set key=value]... [--show id,id] [--every N]
// writer preview: the historical run with some rules.yaml values changed in memory, against the real content
// dotnet run --project Statecraft.Cli -- --release-gate [--content DIR] (exit 0 when shareable, 3 when not)
@@ -15,7 +17,7 @@ CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
string? Arg(string name) { var i = Array.IndexOf(args, name); return i >= 0 && i + 1 < args.Length ? args[i + 1] : null; }
-foreach (var flag in new[] { "--content", "--seed", "--turns", "--auto", "--until", "--set", "--show", "--every", "--timeline-course" })
+foreach (var flag in new[] { "--content", "--translations", "--seed", "--turns", "--auto", "--until", "--set", "--show", "--every", "--timeline-course" })
{
var at = Array.IndexOf(args, flag);
if (at >= 0 && (at + 1 >= args.Length || args[at + 1].StartsWith("--", StringComparison.Ordinal)))
@@ -39,6 +41,7 @@ string FindContent()
if (Array.IndexOf(args, "--preview") >= 0)
{
+ if (Arg("--translations") != null) { Console.Error.WriteLine("--translations is not taken by --preview"); return 1; }
try
{
var sets = new List<string>();
@@ -63,7 +66,14 @@ if (Array.IndexOf(args, "--preview") >= 0)
}
Content content;
-try { content = ContentLoader.Load(Arg("--content") ?? FindContent()); }
+try
+{
+ var contentDir = Arg("--content") ?? FindContent();
+ var translationsDir = Arg("--translations");
+ if (translationsDir != null && !Directory.Exists(translationsDir))
+ { Console.Error.WriteLine($"Content error: translations directory not found: {translationsDir}"); return 2; }
+ content = ContentLoader.Load(contentDir, translationsDir ?? TranslationLoader.Beside(contentDir));
+}
catch (DirectoryNotFoundException) { Console.Error.WriteLine("Content error: content directory not found (use --content <path>)"); return 2; }
catch (ContentException e) { Console.Error.WriteLine($"Content error: {e.Message}"); return 2; }
diff --git a/sim/Statecraft.Sim.Tests/TranslationLoaderTests.cs b/sim/Statecraft.Sim.Tests/TranslationLoaderTests.cs
new file mode 100644
index 000000000..1186c1bb9
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/TranslationLoaderTests.cs
@@ -0,0 +1,447 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using Statecraft.Sim;
+using YamlDotNet.RepresentationModel;
+
+/// <summary>#1618 step 2 (docs/translations.md, "Loading"): translations/ is read with the content, each language is checked
+/// against the content it translates, a translations/he/ must equal the inline Hebrew, and none of it reaches the hash.</summary>
+public class TranslationLoaderTests
+{
+ static string ContentDir => RealContentTests.ContentRoot();
+ static string RepoDir => Path.GetDirectoryName(ContentDir)!;
+ static string UiFile(string lang) => Path.Combine(RepoDir, "unity", "Assets", "UI", $"strings.{lang}.yaml");
+
+ /// <summary>Today's inline Hebrew as a translation set (step 1's reader), re-read each time so a test can change it.</summary>
+ static TranslationSet InlineHe() => Translations.InlineHebrew(ContentDir, UiFile("en"), UiFile("he"));
+
+ static Dictionary<string, string> Files(TranslationSet set)
+ {
+ var (ui, events, content) = Translations.Write(set);
+ var files = new Dictionary<string, string>();
+ if (set.Ui.Count > 0) files[$"{set.Lang}/ui.yaml"] = ui;
+ if (set.Events.Count > 0) files[$"{set.Lang}/events.yaml"] = events;
+ if (set.Content.Count > 0) files[$"{set.Lang}/content.yaml"] = content;
+ return files;
+ }
+
+ /// <summary>A scratch translations folder holding <paramref name="files"/> ("ro/ui.yaml" to its text).</summary>
+ static string Folder(Dictionary<string, string> files)
+ {
+ var dir = Path.Combine(Path.GetTempPath(), "statecraft-tl-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(dir);
+ foreach (var kv in files)
+ {
+ var path = Path.Combine(dir, kv.Key);
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ File.WriteAllText(path, kv.Value);
+ }
+ return dir;
+ }
+
+ static T WithFolder<T>(Dictionary<string, string> files, Func<string, T> body)
+ {
+ var dir = Folder(files);
+ try { return body(dir); }
+ finally { Directory.Delete(dir, true); }
+ }
+
+ static Content LoadReal(Dictionary<string, string> files) => WithFolder(files, dir => ContentLoader.Load(ContentDir, dir));
+ static ContentException Refused(Dictionary<string, string> files) => Assert.Throws<ContentException>(() => LoadReal(files));
+
+ const string Ro = "ui.lang: \"ro\"\n";
+
+ static string RoEvent(string id, params string[] options) =>
+ $"{id}:\n title: \"T\"\n text: \"X\"\n options:\n" + string.Concat(options.Select(o => $" {o}: \"O\"\n"));
+
+ static GameEvent RealEvent(Func<GameEvent, bool> pick) => ContentLoader.Load(ContentDir, null).Events.First(pick);
+
+ // ---- where the translations come from ----
+
+ [Fact]
+ public void BesideFindsTheFolderNextToAFolderNamedContent()
+ {
+ Assert.Equal(Path.Combine(RepoDir, "translations"), TranslationLoader.Beside(ContentDir));
+ Assert.Equal(Path.Combine(RepoDir, "translations"), TranslationLoader.Beside(ContentDir + Path.DirectorySeparatorChar));
+ Assert.Null(TranslationLoader.Beside(Path.Combine(Path.GetTempPath(), "fixture-1234")));
+ }
+
+ [Fact]
+ public void TheRealContentCarriesTheRepositorysTranslations()
+ {
+ var c = ContentLoader.Load(ContentDir);
+ var ro = Assert.Single(c.Translations, t => t.Lang == "ro");
+ Assert.Contains(ro.Ui, kv => kv.Key == Translations.LangKey && kv.Value == "ro");
+ Assert.Contains(ro.Events, e => e.Id == "first_truce");
+ Assert.Equal(c.Translations.Select(t => t.Lang).OrderBy(l => l, StringComparer.Ordinal), c.Translations.Select(t => t.Lang));
+ }
+
+ [Fact]
+ public void AFixtureNeverPicksUpTranslations()
+ {
+ var dir = Fixture.Write();
+ Directory.CreateDirectory(Path.Combine(Path.GetDirectoryName(dir)!, "translations", "ro"));
+ File.WriteAllText(Path.Combine(Path.GetDirectoryName(dir)!, "translations", "ro", "ui.yaml"), Ro);
+ try { Assert.Empty(ContentLoader.Load(dir).Translations); }
+ finally { Directory.Delete(Path.Combine(Path.GetDirectoryName(dir)!, "translations"), true); }
+ }
+
+ [Fact]
+ public void TranslationsStayOutsideTheHash()
+ {
+ var bare = ContentLoader.Load(ContentDir, null);
+ var withRo = ContentLoader.Load(ContentDir);
+ var withHe = LoadReal(Files(InlineHe()));
+ Assert.Empty(bare.Translations);
+ Assert.NotEmpty(withRo.Translations);
+ Assert.Equal("he", Assert.Single(withHe.Translations).Lang);
+ Assert.Equal(bare.Hash, withRo.Hash);
+ Assert.Equal(bare.Hash, withHe.Hash);
+ var game = Simulation.NewGame(bare, 7, Mode.Historical).Hash();
+ Assert.Equal(game, Simulation.NewGame(withRo, 7, Mode.Historical).Hash());
+ Assert.Equal(game, Simulation.NewGame(withHe, 7, Mode.Historical).Hash());
+ }
+
+ // ---- the folder ----
+
+ [Fact]
+ public void CollectListsLanguageFilesAndIgnoresHiddenMetadata()
+ {
+ var dir = Folder(new Dictionary<string, string>
+ {
+ ["README.md"] = "top-level files are not languages",
+ [".DS_Store"] = "", ["ro/.DS_Store"] = "", ["ro/.cache/x"] = "", [".git-keep/x"] = "",
+ ["ro/ui.yaml"] = Ro, ["ro/events.yaml"] = "", ["pt-BR/content.yaml"] = "",
+ });
+ try { Assert.Equal(new[] { "pt-BR/content.yaml", "ro/events.yaml", "ro/ui.yaml" }, TranslationLoader.Collect(dir)); }
+ finally { Directory.Delete(dir, true); }
+ Assert.Empty(TranslationLoader.Collect(null));
+ Assert.Empty(TranslationLoader.Collect(Path.Combine(Path.GetTempPath(), "no-such-" + Guid.NewGuid().ToString("N"))));
+ }
+
+ [Theory]
+ [InlineData("ro/notes.txt", "translations/ro/notes.txt: (file): ")]
+ [InlineData("ro/extra.yaml", "translations/ro/extra.yaml: (file): ")]
+ [InlineData("Romanian/ui.yaml", "translations/Romanian: (folder): not a language code")]
+ [InlineData("ro/old/ui.yaml", "translations/ro: (folder): a language folder has no sub-folders")]
+ public void CollectRefusesWhatIsNotALanguagesFile(string stray, string message)
+ {
+ var dir = Folder(new Dictionary<string, string> { ["ro/ui.yaml"] = Ro, [stray] = "" });
+ try { Assert.StartsWith(message, Assert.Throws<ContentException>(() => TranslationLoader.Collect(dir)).Message); }
+ finally { Directory.Delete(dir, true); }
+ }
+
+ [Fact]
+ public void AFolderThatCannotBeListedIsAContentError()
+ {
+ // A language folder that cannot be listed is reported as a content error naming the folder (the CLI's exit 2,
+ // ContentSync's BuildFailedException), not an unhandled exception (review C4).
+ if (OperatingSystem.IsWindows()) return;
+ var dir = Folder(new Dictionary<string, string> { ["ro/ui.yaml"] = Ro });
+ var ro = Path.Combine(dir, "ro");
+ File.SetUnixFileMode(ro, UnixFileMode.None);
+ try
+ {
+ try { Directory.GetFiles(ro); return; } // a superuser lists it anyway: nothing to test
+ catch (UnauthorizedAccessException) { }
+ var e = Assert.Throws<ContentException>(() => TranslationLoader.Collect(dir));
+ Assert.Equal(("translations", "(folder)"), (e.File, e.Field));
+ Assert.Contains(ro, e.Message);
+ }
+ finally
+ {
+ File.SetUnixFileMode(ro, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+ Directory.Delete(dir, true);
+ }
+ }
+
+ // ---- each language's checks ----
+
+ [Fact]
+ public void ALanguageMustNameItself()
+ {
+ Assert.Equal("translations/ro/ui.yaml: ui.lang: a UI language must name itself: add ui.lang: \"ro\"",
+ Refused(new Dictionary<string, string> { ["ro/events.yaml"] = RoEvent("first_truce", "accept", "refuse") }).Message);
+ Assert.Equal("translations/ro/ui.yaml: ui.lang: says 'fr' but the file is ro's",
+ Refused(new Dictionary<string, string> { ["ro/ui.yaml"] = "ui.lang: \"fr\"\n" }).Message);
+ }
+
+ [Theory]
+ [InlineData("advisor.defeat_economy")]
+ [InlineData("how_to_play.title")]
+ public void OnlyHebrewTranslatesTheAdvisorsAndHowToPlay(string key)
+ {
+ var e = Refused(new Dictionary<string, string> { ["ro/ui.yaml"] = Ro + $"{key}: \"x\"\n" });
+ Assert.Equal("translations/ro/ui.yaml", e.File);
+ Assert.Equal(key, e.Field);
+ }
+
+ [Fact]
+ public void AnEventTranslationNamesARealEventAndEveryOption()
+ {
+ var e = RealEvent(x => x.Options.Count >= 2);
+ var ids = e.Options.Select(o => o.Id).ToArray();
+ Assert.Single(LoadReal(new Dictionary<string, string> { ["ro/ui.yaml"] = Ro, ["ro/events.yaml"] = RoEvent(e.Id, ids) }).Translations);
+
+ var unknown = Refused(new Dictionary<string, string> { ["ro/ui.yaml"] = Ro, ["ro/events.yaml"] = RoEvent("no_such_event", "a") });
+ Assert.Equal(("translations/ro/events.yaml", "no_such_event"), (unknown.File, unknown.Field));
+ var missing = Refused(new Dictionary<string, string> { ["ro/ui.yaml"] = Ro, ["ro/events.yaml"] = RoEvent(e.Id, ids.Skip(1).ToArray()) });
+ Assert.Equal($"{e.Id}.options.{ids[0]}", missing.Field);
+ Assert.Contains("all or none", missing.Message);
+ var extra = Refused(new Dictionary<string, string> { ["ro/ui.yaml"] = Ro, ["ro/events.yaml"] = RoEvent(e.Id, ids.Append("no_such_option").ToArray()) });
+ Assert.Equal($"{e.Id}.options.no_such_option", extra.Field);
+ }
+
+ [Fact]
+ public void AStaleTranslationSaysHowToUnblock()
+ {
+ // Owner, 1 November 2026, on review C2: "Refuse + say how to fix (Recommended)". A writer who changes an event or a
+ // record can unblock without a translator: delete the stale entry and it shows in English.
+ var e = RealEvent(x => x.Options.Count >= 2);
+ var ids = e.Options.Select(o => o.Id).ToArray();
+ const string events = "or delete its block from translations/ro/events.yaml and the event shows in English";
+ foreach (var stale in new[] { RoEvent("no_such_event", "a"), RoEvent(e.Id, ids.Skip(1).ToArray()), RoEvent(e.Id, ids.Append("no_such_option").ToArray()) })
+ Assert.Contains(events, Refused(new Dictionary<string, string> { ["ro/ui.yaml"] = Ro, ["ro/events.yaml"] = stale }).Message);
+
+ var key = Translations.Fields("people.yaml", YamlRoot("people.yaml")).First().Key;
+ var renamed = new ContentKey(key.File, key.Path, "born").ToString();
+ Assert.Contains("or delete it from translations/ro/content.yaml and the field shows in English",
+ Refused(new Dictionary<string, string> { ["ro/ui.yaml"] = Ro, ["ro/content.yaml"] = $"\"{renamed}\":\n text: \"x\"\n" }).Message);
+
+ // Not for Hebrew: a he/ entry deleted is a missing one, since he/ must equal the inline Hebrew.
+ Assert.DoesNotContain("shows in English", Refused(new Dictionary<string, string>
+ { ["he/ui.yaml"] = "ui.lang: \"he\"\n", ["he/events.yaml"] = "no_such_event:\n title: \"א\"\n text: \"ב\"\n options:\n a: \"ג\"\n" }).Message);
+ }
+
+ [Fact]
+ public void AnEventARulesetLeavesOutCanStillBeTranslated()
+ {
+ // A gdd-0.3 fixture that leaves its one event out (gdd03-events.yaml): the event is still real content.
+ var f = Fixture.Gdd();
+ f["eras.yaml"] = f["eras.yaml"].Replace("loop: gdd", "loop: gdd, ruleset: gdd-0.3");
+ f[Gdd03BalanceCatalogue.FileName] = File.ReadAllText(Path.Combine(ContentDir, Gdd03BalanceCatalogue.FileName));
+ f["gdd03-events.yaml"] = "ruleset: gdd-0.3\nexclusions:\n - { id: probe, reason: Fixture }\n";
+ var dir = Fixture.Write(f, new Dictionary<string, string>
+ {
+ ["probe.yaml"] = "id: probe\ntitle: Fixture\ntext: Fixture.\nfrom: 1948-05-15\noptions:\n - id: ok\n text: Accept\n historical: true\n",
+ });
+ var c = WithFolder(new Dictionary<string, string> { ["ro/ui.yaml"] = Ro, ["ro/events.yaml"] = RoEvent("probe", "ok") }, t => ContentLoader.Load(dir, t));
+ Assert.DoesNotContain(c.Events, e => e.Id == "probe");
+ Assert.Equal("probe", Assert.Single(Assert.Single(c.Translations).Events).Id);
+ }
+
+ static YamlMappingNode YamlRoot(string rel)
+ {
+ var s = new YamlStream();
+ s.Load(new StringReader(File.ReadAllText(Path.Combine(ContentDir, rel))));
+ return (YamlMappingNode)s.Documents[0].RootNode;
+ }
+
+ [Fact]
+ public void AContentKeyMustBeATranslatableField()
+ {
+ var key = Translations.Fields("people.yaml", YamlRoot("people.yaml")).First().Key;
+ var good = $"\"{key}\":\n text: \"Nume\"\n";
+ Assert.Single(LoadReal(new Dictionary<string, string> { ["ro/ui.yaml"] = Ro, ["ro/content.yaml"] = good }).Translations);
+
+ var notOffered = new ContentKey(key.File, key.Path, "born").ToString();
+ var e = Refused(new Dictionary<string, string> { ["ro/ui.yaml"] = Ro, ["ro/content.yaml"] = $"\"{notOffered}\":\n text: \"x\"\n" });
+ Assert.Equal(("translations/ro/content.yaml", notOffered), (e.File, e.Field));
+ var noFile = Refused(new Dictionary<string, string> { ["ro/ui.yaml"] = Ro, ["ro/content.yaml"] = "\"nope.yaml#things.a.name\":\n text: \"x\"\n" });
+ Assert.Equal("nope.yaml#things.a.name", noFile.Field);
+ Assert.Contains("no content file nope.yaml", noFile.Message);
+ }
+
+ /// <summary>The readFile overload, as a player loads (WebGL): the real content without the files a player does not ship.</summary>
+ static Content LoadAsPlayer(Dictionary<string, string> translations, Func<string, string?>? content = null)
+ {
+ var events = Directory.GetFiles(Path.Combine(ContentDir, "events"), "*.yaml").Select(f => "events/" + Path.GetFileName(f)).ToList();
+ string? Disk(string rel) { var p = Path.Combine(ContentDir, rel); return File.Exists(p) ? File.ReadAllText(p) : null; }
+ return ContentLoader.Load(content ?? (rel => rel == "map/localities_1948.yaml" ? null : Disk(rel)), events,
+ rel => translations.TryGetValue(rel, out var t) ? t : null, translations.Keys.OrderBy(k => k, StringComparer.Ordinal).ToList());
+ }
+
+ [Fact]
+ public void AKeyIntoAFileAPlayerDoesNotShipIsCheckedWhereTheFileIsRead()
+ {
+ var key = Translations.Fields("map/localities_1948.yaml", YamlRoot("map/localities_1948.yaml")).First().Key;
+ var bad = new ContentKey(key.File, key.Path, "no_such_field").ToString();
+ var files = new Dictionary<string, string> { ["ro/ui.yaml"] = Ro, ["ro/content.yaml"] = $"\"{bad}\":\n text: \"x\"\n" };
+ Assert.Equal(bad, Refused(files).Field); // on disk: the editor, the CLI and the build gate
+ Assert.Single(LoadAsPlayer(files).Translations); // a player has only the baked TSV, so the key is not checked there
+ }
+
+ // ---- translations/he/ must equal the inline Hebrew ----
+
+ [Fact]
+ public void AHebrewSetEqualToTheInlineHebrewLoads()
+ {
+ var he = Assert.Single(LoadReal(Files(InlineHe())).Translations);
+ Assert.Equal(Translations.Write(InlineHe()), Translations.Write(he));
+ Assert.Equal("he", Assert.Single(LoadAsPlayer(Files(InlineHe())).Translations).Lang);
+ }
+
+ [Fact]
+ public void EveryContentFileWithInlineHebrewIsCompared()
+ {
+ var compared = new HashSet<string>(HebrewOverlay.Files.Concat(HebrewOverlay.UnityReads), StringComparer.Ordinal);
+ var withHebrew = InlineHe().Content.Select(t => ContentKey.TryParse(t.Key)!.File).Distinct();
+ Assert.All(withHebrew, f => Assert.Contains(f, compared));
+ }
+
+ [Fact]
+ public void AHebrewSetMissingAFileUnityReadsIsRefused()
+ {
+ // A file whose Hebrew Unity reads itself (HebrewOverlay.UnityReads, not a sim binding), with every key into it
+ // dropped from he/: the comparison must still walk the file and find its fields missing (review C7).
+ var he = InlineHe();
+ var file = HebrewOverlay.UnityReads.Except(HebrewOverlay.Files)
+ .First(f => he.Content.Any(t => ContentKey.TryParse(t.Key)!.File == f));
+ var first = he.Content.First(t => ContentKey.TryParse(t.Key)!.File == file).Key;
+ he.Content.RemoveAll(t => ContentKey.TryParse(t.Key)!.File == file);
+ var e = Refused(Files(he));
+ Assert.Equal(("translations/he/content.yaml", first), (e.File, e.Field));
+ Assert.Contains("missing", e.Message);
+ }
+
+ [Fact]
+ public void AHebrewEventThatDiffersOrIsMissingIsRefused()
+ {
+ var he = InlineHe();
+ he.Events[0].Title += "x";
+ var e = Refused(Files(he));
+ Assert.Equal(("translations/he/events.yaml", InlineHe().Events[0].Id), (e.File, e.Field));
+ Assert.Contains("differs", e.Message);
+
+ he = InlineHe();
+ he.Events[0].Options[0] = new KeyValuePair<string, string>(he.Events[0].Options[0].Key, he.Events[0].Options[0].Value + "x");
+ Assert.Contains("differs", Refused(Files(he)).Message);
+
+ he = InlineHe();
+ he.Events[0].Review = he.Events[0].Review == "" ? "agent-checked" : "";
+ Assert.Contains("differs", Refused(Files(he)).Message);
+
+ he = InlineHe();
+ var dropped = he.Events[0].Id;
+ he.Events.RemoveAt(0);
+ e = Refused(Files(he));
+ Assert.Equal(dropped, e.Field);
+ Assert.Contains("missing", e.Message);
+ }
+
+ [Fact]
+ public void AHebrewContentFieldThatDiffersIsMissingOrHasNoInlineHebrewIsRefused()
+ {
+ var he = InlineHe();
+ var first = he.Content[0].Key;
+ he.Content[0].Text += "x";
+ var e = Refused(Files(he));
+ Assert.Equal(("translations/he/content.yaml", first), (e.File, e.Field));
+ Assert.Contains("differs", e.Message);
+
+ he = InlineHe();
+ he.Content[0].Review = he.Content[0].Review == "" ? "agent-checked" : "";
+ Assert.Contains("differs", Refused(Files(he)).Message);
+
+ he = InlineHe();
+ he.Content.RemoveAt(0);
+ e = Refused(Files(he));
+ Assert.Equal(first, e.Field);
+ Assert.Contains("missing", e.Message);
+
+ // A field offered for translation that has no inline Hebrew yet.
+ var bare = HebrewOverlay.Files.Concat(HebrewOverlay.UnityReads).Where(f => File.Exists(Path.Combine(ContentDir, f)))
+ .SelectMany(f => Translations.Fields(f, YamlRoot(f))).First(f => f.Hebrew == "").Key.ToString();
+ he = InlineHe();
+ he.Content.Add(new ContentTranslation { Key = bare, Text = "שם" });
+ e = Refused(Files(he));
+ Assert.Equal(bare, e.Field);
+ Assert.Contains("no inline Hebrew", e.Message);
+ }
+
+ [Fact]
+ public void AHebrewEventWithNoInlineHebrewIsRefused()
+ {
+ // A fixture event with no Hebrew at all, so the case cannot vanish when the real content gains Hebrew everywhere.
+ var dir = Fixture.Write(events: new Dictionary<string, string> { ["drought.yaml"] = ValidationTests.Event });
+ var plain = ContentLoader.Load(dir, null).Events.Single(x => x.Id == "drought");
+ Assert.Equal("", plain.TitleHe);
+ var files = new Dictionary<string, string>
+ {
+ ["he/ui.yaml"] = "ui.lang: \"he\"\n",
+ ["he/events.yaml"] = "drought:\n title: \"בצורת\"\n text: \"טקסט\"\n options:\n ration: \"קיצוב\"\n wait: \"המתנה\"\n",
+ };
+ var e = WithFolder(files, t => Assert.Throws<ContentException>(() => ContentLoader.Load(dir, t)));
+ Assert.Equal(("translations/he/events.yaml", "drought"), (e.File, e.Field));
+ Assert.Contains("no inline Hebrew to match", e.Message);
+ }
+
+
+ // ---- read failures keep their file ----
+
+ [Fact]
+ public void ATranslationThatCannotBeReadNamesItsFile()
+ {
+ var files = new Dictionary<string, string> { ["ro/ui.yaml"] = Ro };
+ foreach (var fault in new Exception[] { new IOException("disk"), new UnauthorizedAccessException("denied") })
+ {
+ var events = Directory.GetFiles(Path.Combine(ContentDir, "events"), "*.yaml").Select(f => "events/" + Path.GetFileName(f)).ToList();
+ string? Disk(string rel) { var p = Path.Combine(ContentDir, rel); return File.Exists(p) ? File.ReadAllText(p) : null; }
+ var e = Assert.Throws<ContentException>(() => ContentLoader.Load(Disk, events, _ => throw fault, files.Keys.ToList()));
+ Assert.Equal(("translations/ro/ui.yaml", "(file)"), (e.File, e.Field));
+ Assert.Contains(fault.Message, e.Message);
+ }
+ }
+
+ [Fact]
+ public void AContentFileThatCannotBeReadForTheChecksNamesItsFile()
+ {
+ // map/localities_1948.yaml is read only by the translation checks, so the fault is in that reader.
+ var key = Translations.Fields("map/localities_1948.yaml", YamlRoot("map/localities_1948.yaml")).First().Key.ToString();
+ var files = new Dictionary<string, string> { ["ro/ui.yaml"] = Ro, ["ro/content.yaml"] = $"\"{key}\":\n text: \"x\"\n" };
+ foreach (var fault in new Exception[] { new IOException("disk"), new UnauthorizedAccessException("denied") })
+ {
+ string? Content(string rel)
+ {
+ if (rel == "map/localities_1948.yaml") throw fault;
+ var p = Path.Combine(ContentDir, rel);
+ return File.Exists(p) ? File.ReadAllText(p) : null;
+ }
+ var e = Assert.Throws<ContentException>(() => LoadAsPlayer(files, Content));
+ Assert.Equal(("map/localities_1948.yaml", "(file)"), (e.File, e.Field));
+ }
+ }
+
+ // ---- the CLI ----
+
+ static (int Code, string Output) Cli(params string[] args)
+ {
+ var info = new ProcessStartInfo("dotnet") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
+ info.ArgumentList.Add(typeof(Statecraft.Cli.InputParse).Assembly.Location);
+ foreach (var a in args) info.ArgumentList.Add(a);
+ using var child = Process.Start(info)!;
+ var stdout = child.StandardOutput.ReadToEndAsync(); var stderr = child.StandardError.ReadToEndAsync();
+ if (!child.WaitForExit(120_000)) { child.Kill(entireProcessTree: true); throw new TimeoutException(string.Join(" ", args)); }
+ return (child.ExitCode, stdout.Result + stderr.Result);
+ }
+
+ [Fact]
+ public void TheCliTakesATranslationsFolderAndRefusesABadOne()
+ {
+ var missing = Path.Combine(Path.GetTempPath(), "no-such-" + Guid.NewGuid().ToString("N"));
+ var (code, output) = Cli("--content", ContentDir, "--translations", missing, "--auto", "historical", "--turns", "1");
+ Assert.Equal(2, code);
+ Assert.Contains($"translations directory not found: {missing}", output);
+
+ (code, output) = WithFolder(new Dictionary<string, string> { ["ro/ui.yaml"] = "ui.lang: \"fr\"\n" },
+ dir => Cli("--content", ContentDir, "--translations", dir, "--auto", "historical", "--turns", "1"));
+ Assert.Equal(2, code);
+ Assert.Contains("Content error: translations/ro/ui.yaml: ui.lang: says 'fr'", output);
+
+ (code, output) = Cli("--preview", "--translations", ContentDir);
+ Assert.Equal(1, code);
+ Assert.Contains("--translations", output);
+ }
+}
diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.cs
index 33a5c25eb..58691ed6c 100644
--- a/sim/Statecraft.Sim/Content.cs
+++ b/sim/Statecraft.Sim/Content.cs
@@ -1341,6 +1341,9 @@ namespace Statecraft.Sim
public List<MoneyAccount> Money = new List<MoneyAccount>();
public List<PopulationAnchor> PopulationAnchors = new List<PopulationAnchor>();
public List<GameEvent> Events = new List<GameEvent>();
+ /// <summary>Every language in translations/ (#1618 step 2, docs/translations.md "Loading"), by code, each checked
+ /// against this content. Display text, so outside <see cref="Hash"/>; nothing shows it yet.</summary>
+ public List<TranslationSet> Translations = new List<TranslationSet>();
List<MapHex> _hexes = new List<MapHex>();
Dictionary<(int, int), MapHex> _hexIndex = new Dictionary<(int, int), MapHex>();
diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.cs
index 13fe38b93..e3f176685 100644
--- a/sim/Statecraft.Sim/ContentLoader.cs
+++ b/sim/Statecraft.Sim/ContentLoader.cs
@@ -310,19 +310,38 @@ namespace Statecraft.Sim
/// ("people.yaml", "events/x.yaml") and returns the file's text, or null when it is missing. This is the
/// entry point for platforms without a file system (a WebGL build reads StreamingAssets through a URL).
/// <paramref name="eventFiles"/> are the event files, relative to the content root; they load in ordinal order.</summary>
- public static Content Load(Func<string, string?> readFile, IEnumerable<string> eventFiles)
+ public static Content Load(Func<string, string?> readFile, IEnumerable<string> eventFiles) =>
+ Load(readFile, eventFiles, _ => null, Enumerable.Empty<string>());
+
+ /// <summary>Loads content as the overload above does, with the translations <paramref name="translationFiles"/> lists
+ /// ("ro/ui.yaml", as TranslationLoader.Collect gives them), which <paramref name="readTranslation"/> reads relative to
+ /// the translations folder (#1618 step 2). Each language is checked against the content and kept in
+ /// <see cref="Content.Translations"/>, outside the hash.</summary>
+ public static Content Load(Func<string, string?> readFile, IEnumerable<string> eventFiles,
+ Func<string, string?> readTranslation, IEnumerable<string> translationFiles)
{
if (readFile == null) throw new ArgumentNullException(nameof(readFile));
if (eventFiles == null) throw new ArgumentNullException(nameof(eventFiles));
+ if (readTranslation == null) throw new ArgumentNullException(nameof(readTranslation));
+ if (translationFiles == null) throw new ArgumentNullException(nameof(translationFiles));
var read = new List<(string rel, string text)>();
var inner = readFile;
+ static string? NoMark(string? text) =>
+ text != null && text.Length > 0 && text[0] == '\uFEFF' ? text.Substring(1) : text; // a byte-order mark is not content
readFile = rel =>
{
- var text = inner(rel);
- if (text != null && text.Length > 0 && text[0] == '\uFEFF') text = text.Substring(1); // a byte-order mark is not content
+ var text = NoMark(inner(rel));
if (text != null) read.Add((rel, text));
return text;
};
+ // The translation checks read content files outside the hash (a translation is display text, and may name a
+ // file the sim never reads), and a read failure keeps its file rather than passing for a missing file.
+ string? Unhashed(string rel)
+ {
+ try { return NoMark(inner(rel)); }
+ catch (IOException e) { throw new ContentException(rel, "(file)", e.Message); }
+ catch (UnauthorizedAccessException e) { throw new ContentException(rel, "(file)", e.Message); }
+ }
var c = new Content();
c.Offices = Read<OfficesFile>(readFile, "offices.yaml").Offices;
c.Parties = Read<PartiesFile>(readFile, "parties.yaml").Parties;
@@ -383,6 +402,7 @@ namespace Statecraft.Sim
// set without objectives has no file.
// In the file's order, not sorted: it is the order objectives record and their cards fire in (R-OBJ-007, Q-CARD-2).
c.Objectives = ReadOptional<ObjectivesFile>(readFile, ObjectivesFileName)?.Objectives ?? new List<Objective>();
+ var allEvents = c.Events.ToList(); // before a ruleset leaves some out: their translations still name real events
// Leave malformed legacy era records to the original validation path (Ruleset needs Systems).
if (c.Eras.Count > 0 && c.Eras[0].Systems != null && c.Ruleset == SaveGame.Gdd03Ruleset)
{
@@ -418,6 +438,7 @@ namespace Statecraft.Sim
EventRules.ValidateStructured(c); // R-EFX-006: after the GDD records it names are read
c.BuildWindows();
c.Hash = HashOf(read);
+ c.Translations = TranslationLoader.Load(allEvents, Unhashed, readTranslation, translationFiles);
return c;
}
@@ -494,8 +515,13 @@ namespace Statecraft.Sim
return string.Concat(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(sb.ToString())).Select(b => b.ToString("x2", System.Globalization.CultureInfo.InvariantCulture)));
}
- /// <summary>Loads content from a directory: every events/*.yaml file is an event.</summary>
- public static Content Load(string contentRoot)
+ /// <summary>Loads content from a directory: every events/*.yaml file is an event. The translations are those beside it
+ /// (TranslationLoader.Beside: translations/ next to a folder named content), when there are any.</summary>
+ public static Content Load(string contentRoot) => Load(contentRoot, TranslationLoader.Beside(contentRoot));
+
+ /// <summary>Loads content from a directory with the translations in <paramref name="translationsRoot"/> (none when it
+ /// is null or missing).</summary>
+ public static Content Load(string contentRoot, string? translationsRoot)
{
var eventsDir = Path.Combine(contentRoot, "events");
var eventFiles = Directory.Exists(eventsDir)
@@ -505,7 +531,11 @@ namespace Statecraft.Sim
{
var path = Path.Combine(contentRoot, rel);
return File.Exists(path) ? File.ReadAllText(path) : null;
- }, eventFiles);
+ }, eventFiles, rel =>
+ {
+ var path = Path.Combine(translationsRoot!, rel); // only called for a file Collect found there
+ return File.Exists(path) ? File.ReadAllText(path) : null;
+ }, TranslationLoader.Collect(translationsRoot));
// Only this overload can list the directory. The readFile overload (WebGL) cannot, so a misnamed file is caught
// here and by RealContentTests before anything ships.
var rulesDir = Path.Combine(contentRoot, "rules");
diff --git a/sim/Statecraft.Sim/HebrewOverlay.cs b/sim/Statecraft.Sim/HebrewOverlay.cs
index b365ab34c..025670d24 100644
--- a/sim/Statecraft.Sim/HebrewOverlay.cs
+++ b/sim/Statecraft.Sim/HebrewOverlay.cs
@@ -51,6 +51,9 @@ namespace Statecraft.Sim
"map/localities_1948.yaml", "map/settlements_1948.yaml", "map/units_1948.yaml", "map/region_names_he.yaml",
};
+ /// <summary>The content files the typed records hold Hebrew from.</summary>
+ internal static IEnumerable<string> Files => Bindings.Select(b => b.File).Distinct();
+
/// <summary>The (type, property) pairs the overlay fills, events included.</summary>
public static IEnumerable<(Type Type, string Property)> Covered =>
Bindings.Select(b => (b.Value.DeclaringType!, b.Value.Name))
diff --git a/sim/Statecraft.Sim/TranslationLoader.cs b/sim/Statecraft.Sim/TranslationLoader.cs
new file mode 100644
index 000000000..71dc881e3
--- /dev/null
+++ b/sim/Statecraft.Sim/TranslationLoader.cs
@@ -0,0 +1,219 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using YamlDotNet.Core;
+using YamlDotNet.RepresentationModel;
+
+namespace Statecraft.Sim
+{
+ /// <summary>Brings translations/ to the sim with the content (#1618 step 2; docs/translations.md, "Loading"). Each
+ /// language is parsed and checked against the content it translates, then kept in <see cref="Content.Translations"/>,
+ /// outside the content hash. Nothing shows them yet: the game's Hebrew still comes from the inline fields, and a
+ /// translations/he/ that is present must equal them, so the later steps can switch the source with no text changing.</summary>
+ public static class TranslationLoader
+ {
+ public const string Folder = "translations";
+
+ static readonly string[] LanguageFiles = { Translations.UiFile, Translations.EventsFile, Translations.ContentFile };
+
+ /// <summary>UI keys only Hebrew may translate, for now (owner, 24 October 2026, #1604): the advisors and How to play.</summary>
+ public static readonly IReadOnlyList<string> HebrewOnlyUi = new[] { "advisor.", "how_to_play." };
+
+ /// <summary>translations/ beside a folder named content: the repository's beside content/, StreamingAssets/translations
+ /// beside StreamingAssets/content. Null for a content folder with another name, such as a test fixture, so a fixture
+ /// never picks up translations from wherever it happens to be written.</summary>
+ public static string? Beside(string contentRoot)
+ {
+ var dir = Path.GetFullPath(contentRoot).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
+ return Path.GetFileName(dir) == "content" ? Path.Combine(Path.GetDirectoryName(dir)!, Folder) : null;
+ }
+
+ static bool Hidden(string path) => Path.GetFileName(path).StartsWith(".", StringComparison.Ordinal);
+
+ /// <summary>The language files under <paramref name="translationsRoot"/>, as "ro/ui.yaml", in ordinal order (none when
+ /// it is null or missing). Files at the top (README.md) are not languages, and hidden names (.DS_Store) are system
+ /// metadata, so both are passed over. Anything else that is not a language's ui.yaml, events.yaml or content.yaml
+ /// is refused rather than skipped, so a misnamed file cannot drop out unnoticed. A folder that cannot be listed is a
+ /// <see cref="ContentException"/> too, so it is reported as a content error.</summary>
+ public static List<string> Collect(string? translationsRoot)
+ {
+ try { return CollectFiles(translationsRoot); }
+ catch (IOException e) { throw new ContentException(Folder, "(folder)", e.Message); }
+ catch (UnauthorizedAccessException e) { throw new ContentException(Folder, "(folder)", e.Message); }
+ }
+
+ static List<string> CollectFiles(string? translationsRoot)
+ {
+ var files = new List<string>();
+ if (translationsRoot == null || !Directory.Exists(translationsRoot)) return files;
+ foreach (var dir in Directory.GetDirectories(translationsRoot).Where(d => !Hidden(d)))
+ {
+ var lang = Path.GetFileName(dir);
+ if (!Translations.IsLanguage(lang))
+ throw new ContentException($"{Folder}/{lang}", "(folder)", "not a language code (fr, ar, pt-BR)");
+ if (Directory.GetDirectories(dir).Any(d => !Hidden(d)))
+ throw new ContentException($"{Folder}/{lang}", "(folder)", "a language folder has no sub-folders");
+ foreach (var file in Directory.GetFiles(dir).Where(f => !Hidden(f)))
+ {
+ var name = Path.GetFileName(file);
+ if (!LanguageFiles.Contains(name))
+ throw new ContentException($"{Folder}/{lang}/{name}", "(file)", $"a language has only {string.Join(", ", LanguageFiles)}");
+ files.Add(lang + "/" + name);
+ }
+ }
+ files.Sort(StringComparer.Ordinal);
+ return files;
+ }
+
+ /// <summary>Reads and checks every language in <paramref name="files"/> (as <see cref="Collect"/> lists them, or as a
+ /// player's manifest does). <paramref name="readContent"/> reads a content file without hashing it (null: not there);
+ /// <paramref name="events"/> are every parsed event, including those the ruleset leaves out.</summary>
+ internal static List<TranslationSet> Load(IReadOnlyList<GameEvent> events, Func<string, string?> readContent,
+ Func<string, string?> readTranslation, IEnumerable<string> files)
+ {
+ var languages = new SortedDictionary<string, HashSet<string>>(StringComparer.Ordinal);
+ foreach (var f in files)
+ {
+ var parts = (f ?? "").Split('/');
+ if (parts.Length != 2 || !Translations.IsLanguage(parts[0]) || !LanguageFiles.Contains(parts[1]))
+ throw new ContentException($"{Folder}/{f}", "(file)", "not <language>/ui.yaml, events.yaml or content.yaml");
+ if (!languages.TryGetValue(parts[0], out var names)) languages[parts[0]] = names = new HashSet<string>(StringComparer.Ordinal);
+ if (!names.Add(parts[1])) throw new ContentException($"{Folder}/{f}", "(file)", "listed twice");
+ }
+
+ var parsed = new Dictionary<string, YamlNode?>(StringComparer.Ordinal);
+ YamlNode? Yaml(string rel)
+ {
+ if (parsed.TryGetValue(rel, out var cached)) return cached;
+ var text = readContent(rel);
+ YamlNode? root = null;
+ if (text != null)
+ {
+ var stream = new YamlStream();
+ try { stream.Load(new StringReader(text)); }
+ catch (YamlException e) { throw new ContentException(rel, $"line {e.Start.Line}", e.InnerException?.Message ?? e.Message); }
+ root = stream.Documents.Count > 0 ? stream.Documents[0].RootNode : new YamlMappingNode();
+ }
+ return parsed[rel] = root;
+ }
+
+ var sets = new List<TranslationSet>();
+ foreach (var language in languages)
+ {
+ string? Text(string name)
+ {
+ if (!language.Value.Contains(name)) return null;
+ var where = $"{Folder}/{language.Key}/{name}";
+ try { return readTranslation(language.Key + "/" + name) ?? throw new ContentException(where, "(file)", "listed but missing"); }
+ catch (IOException e) { throw new ContentException(where, "(file)", e.Message); }
+ catch (UnauthorizedAccessException e) { throw new ContentException(where, "(file)", e.Message); }
+ }
+ var set = Translations.Parse(language.Key, Text(Translations.UiFile), Text(Translations.EventsFile), Text(Translations.ContentFile));
+ Translations.CheckDeclaredLanguage(set);
+ CheckUi(set);
+ CheckEvents(set, events);
+ CheckContent(set, Yaml);
+ if (set.Lang == Translations.Hebrew) CheckEqualsInlineHebrew(set, events, Yaml);
+ sets.Add(set);
+ }
+ return sets;
+ }
+
+ static string Where(TranslationSet set, string file) => $"{Folder}/{set.Lang}/{file}";
+
+ static void CheckUi(TranslationSet set)
+ {
+ if (set.Lang == Translations.Hebrew) return;
+ foreach (var kv in set.Ui)
+ if (HebrewOnlyUi.Any(p => kv.Key.StartsWith(p, StringComparison.Ordinal)))
+ throw new ContentException(Where(set, Translations.UiFile), kv.Key,
+ "the advisors and How to play stay English or Hebrew only, for now (owner, 24 October 2026, #1604)");
+ }
+
+ /// <summary>How a writer unblocks a stale translation without a translator (owner, 1 November 2026: "Refuse + say how
+ /// to fix (Recommended)"): delete the entry and the text shows in English. Not for Hebrew, whose files must equal the
+ /// inline Hebrew, so a deleted entry is a missing one.</summary>
+ static string Unblock(TranslationSet set, string where, string entry, string what) =>
+ set.Lang == Translations.Hebrew ? "" : $"; update the entry, or delete {entry} from {where} and the {what} shows in English";
+
+ /// <summary>A translated event exists and translates exactly its options: an event is all or none, so a card never
+ /// shows one button in English.</summary>
+ static void CheckEvents(TranslationSet set, IReadOnlyList<GameEvent> events)
+ {
+ var where = Where(set, Translations.EventsFile);
+ var unblock = Unblock(set, where, "its block", "event");
+ foreach (var t in set.Events)
+ {
+ var e = events.FirstOrDefault(x => x.Id == t.Id) ?? throw new ContentException(where, t.Id, "no event has this id" + unblock);
+ foreach (var o in t.Options)
+ if (!e.Options.Any(x => x.Id == o.Key)) throw new ContentException(where, $"{t.Id}.options.{o.Key}", "the event has no such option" + unblock);
+ foreach (var o in e.Options)
+ if (!t.Options.Any(x => x.Key == o.Id))
+ throw new ContentException(where, $"{t.Id}.options.{o.Id}", "required: a translated event translates every option (all or none)" + unblock);
+ }
+ }
+
+ /// <summary>A content key names a field <see cref="Translations.Fields"/> offers in its file. A file a player does not
+ /// ship (<see cref="HebrewOverlay.UnityReads"/>, read there in baked form) is checked where it can be read: the editor,
+ /// the CLI and the build gate.</summary>
+ static void CheckContent(TranslationSet set, Func<string, YamlNode?> yaml)
+ {
+ var where = Where(set, Translations.ContentFile);
+ var unblock = Unblock(set, where, "it", "field");
+ var offered = new Dictionary<string, HashSet<string>?>(StringComparer.Ordinal);
+ foreach (var t in set.Content)
+ {
+ var file = ContentKey.TryParse(t.Key)!.File; // Parse has checked the key's shape
+ if (!offered.TryGetValue(file, out var keys))
+ {
+ var root = yaml(file);
+ if (root == null && !HebrewOverlay.UnityReads.Contains(file)) throw new ContentException(where, t.Key, $"no content file {file}" + unblock);
+ offered[file] = keys = root == null ? null : new HashSet<string>(Translations.Fields(file, root).Select(f => f.Key.ToString()), StringComparer.Ordinal);
+ }
+ if (keys != null && !keys.Contains(t.Key))
+ throw new ContentException(where, t.Key, "not a translatable field: it has no Hebrew form in its file (docs/translations.md, \"Content keys\")" + unblock);
+ }
+ }
+
+ const string Authoritative = "the inline Hebrew stays authoritative until a later step of #1618 moves it";
+
+ /// <summary>translations/he/ equals the inline Hebrew: the same events with the same title, text, options and review
+ /// flag, and the same content fields with the same text and flag, none missing and none extra. A file a player does
+ /// not ship is compared where it can be read.</summary>
+ static void CheckEqualsInlineHebrew(TranslationSet he, IReadOnlyList<GameEvent> events, Func<string, YamlNode?> yaml)
+ {
+ var where = Where(he, Translations.EventsFile);
+ var inline = events.Where(e => e.TitleHe != "").ToDictionary(e => e.Id, StringComparer.Ordinal);
+ foreach (var t in he.Events)
+ {
+ if (!inline.TryGetValue(t.Id, out var e)) throw new ContentException(where, t.Id, "the event has no inline Hebrew to match");
+ var same = t.Title == e.TitleHe && t.Text == e.TextHe && t.Review == e.TextHeReview
+ && t.Options.All(o => e.Options.Single(x => x.Id == o.Key).TextHe == o.Value);
+ if (!same) throw new ContentException(where, t.Id, "differs from the event's inline Hebrew; " + Authoritative);
+ }
+ var translated = new HashSet<string>(he.Events.Select(t => t.Id), StringComparer.Ordinal);
+ foreach (var id in inline.Keys.OrderBy(id => id, StringComparer.Ordinal))
+ if (!translated.Contains(id)) throw new ContentException(where, id, "missing: the event has inline Hebrew");
+
+ where = Where(he, Translations.ContentFile);
+ var mine = he.Content.ToDictionary(t => t.Key, StringComparer.Ordinal);
+ var files = HebrewOverlay.Files.Concat(HebrewOverlay.UnityReads).Concat(mine.Keys.Select(k => ContentKey.TryParse(k)!.File))
+ .Distinct().OrderBy(f => f, StringComparer.Ordinal);
+ foreach (var file in files)
+ {
+ var root = yaml(file);
+ if (root == null) continue; // not shipped to a player (checked on disk), or not in this content set
+ var fields = Translations.Fields(file, root).ToList();
+ foreach (var f in fields.Where(f => f.Hebrew != ""))
+ {
+ var key = f.Key.ToString();
+ if (!mine.TryGetValue(key, out var t)) throw new ContentException(where, key, "missing: the field has inline Hebrew");
+ if (t.Text != f.Hebrew || t.Review != f.Review) throw new ContentException(where, key, "differs from the inline Hebrew; " + Authoritative);
+ }
+ foreach (var f in fields.Where(f => f.Hebrew == "" && mine.ContainsKey(f.Key.ToString())))
+ throw new ContentException(where, f.Key.ToString(), "the field has no inline Hebrew to match");
+ }
+ }
+ }
+}
diff --git a/translations/README.md b/translations/README.md
index 507d06dbe..70e9cac0d 100644
--- a/translations/README.md
+++ b/translations/README.md
@@ -1,9 +1,9 @@
# translations/
Translations into languages other than English and Hebrew, written by `tools/translate.py` ([tools/README.md](../tools/README.md)).
-The game does not read these files yet: loading them needs a change to the sim loader, the content schemas and
-`unity/Assets/Scripts/UI/UiLanguage.cs`, and a language is offered to players through the start-of-game language
-picker and the Settings menu (#1606). English and Hebrew stay where they are, in `content/` and `unity/Assets/UI/`.
+The game loads and checks these files with the content ([docs/translations.md](../docs/translations.md), "Loading"),
+but does not show them yet: a language is offered to players through the start-of-game language picker and the Settings
+menu (#1606). English and Hebrew stay where they are, in `content/` and `unity/Assets/UI/`.
Each language has a folder named by its code (`ro`, `fr`, `pt-BR`), with up to three files:
diff --git a/unity/Assets/Editor/ContentSync.cs b/unity/Assets/Editor/ContentSync.cs
index 14e717268..d35160b5a 100644
--- a/unity/Assets/Editor/ContentSync.cs
+++ b/unity/Assets/Editor/ContentSync.cs
@@ -1,5 +1,8 @@
+using System;
+using System.Collections.Generic;
using System.IO;
using Statecraft.Game.Boot;
+using Statecraft.Sim;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
@@ -8,7 +11,8 @@ namespace Statecraft.Game.EditorTools
{
/// <summary>Copies the repository's content/ into Assets/StreamingAssets/content with a manifest.json and a bundle.json
/// (every text in one file, which the web boot fetches: #1054) before every player build (git-ignored output), so
- /// players read the same content the editor reads from the repo.
+ /// players read the same content the editor reads from the repo. translations/ is copied beside it, to
+ /// Assets/StreamingAssets/translations, and packed into the same bundle (#1618 step 2).
/// Run alone: Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod Statecraft.Game.EditorTools.ContentSync.Sync
/// (copies as for a release player: the armistice lines' draft features left out).</summary>
public sealed class ContentSync : IPreprocessBuildWithReport
@@ -27,10 +31,19 @@ namespace Statecraft.Game.EditorTools
static void SyncTo(bool release)
{
- var files = ContentManifest.Copy(Paths.Content, Target, release);
- try { ContentManifest.Verify(Paths.Content, Target, release); }
- catch (InvalidDataException e) { throw new BuildFailedException("ContentSync: " + e.Message); }
- UnityEngine.Debug.Log($"ContentSync: {files.Count} files to {Target}");
+ List<string> files;
+ int translations;
+ try
+ {
+ files = ContentManifest.Copy(Paths.Content, Target, release);
+ ContentManifest.Verify(Paths.Content, Target, release);
+ translations = ContentManifest.CheckLoads(Paths.Content, Target);
+ }
+ catch (Exception e) when (e is InvalidDataException || e is ContentException)
+ {
+ throw new BuildFailedException("ContentSync: " + e.Message);
+ }
+ UnityEngine.Debug.Log($"ContentSync: {files.Count} files to {Target}, {translations} translated languages beside it");
var source = Path.Combine(Paths.RepoRoot, "sim", "Statecraft.Sim.Tests");
if (Directory.Exists(GoldenTarget)) Directory.Delete(GoldenTarget, true);
Directory.CreateDirectory(Path.Combine(GoldenTarget, "scenarios"));
diff --git a/unity/Assets/Scripts/Boot/ContentManifest.cs b/unity/Assets/Scripts/Boot/ContentManifest.cs
index 1b2ab02f7..732b73e45 100644
--- a/unity/Assets/Scripts/Boot/ContentManifest.cs
+++ b/unity/Assets/Scripts/Boot/ContentManifest.cs
@@ -4,6 +4,7 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using Statecraft.Game.Map;
+using Statecraft.Sim;
using UnityEngine;
namespace Statecraft.Game.Boot
@@ -12,10 +13,15 @@ namespace Statecraft.Game.Boot
/// them: content/manifest.json in StreamingAssets, {"files": [...]} with paths relative to content/, '/' separated,
/// ordinal order. The editor build step (ContentSync) copies the files and writes the manifest, and packs every listed
/// file's text into content/bundle.json, which is what the web boot fetches: one request instead of one per file
- /// (#1054). Desktop players and the editor read the files themselves.</summary>
+ /// (#1054). Desktop players and the editor read the files themselves.
+ /// The translations beside content/ (translations/, #1618 step 2) travel with it: copied to StreamingAssets/translations,
+ /// listed in the manifest's "translations" and packed into the same bundle, so the web boot still makes one request.</summary>
public static class ContentManifest
{
public const string FileName = "manifest.json";
+ /// <summary>The empty file <see cref="Copy"/> leaves at the top of the translations folder it makes. Hidden and at the
+ /// top, so the loader passes over it (TranslationLoader.Collect), and Unity does not import it.</summary>
+ public const string CopyMarker = ".contentmanifest-copy";
/// <summary>Every listed file's text in one file: {"files": [...], "texts": [...]}, the same order (#1054).</summary>
public const string BundleFileName = "bundle.json";
/// <summary>The map's hex table, always in the manifest. The map files players read are this and every map/*.yaml
@@ -33,8 +39,14 @@ namespace Statecraft.Game.Boot
public static readonly IReadOnlyList<string> RuntimeData = new[] { "map/localities_1948.tsv", "map/route_paths_1948.tsv",
"map/subdistrict_hexes_1948.tsv", "map/armistice_hexes_1949.tsv", "map/control_hexes_1948_49.tsv", "map/armistice_lines_1949.geojson" };
- [Serializable] sealed class ManifestJson { public string[] files = new string[0]; }
- [Serializable] sealed class BundleJson { public string[] files = new string[0]; public string[] texts = new string[0]; }
+ // "translations" (and the bundle's "translationTexts") are paths relative to translations/, such as "ro/ui.yaml";
+ // a manifest or bundle written before #1618 step 2 has none, which reads as no translations.
+ [Serializable] sealed class ManifestJson { public string[] files = new string[0]; public string[] translations = new string[0]; }
+ [Serializable] sealed class BundleJson
+ {
+ public string[] files = new string[0]; public string[] texts = new string[0];
+ public string[] translations = new string[0]; public string[] translationTexts = new string[0];
+ }
/// <summary>Every *.yaml in <paramref name="contentDir"/>, events/, map/ and rules/ (era rule overrides, #58; the folder may be absent) (but <see cref="ToolInputs"/>), plus
/// map/hexes.json; ordinal order.</summary>
@@ -48,7 +60,22 @@ namespace Statecraft.Game.Boot
.Where(f => !ToolInputs.Contains(f)).OrderBy(f => f, StringComparer.Ordinal).ToList();
}
- public static string Write(IEnumerable<string> files) => JsonUtility.ToJson(new ManifestJson { files = files.ToArray() }, true);
+ /// <summary>The translation files beside <paramref name="contentDir"/> (TranslationLoader.Collect of the translations/
+ /// next to a folder named content; none otherwise), as "ro/ui.yaml", ordinal order.</summary>
+ public static List<string> CollectTranslations(string contentDir) => TranslationLoader.Collect(TranslationLoader.Beside(contentDir));
+
+ static string TranslationPath(string contentDir, string file) =>
+ Path.Combine(TranslationLoader.Beside(contentDir) ?? throw new InvalidDataException($"{contentDir} has no translations folder beside it"), file);
+
+ public static string Write(IEnumerable<string> files, IEnumerable<string>? translations = null) =>
+ JsonUtility.ToJson(new ManifestJson { files = files.ToArray(), translations = (translations ?? new string[0]).ToArray() }, true);
+
+ /// <summary>The translation files manifest.json lists (none in an older manifest); throws as Parse does.</summary>
+ public static List<string> ParseTranslations(string json)
+ {
+ Parse(json);
+ return (JsonUtility.FromJson<ManifestJson>(json).translations ?? new string[0]).ToList();
+ }
/// <summary>Parses manifest.json; throws InvalidDataException when it is not a manifest.</summary>
public static List<string> Parse(string json)
@@ -62,12 +89,19 @@ namespace Statecraft.Game.Boot
/// <summary>bundle.json for <paramref name="files"/> (paths relative to <paramref name="contentDir"/>), each text
/// read as the disk path reads it (File.ReadAllText), so the content hash is the disk's; a <paramref name="release"/>
- /// build's as <see cref="Shipped"/> gives it.</summary>
- public static string WriteBundle(string contentDir, IReadOnlyList<string> files, bool release = false) => JsonUtility.ToJson(new BundleJson
+ /// build's as <see cref="Shipped"/> gives it. The translations beside it are packed too (<paramref name="translations"/>,
+ /// default CollectTranslations), each as File.ReadAllText reads it.</summary>
+ public static string WriteBundle(string contentDir, IReadOnlyList<string> files, bool release = false, IReadOnlyList<string>? translations = null)
{
- files = files.ToArray(),
- texts = files.Select(f => Shipped(contentDir, f, release)).ToArray(),
- });
+ var packed = translations ?? CollectTranslations(contentDir);
+ return JsonUtility.ToJson(new BundleJson
+ {
+ files = files.ToArray(),
+ texts = files.Select(f => Shipped(contentDir, f, release)).ToArray(),
+ translations = packed.ToArray(),
+ translationTexts = packed.Select(f => File.ReadAllText(TranslationPath(contentDir, f))).ToArray(),
+ });
+ }
/// <summary>A file's text as a build ships it: the source's, but a <paramref name="release"/> build's true armistice
/// lines hold only the features the owner has signed off (ArmisticeLines.ReleaseText; owner review of #2012). The
@@ -81,6 +115,14 @@ namespace Statecraft.Game.Boot
/// <summary>Parses bundle.json into the file list (as manifest.json lists it) and each file's text; throws
/// InvalidDataException when it is not a bundle.</summary>
public static (List<string> Files, Dictionary<string, string> Texts) ParseBundle(string json)
+ {
+ var b = ParseBundleWithTranslations(json);
+ return (b.Files, b.Texts);
+ }
+
+ /// <summary>ParseBundle, with the translation files the bundle packs and their texts (none in an older bundle).</summary>
+ public static (List<string> Files, Dictionary<string, string> Texts, List<string> Translations, Dictionary<string, string> TranslationTexts)
+ ParseBundleWithTranslations(string json)
{
BundleJson? b;
try { b = JsonUtility.FromJson<BundleJson>(json); }
@@ -91,12 +133,21 @@ namespace Statecraft.Game.Boot
var texts = new Dictionary<string, string>(StringComparer.Ordinal);
for (var i = 0; i < b.files.Length; i++)
if (!texts.TryAdd(b.files[i], b.texts[i])) throw new InvalidDataException($"{BundleFileName}: {b.files[i]} twice");
- return (b.files.ToList(), texts);
+ var translations = b.translations ?? new string[0];
+ var translationTexts = b.translationTexts ?? new string[0];
+ if (translationTexts.Length != translations.Length)
+ throw new InvalidDataException($"{BundleFileName}: {translations.Length} translation files but {translationTexts.Length} texts");
+ var byFile = new Dictionary<string, string>(StringComparer.Ordinal);
+ for (var i = 0; i < translations.Length; i++)
+ if (!byFile.TryAdd(translations[i], translationTexts[i])) throw new InvalidDataException($"{BundleFileName}: translation {translations[i]} twice");
+ return (b.files.ToList(), texts, translations.ToList(), byFile);
}
/// <summary>Checks a copy made by Copy: manifest.json equals Collect(contentDir) and every listed file exists, and
/// bundle.json lists the same files with each one's text as the source has it (as a <paramref name="release"/> build
- /// ships it). Throws InvalidDataException naming the problem.</summary>
+ /// ships it). The same for the translations: both files list CollectTranslations(contentDir), the bundle packs each
+ /// one's text, and the copy beside a target named content holds exactly those files, byte for byte. Throws
+ /// InvalidDataException naming the problem.</summary>
public static void Verify(string contentDir, string targetDir, bool release = false)
{
var expected = Collect(contentDir);
@@ -107,19 +158,72 @@ namespace Statecraft.Game.Boot
if (!File.Exists(Path.Combine(targetDir, f))) throw new InvalidDataException($"{f}: listed in {FileName} but missing from {targetDir}");
var bundle = Path.Combine(targetDir, BundleFileName);
if (!File.Exists(bundle)) throw new InvalidDataException($"{BundleFileName}: missing from {targetDir}");
- var (files, texts) = ParseBundle(File.ReadAllText(bundle));
+ var (files, texts, packed, packedTexts) = ParseBundleWithTranslations(File.ReadAllText(bundle));
if (!expected.SequenceEqual(files))
throw new InvalidDataException($"{BundleFileName} in {targetDir} does not match the content files ({files.Count} listed, {expected.Count} expected)");
foreach (var f in files)
if (texts[f] != Shipped(contentDir, f, release)) throw new InvalidDataException($"{f}: its text in {BundleFileName} differs from the source");
+
+ var translations = CollectTranslations(contentDir);
+ var listed = ParseTranslations(File.ReadAllText(Path.Combine(targetDir, FileName)));
+ if (!translations.SequenceEqual(listed))
+ throw new InvalidDataException($"{FileName} in {targetDir} does not list the translation files ({listed.Count} listed, {translations.Count} expected)");
+ if (!translations.SequenceEqual(packed))
+ throw new InvalidDataException($"{BundleFileName} in {targetDir} does not pack the translation files ({packed.Count} packed, {translations.Count} expected)");
+ foreach (var f in translations)
+ if (packedTexts[f] != File.ReadAllText(TranslationPath(contentDir, f)))
+ throw new InvalidDataException($"translations/{f}: its text in {BundleFileName} differs from the source");
+ var copy = TranslationLoader.Beside(targetDir);
+ if (copy == null) return; // a target not named content: the bundle alone carries them
+ var found = Directory.Exists(copy)
+ ? Directory.GetFiles(copy, "*", SearchOption.AllDirectories).Select(p => Path.GetRelativePath(copy, p).Replace('\\', '/'))
+ .Where(p => p != CopyMarker).OrderBy(p => p, StringComparer.Ordinal).ToList()
+ : new List<string>();
+ if (!translations.SequenceEqual(found))
+ throw new InvalidDataException($"{copy} holds {found.Count} files, not the {translations.Count} translation files");
+ foreach (var f in translations)
+ if (!File.ReadAllBytes(Path.Combine(copy, f)).SequenceEqual(File.ReadAllBytes(TranslationPath(contentDir, f))))
+ throw new InvalidDataException($"translations/{f}: the copy differs from the source");
+ }
+
+ /// <summary>Loads the copy in <paramref name="targetDir"/> as a player loads it, and the source in
+ /// <paramref name="contentDir"/> as the editor does, each with the translations beside it, so a broken translation
+ /// that was never committed (so no CI job saw it) fails the build, not a player's boot. Both loads are needed: the
+ /// copy leaves out the <see cref="ToolInputs"/> (map/localities_1948.yaml), so a key into one is checked only
+ /// against the source. Returns the number of languages; throws ContentException.</summary>
+ public static int CheckLoads(string contentDir, string targetDir)
+ {
+ var languages = ContentLoader.Load(targetDir).Translations.Count;
+ ContentLoader.Load(contentDir);
+ return languages;
}
/// <summary>Replaces <paramref name="targetDir"/> with a copy of the collected files plus manifest.json and bundle.json;
- /// for a <paramref name="release"/> build, the files as <see cref="Shipped"/> gives them.</summary>
+ /// for a <paramref name="release"/> build, the files as <see cref="Shipped"/> gives them. When the target is named
+ /// content (StreamingAssets/content), the translations folder beside it is replaced with a copy of the translations
+ /// beside <paramref name="contentDir"/>; the bundle packs them either way. Copy marks the translations folder it makes
+ /// with <see cref="CopyMarker"/> and replaces only a folder so marked: it throws InvalidDataException, before deleting
+ /// anything, rather than delete a translations folder it did not make.</summary>
public static List<string> Copy(string contentDir, string targetDir, bool release = false)
{
var files = Collect(contentDir);
+ var translations = CollectTranslations(contentDir);
+ var copy = TranslationLoader.Beside(targetDir);
+ if (copy != null && Directory.Exists(copy) && !File.Exists(Path.Combine(copy, CopyMarker)))
+ throw new InvalidDataException($"{copy}: not a copy ContentManifest.Copy made (no {CopyMarker}), so it is left alone; move or delete it");
if (Directory.Exists(targetDir)) Directory.Delete(targetDir, true);
+ if (copy != null)
+ {
+ if (Directory.Exists(copy)) Directory.Delete(copy, true);
+ Directory.CreateDirectory(copy);
+ File.WriteAllText(Path.Combine(copy, CopyMarker), "");
+ foreach (var f in translations)
+ {
+ var to = Path.Combine(copy, f);
+ Directory.CreateDirectory(Path.GetDirectoryName(to)!);
+ File.Copy(TranslationPath(contentDir, f), to);
+ }
+ }
foreach (var f in files)
{
var to = Path.Combine(targetDir, f);
@@ -127,8 +231,8 @@ namespace Statecraft.Game.Boot
if (release && f == "map/" + ArmisticeLines.FileName) File.WriteAllText(to, Shipped(contentDir, f, release));
else File.Copy(Path.Combine(contentDir, f), to);
}
- File.WriteAllText(Path.Combine(targetDir, FileName), Write(files));
- File.WriteAllText(Path.Combine(targetDir, BundleFileName), WriteBundle(contentDir, files, release));
+ File.WriteAllText(Path.Combine(targetDir, FileName), Write(files, translations));
+ File.WriteAllText(Path.Combine(targetDir, BundleFileName), WriteBundle(contentDir, files, release, translations));
return files;
}
}
diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.cs
index 627c11a65..3e56875e3 100644
--- a/unity/Assets/Scripts/Boot/GameInputs.cs
+++ b/unity/Assets/Scripts/Boot/GameInputs.cs
@@ -96,11 +96,15 @@ namespace Statecraft.Game.Boot
return new GameInputs { Content = ContentLoader.Load(contentDir), Map = MapFromDisk(contentDir, mapDir), Goldens = goldens };
}
- /// <summary>Builds the inputs from fetched texts (keys are manifest paths) and the packed heightmap's bytes.</summary>
- public static GameInputs FromTexts(IReadOnlyDictionary<string, string> texts, IEnumerable<string> manifest, string heightmapJson, byte[] r16z)
+ /// <summary>Builds the inputs from fetched texts (keys are manifest paths) and the packed heightmap's bytes, with the
+ /// bundle's translations (#1618 step 2: <paramref name="translationTexts"/> keyed as <paramref name="translations"/>
+ /// lists them, "ro/ui.yaml"; none when omitted).</summary>
+ public static GameInputs FromTexts(IReadOnlyDictionary<string, string> texts, IEnumerable<string> manifest, string heightmapJson, byte[] r16z,
+ IReadOnlyDictionary<string, string>? translationTexts = null, IEnumerable<string>? translations = null)
{
var events = manifest.Where(f => f.StartsWith("events/", StringComparison.Ordinal)).ToList();
- var content = ContentLoader.Load(rel => texts.TryGetValue(rel, out var t) ? t : null, events);
+ var content = ContentLoader.Load(rel => texts.TryGetValue(rel, out var t) ? t : null, events,
+ rel => translationTexts != null && translationTexts.TryGetValue(rel, out var t) ? t : null, translations ?? Enumerable.Empty<string>());
return new GameInputs
{
Content = content,
@@ -171,11 +175,11 @@ namespace Statecraft.Game.Boot
var goldenText = GoldenCheck.Requested() ? await Text(Get("golden/manifest.txt"), "golden/manifest.txt", stallSeconds) : "";
var scenarioNames = goldenText.Length == 0 ? new List<string>() : GoldenData.Parse(goldenText).Select(x => x.name).Where(n => n.StartsWith("scenario-", StringComparison.Ordinal)).Select(n => n.Substring("scenario-".Length)).ToList();
foreach (var n in scenarioNames) scenarioRequests.Add((n, Get("golden/scenarios/" + n + ".yaml")));
- var (manifest, texts) = ContentManifest.ParseBundle(await Text(bundle, ContentManifest.BundleFileName, stallSeconds));
+ var (manifest, texts, translations, translationTexts) = ContentManifest.ParseBundleWithTranslations(await Text(bundle, ContentManifest.BundleFileName, stallSeconds));
var metaText = await Text(meta, "heightmap.json", stallSeconds);
var r16zBytes = await Bytes(r16z, HeightmapCodec.FileName, stallSeconds);
- DiagLog.BootPhase($"downloaded {texts.Count + 2} files");
- var inputs = FromTexts(texts, manifest, metaText, r16zBytes);
+ DiagLog.BootPhase($"downloaded {texts.Count + translationTexts.Count + 2} files");
+ var inputs = FromTexts(texts, manifest, metaText, r16zBytes, translationTexts, translations);
inputs.Goldens = new GoldenData { Manifest = goldenText };
foreach (var (name, request) in scenarioRequests) inputs.Goldens.Scenarios[name] = await Text(request, "golden/scenarios/" + name + ".yaml", stallSeconds);
DiagLog.BootPhase("content parsed and validated");
diff --git a/unity/Assets/Scripts/Paths.cs b/unity/Assets/Scripts/Paths.cs
index f63a71851..509a801ee 100644
--- a/unity/Assets/Scripts/Paths.cs
+++ b/unity/Assets/Scripts/Paths.cs
@@ -8,6 +8,8 @@ namespace Statecraft.Game
// In the editor, content is read from the repo. Copying content into player builds comes in M3 (first player build).
public static string RepoRoot => Path.GetFullPath(Path.Combine(Application.dataPath, "..", ".."));
public static string Content => Application.isEditor ? Path.Combine(RepoRoot, "content") : Path.Combine(Application.streamingAssetsPath, "content");
+ /// <summary>translations/ beside <see cref="Content"/> (#1618): the repository's in the editor, StreamingAssets' copy in a player.</summary>
+ public static string Translations => Path.Combine(Path.GetDirectoryName(Content)!, "translations");
public static string StreamingMap => Path.Combine(Application.streamingAssetsPath, "map");
}
}
diff --git a/unity/Assets/Tests/EditMode/GameInputsTests.cs b/unity/Assets/Tests/EditMode/GameInputsTests.cs
index 4bf6a16bc..6dddd2a87 100644
--- a/unity/Assets/Tests/EditMode/GameInputsTests.cs
+++ b/unity/Assets/Tests/EditMode/GameInputsTests.cs
@@ -80,9 +80,15 @@ public class GameInputsTests
Assert.AreEqual(disk.Map.HexesJson, fetched.Map.HexesJson);
Assert.AreEqual(disk.Content.Events.Count, fetched.Content.Events.Count);
Assert.AreEqual(Simulation.NewGame(disk.Content, 7, Mode.Historical).Hash(), Simulation.NewGame(fetched.Content, 7, Mode.Historical).Hash());
+ // #1618 step 2: the web boot gets the disk's translations, from the same bundle.
+ Assert.IsNotEmpty(disk.Content.Translations);
+ CollectionAssert.AreEqual(Written(disk.Content.Translations), Written(fetched.Content.Translations));
Directory.Delete(site, true);
}
+ static List<string> Written(IEnumerable<TranslationSet> sets) =>
+ sets.Select(t => { var (ui, events, content) = Translations.Write(t); return t.Lang + "\n" + ui + events + content; }).ToList();
+
[UnityTest, Timeout(FetchTestTimeoutMs)]
public IEnumerator AMissingBundleNamesTheFile()
{
@@ -326,6 +332,153 @@ public class GameInputsTests
Assert.AreEqual(1f, StreamingFetch.Delay(2, "-5", now));
}
+ // ---- translations (#1618 step 2): copied beside the content, listed in the manifest, packed into the bundle ----
+
+ [Test]
+ public void TheManifestListsTheTranslationsBesideTheContent()
+ {
+ var files = ContentManifest.CollectTranslations(Paths.Content);
+ CollectionAssert.AreEqual(TranslationLoader.Collect(Paths.Translations), files);
+ CollectionAssert.Contains(files, "ro/ui.yaml");
+ CollectionAssert.IsEmpty(ContentManifest.CollectTranslations(Path.Combine(Path.GetTempPath(), "fixture-" + System.Guid.NewGuid().ToString("N"))));
+ var manifest = ContentManifest.Write(ContentManifest.Collect(Paths.Content), files);
+ CollectionAssert.AreEqual(files, ContentManifest.ParseTranslations(manifest));
+ CollectionAssert.IsEmpty(ContentManifest.ParseTranslations(ContentManifest.Write(new[] { "people.yaml" })));
+ }
+
+ [Test]
+ public void TheCopyCarriesTheTranslationsAndVerifyChecksThem()
+ {
+ var root = Path.Combine(Path.GetTempPath(), "statecraft-translations-" + System.Guid.NewGuid().ToString("N"));
+ var target = Path.Combine(root, "content");
+ var copy = Path.Combine(root, "translations");
+ var files = ContentManifest.CollectTranslations(Paths.Content);
+ string Refusal() => Assert.Throws<InvalidDataException>(() => ContentManifest.Verify(Paths.Content, target)).Message;
+ try
+ {
+ ContentManifest.Copy(Paths.Content, target);
+ ContentManifest.Verify(Paths.Content, target);
+ foreach (var f in files)
+ CollectionAssert.AreEqual(File.ReadAllBytes(Path.Combine(Paths.Translations, f)), File.ReadAllBytes(Path.Combine(copy, f)), f);
+ var (_, _, packed, texts) = ContentManifest.ParseBundleWithTranslations(File.ReadAllText(Path.Combine(target, ContentManifest.BundleFileName)));
+ CollectionAssert.AreEqual(files, packed);
+ foreach (var f in files) Assert.AreEqual(File.ReadAllText(Path.Combine(Paths.Translations, f)), texts[f], f);
+
+ File.AppendAllText(Path.Combine(copy, "ro", "ui.yaml"), "# changed after the copy\n");
+ Assert.AreEqual("translations/ro/ui.yaml: the copy differs from the source", Refusal());
+
+ // notes.txt can never be a source file (TranslationLoader.Collect refuses it), so the count holds whatever
+ // languages and files translations/ has (review C6).
+ ContentManifest.Copy(Paths.Content, target);
+ File.WriteAllText(Path.Combine(copy, "ro", "notes.txt"), "");
+ StringAssert.Contains($"holds {files.Count + 1} files, not the {files.Count} translation files", Refusal());
+
+ ContentManifest.Copy(Paths.Content, target);
+ Assert.IsFalse(File.Exists(Path.Combine(copy, "ro", "notes.txt")), "a copy replaces the translations folder");
+ File.WriteAllText(Path.Combine(target, ContentManifest.FileName), ContentManifest.Write(ContentManifest.Collect(Paths.Content)));
+ StringAssert.Contains("does not list the translation files", Refusal());
+
+ ContentManifest.Copy(Paths.Content, target);
+ File.WriteAllText(Path.Combine(target, ContentManifest.BundleFileName),
+ ContentManifest.WriteBundle(Paths.Content, ContentManifest.Collect(Paths.Content), translations: new string[0]));
+ StringAssert.Contains("does not pack the translation files", Refusal());
+ }
+ finally { if (Directory.Exists(root)) Directory.Delete(root, true); }
+ }
+
+ /// <summary>Review C3: Copy replaces the translations folder beside its target only when Copy made it, so a target named
+ /// content never takes a folder of someone's own translations with it.</summary>
+ [Test]
+ public void TheCopyReplacesOnlyATranslationsFolderItMade()
+ {
+ var root = Path.Combine(Path.GetTempPath(), "statecraft-translations-" + System.Guid.NewGuid().ToString("N"));
+ var target = Path.Combine(root, "content");
+ var mine = Path.Combine(root, "translations", "ro", "ui.yaml");
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(mine)!);
+ File.WriteAllText(mine, "mine");
+ var e = Assert.Throws<InvalidDataException>(() => ContentManifest.Copy(Paths.Content, target));
+ StringAssert.Contains("not a copy ContentManifest.Copy made", e.Message);
+ Assert.AreEqual("mine", File.ReadAllText(mine));
+
+ Directory.Delete(Path.Combine(root, "translations"), true);
+ ContentManifest.Copy(Paths.Content, target);
+ File.WriteAllText(Path.Combine(root, "translations", "ro", "notes.txt"), "");
+ ContentManifest.Copy(Paths.Content, target); // its own copy: replaced
+ ContentManifest.Verify(Paths.Content, target);
+ }
+ finally { if (Directory.Exists(root)) Directory.Delete(root, true); }
+ }
+
+ /// <summary>Review C1: the copy leaves out the tool inputs (map/localities_1948.yaml), so the build check also loads the
+ /// source, where a translation key into such a file can be checked.</summary>
+ [Test]
+ public void TheBuildCheckCatchesAKeyIntoAFileThePlayerDoesNotShip()
+ {
+ var root = Path.Combine(Path.GetTempPath(), "statecraft-translations-" + System.Guid.NewGuid().ToString("N"));
+ var source = Path.Combine(root, "repo", "content");
+ var target = Path.Combine(root, "player", "content");
+ try
+ {
+ foreach (var f in Directory.GetFiles(Paths.Content, "*", SearchOption.AllDirectories))
+ {
+ var to = Path.Combine(source, Path.GetRelativePath(Paths.Content, f));
+ Directory.CreateDirectory(Path.GetDirectoryName(to)!);
+ File.Copy(f, to);
+ }
+ Assert.AreEqual(TranslationLoader.Collect(Paths.Translations).Select(f => f.Split('/')[0]).Distinct().Count(),
+ ContentManifest.CheckLoads(Paths.Content, CopyOf(Paths.Content, Path.Combine(root, "real", "content"))));
+
+ const string locality = "map/localities_1948.yaml";
+ CollectionAssert.Contains(ContentManifest.ToolInputs, locality);
+ var yaml = new YamlDotNet.RepresentationModel.YamlStream();
+ yaml.Load(new StringReader(File.ReadAllText(Path.Combine(Paths.Content, locality))));
+ var key = Translations.Fields(locality, yaml.Documents[0].RootNode).First().Key;
+ var bad = new ContentKey(key.File, key.Path, "no_such_field").ToString();
+ Directory.CreateDirectory(Path.Combine(root, "repo", "translations", "ro"));
+ File.WriteAllText(Path.Combine(root, "repo", "translations", "ro", "ui.yaml"), "ui.lang: \"ro\"\n");
+ File.WriteAllText(Path.Combine(root, "repo", "translations", "ro", "content.yaml"), $"\"{bad}\":\n text: \"x\"\n");
+ CopyOf(source, target);
+ Assert.AreEqual(1, ContentLoader.Load(target).Translations.Count, "the copy alone cannot see the key is wrong");
+ var e = Assert.Throws<ContentException>(() => ContentManifest.CheckLoads(source, target));
+ Assert.AreEqual(("translations/ro/content.yaml", bad), (e.File, e.Field));
+ }
+ finally { if (Directory.Exists(root)) Directory.Delete(root, true); }
+ }
+
+ static string CopyOf(string contentDir, string target)
+ {
+ ContentManifest.Copy(contentDir, target);
+ ContentManifest.Verify(contentDir, target);
+ return target;
+ }
+
+ [Test]
+ public void ABundleWithoutTranslationsStillParses()
+ {
+ var (files, _, translations, texts) = ContentManifest.ParseBundleWithTranslations("{\"files\": [\"a.yaml\"], \"texts\": [\"x\"]}");
+ CollectionAssert.AreEqual(new[] { "a.yaml" }, files);
+ CollectionAssert.IsEmpty(translations);
+ CollectionAssert.IsEmpty(texts);
+ Assert.AreEqual("bundle.json: 1 translation files but 0 texts", Assert.Throws<InvalidDataException>(() =>
+ ContentManifest.ParseBundleWithTranslations("{\"files\": [\"a.yaml\"], \"texts\": [\"x\"], \"translations\": [\"ro/ui.yaml\"]}")).Message);
+ Assert.AreEqual("bundle.json: translation ro/ui.yaml twice", Assert.Throws<InvalidDataException>(() =>
+ ContentManifest.ParseBundleWithTranslations("{\"files\": [\"a.yaml\"], \"texts\": [\"x\"], \"translations\": [\"ro/ui.yaml\", \"ro/ui.yaml\"], \"translationTexts\": [\"a\", \"b\"]}")).Message);
+ }
+
+ [Test]
+ public void TheBundlesTranslationsLoadAsTheDisksDo()
+ {
+ var files = ContentManifest.Collect(Paths.Content);
+ var (listed, texts, translations, translationTexts) = ContentManifest.ParseBundleWithTranslations(ContentManifest.WriteBundle(Paths.Content, files));
+ var packed = GameInputs.FromTexts(texts, listed, "", new byte[0], translationTexts, translations);
+ var disk = ContentLoader.Load(Paths.Content);
+ Assert.IsNotEmpty(disk.Translations);
+ CollectionAssert.AreEqual(Written(disk.Translations), Written(packed.Content.Translations));
+ Assert.AreEqual(disk.Hash, packed.Content.Hash);
+ }
+
/// <summary>#1054: the content packed into one file at build time gives back every file's text as the disk path reads
/// it, so the web boot loads the same content with the same content hash.</summary>
[Test]