tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Add coverage, queries, fetch, vendor, Tazel Portal Modules and long help
- Commit
957a9633df9b92afdeb4a2d0dd691fd7bcb6ddaf- Author
- Leitwolf11 ·
- Parents
c3cb084c54a8
Changes
CHANGELOG.md | 4 + docs/commands.md | 55 ++- src/Progmasoft.Tazel/Cli/CommandLine.cs | 105 +++++- src/Progmasoft.Tazel/Cli/Commands.cs | 38 +- src/Progmasoft.Tazel/Cli/Help.cs | 225 +++++++++--- src/Progmasoft.Tazel/Cli/MoreCommands.cs | 232 ++++++++++++ src/Progmasoft.Tazel/Cli/Query.cs | 218 +++++++++++ src/Progmasoft.Tazel/Driver/BuildOptions.cs | 9 +- src/Progmasoft.Tazel/Driver/CCPlanner.cs | 22 ++ src/Progmasoft.Tazel/Driver/CoverageReport.cs | 103 ++++++ src/Progmasoft.Tazel/Driver/TestRunner.cs | 8 +- src/Progmasoft.Tazel/Portal/PortalModules.cs | 212 +++++++++++ src/Progmasoft.Tazel/Project/PortalDependencies.cs | 185 ++++++++++ src/Progmasoft.Tazel/Project/Workspace.cs | 54 ++- .../Progmasoft.Tazel.Tests/QueryAndPortalTests.cs | 397 +++++++++++++++++++++ 15 files changed, 1795 insertions(+), 72 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fa2871..eb1d7f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,10 @@ The first version of Tazel, written in C# for .NET 10. - An action cache by content, depfiles for headers, parallel actions, runfiles, sharded and flaky tests. - Reproducible `.tazel.tar.xz` archives of modules, and dependencies on them checked by SHA-256. - `tazel_options.txt` (with `platform:`) and `tazel_custom.txt`. +- `tazel coverage` (LLVM source-based, an LCOV report), `tazel query`, `cquery` and `aquery`, `tazel fetch`, + `tazel vendor`, and `tazel portal-modules search` and `info`; `tazel help --long`. +- Modules of Tazel Portal Modules as dependencies: each at the highest version asked for, checked by SHA-256, + from `vendor/` first. - Plugins: `Progmasoft.Tazel.PluginApi`, the project SDK `Progmasoft.Tazel.PluginSdk` that packs a plugin with `dotnet pack`, the template `dotnet new tazel-plugin`, local plugins loaded each into its own load context, and build steps that plugins and `BUILD.csx` files declare. diff --git a/docs/commands.md b/docs/commands.md index ba1c6c5..485a936 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -8,10 +8,17 @@ | `tazel build [labels]` | builds the targets of the labels; without a label, those of the package of the current directory | | `tazel test [labels]` | builds the tests of the labels and runs them | | `tazel run <label> [-- arguments]` | builds one executable or test and runs it | +| `tazel coverage [labels]` | runs the tests with LLVM coverage and writes `.tazel/coverage/coverage.lcov` | +| `tazel query <expression>` | answers about the targets and what they depend on | +| `tazel cquery <expression>` | the same, for the platform and mode of the command | +| `tazel aquery <expression>` | prints the actions of the targets | +| `tazel fetch` | downloads and checks the modules and plugins the module depends on, without building | +| `tazel vendor` | copies the modules of Tazel Portal Modules and their indexes into `vendor/` | +| `tazel portal-modules search\|info [-e] [--] <module\|group:module>` | searches Tazel Portal Modules, or shows one module | | `tazel clean [--expunge]` | removes the outputs, the test logs and zig's cache; `--expunge` removes all of `.tazel` | | `tazel package` | writes `.tazel/package/$group.$module-$version.tazel.tar.xz` and its `.sha256sums` | | `tazel custom <name> [arguments]` | runs a command of the `tazel_custom.txt` of the current directory | -| `tazel version`, `tazel help [command]` | print the version, or what Tazel or one command does | +| `tazel version`, `tazel help [command] [--long]` | print the version, or what Tazel or one command does | ## Options @@ -93,3 +100,49 @@ A command is a name of one or more words, a colon, and steps that run in order u starts a program directly; `s("line")` gives one line to the shell (CMD on Windows, `sh` elsewhere). Strings take double quotes, single quotes or backticks and have no escapes. `<N>` is the Nth argument after the name, `<*>` all of them. The longest name that fits the command line wins, and `--` ends the name. + +## Queries + +`tazel query` reads the project files alone: target patterns, `deps(x)`, `deps(x, depth)`, `rdeps(u, x)`, +`rdeps(u, x, depth)`, `kind(k, x)` (the kind is `CC.StaticLibrary`, `Zig.Test`, and so on), `tests(x)`, and `+`, `-`, +`^` or `union`, `except`, `intersect`, with parentheses. An operator stands apart, with spaces around it, as a label +may hold `-` and `+`. `--output label_kind` prints the kind before each label. + +```text +tazel query 'deps(//app:greeter)' +tazel query 'rdeps(//..., //core:core)' --output label_kind +tazel cquery '//...' --platform linux-aarch64 +tazel aquery //core:core +``` + +`tazel cquery` leaves out what does not build for the platform of the command and prints each target with its +configuration, such as `//:app (linux-amd64-debug)`. `tazel aquery` prints each action of the targets: what it runs, +reads and writes; nothing runs. + +## Coverage + +`tazel coverage` builds the tests and what they use with `-fprofile-instr-generate -fcoverage-mapping` into +`.tazel/out/<platform>-<mode>-coverage/`, runs them with `LLVM_PROFILE_FILE` in their log directory, merges the +profiles with llvm-profdata and writes `.tazel/coverage/coverage.lcov` with llvm-cov, with a summary. It needs clang; +llvm-profdata and llvm-cov are taken beside clang, else from PATH. Zig tests run without coverage. + +## Tazel Portal Modules + +A dependency `Module.From(new() { Group, Name, Version, Alias })` comes from Tazel Portal Modules, at +`https://modules.tazel.net` or the address in `TAZEL_PORTAL_MODULES_URL`. Each module is taken at the highest version +that anything asks for, from the indexes `$group/$module/index.json`; a yanked version takes part in no resolution. +Each archive is checked against its `.sha256sums` and unpacked once below `.tazel/external`. `tazel vendor` copies +the archives and the indexes into `vendor/`, and a build reads `vendor/` first, so a module with it builds offline. + +```text +tazel portal-modules search json +tazel portal-modules search com.example:json -e +tazel portal-modules info json +tazel portal-modules info --exact -- com.example:json +``` + +`search` lists the modules whose `group:module` holds the query, from `index.json` at the top of the portal; with +`-e`/`--exact` only that one, and the group is required. `info` prints the versions of one module, yanked ones marked, +with their push dates and dependencies; without `-e` the group may be left out unless the name is a module of more +than one group. `--` ends the options, so a query may start with a dash. + diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index 306f267..340fc58 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -76,7 +76,34 @@ internal sealed record CustomCommandLine(OutputOptions Output, IReadOnlyList<str internal sealed record VersionCommand(OutputOptions Output) : Command(Output); -internal sealed record HelpCommand(OutputOptions Output, string? Topic) : Command(Output); +internal sealed record HelpCommand(OutputOptions Output, string? Topic, bool Long = false) : Command(Output); + +internal sealed record CoverageCommand(OutputOptions Output, IReadOnlyList<string> Labels, BuildFlags Flags) : Command(Output); + +/// <summary>Which query: of the target graph, of the configured targets, or of the actions.</summary> +internal enum QueryKind +{ + Query, + CQuery, + AQuery, +} + +internal sealed record QueryCommand(OutputOptions Output, QueryKind Kind, string Expression, BuildFlags Flags, string Format) + : Command(Output); + +internal sealed record FetchCommand(OutputOptions Output) : Command(Output); + +internal sealed record VendorCommand(OutputOptions Output) : Command(Output); + +/// <summary>Searching Tazel Portal Modules, or the versions of one module.</summary> +internal enum PortalAction +{ + Search, + Info, +} + +internal sealed record PortalModulesCommand(OutputOptions Output, PortalAction Action, string Query, bool Exact) + : Command(Output); internal sealed record DaemonCommand(OutputOptions Output, string Action) : Command(Output); @@ -90,7 +117,8 @@ internal static class CommandLine { /// <summary>The commands, as <c>tazel help</c> lists them.</summary> public static IReadOnlyList<string> Commands { get; } = - ["build", "run", "test", "clean", "package", "custom", "version", "help", "dotnet"]; + ["build", "run", "test", "coverage", "query", "cquery", "aquery", "fetch", "vendor", "clean", "package", "custom", + "portal-modules", "version", "help", "dotnet"]; private enum Kind { @@ -101,7 +129,7 @@ internal static class CommandLine private sealed record Option(string Long, Kind Kind, IReadOnlyList<string>? Values, params string[] Commands); - private static readonly string[] Building = ["build", "run", "test"]; + private static readonly string[] Building = ["build", "run", "test", "coverage", "cquery", "aquery"]; private static readonly Option[] Options = [ @@ -121,6 +149,9 @@ internal static class CommandLine new("linker-options", Kind.List, null, Building), new("zig-compiler-options", Kind.List, null, Building), new("expunge", Kind.Flag, null, "clean"), + new("long", Kind.Flag, null, "help"), + new("exact", Kind.Flag, null, "portal-modules"), + new("output", Kind.Value, ["label", "label_kind"], "query", "cquery", "aquery"), ]; /// <summary>Reads <paramref name="arguments"/>.</summary> @@ -184,6 +215,13 @@ internal static class CommandLine return new HelpCommand(output, command); } + if (command == "portal-modules") + { + // After -- a query may start with a dash. + positional.AddRange(afterDashes); + afterDashes.Clear(); + } + if (afterDashes.Count > 0 && command != "run") { throw new CommandLineException($"tazel {command} takes nothing after --; only tazel run passes arguments on"); @@ -203,6 +241,28 @@ internal static class CommandLine } return new RunCommand(output, positional.FirstOrDefault(), Flags(seen), afterDashes); + case "coverage": + return new CoverageCommand(output, positional, Flags(seen)); + case "query" or "cquery" or "aquery": + if (positional.Count == 0) + { + throw new CommandLineException($"tazel {command} needs an expression, such as deps(//app:greeter)"); + } + + return new QueryCommand(output, command switch + { + "query" => QueryKind.Query, + "cquery" => QueryKind.CQuery, + _ => QueryKind.AQuery, + }, string.Join(' ', positional), Flags(seen), Last(seen, "output") ?? "label"); + case "fetch": + NoPositional(command, positional); + return new FetchCommand(output); + case "vendor": + NoPositional(command, positional); + return new VendorCommand(output); + case "portal-modules": + return PortalModules(output, positional, seen.Any(entry => entry.Option.Long == "exact")); case "clean": NoPositional(command, positional); return new CleanCommand(output, seen.Any(entry => entry.Option.Long == "expunge")); @@ -229,7 +289,7 @@ internal static class CommandLine default: return positional.Count > 1 ? throw new CommandLineException("tazel help takes one command") - : new HelpCommand(output, positional.FirstOrDefault()); + : new HelpCommand(output, positional.FirstOrDefault(), seen.Any(entry => entry.Option.Long == "long")); } } @@ -320,6 +380,12 @@ internal static class CommandLine return; } + if (argument == "-e") + { + seen.Add((Options.First(o => o.Long == "exact"), [], "-e")); + return; + } + throw new CommandLineException($"{argument} is not an option; tazel help lists them"); } @@ -389,6 +455,37 @@ internal static class CommandLine return flags; } + private static PortalModulesCommand PortalModules(OutputOptions output, List<string> positional, bool exact) + { + var actions = new[] { "search", "info" }; + if (positional.Count == 0 || !actions.Contains(positional[0], StringComparer.Ordinal)) + { + var near = positional.Count > 0 ? Suggestions.Nearest(positional[0], actions) : null; + throw new CommandLineException( + $"tazel portal-modules takes search or info{(near is null ? "" : $"; did you mean {near}?")}"); + } + + if (positional.Count != 2) + { + throw new CommandLineException($"tazel portal-modules {positional[0]} takes one module: module or group:module"); + } + + var query = positional[1]; + var colon = query.IndexOf(':', StringComparison.Ordinal); + if (exact && colon <= 0) + { + throw new CommandLineException( + $"with -e or --exact, tazel portal-modules {positional[0]} needs the group too: group:{query.TrimStart(':')}"); + } + + if (colon >= 0 && (colon == 0 || colon == query.Length - 1 || query.IndexOf(':', colon + 1) >= 0)) + { + throw new CommandLineException($"'{query}' is not module or group:module"); + } + + return new PortalModulesCommand(output, positional[0] == "search" ? PortalAction.Search : PortalAction.Info, query, exact); + } + private static void NoPositional(string command, List<string> positional) { if (positional.Count > 0) diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 650f0ee..697daed 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -21,7 +21,7 @@ using Progmasoft.Tazel.Project; namespace Progmasoft.Tazel.Cli; /// <summary>Carries out a command line read by <see cref="CommandLine"/>.</summary> -internal sealed class Commands(Reporter reporter, string workingDirectory) +internal sealed partial class Commands(Reporter reporter, string workingDirectory) { /// <summary>The version of this Tazel.</summary> public static Version TazelVersion { get; } = @@ -37,8 +37,18 @@ internal sealed class Commands(Reporter reporter, string workingDirectory) reporter.Plain($"tazel {TazelVersion.ToString(3)} (.NET {Environment.Version}, {Host.Platform.Name()})"); return 0; case HelpCommand help: - reporter.Plain(Help.Text(help.Topic)); + reporter.Plain(Help.Text(help.Topic, help.Long)); return 0; + case CoverageCommand coverage: + return await BuildAsync(coverage.Labels, coverage.Flags, BuildKind.Coverage, null, cancel).ConfigureAwait(false); + case QueryCommand query: + return await QueryAsync(query, cancel).ConfigureAwait(false); + case FetchCommand: + return await FetchAsync().ConfigureAwait(false); + case VendorCommand: + return await VendorAsync(cancel).ConfigureAwait(false); + case PortalModulesCommand portal: + return await PortalModulesAsync(portal, cancel).ConfigureAwait(false); case DaemonCommand daemon: reporter.Error($"tazel dotnet {daemon.Action}: this Tazel runs every command in a process of its own and has no daemon"); return 1; @@ -64,6 +74,7 @@ internal sealed class Commands(Reporter reporter, string workingDirectory) { Build, Test, + Coverage, Run, } @@ -107,7 +118,7 @@ internal sealed class Commands(Reporter reporter, string workingDirectory) var state = Path.Combine(root, ModuleFiles.StateDirectory); var removed = clean.Expunge ? [state] - : new[] { "out", "testlogs", "zig-cache", "package" }.Select(name => Path.Combine(state, name)).ToArray(); + : new[] { "out", "testlogs", "coverage", "zig-cache", "package", "downloads" }.Select(name => Path.Combine(state, name)).ToArray(); foreach (var directory in removed.Where(Directory.Exists)) { Directory.Delete(directory, recursive: true); @@ -210,12 +221,14 @@ internal sealed class Commands(Reporter reporter, string workingDirectory) CppCompilerOptions = flags.CppCompilerOptions, LinkerOptions = flags.LinkerOptions, ZigCompilerOptions = flags.ZigCompilerOptions, + Coverage = kind == BuildKind.Coverage, }; var selector = new Selector(workspace, platform); var selected = kind switch { - BuildKind.Test => selector.Select(labels, workingDirectory, target => target.Kind == TargetKind.Test, "a test"), + BuildKind.Test or BuildKind.Coverage => + selector.Select(labels, workingDirectory, target => target.Kind == TargetKind.Test, "a test"), BuildKind.Run => selector.Select(labels, workingDirectory, target => target.IsRunnable, "an executable or a test"), _ => selector.Select(labels, workingDirectory, _ => true, "a target"), }; @@ -239,18 +252,25 @@ internal sealed class Commands(Reporter reporter, string workingDirectory) reporter.Status($"building {selected.Count} target{(selected.Count == 1 ? "" : "s")}"); var digests = new Digests(); var cacheSettings = workspace.Main.Globals.cache?.Settings; - var executor = new Executor(buildOptions.Jobs, buildOptions.KeepGoing || kind == BuildKind.Test, + var executor = new Executor(buildOptions.Jobs, buildOptions.KeepGoing || kind is BuildKind.Test or BuildKind.Coverage, new ActionCache(digests, enabled: cacheSettings?.Local ?? true), reporter); var built = await executor.RunAsync(goals, cancel).ConfigureAwait(false); switch (kind) { - case BuildKind.Test: + case BuildKind.Test or BuildKind.Coverage: var tests = planned.Select(entry => (entry.Target, entry.Products, Built: entry.Products.Main is { } main && executor.Succeeded(main))).ToList(); - var outcomes = await new TestRunner(planner.Layout, buildOptions.Jobs, reporter).RunAsync(tests, cancel) - .ConfigureAwait(false); + var outcomes = await new TestRunner(planner.Layout, buildOptions.Jobs, reporter, buildOptions.Coverage) + .RunAsync(tests, cancel).ConfigureAwait(false); reporter.TestSummary(outcomes); - return outcomes.All(outcome => outcome.Status is TestStatus.Passed or TestStatus.Flaky) ? 0 : 1; + var passed = outcomes.All(outcome => outcome.Status is TestStatus.Passed or TestStatus.Flaky); + if (kind == BuildKind.Coverage) + { + var reported = await CoverageReport.WriteAsync(planner, chooser, tests, reporter, cancel).ConfigureAwait(false); + return passed && reported ? 0 : 1; + } + + return passed ? 0 : 1; case BuildKind.Run: if (!built) { diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 327c812..17327bf 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -2,13 +2,15 @@ // SPDX-License-Identifier: MIT using System.Collections.Generic; +using System.Linq; namespace Progmasoft.Tazel.Cli; -/// <summary>What <c>tazel help</c> prints.</summary> +/// <summary>What <c>tazel help</c> prints: the general help or one command's, short or with <c>--long</c>.</summary> internal static class Help { private const string BuildOptions = """ + Options of build, run, test, coverage, cquery and aquery: --mode debug|release debug (the default) or optimized --platform <name> the platform to build for; default: tazel_options.txt, else this machine's --jobs <n> how many actions run at once; default: MODULE.csx, else the processors @@ -23,98 +25,215 @@ internal static class Help A list of values goes after = or : without spaces (--feature=asan,lto); \, is a comma of a value. """; - private static readonly Dictionary<string, string> Topics = new(System.StringComparer.Ordinal) + private const string Labels = """ + Labels: //dir:name, //:name, :name (in the current package), @dependency//dir:name, //dir/... (a package and + those below it), //... (the whole module). Without a label, the package of the current directory. + """; + + private sealed record Topic(string Short, string Long); + + private static readonly Dictionary<string, Topic> Topics = new(System.StringComparer.Ordinal) { - ["build"] = $""" + ["build"] = new("tazel build [labels] [options]: builds the targets of the labels.", $""" tazel build [labels] [options] - Builds the targets of the labels: //dir:name, //:name, :name, //dir/... or //...; without a label, the - package of the current directory. //... leaves out targets tagged manual and those that do not build for - the platform. + Builds the targets of the labels. //... leaves out targets tagged manual and those that do not build for + the platform, and says how many it left out. Each action runs again only when its command, an input or an + output changed by content; outputs go to .tazel/out/<platform>-<mode>/. + + {Labels} {BuildOptions} - """, - ["test"] = $""" + + Examples: + tazel build //... + tazel build //app:greeter --mode release + tazel build //... --platform linux-aarch64 --feature=lto + """), + ["test"] = new("tazel test [labels] [options]: builds the tests of the labels and runs them.", $""" tazel test [labels] [options] - Builds the tests of the labels and runs each in its runfiles directory, with its own TEST_TMPDIR and a - timeout from its TestSize; a flaky test is run up to three times. Logs go to .tazel/testlogs. + Builds the tests of the labels and runs each in its runfiles directory, with its own TEST_TMPDIR, the + shard variables, and a timeout from its TestSize (1, 5, 15, 60 minutes) or its Timeout; a flaky test runs + up to three times, and a test tagged exclusive runs alone. Logs go to .tazel/testlogs/; the output of a + test that failed is printed, then a table of every test. + + {Labels} {BuildOptions} - """, - ["run"] = $""" + """), + ["coverage"] = new("tazel coverage [labels] [options]: runs the tests with coverage and writes its report.", $""" + tazel coverage [labels] [options] + + Builds the tests of the labels and what they use with LLVM source-based coverage (clang: + -fprofile-instr-generate -fcoverage-mapping), runs them as tazel test does, merges their profiles with + llvm-profdata, and writes .tazel/coverage/coverage.lcov with llvm-cov, with a summary. The outputs go to + .tazel/out/<platform>-<mode>-coverage/, apart from those of tazel build. Zig tests run without coverage. + + {Labels} + + {BuildOptions} + """), + ["run"] = new("tazel run <label> [options] [-- arguments]: builds one program and runs it.", $""" tazel run <label> [options] [-- arguments] - Builds one executable or test and runs it in its runfiles directory, with Tazel's environment and the - program's EnvironmentVariables; Arguments and what follows -- are passed to it. + Builds one executable or test and runs it in its runfiles directory, where its RuntimeData is, with + Tazel's environment and the program's EnvironmentVariables. Its Arguments and what follows -- are passed + to it, and its exit status is tazel's. + + {BuildOptions} + """), + ["query"] = new("tazel query <expression>: answers about the targets and what they depend on.", """ + tazel query <expression> [--output label|label_kind] + + Answers about the target graph from the project files alone. + //dir:name, //dir/..., //... targets and target patterns + deps(x), deps(x, depth) x and what it depends on + rdeps(u, x), rdeps(u, x, depth) what in u depends on x + kind(k, x) the targets of x whose kind (CC.StaticLibrary, Zig.Test...) holds k + tests(x) the tests of x + x + y, x - y, x ^ y union, difference, intersection; also union, except, intersect + An operator stands apart, with spaces around it. + + Examples: + tazel query 'deps(//app:greeter)' + tazel query 'rdeps(//..., //core:core)' --output label_kind + tazel query '//... - tests(//...)' + """), + ["cquery"] = new("tazel cquery <expression>: query for the platform and mode of the command.", $""" + tazel cquery <expression> [--output label|label_kind] [options] + + Answers as tazel query does, for the platform and mode of the command: what does not build for the + platform is left out, and each target is printed with its configuration, such as (linux-amd64-debug). + + {BuildOptions} + """), + ["aquery"] = new("tazel aquery <expression>: prints the actions of the targets.", $""" + tazel aquery <expression> [options] + + Prints the actions of the targets of the expression, for the platform and mode of the command: what each + runs, reads and writes. Nothing runs. {BuildOptions} - """, - ["clean"] = """ + """), + ["fetch"] = new("tazel fetch: downloads and checks what the module depends on.", """ + tazel fetch + + Downloads and checks the modules of Tazel Portal Modules and the plugins the module depends on, and unpacks + its local modules and plugins, without building. It takes no arguments. + """), + ["vendor"] = new("tazel vendor: copies the modules of Tazel Portal Modules into vendor/.", """ + tazel vendor + + Copies every module of Tazel Portal Modules the module depends on into vendor/, with its .sha256sums. + Builds take an archive from vendor/ before they download it, so a module with vendor/ builds offline. + """), + ["portal-modules"] = new("tazel portal-modules search|info [-e] [--] <module|group:module>: Tazel Portal Modules.", """ + tazel portal-modules search [-e|--exact] [--] <module|group:module> + tazel portal-modules info [-e|--exact] [--] <module|group:module> + + search lists the modules whose group:module holds the query; info prints the versions of one module, with + yanked ones marked, their push dates and dependencies. + -e, --exact only group:module, exactly; the group is required with it + Without -e the group may be left out; for info, a name that is a module of more than one group needs it. + -- ends the options, so a query may start with a dash. + + Examples: + tazel portal-modules search json + tazel portal-modules info com.example:json -e + """), + ["clean"] = new("tazel clean [--expunge]: removes what builds made.", """ tazel clean [--expunge] - Removes the outputs of every platform and mode, the test logs and zig's cache; --expunge removes all of - .tazel, the unpacked dependencies too. - """, - ["package"] = """ + Removes the outputs of every platform and mode, the test logs, the coverage report, zig's cache and the + archives of tazel package; --expunge removes all of .tazel, the unpacked dependencies and plugins too. + """), + ["package"] = new("tazel package: writes the archive of the module.", """ tazel package - Writes the archive of the module, $group.$module-$version.tazel.tar.xz, and its .sha256sums to - .tazel/package. The files of PortalModules' Exclude are left out. - """, - ["custom"] = """ + Writes .tazel/package/$group.$module-$version.tazel.tar.xz and its .sha256sums. The archive is the same + bytes for the same files: sorted, owned by no one, dated at the epoch. Files starting with a dot, the + directories of other modules and what PortalModules' Exclude names are left out. + """), + ["custom"] = new("tazel custom <name> [arguments]: runs a command of tazel_custom.txt.", """ tazel custom <name> [arguments] Runs a command of the tazel_custom.txt of the current directory. The longest name that fits wins; -- ends - the name, and what follows is arguments. - """, - ["version"] = """ + the name, and what follows is arguments, which <1>, <2>... and <*> take. Everything after custom belongs to + the command, its options too. + """), + ["version"] = new("tazel version: prints the version of Tazel.", """ tazel version - Prints the version of Tazel. - """, - ["help"] = """ - tazel help [command] + Prints the version of Tazel, the .NET runtime it runs on and the platform of this machine. + """), + ["help"] = new("tazel help [command] [--long]: prints help.", """ + tazel help [command] [--long] - Prints what Tazel can do, or what one command does. - """, - ["dotnet"] = """ + Prints what Tazel can do, or what one command does; --long says more. + """), + ["dotnet"] = new("tazel dotnet start-daemon|restart-daemon|stop-daemon: the daemon of Tazel.", """ tazel dotnet start-daemon|restart-daemon|stop-daemon The daemon that keeps the .NET runtime of Tazel warm between commands. - """, + """), }; - /// <summary>The help of <paramref name="topic"/>, or the general help.</summary> - public static string Text(string? topic) + private const string GlobalOptions = """ + Options of every command: + --color always|auto|never colors; default: auto + --progress always|auto|never the [done/total] counter; default: auto + --quiet only problems and the program's own output + --help, -h the help of the command + """; + + /// <summary>The help of <paramref name="topic"/>, or the general help; <paramref name="long"/> says more.</summary> + public static string Text(string? topic, bool @long = false) { if (topic is not null) { return Topics.TryGetValue(topic, out var text) - ? text.TrimEnd() + ? (@long ? text.Long : text.Short + $"\nMore: tazel help {topic} --long").TrimEnd() : throw new CommandLineException( $"'{topic}' is not a command of tazel{(Suggestions.Nearest(topic, Topics.Keys) is { } near ? $"; did you mean {near}?" : "")}"); } - return """ + var commands = string.Join('\n', Topics.Select(entry => $" {entry.Key,-15} {Summary(entry.Value.Short)}")); + var general = $""" Tazel builds C, C++, Objective-C, Objective-C++ and Zig. A module has a MODULE.csx at its root and a BUILD.csx in each package; targets are named by labels such as //app:greeter. Commands: - build build targets - test build and run tests - run build and run one program - clean remove what builds made - package write the archive of the module - custom run a command of tazel_custom.txt - version print the version - help print help; tazel help <command> for one command - - Options of every command: - --color always|auto|never colors; default: auto - --progress always|auto|never the [done/total] counter; default: auto - --quiet only problems and the program's own output - --help, -h the help of the command + {commands} + + {GlobalOptions} + tazel help <command> prints the help of one command; --long says more. """; + if (!@long) + { + return general.TrimEnd(); + } + + return $""" + {general.TrimEnd()} + + {Labels} + + {BuildOptions} + + Files Tazel reads: + MODULE.csx the module: its name, version, dependencies, plugins, toolchains (a C# script) + BUILD.csx the targets of one package (a C# script) + tazel_options.txt the options of this machine: the platform, the MicroVM sandbox + tazel_custom.txt the commands of tazel custom + + Exit status: 0 when the command did what it was asked, 1 when it failed, 2 for a command line it cannot take. + """.TrimEnd(); + } + + private static string Summary(string text) + { + var colon = text.IndexOf(": ", System.StringComparison.Ordinal); + return colon < 0 ? text : text[(colon + 2)..].TrimEnd('.'); } } diff --git a/src/Progmasoft.Tazel/Cli/MoreCommands.cs b/src/Progmasoft.Tazel/Cli/MoreCommands.cs new file mode 100644 index 0000000..3255860 --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/MoreCommands.cs @@ -0,0 +1,232 @@ +// 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 System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Archive; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Dsl.Build.Prelude; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Dsl.Options; +using Progmasoft.Tazel.Label; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Portal; +using Progmasoft.Tazel.Project; +using Spectre.Console; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>The queries, fetching and vendoring, and Tazel Portal Modules.</summary> +internal sealed partial class Commands +{ + private async Task<int> QueryAsync(QueryCommand query, CancellationToken cancel) + { + RefuseWithoutSandbox(); + var (options, _) = TazelOptionsFile.Effective(workingDirectory); + var platform = query.Flags.Platform ?? options.Platform ?? Host.Platform; + var mode = query.Flags.Mode ?? BuildMode.Debug; + var workspace = await Workspace.LoadAsync(workingDirectory, new BuildContext(mode, platform), TazelVersion, + reporter.Status).ConfigureAwait(false); + var current = CurrentPackage(workspace); + var targets = new Query(workspace, current).Evaluate(query.Expression); + var configuration = $"{platform.Name()}-{mode.ToString().ToLowerInvariant()}"; + switch (query.Kind) + { + case QueryKind.Query: + foreach (var target in targets) + { + reporter.Plain(query.Format == "label_kind" ? $"{Query.KindOf(target)} {target.Label}" : target.Label.ToString()); + } + + return 0; + case QueryKind.CQuery: + var selector = new Selector(workspace, platform); + foreach (var target in targets.Where(target => selector.Incompatibility(target) is null)) + { + var label = $"{target.Label} ({configuration})"; + reporter.Plain(query.Format == "label_kind" ? $"{Query.KindOf(target)} {label}" : label); + } + + return 0; + default: + var compatible = new Selector(workspace, platform); + var buildOptions = new BuildOptions + { + Mode = mode, + Platform = platform, + FeaturesOn = query.Flags.FeaturesOn, + FeaturesOff = query.Flags.FeaturesOff, + CompilerOptions = query.Flags.CompilerOptions, + CCompilerOptions = query.Flags.CCompilerOptions, + CppCompilerOptions = query.Flags.CppCompilerOptions, + LinkerOptions = query.Flags.LinkerOptions, + ZigCompilerOptions = query.Flags.ZigCompilerOptions, + }; + var planner = new Planner(workspace, buildOptions, new ToolchainChooser(workspace, platform)); + var seen = new HashSet<BuildAction>(); + foreach (var target in targets.Where(target => compatible.Incompatibility(target) is null)) + { + if (planner.Plan(target).Main is not { } main) + { + continue; + } + + foreach (var action in Owned(main, target, planner).Where(seen.Add)) + { + reporter.Plain($"action '{action.Description}'\n Target: {target.Label} ({configuration})\n" + + $" Command: {(action.Work is null ? Reporter.Quote(action.Command) : "(in Tazel) " + string.Join(' ', action.Command))}\n" + + $" Inputs: [{string.Join(", ", action.Inputs)}]\n Outputs: [{string.Join(", ", action.Outputs)}]\n"); + } + } + + return 0; + } + } + + /// <summary>The actions of <paramref name="target"/> itself, not those of what it depends on, in the order they run.</summary> + private static List<BuildAction> Owned(BuildAction main, ProjectTarget target, Planner planner) + { + var others = new HashSet<BuildAction>(target.Dependencies.Concat(target.ZigImports.Values) + .Select(dependency => planner.Plan(dependency)).SelectMany(products => products.HeaderActions.Append(products.Main)) + .OfType<BuildAction>()); + var order = new List<BuildAction>(); + Visit(main); + return order; + + void Visit(BuildAction action) + { + if (others.Contains(action) || order.Contains(action)) + { + return; + } + + foreach (var prerequisite in action.Prerequisites) + { + Visit(prerequisite); + } + + order.Add(action); + } + } + + private PackageId CurrentPackage(Workspace workspace) + { + var relative = FileSets.ToRoot(Path.GetFullPath(workingDirectory), workspace.Main.Root); + var path = relative == "." ? "" : relative; + while (path.Length > 0 && !workspace.Packages.Contains(new PackageId(null, path))) + { + var slash = path.LastIndexOf('/'); + path = slash < 0 ? "" : path[..slash]; + } + + return new PackageId(null, path); + } + + private async Task<int> FetchAsync() + { + RefuseWithoutSandbox(); + var (options, _) = TazelOptionsFile.Effective(workingDirectory); + var workspace = await Workspace.LoadAsync(workingDirectory, + new BuildContext(BuildMode.Debug, options.Platform ?? Host.Platform), TazelVersion, reporter.Status).ConfigureAwait(false); + var plugins = workspace.PluginsOf.Values.Sum(list => list.Count); + reporter.Success($"fetched {workspace.External.Count} module{(workspace.External.Count == 1 ? "" : "s")} " + + $"({workspace.PortalModules.Count} of Tazel Portal Modules) and {plugins} plugin{(plugins == 1 ? "" : "s")}"); + return 0; + } + + private async Task<int> VendorAsync(CancellationToken cancel) + { + RefuseWithoutSandbox(); + using var client = new PortalModulesClient(); + var (main, modules) = await Workspace.ResolvePortalAsync(workingDirectory, TazelVersion, client).ConfigureAwait(false); + var vendor = Path.Combine(main.Root, PortalDependencies.VendorDirectory); + foreach (var module in modules) + { + // The index too, so that a build with vendor/ resolves without the network. + var index = await client.IndexTextAsync(module.Group, module.Module, cancel).ConfigureAwait(false); + Directory.CreateDirectory(Path.Combine(vendor, module.Group, module.Module)); + await File.WriteAllTextAsync(Path.Combine(vendor, module.Group, module.Module, "index.json"), index, cancel) + .ConfigureAwait(false); + var name = module.BaseName + ModuleArchive.Extension; + if (File.Exists(Path.Combine(vendor, name))) + { + continue; + } + + await client.DownloadAsync(module.Group, module.Module, module.Version.ToNormalizedString(), vendor, cancel) + .ConfigureAwait(false); + reporter.Status($"vendored {module.Key} {module.Version}"); + } + + reporter.Success(modules.Count == 0 + ? "the module depends on no module of Tazel Portal Modules; its local modules and plugins are in it already" + : $"vendor/ holds the {modules.Count} module{(modules.Count == 1 ? "" : "s")} of Tazel Portal Modules the module needs"); + return 0; + } + + private async Task<int> PortalModulesAsync(PortalModulesCommand command, CancellationToken cancel) + { + using var client = new PortalModulesClient(); + var colon = command.Query.IndexOf(':', StringComparison.Ordinal); + var group = colon < 0 ? null : command.Query[..colon]; + var name = colon < 0 ? command.Query : command.Query[(colon + 1)..]; + if (command.Action == PortalAction.Search) + { + var catalog = await client.CatalogAsync(cancel).ConfigureAwait(false); + var found = catalog.Modules.Where(entry => command.Exact + ? entry.Group == group && entry.Module == name + : $"{entry.Group}:{entry.Module}".Contains(command.Query, StringComparison.OrdinalIgnoreCase)) + .OrderBy(entry => entry.Group, StringComparer.Ordinal).ThenBy(entry => entry.Module, StringComparer.Ordinal).ToList(); + if (found.Count == 0) + { + reporter.Warning($"Tazel Portal Modules has no module that matches {command.Query}"); + return 1; + } + + var table = new Table().Border(TableBorder.Rounded).AddColumn("Module").AddColumn("Latest").AddColumn("Description"); + foreach (var entry in found) + { + table.AddRow(Markup.Escape($"{entry.Group}:{entry.Module}"), Markup.Escape(entry.Latest ?? ""), + Markup.Escape(entry.Description ?? "")); + } + + reporter.Console.Write(table); + return 0; + } + + if (group is null) + { + // Without a group, the name must be one module's alone. + var catalog = await client.CatalogAsync(cancel).ConfigureAwait(false); + var groups = catalog.Modules.Where(entry => entry.Module == name).Select(entry => entry.Group).Distinct().Order().ToList(); + group = groups.Count switch + { + 0 => throw new ProjectException($"Tazel Portal Modules has no module {name}"), + 1 => groups[0], + _ => throw new CommandLineException( + $"{name} is a module of {string.Join(", ", groups)}; write the group: group:{name}"), + }; + } + + var index = await client.IndexAsync(group, name, cancel).ConfigureAwait(false) + ?? throw new ProjectException($"Tazel Portal Modules has no module {group}:{name}"); + var highest = PortalModulesClient.Highest(index); + reporter.Console.MarkupLine($"[bold]{Markup.Escape($"{index.Group}:{index.Module}")}[/]" + + (highest is null ? "" : $" latest {Markup.Escape(highest.Version)}")); + var versions = new Table().Border(TableBorder.Rounded).AddColumn("Version").AddColumn("Pushed").AddColumn("Dependencies"); + foreach (var version in index.Versions.Reverse()) + { + var dependencies = string.Join(", ", version.Dependencies.Select(d => $"{d.Group}:{d.Module} {d.Version}{(d.Test ? " (test)" : "")}")); + versions.AddRow(Markup.Escape(version.Version) + (version.Yanked ? " [red]yanked[/]" : ""), + version.Pushed.UtcDateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), Markup.Escape(dependencies)); + } + + reporter.Console.Write(versions); + return 0; + } +} diff --git a/src/Progmasoft.Tazel/Cli/Query.cs b/src/Progmasoft.Tazel/Cli/Query.cs new file mode 100644 index 0000000..c3af743 --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/Query.cs @@ -0,0 +1,218 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using Progmasoft.Tazel.Dsl; +using Progmasoft.Tazel.Label; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Cli; + +/// <summary> +/// The query language of <c>tazel query</c>, a part of Bazel's: target patterns, <c>deps(x)</c>, <c>deps(x, depth)</c>, +/// <c>rdeps(universe, x)</c>, <c>rdeps(universe, x, depth)</c>, <c>kind(k, x)</c>, <c>tests(x)</c>, and <c>+</c>, +/// <c>-</c>, <c>^</c> (or <c>union</c>, <c>except</c>, <c>intersect</c>) with parentheses. An operator stands apart, with +/// spaces around it, as a label may hold <c>-</c> and <c>+</c>. +/// </summary> +internal sealed class Query(Workspace workspace, PackageId current) +{ + private List<string> _tokens = []; + private int _position; + + /// <summary>The name of a target's kind, as <c>kind()</c> matches it and <c>--output label_kind</c> prints it.</summary> + public static string KindOf(ProjectTarget target) + { + ArgumentNullException.ThrowIfNull(target); + return $"{target.Family}.{target.Kind}"; + } + + /// <summary>The targets <paramref name="expression"/> names, in label order.</summary> + public IReadOnlyList<ProjectTarget> Evaluate(string expression) + { + _tokens = Tokens(expression); + _position = 0; + if (_tokens.Count == 0) + { + throw new ProjectException("the query is empty"); + } + + var result = Expression(); + if (_position < _tokens.Count) + { + throw new ProjectException($"the query has '{_tokens[_position]}' where it should end"); + } + + return result.OrderBy(target => target.Label.ToString(), StringComparer.Ordinal).ToList(); + } + + private static List<string> Tokens(string text) + { + var tokens = new List<string>(); + var i = 0; + while (i < text.Length) + { + if (char.IsWhiteSpace(text[i])) + { + i++; + } + else if (text[i] is '(' or ')' or ',') + { + tokens.Add(text[i++].ToString()); + } + else + { + var start = i; + while (i < text.Length && !char.IsWhiteSpace(text[i]) && text[i] is not ('(' or ')' or ',')) + { + i++; + } + + tokens.Add(text[start..i]); + } + } + + return tokens; + } + + private string? Peek => _position < _tokens.Count ? _tokens[_position] : null; + + private string Take(string? wanted = null) + { + if (_position >= _tokens.Count) + { + throw new ProjectException($"the query ends where it needs {(wanted is null ? "more" : $"'{wanted}'")}"); + } + + var token = _tokens[_position++]; + if (wanted is not null && token != wanted) + { + throw new ProjectException($"the query has '{token}' where it needs '{wanted}'"); + } + + return token; + } + + private HashSet<ProjectTarget> Expression() + { + var result = Term(); + while (Peek is "+" or "-" or "^" or "union" or "except" or "intersect") + { + var op = Take(); + var right = Term(); + switch (op) + { + case "+" or "union": + result.UnionWith(right); + break; + case "-" or "except": + result.ExceptWith(right); + break; + default: + result.IntersectWith(right); + break; + } + } + + return result; + } + + private HashSet<ProjectTarget> Term() + { + var token = Take(); + if (token == "(") + { + var inner = Expression(); + Take(")"); + return inner; + } + + if (Peek == "(" && token is "deps" or "rdeps" or "kind" or "tests") + { + Take("("); + HashSet<ProjectTarget> result; + switch (token) + { + case "deps": + var of = Expression(); + result = Closure(of, Depth(), target => target.Dependencies.Concat(target.ZigImports.Values)); + break; + case "rdeps": + var universe = Expression(); + Take(","); + var targets = Expression(); + var reverse = universe.SelectMany(target => target.Dependencies.Concat(target.ZigImports.Values) + .Select(dependency => (dependency, target))) + .ToLookup(pair => pair.dependency, pair => pair.target); + result = Closure(targets, Depth(), target => reverse[target]); + result.IntersectWith(universe.Union(targets)); + break; + case "kind": + var kind = Take(); + Take(","); + result = Expression().Where(target => KindOf(target).Contains(kind, StringComparison.OrdinalIgnoreCase)) + .ToHashSet(); + break; + default: + result = Expression().Where(target => target.Kind == TargetKind.Test).ToHashSet(); + break; + } + + Take(")"); + return result; + } + + return Pattern(token); + } + + private int? Depth() + { + if (Peek != ",") + { + return null; + } + + Take(","); + var text = Take(); + return int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var depth) + ? depth + : throw new ProjectException($"'{text}' is not a depth"); + } + + private static HashSet<ProjectTarget> Closure( + HashSet<ProjectTarget> start, int? depth, Func<ProjectTarget, IEnumerable<ProjectTarget>> next) + { + var result = new HashSet<ProjectTarget>(start); + var frontier = start.ToList(); + for (var level = 0; frontier.Count > 0 && (depth is null || level < depth); level++) + { + frontier = frontier.SelectMany(next).Where(result.Add).ToList(); + } + + return result; + } + + private HashSet<ProjectTarget> Pattern(string text) + { + Selection selection; + try + { + selection = Labels.Selection(text, current); + } + catch (LabelException error) + { + throw new ProjectException(error.Message, error); + } + + return selection switch + { + TargetLabel label => workspace.Targets.TryGetValue(label, out var target) + ? [target] + : throw new ProjectException($"{label} is not a target"), + PackagePattern pattern => workspace.Targets.Values.Where(target => pattern.Covers(target.Label.Package)).ToHashSet(), + _ => [], + }; + } +} diff --git a/src/Progmasoft.Tazel/Driver/BuildOptions.cs b/src/Progmasoft.Tazel/Driver/BuildOptions.cs index c7c9732..9492dc1 100644 --- a/src/Progmasoft.Tazel/Driver/BuildOptions.cs +++ b/src/Progmasoft.Tazel/Driver/BuildOptions.cs @@ -33,6 +33,9 @@ internal sealed record BuildOptions public IReadOnlyList<string> LinkerOptions { get; init; } = []; public IReadOnlyList<string> ZigCompilerOptions { get; init; } = []; + + /// <summary>Whether C-family code is built with LLVM source-based coverage, for <c>tazel coverage</c>.</summary> + public bool Coverage { get; init; } } /// <summary>Where a build writes, below the state directory of the main module.</summary> @@ -43,7 +46,11 @@ internal sealed class OutputLayout(string mainRoot, BuildOptions options) /// <summary>The outputs of this platform and mode, relative to <see cref="MainRoot"/>.</summary> public string OutRoot { get; } = - $"{ModuleFiles.StateDirectory}/out/{options.Platform.Name()}-{options.Mode.ToString().ToLowerInvariant()}"; + $"{ModuleFiles.StateDirectory}/out/{options.Platform.Name()}-{options.Mode.ToString().ToLowerInvariant()}" + + (options.Coverage ? "-coverage" : ""); + + /// <summary>Where <c>tazel coverage</c> writes its report, relative to <see cref="MainRoot"/>.</summary> + public string CoverageRoot { get; } = $"{ModuleFiles.StateDirectory}/coverage"; /// <summary>Where the tests write their logs, relative to <see cref="MainRoot"/>.</summary> public string TestLogs { get; } = $"{ModuleFiles.StateDirectory}/testlogs"; diff --git a/src/Progmasoft.Tazel/Driver/CCPlanner.cs b/src/Progmasoft.Tazel/Driver/CCPlanner.cs index c5226e0..9828bb2 100644 --- a/src/Progmasoft.Tazel/Driver/CCPlanner.cs +++ b/src/Progmasoft.Tazel/Driver/CCPlanner.cs @@ -153,6 +153,12 @@ internal sealed partial class Planner } } + if (Options.Coverage) + { + RequireClang(toolchain, target); + command.AddRange(["-fprofile-instr-generate", "-fcoverage-mapping"]); + } + command.AddRange(Options.CompilerOptions); command.AddRange(cxx ? Options.CppCompilerOptions : Options.CCompilerOptions); command.AddRange(["-MD", "-MF", objectFile + ".d", "-c", source, "-o", objectFile]); @@ -289,6 +295,11 @@ internal sealed partial class Planner _ => Files.None, }; var extraFiles = FileSets.Resolve(extra, target.PackageDirectory, Layout.MainRoot, target.Place); + if (Options.Coverage) + { + command.Add("-fprofile-instr-generate"); + } + command.AddRange(Options.LinkerOptions); var link = new BuildAction { @@ -339,6 +350,17 @@ internal sealed partial class Planner return toolchain.Features.Where(feature => on.Contains(feature.Name)).ToList(); } + /// <summary>LLVM source-based coverage needs clang; gcc and zig cc write another format.</summary> + private static void RequireClang(CCToolchain toolchain, ProjectTarget target) + { + if (!Path.GetFileNameWithoutExtension(toolchain.C.Program).Contains("clang", StringComparison.Ordinal) || + toolchain.C.Prefix.Count > 0) + { + throw new ProjectException( + $"tazel coverage needs clang, and {target.Label} is built with {toolchain.C} of {toolchain.Name}"); + } + } + private static IEnumerable<string> Flags(IReadOnlyList<Feature> features, CCAction action) => features.SelectMany(feature => feature.Settings.FlagSets) .Where(set => set.Actions.Contains(action)) diff --git a/src/Progmasoft.Tazel/Driver/CoverageReport.cs b/src/Progmasoft.Tazel/Driver/CoverageReport.cs new file mode 100644 index 0000000..6e19b47 --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/CoverageReport.cs @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Dsl; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Driver; + +/// <summary> +/// The report of <c>tazel coverage</c>: the profiles the tests wrote, merged by llvm-profdata, read by llvm-cov into an +/// LCOV file and a summary. Both tools are taken beside the clang of the build, else from PATH. +/// </summary> +internal static class CoverageReport +{ + public static async Task<bool> WriteAsync( + Planner planner, ToolchainChooser chooser, + IReadOnlyList<(ProjectTarget Target, TargetProducts Products, bool Built)> tests, Reporter reporter, + CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(planner); + ArgumentNullException.ThrowIfNull(chooser); + ArgumentNullException.ThrowIfNull(tests); + var layout = planner.Layout; + var programs = tests.Where(test => test.Built && test.Target.Family != Family.Zig && test.Products.Executable is not null) + .Select(test => layout.Full(test.Products.Executable!)).ToList(); + foreach (var zig in tests.Where(test => test.Target.Family == Family.Zig)) + { + reporter.Status($"{zig.Target.Label}: Zig tests are run, and LLVM coverage covers C-family code only"); + } + + var profiles = Directory.Exists(layout.Full(layout.TestLogs)) + ? Directory.EnumerateFiles(layout.Full(layout.TestLogs), "coverage-*.profraw", SearchOption.AllDirectories).Order().ToList() + : []; + if (programs.Count == 0 || profiles.Count == 0) + { + reporter.Warning("no test wrote a coverage profile, so there is no report"); + return programs.Count == 0; + } + + var clangDirectory = chooser.UsedCC.Select(toolchain => Path.GetDirectoryName(toolchain.C.Program)).FirstOrDefault(); + var profdata = Tool("llvm-profdata", clangDirectory); + var cov = Tool("llvm-cov", clangDirectory); + var directory = layout.Full(layout.CoverageRoot); + Directory.CreateDirectory(directory); + var merged = Path.Combine(directory, "coverage.profdata"); + var environment = Processes.ForActions(); + var merge = await Processes.RunAsync([profdata, "merge", "-sparse", "-o", merged, .. profiles], layout.MainRoot, + environment, null, cancel).ConfigureAwait(false); + if (merge.ExitCode != 0) + { + reporter.ActionFailed("Merging the coverage profiles", [profdata, "merge"], merge.Output); + return false; + } + + var objects = programs.Skip(1).SelectMany(program => new[] { "-object", program }).ToList(); + var export = await Processes.RunAsync( + [cov, "export", "-format=lcov", $"-instr-profile={merged}", programs[0], .. objects], layout.MainRoot, + environment, null, cancel).ConfigureAwait(false); + if (export.ExitCode != 0) + { + reporter.ActionFailed("Writing the coverage report", [cov, "export"], export.Output); + return false; + } + + var lcov = Path.Combine(directory, "coverage.lcov"); + await File.WriteAllTextAsync(lcov, export.Output, cancel).ConfigureAwait(false); + var summary = await Processes.RunAsync( + [cov, "report", $"-instr-profile={merged}", programs[0], .. objects], layout.MainRoot, environment, null, cancel) + .ConfigureAwait(false); + if (summary.ExitCode == 0) + { + reporter.Plain(summary.Output.TrimEnd('\n')); + } + + reporter.Success($"wrote {FileSets.ToRoot(lcov, layout.MainRoot)}"); + return true; + } + + private static string Tool(string name, string? beside) + { + if (beside is not null) + { + foreach (var candidate in new[] { name, name + ".exe" }) + { + var path = Path.Combine(beside, candidate); + if (File.Exists(path)) + { + return path; + } + } + } + + return Host.Which(name) ?? throw new ProjectException( + $"tazel coverage needs {name} beside clang or on PATH; it comes with LLVM"); + } +} diff --git a/src/Progmasoft.Tazel/Driver/TestRunner.cs b/src/Progmasoft.Tazel/Driver/TestRunner.cs index 85a8321..972aaaf 100644 --- a/src/Progmasoft.Tazel/Driver/TestRunner.cs +++ b/src/Progmasoft.Tazel/Driver/TestRunner.cs @@ -59,7 +59,7 @@ internal static class Runfiles } /// <summary>Runs tests: each with a small environment, its own temporary directory, a timeout, and retries when flaky.</summary> -internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporter) +internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporter, bool coverage = false) { /// <summary>The timeout of a size, as in Bazel.</summary> public static TimeSpan TimeoutOf(TestSize size) => size switch @@ -128,6 +128,12 @@ internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporte for (var shard = 0; shard < settings.ShardCount; shard++) { var environment = Environment(target, settings, logDirectory, shard, runfiles); + if (coverage) + { + // Each process of the test writes its own profile; tazel coverage merges them. + environment["LLVM_PROFILE_FILE"] = System.IO.Path.Combine(logDirectory, $"coverage-{shard}-%p.profraw"); + } + Runfiles.AddLibraryPath(environment, products, layout); var command = new List<string> { layout.Full(products.Executable!) }; command.AddRange(settings.Arguments); diff --git a/src/Progmasoft.Tazel/Portal/PortalModules.cs b/src/Progmasoft.Tazel/Portal/PortalModules.cs new file mode 100644 index 0000000..cd3adcf --- /dev/null +++ b/src/Progmasoft.Tazel/Portal/PortalModules.cs @@ -0,0 +1,212 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +using NuGet.Versioning; +using Progmasoft.Tazel.Archive; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Portal; + +/// <summary>A dependency of a version in an index.</summary> +internal sealed record IndexDependency( + [property: JsonPropertyName("group")] string Group, + [property: JsonPropertyName("module")] string Module, + [property: JsonPropertyName("version")] string Version, + [property: JsonPropertyName("test")] bool Test); + +/// <summary>One version in an index.</summary> +internal sealed record IndexVersion( + [property: JsonPropertyName("version")] string Version, + [property: JsonPropertyName("pushed")] DateTimeOffset Pushed, + [property: JsonPropertyName("yanked")] bool Yanked, + [property: JsonPropertyName("dependencies")] IReadOnlyList<IndexDependency> Dependencies); + +/// <summary><c>modules.tazel.net/$group/$module/index.json</c>: every version of one module.</summary> +internal sealed record ModuleIndex( + [property: JsonPropertyName("group")] string Group, + [property: JsonPropertyName("module")] string Module, + [property: JsonPropertyName("versions")] IReadOnlyList<IndexVersion> Versions); + +/// <summary>One module of <c>modules.tazel.net/index.json</c>, the list that search reads.</summary> +internal sealed record CatalogEntry( + [property: JsonPropertyName("group")] string Group, + [property: JsonPropertyName("module")] string Module, + [property: JsonPropertyName("description")] string? Description, + [property: JsonPropertyName("latest")] string? Latest); + +/// <summary><c>modules.tazel.net/index.json</c>.</summary> +internal sealed record Catalog([property: JsonPropertyName("modules")] IReadOnlyList<CatalogEntry> Modules); + +/// <summary> +/// The client of Tazel Portal Modules, laid out as the Bazel Central Registry is: an index per module, and each version's +/// archive with its <c>.sha256sums</c> beside it. The address is <c>https://modules.tazel.net</c>, or +/// <c>TAZEL_PORTAL_MODULES_URL</c>. +/// </summary> +internal sealed class PortalModulesClient : IDisposable +{ + public const string DefaultAddress = "https://modules.tazel.net"; + + private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = false }; + + private readonly HttpClient _http; + + private readonly string? _vendor; + + /// <summary> + /// A client of the portal at <paramref name="address"/>; with <paramref name="vendor"/>, an index found there is read + /// from there instead. + /// </summary> + public PortalModulesClient(Uri? address = null, HttpMessageHandler? handler = null, string? vendor = null) + { + _vendor = vendor; + Address = address ?? new Uri(Environment.GetEnvironmentVariable("TAZEL_PORTAL_MODULES_URL") is { Length: > 0 } set + ? set.TrimEnd('/') + : DefaultAddress); + if (Address.Scheme != Uri.UriSchemeHttps && !Address.IsLoopback) + { + throw new ProjectException($"Tazel Portal Modules is reached over https only, not {Address}"); + } + + _http = handler is null ? new HttpClient() : new HttpClient(handler); + _http.Timeout = TimeSpan.FromMinutes(5); + _http.DefaultRequestHeaders.UserAgent.ParseAdd($"tazel/{Cli.Commands.TazelVersion.ToString(3)}"); + } + + public Uri Address { get; } + + /// <summary>The address as text without a closing slash, for the paths below it.</summary> + private string Base => Address.ToString().TrimEnd('/'); + + /// <summary>The list of every module, for search.</summary> + public async Task<Catalog> CatalogAsync(CancellationToken cancel) => + await GetJsonAsync<Catalog>("index.json", cancel).ConfigureAwait(false) + ?? throw new ProjectException($"{Base}/index.json is empty"); + + /// <summary>The index of <paramref name="group"/>:<paramref name="module"/>, or null when there is no such module.</summary> + public async Task<ModuleIndex?> IndexAsync(string group, string module, CancellationToken cancel) + { + var text = await IndexTextAsync(group, module, cancel).ConfigureAwait(false); + return text is null ? null : Parse<ModuleIndex>(text, $"{group}/{module}/index.json"); + } + + /// <summary>The text of an index: from vendor/ when it is there, else from the portal; null for no such module.</summary> + public async Task<string?> IndexTextAsync(string group, string module, CancellationToken cancel) + { + var path = $"{group}/{module}/index.json"; + if (_vendor is not null && File.Exists(Path.Combine(_vendor, group, module, "index.json"))) + { + return await File.ReadAllTextAsync(Path.Combine(_vendor, group, module, "index.json"), cancel).ConfigureAwait(false); + } + + return await GetTextAsync(path, cancel).ConfigureAwait(false); + } + + /// <summary> + /// Downloads the archive of a version into <paramref name="directory"/>, checks it against its + /// <c>.sha256sums</c>, and returns its path and SHA-256. + /// </summary> + public async Task<(string Archive, string Sha256)> DownloadAsync( + string group, string module, string version, string directory, CancellationToken cancel) + { + var name = $"{ModuleArchive.BaseName(group, module, version)}{ModuleArchive.Extension}"; + var path = $"{group}/{module}/{version}/{name}"; + var sums = await GetTextAsync(path + ".sha256sums", cancel).ConfigureAwait(false) + ?? throw new ProjectException($"{Base}/{path}.sha256sums is not there"); + var expected = Sha256Sums.SumFor(sums, name, $"{path}.sha256sums") + ?? throw new ProjectException($"{Base}/{path}.sha256sums does not name {name}"); + Directory.CreateDirectory(directory); + var file = Path.Combine(directory, name); + var partial = file + ".partial"; + using (var response = await _http.GetAsync(new Uri($"{Base}/{path}"), HttpCompletionOption.ResponseHeadersRead, cancel) + .ConfigureAwait(false)) + { + if (!response.IsSuccessStatusCode) + { + throw new ProjectException($"{Base}/{path} answered {(int)response.StatusCode}"); + } + + var output = File.Create(partial); + await using (output.ConfigureAwait(false)) + { + await response.Content.CopyToAsync(output, cancel).ConfigureAwait(false); + } + } + + var actual = Sha256Sums.Sha256(partial); + if (!string.Equals(actual, expected, StringComparison.Ordinal)) + { + File.Delete(partial); + throw new ProjectException($"{Base}/{path} has the SHA-256 {actual}, and its .sha256sums says {expected}"); + } + + File.Move(partial, file, overwrite: true); + await File.WriteAllTextAsync(file + ".sha256sums", $"{actual} {name}\n", cancel).ConfigureAwait(false); + return (file, actual); + } + + /// <summary>The highest version of <paramref name="index"/> by SemVer that is not yanked; a release before any pre-release.</summary> + public static IndexVersion? Highest(ModuleIndex index) + { + ArgumentNullException.ThrowIfNull(index); + var usable = index.Versions.Where(v => !v.Yanked && NuGetVersion.TryParseStrict(v.Version, out _)) + .Select(v => (Entry: v, Version: NuGetVersion.Parse(v.Version))).ToList(); + var releases = usable.Where(v => !v.Version.IsPrerelease).ToList(); + return (releases.Count > 0 ? releases : usable).OrderByDescending(v => v.Version).Select(v => v.Entry).FirstOrDefault(); + } + + public void Dispose() => _http.Dispose(); + + private async Task<T?> GetJsonAsync<T>(string path, CancellationToken cancel) + where T : class + { + var text = await GetTextAsync(path, cancel).ConfigureAwait(false); + return text is null ? null : Parse<T>(text, path); + } + + private T Parse<T>(string text, string path) + where T : class + { + try + { + return JsonSerializer.Deserialize<T>(text, Json) + ?? throw new ProjectException($"{Base}/{path} is empty"); + } + catch (JsonException error) + { + throw new ProjectException($"{Base}/{path} is not what Tazel Portal Modules serves: {error.Message}", error); + } + } + + private async Task<string?> GetTextAsync(string path, CancellationToken cancel) + { + try + { + using var response = await _http.GetAsync(new Uri($"{Base}/{path}"), cancel).ConfigureAwait(false); + if (response.StatusCode == HttpStatusCode.NotFound) + { + return null; + } + + if (!response.IsSuccessStatusCode) + { + throw new ProjectException($"{Base}/{path} answered {(int)response.StatusCode}"); + } + + return await response.Content.ReadAsStringAsync(cancel).ConfigureAwait(false); + } + catch (HttpRequestException error) + { + throw new ProjectException($"Tazel Portal Modules at {Address} cannot be reached: {error.Message}", error); + } + } +} diff --git a/src/Progmasoft.Tazel/Project/PortalDependencies.cs b/src/Progmasoft.Tazel/Project/PortalDependencies.cs new file mode 100644 index 0000000..2f056cc --- /dev/null +++ b/src/Progmasoft.Tazel/Project/PortalDependencies.cs @@ -0,0 +1,185 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using NuGet.Versioning; +using Progmasoft.Tazel.Archive; +using Progmasoft.Tazel.Portal; + +namespace Progmasoft.Tazel.Project; + +/// <summary>A module of Tazel Portal Modules a build uses, at the version the resolution chose.</summary> +/// <param name="Repository">The name its labels use: the alias, or the module's name.</param> +/// <param name="Group">Its group.</param> +/// <param name="Module">Its name.</param> +/// <param name="Version">The version chosen.</param> +internal sealed record ResolvedModule(string Repository, string Group, string Module, NuGetVersion Version) +{ + public string Key => $"{Group}:{Module}"; + + public string BaseName => ModuleArchive.BaseName(Group, Module, Version.ToNormalizedString()); +} + +/// <summary> +/// Resolves the modules of Tazel Portal Modules a build needs, as Bazel's minimal version selection does: each module at +/// the highest version anything asks for. Their dependencies come from the indexes, so no archive is downloaded to +/// resolve. A yanked version takes part in no resolution. +/// </summary> +internal static class PortalDependencies +{ + /// <summary>The directory below the main module whose archives a build takes before it downloads.</summary> + public const string VendorDirectory = "vendor"; + + public static async Task<IReadOnlyList<ResolvedModule>> ResolveAsync( + IReadOnlyList<(string Group, string Module, string Version, string? Alias, string Place)> direct, + PortalModulesClient client, CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(direct); + var wanted = new Dictionary<string, NuGetVersion>(StringComparer.Ordinal); + var names = new Dictionary<string, string>(StringComparer.Ordinal); + var why = new Dictionary<string, string>(StringComparer.Ordinal); + var queue = new Queue<string>(); + foreach (var (group, module, text, alias, place) in direct) + { + if (!NuGetVersion.TryParseStrict(text, out var version)) + { + throw new ProjectException($"{place}: '{text}' is not a SemVer version"); + } + + var key = $"{group}:{module}"; + var repository = alias ?? module; + if (names.TryGetValue(key, out var other) && other != repository) + { + throw new ProjectException($"{place}: {key} is named twice, as @{other} and @{repository}"); + } + + names[key] = repository; + Ask(key, version, place); + } + + var indexes = new Dictionary<string, ModuleIndex>(StringComparer.Ordinal); + var done = new Dictionary<string, NuGetVersion>(StringComparer.Ordinal); + while (queue.Count > 0) + { + var key = queue.Dequeue(); + var version = wanted[key]; + if (done.TryGetValue(key, out var seen) && seen == version) + { + continue; + } + + done[key] = version; + if (!indexes.TryGetValue(key, out var index)) + { + var parts = key.Split(':'); + index = await client.IndexAsync(parts[0], parts[1], cancel).ConfigureAwait(false) + ?? throw new ProjectException($"{why[key]}: Tazel Portal Modules has no module {key}"); + indexes[key] = index; + } + + var entry = index.Versions.FirstOrDefault(v => + NuGetVersion.TryParseStrict(v.Version, out var listed) && listed == version) + ?? throw new ProjectException( + $"{why[key]}: {key} has no version {version}; it has {string.Join(", ", index.Versions.Select(v => v.Version))}"); + if (entry.Yanked) + { + throw new ProjectException($"{why[key]}: {key} {version} is yanked, so it takes part in no resolution"); + } + + foreach (var dependency in entry.Dependencies.Where(d => !d.Test)) + { + if (!NuGetVersion.TryParseStrict(dependency.Version, out var needed)) + { + throw new ProjectException($"the index of {key} names {dependency.Group}:{dependency.Module} at '{dependency.Version}'"); + } + + var next = $"{dependency.Group}:{dependency.Module}"; + names.TryAdd(next, dependency.Module); + Ask(next, needed, $"{key} {version}"); + } + } + + var resolved = wanted.Select(entry => + { + var parts = entry.Key.Split(':'); + return new ResolvedModule(names[entry.Key], parts[0], parts[1], entry.Value); + }).OrderBy(module => module.Key, StringComparer.Ordinal).ToList(); + var clash = resolved.GroupBy(module => module.Repository).FirstOrDefault(group => group.Count() > 1); + if (clash is not null) + { + throw new ProjectException( + $"{string.Join(" and ", clash.Select(m => m.Key))} would both be @{clash.Key}; give one of them an Alias"); + } + + return resolved; + + void Ask(string key, NuGetVersion version, string place) + { + if (!wanted.TryGetValue(key, out var current) || version > current) + { + wanted[key] = version; + why[key] = place; + queue.Enqueue(key); + } + } + } + + /// <summary> + /// The root of <paramref name="module"/>, unpacked once below the state directory: from <c>vendor/</c> when its + /// archive is there, checked against its <c>.sha256sums</c>, or downloaded. + /// </summary> + public static async Task<string> FetchAsync( + string mainRoot, ResolvedModule module, PortalModulesClient? client, CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(module); + var name = module.BaseName + ModuleArchive.Extension; + var vendored = Path.Combine(mainRoot, VendorDirectory, name); + string archive; + string sha; + if (File.Exists(vendored)) + { + var sums = vendored + ".sha256sums"; + var expected = File.Exists(sums) + ? Sha256Sums.SumFor(await File.ReadAllTextAsync(sums, cancel).ConfigureAwait(false), name, $"vendor/{name}.sha256sums") + : null; + sha = Sha256Sums.Sha256(vendored); + if (expected is null || !string.Equals(expected, sha, StringComparison.Ordinal)) + { + throw new ProjectException($"vendor/{name} does not match its .sha256sums; run tazel vendor again"); + } + + archive = vendored; + } + else + { + if (client is null) + { + throw new ProjectException($"{module.Key} {module.Version} is not in vendor/ and nothing may be downloaded"); + } + + (archive, sha) = await client.DownloadAsync(module.Group, module.Module, module.Version.ToNormalizedString(), + Path.Combine(mainRoot, ModuleFiles.StateDirectory, "downloads"), cancel).ConfigureAwait(false); + } + + var destination = Path.Combine(mainRoot, ModuleFiles.StateDirectory, "external", $"{module.BaseName}-{sha[..16]}"); + var marker = Path.Combine(destination, ".unpacked"); + if (File.Exists(marker)) + { + return Path.Combine(destination, (await File.ReadAllTextAsync(marker, cancel).ConfigureAwait(false)).Trim()); + } + + if (Directory.Exists(destination)) + { + Directory.Delete(destination, recursive: true); + } + + var root = ModuleArchive.Unpack(archive, destination); + await File.WriteAllTextAsync(marker, Path.GetFileName(root), cancel).ConfigureAwait(false); + return root; + } +} diff --git a/src/Progmasoft.Tazel/Project/Workspace.cs b/src/Progmasoft.Tazel/Project/Workspace.cs index 49fa7e3..519d6e7 100644 --- a/src/Progmasoft.Tazel/Project/Workspace.cs +++ b/src/Progmasoft.Tazel/Project/Workspace.cs @@ -103,6 +103,7 @@ internal sealed class Workspace var main = await LoadModuleAsync(root, null, tazelVersion).ConfigureAwait(false); var workspace = new Workspace(main); await workspace.LoadDependenciesAsync(main, tazelVersion).ConfigureAwait(false); + await workspace.LoadPortalModulesAsync(tazelVersion, offline: false).ConfigureAwait(false); await workspace.LoadPackagesAsync(main, build, status ?? (_ => { })).ConfigureAwait(false); foreach (var module in workspace.External.Values) { @@ -161,9 +162,9 @@ internal sealed class Workspace { if (dependency.Portal is { } portal) { - throw new ProjectException( - $"{module.Shown(ModuleFiles.ModuleFile)}: {portal.Group}:{portal.Name}:{portal.Version} is a module of " + - "Tazel Portal Modules, and this Tazel fetches no modules; use LocalModule.From with its archive"); + // Modules of Tazel Portal are resolved together, once every local module is loaded. + PortalRequests.Add((portal.Group, portal.Name, portal.Version, portal.Alias, module.Shown(ModuleFiles.ModuleFile))); + continue; } var local = dependency.Local!; @@ -185,6 +186,53 @@ internal sealed class Workspace } } + /// <summary>The modules of Tazel Portal Modules the project files ask for, before resolution.</summary> + private List<(string Group, string Module, string Version, string? Alias, string Place)> PortalRequests { get; } = []; + + /// <summary>The modules of Tazel Portal Modules the build uses, at the versions the resolution chose.</summary> + public List<ResolvedModule> PortalModules { get; } = []; + + /// <summary>Resolves the modules of Tazel Portal Modules, then fetches and loads each.</summary> + private async Task LoadPortalModulesAsync(Version tazelVersion, bool offline) + { + if (PortalRequests.Count == 0) + { + return; + } + + using var client = new Portal.PortalModulesClient(vendor: System.IO.Path.Combine(Main.Root, PortalDependencies.VendorDirectory)); + var resolved = await PortalDependencies.ResolveAsync(PortalRequests, client, System.Threading.CancellationToken.None) + .ConfigureAwait(false); + foreach (var module in resolved) + { + if (External.ContainsKey(module.Repository)) + { + throw new ProjectException($"{module.Key} would be @{module.Repository}, the name of a local module; give it an Alias"); + } + + var root = await PortalDependencies.FetchAsync(Main.Root, module, offline ? null : client, + System.Threading.CancellationToken.None).ConfigureAwait(false); + External[module.Repository] = await LoadModuleAsync(root, module.Repository, tazelVersion).ConfigureAwait(false); + PortalModules.Add(module); + } + } + + /// <summary>The modules of Tazel Portal Modules that <paramref name="directory"/>'s module needs, resolved but not fetched.</summary> + public static async Task<(LoadedModule Main, IReadOnlyList<ResolvedModule> Modules)> ResolvePortalAsync( + string directory, Version tazelVersion, Portal.PortalModulesClient client) + { + var main = await LoadMainModuleAsync(directory, tazelVersion).ConfigureAwait(false); + var workspace = new Workspace(main); + await workspace.LoadDependenciesAsync(main, tazelVersion).ConfigureAwait(false); + if (workspace.PortalRequests.Count == 0) + { + return (main, []); + } + + return (main, await PortalDependencies.ResolveAsync(workspace.PortalRequests, client, System.Threading.CancellationToken.None) + .ConfigureAwait(false)); + } + /// <summary>The plugins each module loaded, by its repository (null for the main module).</summary> public Dictionary<string, IReadOnlyList<LoadedPlugin>> PluginsOf { get; } = new(StringComparer.Ordinal); diff --git a/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs b/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs new file mode 100644 index 0000000..17dc0ec --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs @@ -0,0 +1,397 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Archive; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Label; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class QueryTests +{ + private const string Build = """ + using Progmasoft.Tazel.Dsl.Build.Prelude; + var core = CC.StaticLibrary("core", new() { Sources = ["core.c"], Visibility = Visibility.Module }); + var util = CC.StaticLibrary("util", new() { Sources = ["util.c"], Depends = [core], Visibility = Visibility.Module }); + CC.Executable("app", new() { Sources = ["main.c"], Depends = [util] }); + CC.Test("util_test", new() { Sources = ["test.c"], Depends = [util] }); + ObjectiveC.StaticLibrary("mac", new()); + """; + + private static TemporaryModule Module() => new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile).Write("BUILD.csx", Build) + .Write("core.c", "").Write("util.c", "").Write("main.c", "").Write("test.c", ""); + + [Theory] + [InlineData("deps(//:app)", "//:app //:core //:util")] + [InlineData("deps(//:app, 1)", "//:app //:util")] + [InlineData("rdeps(//..., //:core)", "//:app //:core //:util //:util_test")] + [InlineData("rdeps(//..., //:core, 1)", "//:core //:util")] + [InlineData("kind(Test, //...)", "//:util_test")] + [InlineData("tests(//...)", "//:util_test")] + [InlineData("//... - tests(//...) - //:mac", "//:app //:core //:util")] + [InlineData("deps(//:app) ^ deps(//:util_test)", "//:core //:util")] + [InlineData("(//:app union //:core) except //:app", "//:core")] + [InlineData(":app", "//:app")] + public async Task QueriesTheTargetGraph(string expression, string expected) + { + using var module = Module(); + var workspace = await module.LoadAsync(); + var found = new Query(workspace, PackageId.Root).Evaluate(expression); + Assert.Equal(expected, string.Join(' ', found.Select(target => target.Label.ToString()))); + } + + [Theory] + [InlineData("deps(//:app", "ends where it needs ')'")] + [InlineData("//:nope", "//:nope is not a target")] + [InlineData("//:app //:core", "has '//:core' where it should end")] + [InlineData("deps(//:app, x)", "'x' is not a depth")] + public async Task SaysWhatIsWrongWithAQuery(string expression, string message) + { + using var module = Module(); + var workspace = await module.LoadAsync(); + var error = Assert.Throws<Project.ProjectException>(() => new Query(workspace, PackageId.Root).Evaluate(expression)); + Assert.Contains(message, error.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task CQueryLeavesOutWhatDoesNotBuildAndAQueryPrintsActions() + { + using var module = Module(); + var (status, output) = await module.TazelAsync(".", "cquery", "//...", "--platform", "linux-amd64", "--quiet"); + Assert.True(status == 0, output); + Assert.Contains("//:app (linux-amd64-debug)", output, StringComparison.Ordinal); + Assert.DoesNotContain("//:mac", output, StringComparison.Ordinal); + + (status, output) = await module.TazelAsync(".", "query", "//...", "--output", "label_kind", "--quiet"); + Assert.True(status == 0, output); + Assert.Contains("ObjectiveC.StaticLibrary //:mac", output, StringComparison.Ordinal); + + Assert.SkipWhen(Host.Which("clang") is null && Host.Which("gcc") is null && Host.Which("zig") is null, "no C compiler"); + (status, output) = await module.TazelAsync(".", "aquery", "//:util", "--quiet"); + Assert.True(status == 0, output); + Assert.Contains("action 'Compiling //:util util.c'", output, StringComparison.Ordinal); + Assert.Contains("action 'Archiving //:util'", output, StringComparison.Ordinal); + Assert.DoesNotContain("//:core core.c", output, StringComparison.Ordinal); + } +} + +public sealed class HelpTests +{ + [Fact] + public void EveryCommandHasShortAndLongHelp() + { + foreach (var command in CommandLine.Commands) + { + var brief = Help.Text(command); + var full = Help.Text(command, @long: true); + Assert.Contains($"tazel help {command} --long", brief, StringComparison.Ordinal); + Assert.True(full.Length > brief.Length, command); + } + + Assert.Contains("Exit status", Help.Text(null, @long: true), StringComparison.Ordinal); + Assert.DoesNotContain("Exit status", Help.Text(null), StringComparison.Ordinal); + } + + [Theory] + [InlineData(new[] { "help" }, null, false)] + [InlineData(new[] { "help", "--long" }, null, true)] + [InlineData(new[] { "help", "query" }, "query", false)] + [InlineData(new[] { "help", "query", "--long" }, "query", true)] + public void ReadsHelpAndLong(string[] arguments, string? topic, bool @long) + { + var help = Assert.IsType<HelpCommand>(CommandLine.Parse(arguments)); + Assert.Equal(topic, help.Topic); + Assert.Equal(@long, help.Long); + } +} + +public sealed class PortalCommandLineTests +{ + [Theory] + [InlineData(new[] { "portal-modules", "search", "json" }, "search", "json", false)] + [InlineData(new[] { "portal-modules", "search", "com.example:json", "-e" }, "search", "com.example:json", true)] + [InlineData(new[] { "portal-modules", "search", "com.example:json", "--exact" }, "search", "com.example:json", true)] + [InlineData(new[] { "portal-modules", "search", "--", "-json" }, "search", "-json", false)] + [InlineData(new[] { "portal-modules", "search", "-e", "--", "com.example:json" }, "search", "com.example:json", true)] + [InlineData(new[] { "portal-modules", "info", "json" }, "info", "json", false)] + [InlineData(new[] { "portal-modules", "info", "--exact", "--", "com.example:json" }, "info", "com.example:json", true)] + public void ReadsSearchAndInfo(string[] arguments, string action, string query, bool exact) + { + var command = Assert.IsType<PortalModulesCommand>(CommandLine.Parse(arguments)); + Assert.Equal(action == "search" ? PortalAction.Search : PortalAction.Info, command.Action); + Assert.Equal(query, command.Query); + Assert.Equal(exact, command.Exact); + } + + [Theory] + [InlineData(new[] { "portal-modules", "search", "json", "-e" }, "needs the group too: group:json")] + [InlineData(new[] { "portal-modules", "info", "-e", "--", "json" }, "needs the group too")] + [InlineData(new[] { "portal-modules", "serch", "json" }, "did you mean search?")] + [InlineData(new[] { "portal-modules", "info", "a:b:c" }, "is not module or group:module")] + [InlineData(new[] { "fetch", "x" }, "tazel fetch takes no 'x'")] + [InlineData(new[] { "build", "--exact" }, "--exact is not an option of tazel build")] + public void RefusesWhatIsWrong(string[] arguments, string message) + { + var error = Assert.Throws<CommandLineException>(() => CommandLine.Parse(arguments)); + Assert.Contains(message, error.Message, StringComparison.Ordinal); + } +} + +/// <summary>Tazel Portal Modules served from a directory by a server on this machine.</summary> +internal sealed class FakePortal : IDisposable +{ + private readonly HttpListener _listener = new(); + private readonly Dictionary<(string, string), List<Dictionary<string, object>>> _versions = []; + private readonly CancellationTokenSource _stop = new(); + private bool _disposed; + + public FakePortal(string directory) + { + Directory = directory; + var port = FreePort(); + Address = $"http://127.0.0.1:{port}"; + _listener.Prefixes.Add(Address + "/"); + _listener.Start(); + _ = Task.Run(ServeAsync); + } + + public string Directory { get; } + + public string Address { get; } + + /// <summary>Puts a module with these versions and dependencies on the portal, its archive with its .sha256sums.</summary> + public void Push(string group, string module, string version, string build, params (string Group, string Module, string Version)[] dependencies) + { + var source = Path.Combine(Directory, "sources", $"{module}-{version}"); + System.IO.Directory.CreateDirectory(source); + File.WriteAllText(Path.Combine(source, "MODULE.csx"), $$""" + using Progmasoft.Tazel.Dsl.Module.Prelude; + module = Module.Define(new() { Group = "{{group}}", Name = "{{module}}", Version = "{{version}}" }); + """); + File.WriteAllText(Path.Combine(source, "BUILD.csx"), build); + var name = ModuleArchive.BaseName(group, module, version); + var directory = Path.Combine(Directory, group, module, version); + var archive = Path.Combine(directory, name + ModuleArchive.Extension); + ModuleArchive.Write(source, name, archive, ["BUILD.csx", "MODULE.csx"]); + File.WriteAllText(archive + ".sha256sums", Sha256Sums.SumsLine(archive)); + if (!_versions.TryGetValue((group, module), out var versions)) + { + versions = []; + _versions[(group, module)] = versions; + } + + versions.Add(new Dictionary<string, object> + { + ["version"] = version, + ["pushed"] = "2026-11-20T10:00:00Z", + ["yanked"] = false, + ["dependencies"] = dependencies.Select(d => new Dictionary<string, object> + { + ["group"] = d.Group, ["module"] = d.Module, ["version"] = d.Version, ["test"] = false, + }).ToList(), + }); + File.WriteAllText(Path.Combine(Directory, group, module, "index.json"), System.Text.Json.JsonSerializer.Serialize( + new Dictionary<string, object> { ["group"] = group, ["module"] = module, ["versions"] = versions })); + } + + public void Catalog(params (string Group, string Module, string Latest, string Description)[] modules) => + File.WriteAllText(Path.Combine(Directory, "index.json"), + "{\"modules\":[" + string.Join(",", modules.Select(m => + $$"""{"group":"{{m.Group}}","module":"{{m.Module}}","latest":"{{m.Latest}}","description":"{{m.Description}}"}""")) + "]}"); + + public void Dispose() + { + // A test stops the portal on purpose before its using does. + if (_disposed) + { + return; + } + + _disposed = true; + _stop.Cancel(); + _listener.Close(); + _stop.Dispose(); + } + + private static int FreePort() + { + using var socket = new TcpListener(IPAddress.Loopback, 0); + socket.Start(); + return ((IPEndPoint)socket.LocalEndpoint).Port; + } + + private async Task ServeAsync() + { + while (!_stop.IsCancellationRequested) + { + HttpListenerContext context; + try + { + context = await _listener.GetContextAsync(); + } + catch (Exception error) when (error is HttpListenerException or ObjectDisposedException) + { + return; + } + + var file = Path.Combine(Directory, context.Request.Url!.AbsolutePath.TrimStart('/')); + if (File.Exists(file)) + { + var bytes = await File.ReadAllBytesAsync(file); + context.Response.StatusCode = 200; + await context.Response.OutputStream.WriteAsync(bytes); + } + else + { + context.Response.StatusCode = 404; + } + + context.Response.Close(); + } + } +} + +[Collection("environment")] +public sealed class PortalTests +{ + private const string Library = """ + using Progmasoft.Tazel.Dsl.Build.Prelude; + CC.StaticLibrary("lib", new() { Visibility = Visibility.Public }); + """; + + [Fact] + public async Task ResolvesFetchesAndVendorsModulesOfThePortal() + { + using var served = new TemporaryModule(); + using var portal = new FakePortal(served.Root); + portal.Push("com.example", "base", "1.0.0", Library); + portal.Push("com.example", "base", "1.2.0", Library); + portal.Push("com.example", "json", "2.0.0", Library, ("com.example", "base", "1.2.0")); + using var module = new TemporaryModule(); + module.Write("MODULE.csx", TemporaryModule.ModuleFile + """ + + dependencies = Dependencies.Define( + Module.From(new() { Group = "com.example", Name = "json", Version = "2.0.0" }), + Module.From(new() { Group = "com.example", Name = "base", Version = "1.0.0", Alias = "base" })); + """) + .Write("BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Prelude;\nCC.StaticLibrary(\"app\", new() { Depends = [\"@json//:lib\", \"@base//:lib\"] });"); + using var address = new EnvironmentVariable("TAZEL_PORTAL_MODULES_URL", portal.Address); + + var workspace = await module.LoadAsync(); + // The highest version anything asks for: json asks for base 1.2.0. + Assert.Equal(["com.example:base 1.2.0", "com.example:json 2.0.0"], + workspace.PortalModules.Select(m => $"{m.Key} {m.Version}")); + + var (status, output) = await module.TazelAsync(".", "vendor"); + Assert.True(status == 0, output); + Assert.True(File.Exists(Path.Combine(module.Root, "vendor", "com.example.json-2.0.0.tazel.tar.xz.sha256sums"))); + + // With vendor/ and no state, nothing is downloaded: the portal may be gone. + System.IO.Directory.Delete(Path.Combine(module.Root, ".tazel"), recursive: true); + portal.Dispose(); + (status, output) = await module.TazelAsync(".", "fetch"); + Assert.True(status == 0, output); + Assert.Contains("fetched 2 modules (2 of Tazel Portal Modules)", output, StringComparison.Ordinal); + } + + [Fact] + public async Task SearchesAndShowsModules() + { + using var served = new TemporaryModule(); + using var portal = new FakePortal(served.Root); + portal.Push("com.example", "json", "1.0.0", Library); + portal.Push("com.example", "json", "1.1.0", Library); + portal.Push("org.other", "json", "0.1.0", Library); + portal.Catalog(("com.example", "json", "1.1.0", "JSON for C"), ("org.other", "json", "0.1.0", "Another"), + ("com.example", "yaml", "0.2.0", "YAML")); + using var module = new TemporaryModule(); + using var address = new EnvironmentVariable("TAZEL_PORTAL_MODULES_URL", portal.Address); + + var (status, output) = await module.TazelAsync(".", "portal-modules", "search", "json"); + Assert.True(status == 0, output); + Assert.Contains("com.example:json", output, StringComparison.Ordinal); + Assert.Contains("org.other:json", output, StringComparison.Ordinal); + Assert.DoesNotContain("yaml", output, StringComparison.Ordinal); + + (status, output) = await module.TazelAsync(".", "portal-modules", "search", "com.example:json", "-e"); + Assert.True(status == 0, output); + Assert.DoesNotContain("org.other", output, StringComparison.Ordinal); + + (status, output) = await module.TazelAsync(".", "portal-modules", "info", "json"); + Assert.Equal(2, status); + Assert.Contains("json is a module of com.example, org.other; write the group", output, StringComparison.Ordinal); + + (status, output) = await module.TazelAsync(".", "portal-modules", "info", "com.example:json", "--exact"); + Assert.True(status == 0, output); + Assert.Contains("latest 1.1.0", output, StringComparison.Ordinal); + Assert.Contains("1.0.0", output, StringComparison.Ordinal); + } +} + +/// <summary>Sets an environment variable for one test and puts it back.</summary> +internal sealed class EnvironmentVariable : IDisposable +{ + private readonly string _name; + private readonly string? _old; + + public EnvironmentVariable(string name, string value) + { + _name = name; + _old = Environment.GetEnvironmentVariable(name); + Environment.SetEnvironmentVariable(name, value); + } + + public void Dispose() => Environment.SetEnvironmentVariable(_name, _old); +} + +[CollectionDefinition("environment", DisableParallelization = true)] +public sealed class EnvironmentCollection; + +public sealed class CoverageTests +{ + [Fact] + public async Task WritesTheCoverageOfTheTests() + { + Assert.SkipWhen(Host.Which("clang") is null || Host.Which("llvm-profdata") is null || Host.Which("llvm-cov") is null, + "clang, llvm-profdata and llvm-cov are not all on PATH"); + using var module = new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile + """ + + toolchains = Toolchains.Define("//toolchains:clang"); + """) + .Write("toolchains/BUILD.csx", $$""" + using Progmasoft.Tazel.Dsl.Build.Toolchain.Prelude; + CC.Toolchain("clang", new() + { + ExecutionPlatform = Platform.{{Host.Platform}}, + TargetPlatform = Platform.{{Host.Platform}}, + Tools = new() { CCompiler = "clang", CppCompiler = "clang++", Archiver = "{{(Host.Which("llvm-ar") is null ? "ar" : "llvm-ar")}}" }, + }); + """) + .Write("BUILD.csx", """ + using Progmasoft.Tazel.Dsl.Build.Prelude; + CC.Test("half_test", new() { Sources = ["half.c"] }); + """) + .Write("half.c", "int half(int x) { if (x < 0) { return -1; } return x / 2; }\nint main(void) { return half(4) == 2 ? 0 : 1; }\n"); + var (status, output) = await module.TazelAsync(".", "coverage", "//..."); + Assert.True(status == 0, output); + var lcov = await File.ReadAllTextAsync(Path.Combine(module.Root, ".tazel", "coverage", "coverage.lcov"), + TestContext.Current.CancellationToken); + Assert.Contains("SF:", lcov, StringComparison.Ordinal); + Assert.Contains("half.c", lcov, StringComparison.Ordinal); + Assert.True(System.IO.Directory.Exists(System.IO.Directory.GetDirectories(Path.Combine(module.Root, ".tazel", "out")) + .Single(d => d.EndsWith("-coverage", StringComparison.Ordinal)))); + } +}