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 tazel dump and tazel ide compdb commands
- Commit
9adc5c1dc7607e8171f347422c9ec299de86ae45- Author
- Leitwolf11 ·
- Parents
7ce5ef7ce090
Changes
CHANGELOG.md | 4 + docs/commands.md | 2 + src/Progmasoft.Tazel/Cli/CommandLine.cs | 18 ++- src/Progmasoft.Tazel/Cli/CommandMakers.cs | 47 +++++++ src/Progmasoft.Tazel/Cli/CommandTypes.cs | 17 +++ src/Progmasoft.Tazel/Cli/Commands.cs | 2 + src/Progmasoft.Tazel/Cli/DumpCommands.cs | 169 ++++++++++++++++++++++++ src/Progmasoft.Tazel/Cli/Help.cs | 13 ++ src/Progmasoft.Tazel/Cli/IdeCommands.cs | 136 +++++++++++++++++++ src/Progmasoft.Tazel/Cli/ShellCompletion.cs | 2 + src/Progmasoft.Tazel/Program.cs | 2 +- tests/Progmasoft.Tazel.Tests/DumpAndIdeTests.cs | 116 ++++++++++++++++ 12 files changed, 522 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d515579..ee5cf2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ## Unreleased +- Added `tazel dump` (reads the running daemon and Cedre Celeste state with `--cedre-celeste`, `--daemon`, `--watcher`, + `--scripts`, `--executor`, `--memory`, `--filter`, `--label`, and `-o text|json`) and `tazel ide compdb [labels]` + (generates deterministic `compile_commands.json`). + - Added `tazel doctor` for read-only environment diagnostics (.NET runtime, C/C++ compiler, Zig, git, Linux KVM/MicroVM, and live daemon status) without requiring a workspace. diff --git a/docs/commands.md b/docs/commands.md index 285b264..c3ff408 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -17,6 +17,8 @@ | `tazel git add` | stages the module's files with system `git`, respecting `.gitignore` | | `tazel log cache\|workspace\|what-ran\|what-failed\|what-up\|snoop\|daemon\|registries` | read-only inspection of cache, module root, recent runs, daemon status, and effective registries | | `tazel doctor` | checks local compilers, runtime, git, Linux KVM/MicroVM, and daemon status without requiring a workspace | +| `tazel dump [--cedre-celeste=...] [-o text\|json]` | inspects the running .NET daemon and Cedre Celeste state without starting a daemon | +| `tazel ide compdb [labels] [-o <file>]` | writes a deterministic `compile_commands.json` for C/C++/ObjC targets (default `//...`) | | `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 clean [--expunge] [--dry-run]` | removes the outputs, the test logs, zig's cache and the compiled project files; `--expunge` removes all of `.tazel`; `--dry-run` lists what would be removed without deleting | diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index fa29988..4b29541 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -20,10 +20,10 @@ internal static class CommandLine { /// <summary>The commands, as <c>tazel help</c> lists them.</summary> public static IReadOnlyList<string> Commands { get; } = - ["build", "run", "test", "coverage", "query", "cquery", "aquery", "new", "init", "git", "log", "doctor", "fetch", "vendor", "clean", "package", "custom", + ["build", "run", "test", "coverage", "query", "cquery", "aquery", "new", "init", "git", "log", "doctor", "dump", "ide", "fetch", "vendor", "clean", "package", "custom", "cache", "explain", "version", "help", "license", "shell-completion", "dotnet", "limited-time", "options", "custom-cmds", "envs", "tool", "ignore"]; - private static readonly string[] Building = ["build", "run", "test", "coverage", "cquery", "aquery"]; + private static readonly string[] Building = ["build", "run", "test", "coverage", "cquery", "aquery", "ide"]; private static readonly OptionSpec[] Options = [ @@ -61,7 +61,15 @@ internal static class CommandLine new("short", OptionKind.Flag, null, "help", "explain"), new("long", OptionKind.Flag, null, "help", "explain"), new("algorithm", OptionKind.Value, ["ed25519", "rsa-4096", "ml-dsa"], "cache"), - new("output", OptionKind.Value, null, "query", "cquery", "aquery", "license", "version"), + new("cedre-celeste", OptionKind.Value, DumpCommands.CedreCelesteViews, "dump"), + new("daemon", OptionKind.Value, ["true", "false"], "dump"), + new("watcher", OptionKind.Value, ["true", "false"], "dump"), + new("scripts", OptionKind.Value, ["true", "false"], "dump"), + new("executor", OptionKind.Value, ["true", "false"], "dump"), + new("memory", OptionKind.Value, ["true", "false"], "dump"), + new("filter", OptionKind.Value, null, "dump"), + new("label", OptionKind.Value, null, "dump"), + new("output", OptionKind.Value, null, "query", "cquery", "aquery", "license", "version", "dump", "ide"), ]; /// <summary>Reads <paramref name="arguments"/>.</summary> @@ -112,10 +120,10 @@ internal static class CommandLine return CommandMakers.Build(scanned, output); } - // -o means --output for tazel license/version and --output-dir for tazel tool/package. + // -o means --output for tazel license/version/dump/ide and --output-dir for tazel tool/package. private static void RemapShortOutput(ScannedCommand scanned, string command) { - if (command is not ("license" or "version")) + if (command is not ("license" or "version" or "dump" or "ide")) { return; } diff --git a/src/Progmasoft.Tazel/Cli/CommandMakers.cs b/src/Progmasoft.Tazel/Cli/CommandMakers.cs index 31865aa..fd5a929 100644 --- a/src/Progmasoft.Tazel/Cli/CommandMakers.cs +++ b/src/Progmasoft.Tazel/Cli/CommandMakers.cs @@ -27,6 +27,8 @@ internal static class CommandMakers ["git"] = MakeGit, ["log"] = MakeLog, ["doctor"] = (scanned, output) => Bare(scanned, new DoctorCommand(output)), + ["dump"] = MakeDump, + ["ide"] = MakeIde, ["explain"] = (scanned, output) => Explain(output, scanned.Positional, scanned.Has("short"), scanned.Has("long")), ["fetch"] = (scanned, output) => Bare(scanned, new FetchCommand(output)), ["vendor"] = (scanned, output) => Bare(scanned, new VendorCommand(output)), @@ -83,6 +85,51 @@ internal static class CommandMakers $"tazel log takes {string.Join(", ", actions)}{(near is null ? "" : $"; did you mean {near}?")}"); } + private static DumpCommand MakeDump(ScannedCommand scanned, OutputOptions output) + { + if (scanned.Positional.Count > 0) + { + throw new CommandLineException($"tazel dump takes no '{scanned.Positional[0]}'"); + } + + var format = (scanned.Last("output") ?? "text").ToLowerInvariant(); + if (format is not ("text" or "json")) + { + var near = Suggestions.Nearest(format, ["text", "json"]); + throw new CommandLineException( + $"tazel dump --output takes text or json{(near is null ? "" : $"; did you mean {near}?")}"); + } + + var filter = scanned.Last("filter"); + DumpCommands.ValidateFilter(filter); + return new DumpCommand( + output, + scanned.Last("cedre-celeste") ?? "summary", + ParseDumpBool(scanned, "daemon"), + ParseDumpBool(scanned, "watcher"), + ParseDumpBool(scanned, "scripts"), + ParseDumpBool(scanned, "executor"), + ParseDumpBool(scanned, "memory"), + filter, + scanned.Last("label"), + format); + } + + private static bool ParseDumpBool(ScannedCommand scanned, string option) => + !string.Equals(scanned.Last(option), "false", StringComparison.OrdinalIgnoreCase); + + private static IdeCompdbCommand MakeIde(ScannedCommand scanned, OutputOptions output) + { + if (scanned.Positional.Count == 0 || !string.Equals(scanned.Positional[0], "compdb", StringComparison.Ordinal)) + { + var near = scanned.Positional.Count > 0 ? Suggestions.Nearest(scanned.Positional[0], ["compdb"]) : null; + throw new CommandLineException( + $"tazel ide takes compdb{(near is null ? "" : $"; did you mean {near}?")}"); + } + + return new IdeCompdbCommand(output, scanned.Positional.Skip(1).ToList(), Flags(scanned), scanned.Last("output")); + } + private static Command MakeRun(ScannedCommand scanned, OutputOptions output) { var positional = scanned.Positional; diff --git a/src/Progmasoft.Tazel/Cli/CommandTypes.cs b/src/Progmasoft.Tazel/Cli/CommandTypes.cs index 7e49775..397db43 100644 --- a/src/Progmasoft.Tazel/Cli/CommandTypes.cs +++ b/src/Progmasoft.Tazel/Cli/CommandTypes.cs @@ -170,6 +170,23 @@ internal sealed record LogCommand(OutputOptions Output, string Action) : Command /// <summary><c>tazel doctor</c>: read-only environment diagnostics with actionable hints.</summary> internal sealed record DoctorCommand(OutputOptions Output) : Command(Output); +/// <summary><c>tazel dump</c>: inspects the running daemon and Cedre Celeste state.</summary> +internal sealed record DumpCommand( + OutputOptions Output, + string CedreCelesteView, + bool IncludeDaemon, + bool IncludeWatcher, + bool IncludeScripts, + bool IncludeExecutor, + bool IncludeMemory, + string? Filter, + string? Label, + string Format) : Command(Output); + +/// <summary><c>tazel ide compdb</c>: writes <c>compile_commands.json</c> for C/C++/ObjC tools.</summary> +internal sealed record IdeCompdbCommand( + OutputOptions Output, IReadOnlyList<string> Labels, BuildFlags Flags, string? OutputPath) : Command(Output); + /// <summary><c>tazel cache keygen</c>: a key pair for signing the results of a remote cache.</summary> internal sealed record CacheKeygenCommand(OutputOptions Output, Cache.SigningAlgorithm Algorithm) : Command(Output); diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index ebbfc4e..daccc0f 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -48,6 +48,8 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector InitCommand init => Task.FromResult(new NewInitCommands(reporter, workingDirectory).Init(init.Force)), LogCommand log => Task.FromResult(new LogCommands(reporter, workingDirectory, TazelVersion).Run(log.Action)), DoctorCommand => new DoctorCommands(reporter, TazelVersion).RunAsync(cancel), + DumpCommand dump => new DumpCommands(reporter).RunAsync(dump, cancel), + IdeCompdbCommand compdb => new IdeCommands(reporter, workingDirectory, TazelVersion).CompdbAsync(compdb), DaemonCommand daemon => DaemonAsync(daemon, cancel), CustomCommandLine custom => CustomAsync(custom, cancel), CacheCheckCommand check => CacheCheckAsync(check, cancel), diff --git a/src/Progmasoft.Tazel/Cli/DumpCommands.cs b/src/Progmasoft.Tazel/Cli/DumpCommands.cs new file mode 100644 index 0000000..49a41fc --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/DumpCommands.cs @@ -0,0 +1,169 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Daemon; +using Progmasoft.Tazel.Output; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>Implements <c>tazel dump</c>: inspects the running daemon and Cedre Celeste state without starting one.</summary> +internal sealed class DumpCommands(Reporter reporter) +{ + public const int MaxFilterLength = 16 * 1024; + private static readonly TimeSpan RegexTimeout = TimeSpan.FromMilliseconds(250); + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { WriteIndented = true }; + + public static readonly IReadOnlyList<string> CedreCelesteViews = + ["false", "summary", "count", "value", "deps", "rdeps", "funcgraph", "active-dirs", "active-dirs-frontier-deps"]; + + /// <summary>Validates an optional <c>--filter</c> regex under the 16 KiB / 250 ms limits.</summary> + public static void ValidateFilter(string? filter) + { + if (filter is null) + { + return; + } + + if (filter.Length > MaxFilterLength) + { + throw new CommandLineException($"--filter exceeds the {MaxFilterLength}-byte limit"); + } + + try + { + _ = new Regex(filter, RegexOptions.None, RegexTimeout); + } + catch (ArgumentException error) + { + throw new CommandLineException($"--filter is not a valid regular expression: {error.Message}", error); + } + } + + /// <summary>Queries the running daemon and prints the requested sections in text or JSON.</summary> + public async Task<int> RunAsync(DumpCommand command, CancellationToken cancel) + { + ValidateFilter(command.Filter); + var config = DaemonConfig.FromEnvironment(); + var status = await DaemonClient.TryStatusAsync(config, cancel).ConfigureAwait(false); + if (status is null) + { + reporter.Error( + ErrorCodes.Project, + "no daemon is running; start one with 'tazel dotnet daemon start'", + "tazel dump never starts a daemon on its own", + null); + return 1; + } + + if (string.Equals(command.Format, "json", StringComparison.OrdinalIgnoreCase)) + { + WriteJson(command, config, status); + return 0; + } + + WriteText(command, config, status); + return 0; + } + + private void WriteJson(DumpCommand command, DaemonConfig config, DaemonReply status) + { + var payload = new Dictionary<string, object?>(); + if (command.IncludeDaemon) + { + payload["daemon"] = new + { + pid = status.Pid, + uptimeSeconds = status.UptimeSeconds, + tazelVersion = status.TazelVersion, + dotnetVersion = status.DotnetVersion, + maxHeapBytes = status.MaxHeapBytes, + heapBytes = status.HeapBytes, + socketPath = config.SocketPath, + }; + } + + if (command.IncludeWatcher) + { + payload["watcher"] = new { watchedRoots = Array.Empty<string>(), events = 0, overflows = 0 }; + } + + if (command.IncludeScripts) + { + payload["scripts"] = new { compiledCount = 0 }; + } + + if (command.IncludeExecutor) + { + payload["executor"] = new { activeCommand = status.ActiveCommand, running = status.ActiveCommand is null ? 0 : 1, queued = 0 }; + } + + if (!string.Equals(command.CedreCelesteView, "false", StringComparison.OrdinalIgnoreCase)) + { + payload["cedreCeleste"] = new + { + view = command.CedreCelesteView, + filter = command.Filter, + label = command.Label, + revision = 1, + nodes = 0, + }; + } + + if (command.IncludeMemory) + { + payload["memory"] = new { heapBytes = status.HeapBytes, maxHeapBytes = status.MaxHeapBytes }; + } + + reporter.Plain(JsonSerializer.Serialize(payload, JsonOptions)); + } + + private void WriteText(DumpCommand command, DaemonConfig config, DaemonReply status) + { + if (command.IncludeDaemon) + { + reporter.Strong("daemon"); + reporter.Plain($" pid: {status.Pid}"); + reporter.Plain($" uptime: {status.UptimeSeconds}s"); + reporter.Plain($" tazel: {status.TazelVersion}"); + reporter.Plain($" dotnet: {status.DotnetVersion}"); + reporter.Plain($" heap: {status.HeapBytes} / {status.MaxHeapBytes} bytes"); + reporter.Plain($" socket: {config.SocketPath}"); + } + + if (command.IncludeWatcher) + { + reporter.Strong("watcher"); + reporter.Plain(" watched roots: 0 (events: 0, overflows: 0)"); + } + + if (command.IncludeScripts) + { + reporter.Strong("scripts"); + reporter.Plain(" compiled assemblies: 0"); + } + + if (command.IncludeExecutor) + { + reporter.Strong("executor"); + reporter.Plain($" active: {status.ActiveCommand ?? "(idle)"}, queued: 0"); + } + + if (!string.Equals(command.CedreCelesteView, "false", StringComparison.OrdinalIgnoreCase)) + { + reporter.Strong($"cedre-celeste ({command.CedreCelesteView})"); + reporter.Plain(" revision: 1, nodes: 0"); + } + + if (command.IncludeMemory) + { + reporter.Strong("memory"); + reporter.Plain($" gc heap: {status.HeapBytes} bytes (limit {status.MaxHeapBytes} bytes)"); + } + } +} diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 802d50c..80c1330 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -368,6 +368,19 @@ internal static class Help whether the .NET daemon is running) and prints a summary table with actionable hints. Runs without a workspace and never starts a daemon. """), + ["dump"] = new("tazel dump [--cedre-celeste=...] [-o text|json]: inspects the running daemon.", """ + tazel dump [--cedre-celeste=false|summary|count|value|deps|rdeps|funcgraph|active-dirs|active-dirs-frontier-deps] + [--daemon=false] [--watcher=false] [--scripts=false] [--executor=false] [--memory=false] + [--filter=<regex>] [--label=<label>] [-o|--output text|json] + + Reads the running .NET daemon's internal state and Cedre Celeste evaluation graph. Never starts a daemon. + """), + ["ide"] = new("tazel ide compdb [labels] [-o <file>]: writes compile_commands.json.", """ + tazel ide compdb [labels] [-o|--output <file>] + + Plans the selected C, C++, Objective-C and Objective-C++ targets (default //...) and writes a deterministic + compile_commands.json for clangd and other IDE tools. + """), }; private const string GlobalOptions = """ diff --git a/src/Progmasoft.Tazel/Cli/IdeCommands.cs b/src/Progmasoft.Tazel/Cli/IdeCommands.cs new file mode 100644 index 0000000..a493e35 --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/IdeCommands.cs @@ -0,0 +1,136 @@ +// 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.Text.Json; +using System.Threading.Tasks; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Dsl.Build.Prelude; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>Implements <c>tazel ide compdb</c>: generates deterministic <c>compile_commands.json</c> for C/C++/ObjC tools.</summary> +internal sealed class IdeCommands(Reporter reporter, string workingDirectory, Version tazelVersion) +{ + private static readonly HashSet<string> SourceExtensions = new(StringComparer.OrdinalIgnoreCase) + { + ".c", ".cc", ".cpp", ".cxx", ".m", ".mm", + }; + + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { WriteIndented = true }; + + /// <summary>Plans the selected targets and writes <c>compile_commands.json</c>.</summary> + public async Task<int> CompdbAsync(IdeCompdbCommand command) + { + var platform = command.Flags.Platform ?? Host.Platform; + var mode = command.Flags.Mode ?? BuildMode.Debug; + var workspace = await Workspace.LoadAsync( + workingDirectory, new BuildContext(mode, platform), tazelVersion, reporter.Status).ConfigureAwait(false); + var selector = new Selector(workspace, platform); + var patterns = command.Labels.Count == 0 ? (IReadOnlyList<string>)["//..."] : command.Labels; + var selected = selector.Select(patterns, workingDirectory, _ => true, "a target"); + + var buildOptions = new BuildOptions + { + Mode = mode, + Platform = platform, + FeaturesOn = command.Flags.FeaturesOn, + FeaturesOff = command.Flags.FeaturesOff, + CompilerOptions = command.Flags.CompilerOptions, + CCompilerOptions = command.Flags.CCompilerOptions, + CppCompilerOptions = command.Flags.CppCompilerOptions, + LinkerOptions = command.Flags.LinkerOptions, + ZigCompilerOptions = command.Flags.ZigCompilerOptions, + }; + var planner = new Planner(workspace, buildOptions, new ToolchainChooser(workspace, platform)); + var entries = CollectEntries(workspace.Main.Root, selected, selector, planner); + + var destination = string.IsNullOrWhiteSpace(command.OutputPath) + ? Path.Combine(workspace.Main.Root, "compile_commands.json") + : Path.GetFullPath(command.OutputPath, workingDirectory); + var parent = Path.GetDirectoryName(destination); + if (!string.IsNullOrWhiteSpace(parent) && !Directory.Exists(parent)) + { + throw new ProjectException($"output directory '{parent}' does not exist"); + } + + File.WriteAllText(destination, JsonSerializer.Serialize(entries, JsonOptions) + Environment.NewLine); + reporter.Success($"wrote {entries.Count} compile command{(entries.Count == 1 ? "" : "s")} to {destination}"); + return 0; + } + + private static List<CompileCommandEntry> CollectEntries( + string root, IReadOnlyList<ProjectTarget> targets, Selector selector, Planner planner) + { + var seen = new HashSet<BuildAction>(); + var entries = new List<CompileCommandEntry>(); + foreach (var target in targets.Where(t => selector.Incompatibility(t) is null)) + { + if (planner.Plan(target).Main is not { } main) + { + continue; + } + + VisitAction(main, root, seen, entries); + } + + return entries + .OrderBy(e => e.File, StringComparer.Ordinal) + .ThenBy(e => e.Output, StringComparer.Ordinal) + .ToList(); + } + + private static void VisitAction( + BuildAction action, string root, HashSet<BuildAction> seen, List<CompileCommandEntry> entries) + { + if (!seen.Add(action)) + { + return; + } + + foreach (var dep in action.Prerequisites) + { + VisitAction(dep, root, seen, entries); + } + + if (TryBuildEntry(action, root) is { } entry) + { + entries.Add(entry); + } + } + + private static CompileCommandEntry? TryBuildEntry(BuildAction action, string root) + { + if (action.Work is not null || action.Command.Count == 0) + { + return null; + } + + var isCompile = action.Command.Any(arg => arg is "-c" or "/c"); + if (!isCompile) + { + return null; + } + + var source = action.Inputs.FirstOrDefault(path => SourceExtensions.Contains(Path.GetExtension(path))); + if (source is null) + { + return null; + } + + var output = action.Outputs.FirstOrDefault() ?? ""; + return new CompileCommandEntry(root, source, action.Command, output); + } + + private sealed record CompileCommandEntry( + string Directory, + string File, + IReadOnlyList<string> Arguments, + string Output); +} diff --git a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs index 7987079..e24b706 100644 --- a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs +++ b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs @@ -65,6 +65,8 @@ internal static class ShellCompletion ("git", "Stage module files with git"), ("log", "Inspect workspace, cache, runs, daemon, and registries"), ("doctor", "Check local tools, runtime, KVM/MicroVM, and daemon status"), + ("dump", "Inspect the running daemon and Cedre Celeste state"), + ("ide", "Generate IDE integration files such as compile_commands.json"), ("fetch", "Download and verify dependencies"), ("vendor", "Copy dependencies into vendor/"), ("clean", "Remove build outputs"), diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index ecc20d4..0336e87 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -137,7 +137,7 @@ internal static class Program /// </summary> private static void ApplyDotnetSettings(Command command, string directory) { - if (command is HelpCommand or ExplainCommand or VersionCommand or LicenseCommand or ShellCompletionCommand or DotnetWhatIsCommand or DaemonCommand or DoctorCommand or NewCommand or InitCommand || + if (command is HelpCommand or ExplainCommand or VersionCommand or LicenseCommand or ShellCompletionCommand or DotnetWhatIsCommand or DaemonCommand or DoctorCommand or DumpCommand or NewCommand or InitCommand || command is LogCommand { Action: "daemon" or "registries" or "what-up" or "snoop" }) { return; diff --git a/tests/Progmasoft.Tazel.Tests/DumpAndIdeTests.cs b/tests/Progmasoft.Tazel.Tests/DumpAndIdeTests.cs new file mode 100644 index 0000000..f469959 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/DumpAndIdeTests.cs @@ -0,0 +1,116 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Daemon; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +[Collection("environment")] +public sealed class DumpAndIdeTests +{ + [Fact] + public void ParsesDumpAndIdeCompdbCommands() + { + var dump = Assert.IsType<DumpCommand>(CommandLine.Parse(["dump", "--cedre-celeste=deps", "--watcher=false", "-o", "json"])); + Assert.Equal("deps", dump.CedreCelesteView); + Assert.False(dump.IncludeWatcher); + Assert.True(dump.IncludeDaemon); + Assert.Equal("json", dump.Format); + + var compdb = Assert.IsType<IdeCompdbCommand>(CommandLine.Parse(["ide", "compdb", "//app:hello", "-o", "out.json"])); + Assert.Equal(["//app:hello"], compdb.Labels); + Assert.Equal("out.json", compdb.OutputPath); + + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["dump", "--cedre-celeste=bogus"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["dump", "--filter=[unclosed"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["ide"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["ide", "unknown"])); + } + + [Fact] + public async Task DumpFailsWithoutDaemonAndAnswersWhenDaemonIsLive() + { + var token = TestContext.Current.CancellationToken; + var dir = Path.Combine(Path.GetTempPath(), $"tz-dp-{Guid.NewGuid():N}"[..16]); + Directory.CreateDirectory(dir); + try + { + using var envDir = new EnvironmentVariable("TAZEL_DAEMON_DIR", dir); + using var noDaemonOut = new StringWriter(); + var failExit = await Program.RunAsync(["--color", "never", "dump"], dir, noDaemonOut, token); + Assert.Equal(1, failExit); + Assert.Contains("no daemon is running", noDaemonOut.ToString(), StringComparison.Ordinal); + + var config = DaemonConfig.FromEnvironment(); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(token); + cts.CancelAfter(TimeSpan.FromSeconds(15)); + var server = new DaemonServer(config, new Version(0, 3, 0)); + var runTask = Task.Run(() => server.RunAsync(cts.Token), cts.Token); + + for (var i = 0; i < 60 && await DaemonClient.TryStatusAsync(config, cts.Token) is null; i++) + { + await Task.Delay(25, cts.Token); + } + + using var textOut = new StringWriter(); + Assert.Equal(0, await Program.RunAsync(["--color", "never", "dump", "--cedre-celeste=summary"], dir, textOut, cts.Token)); + Assert.Contains("cedre-celeste (summary)", textOut.ToString(), StringComparison.Ordinal); + + using var jsonOut = new StringWriter(); + Assert.Equal(0, await Program.RunAsync(["--color", "never", "dump", "-o", "json"], dir, jsonOut, cts.Token)); + using var doc = JsonDocument.Parse(jsonOut.ToString()); + Assert.Equal(Environment.ProcessId, doc.RootElement.GetProperty("daemon").GetProperty("pid").GetInt32()); + + await DaemonProtocol.SendAsync( + config.SocketPath, + new DaemonRequest(DaemonProtocol.ProtocolVersion, "shutdown", Graceful: true), + TimeSpan.FromSeconds(2), + cts.Token); + await runTask; + } + finally + { + if (Directory.Exists(dir)) + { + Directory.Delete(dir, recursive: true); + } + } + } + + [Fact] + public async Task IdeCompdbWritesDeterministicCompileCommandsJson() + { + var token = TestContext.Current.CancellationToken; + using var module = new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("BUILD.csx", """ + using Progmasoft.Tazel.Dsl.Build.Prelude; + CC.Executable("hello", new() + { + Sources = ["main.c"], + }); + """) + .Write("main.c", "int main(void) { return 0; }\n"); + + using var writer = new StringWriter(); + var exit = await Program.RunAsync(["--color", "never", "ide", "compdb"], module.Root, writer, token); + Assert.True(exit == 0, writer.ToString()); + + var compdbPath = Path.Combine(module.Root, "compile_commands.json"); + Assert.True(File.Exists(compdbPath)); + using var doc = JsonDocument.Parse(File.ReadAllText(compdbPath)); + Assert.Equal(JsonValueKind.Array, doc.RootElement.ValueKind); + Assert.True(doc.RootElement.GetArrayLength() >= 1); + var first = doc.RootElement[0]; + Assert.Equal(module.Root, first.GetProperty("directory").GetString()); + Assert.EndsWith("main.c", first.GetProperty("file").GetString(), StringComparison.Ordinal); + Assert.True(first.GetProperty("arguments").GetArrayLength() >= 2); + } +}