Solution layout, build rules with zero-package guard, in-house test framework, localization runtime, brand mark rasteriser with ICO/PNG generation, Core contracts (imaging, video, domain model, TIFF reader), Titano.Tools (make-icon, i18n, xaml-lint, package-guard) and docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
204 lines
9.5 KiB
C#
204 lines
9.5 KiB
C#
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
using System.Xml.Linq;
|
|
using Titano.Core.Localization;
|
|
|
|
namespace Titano.Tools.Commands;
|
|
|
|
/// <summary>
|
|
/// <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.
|
|
/// </summary>
|
|
internal sealed partial class I18nCommand : ICommand
|
|
{
|
|
private static readonly string[] RequiredCultures = ["en", "it"];
|
|
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 Task<int> RunAsync(string[] args)
|
|
{
|
|
var a = new Args(args);
|
|
var sub = a.Positional.FirstOrDefault() ?? "check";
|
|
var root = Args.RepoRoot();
|
|
var catalog = Catalog.Load(Path.Combine(root, "i18n"));
|
|
return Task.FromResult(sub switch
|
|
{
|
|
"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")),
|
|
_ => throw new ToolException($"Unknown i18n subcommand '{sub}'"),
|
|
});
|
|
}
|
|
|
|
private static int Check(string root, Catalog catalog)
|
|
{
|
|
var errors = new List<string>();
|
|
var warnings = new List<string>();
|
|
if (!catalog.Cultures.TryGetValue("en", out var en)) throw new ToolException("i18n/en missing");
|
|
|
|
foreach (var (key, entry) in en)
|
|
{
|
|
var area = key.Split('.')[0];
|
|
if (!entry.File.Equals(area, StringComparison.Ordinal))
|
|
errors.Add($"en: key {key} lives in {entry.File}.resx but its area is {area}");
|
|
var limit = Limit(key, area, entry.Comment);
|
|
if (entry.Value.Length > limit)
|
|
errors.Add($"en: {key} is {entry.Value.Length} chars (budget {limit})");
|
|
if (string.IsNullOrWhiteSpace(entry.Value))
|
|
errors.Add($"en: {key} is empty");
|
|
}
|
|
|
|
foreach (var (culture, strings) in catalog.Cultures)
|
|
{
|
|
if (culture == "en") continue;
|
|
var required = RequiredCultures.Contains(culture);
|
|
var missing = 0;
|
|
foreach (var (key, entry) in en)
|
|
{
|
|
if (entry.Comment is not null && entry.Comment.Contains("invariant", StringComparison.OrdinalIgnoreCase)) continue;
|
|
if (!strings.TryGetValue(key, out var translated))
|
|
{
|
|
if (required) errors.Add($"{culture}: missing {key}");
|
|
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})");
|
|
}
|
|
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 (file, key) in UsedKeys(root))
|
|
{
|
|
if (en.ContainsKey(key)) continue;
|
|
// Plural lookups reference the stem; any suffix satisfies them.
|
|
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 w in warnings.Take(50)) Console.WriteLine("warning: " + w);
|
|
if (warnings.Count > 50) Console.WriteLine($"warning: … {warnings.Count - 50} more");
|
|
foreach (var e in errors) Console.Error.WriteLine("error: " + e);
|
|
Console.WriteLine($"i18n: {en.Count} keys, {catalog.Cultures.Count} cultures, {errors.Count} error(s), {warnings.Count} warning(s)");
|
|
return errors.Count == 0 ? 0 : 1;
|
|
}
|
|
|
|
private static int Missing(Catalog catalog, string culture)
|
|
{
|
|
var en = catalog.Cultures["en"];
|
|
catalog.Cultures.TryGetValue(culture, out var target);
|
|
foreach (var (key, entry) in en.OrderBy(k => k.Key, StringComparer.Ordinal))
|
|
{
|
|
if (target is null || !target.ContainsKey(key)) Console.WriteLine($"{key}\t{entry.Value}");
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
private static int Limit(string key, string area, string? comment)
|
|
{
|
|
if (comment is not null && comment.Contains("long", StringComparison.OrdinalIgnoreCase)) return 200;
|
|
if (SentenceAreas.Contains(area) || key.EndsWith(".Tip", StringComparison.Ordinal)) return 200;
|
|
return 30;
|
|
}
|
|
|
|
private static int Export(Catalog catalog, string outDir)
|
|
{
|
|
Directory.CreateDirectory(outDir);
|
|
var en = catalog.Cultures["en"];
|
|
foreach (var (culture, strings) in catalog.Cultures)
|
|
{
|
|
var merged = new SortedDictionary<string, string>(StringComparer.Ordinal);
|
|
foreach (var (k, v) in en) merged[k] = strings.TryGetValue(k, out var t) ? t.Value : v.Value;
|
|
var json = JsonSerializer.Serialize(merged, new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
|
|
File.WriteAllText(Path.Combine(outDir, culture + ".json"), json, new UTF8Encoding(false));
|
|
}
|
|
Console.WriteLine($"Exported {catalog.Cultures.Count} cultures to {outDir}");
|
|
return 0;
|
|
}
|
|
|
|
private static HashSet<string> Placeholders(string s) =>
|
|
[.. PlaceholderRegex().Matches(s).Select(m => m.Groups[1].Value)];
|
|
|
|
/// <summary>Keys referenced from C# (<c>L("…")</c>, <c>Plural("…")</c>, <c>Loc.Get("…")</c>), XAML (<c>{l:Loc …}</c>) and admin JS (<c>t("…")</c>).</summary>
|
|
private static IEnumerable<(string File, string Key)> UsedKeys(string root)
|
|
{
|
|
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;
|
|
var ext = Path.GetExtension(file);
|
|
Regex? regex = ext switch
|
|
{
|
|
".cs" => CsKeyRegex(),
|
|
".xaml" => XamlKeyRegex(),
|
|
".js" or ".html" => JsKeyRegex(),
|
|
_ => null,
|
|
};
|
|
if (regex is null) continue;
|
|
var text = File.ReadAllText(file);
|
|
foreach (Match m in regex.Matches(text)) yield return (file, m.Groups[1].Value);
|
|
}
|
|
}
|
|
|
|
[GeneratedRegex(@"\{(\d+)(?:[,:][^}]*)?\}")]
|
|
private static partial Regex PlaceholderRegex();
|
|
|
|
[GeneratedRegex(@"\b(?:L|Plural|Loc\.Get|LocKey)\(\s*""([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)""")]
|
|
private static partial Regex CsKeyRegex();
|
|
|
|
[GeneratedRegex(@"\{(?:l|loc):Loc\s+(?:Key=)?([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)")]
|
|
private static partial Regex XamlKeyRegex();
|
|
|
|
[GeneratedRegex(@"(?:\bt\(\s*['""]|data-i18n(?:-[a-z]+)?=['""])([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)")]
|
|
private static partial Regex JsKeyRegex();
|
|
|
|
[GeneratedRegex(@"^(one|few|many|other)$")]
|
|
private static partial Regex PluralSuffix();
|
|
|
|
internal sealed record Entry(string File, string Value, string? Comment);
|
|
|
|
internal sealed class Catalog
|
|
{
|
|
public Dictionary<string, Dictionary<string, Entry>> Cultures { get; } = new(StringComparer.OrdinalIgnoreCase);
|
|
|
|
public static Catalog Load(string dir)
|
|
{
|
|
var c = new Catalog();
|
|
foreach (var cultureDir in Directory.EnumerateDirectories(dir))
|
|
{
|
|
var culture = Path.GetFileName(cultureDir);
|
|
var strings = new Dictionary<string, Entry>(StringComparer.Ordinal);
|
|
foreach (var file in Directory.EnumerateFiles(cultureDir, "*.resx"))
|
|
{
|
|
var area = Path.GetFileName(file).Split('.')[0];
|
|
var doc = XDocument.Load(file);
|
|
foreach (var data in doc.Root!.Elements("data"))
|
|
{
|
|
var name = (string?)data.Attribute("name") ?? throw new ToolException($"{file}: data without name");
|
|
var value = (string?)data.Element("value") ?? string.Empty;
|
|
if (!strings.TryAdd(name, new Entry(area, value, (string?)data.Element("comment"))))
|
|
throw new ToolException($"{file}: duplicate key {name}");
|
|
}
|
|
}
|
|
c.Cultures[culture] = strings;
|
|
}
|
|
foreach (var code in Languages.Shipped.Where(s => !c.Cultures.ContainsKey(s)))
|
|
c.Cultures.TryAdd(code, new Dictionary<string, Entry>(StringComparer.Ordinal));
|
|
return c;
|
|
}
|
|
}
|
|
}
|