feat(i18n): plural forms per language, translation import and glossary
i18n check accepts the few/many forms a language adds, comparing them with the English other form; i18n missing lists the work as TSV (or every key with --all for review) and i18n import merges translated rows into the culture's resx files. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
4 files changed
+216
-17
No files matched your search
@@ -10,6 +10,8 @@ namespace Titano.Tools.Commands;
|
||||
/// <c>i18n check</c>: completeness of <c>en</c> and <c>it</c>, placeholder parity, length budgets and that
|
||||
/// every key used in code/XAML/admin JS exists (BRIEF §16).
|
||||
/// <c>i18n export --out dir</c>: one JSON per culture for the web admin.
|
||||
/// <c>i18n missing --culture xx [--all]</c>: untranslated (or all) keys as TSV for a translator or reviewer.
|
||||
/// <c>i18n import --culture xx file.tsv</c>: merges translated <c>key<TAB>text</c> rows into the culture's resx files.
|
||||
/// </summary>
|
||||
internal sealed partial class I18nCommand : ICommand
|
||||
{
|
||||
@@ -17,11 +19,11 @@ internal sealed partial class I18nCommand : ICommand
|
||||
private static readonly HashSet<string> SentenceAreas = new(StringComparer.Ordinal) { "Tooltips", "Errors", "Advisor" };
|
||||
|
||||
public string Name => "i18n";
|
||||
public string Summary => "check | export --out <dir> (resource completeness and web export)";
|
||||
public string Summary => "check | export --out <dir> | missing --culture <c> [--all] | import --culture <c> <tsv>";
|
||||
|
||||
public Task<int> RunAsync(string[] args)
|
||||
{
|
||||
var a = new Args(args);
|
||||
var a = new Args(args, "all");
|
||||
var sub = a.Positional.FirstOrDefault() ?? "check";
|
||||
var root = Args.RepoRoot();
|
||||
var catalog = Catalog.Load(Path.Combine(root, "i18n"));
|
||||
@@ -29,7 +31,9 @@ internal sealed partial class I18nCommand : ICommand
|
||||
{
|
||||
"check" => Check(root, catalog),
|
||||
"export" => Export(catalog, a.Get("out") ?? throw new ToolException("--out <dir> required")),
|
||||
"missing" => Missing(catalog, a.Get("culture") ?? throw new ToolException("--culture <code> required")),
|
||||
"missing" => Missing(catalog, a.Get("culture") ?? throw new ToolException("--culture <code> required"), a.Has("all")),
|
||||
"import" => Import(root, catalog, a.Get("culture") ?? throw new ToolException("--culture <code> required"),
|
||||
a.Positional.ElementAtOrDefault(1) ?? throw new ToolException("TSV file required")),
|
||||
_ => throw new ToolException($"Unknown i18n subcommand '{sub}'"),
|
||||
});
|
||||
}
|
||||
@@ -66,18 +70,15 @@ internal sealed partial class I18nCommand : ICommand
|
||||
else missing++;
|
||||
continue;
|
||||
}
|
||||
var p1 = Placeholders(entry.Value);
|
||||
var p2 = Placeholders(translated.Value);
|
||||
if (!p1.SetEquals(p2))
|
||||
errors.Add($"{culture}: {key} placeholders {{{string.Join(",", p2)}}} differ from en {{{string.Join(",", p1)}}}");
|
||||
var area = key.Split('.')[0];
|
||||
var limit = (int)(Limit(key, area, entry.Comment) * 1.6);
|
||||
if (translated.Value.Length > limit)
|
||||
warnings.Add($"{culture}: {key} is {translated.Value.Length} chars (soft budget {limit})");
|
||||
CheckTranslation(culture, key, entry, translated, en, errors, warnings);
|
||||
}
|
||||
if (missing > 0) warnings.Add($"{culture}: {missing} key(s) not translated yet");
|
||||
foreach (var key in strings.Keys.Where(k => !en.ContainsKey(k)))
|
||||
errors.Add($"{culture}: orphan key {key}");
|
||||
foreach (var (key, translated) in strings.Where(s => !en.ContainsKey(s.Key)))
|
||||
{
|
||||
// Languages with more plural forms than English add key.few / key.many next to key.one / key.other.
|
||||
if (PluralStem(key, en) is { } other) CheckTranslation(culture, key, other, translated, en, errors, warnings);
|
||||
else errors.Add($"{culture}: orphan key {key}");
|
||||
}
|
||||
}
|
||||
|
||||
var areas = en.Keys.Select(k => k[..k.IndexOf('.')]).ToHashSet(StringComparer.Ordinal);
|
||||
@@ -98,17 +99,122 @@ internal sealed partial class I18nCommand : ICommand
|
||||
return errors.Count == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static int Missing(Catalog catalog, string culture)
|
||||
/// <summary>A translation keeps the English placeholders and stays within 1.6× the English budget. Plural forms
|
||||
/// are compared with the English <c>other</c> form and may drop the count <c>{0}</c> (as English "Rendered once" does).</summary>
|
||||
private static void CheckTranslation(string culture, string key, Entry source, Entry translated, Dictionary<string, Entry> en, List<string> errors, List<string> warnings)
|
||||
{
|
||||
var p2 = Placeholders(translated.Value);
|
||||
if (PluralStem(key, en) is { } other)
|
||||
{
|
||||
var p1 = Placeholders(other.Value);
|
||||
p1.Remove("0");
|
||||
if (!p2.IsSubsetOf([.. p1, "0"]) || !p1.IsSubsetOf(p2))
|
||||
errors.Add($"{culture}: {key} placeholders {{{string.Join(",", p2)}}} differ from en {{{string.Join(",", p1.Prepend("0"))}}}");
|
||||
}
|
||||
else
|
||||
{
|
||||
var p1 = Placeholders(source.Value);
|
||||
if (!p1.SetEquals(p2))
|
||||
errors.Add($"{culture}: {key} placeholders {{{string.Join(",", p2)}}} differ from en {{{string.Join(",", p1)}}}");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(translated.Value))
|
||||
errors.Add($"{culture}: {key} is empty");
|
||||
var limit = (int)(Limit(key, key.Split('.')[0], source.Comment) * 1.6);
|
||||
if (translated.Value.Length > limit)
|
||||
warnings.Add($"{culture}: {key} is {translated.Value.Length} chars (soft budget {limit})");
|
||||
}
|
||||
|
||||
/// <summary>The English <c>other</c> form when <paramref name="key"/> is a plural form of an English plural key.</summary>
|
||||
private static Entry? PluralStem(string key, Dictionary<string, Entry> en)
|
||||
{
|
||||
var dot = key.LastIndexOf('.');
|
||||
if (dot <= 0 || !PluralSuffix().IsMatch(key[(dot + 1)..])) return null;
|
||||
return en.GetValueOrDefault(key[..dot] + ".other");
|
||||
}
|
||||
|
||||
/// <summary>Untranslated keys as <c>key, English, budget, note</c>; with <c>--all</c> every key plus its current
|
||||
/// translation (plural forms the language adds included) for review.</summary>
|
||||
private static int Missing(Catalog catalog, string culture, bool all)
|
||||
{
|
||||
var en = catalog.Cultures["en"];
|
||||
catalog.Cultures.TryGetValue(culture, out var target);
|
||||
foreach (var (key, entry) in en.OrderBy(k => k.Key, StringComparer.Ordinal))
|
||||
target ??= [];
|
||||
var rows = en.Select(e => (Key: e.Key, Source: e.Value))
|
||||
.Concat(target.Keys.Where(k => !en.ContainsKey(k)).Select(k => (Key: k, Source: PluralStem(k, en)!)))
|
||||
.Where(r => r.Source is not null)
|
||||
.OrderBy(r => r.Key, StringComparer.Ordinal);
|
||||
foreach (var (key, source) in rows)
|
||||
{
|
||||
if (target is null || !target.ContainsKey(key)) Console.WriteLine($"{key}\t{entry.Value}");
|
||||
if (source.Comment is not null && source.Comment.Contains("invariant", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var translated = target.GetValueOrDefault(key);
|
||||
if (translated is not null && !all) continue;
|
||||
var budget = (int)(Limit(key, key.Split('.')[0], source.Comment) * 1.6);
|
||||
Console.WriteLine(all ? $"{key}\t{source.Value}\t{budget}\t{source.Comment}\t{translated?.Value}" : $"{key}\t{source.Value}\t{budget}\t{source.Comment}");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Merges <c>key<TAB>text</c> rows (further columns and <c>#</c> lines ignored) into
|
||||
/// <c>i18n/<culture>/<Area>.<culture>.resx</c>, replacing existing values and keeping keys sorted.
|
||||
/// Keys must exist in English or be a plural form of an English plural key; placeholders are verified by <c>check</c>.
|
||||
/// </summary>
|
||||
private static int Import(string root, Catalog catalog, string culture, string tsv)
|
||||
{
|
||||
if (culture.Equals("en", StringComparison.OrdinalIgnoreCase)) throw new ToolException("English is the source; edit i18n/en directly");
|
||||
if (!Languages.Shipped.Contains(culture, StringComparer.OrdinalIgnoreCase)) throw new ToolException($"{culture} is not a shipped language");
|
||||
culture = Languages.Shipped.First(c => c.Equals(culture, StringComparison.OrdinalIgnoreCase));
|
||||
var en = catalog.Cultures["en"];
|
||||
var rows = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
var line = 0;
|
||||
foreach (var raw in File.ReadLines(tsv))
|
||||
{
|
||||
line++;
|
||||
if (raw.Length == 0 || raw.StartsWith('#')) continue;
|
||||
var cells = raw.Split('\t');
|
||||
if (cells.Length < 2) throw new ToolException($"{tsv}:{line}: expected key<TAB>text");
|
||||
var key = cells[0].Trim();
|
||||
if (!en.ContainsKey(key) && PluralStem(key, en) is null) throw new ToolException($"{tsv}:{line}: unknown key {key}");
|
||||
if (!rows.TryAdd(key, cells[1])) throw new ToolException($"{tsv}:{line}: duplicate key {key}");
|
||||
}
|
||||
|
||||
var dir = Path.Combine(root, "i18n", culture);
|
||||
Directory.CreateDirectory(dir);
|
||||
var written = 0;
|
||||
foreach (var group in rows.GroupBy(r => r.Key[..r.Key.IndexOf('.')], StringComparer.Ordinal))
|
||||
{
|
||||
var path = Path.Combine(dir, $"{group.Key}.{culture}.resx");
|
||||
var values = new SortedDictionary<string, string>(StringComparer.Ordinal);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
foreach (var data in XDocument.Load(path).Root!.Elements("data"))
|
||||
values[(string)data.Attribute("name")!] = (string?)data.Element("value") ?? string.Empty;
|
||||
}
|
||||
foreach (var (key, value) in group) values[key] = value;
|
||||
WriteResx(path, values);
|
||||
written += group.Count();
|
||||
}
|
||||
Console.WriteLine($"{culture}: {written} string(s) imported");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static void WriteResx(string path, IEnumerable<KeyValuePair<string, string>> values)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n");
|
||||
sb.Append(" <resheader name=\"resmimetype\"><value>text/microsoft-resx</value></resheader>\n");
|
||||
sb.Append(" <resheader name=\"version\"><value>2.0</value></resheader>\n");
|
||||
sb.Append(" <resheader name=\"reader\"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>\n");
|
||||
sb.Append(" <resheader name=\"writer\"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>\n");
|
||||
foreach (var (key, value) in values)
|
||||
sb.Append($" <data name=\"{Escape(key)}\" xml:space=\"preserve\"><value>{Escape(value)}</value></data>\n");
|
||||
sb.Append("</root>\n");
|
||||
File.WriteAllText(path, sb.ToString(), new UTF8Encoding(false));
|
||||
}
|
||||
|
||||
private static string Escape(string s) => s.Replace("&", "&", StringComparison.Ordinal).Replace("<", "<", StringComparison.Ordinal)
|
||||
.Replace(">", ">", StringComparison.Ordinal).Replace("\"", """, StringComparison.Ordinal);
|
||||
|
||||
private static int Limit(string key, string area, string? comment)
|
||||
{
|
||||
if (comment is not null && comment.Contains("long", StringComparison.OrdinalIgnoreCase)) return 200;
|
||||
|
||||
Reference in new issue
Block a user