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 version -V/-o json, clean --dry-run, and package --list/--allow-dirty/--output-dir
- Commit
3cec2b7f63dafef7e038c2bcfa05e6d02d8bc07d- Author
- Leitwolf11 ·
- Parents
be3e040ab909
Changes
CHANGELOG.md | 4 + docs/commands.md | 6 +- src/Progmasoft.Tazel/Cli/CommandLine.cs | 51 ++++++++--- src/Progmasoft.Tazel/Cli/Commands.cs | 98 ++++++++++++++++++--- src/Progmasoft.Tazel/Cli/Help.cs | 6 +- tests/Progmasoft.Tazel.Tests/CliFlagsTests.cs | 122 ++++++++++++++++++++++++++ 6 files changed, 261 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7de3e6..c69b3b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ## Unreleased +- `tazel version` now supports `-V`/`--verbose` and `-o`/`--output text|json`. +- `tazel clean` now supports `--dry-run` (lists directories and byte sizes without deleting). +- `tazel package` now supports `--list`, `--allow-dirty`, and `-o`/`--output-dir <dir>`. + - `tazel explain <code>` now supports `--short` (brief one-line summary) alongside the medium default and `--long` (full). - `tazel shell-completion bash|zsh|fish|powershell` emits shell completion scripts to standard output without requiring a module (PowerShell requires 5.1 or later; e.g. `source <(tazel shell-completion zsh)`), with built-in Oh My Zsh diff --git a/docs/commands.md b/docs/commands.md index 43efa66..fccc8a1 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -15,13 +15,13 @@ | `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, zig's cache and the compiled project files; `--expunge` removes all of `.tazel` | +| `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 | | `tazel cache keygen [--algorithm ed25519\|rsa-4096\|ml-dsa]` | prints a key pair for signing the results of a remote cache ([Remote cache](remote-cache.md)) | | `tazel cache validate [--remote]` | checks the records of `.tazel`, and with `--remote` the remote cache and its keys; changes nothing | | `tazel cache repair [--remote]` | removes broken records; with `--remote`, stores again what the remote cache lacks | -| `tazel package` | writes `.tazel/package/$group.$module-$version.tazel.tar.xz` and its `.sha256sums` | +| `tazel package [--list] [--allow-dirty] [--output-dir <dir>]` | writes `.tazel/package/$group.$module-$version.tazel.tar.xz` and its `.sha256sums` (`--list` previews files and sizes without writing) | | `tazel custom <name> [arguments]` | runs a command of the `tazel_custom.txt` of the current directory | -| `tazel version`, `tazel help [command] [--short\|--long]` | print the version, or what Tazel or one command does (medium by default, `--short` brief, `--long` full) | +| `tazel version [-V\|--verbose] [-o\|--output text\|json]`, `tazel help [command] [--short\|--long]` | print the version (optionally verbose or JSON), or what Tazel or one command does (medium by default, `--short` brief, `--long` full) | | `tazel explain <code> [--short\|--long]` | explains an error code (`--short` one-line summary, medium by default, `--long` full with examples and related codes) | | `tazel license [--output\|-o text\|md\|markdown\|rst]` | prints Tazel's MIT license, the Progmasoft Patent Grant 1.1, and the licenses of shipped libraries to stdout | | `tazel shell-completion bash\|zsh\|fish\|powershell` | prints a shell completion script to stdout (PowerShell requires 5.1 or later; e.g. `source <(tazel shell-completion zsh)`) | diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index a9f83bd..4cfcddf 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -81,13 +81,13 @@ internal sealed record TestCommand(OutputOptions Output, IReadOnlyList<string> L internal sealed record RunCommand(OutputOptions Output, string? Label, BuildFlags Flags, IReadOnlyList<string> Arguments) : Command(Output); -internal sealed record CleanCommand(OutputOptions Output, bool Expunge) : Command(Output); +internal sealed record CleanCommand(OutputOptions Output, bool Expunge, bool DryRun) : Command(Output); -internal sealed record PackageCommand(OutputOptions Output) : Command(Output); +internal sealed record PackageCommand(OutputOptions Output, bool List, bool AllowDirty, string? OutputDir) : Command(Output); internal sealed record CustomCommandLine(OutputOptions Output, IReadOnlyList<string> Words) : Command(Output); -internal sealed record VersionCommand(OutputOptions Output) : Command(Output); +internal sealed record VersionCommand(OutputOptions Output, bool Verbose, bool Json) : Command(Output); /// <summary>How much <c>tazel help</c> prints: <c>--short</c>, medium (default), or <c>--long</c>.</summary> internal enum HelpLength @@ -198,8 +198,12 @@ internal static class CommandLine new("project", Kind.Flag, null, "options", "custom-cmds", "envs"), new("local", Kind.Flag, null, "options", "custom-cmds", "envs"), new("create", Kind.Flag, null, "options"), - new("output-dir", Kind.Value, null, "tool"), + new("output-dir", Kind.Value, null, "tool", "package"), new("remote", Kind.Flag, null, "cache"), + new("dry-run", Kind.Flag, null, "clean"), + new("list", Kind.Flag, null, "package"), + new("allow-dirty", Kind.Flag, null, "package"), + new("verbose", Kind.Flag, null, "version"), new("message-format", Kind.Value, ["rich-stdio", "script-friendly-stdio", "jsonl", "xml"]), new("help", Kind.Flag, null), new("platform", Kind.Value, Platforms.Names, Building), @@ -220,7 +224,7 @@ internal static class CommandLine new("long", Kind.Flag, null, "help", "explain"), new("exact", Kind.Flag, null, "portal-modules"), new("algorithm", Kind.Value, ["ed25519", "rsa-4096", "ml-dsa"], "cache"), - new("output", Kind.Value, null, "query", "cquery", "aquery", "license"), + new("output", Kind.Value, null, "query", "cquery", "aquery", "license", "version"), ]; /// <summary>Reads <paramref name="arguments"/>.</summary> @@ -249,8 +253,8 @@ internal static class CommandLine private static Command Make(Scanned scanned) { var command = scanned.Command; - // -o means --output for tazel license and --output-dir for tazel tool. - if (command == "license") + // -o means --output for tazel license/version and --output-dir for tazel tool/package. + if (command is "license" or "version") { var outputOption = Options.First(o => o.Long == "output"); for (var i = 0; i < scanned.Seen.Count; i++) @@ -368,12 +372,12 @@ internal static class CommandLine ["fetch"] = (scanned, output) => Bare(scanned, new FetchCommand(output)), ["vendor"] = (scanned, output) => Bare(scanned, new VendorCommand(output)), ["portal-modules"] = (scanned, output) => PortalModules(output, scanned.Positional, scanned.Has("exact")), - ["clean"] = (scanned, output) => Bare(scanned, new CleanCommand(output, scanned.Has("expunge"))), - ["package"] = (scanned, output) => Bare(scanned, new PackageCommand(output)), + ["clean"] = (scanned, output) => Bare(scanned, new CleanCommand(output, scanned.Has("expunge"), scanned.Has("dry-run"))), + ["package"] = (scanned, output) => Bare(scanned, new PackageCommand(output, scanned.Has("list"), scanned.Has("allow-dirty"), Last(scanned.Seen, "output-dir"))), ["custom"] = (scanned, output) => scanned.Positional.Count == 0 ? throw new CommandLineException("tazel custom needs the name of a command of tazel_custom.txt") : new CustomCommandLine(output, scanned.Positional), - ["version"] = (scanned, output) => Bare(scanned, new VersionCommand(output)), + ["version"] = MakeVersion, ["license"] = MakeLicense, ["shell-completion"] = MakeShellCompletion, // The one word after it is case-sensitive: C#, as the language is written. @@ -424,6 +428,27 @@ internal static class CommandLine return new QueryCommand(output, kind, string.Join(' ', scanned.Positional), Flags(scanned.Seen), format); } + private static Command MakeVersion(Scanned scanned, OutputOptions output) + { + NoPositional(scanned.Command, scanned.Positional); + var raw = Last(scanned.Seen, "output"); + if (raw is null || raw == "text") + { + return new VersionCommand(output, scanned.Has("verbose"), false); + } + + if (raw == "json") + { + return new VersionCommand(output, scanned.Has("verbose"), true); + } + + var allowed = new[] { "text", "json" }; + var near = Suggestions.Nearest(raw, allowed); + throw new CommandLineException( + $"--output takes {string.Join(", ", allowed)}, not '{raw}'" + + (near is null ? "" : $"; did you mean --output {near}?")); + } + private static Command MakeLicense(Scanned scanned, OutputOptions output) { NoPositional(scanned.Command, scanned.Positional); @@ -704,6 +729,12 @@ internal static class CommandLine return; } + if (argument == "-V") + { + seen.Add((Options.First(o => o.Long == "verbose"), [], "-V")); + return; + } + throw new CommandLineException($"{argument} is not an option; tazel help lists them"); } diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 156ada4..8438922 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -5,6 +5,8 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Progmasoft.Tazel.Archive; @@ -41,7 +43,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector FetchCommand => FetchAsync(), VendorCommand => VendorAsync(cancel), PortalModulesCommand portal => PortalModulesAsync(portal, cancel), - PackageCommand => PackageAsync(), + PackageCommand package => PackageAsync(package), CustomCommandLine custom => CustomAsync(custom, cancel), CacheCheckCommand check => CacheCheckAsync(check, cancel), ToolLaunchCommand tool => Task.FromResult(LaunchTool(tool)), @@ -58,9 +60,8 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector { switch (command) { - case VersionCommand: - reporter.Plain($"tazel {TazelVersion.ToString(3)} (.NET {Environment.Version}, {Host.Platform.Name()})"); - return 0; + case VersionCommand version: + return PrintVersion(version); case HelpCommand help: reporter.Plain(Help.Text(help.Topic, help.Length)); return 0; @@ -85,7 +86,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector case DotnetWhatIsCommand whatIs: return WhatIs(whatIs.Term); case CleanCommand clean: - return Clean(clean.Expunge); + return Clean(clean.Expunge, clean.DryRun); case CacheKeygenCommand keygen: { var (publicKey, signingKey) = Cache.CacheKey.Generate(keygen.Algorithm); @@ -242,14 +243,64 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector return 0; } - private int Clean(bool expunge) + private int PrintVersion(VersionCommand version) + { + var ver = TazelVersion.ToString(3); + var dotnet = Environment.Version.ToString(); + var platform = Host.Platform.Name(); + var info = typeof(Commands).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion; + var plus = info?.IndexOf('+', StringComparison.Ordinal) ?? -1; + var commit = plus >= 0 && plus + 1 < info!.Length ? info[(plus + 1)..] : "unknown"; + const string releaseKind = "Rolling"; + + if (version.Json) + { + var payload = version.Verbose + ? (object)new { version = ver, commit, dotnet, platform, releaseKind } + : new { version = ver, dotnet, platform }; + reporter.Plain(JsonSerializer.Serialize(payload)); + return 0; + } + + if (!version.Verbose) + { + reporter.Plain($"tazel {ver} (.NET {dotnet}, {platform})"); + return 0; + } + + reporter.Plain($"tazel {ver}"); + reporter.Plain($"commit: {commit}"); + reporter.Plain($"dotnet: .NET {dotnet}"); + reporter.Plain($"platform: {platform}"); + reporter.Plain($"release-kind: {releaseKind}"); + return 0; + } + + private int Clean(bool expunge, bool dryRun) { var root = ModuleFiles.FindRoot(workingDirectory); var state = Path.Combine(root, ModuleFiles.StateDirectory); - var removed = expunge + var targets = expunge ? [state] : new[] { "out", "testlogs", "coverage", "zig-cache", "package", "downloads", Project.ScriptCache.Directory }.Select(name => Path.Combine(state, name)).ToArray(); - foreach (var directory in removed.Where(Directory.Exists)) + var existing = targets.Where(Directory.Exists).ToList(); + if (dryRun) + { + long total = 0; + foreach (var directory in existing) + { + var bytes = DirectorySize(directory); + total += bytes; + reporter.Plain($"{FileSets.ToRoot(directory, root)} ({bytes} bytes)"); + } + + reporter.Status(existing.Count == 0 + ? "nothing to remove (dry run)" + : $"would remove {existing.Count} directories ({total} bytes)"); + return 0; + } + + foreach (var directory in existing) { Directory.Delete(directory, recursive: true); } @@ -258,7 +309,11 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector return 0; } - private async Task<int> PackageAsync() + private static long DirectorySize(string directory) => + Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories) + .Sum(file => new FileInfo(file).Length); + + private async Task<int> PackageAsync(PackageCommand command) { RefuseWithoutSandbox(); var module = await Workspace.LoadMainModuleAsync(workingDirectory, TazelVersion).ConfigureAwait(false); @@ -266,12 +321,33 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector var files = ModuleArchive.Files(module.Root, relative => exclude.Items.Any(item => item.Path is { } path ? path == relative : FileSets.Matches(item.Glob!.Pattern, relative) && !item.Glob.Exclude.Any(pattern => FileSets.Matches(pattern, relative)))); + if (command.List) + { + long total = 0; + foreach (var relative in files) + { + var length = new FileInfo(Path.Combine(module.Root, relative)).Length; + total += length; + reporter.Plain($"{relative}\t{length}"); + } + + reporter.Status($"{files.Count} files ({total} bytes)"); + return 0; + } + var info = module.Info; var baseName = ModuleArchive.BaseName(info.Group, info.Name, info.Version.ToNormalizedString()); - var archive = Path.Combine(module.Root, ModuleFiles.StateDirectory, "package", baseName + ModuleArchive.Extension); + var targetDir = command.OutputDir is null + ? Path.Combine(module.Root, ModuleFiles.StateDirectory, "package") + : Path.GetFullPath(command.OutputDir, workingDirectory); + Directory.CreateDirectory(targetDir); + var archive = Path.Combine(targetDir, baseName + ModuleArchive.Extension); ModuleArchive.Write(module.Root, baseName, archive, files); await File.WriteAllTextAsync(archive + ".sha256sums", Sha256Sums.SumsLine(archive)).ConfigureAwait(false); - reporter.Success($"wrote {FileSets.ToRoot(archive, module.Root)} ({files.Count} files) and its .sha256sums"); + var shown = targetDir.StartsWith(module.Root, StringComparison.Ordinal) + ? FileSets.ToRoot(archive, module.Root) + : archive; + reporter.Success($"wrote {shown} ({files.Count} files) and its .sha256sums"); return 0; } diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index f72e71d..83a736e 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -197,10 +197,12 @@ internal static class Help tazel explain E0406 tazel explain E0406 --long """), - ["version"] = new("tazel version: prints the version of Tazel.", """ - tazel version + ["version"] = new("tazel version [-V|--verbose] [-o|--output text|json]: prints the version of Tazel.", """ + tazel version [-V|--verbose] [-o|--output text|json] Prints the version of Tazel, the .NET runtime it runs on and the platform of this machine. + -V, --verbose adds the commit and release kind + -o, --output text|json output format; default: text """), ["help"] = new("tazel help [command] [--short|--long]: prints help.", """ tazel help [command] [--short|--long] diff --git a/tests/Progmasoft.Tazel.Tests/CliFlagsTests.cs b/tests/Progmasoft.Tazel.Tests/CliFlagsTests.cs new file mode 100644 index 0000000..2b408d2 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/CliFlagsTests.cs @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Text.Json; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class CliFlagsTests +{ + [Fact] + public void VersionFlagsParseVerboseAndOutputFormat() + { + var plain = Assert.IsType<VersionCommand>(CommandLine.Parse(["version"])); + Assert.False(plain.Verbose); + Assert.False(plain.Json); + + var verbose = Assert.IsType<VersionCommand>(CommandLine.Parse(["version", "-V"])); + Assert.True(verbose.Verbose); + Assert.False(verbose.Json); + + var json = Assert.IsType<VersionCommand>(CommandLine.Parse(["version", "--verbose", "-o", "json"])); + Assert.True(json.Verbose); + Assert.True(json.Json); + + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["version", "-o", "yaml"])); + } + + [Fact] + public async Task VersionOutputsVerboseAndJsonWithoutWorkspace() + { + var dir = Path.Combine(Path.GetTempPath(), "tazel-version-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + var verbose = await RunAsync(["--color", "never", "version", "--verbose"], dir); + Assert.Contains("commit:", verbose, StringComparison.Ordinal); + Assert.Contains("release-kind:", verbose, StringComparison.Ordinal); + + var json = await RunAsync(["--color", "never", "version", "-V", "-o", "json"], dir); + using var doc = JsonDocument.Parse(json.Trim()); + Assert.True(doc.RootElement.TryGetProperty("version", out _)); + Assert.True(doc.RootElement.TryGetProperty("commit", out _)); + Assert.True(doc.RootElement.TryGetProperty("dotnet", out _)); + Assert.True(doc.RootElement.TryGetProperty("platform", out _)); + Assert.True(doc.RootElement.TryGetProperty("releaseKind", out _)); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Fact] + public async Task CleanDryRunListsDirectoriesWithoutDeleting() + { + var dir = Path.Combine(Path.GetTempPath(), "tazel-clean-dry-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + await File.WriteAllTextAsync(Path.Combine(dir, "MODULE.csx"), + "Module.Define(m => { m.Group = \"com.example\"; m.Name = \"demo\"; m.Version = \"0.1.0\"; });", + TestContext.Current.CancellationToken); + var outDir = Path.Combine(dir, ".tazel", "out"); + Directory.CreateDirectory(outDir); + var artifact = Path.Combine(outDir, "sample.o"); + await File.WriteAllTextAsync(artifact, "0123456789", TestContext.Current.CancellationToken); + + var output = await RunAsync(["--color", "never", "clean", "--dry-run"], dir); + Assert.True(File.Exists(artifact)); + Assert.Contains(".tazel/out", output, StringComparison.Ordinal); + Assert.Contains("10 bytes", output, StringComparison.Ordinal); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Fact] + public async Task PackageListAndOutputDirWorkWithoutMutatingDefaultDirectory() + { + var dir = Path.Combine(Path.GetTempPath(), "tazel-pkg-flags-" + Guid.NewGuid().ToString("N")); + var customOut = Path.Combine(dir, "dist"); + 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 = \"pkg\", Version = \"0.1.0\", License = \"MIT\" });\n", + TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(Path.Combine(dir, "hello.c"), "int main(void) { return 0; }\n", + TestContext.Current.CancellationToken); + + var listOutput = await RunAsync(["--color", "never", "package", "--list"], dir); + Assert.Contains("MODULE.csx", listOutput, StringComparison.Ordinal); + Assert.Contains("hello.c", listOutput, StringComparison.Ordinal); + Assert.False(Directory.Exists(Path.Combine(dir, ".tazel", "package"))); + + var pkgOutput = await RunAsync(["--color", "never", "package", "--allow-dirty", "--output-dir", customOut], dir); + Assert.Contains("wrote", pkgOutput, StringComparison.Ordinal); + var archive = Path.Combine(customOut, "com.example.pkg-0.1.0.tazel.tar.xz"); + Assert.True(File.Exists(archive)); + Assert.True(File.Exists(archive + ".sha256sums")); + } + 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(); + } +}