refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout and the system SQLite. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow; the throw-away server runs without durability) and pe-check. - Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR, 3 on the shared runner; the weekly performance gates keep theirs). BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>Chronos.Tools</RootNamespace>
|
||||
<AssemblyName>Chronos.Tools</AssemblyName>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Chronos.Tools.Tests" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Chronos.Core\Chronos.Core.csproj" />
|
||||
<ProjectReference Include="..\Chronos.Data\Chronos.Data.csproj" />
|
||||
<ProjectReference Include="..\Chronos.Protocol\Chronos.Protocol.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,94 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Chronos.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Builds release notes from Conventional Commits. Reads <c>git log --format=%h%x09%s</c> lines from stdin
|
||||
/// (or <c>--in file</c>) and writes Markdown grouped by type.
|
||||
/// </summary>
|
||||
internal sealed partial class ChangelogCommand : ICommand
|
||||
{
|
||||
private static readonly (string Type, string Heading)[] Sections =
|
||||
[
|
||||
("feat", "Added"),
|
||||
("fix", "Fixed"),
|
||||
("perf", "Performance"),
|
||||
("security", "Security"),
|
||||
("i18n", "Localization"),
|
||||
("docs", "Documentation"),
|
||||
];
|
||||
|
||||
public string Name => "changelog";
|
||||
public string Summary => "Release notes from Conventional Commits on stdin (--title, --out file)";
|
||||
|
||||
public async Task<int> RunAsync(string[] args)
|
||||
{
|
||||
var a = new Args(args);
|
||||
IReadOnlyList<string> input = a.Get("in") is { } file ? await File.ReadAllLinesAsync(file) : ReadStdin();
|
||||
var markdown = Render(input, a.Get("title"));
|
||||
if (a.Get("out") is { } outFile)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outFile))!);
|
||||
await File.WriteAllTextAsync(outFile, markdown, new UTF8Encoding(false));
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.Write(markdown);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal static string Render(IEnumerable<string> lines, string? title)
|
||||
{
|
||||
var groups = new Dictionary<string, List<string>>(StringComparer.Ordinal);
|
||||
var breaking = new List<string>();
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var tab = line.IndexOf('\t');
|
||||
var hash = tab > 0 ? line[..tab] : string.Empty;
|
||||
var subject = tab > 0 ? line[(tab + 1)..] : line;
|
||||
var m = Conventional().Match(subject);
|
||||
if (!m.Success) continue;
|
||||
var type = m.Groups["type"].Value.ToLowerInvariant();
|
||||
var scope = m.Groups["scope"].Success ? $"**{m.Groups["scope"].Value}**: " : string.Empty;
|
||||
var entry = $"- {scope}{m.Groups["desc"].Value.Trim()}{(hash.Length > 0 ? $" ({hash})" : string.Empty)}";
|
||||
if (m.Groups["bang"].Success) breaking.Add(entry);
|
||||
if (!groups.TryGetValue(type, out var list)) groups[type] = list = [];
|
||||
list.Add(entry);
|
||||
}
|
||||
|
||||
var sb = new StringBuilder();
|
||||
if (title is not null) sb.Append("# ").AppendLine(title).AppendLine();
|
||||
// The title alone says nothing about the release: the fallback depends on the entries written, not on the text.
|
||||
var written = false;
|
||||
if (breaking.Count > 0)
|
||||
{
|
||||
sb.AppendLine("### Breaking changes");
|
||||
foreach (var e in breaking) sb.AppendLine(e);
|
||||
sb.AppendLine();
|
||||
written = true;
|
||||
}
|
||||
foreach (var (type, heading) in Sections)
|
||||
{
|
||||
if (!groups.TryGetValue(type, out var entries)) continue;
|
||||
sb.Append("### ").AppendLine(heading);
|
||||
foreach (var e in entries) sb.AppendLine(e);
|
||||
sb.AppendLine();
|
||||
written = true;
|
||||
}
|
||||
if (!written) sb.AppendLine("Maintenance release.");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static List<string> ReadStdin()
|
||||
{
|
||||
var lines = new List<string>();
|
||||
if (!Console.IsInputRedirected) return lines;
|
||||
while (Console.In.ReadLine() is { } line) lines.Add(line);
|
||||
return lines;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^(?<type>[a-zA-Z]+)(?:\((?<scope>[^)]+)\))?(?<bang>!)?:\s*(?<desc>.+)$")]
|
||||
private static partial Regex Conventional();
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.Metadata;
|
||||
|
||||
namespace Chronos.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Per-file decode report for a folder of photos: format, the tier the managed decoders reach (the server's view — WIC
|
||||
/// does not exist in this tool), dimensions, camera, capture time and its source, warnings; then a summary per format.
|
||||
/// </summary>
|
||||
internal sealed class DiagnoseCommand : ICommand
|
||||
{
|
||||
public string Name => "diagnose";
|
||||
public string Summary => "Decode tiers and metadata of the photos in a folder (--recursive, --formats)";
|
||||
|
||||
public Task<int> RunAsync(string[] args)
|
||||
{
|
||||
var a = new Args(args, "recursive", "formats");
|
||||
if (a.Has("formats")) PrintFormats();
|
||||
if (a.Positional.Count == 0)
|
||||
{
|
||||
if (a.Has("formats")) return Task.FromResult(0);
|
||||
throw new ToolException("Usage: diagnose <folder> [--recursive] [--formats]");
|
||||
}
|
||||
var folder = Path.GetFullPath(a.Positional[0]);
|
||||
if (!Directory.Exists(folder)) throw new ToolException($"Folder not found: {folder}");
|
||||
var files = Directory.EnumerateFiles(folder, "*", a.Has("recursive") ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
|
||||
.Where(ImageFormatInfo.IsSupportedExtension)
|
||||
.Order(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
Console.WriteLine($"{files.Count} photo(s) in {folder}. Tiers are the managed (server) view; WIC is not available in Chronos.Tools.");
|
||||
var provider = new ManagedDecoderProvider();
|
||||
var summary = new SortedDictionary<string, int[]>(StringComparer.Ordinal);
|
||||
foreach (var file in files)
|
||||
{
|
||||
var line = Describe(provider, folder, file, out var format, out var tier);
|
||||
Console.WriteLine(line);
|
||||
if (!summary.TryGetValue(format, out var counts)) summary[format] = counts = new int[3];
|
||||
counts[(int)tier - 1]++;
|
||||
}
|
||||
if (summary.Count > 0)
|
||||
{
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"{"Format",-8} {"Files",6} {"Native",7} {"Preview",8} {"None",5}");
|
||||
foreach (var (format, c) in summary) Console.WriteLine($"{format,-8} {c.Sum(),6} {c[0],7} {c[1],8} {c[2],5}");
|
||||
}
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
private static string Describe(ManagedDecoderProvider provider, string folder, string file, out string format, out DecodeTier tier)
|
||||
{
|
||||
var name = Path.GetRelativePath(folder, file);
|
||||
FrameMetadata metadata;
|
||||
FileTier fileTier;
|
||||
try
|
||||
{
|
||||
metadata = MetadataReader.Read(file);
|
||||
fileTier = provider.Probe(file);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
format = ImageFormatInfo.FromPath(file).Format.ToString();
|
||||
tier = DecodeTier.Unavailable;
|
||||
return $"{name}\n unreadable: {ex.Message}";
|
||||
}
|
||||
format = fileTier.Format.ToString();
|
||||
tier = fileTier.Tier;
|
||||
var (w, h) = fileTier.Width > 0 ? (fileTier.Width, fileTier.Height) : metadata.OrientedSize;
|
||||
var camera = string.Join(' ', new[] { metadata.Make, metadata.Model }.Where(s => !string.IsNullOrEmpty(s)));
|
||||
var captured = metadata.CapturedAt is { } t
|
||||
? $"{t.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)} ({metadata.TimestampSource})"
|
||||
: "unknown";
|
||||
var tierText = fileTier.Tier switch
|
||||
{
|
||||
DecodeTier.Native => $"native ({fileTier.Decoder})",
|
||||
DecodeTier.EmbeddedPreview => "embedded preview",
|
||||
_ => "unavailable",
|
||||
};
|
||||
var lines = new List<string> { $"{name}\n {format,-5} {tierText,-24} {$"{w}x{h}",-11} {(camera.Length > 0 ? camera : "camera unknown")}; captured {captured}" };
|
||||
if (fileTier.Reason is { } reason) lines.Add($" reason: {reason}");
|
||||
lines.AddRange(metadata.Warnings.Select(warning => $" warning: {warning}"));
|
||||
return string.Join('\n', lines);
|
||||
}
|
||||
|
||||
private static void PrintFormats()
|
||||
{
|
||||
Console.WriteLine("Format tiers (managed decoders):");
|
||||
foreach (var row in DecoderFactory.DescribeFormats(DecoderFactory.CreateServer()))
|
||||
{
|
||||
var tier = row.Tier switch
|
||||
{
|
||||
DecodeTier.Native => "native",
|
||||
DecodeTier.EmbeddedPreview => "embedded preview",
|
||||
_ => "unavailable",
|
||||
};
|
||||
Console.WriteLine($" {row.Format.Format,-8} {string.Join(' ', row.Format.Extensions),-18} {tier}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Chronos.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Fetches the CC0 RAW samples listed in <c>tests/fixtures/manifest.json</c> into <c>tests/fixtures/external</c> (BRIEF
|
||||
/// §20.2): interrupted downloads resume from their <c>.part</c> file with an HTTP range request, every file is verified
|
||||
/// against its SHA-256, and verified files are skipped. An entry whose <c>sha256</c> is null gets the hash of its first
|
||||
/// download recorded in <c>external/recorded-hashes.json</c> (later runs verify against it) and printed so it can be
|
||||
/// copied into the manifest. A fixture that cannot be fetched is reported as a workflow warning (<c>::warning</c>) when
|
||||
/// running in Gitea Actions (tests that need it skip); <c>--allow-missing</c> then keeps the exit code 0, so CI shows the warning
|
||||
/// instead of a silently "passed" step.
|
||||
/// </summary>
|
||||
internal sealed class FixturesCommand : ICommand
|
||||
{
|
||||
private const string RecordedHashesFile = "recorded-hashes.json";
|
||||
|
||||
public string Name => "fixtures";
|
||||
public string Summary => "Download and verify the CC0 RAW samples in tests/fixtures/manifest.json (--manifest, --out, --allow-missing)";
|
||||
|
||||
public async Task<int> RunAsync(string[] args)
|
||||
{
|
||||
var a = new Args(args, "allow-missing");
|
||||
var root = Args.RepoRoot();
|
||||
var manifestPath = a.Get("manifest") ?? Path.Combine(root, "tests", "fixtures", "manifest.json");
|
||||
var outDir = a.Get("out") ?? Path.Combine(root, "tests", "fixtures", "external");
|
||||
if (!File.Exists(manifestPath)) throw new ToolException($"Manifest not found: {manifestPath}");
|
||||
var entries = ReadManifest(manifestPath);
|
||||
Directory.CreateDirectory(outDir);
|
||||
var recordedPath = Path.Combine(outDir, RecordedHashesFile);
|
||||
var recorded = File.Exists(recordedPath)
|
||||
? JsonSerializer.Deserialize<Dictionary<string, string>>(await File.ReadAllTextAsync(recordedPath)) ?? []
|
||||
: [];
|
||||
var newlyRecorded = new List<string>();
|
||||
var missing = new List<(Entry Entry, string Reason)>();
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(10) };
|
||||
http.DefaultRequestHeaders.UserAgent.ParseAdd("Chronos.Tools/1.0 (+fixtures)");
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
var target = Path.Combine(outDir, entry.Name);
|
||||
var expected = entry.Sha256 ?? recorded.GetValueOrDefault(entry.Name);
|
||||
try
|
||||
{
|
||||
if (File.Exists(target))
|
||||
{
|
||||
var hash = await HashAsync(target);
|
||||
if (expected is null || hash.Equals(expected, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (expected is null) Record(entry.Name, hash);
|
||||
Console.WriteLine($"ok {entry.Name} (verified)");
|
||||
continue;
|
||||
}
|
||||
Console.WriteLine($"mismatch {entry.Name}: downloading again");
|
||||
File.Delete(target);
|
||||
}
|
||||
var actual = await DownloadAsync(http, entry, target);
|
||||
if (expected is not null && !actual.Equals(expected, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
File.Delete(target);
|
||||
throw new InvalidDataException($"SHA-256 {actual} does not match {expected}");
|
||||
}
|
||||
if (expected is null) Record(entry.Name, actual);
|
||||
Console.WriteLine($"fetched {entry.Name} ({new FileInfo(target).Length / 1e6:F1} MB)");
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or IOException or InvalidDataException or TaskCanceledException or UnauthorizedAccessException)
|
||||
{
|
||||
missing.Add((entry, ex.Message));
|
||||
Console.Error.WriteLine($"failed {entry.Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
await File.WriteAllTextAsync(recordedPath, JsonSerializer.Serialize(recorded, new JsonSerializerOptions { WriteIndented = true }));
|
||||
if (newlyRecorded.Count > 0)
|
||||
{
|
||||
Console.WriteLine("Recorded SHA-256 of first downloads (copy into the manifest to pin them):");
|
||||
foreach (var line in newlyRecorded) Console.WriteLine(" " + line);
|
||||
}
|
||||
if (missing.Count == 0)
|
||||
{
|
||||
Console.WriteLine($"{entries.Count} fixture(s) ready in {outDir}");
|
||||
return 0;
|
||||
}
|
||||
Console.WriteLine($"{missing.Count} of {entries.Count} fixture(s) missing; the tests that need them are skipped.");
|
||||
// Gitea Actions sets GITHUB_ACTIONS (and GITEA_ACTIONS) and keeps the GitHub-compatible workflow commands.
|
||||
if (Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true")
|
||||
{
|
||||
var manifestFile = Path.GetRelativePath(root, manifestPath).Replace('\\', '/');
|
||||
foreach (var (entry, reason) in missing) Console.WriteLine(Annotation(manifestFile, entry, reason));
|
||||
}
|
||||
return a.Has("allow-missing") ? 0 : 1;
|
||||
|
||||
void Record(string name, string hash)
|
||||
{
|
||||
if (recorded.GetValueOrDefault(name) == hash) return;
|
||||
recorded[name] = hash;
|
||||
newlyRecorded.Add($"{name}: {hash}");
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed record Entry(string Name, Uri Url, string? Sha256, long? Size, string? Format);
|
||||
|
||||
/// <summary>A workflow warning naming the missing fixture, why, and where the fix goes.</summary>
|
||||
internal static string Annotation(string manifestFile, Entry entry, string reason)
|
||||
{
|
||||
var message = $"{entry.Name} ({entry.Format ?? "RAW"}) could not be fetched from {entry.Url.AbsoluteUri}: {reason.TrimEnd('.')}. " +
|
||||
"Its decode tests are skipped. Replace the url in the manifest (see its 'instructions').";
|
||||
return $"::warning file={Escape(manifestFile, property: true)},title={Escape("RAW fixture missing", property: true)}::{Escape(message, property: false)}";
|
||||
}
|
||||
|
||||
/// <summary>Workflow-command escaping (properties also escape ':' and ',').</summary>
|
||||
private static string Escape(string value, bool property)
|
||||
{
|
||||
var escaped = value.Replace("%", "%25", StringComparison.Ordinal).Replace("\r", "%0D", StringComparison.Ordinal).Replace("\n", "%0A", StringComparison.Ordinal);
|
||||
return property ? escaped.Replace(":", "%3A", StringComparison.Ordinal).Replace(",", "%2C", StringComparison.Ordinal) : escaped;
|
||||
}
|
||||
|
||||
internal static List<Entry> ReadManifest(string path)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(path));
|
||||
if (!doc.RootElement.TryGetProperty("files", out var files) || files.ValueKind != JsonValueKind.Array) throw new ToolException("Manifest has no 'files' array");
|
||||
var entries = new List<Entry>();
|
||||
foreach (var f in files.EnumerateArray())
|
||||
{
|
||||
var name = f.GetProperty("name").GetString() ?? throw new ToolException("Fixture without a name");
|
||||
if (name != Path.GetFileName(name) || name.StartsWith('.')) throw new ToolException($"Fixture name must be a plain file name: {name}");
|
||||
if (!Uri.TryCreate(f.GetProperty("url").GetString(), UriKind.Absolute, out var url) || url.Scheme != Uri.UriSchemeHttps)
|
||||
throw new ToolException($"Fixture {name} needs an https URL");
|
||||
var sha = f.TryGetProperty("sha256", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString() : null;
|
||||
long? size = f.TryGetProperty("size", out var z) && z.ValueKind == JsonValueKind.Number ? z.GetInt64() : null;
|
||||
var format = f.TryGetProperty("format", out var fm) && fm.ValueKind == JsonValueKind.String ? fm.GetString() : null;
|
||||
entries.Add(new Entry(name, url, sha, size, format));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>Downloads into <c>target.part</c>, resuming from its length with a range request, then renames it.</summary>
|
||||
private static async Task<string> DownloadAsync(HttpClient http, Entry entry, string target)
|
||||
{
|
||||
var part = target + ".part";
|
||||
var existing = File.Exists(part) ? new FileInfo(part).Length : 0;
|
||||
if (entry.Size is not { } size || existing < size)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, entry.Url);
|
||||
if (existing > 0) request.Headers.Range = new RangeHeaderValue(existing, null);
|
||||
using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
|
||||
if (response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable && existing > 0)
|
||||
{
|
||||
// The partial file is already complete (or the server lost it): verified below.
|
||||
}
|
||||
else
|
||||
{
|
||||
response.EnsureSuccessStatusCode();
|
||||
var resume = response.StatusCode == HttpStatusCode.PartialContent;
|
||||
await using var output = new FileStream(part, resume ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous);
|
||||
await using var input = await response.Content.ReadAsStreamAsync();
|
||||
await input.CopyToAsync(output);
|
||||
}
|
||||
}
|
||||
if (entry.Size is { } expected && new FileInfo(part).Length is var length && length != expected)
|
||||
{
|
||||
File.Delete(part);
|
||||
throw new InvalidDataException($"size {length} differs from {expected}");
|
||||
}
|
||||
var hash = await HashAsync(part);
|
||||
File.Move(part, target, overwrite: true);
|
||||
return hash;
|
||||
}
|
||||
|
||||
private static async Task<string> HashAsync(string path)
|
||||
{
|
||||
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace Chronos.Tools.Commands;
|
||||
|
||||
/// <summary>What <see cref="GiteaReleaseCommand"/> publishes.</summary>
|
||||
internal sealed record ReleaseRequest(
|
||||
string Server,
|
||||
string Repository,
|
||||
string Tag,
|
||||
string Title,
|
||||
string Notes,
|
||||
IReadOnlyList<string> Files,
|
||||
bool Prerelease,
|
||||
string? Target = null);
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a release through the Gitea REST API (BRIEF §19.3, amended 2026-10-23, R3): a tag without a release gets
|
||||
/// a draft first, every file of the assets folder is uploaded (a file of the same name is replaced), and only then the
|
||||
/// title, notes and pre-release flag are set and the release is published, so clients never see a release without its
|
||||
/// files. The token is read from an environment variable and never written out.
|
||||
/// </summary>
|
||||
internal sealed class GiteaReleaseCommand : ICommand
|
||||
{
|
||||
public string Name => "gitea-release";
|
||||
public string Summary => "Create or update a Gitea release with its files (--server, --repo, --tag, --title, --notes-file, --assets, --prerelease, --token-env)";
|
||||
|
||||
public async Task<int> RunAsync(string[] args)
|
||||
{
|
||||
var a = new Args(args);
|
||||
var assets = a.Get("assets");
|
||||
if (assets is not null && !Directory.Exists(assets)) throw new ToolException($"Assets folder not found: {assets}");
|
||||
var request = new ReleaseRequest(
|
||||
Required(a, "server"),
|
||||
Required(a, "repo"),
|
||||
Required(a, "tag"),
|
||||
Required(a, "title"),
|
||||
a.Get("notes-file") is { } notes ? await File.ReadAllTextAsync(notes) : string.Empty,
|
||||
assets is null ? [] : Directory.GetFiles(assets).Order(StringComparer.Ordinal).ToList(),
|
||||
// "--prerelease" alone or "--prerelease true"; "--prerelease false" lets a workflow pass its output as is.
|
||||
a.Has("prerelease") && !string.Equals(a.Get("prerelease"), "false", StringComparison.OrdinalIgnoreCase),
|
||||
a.Get("target"));
|
||||
var variable = a.Get("token-env", "GITEA_TOKEN");
|
||||
var token = Environment.GetEnvironmentVariable(variable);
|
||||
if (string.IsNullOrEmpty(token)) throw new ToolException($"The token variable {variable} is empty.");
|
||||
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(30) };
|
||||
var url = await PublishAsync(http, request, token, Console.Out, CancellationToken.None);
|
||||
Console.WriteLine($"Release {request.Tag} published: {url}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>Creates or updates the release, uploads its files, publishes it and checks what the server lists.</summary>
|
||||
/// <returns>The release page.</returns>
|
||||
internal static async Task<string> PublishAsync(HttpClient http, ReleaseRequest request, string token, TextWriter log, CancellationToken ct)
|
||||
{
|
||||
if (request.Repository.Split('/') is not [{ Length: > 0 }, { Length: > 0 }])
|
||||
throw new ToolException($"--repo must be owner/name, not '{request.Repository}'.");
|
||||
var api = $"{request.Server.TrimEnd('/')}/api/v1/repos/{request.Repository}";
|
||||
var client = new Client(http, token, ct);
|
||||
|
||||
var existing = await client.SendAsync(HttpMethod.Get, $"{api}/releases/tags/{Uri.EscapeDataString(request.Tag)}", null, HttpStatusCode.OK, HttpStatusCode.NotFound);
|
||||
long id;
|
||||
var published = false;
|
||||
if (existing.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
var draft = new JsonObject
|
||||
{
|
||||
["tag_name"] = request.Tag,
|
||||
["name"] = request.Title,
|
||||
["body"] = request.Notes,
|
||||
["draft"] = true,
|
||||
["prerelease"] = request.Prerelease,
|
||||
};
|
||||
if (!string.IsNullOrEmpty(request.Target)) draft["target_commitish"] = request.Target;
|
||||
id = Id((await client.SendAsync(HttpMethod.Post, $"{api}/releases", Json(draft), HttpStatusCode.Created)).Body);
|
||||
log.WriteLine($"Release {request.Tag}: draft {id} created");
|
||||
}
|
||||
else
|
||||
{
|
||||
id = Id(existing.Body);
|
||||
published = existing.Body?["draft"]?.GetValue<bool>() != true;
|
||||
log.WriteLine($"Release {request.Tag}: {id} exists, its files are replaced");
|
||||
}
|
||||
|
||||
var listed = (await client.SendAsync(HttpMethod.Get, $"{api}/releases/{id}/assets", null, HttpStatusCode.OK)).Body as JsonArray ?? [];
|
||||
var assets = listed.OfType<JsonObject>()
|
||||
.Where(x => x["name"] is not null && x["id"] is not null)
|
||||
.ToDictionary(x => x["name"]!.GetValue<string>(), x => x["id"]!.GetValue<long>(), StringComparer.Ordinal);
|
||||
// The checksums go last. On a release clients can already see, the old ones go first: while the files are
|
||||
// replaced, the app finds no SHA256SUMS and offers only the release page instead of a mismatching download.
|
||||
var files = request.Files.OrderBy(f => Path.GetFileName(f) == Checksums ? 1 : 0).ToList();
|
||||
if (published && assets.Remove(Checksums, out var oldChecksums))
|
||||
await client.SendAsync(HttpMethod.Delete, $"{api}/releases/{id}/assets/{oldChecksums}", null, HttpStatusCode.NoContent, HttpStatusCode.NotFound);
|
||||
foreach (var file in files)
|
||||
{
|
||||
var name = Path.GetFileName(file);
|
||||
if (assets.TryGetValue(name, out var old))
|
||||
await client.SendAsync(HttpMethod.Delete, $"{api}/releases/{id}/assets/{old}", null, HttpStatusCode.NoContent, HttpStatusCode.NotFound);
|
||||
// The request disposes its content, and with it the stream: the length is read first.
|
||||
var length = new FileInfo(file).Length;
|
||||
await using var stream = File.OpenRead(file);
|
||||
using var part = new StreamContent(stream);
|
||||
part.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
using var form = new MultipartFormDataContent { { part, "attachment", name } };
|
||||
await client.SendAsync(HttpMethod.Post, $"{api}/releases/{id}/assets?name={Uri.EscapeDataString(name)}", form, HttpStatusCode.Created);
|
||||
log.WriteLine($" {name} ({length:N0} bytes)");
|
||||
}
|
||||
|
||||
// Every file at its full size before the release is published (a new release is still a draft here).
|
||||
var uploaded = ((await client.SendAsync(HttpMethod.Get, $"{api}/releases/{id}/assets", null, HttpStatusCode.OK)).Body as JsonArray ?? [])
|
||||
.OfType<JsonObject>()
|
||||
.Where(x => x["name"] is not null)
|
||||
.ToDictionary(x => x["name"]!.GetValue<string>(), x => x["size"]?.GetValue<long>() ?? -1, StringComparer.Ordinal);
|
||||
foreach (var file in files)
|
||||
{
|
||||
var name = Path.GetFileName(file);
|
||||
var size = new FileInfo(file).Length;
|
||||
if (!uploaded.TryGetValue(name, out var listedSize) || listedSize != size)
|
||||
throw new ToolException($"Release {request.Tag}: {name} is listed with {(uploaded.ContainsKey(name) ? listedSize + " bytes" : "no file")}, expected {size} bytes.");
|
||||
}
|
||||
|
||||
var publish = new JsonObject
|
||||
{
|
||||
["name"] = request.Title,
|
||||
["body"] = request.Notes,
|
||||
["draft"] = false,
|
||||
["prerelease"] = request.Prerelease,
|
||||
};
|
||||
await client.SendAsync(new HttpMethod("PATCH"), $"{api}/releases/{id}", Json(publish), HttpStatusCode.OK);
|
||||
|
||||
var release = (await client.SendAsync(HttpMethod.Get, $"{api}/releases/{id}", null, HttpStatusCode.OK)).Body as JsonObject
|
||||
?? throw new ToolException($"Release {id}: the server returned no release.");
|
||||
if (release["draft"]?.GetValue<bool>() == true) throw new ToolException($"Release {request.Tag} is still a draft.");
|
||||
return release["html_url"]?.GetValue<string>() ?? $"{request.Server.TrimEnd('/')}/{request.Repository}/releases/tag/{request.Tag}";
|
||||
}
|
||||
|
||||
/// <summary>The checksum file the in-app update verifies downloads against (BRIEF §18).</summary>
|
||||
private const string Checksums = "SHA256SUMS";
|
||||
|
||||
private static string Required(Args a, string key) =>
|
||||
a.Get(key) is { Length: > 0 } value ? value : throw new ToolException($"--{key} is required.");
|
||||
|
||||
private static StringContent Json(JsonObject body) => new(body.ToJsonString(), Encoding.UTF8, "application/json");
|
||||
|
||||
private static long Id(JsonNode? release) =>
|
||||
release?["id"]?.GetValue<long>() ?? throw new ToolException("The server's reply has no release id.");
|
||||
|
||||
private sealed class Client(HttpClient http, string token, CancellationToken ct)
|
||||
{
|
||||
public async Task<(HttpStatusCode Status, JsonNode? Body)> SendAsync(HttpMethod method, string url, HttpContent? content, params HttpStatusCode[] expected)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, url) { Content = content };
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("token", token);
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
using var response = await http.SendAsync(request, ct).ConfigureAwait(false);
|
||||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
if (!expected.Contains(response.StatusCode))
|
||||
{
|
||||
var detail = text.Length > 500 ? text[..500] + "…" : text;
|
||||
throw new ToolException($"{method} {url}: {(int)response.StatusCode} {response.ReasonPhrase} {detail}".TrimEnd());
|
||||
}
|
||||
try
|
||||
{
|
||||
return (response.StatusCode, text.Length == 0 ? null : JsonNode.Parse(text));
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return (response.StatusCode, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml.Linq;
|
||||
using Chronos.Core.Localization;
|
||||
|
||||
namespace Chronos.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// <c>i18n check</c>: completeness of <c>en</c> and <c>it</c>, 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).
|
||||
/// <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.
|
||||
/// <c>i18n prune</c>: removes from every translation the keys English no longer has (renamed or removed keys), which
|
||||
/// <c>check</c> reports as orphans.
|
||||
/// </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> | missing --culture <c> [--all] | import --culture <c> <tsv> | prune";
|
||||
|
||||
public Task<int> RunAsync(string[] 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"));
|
||||
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"), 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")),
|
||||
"prune" => Prune(Path.Combine(root, "i18n"), catalog),
|
||||
_ => 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");
|
||||
if (CountedNoun(key, entry.Value) is { } noun)
|
||||
errors.Add($"en: {key} counts {noun} but is not a plural stem: write {key}.one and {key}.other with the count as {{0}}, or a label (\"Frames: {{0}}\")");
|
||||
if (CountedTally(key, entry.Value) is { } word)
|
||||
errors.Add($"en: {key} puts counts before \"{word}\", which agrees with the number in other languages: write labels (\"Copied: {{0}}, failed: {{1}}\")");
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
CheckTranslation(culture, key, entry, translated, en, errors, warnings);
|
||||
}
|
||||
if (missing > 0) warnings.Add($"{culture}: {missing} key(s) not translated yet");
|
||||
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);
|
||||
foreach (var (file, key) in UsedKeys(root, areas))
|
||||
{
|
||||
if (en.ContainsKey(key)) continue;
|
||||
// Prefix lookups such as L("Settings.Page." + page) are satisfied by any key under the prefix.
|
||||
if (key.EndsWith('.') && en.Keys.Any(k => k.StartsWith(key, StringComparison.Ordinal))) 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 (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");
|
||||
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;
|
||||
}
|
||||
|
||||
/// <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 noun a plain (non-plural) English value counts with a number in front of it ("{0} frames", "{0} short gaps"):
|
||||
/// such a key reads "1 frames", and Italian or Slavic forms cannot follow the number either (BRIEF §16). Bounds the code
|
||||
/// sets ("at most {0} characters") and labels ("Frames: {0}") count nothing; null when the value counts nothing.
|
||||
/// </summary>
|
||||
internal static string? CountedNoun(string key, string value)
|
||||
{
|
||||
if (PluralSuffix().IsMatch(key[(key.LastIndexOf('.') + 1)..])) return null;
|
||||
foreach (Match m in CountedNounRegex().Matches(value))
|
||||
{
|
||||
if (!m.Groups["bound"].Success) return m.Groups["noun"].Value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first word of a tally that counts with participles or adjectives ("{0} copied · {1} failed", "{1} made, {2}
|
||||
/// reused"): Italian, Polish or Russian inflect those words for the number ("1 copiata", "3 copiate"), so the tally
|
||||
/// reads "1 copiate" unless it is written as labels ("Copied: {0} · failed: {1}"). Only a list of two or more counts
|
||||
/// is a tally: before a single "failed" or "missing" the placeholder is as often a name ("Import of {0} failed") or a
|
||||
/// size ("{0} missing") as a count. Null when the value holds no such tally.
|
||||
/// </summary>
|
||||
internal static string? CountedTally(string key, string value)
|
||||
{
|
||||
if (PluralSuffix().IsMatch(key[(key.LastIndexOf('.') + 1)..])) return null;
|
||||
var items = CountedTallyRegex().Matches(value);
|
||||
return items.Count >= 2 ? items[0].Groups["word"].Value : null;
|
||||
}
|
||||
|
||||
/// <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);
|
||||
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 (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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the orphan keys of every translation under <paramref name="dir"/> (those <see cref="Check"/> reports: not in
|
||||
/// English and not a plural form of an English plural key), rewriting only the files that had some, as
|
||||
/// <see cref="Import"/> writes them. English is the source and is never touched. Returns the number of keys removed.
|
||||
/// </summary>
|
||||
internal static int PruneOrphans(string dir, Catalog catalog)
|
||||
{
|
||||
var en = catalog.Cultures["en"];
|
||||
var removed = 0;
|
||||
foreach (var cultureDir in Directory.EnumerateDirectories(dir).Order(StringComparer.Ordinal))
|
||||
{
|
||||
var culture = Path.GetFileName(cultureDir);
|
||||
if (culture.Equals("en", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
foreach (var path in Directory.EnumerateFiles(cultureDir, "*.resx").Order(StringComparer.Ordinal))
|
||||
{
|
||||
var values = new SortedDictionary<string, string>(StringComparer.Ordinal);
|
||||
var orphans = 0;
|
||||
foreach (var data in XDocument.Load(path).Root!.Elements("data"))
|
||||
{
|
||||
var key = (string)data.Attribute("name")!;
|
||||
if (en.ContainsKey(key) || PluralStem(key, en) is not null) values[key] = (string?)data.Element("value") ?? string.Empty;
|
||||
else orphans++;
|
||||
}
|
||||
if (orphans == 0) continue;
|
||||
WriteResx(path, values);
|
||||
removed += orphans;
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
private static int Prune(string dir, Catalog catalog)
|
||||
{
|
||||
var removed = PruneOrphans(dir, catalog);
|
||||
Console.WriteLine($"i18n: {removed} orphan key(s) removed");
|
||||
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");
|
||||
// Atomic replace: other translators may be running `i18n check` over the same tree.
|
||||
var temp = path + ".tmp";
|
||||
File.WriteAllText(temp, sb.ToString(), new UTF8Encoding(false));
|
||||
File.Move(temp, path, overwrite: true);
|
||||
}
|
||||
|
||||
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;
|
||||
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>, and any string literal shaped
|
||||
/// <c>Area.Group.Name</c> whose area has a catalog, since reason and warning keys travel as data), XAML
|
||||
/// (<c>{l:Loc …}</c>) and admin JS (<c>t("…")</c>, <c>plural("…")</c>).
|
||||
/// </summary>
|
||||
private static IEnumerable<(string File, string Key)> UsedKeys(string root, IReadOnlySet<string> areas)
|
||||
{
|
||||
var src = Path.Combine(root, "src");
|
||||
foreach (var file in Directory.EnumerateFiles(src, "*.*", SearchOption.AllDirectories))
|
||||
{
|
||||
if (IsBuildOutput(file)) 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);
|
||||
if (ext != ".cs") continue;
|
||||
foreach (Match m in CsKeyLiteralRegex().Matches(text))
|
||||
{
|
||||
if (areas.Contains(m.Groups[2].Value)) yield return (file, m.Groups[1].Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Error codes of the server (literals passed to <c>ApiErrors</c>, <c>Outcome.Fail</c> and the local <c>Fail</c> and
|
||||
/// <c>TooMany</c> helpers) whose message <c>Server.Error.<Code></c> is not in <paramref name="keys"/>, each once.
|
||||
/// <c>ApiErrors.Message</c> builds that key at run time, so the scan of used keys cannot see it.
|
||||
/// </summary>
|
||||
internal static IEnumerable<(string File, string Code, string Key)> MissingErrorMessages(string root, IReadOnlySet<string> keys)
|
||||
{
|
||||
var reported = new HashSet<string>(StringComparer.Ordinal);
|
||||
var server = Path.Combine(root, "src", "Chronos.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The literal error codes (snake_case) a C# source passes to the server's error helpers.</summary>
|
||||
internal static IEnumerable<string> ErrorCodes(string source) => ErrorCodeRegex().Matches(source).Select(m => m.Groups[1].Value);
|
||||
|
||||
/// <summary>The message key of an error code, built like <c>ApiErrors.Message</c>: <c>render_exists</c> → <c>Server.Error.RenderExists</c>.</summary>
|
||||
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();
|
||||
|
||||
/// <summary>A call of an error helper up to its first string argument (no statement end in between) when that is a snake_case code.</summary>
|
||||
[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();
|
||||
|
||||
[GeneratedRegex(@"(?<![@$\w])""(([A-Z][A-Za-z0-9]*)\.[A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)""")]
|
||||
private static partial Regex CsKeyLiteralRegex();
|
||||
|
||||
[GeneratedRegex(@"\{(?:l|loc):Loc\s+(?:Key=)?([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)")]
|
||||
private static partial Regex XamlKeyRegex();
|
||||
|
||||
[GeneratedRegex(@"(?:\b(?:t|plural)\(\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();
|
||||
|
||||
/// <summary>A placeholder, up to two describing words that are not function words, then a noun the product counts.</summary>
|
||||
[GeneratedRegex(@"(?<bound>\b(?i:at least|at most|up to|to)\s+)?\{\d+(?:[,:][^}]*)?\}(?:\s+(?!(?:and|or|of|the|a|an|to|on|in|at|by|for|with|from|is|are|was|were)\b)[a-z]+){0,2}?\s+"
|
||||
+ @"(?<noun>frames|photos|sequences|files|folders|exports|renders|jobs|times|gaps|sessions|changes|steps|warnings|cores|days|hours|minutes|"
|
||||
+ @"items|cards|tags|users|accounts|nodes|presets|characters|originals|copies|groups|issues|cameras|lenses|uploads|downloads|transfers|"
|
||||
+ @"keyframes|encoders|errors|problems|duplicates|locks|packs|flags|lines|months|years|previews|settings|versions|workers|stars|rows|chunks)\b")]
|
||||
private static partial Regex CountedNounRegex();
|
||||
|
||||
/// <summary>One item of a tally: a placeholder that starts the text or follows a list separator, then a participle or
|
||||
/// adjective that ends the item.</summary>
|
||||
[GeneratedRegex(@"(?<=^|[,;:·(]\s*)\{\d+(?:[,:][^}]*)?\}\s+(?<word>copied|skipped|failed|made|reused|missing|damaged|unreadable|deleted|kept|"
|
||||
+ @"moved|removed|added|indexed|adopted|checked|intact|hashed|verified|imported|exported|rendered|renamed|uploaded|downloaded|sent|"
|
||||
+ @"received|created|updated|changed|restored|trashed|merged|found|lost|broken|corrupt|undecodable|unchanged|cancelled|done|finished|"
|
||||
+ @"queued|running|waiting|pending|selected|linked|synced|compacted|flagged|marked)(?=\s*(?:$|[,;·.)]))")]
|
||||
private static partial Regex CountedTallyRegex();
|
||||
|
||||
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 Chronos.Core.Branding;
|
||||
using Chronos.Core.Codecs.Ico;
|
||||
using Chronos.Core.Codecs.Png;
|
||||
|
||||
namespace Chronos.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, "chronos"),
|
||||
(BrandVariant.Server, "chronos-server"),
|
||||
(BrandVariant.Uploader, "chronos-uploader"),
|
||||
(BrandVariant.Mono, "chronos-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, "chronos.svg"), BrandMark.ToSvg(BrandVariant.App));
|
||||
File.WriteAllText(Path.Combine(svgDir, "chronos-server.svg"), BrandMark.ToSvg(BrandVariant.Server));
|
||||
File.WriteAllText(Path.Combine(svgDir, "chronos-uploader.svg"), BrandMark.ToSvg(BrandVariant.Uploader));
|
||||
File.WriteAllText(Path.Combine(svgDir, "chronos-mono.svg"), BrandMark.ToSvg(BrandVariant.Mono));
|
||||
}
|
||||
|
||||
Console.WriteLine($"Icons written to {outDir}");
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Packaging;
|
||||
|
||||
namespace Chronos.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// <c>pack-installer --setup Chronos.Setup.exe --product Chronos --version 1.2.3 --component Id=folder … --out file</c>:
|
||||
/// appends a TPK1 payload (BRIEF §18) to the setup program. Known component ids carry their display name, default
|
||||
/// selection, shortcuts and file types; unknown ids are packed as plain, preselected components. The Server
|
||||
/// installs only for all users: it is registered as a LocalSystem service, which must run from Program Files.
|
||||
/// </summary>
|
||||
internal sealed class PackInstallerCommand : ICommand
|
||||
{
|
||||
private sealed record KnownComponent(string DisplayName, bool DefaultSelected, string Program, bool Desktop, PayloadAssociation? Association, bool AllUsersOnly = false);
|
||||
|
||||
/// <remarks>The file type's description is the English fallback; setup writes it in its own language (<c>Setup.FileType.*</c>).</remarks>
|
||||
private static readonly Dictionary<string, KnownComponent> Known = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["Chronos"] = new("Chronos", true, "Chronos.exe", Desktop: true,
|
||||
new PayloadAssociation { Component = "Chronos", Extension = ".chronos", ProgId = "Chronos.Project", Description = "Chronos project", Target = "Chronos.exe" }),
|
||||
["Uploader"] = new("Chronos Uploader", true, "Chronos.Uploader.exe", Desktop: true, null),
|
||||
["Server"] = new("Chronos Server", false, "Chronos.Server.exe", Desktop: false, null, AllUsersOnly: true),
|
||||
};
|
||||
|
||||
public string Name => "pack-installer";
|
||||
public string Summary => "--setup <exe> --product <name> --version <v> --component Id=dir … --out <file>";
|
||||
|
||||
public Task<int> RunAsync(string[] args)
|
||||
{
|
||||
var options = Parse(args);
|
||||
var setup = Required(options, "setup");
|
||||
var output = Required(options, "out");
|
||||
if (!File.Exists(setup)) throw new ToolException($"Setup program '{setup}' not found.");
|
||||
if (!options.TryGetValue("component", out var specs)) throw new ToolException("At least one --component Id=folder is required.");
|
||||
|
||||
var components = new List<PayloadComponentSource>();
|
||||
var shortcuts = new List<PayloadShortcut>();
|
||||
var associations = new List<PayloadAssociation>();
|
||||
foreach (var spec in specs)
|
||||
{
|
||||
var eq = spec.IndexOf('=', StringComparison.Ordinal);
|
||||
if (eq <= 0 || eq == spec.Length - 1) throw new ToolException($"--component expects Id=folder, got '{spec}'.");
|
||||
var id = spec[..eq];
|
||||
var folder = spec[(eq + 1)..];
|
||||
if (!PayloadManifest.IdentifierRegex().IsMatch(id)) throw new ToolException($"Component id '{id}' must be letters and digits.");
|
||||
if (components.Any(c => c.Id.Equals(id, StringComparison.OrdinalIgnoreCase))) throw new ToolException($"Component '{id}' given twice.");
|
||||
if (!Directory.Exists(folder)) throw new ToolException($"Component folder '{folder}' not found.");
|
||||
|
||||
if (!Known.TryGetValue(id, out var known))
|
||||
{
|
||||
components.Add(new PayloadComponentSource(id, id, true, folder));
|
||||
continue;
|
||||
}
|
||||
components.Add(new PayloadComponentSource(id, known.DisplayName, known.DefaultSelected, folder, known.AllUsersOnly));
|
||||
if (!File.Exists(Path.Combine(folder, known.Program)))
|
||||
{
|
||||
Console.Error.WriteLine($"warning: {id} has no {known.Program}; no shortcut or file type registered.");
|
||||
continue;
|
||||
}
|
||||
shortcuts.Add(new PayloadShortcut { Component = id, Name = known.DisplayName, Target = known.Program, StartMenu = true, Desktop = known.Desktop });
|
||||
if (known.Association is { } association) associations.Add(association);
|
||||
}
|
||||
|
||||
var source = new PayloadSource
|
||||
{
|
||||
Product = Required(options, "product"),
|
||||
Version = Required(options, "version"),
|
||||
Components = components,
|
||||
Shortcuts = shortcuts,
|
||||
Associations = associations,
|
||||
};
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output))!);
|
||||
var result = PayloadWriter.Write(setup, source, output);
|
||||
Console.WriteLine(string.Create(CultureInfo.InvariantCulture,
|
||||
$"{output}: {result.FileCount} files in {components.Count} component(s), {Megabytes(result.InstallerBytes)} ({result.InstallerBytes:N0} bytes), installs {Megabytes(result.InstalledBytes)}"));
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
catch (Exception ex) when (ex is PayloadException or ArgumentException or IOException)
|
||||
{
|
||||
throw new ToolException("pack-installer: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary><c>--key value</c> pairs; every key may repeat (only <c>--component</c> is meant to).</summary>
|
||||
private static Dictionary<string, List<string>> Parse(string[] args)
|
||||
{
|
||||
var allowed = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "setup", "product", "version", "component", "out" };
|
||||
var options = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
if (!args[i].StartsWith("--", StringComparison.Ordinal) || !allowed.Contains(args[i][2..]))
|
||||
throw new ToolException($"Unexpected argument '{args[i]}'.");
|
||||
if (i + 1 >= args.Length) throw new ToolException($"{args[i]} needs a value.");
|
||||
var key = args[i][2..];
|
||||
if (!options.TryGetValue(key, out var values)) options[key] = values = [];
|
||||
values.Add(args[++i]);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
private static string Required(Dictionary<string, List<string>> options, string key)
|
||||
{
|
||||
if (!options.TryGetValue(key, out var values) || string.IsNullOrWhiteSpace(values[^1])) throw new ToolException($"--{key} is required.");
|
||||
if (values.Count > 1) throw new ToolException($"--{key} given more than once.");
|
||||
return values[0];
|
||||
}
|
||||
|
||||
private static string Megabytes(long bytes) => (bytes / 1_000_000d).ToString("0.0", CultureInfo.InvariantCulture) + " MB";
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Chronos.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,90 @@
|
||||
using System.Reflection.PortableExecutable;
|
||||
using System.Text;
|
||||
|
||||
namespace Chronos.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Checks the Windows programs the release builds on Linux (BRIEF §18, amended 2026-10-23, R3): each must be a GUI
|
||||
/// program whose own Win32 resources hold the icon, the version and the application manifest with per-monitor DPI
|
||||
/// awareness. The SDK copies them from the assembly into the apphost; a build that silently skipped that step would
|
||||
/// ship programs without an icon that Windows scales as blurry bitmaps.
|
||||
/// </summary>
|
||||
internal sealed class PeCheckCommand : ICommand
|
||||
{
|
||||
private const int GroupIcon = 14;
|
||||
private const int Version = 16;
|
||||
private const int Manifest = 24;
|
||||
|
||||
public string Name => "pe-check";
|
||||
public string Summary => "Check that Windows programs carry their icon, version and DPI-aware manifest: pe-check <exe>...";
|
||||
|
||||
public Task<int> RunAsync(string[] args)
|
||||
{
|
||||
var a = new Args(args);
|
||||
if (a.Positional.Count == 0) throw new ToolException("Usage: pe-check <program.exe>...");
|
||||
var failed = 0;
|
||||
foreach (var path in a.Positional)
|
||||
{
|
||||
var problems = Check(path);
|
||||
Console.WriteLine(problems.Count == 0 ? $"ok {path}" : $"failed {path}: {string.Join("; ", problems)}");
|
||||
if (problems.Count > 0) failed++;
|
||||
}
|
||||
return Task.FromResult(failed == 0 ? 0 : 1);
|
||||
}
|
||||
|
||||
/// <summary>What <paramref name="path"/> lacks; empty when it is a complete GUI program.</summary>
|
||||
internal static List<string> Check(string path)
|
||||
{
|
||||
var problems = new List<string>();
|
||||
if (!File.Exists(path)) return ["file not found"];
|
||||
using var stream = File.OpenRead(path);
|
||||
using var pe = new PEReader(stream);
|
||||
PEHeader? header;
|
||||
try
|
||||
{
|
||||
header = pe.PEHeaders.PEHeader;
|
||||
}
|
||||
catch (BadImageFormatException)
|
||||
{
|
||||
header = null;
|
||||
}
|
||||
if (header is null) return ["not a PE image"];
|
||||
if (header.Subsystem != Subsystem.WindowsGui) problems.Add($"subsystem {header.Subsystem}, not WindowsGui");
|
||||
var directory = header.ResourceTableDirectory;
|
||||
if (directory.Size == 0) return [.. problems, "no Win32 resources"];
|
||||
|
||||
var root = pe.GetSectionData(directory.RelativeVirtualAddress);
|
||||
var types = Entries(root, 0).ToDictionary(e => e.Id, e => e.Offset);
|
||||
if (!types.ContainsKey(GroupIcon)) problems.Add("no icon");
|
||||
if (!types.ContainsKey(Version)) problems.Add("no version information");
|
||||
if (!types.TryGetValue(Manifest, out var manifest)) problems.Add("no application manifest");
|
||||
else if (!ManifestText(pe, root, manifest).Contains("PerMonitorV2", StringComparison.Ordinal)) problems.Add("the manifest does not declare PerMonitorV2 DPI awareness");
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <summary>The first manifest resource under the type directory at <paramref name="typeOffset"/>.</summary>
|
||||
private static string ManifestText(PEReader pe, PEMemoryBlock root, uint typeOffset)
|
||||
{
|
||||
foreach (var (_, nameOffset) in Entries(root, typeOffset & 0x7FFFFFFF))
|
||||
foreach (var (_, dataOffset) in Entries(root, nameOffset & 0x7FFFFFFF))
|
||||
{
|
||||
var entry = root.GetReader();
|
||||
entry.Offset = (int)(dataOffset & 0x7FFFFFFF);
|
||||
int rva = entry.ReadInt32(), size = entry.ReadInt32();
|
||||
var data = pe.GetSectionData(rva).GetReader();
|
||||
return Encoding.UTF8.GetString(data.ReadBytes(Math.Min(size, data.Length)));
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>The entries of the IMAGE_RESOURCE_DIRECTORY at <paramref name="offset"/> (ids, or name offsets).</summary>
|
||||
private static List<(int Id, uint Offset)> Entries(PEMemoryBlock root, uint offset)
|
||||
{
|
||||
var reader = root.GetReader();
|
||||
reader.Offset = (int)offset + 12;
|
||||
var count = reader.ReadUInt16() + reader.ReadUInt16();
|
||||
var entries = new List<(int, uint)>(count);
|
||||
for (var i = 0; i < count; i++) entries.Add(((int)(reader.ReadUInt32() & 0x7FFFFFFF), reader.ReadUInt32()));
|
||||
return entries;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Text;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Postgres;
|
||||
|
||||
namespace Chronos.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Prepares a PostgreSQL service container for the wire-protocol tests that need more than the image's defaults
|
||||
/// (BRIEF §6.3): one role per authentication method (MD5, cleartext, trust) with its pg_hba line ahead of the image's
|
||||
/// catch-all SCRAM line, TLS with a self-signed certificate for the service's host name, and no durability (a CI
|
||||
/// server: fsync, synchronous commit and full-page writes off). Everything goes through
|
||||
/// SQL as the superuser (server-side file functions), so the CI job needs neither docker nor psql
|
||||
/// (amended 2026-10-23, R3: Gitea Actions gives no id of the service container to exec into).
|
||||
/// </summary>
|
||||
internal sealed class PostgresCiCommand : ICommand
|
||||
{
|
||||
/// <summary>The roles the wire tests sign in with, their password and the pg_hba method that forces each one.</summary>
|
||||
internal static readonly (string Role, string? Password, string Method)[] Roles =
|
||||
[
|
||||
("chronos_md5", "md5-ci", "md5"),
|
||||
("chronos_clear", "clear-ci", "password"),
|
||||
("chronos_trust", null, "trust"),
|
||||
];
|
||||
|
||||
public string Name => "postgres-ci";
|
||||
public string Summary => "Prepare a CI PostgreSQL for the wire tests (--connection superuser string, --host name, --certificates dir)";
|
||||
|
||||
public async Task<int> RunAsync(string[] args)
|
||||
{
|
||||
var a = new Args(args);
|
||||
var connection = a.Get("connection") ?? throw new ToolException("--connection is required (a superuser connection string).");
|
||||
var host = a.Get("host") ?? throw new ToolException("--host is required (the name the tests connect to).");
|
||||
var folder = a.Get("certificates") ?? throw new ToolException("--certificates is required (where server.crt is kept for the tests).");
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3));
|
||||
var ct = timeout.Token;
|
||||
|
||||
var (certificatePem, keyPem) = CreateCertificate(host);
|
||||
Directory.CreateDirectory(folder);
|
||||
await File.WriteAllTextAsync(Path.Combine(folder, "server.crt"), certificatePem, ct);
|
||||
|
||||
var settings = PostgresSettings.Parse(connection) with { SslMode = SslMode.Disable };
|
||||
await using var database = new PostgresDatabase(settings);
|
||||
await using (var session = await WaitForServerAsync(database, ct))
|
||||
{
|
||||
var data = await ScalarTextAsync(session, "SHOW data_directory", ct);
|
||||
var hba = await ScalarTextAsync(session, "SHOW hba_file", ct);
|
||||
await WriteServerFileAsync(session, data + "/server.crt", Encoding.ASCII.GetBytes(certificatePem), ct);
|
||||
await WriteServerFileAsync(session, data + "/server.key", Encoding.ASCII.GetBytes(keyPem), ct);
|
||||
// lo_export creates files readable by everyone (0644) and PostgreSQL refuses such a key: the server's own
|
||||
// shell, run as its user through COPY TO PROGRAM (superuser only), makes it private.
|
||||
await session.ExecuteAsync($"COPY (SELECT 1 WHERE false) TO PROGRAM {Literal("chmod 600 '" + data + "/server.key'")}", [], ct);
|
||||
var rules = await ScalarTextAsync(session, $"SELECT pg_read_file({Literal(hba)})", ct);
|
||||
await WriteServerFileAsync(session, hba, Encoding.UTF8.GetBytes(PrependRules(rules)), ct);
|
||||
|
||||
foreach (var (role, password, method) in Roles)
|
||||
{
|
||||
await session.ExecuteAsync($"DROP ROLE IF EXISTS {role}", [], ct);
|
||||
// An MD5 role needs an MD5 hash stored; the others keep the server's default (SCRAM) or no password.
|
||||
if (method == "md5") await session.ExecuteAsync("SET password_encryption = 'md5'", [], ct);
|
||||
await session.ExecuteAsync($"CREATE ROLE {role} LOGIN{(password is null ? string.Empty : " PASSWORD " + Literal(password))}", [], ct);
|
||||
if (method == "md5") await session.ExecuteAsync("RESET password_encryption", [], ct);
|
||||
}
|
||||
await session.ExecuteAsync("ALTER SYSTEM SET ssl = on", [], ct);
|
||||
// A throw-away server on the runner's shared storage: no durability, so the timed tests (the 100k-frame bulk
|
||||
// insert of the Phase 2 gate) measure the client's protocol path rather than the host's disk flushes.
|
||||
foreach (var setting in new[] { "fsync", "synchronous_commit", "full_page_writes" })
|
||||
await session.ExecuteAsync($"ALTER SYSTEM SET {setting} = off", [], ct);
|
||||
await session.QuerySingleAsync("SELECT pg_reload_conf()", [], ct);
|
||||
}
|
||||
|
||||
// A reload that fails keeps the old settings silently: report the rejected lines. "ssl = on" only says what the
|
||||
// setting reads; a key or certificate the server refused appears in its log alone, so the proof is a session
|
||||
// that negotiated TLS.
|
||||
await using (var session = await database.OpenAsync(ct))
|
||||
{
|
||||
var errors = new List<string>();
|
||||
await foreach (var row in session.QueryAsync(
|
||||
"SELECT line_number || ': ' || error FROM pg_hba_file_rules WHERE error IS NOT NULL " +
|
||||
"UNION ALL SELECT name || ': ' || error FROM pg_file_settings WHERE error IS NOT NULL", [], ct))
|
||||
errors.Add(row.GetString(0));
|
||||
if (errors.Count > 0) throw new ToolException("::error title=PostgreSQL setup::" + string.Join("; ", errors));
|
||||
}
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var tls = new PostgresDatabase(settings with { SslMode = SslMode.Require, MaxPoolSize = 1 });
|
||||
await using var session = await tls.OpenAsync(ct);
|
||||
if ((await session.QuerySingleAsync("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], ct)).GetBool(0))
|
||||
{
|
||||
Console.WriteLine($"PostgreSQL at {settings.Host}: MD5, cleartext and trust roles, TLS on for {host}");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (attempt < 20 && IsConnectionFailure(ex))
|
||||
{
|
||||
}
|
||||
catch (Exception ex) when (IsConnectionFailure(ex))
|
||||
{
|
||||
throw new ToolException($"::error title=PostgreSQL setup::the server does not accept TLS after the reload (its log says why the certificate or key was refused): {ex.Message}");
|
||||
}
|
||||
await Task.Delay(500, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The image's rules with one line per test role ahead of them (the first matching line wins); idempotent.</summary>
|
||||
internal static string PrependRules(string rules)
|
||||
{
|
||||
var lines = Roles.Select(r => $"host all {r.Role} all {r.Method}").ToList();
|
||||
var kept = rules.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n').Where(l => !lines.Contains(l.Trim())).ToList();
|
||||
return string.Join('\n', lines.Concat(kept));
|
||||
}
|
||||
|
||||
/// <summary>A two-day self-signed certificate (PEM) for <paramref name="host"/>, localhost and 127.0.0.1, and its key.</summary>
|
||||
internal static (string Certificate, string Key) CreateCertificate(string host)
|
||||
{
|
||||
using var rsa = RSA.Create(2048);
|
||||
var request = new CertificateRequest($"CN={host}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
var names = new SubjectAlternativeNameBuilder();
|
||||
foreach (var name in new[] { host, "localhost" }.Distinct(StringComparer.OrdinalIgnoreCase)) names.AddDnsName(name);
|
||||
names.AddIpAddress(IPAddress.Loopback);
|
||||
request.CertificateExtensions.Add(names.Build());
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
||||
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.KeyCertSign, true));
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
using var certificate = request.CreateSelfSigned(now.AddMinutes(-5), now.AddDays(2));
|
||||
return (certificate.ExportCertificatePem() + "\n", rsa.ExportPkcs8PrivateKeyPem() + "\n");
|
||||
}
|
||||
|
||||
private static bool IsConnectionFailure(Exception ex) =>
|
||||
ex is DatabaseException or IOException or System.Security.Authentication.AuthenticationException;
|
||||
|
||||
/// <summary>A SQL string literal.</summary>
|
||||
internal static string Literal(string value) => "'" + value.Replace("'", "''", StringComparison.Ordinal) + "'";
|
||||
|
||||
private static async Task<IDbSession> WaitForServerAsync(PostgresDatabase database, CancellationToken ct)
|
||||
{
|
||||
// The service container may still be initialising its database when the job starts.
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await database.OpenAsync(ct);
|
||||
}
|
||||
catch (Exception ex) when (attempt < 60 && ex is DatabaseException or IOException or System.Net.Sockets.SocketException)
|
||||
{
|
||||
await Task.Delay(1000, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string> ScalarTextAsync(IDbSession session, string sql, CancellationToken ct) =>
|
||||
(await session.QuerySingleAsync(sql, [], ct)).GetString(0);
|
||||
|
||||
/// <summary>Writes a file on the server as the server's user; a new file is readable by everyone (mode 0644).</summary>
|
||||
private static async Task WriteServerFileAsync(IDbSession session, string path, byte[] content, CancellationToken ct)
|
||||
{
|
||||
var oid = (await session.QuerySingleAsync($"SELECT lo_from_bytea(0, decode({Literal(Convert.ToBase64String(content))}, 'base64'))::int8", [], ct)).GetInt64(0);
|
||||
try
|
||||
{
|
||||
await session.QuerySingleAsync($"SELECT lo_export({oid}::oid, {Literal(path)})", [], ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await session.QuerySingleAsync($"SELECT lo_unlink({oid}::oid)", [], ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Chronos.Core.Codecs.Png;
|
||||
|
||||
namespace Chronos.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Visual regression for the <c>--capture</c> screenshots (BRIEF §20.2). <c>screenshots diff <dir></c> compares every
|
||||
/// PNG with the baseline of the same name (<c>tests/visual/baselines</c> unless <c>--baseline</c>): a pixel differs when
|
||||
/// one of its channels moves by more than <c>--tolerance</c> (of 255), and a screen fails when more than <c>--max-diff</c>
|
||||
/// of its pixels differ (a fraction), when its size changed, or when a baseline has no screenshot any more. A screen
|
||||
/// without a baseline fails once the baseline folder holds any PNG, so a screen added later cannot stay ungated; before
|
||||
/// the first baselines are committed nothing is compared, and the run says so in a warning and in its summary instead
|
||||
/// of passing for a clean diff. Every screen with differing pixels gets <c><name>-diff.png</c> in <c>--out</c> (the
|
||||
/// baseline faded to grey, the differing pixels magenta) and the run a <c>summary.md</c> there, copied to the job summary
|
||||
/// when the workflow runner provides one. <c>screenshots accept <dir></c> copies the screenshots over the baselines.
|
||||
/// </summary>
|
||||
internal sealed class ScreenshotsCommand : ICommand
|
||||
{
|
||||
/// <summary>Absorbs the last-bit noise of anti-aliased edges, not a changed colour.</summary>
|
||||
public const int DefaultTolerance = 8;
|
||||
|
||||
/// <summary>
|
||||
/// 0.05 %: about 650 pixels of a 1440×900 screen. A few digits of a measured value (latency, the last comparison's
|
||||
/// time) stay below it; a moved or resized control, a new colour or a missing picture do not.
|
||||
/// </summary>
|
||||
public const double DefaultMaxDiff = 0.0005;
|
||||
|
||||
public string Name => "screenshots";
|
||||
public string Summary => "Pixel diff of --capture screenshots against tests/visual/baselines (diff <dir> [--baseline, --out, --tolerance, --max-diff]; accept <dir>)";
|
||||
|
||||
public Task<int> RunAsync(string[] args) => Task.FromResult(Run(args, Environment.GetEnvironmentVariable, Console.Out));
|
||||
|
||||
/// <summary>The command with its environment passed in: tests run it without workflow commands or job summary.</summary>
|
||||
internal static int Run(string[] args, Func<string, string?> environment, TextWriter output)
|
||||
{
|
||||
var a = new Args(args);
|
||||
if (a.Positional is not [var verb, var directory]) throw new ToolException("Usage: screenshots diff <dir> [--baseline <dir>] [--out <dir>] [--tolerance 0-255] [--max-diff fraction] | screenshots accept <dir> [--baseline <dir>]");
|
||||
if (!Directory.Exists(directory)) throw new ToolException($"Screenshot folder not found: {directory}");
|
||||
var baseline = a.Get("baseline") ?? Path.Combine(Args.RepoRoot(), "tests", "visual", "baselines");
|
||||
switch (verb)
|
||||
{
|
||||
case "diff":
|
||||
var options = new DiffOptions(
|
||||
directory,
|
||||
baseline,
|
||||
a.Get("out") ?? Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory)) + "-diff",
|
||||
ParseTolerance(a.Get("tolerance")),
|
||||
ParseMaxDiff(a.Get("max-diff")));
|
||||
// Gitea Actions sets GITHUB_ACTIONS and understands the GitHub-compatible workflow commands.
|
||||
var actions = environment("GITHUB_ACTIONS") == "true";
|
||||
var summary = actions ? environment("GITHUB_STEP_SUMMARY") : null;
|
||||
return Diff(options, output, annotate: actions, stepSummary: summary).Fails ? 1 : 0;
|
||||
case "accept":
|
||||
Directory.CreateDirectory(baseline);
|
||||
var accepted = 0;
|
||||
foreach (var file in Directory.EnumerateFiles(directory, "*.png").Order(StringComparer.Ordinal))
|
||||
{
|
||||
File.Copy(file, Path.Combine(baseline, Path.GetFileName(file)), overwrite: true);
|
||||
accepted++;
|
||||
}
|
||||
output.WriteLine($"{accepted} screenshot(s) copied to {baseline}");
|
||||
return 0;
|
||||
default:
|
||||
throw new ToolException($"Unknown screenshots verb '{verb}' (use diff or accept).");
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed record DiffOptions(string Directory, string Baseline, string Output, int Tolerance, double MaxDiff);
|
||||
|
||||
internal enum Verdict
|
||||
{
|
||||
/// <summary>No pixel beyond the tolerance.</summary>
|
||||
Same,
|
||||
|
||||
/// <summary>Some pixels beyond the tolerance, no more than the allowed fraction.</summary>
|
||||
Within,
|
||||
|
||||
Changed,
|
||||
Resized,
|
||||
Unreadable,
|
||||
|
||||
/// <summary>A screenshot without a baseline while the baseline folder holds none at all: warns only.</summary>
|
||||
New,
|
||||
|
||||
/// <summary>A screenshot without a baseline while other screens have one.</summary>
|
||||
Unbased,
|
||||
|
||||
/// <summary>A baseline whose screen was not captured.</summary>
|
||||
Missing,
|
||||
}
|
||||
|
||||
internal sealed record ScreenResult(string Name, Verdict Verdict, long Differing, long Pixels, string? Detail = null)
|
||||
{
|
||||
public double Fraction => Pixels == 0 ? 0 : (double)Differing / Pixels;
|
||||
public bool Fails => Verdict is Verdict.Changed or Verdict.Resized or Verdict.Unreadable or Verdict.Unbased or Verdict.Missing;
|
||||
}
|
||||
|
||||
/// <param name="Armed">The baseline folder holds at least one PNG: from then on every screen needs its own.</param>
|
||||
internal sealed record DiffReport(IReadOnlyList<ScreenResult> Screens, bool Armed)
|
||||
{
|
||||
public bool Fails => Screens.Any(s => s.Fails);
|
||||
}
|
||||
|
||||
/// <summary>RGBA, 8 bits per channel, top-down.</summary>
|
||||
internal sealed record Picture(int Width, int Height, byte[] Pixels);
|
||||
|
||||
/// <summary>Compares the folders, writes the diff images and <c>summary.md</c>, and reports every screen.</summary>
|
||||
internal static DiffReport Diff(DiffOptions options, TextWriter output, bool annotate, string? stepSummary)
|
||||
{
|
||||
var captured = PngNames(options.Directory);
|
||||
var baselines = Directory.Exists(options.Baseline) ? PngNames(options.Baseline) : new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var armed = baselines.Count > 0;
|
||||
// Diffs of an earlier run must not pass for this run's.
|
||||
if (Directory.Exists(options.Output))
|
||||
{
|
||||
foreach (var old in Directory.EnumerateFiles(options.Output, "*-diff.png")) File.Delete(old);
|
||||
}
|
||||
Directory.CreateDirectory(options.Output);
|
||||
|
||||
var results = new List<ScreenResult>();
|
||||
foreach (var name in captured)
|
||||
{
|
||||
if (!baselines.Contains(name))
|
||||
{
|
||||
results.Add(new ScreenResult(name, armed ? Verdict.Unbased : Verdict.New, 0, 0));
|
||||
continue;
|
||||
}
|
||||
results.Add(CompareFiles(name, Path.Combine(options.Baseline, name), Path.Combine(options.Directory, name), options));
|
||||
}
|
||||
results.AddRange(baselines.Where(b => !captured.Contains(b)).Select(b => new ScreenResult(b, Verdict.Missing, 0, 0)));
|
||||
results.Sort((x, y) => StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name));
|
||||
|
||||
foreach (var r in results) output.WriteLine($"{Label(r.Verdict),-11} {r.Name}{Describe(r, options)}");
|
||||
var report = new DiffReport(results, armed);
|
||||
var markdown = Markdown(report, options);
|
||||
File.WriteAllText(Path.Combine(options.Output, "summary.md"), markdown);
|
||||
if (stepSummary is not null) File.AppendAllText(stepSummary, markdown);
|
||||
output.WriteLine(Totals(report));
|
||||
if (annotate)
|
||||
{
|
||||
foreach (var r in results.Where(r => r.Fails))
|
||||
{
|
||||
var title = r.Verdict == Verdict.Unbased ? "Screenshot without baseline" : "Screenshot " + Label(r.Verdict);
|
||||
output.WriteLine($"::error title={Escape(title, property: true)}::{Escape(r.Name + Describe(r, options), property: false)}");
|
||||
}
|
||||
// One warning for them all (a log of hundreds helps nobody): before the first baselines every screen is new.
|
||||
var unbased = results.Where(r => r.Verdict == Verdict.New).Select(r => r.Name).ToList();
|
||||
if (unbased.Count > 0)
|
||||
{
|
||||
var names = string.Join(", ", unbased.Take(5)) + (unbased.Count > 5 ? ", …" : string.Empty);
|
||||
output.WriteLine($"::warning title={Escape("No screenshot baselines", property: true)}::" +
|
||||
Escape($"{NotArmed} {unbased.Count} screenshot(s) without a baseline ({names}); tests/visual/baselines/README.md says how to add them.", property: false));
|
||||
}
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
private static ScreenResult CompareFiles(string name, string baselinePath, string capturedPath, DiffOptions options)
|
||||
{
|
||||
Picture expected, actual;
|
||||
try
|
||||
{
|
||||
expected = Read(baselinePath);
|
||||
actual = Read(capturedPath);
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
return new ScreenResult(name, Verdict.Unreadable, 0, 0, ex.Message);
|
||||
}
|
||||
if (expected.Width != actual.Width || expected.Height != actual.Height)
|
||||
return new ScreenResult(name, Verdict.Resized, 0, 0, $"{actual.Width}×{actual.Height}, baseline {expected.Width}×{expected.Height}");
|
||||
|
||||
var (differing, diff) = Compare(expected, actual, options.Tolerance);
|
||||
var pixels = (long)actual.Width * actual.Height;
|
||||
if (differing == 0) return new ScreenResult(name, Verdict.Same, 0, pixels);
|
||||
File.WriteAllBytes(Path.Combine(options.Output, Path.GetFileNameWithoutExtension(name) + "-diff.png"),
|
||||
PngEncoder.Encode(diff, actual.Width, actual.Height, PngColorType.Rgb, level: System.IO.Compression.CompressionLevel.Fastest));
|
||||
var verdict = (double)differing / pixels > options.MaxDiff ? Verdict.Changed : Verdict.Within;
|
||||
return new ScreenResult(name, verdict, differing, pixels);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Counts the pixels where a channel differs by more than <paramref name="tolerance"/> and draws the diff image: the
|
||||
/// baseline as faded grey, differing pixels magenta.
|
||||
/// </summary>
|
||||
internal static (long Differing, byte[] Diff) Compare(Picture expected, Picture actual, int tolerance)
|
||||
{
|
||||
if (expected.Width != actual.Width || expected.Height != actual.Height) throw new ArgumentException("The pictures differ in size.");
|
||||
var count = expected.Width * expected.Height;
|
||||
var diff = new byte[count * 3];
|
||||
long differing = 0;
|
||||
var e = expected.Pixels;
|
||||
var a = actual.Pixels;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var p = i * 4;
|
||||
var delta = Math.Max(Math.Max(Math.Abs(e[p] - a[p]), Math.Abs(e[p + 1] - a[p + 1])), Math.Max(Math.Abs(e[p + 2] - a[p + 2]), Math.Abs(e[p + 3] - a[p + 3])));
|
||||
var q = i * 3;
|
||||
if (delta > tolerance)
|
||||
{
|
||||
differing++;
|
||||
diff[q] = 255;
|
||||
diff[q + 1] = 0;
|
||||
diff[q + 2] = 255;
|
||||
continue;
|
||||
}
|
||||
// Rec.709 luma of the baseline, over its alpha, squeezed into 112..207 so magenta stands out in light and dark themes.
|
||||
var luma = (e[p] * 54 + e[p + 1] * 183 + e[p + 2] * 19) >> 8;
|
||||
var grey = (byte)(112 + luma * e[p + 3] / 255 * 3 / 8);
|
||||
diff[q] = diff[q + 1] = diff[q + 2] = grey;
|
||||
}
|
||||
return (differing, diff);
|
||||
}
|
||||
|
||||
/// <summary>Decodes a PNG of any colour type and depth to <see cref="Picture"/> (16-bit samples keep their high byte).</summary>
|
||||
internal static Picture Read(string path)
|
||||
{
|
||||
var png = PngDecoder.Decode(File.ReadAllBytes(path));
|
||||
var count = png.Width * png.Height;
|
||||
var rgba = new byte[count * 4];
|
||||
var channels = png.Channels;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
byte Sample(int c) => png.Pixels8 is { } p8 ? p8[i * channels + c] : (byte)(png.Pixels16![i * channels + c] >> 8);
|
||||
var (r, g, b, alpha) = channels switch
|
||||
{
|
||||
1 => (Sample(0), Sample(0), Sample(0), (byte)255),
|
||||
2 => (Sample(0), Sample(0), Sample(0), Sample(1)),
|
||||
3 => (Sample(0), Sample(1), Sample(2), (byte)255),
|
||||
_ => (Sample(0), Sample(1), Sample(2), Sample(3)),
|
||||
};
|
||||
rgba[i * 4] = r;
|
||||
rgba[i * 4 + 1] = g;
|
||||
rgba[i * 4 + 2] = b;
|
||||
rgba[i * 4 + 3] = alpha;
|
||||
}
|
||||
return new Picture(png.Width, png.Height, rgba);
|
||||
}
|
||||
|
||||
private static SortedSet<string> PngNames(string directory) =>
|
||||
new(Directory.EnumerateFiles(directory, "*.png").Select(f => Path.GetFileName(f)), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private static string Label(Verdict verdict) => verdict switch
|
||||
{
|
||||
Verdict.Same => "same",
|
||||
Verdict.Within => "tolerated",
|
||||
Verdict.Changed => "changed",
|
||||
Verdict.Resized => "resized",
|
||||
Verdict.Unreadable => "unreadable",
|
||||
Verdict.New => "new",
|
||||
Verdict.Unbased => "no baseline",
|
||||
_ => "missing",
|
||||
};
|
||||
|
||||
private static string Describe(ScreenResult r, DiffOptions options) => r.Verdict switch
|
||||
{
|
||||
Verdict.Same => string.Empty,
|
||||
Verdict.Within or Verdict.Changed => $": {Percent(r.Fraction)} of the pixels differ ({r.Differing.ToString("N0", CultureInfo.InvariantCulture)}; limit {Percent(options.MaxDiff)})",
|
||||
Verdict.Resized or Verdict.Unreadable => $": {r.Detail}",
|
||||
Verdict.New => ": no baseline",
|
||||
Verdict.Unbased => ": no baseline, while other screens have one (screenshots accept adds it)",
|
||||
_ => ": a baseline without a screenshot",
|
||||
};
|
||||
|
||||
/// <summary>What a run before the first baselines must not hide: it compared nothing, so it could not have failed.</summary>
|
||||
private const string NotArmed = "The baseline folder holds no PNG: nothing was compared, and no visual change can fail this step until baselines are committed.";
|
||||
|
||||
private static string Percent(double fraction) => (fraction * 100).ToString("0.###", CultureInfo.InvariantCulture) + " %";
|
||||
|
||||
private static string Totals(DiffReport report)
|
||||
{
|
||||
int Count(params Verdict[] verdicts) => report.Screens.Count(s => verdicts.Contains(s.Verdict));
|
||||
return $"{Count(Verdict.Same, Verdict.Within, Verdict.Changed, Verdict.Resized, Verdict.Unreadable)} compared: {Count(Verdict.Same, Verdict.Within)} within tolerance, " +
|
||||
$"{Count(Verdict.Changed, Verdict.Resized, Verdict.Unreadable)} changed; {Count(Verdict.New, Verdict.Unbased)} without a baseline; {Count(Verdict.Missing)} missing.";
|
||||
}
|
||||
|
||||
private static string Markdown(DiffReport report, DiffOptions options)
|
||||
{
|
||||
var md = new StringBuilder();
|
||||
md.AppendLine("### Screenshot diff").AppendLine();
|
||||
md.AppendLine(CultureInfo.InvariantCulture, $"Tolerance {options.Tolerance} of 255 per channel, at most {Percent(options.MaxDiff)} of the pixels.").AppendLine();
|
||||
if (!report.Armed) md.AppendLine(CultureInfo.InvariantCulture, $"**{NotArmed}**").AppendLine();
|
||||
var listed = report.Screens.Where(s => s.Verdict != Verdict.Same).ToList();
|
||||
if (listed.Count > 0)
|
||||
{
|
||||
md.AppendLine("| Screen | Result | Detail |").AppendLine("|---|---|---|");
|
||||
foreach (var r in listed) md.AppendLine(CultureInfo.InvariantCulture, $"| {r.Name} | {Label(r.Verdict)} | {Describe(r, options).TrimStart(':', ' ')} |");
|
||||
md.AppendLine();
|
||||
}
|
||||
md.AppendLine(Totals(report)).AppendLine();
|
||||
return md.ToString();
|
||||
}
|
||||
|
||||
private static int ParseTolerance(string? value) =>
|
||||
value is null ? DefaultTolerance
|
||||
: int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var t) && t is >= 0 and <= 255 ? t
|
||||
: throw new ToolException($"--tolerance takes 0 to 255, not '{value}'.");
|
||||
|
||||
private static double ParseMaxDiff(string? value) =>
|
||||
value is null ? DefaultMaxDiff
|
||||
: double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var f) && f is >= 0 and <= 1 ? f
|
||||
: throw new ToolException($"--max-diff takes a fraction from 0 to 1, not '{value}'.");
|
||||
|
||||
/// <summary>Workflow-command escaping (properties also escape ':' and ',').</summary>
|
||||
private static string Escape(string value, bool property)
|
||||
{
|
||||
var escaped = value.Replace("%", "%25", StringComparison.Ordinal).Replace("\r", "%0D", StringComparison.Ordinal).Replace("\n", "%0A", StringComparison.Ordinal);
|
||||
return property ? escaped.Replace(":", "%3A", StringComparison.Ordinal).Replace(",", "%2C", StringComparison.Ordinal) : escaped;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Render.Diagnostics;
|
||||
|
||||
namespace Chronos.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// <c>selftest [prefix…] [--filter prefix] [--list]</c>: the engine's end-to-end self-test (BRIEF §20.2, §20.4) with
|
||||
/// the managed encoders. Prints a PASS/FAIL table; exits 1 when a check fails, 2 when no check matched.
|
||||
/// </summary>
|
||||
internal sealed class SelfTestCommand : ICommand
|
||||
{
|
||||
public string Name => "selftest";
|
||||
public string Summary => "Render synthetic sequences end to end and verify the outputs";
|
||||
|
||||
public async Task<int> RunAsync(string[] args)
|
||||
{
|
||||
var a = new Args(args, "list");
|
||||
var filters = a.Positional.ToList();
|
||||
if (a.Get("filter") is { } filter) filters.Add(filter);
|
||||
if (a.Has("list"))
|
||||
{
|
||||
foreach (var check in SelfTest.Checks) Console.WriteLine($"{check.Id,-26} {check.Description}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
using var cts = new CancellationTokenSource();
|
||||
ConsoleCancelEventHandler cancel = (_, e) =>
|
||||
{
|
||||
e.Cancel = true;
|
||||
cts.Cancel();
|
||||
};
|
||||
Console.CancelKeyPress += cancel;
|
||||
// Expected failures (fault injection, render-node notices) are logged by the engine; the table says enough.
|
||||
var level = Log.MinimumLevel;
|
||||
Log.MinimumLevel = LogLevel.Error;
|
||||
try
|
||||
{
|
||||
var clock = Stopwatch.StartNew();
|
||||
Console.WriteLine($"{"RESULT",-6} {"CHECK",-26} {"TIME",8} DETAIL");
|
||||
var results = await SelfTest.RunAsync(new SelfTestOptions { Filters = filters }, new ConsoleRows(), cts.Token);
|
||||
var passed = results.Count(r => r.Outcome == SelfTestOutcome.Passed);
|
||||
var failed = results.Count(r => r.Outcome == SelfTestOutcome.Failed);
|
||||
var skipped = results.Count(r => r.Outcome == SelfTestOutcome.Skipped);
|
||||
Console.WriteLine(string.Create(CultureInfo.InvariantCulture,
|
||||
$"{(failed == 0 ? "PASSED" : "FAILED")} {results.Count} checks: {passed} passed, {failed} failed, {skipped} skipped in {clock.Elapsed.TotalSeconds:F1} s"));
|
||||
if (results.Count == 0) return 2;
|
||||
return failed == 0 ? 0 : 1;
|
||||
}
|
||||
catch (OperationCanceledException) when (cts.IsCancellationRequested)
|
||||
{
|
||||
Console.Error.WriteLine("Self-test cancelled.");
|
||||
return 2;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Log.MinimumLevel = level;
|
||||
Console.CancelKeyPress -= cancel;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Prints each result as soon as its check finishes.</summary>
|
||||
private sealed class ConsoleRows : IProgress<SelfTestResult>
|
||||
{
|
||||
public void Report(SelfTestResult r)
|
||||
{
|
||||
var label = r.Outcome switch
|
||||
{
|
||||
SelfTestOutcome.Passed => "PASS",
|
||||
SelfTestOutcome.Failed => "FAIL",
|
||||
_ => "SKIP",
|
||||
};
|
||||
var line = string.Create(CultureInfo.InvariantCulture, $"{label,-6} {r.Id,-26} {r.Elapsed.TotalMilliseconds,6:F0} ms {r.Detail}");
|
||||
if (r.Outcome == SelfTestOutcome.Failed) Console.Error.WriteLine(line);
|
||||
else Console.WriteLine(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Chronos.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();
|
||||
|
||||
var documents = files.Select(f => (File: f, Doc: XDocument.Load(f, LoadOptions.SetLineInfo))).ToList();
|
||||
var valueTypes = ValueResourceTypes(documents.Select(d => d.Doc));
|
||||
|
||||
foreach (var (file, doc) in documents)
|
||||
{
|
||||
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 …}})");
|
||||
}
|
||||
|
||||
foreach (var attr in el.Attributes())
|
||||
{
|
||||
if (ExpectedValueType(name, attr.Name.LocalName) is not { } expected || ResourceKey(attr.Value) is not { } key) continue;
|
||||
if (valueTypes.TryGetValue(key, out var actual) && actual != expected)
|
||||
problems.Add($"{where}: {name}.{attr.Name.LocalName} needs a {expected} but resource {key} is a {actual}");
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
/// <summary>Keyed resources of the value types WPF cannot convert into each other at run time (parsing succeeds, loading fails).</summary>
|
||||
private static Dictionary<string, string> ValueResourceTypes(IEnumerable<XDocument> documents)
|
||||
{
|
||||
var types = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var el in documents.SelectMany(d => d.Descendants()))
|
||||
{
|
||||
if (el.Name.LocalName is not ("Double" or "GridLength" or "Thickness" or "CornerRadius")) continue;
|
||||
if (el.Attributes().FirstOrDefault(a => a.Name.LocalName == "Key") is { } key) types[key.Value] = el.Name.LocalName;
|
||||
}
|
||||
return types;
|
||||
}
|
||||
|
||||
private static string? ExpectedValueType(string element, string attribute) => attribute switch
|
||||
{
|
||||
"Width" when element == "ColumnDefinition" => "GridLength",
|
||||
"Height" when element == "RowDefinition" => "GridLength",
|
||||
"Margin" or "Padding" or "BorderThickness" => "Thickness",
|
||||
"CornerRadius" => "CornerRadius",
|
||||
"Width" or "Height" or "MinWidth" or "MaxWidth" or "MinHeight" or "MaxHeight" or "FontSize" => "Double",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static string? ResourceKey(string value)
|
||||
{
|
||||
var match = System.Text.RegularExpressions.Regex.Match(value, @"^\{(?:Static|Dynamic)Resource\s+(?:ResourceKey=)?([^\s}]+)\s*\}$");
|
||||
return match.Success ? match.Groups[1].Value : null;
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace Chronos.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Zips the contents of a folder (not the folder itself) for the release archives (BRIEF §19.3). The release runs in
|
||||
/// the .NET SDK container, which has no zip program: the archive comes from the BCL instead.
|
||||
/// </summary>
|
||||
internal sealed class ZipCommand : ICommand
|
||||
{
|
||||
public string Name => "zip";
|
||||
public string Summary => "Zip a folder's contents: zip <folder> --out <file.zip>";
|
||||
|
||||
public Task<int> RunAsync(string[] args)
|
||||
{
|
||||
var a = new Args(args);
|
||||
if (a.Positional.Count != 1 || a.Get("out") is not { Length: > 0 } output)
|
||||
throw new ToolException("Usage: zip <folder> --out <file.zip>");
|
||||
var count = Create(a.Positional[0], output);
|
||||
Console.WriteLine($"{output}: {count} files");
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
/// <summary>Writes <paramref name="output"/> with every file under <paramref name="folder"/>; returns how many.</summary>
|
||||
internal static int Create(string folder, string output)
|
||||
{
|
||||
var source = Path.GetFullPath(folder);
|
||||
if (!Directory.Exists(source)) throw new ToolException($"Folder not found: {folder}");
|
||||
var target = Path.GetFullPath(output);
|
||||
if (target.StartsWith(source + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
||||
throw new ToolException("The archive cannot be written inside the folder it zips.");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
if (File.Exists(target)) File.Delete(target);
|
||||
|
||||
// Sorted, '/'-separated names: the same folder gives the same entry order on Windows and Linux.
|
||||
var files = Directory.GetFiles(source, "*", SearchOption.AllDirectories)
|
||||
.Select(f => (Path: f, Name: Path.GetRelativePath(source, f).Replace(Path.DirectorySeparatorChar, '/')))
|
||||
.OrderBy(f => f.Name, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
using var zip = ZipFile.Open(target, ZipArchiveMode.Create);
|
||||
foreach (var (path, name) in files) zip.CreateEntryFromFile(path, name, CompressionLevel.Optimal);
|
||||
return files.Count;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
namespace Chronos.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, "Chronos.slnx"))) return dir.FullName;
|
||||
dir = dir.Parent;
|
||||
}
|
||||
dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (dir is not null)
|
||||
{
|
||||
if (File.Exists(Path.Combine(dir.FullName, "Chronos.slnx"))) return dir.FullName;
|
||||
dir = dir.Parent;
|
||||
}
|
||||
throw new ToolException("Repository root (Chronos.slnx) not found.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using Chronos.Tools;
|
||||
using Chronos.Tools.Commands;
|
||||
|
||||
var commands = new ICommand[]
|
||||
{
|
||||
new MakeIconCommand(),
|
||||
new I18nCommand(),
|
||||
new XamlLintCommand(),
|
||||
new PackageGuardCommand(),
|
||||
new ChangelogCommand(),
|
||||
new PackInstallerCommand(),
|
||||
new SelfTestCommand(),
|
||||
new DiagnoseCommand(),
|
||||
new FixturesCommand(),
|
||||
new ScreenshotsCommand(),
|
||||
new ZipCommand(),
|
||||
new GiteaReleaseCommand(),
|
||||
new PostgresCiCommand(),
|
||||
new PeCheckCommand(),
|
||||
};
|
||||
|
||||
if (args.Length == 0 || args[0] is "-h" or "--help" or "help")
|
||||
{
|
||||
Console.WriteLine("Chronos.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;
|
||||
}
|
||||
Reference in new issue
Block a user