chore: bootstrap repository foundation

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
This commit is contained in:
Claude committed 2026-10-02 08:59:40 +00:00
1 parent def3fadb6e
commit 83a54fb57b
109 files changed
+7523

No files matched your search

+203
View File
@@ -0,0 +1,203 @@
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;
}
}
}
@@ -0,0 +1,51 @@
using Titano.Core.Branding;
using Titano.Core.Codecs.Ico;
using Titano.Core.Codecs.Png;
namespace Titano.Tools.Commands;
/// <summary>Generates ICO/PNG sets and SVG masters from <see cref="BrandMark"/> geometry.</summary>
internal sealed class MakeIconCommand : ICommand
{
private static readonly int[] IcoSizes = [16, 20, 24, 32, 48, 64, 128, 256];
public string Name => "make-icon";
public string Summary => "Generate ICO/PNG/SVG brand assets (--out dir, --svg dir to refresh masters)";
public Task<int> RunAsync(string[] args)
{
var a = new Args(args);
var outDir = Path.GetFullPath(a.Get("out", Path.Combine(Args.RepoRoot(), "artifacts", "icons")));
Directory.CreateDirectory(outDir);
foreach (var (variant, name) in new[]
{
(BrandVariant.App, "titano"),
(BrandVariant.Server, "titano-server"),
(BrandVariant.Uploader, "titano-uploader"),
(BrandVariant.Mono, "titano-mono"),
})
{
var images = IcoSizes.Select(s => (s, BrandMark.Render(variant, s))).ToList();
File.WriteAllBytes(Path.Combine(outDir, name + ".ico"), IcoWriter.Write(images));
foreach (var size in new[] { 16, 32, 48, 64, 128, 256, 512, 1024 })
{
var rgba = BrandMark.Render(variant, size);
File.WriteAllBytes(Path.Combine(outDir, $"{name}-{size}.png"), PngEncoder.Encode(rgba, size, size, PngColorType.Rgba));
}
File.WriteAllText(Path.Combine(outDir, name + ".svg"), BrandMark.ToSvg(variant));
}
if (a.Get("svg") is { } svgDir)
{
Directory.CreateDirectory(svgDir);
File.WriteAllText(Path.Combine(svgDir, "titano.svg"), BrandMark.ToSvg(BrandVariant.App));
File.WriteAllText(Path.Combine(svgDir, "titano-server.svg"), BrandMark.ToSvg(BrandVariant.Server));
File.WriteAllText(Path.Combine(svgDir, "titano-uploader.svg"), BrandMark.ToSvg(BrandVariant.Uploader));
File.WriteAllText(Path.Combine(svgDir, "titano-mono.svg"), BrandMark.ToSvg(BrandVariant.Mono));
}
Console.WriteLine($"Icons written to {outDir}");
return Task.FromResult(0);
}
}
@@ -0,0 +1,45 @@
using System.Text.Json;
using System.Text.RegularExpressions;
namespace Titano.Tools.Commands;
/// <summary>BRIEF §19.2: no PackageReference anywhere and no restored packages in project.assets.json.</summary>
internal sealed partial class PackageGuardCommand : ICommand
{
public string Name => "package-guard";
public string Summary => "Fail when any project references or restores a package";
public Task<int> RunAsync(string[] args)
{
var root = Args.RepoRoot();
var failures = new List<string>();
foreach (var file in Directory.EnumerateFiles(root, "*.*", SearchOption.AllDirectories)
.Where(f => f.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".props", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".targets", StringComparison.OrdinalIgnoreCase))
.Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)
&& !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal)))
{
var text = File.ReadAllText(file);
if (PackageReference().IsMatch(text)) failures.Add($"{Path.GetRelativePath(root, file)}: PackageReference");
}
foreach (var assets in Directory.EnumerateFiles(root, "project.assets.json", SearchOption.AllDirectories))
{
using var doc = JsonDocument.Parse(File.ReadAllText(assets));
if (doc.RootElement.TryGetProperty("libraries", out var libs))
{
foreach (var lib in libs.EnumerateObject())
{
if (lib.Value.TryGetProperty("type", out var type) && type.GetString() == "package")
failures.Add($"{Path.GetRelativePath(root, assets)}: restored package {lib.Name}");
}
}
}
foreach (var f in failures) Console.Error.WriteLine(f);
Console.WriteLine(failures.Count == 0 ? "Zero packages: OK" : $"{failures.Count} package violation(s)");
return Task.FromResult(failures.Count == 0 ? 0 : 1);
}
[GeneratedRegex(@"<\s*PackageReference\b", RegexOptions.IgnoreCase)]
private static partial Regex PackageReference();
}
@@ -0,0 +1,74 @@
using System.Xml.Linq;
namespace Titano.Tools.Commands;
/// <summary>
/// BRIEF §20.3 / DESIGN §4: every actionable control carries a tooltip and no visible text is a literal.
/// Elements inside <c>ControlTemplate</c>s are template parts and exempt from the tooltip rule.
/// </summary>
internal sealed class XamlLintCommand : ICommand
{
private static readonly HashSet<string> Actionable = new(StringComparer.Ordinal)
{
"Button", "ToggleButton", "RepeatButton", "Slider", "ComboBox", "CheckBox", "RadioButton", "MenuItem",
"AutoSlider", "IconButton", "SplitButton",
};
private static readonly string[] TextAttributes = ["Content", "Text", "Header", "ToolTip", "Title", "Tag"];
public string Name => "xaml-lint";
public string Summary => "Check tooltips and literal text in all XAML under src/";
public Task<int> RunAsync(string[] args)
{
var root = Args.RepoRoot();
var problems = new List<string>();
var files = Directory.EnumerateFiles(Path.Combine(root, "src"), "*.xaml", SearchOption.AllDirectories)
.Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)
&& !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal))
.ToList();
foreach (var file in files)
{
var doc = XDocument.Load(file, LoadOptions.SetLineInfo);
foreach (var el in doc.Descendants())
{
var line = ((System.Xml.IXmlLineInfo)el).LineNumber;
var where = $"{Path.GetRelativePath(root, file)}:{line}";
var name = el.Name.LocalName;
var inTemplate = el.Ancestors().Any(a => a.Name.LocalName is "ControlTemplate" or "Setter" or "Style");
if (Actionable.Contains(name) && !inTemplate && !HasToolTip(el) && !IsExempt(el))
problems.Add($"{where}: <{name}> has no ToolTip");
foreach (var attrName in TextAttributes)
{
var attr = el.Attribute(attrName);
if (attr is null) continue;
var v = attr.Value;
if (v.Length == 0 || v.StartsWith('{')) continue;
if (attrName == "Tag" || (attrName == "Content" && inTemplate)) continue;
if (v.Any(char.IsLetter))
problems.Add($"{where}: literal {attrName}=\"{v}\" on <{name}> (use {{l:Loc …}})");
}
// Literal element content such as <TextBlock>Hello</TextBlock> or <Run>Hi</Run>.
if (name is "TextBlock" or "Run" or "Label" or "Button" && !el.HasElements && el.Value.Any(char.IsLetter))
problems.Add($"{where}: literal text in <{name}>");
}
}
foreach (var p in problems) Console.Error.WriteLine(p);
Console.WriteLine($"xaml-lint: {files.Count} file(s), {problems.Count} problem(s)");
return Task.FromResult(problems.Count == 0 ? 0 : 1);
}
private static bool HasToolTip(XElement el) =>
el.Attribute("ToolTip") is not null
|| el.Elements().Any(c => c.Name.LocalName.EndsWith(".ToolTip", StringComparison.Ordinal))
|| el.Attributes().Any(a => a.Name.LocalName == "TipKey");
/// <summary>Opt-out for controls whose tooltip is applied by a style (marked explicitly in XAML).</summary>
private static bool IsExempt(XElement el) =>
el.Attributes().Any(a => a.Name.LocalName == "ToolTipFromStyle" && a.Value == "True");
}
+61
View File
@@ -0,0 +1,61 @@
namespace Titano.Tools;
internal interface ICommand
{
string Name { get; }
string Summary { get; }
Task<int> RunAsync(string[] args);
}
internal sealed class ToolException(string message) : Exception(message);
/// <summary>Minimal option parser: <c>--key value</c>, <c>--flag</c>, positional arguments.</summary>
internal sealed class Args
{
private readonly Dictionary<string, string?> _options = new(StringComparer.OrdinalIgnoreCase);
public Args(string[] args, params string[] flags)
{
for (var i = 0; i < args.Length; i++)
{
var a = args[i];
if (a.StartsWith("--", StringComparison.Ordinal))
{
var key = a[2..];
if (flags.Contains(key, StringComparer.OrdinalIgnoreCase) || i + 1 >= args.Length || args[i + 1].StartsWith("--", StringComparison.Ordinal))
_options[key] = null;
else
_options[key] = args[++i];
}
else
{
Positional.Add(a);
}
}
}
public List<string> Positional { get; } = [];
public bool Has(string key) => _options.ContainsKey(key);
public string? Get(string key) => _options.TryGetValue(key, out var v) ? v : null;
public string Get(string key, string fallback) => Get(key) ?? fallback;
public static string RepoRoot()
{
var dir = new DirectoryInfo(Directory.GetCurrentDirectory());
while (dir is not null)
{
if (File.Exists(Path.Combine(dir.FullName, "Titano.slnx"))) return dir.FullName;
dir = dir.Parent;
}
dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir is not null)
{
if (File.Exists(Path.Combine(dir.FullName, "Titano.slnx"))) return dir.FullName;
dir = dir.Parent;
}
throw new ToolException("Repository root (Titano.slnx) not found.");
}
}
+34
View File
@@ -0,0 +1,34 @@
using Titano.Tools;
using Titano.Tools.Commands;
var commands = new ICommand[]
{
new MakeIconCommand(),
new I18nCommand(),
new XamlLintCommand(),
new PackageGuardCommand(),
};
if (args.Length == 0 || args[0] is "-h" or "--help" or "help")
{
Console.WriteLine("Titano.Tools <command> [options]");
foreach (var c in commands) Console.WriteLine($" {c.Name,-14} {c.Summary}");
return args.Length == 0 ? 2 : 0;
}
var command = commands.FirstOrDefault(c => c.Name.Equals(args[0], StringComparison.OrdinalIgnoreCase));
if (command is null)
{
Console.Error.WriteLine($"Unknown command '{args[0]}'. Run with --help.");
return 2;
}
try
{
return await command.RunAsync(args[1..]);
}
catch (ToolException ex)
{
Console.Error.WriteLine(ex.Message);
return 2;
}
+13
View File
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>Titano.Tools</RootNamespace>
<AssemblyName>Titano.Tools</AssemblyName>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Titano.Core\Titano.Core.csproj" />
<ProjectReference Include="..\Titano.Data\Titano.Data.csproj" />
<ProjectReference Include="..\Titano.Protocol\Titano.Protocol.csproj" />
</ItemGroup>
</Project>