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 Bazel-aligned query/cquery/aquery output formats without underscores
- Commit
7a5ca0a4b768185cacd34c09254b01b34d63634d- Author
- Leitwolf11 ·
- Parents
599b5c4f5583
Changes
CHANGELOG.md | 4 + src/Progmasoft.Tazel/Cli/CommandMakers.cs | 8 +- src/Progmasoft.Tazel/Cli/Help.cs | 8 +- src/Progmasoft.Tazel/Cli/MoreCommands.cs | 18 +- src/Progmasoft.Tazel/Cli/QueryOutput.cs | 203 +++++++++++++++++++++ .../Progmasoft.Tazel.Tests/QueryAndPortalTests.cs | 2 +- tests/Progmasoft.Tazel.Tests/QueryOutputTests.cs | 107 +++++++++++ 7 files changed, 329 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e1d7424..75d9c36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ## Unreleased +- `query`, `cquery`, and `aquery` now support `--output` types `label`, `labelkind`, `build`, `package`, `location`, + `graph`, `xml`, `proto`, `streamedproto`, `streamed-jsonproto`, `csx`/`C#`, `minrank`, and `maxrank` (no underscores; + `label_kind` suggests `labelkind`, `starlark` suggests `csx`). + - `tazel log cache|workspace|what-ran|what-failed|what-up|snoop|daemon|registries` adds read-only inspection commands for workspace root, cache sizes, recent runs, daemon status, and effective registries (never printing tokens). diff --git a/src/Progmasoft.Tazel/Cli/CommandMakers.cs b/src/Progmasoft.Tazel/Cli/CommandMakers.cs index 734453c..9652c99 100644 --- a/src/Progmasoft.Tazel/Cli/CommandMakers.cs +++ b/src/Progmasoft.Tazel/Cli/CommandMakers.cs @@ -100,10 +100,14 @@ internal static class CommandMakers } var format = scanned.Last("output") ?? "label"; - var allowed = new[] { "label", "label_kind" }; + var allowed = QueryOutput.AllowedFormats; if (!allowed.Contains(format, StringComparer.Ordinal)) { - var near = Suggestions.Nearest(format, allowed); + var near = format == "label_kind" ? "labelkind" + : format == "streamed_proto" ? "streamedproto" + : format == "streamed_jsonproto" ? "streamed-jsonproto" + : format == "starlark" ? "csx" + : Suggestions.Nearest(format, allowed); throw new CommandLineException( $"--output takes {string.Join(", ", allowed)}, not '{format}'" + (near is null ? "" : $"; did you mean --output {near}?")); diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 36c280d..7cdbac0 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -88,7 +88,7 @@ internal static class Help {BuildOptions} """), ["query"] = new("tazel query <expression>: answers about the targets and what they depend on.", """ - tazel query <expression> [--output label|label_kind] + tazel query <expression> [--output label|labelkind|build|package|location|graph|xml|proto|streamedproto|streamed-jsonproto|csx|C#|minrank|maxrank] Answers about the target graph from the project files alone. //dir:name, //dir/..., //... targets and target patterns @@ -101,11 +101,11 @@ internal static class Help Examples: tazel query 'deps(//app:greeter)' - tazel query 'rdeps(//..., //core:core)' --output label_kind - tazel query '//... - tests(//...)' + tazel query 'rdeps(//..., //core:core)' --output labelkind + tazel query '//... - tests(//...)' --output graph """), ["cquery"] = new("tazel cquery <expression>: query for the platform and mode of the command.", $""" - tazel cquery <expression> [--output label|label_kind] [options] + tazel cquery <expression> [--output label|labelkind|build|package|location|graph|xml|proto|streamedproto|streamed-jsonproto|csx|C#|minrank|maxrank] [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). diff --git a/src/Progmasoft.Tazel/Cli/MoreCommands.cs b/src/Progmasoft.Tazel/Cli/MoreCommands.cs index 07a91a6..48945c2 100644 --- a/src/Progmasoft.Tazel/Cli/MoreCommands.cs +++ b/src/Progmasoft.Tazel/Cli/MoreCommands.cs @@ -38,20 +38,12 @@ internal sealed partial class Commands 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()); - } - + QueryOutput.WriteTargets(reporter, targets, query.Format, configuration: null); 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); - } - + var matched = targets.Where(target => selector.Incompatibility(target) is null).ToList(); + QueryOutput.WriteTargets(reporter, matched, query.Format, configuration); return 0; default: var compatible = new Selector(workspace, platform); @@ -78,9 +70,7 @@ internal sealed partial class Commands 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"); + QueryOutput.WriteAction(reporter, action, target, configuration, query.Format); } } diff --git a/src/Progmasoft.Tazel/Cli/QueryOutput.cs b/src/Progmasoft.Tazel/Cli/QueryOutput.cs new file mode 100644 index 0000000..a04cbbc --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/QueryOutput.cs @@ -0,0 +1,203 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Xml.Linq; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>Formats the results of <c>tazel query</c>, <c>cquery</c>, and <c>aquery</c>.</summary> +internal static class QueryOutput +{ + /// <summary>Allowed <c>--output</c> format names (no underscores; kebab-case or lowercase, plus <c>C#</c>).</summary> + public static IReadOnlyList<string> AllowedFormats { get; } = + [ + "label", + "labelkind", + "build", + "package", + "location", + "graph", + "xml", + "proto", + "streamedproto", + "streamed-jsonproto", + "csx", + "C#", + "minrank", + "maxrank", + ]; + + private static readonly Dictionary<string, Action<Reporter, IReadOnlyList<ProjectTarget>, string?>> Formatters = + new(StringComparer.Ordinal) + { + ["label"] = (r, t, c) => WriteEach(r, t, x => FormatLabel(x, c)), + ["labelkind"] = (r, t, c) => WriteEach(r, t, x => $"{Query.KindOf(x)} {FormatLabel(x, c)}"), + ["package"] = (r, t, _) => WritePackages(r, t), + ["location"] = (r, t, c) => WriteEach(r, t, x => $"{x.Place}: {Query.KindOf(x)} {FormatLabel(x, c)}"), + ["graph"] = (r, t, _) => WriteGraph(r, t), + ["xml"] = WriteXml, + ["minrank"] = (r, t, _) => WriteRanks(r, t, max: false), + ["maxrank"] = (r, t, _) => WriteRanks(r, t, max: true), + ["proto"] = WriteJsonTargets, + ["streamedproto"] = WriteJsonTargets, + ["streamed-jsonproto"] = WriteJsonTargets, + ["csx"] = (r, t, _) => WriteCsxTargets(r, t), + ["C#"] = (r, t, _) => WriteCsxTargets(r, t), + ["build"] = (r, t, _) => WriteCsxTargets(r, t), + }; + + /// <summary>Writes formatted target results for <c>query</c> or <c>cquery</c>.</summary> + public static void WriteTargets( + Reporter reporter, IReadOnlyList<ProjectTarget> targets, string format, string? configuration) + { + if (!Formatters.TryGetValue(format, out var write)) + { + throw new CommandLineException($"unsupported query output format '{format}'"); + } + + write(reporter, targets, configuration); + } + + private static void WriteEach(Reporter reporter, IReadOnlyList<ProjectTarget> targets, Func<ProjectTarget, string> render) + { + foreach (var target in targets) + { + reporter.Plain(render(target)); + } + } + + private static void WritePackages(Reporter reporter, IReadOnlyList<ProjectTarget> targets) + { + foreach (var pkg in targets.Select(t => t.Label.Package.ToString()).Distinct(StringComparer.Ordinal)) + { + reporter.Plain(pkg); + } + } + + /// <summary>Writes one <c>aquery</c> action in the requested format.</summary> + public static void WriteAction( + Reporter reporter, BuildAction action, ProjectTarget target, string configuration, string format) + { + var command = action.Work is null + ? Reporter.Quote(action.Command) + : "(in Tazel) " + string.Join(' ', action.Command); + if (format is "streamed-jsonproto" or "proto" or "streamedproto") + { + var payload = new + { + description = action.Description, + target = target.Label.ToString(), + configuration, + command, + inputs = action.Inputs, + outputs = action.Outputs, + }; + reporter.Plain(JsonSerializer.Serialize(payload)); + return; + } + + reporter.Plain($"action '{action.Description}'\n Target: {target.Label} ({configuration})\n" + + $" Command: {command}\n" + + $" Inputs: [{string.Join(", ", action.Inputs)}]\n Outputs: [{string.Join(", ", action.Outputs)}]\n"); + } + + private static string FormatLabel(ProjectTarget target, string? configuration) => + configuration is null ? target.Label.ToString() : $"{target.Label} ({configuration})"; + + private static void WriteGraph(Reporter reporter, IReadOnlyList<ProjectTarget> targets) + { + var sb = new StringBuilder(); + sb.AppendLine("digraph mygraph {"); + sb.AppendLine(" node [shape=box];"); + var set = new HashSet<ProjectTarget>(targets); + foreach (var target in targets) + { + sb.Append(" \"").Append(target.Label).AppendLine("\";"); + foreach (var dep in target.Dependencies.Where(set.Contains)) + { + sb.Append(" \"").Append(target.Label).Append("\" -> \"").Append(dep.Label).AppendLine("\";"); + } + } + + sb.Append('}'); + reporter.Plain(sb.ToString()); + } + + private static void WriteXml(Reporter reporter, IReadOnlyList<ProjectTarget> targets, string? configuration) + { + var root = new XElement("query", new XAttribute("version", "2")); + foreach (var target in targets) + { + var rule = new XElement("rule", + new XAttribute("class", Query.KindOf(target)), + new XAttribute("location", target.Place), + new XAttribute("name", target.Label.ToString())); + if (configuration is not null) + { + rule.Add(new XAttribute("configuration", configuration)); + } + + root.Add(rule); + } + + reporter.Plain(new XDocument(root).ToString()); + } + + private static void WriteRanks(Reporter reporter, IReadOnlyList<ProjectTarget> targets, bool max) + { + var set = new HashSet<ProjectTarget>(targets); + var memo = new Dictionary<ProjectTarget, int>(); + foreach (var target in targets) + { + reporter.Plain($"{RankOf(target, set, memo, max)} {target.Label}"); + } + } + + private static int RankOf(ProjectTarget target, HashSet<ProjectTarget> set, Dictionary<ProjectTarget, int> memo, bool max) + { + if (memo.TryGetValue(target, out var cached)) + { + return cached; + } + + memo[target] = 0; + var deps = target.Dependencies.Where(set.Contains).Select(dep => RankOf(dep, set, memo, max) + 1).ToList(); + var rank = deps.Count == 0 ? 0 : (max ? deps.Max() : deps.Min()); + memo[target] = rank; + return rank; + } + + private static void WriteJsonTargets(Reporter reporter, IReadOnlyList<ProjectTarget> targets, string? configuration) + { + foreach (var target in targets) + { + var payload = new + { + kind = Query.KindOf(target), + label = target.Label.ToString(), + location = target.Place, + configuration, + dependencies = target.Dependencies.Select(d => d.Label.ToString()).ToArray(), + }; + reporter.Plain(JsonSerializer.Serialize(payload)); + } + } + + private static void WriteCsxTargets(Reporter reporter, IReadOnlyList<ProjectTarget> targets) + { + foreach (var target in targets) + { + var deps = string.Join(", ", target.Dependencies.Select(d => $"\"{d.Label}\"")); + reporter.Plain($"// {target.Place}"); + reporter.Plain($"{Query.KindOf(target)}(\"{target.Label.Name}\", new() {{ Depends = [{deps}] }});"); + } + } +} diff --git a/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs b/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs index 7bdb741..d9cd733 100644 --- a/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs +++ b/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs @@ -74,7 +74,7 @@ public sealed class QueryTests 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"); + (status, output) = await module.TazelAsync(".", "query", "//...", "--output", "labelkind", "--quiet"); Assert.True(status == 0, output); Assert.Contains("ObjectiveC.StaticLibrary //:mac", output, StringComparison.Ordinal); diff --git a/tests/Progmasoft.Tazel.Tests/QueryOutputTests.cs b/tests/Progmasoft.Tazel.Tests/QueryOutputTests.cs new file mode 100644 index 0000000..82975f7 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/QueryOutputTests.cs @@ -0,0 +1,107 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class QueryOutputTests +{ + [Theory] + [InlineData("label")] + [InlineData("labelkind")] + [InlineData("build")] + [InlineData("package")] + [InlineData("location")] + [InlineData("graph")] + [InlineData("xml")] + [InlineData("proto")] + [InlineData("streamedproto")] + [InlineData("streamed-jsonproto")] + [InlineData("csx")] + [InlineData("C#")] + [InlineData("minrank")] + [InlineData("maxrank")] + public void CommandLineAcceptsAllQueryOutputFormats(string format) + { + var cmd = Assert.IsType<QueryCommand>(CommandLine.Parse(["query", "//...", "--output", format])); + Assert.Equal(format, cmd.Format); + } + + [Theory] + [InlineData("label_kind", "labelkind")] + [InlineData("streamed_proto", "streamedproto")] + [InlineData("streamed_jsonproto", "streamed-jsonproto")] + [InlineData("starlark", "csx")] + public void CommandLineRejectsBazelUnderscoreOrStarlarkNamesWithHints(string written, string expectedHint) + { + var error = Assert.Throws<CommandLineException>(() => CommandLine.Parse(["query", "//...", "--output", written])); + Assert.Contains($"did you mean --output {expectedHint}?", error.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task QueryRendersAllNewOutputFormats() + { + var dir = Path.Combine(Path.GetTempPath(), "tazel-query-out-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + await File.WriteAllTextAsync(Path.Combine(dir, "MODULE.csx"), + "using Progmasoft.Tazel.Dsl.Module.Prelude;\nmodule = Module.Define(new() { Group = \"com.example\", Name = \"qdemo\", Version = \"0.1.0\", License = \"MIT\" });\n", + TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(Path.Combine(dir, "BUILD.csx"), """ + using Progmasoft.Tazel.Dsl.Build.Prelude; + CC.StaticLibrary("core", new() { Sources = ["core.c"] }); + CC.Executable("app", new() { Sources = ["main.c"], Depends = ["//:core"] }); + """, TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(Path.Combine(dir, "core.c"), "int x = 1;\n", TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(Path.Combine(dir, "main.c"), "int main(void) { return 0; }\n", TestContext.Current.CancellationToken); + + var graph = await RunAsync(["--color", "never", "query", "//...", "--output", "graph", "--quiet"], dir); + Assert.Contains("digraph mygraph", graph, StringComparison.Ordinal); + Assert.Contains("\"//:app\" -> \"//:core\"", graph, StringComparison.Ordinal); + + var xml = await RunAsync(["--color", "never", "query", "//...", "--output", "xml", "--quiet"], dir); + Assert.Contains("<query version=\"2\">", xml, StringComparison.Ordinal); + Assert.Contains("name=\"//:app\"", xml, StringComparison.Ordinal); + + var jsonl = await RunAsync(["--color", "never", "query", "//...", "--output", "streamed-jsonproto", "--quiet"], dir); + Assert.Contains("\"label\":\"//:app\"", jsonl, StringComparison.Ordinal); + + var csx = await RunAsync(["--color", "never", "query", "//...", "--output", "C#", "--quiet"], dir); + Assert.Contains("CC.Executable(\"app\"", csx, StringComparison.Ordinal); + + var pkg = await RunAsync(["--color", "never", "query", "//...", "--output", "package", "--quiet"], dir); + Assert.Contains("//", pkg, StringComparison.Ordinal); + + var loc = await RunAsync(["--color", "never", "query", "//...", "--output", "location", "--quiet"], dir); + Assert.Contains("BUILD.csx", loc, StringComparison.Ordinal); + + var minrank = await RunAsync(["--color", "never", "query", "//...", "--output", "minrank", "--quiet"], dir); + Assert.Contains("0 //:core", minrank, StringComparison.Ordinal); + Assert.Contains("1 //:app", minrank, StringComparison.Ordinal); + + var maxrank = await RunAsync(["--color", "never", "query", "//...", "--output", "maxrank", "--quiet"], dir); + Assert.Contains("1 //:app", maxrank, StringComparison.Ordinal); + + var aquery = await RunAsync(["--color", "never", "aquery", "//:app", "--output", "streamed-jsonproto", "--quiet"], dir); + Assert.Contains("\"target\":\"//:app\"", aquery, StringComparison.Ordinal); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + private static async Task<string> RunAsync(string[] args, string directory) + { + using var output = new StringWriter(); + var status = await Program.RunAsync(args, directory, output, TestContext.Current.CancellationToken); + Assert.Equal(0, status); + return output.ToString(); + } +}