tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
feat(registries): add tazel_registries.txt lexer, parser, and fuzz target
- Commit
d2235e0779b66d9c51ff71c56c8e4e1fdf4eaa4c- Author
- Leitwolf11 ·
- Parents
c3337193c833
Changes
.github/workflows/fuzzing.yml | 2 +- CHANGELOG.md | 3 + fuzz/Progmasoft.Tazel.Fuzz/Program.cs | 3 +- fuzz/corpus/registries/basic | 5 + src/Progmasoft.Tazel/Cli/LogCommands.cs | 56 +-- .../Dsl/Registries/TazelRegistries.cs | 523 +++++++++++++++++++++ src/Progmasoft.Tazel/Output/ErrorCodes.cs | 5 + tests/Progmasoft.Tazel.Tests/LogCommandsTests.cs | 2 +- tests/Progmasoft.Tazel.Tests/RegistriesTests.cs | 132 ++++++ 9 files changed, 681 insertions(+), 50 deletions(-) diff --git a/.github/workflows/fuzzing.yml b/.github/workflows/fuzzing.yml index eae5606..c311a9b 100644 --- a/.github/workflows/fuzzing.yml +++ b/.github/workflows/fuzzing.yml @@ -26,7 +26,7 @@ jobs: strategy: fail-fast: false matrix: - target: [custom, options, envs, label, depfile, command-line, license] + target: [custom, options, envs, label, depfile, command-line, license, registries] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: diff --git a/CHANGELOG.md b/CHANGELOG.md index ade26e2..78bc598 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ ## Unreleased +- Added `tazel_registries.txt` lexer and parser (`Progmasoft.Tazel.Dsl.Registries`), error code `E0510`, fuzz target + `registries`, and structured priority/URL reporting in `tazel log registries`. + ## 0.4.0 - 2026-12-02 - Added `tazel dump` (reads the running daemon and Cedre Celeste state with `--cedre-celeste`, `--daemon`, `--watcher`, diff --git a/fuzz/Progmasoft.Tazel.Fuzz/Program.cs b/fuzz/Progmasoft.Tazel.Fuzz/Program.cs index a82c715..7d917a3 100644 --- a/fuzz/Progmasoft.Tazel.Fuzz/Program.cs +++ b/fuzz/Progmasoft.Tazel.Fuzz/Program.cs @@ -22,7 +22,7 @@ namespace Progmasoft.Tazel.Fuzz; public static class Program { /// <summary>The fuzz targets by name.</summary> - public static readonly string[] Targets = ["custom", "options", "envs", "label", "depfile", "command-line", "license"]; + public static readonly string[] Targets = ["custom", "options", "envs", "label", "depfile", "command-line", "license", "registries"]; /// <summary>Runs one target on the inputs libFuzzer gives.</summary> public static void Main(string[] arguments) @@ -37,6 +37,7 @@ public static class Program "depfile" => text => Depfiles.Inputs(text), "command-line" => text => Refused<CommandLineException>(() => CommandLine.Parse(text.Split('\n'))), "license" => text => Refused<Project.LicenseException>(() => Project.SpdxLicenses.Check(text, "MODULE.csx")), + "registries" => text => Refused<CustomCommandsException>(() => Dsl.Registries.TazelRegistriesFile.Parse(text)), _ => throw new ArgumentException($"the targets are {string.Join(", ", Targets)}"), }; Fuzzer.LibFuzzer.Run(span => diff --git a/fuzz/corpus/registries/basic b/fuzz/corpus/registries/basic new file mode 100644 index 0000000..956cda1 --- /dev/null +++ b/fuzz/corpus/registries/basic @@ -0,0 +1,5 @@ +# Default and custom module registries +1. portal-modules + +2. custom + "https://tazel.example.com" diff --git a/src/Progmasoft.Tazel/Cli/LogCommands.cs b/src/Progmasoft.Tazel/Cli/LogCommands.cs index 0cf6906..548bd99 100644 --- a/src/Progmasoft.Tazel/Cli/LogCommands.cs +++ b/src/Progmasoft.Tazel/Cli/LogCommands.cs @@ -96,61 +96,23 @@ internal sealed class LogCommands(Reporter reporter, string workingDirectory, Ve private int Registries() { - var source = FindRegistriesFile(); - reporter.Plain($"source: {source ?? "built-in"}"); - if (source is not null && PrintRedactedRegistries(source)) + var resolved = Dsl.Registries.TazelRegistriesFile.Load(workingDirectory); + reporter.Plain($"source: {resolved.Source ?? "built-in"}"); + foreach (var entry in resolved.Entries) { - return 0; + var sanitized = SanitizeUri(entry.Address); + var tag = entry.IsBuiltIn ? " (built-in)" : string.Empty; + reporter.Plain($"{entry.Priority}. {entry.Name}{tag} {sanitized}"); } - reporter.Plain("1. portal-modules (built-in)"); reporter.Plain("global-credential-providers: (none)"); return 0; } - private string? FindRegistriesFile() + private static string SanitizeUri(Uri uri) { - var moduleFile = TryModuleRegistriesFile(); - if (moduleFile is not null) - { - return moduleFile; - } - - var userHome = Environment.GetEnvironmentVariable("TAZEL_HOME"); - if (string.IsNullOrWhiteSpace(userHome)) - { - return null; - } - - var userFile = Path.Combine(userHome, "User", "tazel_registries.txt"); - return File.Exists(userFile) ? userFile : null; - } - - private string? TryModuleRegistriesFile() - { - try - { - var path = Path.Combine(ModuleFiles.FindRoot(workingDirectory), "tazel_registries.txt"); - return File.Exists(path) ? path : null; - } - catch (ProjectException) - { - return null; - } - } - - private bool PrintRedactedRegistries(string path) - { - var lines = File.ReadAllLines(path) - .Select(line => line.Trim()) - .Where(line => line.Length > 0 && !line.StartsWith('#') && !line.Contains("token", StringComparison.OrdinalIgnoreCase)) - .ToList(); - foreach (var line in lines) - { - reporter.Plain($" {line}"); - } - - return lines.Count > 0; + var builder = new UriBuilder(uri) { UserName = string.Empty, Password = string.Empty }; + return builder.Uri.AbsoluteUri.TrimEnd('/'); } private int WhatRan(bool failedOnly) diff --git a/src/Progmasoft.Tazel/Dsl/Registries/TazelRegistries.cs b/src/Progmasoft.Tazel/Dsl/Registries/TazelRegistries.cs new file mode 100644 index 0000000..ba342cb --- /dev/null +++ b/src/Progmasoft.Tazel/Dsl/Registries/TazelRegistries.cs @@ -0,0 +1,523 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using Progmasoft.Tazel.Dsl.Configuration; +using Progmasoft.Tazel.Dsl.Custom; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Dsl.Registries; + +/// <summary>One module registry entry from <c>tazel_registries.txt</c>, ordered by <see cref="Priority"/>.</summary> +/// <param name="Priority">The positive integer priority (1 first).</param> +/// <param name="Name">The registry name, or <c>portal-modules</c> for the built-in Tazel Portal Modules registry.</param> +/// <param name="Address">The base repository URI without a trailing slash.</param> +/// <param name="IsBuiltIn">Whether this entry refers to the built-in <c>portal-modules</c> registry.</param> +/// <param name="Line">The 1-based line number in the source file, or 0 for the implicit built-in default.</param> +public sealed record RegistryEntry(int Priority, string Name, Uri Address, bool IsBuiltIn, int Line) +{ + /// <summary>The index document URI (<c><address>/index.json</c>).</summary> + public Uri IndexUri => new($"{Address.AbsoluteUri.TrimEnd('/')}/index.json"); +} + +/// <summary>The effective registry list and where it came from.</summary> +/// <param name="Source">The file path that was read, or <see langword="null"/> when the built-in default applies.</param> +/// <param name="Entries">The registries ordered by ascending <see cref="RegistryEntry.Priority"/>.</param> +public sealed record ResolvedRegistries(string? Source, IReadOnlyList<RegistryEntry> Entries) +{ + /// <summary>Finds a registry by name, or <see langword="null"/> when no entry has that name.</summary> + /// <param name="name">The registry name.</param> + public RegistryEntry? FindByName(string name) + { + ArgumentNullException.ThrowIfNull(name); + return Entries.FirstOrDefault(entry => string.Equals(entry.Name, name, StringComparison.Ordinal)); + } +} + +/// <summary> +/// Reads and parses <c>tazel_registries.txt</c> with its own indentation-based lexer and parser. +/// </summary> +public static class TazelRegistriesFile +{ + /// <summary>The file name read from the module root or <c>$TAZEL_HOME/User/</c>.</summary> + public static string FileName { get; } = "tazel_registries.txt"; + + /// <summary>The built-in hard keyword for Tazel Portal Modules.</summary> + public static string PortalModulesKeyword { get; } = "portal-modules"; + + /// <summary>The default base URI of Tazel Portal Modules.</summary> + public static Uri PortalModulesUri { get; } = new("https://modules.tazel.net"); + + /// <summary>The default registry list used when no <c>tazel_registries.txt</c> exists.</summary> + public static IReadOnlyList<RegistryEntry> BuiltInDefault { get; } = + [new RegistryEntry(1, PortalModulesKeyword, PortalModulesUri, IsBuiltIn: true, Line: 0)]; + + /// <summary>Parses <paramref name="text"/> as <c>tazel_registries.txt</c>, sorted by ascending priority.</summary> + /// <param name="text">The file contents.</param> + public static IReadOnlyList<RegistryEntry> Parse(string text) => Parse(text, FileName); + + /// <summary>Parses <paramref name="text"/> as <c>tazel_registries.txt</c>, naming <paramref name="file"/> in diagnostics.</summary> + /// <param name="text">The file contents.</param> + /// <param name="file">The file name shown in error messages.</param> + public static IReadOnlyList<RegistryEntry> Parse(string text, string file) + { + ArgumentNullException.ThrowIfNull(text); + ArgumentNullException.ThrowIfNull(file); + var lines = RegistryLexer.TokenizeLines(text, file); + return RegistryParser.ParseLines(lines, text, file); + } + + /// <summary> + /// Loads the effective registries for <paramref name="workingDirectory"/>: module root first, then + /// <c>$TAZEL_HOME/User/tazel_registries.txt</c>, then the built-in <c>portal-modules</c> default. + /// </summary> + /// <param name="workingDirectory">The directory from which to locate the module root.</param> + public static ResolvedRegistries Load(string workingDirectory) + { + ArgumentNullException.ThrowIfNull(workingDirectory); + var source = FindFile(workingDirectory); + if (source is null) + { + return new ResolvedRegistries(null, BuiltInDefault); + } + + var text = File.ReadAllText(source); + var entries = Parse(text, source); + return entries.Count == 0 + ? new ResolvedRegistries(source, BuiltInDefault) + : new ResolvedRegistries(source, entries); + } + + /// <summary>Finds the active <c>tazel_registries.txt</c> path, or <see langword="null"/> when none exists.</summary> + /// <param name="workingDirectory">The directory from which to locate the module root.</param> + public static string? FindFile(string workingDirectory) + { + ArgumentNullException.ThrowIfNull(workingDirectory); + var moduleFile = TryModuleFile(workingDirectory); + if (moduleFile is not null) + { + return moduleFile; + } + + var userFile = Path.Combine(TazelHome.Directory(), "User", FileName); + return File.Exists(userFile) ? userFile : null; + } + + private static string? TryModuleFile(string workingDirectory) + { + try + { + var path = Path.Combine(ModuleFiles.FindRoot(workingDirectory), FileName); + return File.Exists(path) ? path : null; + } + catch (ProjectException) + { + return null; + } + } +} + +internal enum RegistryTokenKind +{ + Number, + Dot, + Name, + String, +} + +internal readonly record struct RegistryToken(RegistryTokenKind Kind, string Text, int Line, int Column); + +internal sealed record RegistryLogicalLine(int Line, bool IsIndented, IReadOnlyList<RegistryToken> Tokens); + +internal static class RegistryLexer +{ + public static List<RegistryLogicalLine> TokenizeLines(string text, string file) + { + var result = new List<RegistryLogicalLine>(); + var i = 0; + var line = 1; + + while (i < text.Length) + { + var (indented, nextIndex, nextLine) = ReadIndentation(text, i, line, file); + i = nextIndex; + line = nextLine; + + if (i >= text.Length) + { + break; + } + + if (IsLineBreak(text[i])) + { + i = ConsumeLineBreak(text, i); + line++; + continue; + } + + var startLine = line; + var tokens = new List<RegistryToken>(); + (i, line) = ReadLineTokens(text, i, line, file, tokens); + if (tokens.Count > 0) + { + result.Add(new RegistryLogicalLine(startLine, indented, tokens)); + } + } + + return result; + } + + private static (bool Indented, int NextIndex, int NextLine) ReadIndentation(string text, int index, int line, string file) + { + var spaces = 0; + var tabs = 0; + var i = index; + while (i < text.Length && (text[i] == ' ' || text[i] == '\t')) + { + if (text[i] == ' ') + { + spaces++; + } + else + { + tabs++; + } + + i++; + } + + if (i >= text.Length || IsLineBreak(text[i]) || text[i] == '#') + { + return (false, i, line); + } + + if (spaces > 0 && tabs > 0) + { + throw Fail(text, file, line, 1, "mixed tabs and spaces in indentation", + "use either tabs or spaces in multiples of 2"); + } + + if (spaces > 0 && spaces % 2 != 0) + { + throw Fail(text, file, line, 1, $"indentation of {spaces} space(s) is not a multiple of 2", + "indent with tabs or spaces in multiples of 2"); + } + + return (spaces > 0 || tabs > 0, i, line); + } + + private static (int NextIndex, int NextLine) ReadLineTokens( + string text, int index, int line, string file, List<RegistryToken> tokens) + { + var i = index; + var lineStart = FindLineStart(text, i); + + while (i < text.Length) + { + var ch = text[i]; + if (IsLineBreak(ch)) + { + return (ConsumeLineBreak(text, i), line + 1); + } + + if (ch == ' ' || ch == '\t') + { + i++; + continue; + } + + if (ch == '#') + { + i = SkipToLineEnd(text, i); + continue; + } + + if (ch == '<' && i + 1 < text.Length && text[i + 1] == '#') + { + (i, line) = SkipBlockComment(text, i, line, file); + lineStart = FindLineStart(text, i); + continue; + } + + var column = i - lineStart + 1; + var (token, nextIndex) = ReadToken(text, i, line, column, file); + tokens.Add(token); + i = nextIndex; + } + + return (i, line); + } + + private static (RegistryToken Token, int NextIndex) ReadToken(string text, int i, int line, int column, string file) + { + var ch = text[i]; + if (ch == '.') + { + return (new RegistryToken(RegistryTokenKind.Dot, ".", line, column), i + 1); + } + + if (ch is '"' or '\'' or '`') + { + return ReadString(text, i, line, column, file); + } + + if (char.IsAsciiDigit(ch)) + { + return ReadNumber(text, i, line, column); + } + + if (IsNameStart(ch)) + { + return ReadName(text, i, line, column); + } + + throw Fail(text, file, line, column, $"unexpected character '{ch}'", + "expected a priority number, registry name, or quoted address"); + } + + private static (RegistryToken Token, int NextIndex) ReadString(string text, int i, int line, int column, string file) + { + var quote = text[i]; + var start = i + 1; + var end = start; + while (end < text.Length && text[end] != quote && !IsLineBreak(text[end])) + { + end++; + } + + if (end >= text.Length || text[end] != quote) + { + throw Fail(text, file, line, column, $"unterminated string literal starting with {quote}", + $"close the string with {quote} on the same line"); + } + + return (new RegistryToken(RegistryTokenKind.String, text[start..end], line, column), end + 1); + } + + private static (RegistryToken Token, int NextIndex) ReadNumber(string text, int i, int line, int column) + { + var end = i; + while (end < text.Length && char.IsAsciiDigit(text[end])) + { + end++; + } + + return (new RegistryToken(RegistryTokenKind.Number, text[i..end], line, column), end); + } + + private static (RegistryToken Token, int NextIndex) ReadName(string text, int i, int line, int column) + { + var end = i; + while (end < text.Length && IsNamePart(text[end])) + { + end++; + } + + return (new RegistryToken(RegistryTokenKind.Name, text[i..end], line, column), end); + } + + private static (int NextIndex, int NextLine) SkipBlockComment(string text, int i, int line, string file) + { + var startLine = line; + var col = i - FindLineStart(text, i) + 1; + i += 2; + while (i + 1 < text.Length) + { + if (text[i] == '#' && text[i + 1] == '>') + { + return (i + 2, line); + } + + if (IsLineBreak(text[i])) + { + i = ConsumeLineBreak(text, i); + line++; + continue; + } + + i++; + } + + throw Fail(text, file, startLine, col, "unterminated block comment '<#'", "close the comment with '#>'"); + } + + private static bool IsLineBreak(char ch) => ch is '\n' or '\r'; + + private static int ConsumeLineBreak(string text, int i) => + text[i] == '\r' && i + 1 < text.Length && text[i + 1] == '\n' ? i + 2 : i + 1; + + private static int SkipToLineEnd(string text, int i) + { + while (i < text.Length && !IsLineBreak(text[i])) + { + i++; + } + + return i; + } + + private static int FindLineStart(string text, int i) + { + var pos = Math.Min(i, text.Length); + while (pos > 0 && !IsLineBreak(text[pos - 1])) + { + pos--; + } + + return pos; + } + + private static bool IsNameStart(char ch) => char.IsAsciiLetter(ch) || ch == '_'; + + private static bool IsNamePart(char ch) => char.IsAsciiLetterOrDigit(ch) || ch is '-' or '_'; + + internal static CustomCommandsException Fail(string text, string file, int line, int column, string headline, string help) => + new(Diagnostic.At(Output.ErrorCodes.RegistriesInvalid, text, file, new Place(line, column, 1), headline, "here", help, + "tazel_registries.txt is static data: numbered entries with indented URLs.")); +} + +internal static class RegistryParser +{ + public static IReadOnlyList<RegistryEntry> ParseLines(IReadOnlyList<RegistryLogicalLine> lines, string text, string file) + { + var entries = new List<RegistryEntry>(); + var seenPriorities = new Dictionary<int, int>(); + var seenNames = new Dictionary<string, int>(StringComparer.Ordinal); + var index = 0; + + while (index < lines.Count) + { + var header = lines[index]; + if (header.IsIndented) + { + var tok = header.Tokens[0]; + throw RegistryLexer.Fail(text, file, tok.Line, tok.Column, + "unexpected indented line without a registry entry above it", + "start each registry entry at column 0 as '<number>. <name>'"); + } + + var (priority, name) = ParseHeader(header, text, file); + CheckDuplicates(priority, name, header.Line, seenPriorities, seenNames, text, file); + + index++; + var entry = ParseEntryBody(priority, name, header.Line, lines, ref index, text, file); + entries.Add(entry); + } + + entries.Sort((a, b) => a.Priority.CompareTo(b.Priority)); + return entries; + } + + private static (int Priority, string Name) ParseHeader(RegistryLogicalLine line, string text, string file) + { + var tokens = line.Tokens; + if (tokens.Count != 3 || tokens[0].Kind != RegistryTokenKind.Number || tokens[1].Kind != RegistryTokenKind.Dot || + tokens[2].Kind != RegistryTokenKind.Name) + { + var tok = tokens[0]; + throw RegistryLexer.Fail(text, file, tok.Line, tok.Column, + "invalid registry entry header", + "write each entry as '<priority>. <name>', for example '1. portal-modules'"); + } + + if (!int.TryParse(tokens[0].Text, NumberStyles.None, CultureInfo.InvariantCulture, out var priority) || priority < 1) + { + throw RegistryLexer.Fail(text, file, tokens[0].Line, tokens[0].Column, + $"registry priority '{tokens[0].Text}' must be a positive integer starting at 1", + "use 1, 2, 3, ..."); + } + + return (priority, tokens[2].Text); + } + + private static void CheckDuplicates( + int priority, string name, int line, + Dictionary<int, int> seenPriorities, Dictionary<string, int> seenNames, + string text, string file) + { + if (seenPriorities.TryGetValue(priority, out var prevPriorityLine)) + { + throw RegistryLexer.Fail(text, file, line, 1, + $"duplicate registry priority '{priority}' (already used on line {prevPriorityLine})", + "give each registry entry a distinct priority number"); + } + + if (seenNames.TryGetValue(name, out var prevNameLine)) + { + throw RegistryLexer.Fail(text, file, line, 1, + $"duplicate registry name '{name}' (already defined on line {prevNameLine})", + "give each registry entry a unique name"); + } + + seenPriorities[priority] = line; + seenNames[name] = line; + } + + private static RegistryEntry ParseEntryBody( + int priority, string name, int headerLine, + IReadOnlyList<RegistryLogicalLine> lines, ref int index, + string text, string file) + { + var isBuiltIn = string.Equals(name, TazelRegistriesFile.PortalModulesKeyword, StringComparison.Ordinal); + var hasIndented = index < lines.Count && lines[index].IsIndented; + + if (isBuiltIn) + { + if (hasIndented) + { + var tok = lines[index].Tokens[0]; + throw RegistryLexer.Fail(text, file, tok.Line, tok.Column, + $"built-in registry '{TazelRegistriesFile.PortalModulesKeyword}' cannot declare a custom address", + "remove the indented address line or rename the custom registry"); + } + + return new RegistryEntry(priority, name, TazelRegistriesFile.PortalModulesUri, IsBuiltIn: true, headerLine); + } + + if (!hasIndented) + { + throw RegistryLexer.Fail(text, file, headerLine, 1, + $"registry '{name}' is missing its indented address line", + "add an indented quoted URL below it, for example ' \"https://tazel.example.com\"'"); + } + + var addressLine = lines[index]; + index++; + if (index < lines.Count && lines[index].IsIndented) + { + var tok = lines[index].Tokens[0]; + throw RegistryLexer.Fail(text, file, tok.Line, tok.Column, + $"registry '{name}' has more than one indented line", + "each custom registry takes exactly one address string"); + } + + var address = ParseAddress(addressLine, name, text, file); + return new RegistryEntry(priority, name, address, IsBuiltIn: false, headerLine); + } + + private static Uri ParseAddress(RegistryLogicalLine line, string name, string text, string file) + { + if (line.Tokens.Count != 1 || line.Tokens[0].Kind != RegistryTokenKind.String) + { + var tok = line.Tokens[0]; + throw RegistryLexer.Fail(text, file, tok.Line, tok.Column, + $"registry '{name}' address must be a single quoted string literal", + "quote the URL with \"...\", '...', or `...`"); + } + + var raw = line.Tokens[0].Text.Trim(); + if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri) || + (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) + { + throw RegistryLexer.Fail(text, file, line.Tokens[0].Line, line.Tokens[0].Column, + $"invalid registry address '{raw}'", + "provide an absolute http:// or https:// repository base URL"); + } + + return new Uri(uri.AbsoluteUri.TrimEnd('/')); + } +} diff --git a/src/Progmasoft.Tazel/Output/ErrorCodes.cs b/src/Progmasoft.Tazel/Output/ErrorCodes.cs index b90691d..b34ab07 100644 --- a/src/Progmasoft.Tazel/Output/ErrorCodes.cs +++ b/src/Progmasoft.Tazel/Output/ErrorCodes.cs @@ -90,6 +90,7 @@ internal static partial class ErrorCodes public const string Tool = "E0507"; public const string CacheBroken = "E0508"; public const string License = "E0509"; + public const string RegistriesInvalid = "E0510"; public const string Label = "E0600"; private const string Lexer = "the text files: tazel_custom.txt, tazel_options.txt and tazel_envs.txt"; @@ -345,6 +346,10 @@ internal static partial class ErrorCodes "4096-bit key for RSA and 1952 bytes for ML-DSA-65; a signing key is a 32-byte seed for Ed25519 and " + "ML-DSA-65 and a PKCS #8 key for RSA. tazel cache keygen makes a pair.", "PublicKey = \"AAECAwQF...\"", "PublicKey = \"ed25519:AAECAwQF...\"", "MODULE.csx"), + new(RegistriesInvalid, "a tazel_registries.txt file Tazel cannot read", + "tazel_registries.txt lists numbered module registries in priority order with indented quoted HTTP/HTTPS URLs; " + + "'portal-modules' is a built-in keyword with no address line.", + "1. custom\n not-a-url", "1. portal-modules\n2. custom\n \"https://tazel.example.com\"", "tazel_registries.txt"), new(Label, "a label Tazel cannot read", "A label names a target: //dir:name, //:name, :name in the current package, @dependency//dir:name; //dir/... " + "and //... are patterns of packages. Names hold letters, digits and _ + . -.", diff --git a/tests/Progmasoft.Tazel.Tests/LogCommandsTests.cs b/tests/Progmasoft.Tazel.Tests/LogCommandsTests.cs index 6389520..4be44b2 100644 --- a/tests/Progmasoft.Tazel.Tests/LogCommandsTests.cs +++ b/tests/Progmasoft.Tazel.Tests/LogCommandsTests.cs @@ -66,7 +66,7 @@ public sealed class LogCommandsTests "using Progmasoft.Tazel.Dsl.Module.Prelude;\nmodule = Module.Define(new() { Group = \"com.example\", Name = \"logdemo\", Version = \"0.1.0\", License = \"MIT\" });\n", TestContext.Current.CancellationToken); await File.WriteAllTextAsync(Path.Combine(dir, "tazel_registries.txt"), - "1. portal-modules\ntoken: super-secret-value\n", + "1. portal-modules\n2. corp\n \"https://user:super-secret-value@tazel.example.com\"\n", TestContext.Current.CancellationToken); var logsDir = Path.Combine(dir, ".tazel", "testlogs"); Directory.CreateDirectory(logsDir); diff --git a/tests/Progmasoft.Tazel.Tests/RegistriesTests.cs b/tests/Progmasoft.Tazel.Tests/RegistriesTests.cs new file mode 100644 index 0000000..8732c3d --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/RegistriesTests.cs @@ -0,0 +1,132 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Threading.Tasks; +using Progmasoft.Tazel.Dsl.Custom; +using Progmasoft.Tazel.Dsl.Registries; +using Progmasoft.Tazel.Output; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class RegistriesTests +{ + [Fact] + public void ParsesBuiltInAndCustomInPriorityOrder() + { + var text = """ + # Line comment + <# Multi-line + block comment #> + 2. corp + 'https://tazel.example.com/index/' + + 1. portal-modules + + 3. mirror + `https://mirror.example.org/repo` + """; + + var entries = TazelRegistriesFile.Parse(text); + + Assert.Equal(3, entries.Count); + Assert.Equal((1, "portal-modules", true), (entries[0].Priority, entries[0].Name, entries[0].IsBuiltIn)); + Assert.Equal("https://modules.tazel.net/index.json", entries[0].IndexUri.AbsoluteUri); + + Assert.Equal((2, "corp", false), (entries[1].Priority, entries[1].Name, entries[1].IsBuiltIn)); + Assert.Equal("https://tazel.example.com/index/index.json", entries[1].IndexUri.AbsoluteUri); + + Assert.Equal((3, "mirror", false), (entries[2].Priority, entries[2].Name, entries[2].IsBuiltIn)); + Assert.Equal("https://mirror.example.org/repo/index.json", entries[2].IndexUri.AbsoluteUri); + } + + [Fact] + public void StringLiteralsHaveNoEscapes() + { + var text = """ + 1. custom + "https://tazel.example.com/a/b" + """; + + var entries = TazelRegistriesFile.Parse(text); + + Assert.Single(entries); + Assert.Equal("https://tazel.example.com/a/b", entries[0].Address.AbsoluteUri); + } + + [Theory] + [InlineData("1. custom\n \"https://tazel.example.com\"", "multiple of 2")] + [InlineData("1. custom\n \"https://tazel.example.com\"", "multiple of 2")] + [InlineData("1. custom\n \t\"https://tazel.example.com\"", "mixed tabs and spaces")] + [InlineData("1. portal-modules\n \"https://tazel.example.com\"", "cannot declare a custom address")] + [InlineData("1. custom\n", "missing its indented address")] + [InlineData("1. custom\n \"https://a.example\"\n \"https://b.example\"", "more than one indented line")] + [InlineData("1. custom\n https://a.example", "unexpected character")] + [InlineData("1. custom\n \"ftp://a.example\"", "invalid registry address")] + [InlineData("0. portal-modules", "positive integer")] + [InlineData("1. portal-modules\n1. custom\n \"https://a.example\"", "duplicate registry priority")] + [InlineData("1. custom\n \"https://a.example\"\n2. custom\n \"https://b.example\"", "duplicate registry name")] + [InlineData(" \"https://a.example\"", "unexpected indented line")] + [InlineData("1. custom\n \"https://a.example", "unterminated string")] + [InlineData("<# open comment\n1. portal-modules", "unterminated block comment")] + public void RejectsInvalidRegistriesFiles(string input, string expectedMessagePart) + { + var ex = Assert.Throws<CustomCommandsException>(() => TazelRegistriesFile.Parse(input)); + Assert.NotNull(ex.Diagnostic); + Assert.Equal(ErrorCodes.RegistriesInvalid, ex.Diagnostic.Code); + Assert.Contains(expectedMessagePart, ex.Diagnostic.Message, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void LoadFallsBackToBuiltInDefaultWhenNoFileExists() + { + var dir = Path.Combine(Path.GetTempPath(), $"tazel-reg-{Guid.NewGuid():N}"); + Directory.CreateDirectory(dir); + try + { + var resolved = TazelRegistriesFile.Load(dir); + Assert.Null(resolved.Source); + Assert.Single(resolved.Entries); + Assert.Equal("portal-modules", resolved.Entries[0].Name); + Assert.NotNull(resolved.FindByName("portal-modules")); + Assert.Null(resolved.FindByName("missing")); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Fact] + public async Task LogRegistriesPrintsSortedSanitizedEntries() + { + var dir = Path.Combine(Path.GetTempPath(), $"tazel-log-reg-{Guid.NewGuid():N}"); + Directory.CreateDirectory(dir); + try + { + await File.WriteAllTextAsync(Path.Combine(dir, "MODULE.csx"), """ + module = Module.Define(new() { Group = "com.example", Name = "demo", Version = "0.1.0" }); + """, TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(Path.Combine(dir, "tazel_registries.txt"), """ + 2. corp + "https://user:secret@tazel.example.com/reg" + 1. portal-modules + """, TestContext.Current.CancellationToken); + + using var output = new StringWriter(); + var status = await Program.RunAsync(["--color", "never", "log", "registries"], dir, output, TestContext.Current.CancellationToken); + + Assert.Equal(0, status); + var text = output.ToString(); + Assert.Contains("1. portal-modules (built-in) https://modules.tazel.net", text, StringComparison.Ordinal); + Assert.Contains("2. corp https://tazel.example.com/reg", text, StringComparison.Ordinal); + Assert.DoesNotContain("secret", text, StringComparison.Ordinal); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } +}