diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index 543c7626..442fec13 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -69,6 +69,7 @@ Change your password first.long This upload would exceed your quota.long Too many attempts; wait a minute and try again.long + This render is already filed under another sequence.long Choose a password different from the current one.long You cannot do this to your own account.long A job is working on this sequence or its archive; try again when it is free.long diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index 8baccf97..da9e2521 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -67,6 +67,7 @@ Cambia prima la password. Questo caricamento supererebbe la tua quota. Troppi tentativi; attendi un minuto e riprova. + Questo render è già archiviato in un'altra sequenza. Scegli una password diversa da quella attuale. Non puoi farlo sul tuo account. Un'attività sta lavorando su questa sequenza o sul suo archivio; riprova quando è libera. diff --git a/src/Titano.Tools/Commands/I18nCommand.cs b/src/Titano.Tools/Commands/I18nCommand.cs index 1fab1d74..95f8f86a 100644 --- a/src/Titano.Tools/Commands/I18nCommand.cs +++ b/src/Titano.Tools/Commands/I18nCommand.cs @@ -7,8 +7,8 @@ using Titano.Core.Localization; namespace Titano.Tools.Commands; /// -/// i18n check: completeness of en and it, placeholder parity, length budgets and that -/// every key used in code/XAML/admin JS exists (BRIEF §16). +/// i18n check: completeness of en and it, placeholder parity, length budgets, that every key +/// used in code/XAML/admin JS exists and that every error code the server answers with has its message (BRIEF §16). /// i18n export --out dir: one JSON per culture for the web admin. /// i18n missing --culture xx [--all]: untranslated (or all) keys as TSV for a translator or reviewer. /// i18n import --culture xx file.tsv: merges translated key<TAB>text rows into the culture's resx files. @@ -91,6 +91,8 @@ internal sealed partial class I18nCommand : ICommand if (en.Keys.Any(k => k.StartsWith(key + ".", StringComparison.Ordinal) && PluralSuffix().IsMatch(k[(key.Length + 1)..]))) continue; errors.Add($"{Path.GetRelativePath(root, file)}: unknown key {key}"); } + foreach (var (file, code, key) in MissingErrorMessages(root, en.Keys.ToHashSet(StringComparer.Ordinal))) + errors.Add($"{Path.GetRelativePath(root, file)}: error code {code} has no message {key}"); foreach (var w in warnings.Take(50)) Console.WriteLine("warning: " + w); if (warnings.Count > 50) Console.WriteLine($"warning: … {warnings.Count - 50} more"); @@ -253,8 +255,7 @@ internal sealed partial class I18nCommand : ICommand var src = Path.Combine(root, "src"); foreach (var file in Directory.EnumerateFiles(src, "*.*", SearchOption.AllDirectories)) { - if (file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal) - || file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) continue; + if (IsBuildOutput(file)) continue; var ext = Path.GetExtension(file); Regex? regex = ext switch { @@ -274,9 +275,44 @@ internal sealed partial class I18nCommand : ICommand } } + /// + /// Error codes of the server (literals passed to ApiErrors, Outcome.Fail and the local Fail and + /// TooMany helpers) whose message Server.Error.<Code> is not in , each once. + /// ApiErrors.Message builds that key at run time, so the scan of used keys cannot see it. + /// + internal static IEnumerable<(string File, string Code, string Key)> MissingErrorMessages(string root, IReadOnlySet keys) + { + var reported = new HashSet(StringComparer.Ordinal); + var server = Path.Combine(root, "src", "Titano.Server"); + foreach (var file in Directory.EnumerateFiles(server, "*.cs", SearchOption.AllDirectories).Order(StringComparer.Ordinal)) + { + if (IsBuildOutput(file)) continue; + foreach (var code in ErrorCodes(File.ReadAllText(file))) + { + var key = ErrorKey(code); + if (!keys.Contains(key) && reported.Add(code)) yield return (file, code, key); + } + } + } + + /// The literal error codes (snake_case) a C# source passes to the server's error helpers. + internal static IEnumerable ErrorCodes(string source) => ErrorCodeRegex().Matches(source).Select(m => m.Groups[1].Value); + + /// The message key of an error code, built like ApiErrors.Message: render_exists → Server.Error.RenderExists. + internal static string ErrorKey(string code) => + "Server.Error." + string.Concat(code.Split('_', StringSplitOptions.RemoveEmptyEntries).Select(part => char.ToUpperInvariant(part[0]) + part[1..])); + + private static bool IsBuildOutput(string file) => + file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal) + || file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal); + [GeneratedRegex(@"\{(\d+)(?:[,:][^}]*)?\}")] private static partial Regex PlaceholderRegex(); + /// A call of an error helper up to its first string argument (no statement end in between) when that is a snake_case code. + [GeneratedRegex(@"(?:\bApiErrors\.(?:Result|WriteAsync|BadRequest|Conflict|Message)|\bFail(?:<[^;()]*?>)?|\bTooMany)\([^;""]*?""([a-z][a-z0-9_]*)""")] + private static partial Regex ErrorCodeRegex(); + [GeneratedRegex(@"\b(?:L|Plural|Loc\.Get|LocKey)\(\s*""([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)""")] private static partial Regex CsKeyRegex(); diff --git a/tests/Titano.Tools.Tests/I18nCommandTests.cs b/tests/Titano.Tools.Tests/I18nCommandTests.cs new file mode 100644 index 00000000..83dfac51 --- /dev/null +++ b/tests/Titano.Tools.Tests/I18nCommandTests.cs @@ -0,0 +1,53 @@ +using System.Xml.Linq; +using Titano.Testing; +using Titano.Tools.Commands; + +namespace Titano.Tools.Tests; + +/// i18n check also covers the messages of the server's error codes, whose keys are built at run time. +public sealed class I18nCommandTests +{ + [Test] + public void ErrorCodesAreTheLiteralsPassedToTheServerErrorHelpers() + { + const string source = """ + if (bad) return ApiErrors.BadRequest(context, "invalid_filter", "status"); + return known.SequenceId == sequenceId + ? new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, null) + : Outcome.Fail(409, "render_exists"); + return Fail(400, "chunk_size", expected.ToString(CultureInfo.InvariantCulture)); + DeleteBlock.Offline => ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, + "archive_offline"), + return TooMany(context, "rate_limited", wait); + return ApiErrors.NotFound(context, "sequence"); + return ApiErrors.BadRequest(context, code, setting, setting); + await FailAsync(upload, "not_a_code"); + """; + + Assert.SequenceEqual(["invalid_filter", "render_exists", "chunk_size", "archive_offline", "rate_limited"], I18nCommand.ErrorCodes(source).ToList()); + } + + [Test] + public void AnErrorCodeNamesItsMessageKeyLikeTheServer() + { + Assert.Equal("Server.Error.RenderExists", I18nCommand.ErrorKey("render_exists")); + Assert.Equal("Server.Error.Forbidden", I18nCommand.ErrorKey("forbidden")); + Assert.Equal("Server.Error.Http413", I18nCommand.ErrorKey("http_413")); + } + + [Test] + public void EveryErrorCodeOfTheServerHasAnEnglishMessage() + { + var root = Args.RepoRoot(); + var keys = XDocument.Load(Path.Combine(root, "i18n", "en", "Server.resx")).Root!.Elements("data") + .Select(d => (string)d.Attribute("name")!).ToHashSet(StringComparer.Ordinal); + + var missing = I18nCommand.MissingErrorMessages(root, keys).ToList(); + + Assert.Empty(missing.Select(m => $"{m.Code} ({Path.GetFileName(m.File)})")); + var withoutOne = keys.Where(k => k != "Server.Error.RenderExists").ToHashSet(StringComparer.Ordinal); + var reported = I18nCommand.MissingErrorMessages(root, withoutOne).ToList(); + Assert.Count(1, reported); + Assert.Equal(("render_exists", "Server.Error.RenderExists", "RenderUploads.cs"), (reported[0].Code, reported[0].Key, Path.GetFileName(reported[0].File))); + } +}