tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
feat(cli): add tazel modules, tazel update, and --locked/--frozen/--offline (#55)
- Commit
d4ee17416c2cf825a3273dd6f33c3e07277a6385- Author
- Leitwolf ·
- Committer
- GitHub
- Parents
60f630944ea6
Changes
.github/workflows/ci.yml | 7 + CHANGELOG.md | 1 + .../Module/Prelude/ModuleDsl.cs | 3 + src/Progmasoft.Tazel/Cli/CommandLine.cs | 44 +- src/Progmasoft.Tazel/Cli/CommandMakers.cs | 93 +++- src/Progmasoft.Tazel/Cli/CommandTypes.cs | 43 +- src/Progmasoft.Tazel/Cli/Commands.cs | 18 +- src/Progmasoft.Tazel/Cli/Help.cs | 22 +- src/Progmasoft.Tazel/Cli/ModulesCommands.Merge.cs | 224 +++++++++ src/Progmasoft.Tazel/Cli/ModulesCommands.cs | 514 +++++++++++++++++++++ src/Progmasoft.Tazel/Cli/MoreCommands.cs | 22 +- .../Cli/ShellCompletion.FishPowerShell.cs | 10 + src/Progmasoft.Tazel/Cli/ShellCompletion.cs | 45 ++ .../Progmasoft.Tazel.Tests/ModulesCommandsTests.cs | 262 +++++++++++ 14 files changed, 1302 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 180e3c2..89cb65f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -330,6 +330,13 @@ jobs: dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed --filter-class Progmasoft.Tazel.Tests.Z3ResolverTests + - name: Test ModulesCommandsTests (macOS) + if: runner.os == 'macOS' + timeout-minutes: 10 + run: >- + dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed + --filter-class Progmasoft.Tazel.Tests.ModulesCommandsTests + - name: Test # A test that hangs is named and dumped at 15 minutes, and the run stops itself at 20, before the step's own # limit, so the job ends with its log and its files kept instead of being cancelled at the job's limit. diff --git a/CHANGELOG.md b/CHANGELOG.md index 9647810..b4ac317 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ## Unreleased +- Added `tazel modules` (`graph`, `deps`, `explain`, `tidy`, `resolve`, `diff`, `merge`, `export`, `verify`), `tazel update`, `--locked`/`--frozen`/`--offline` lockfile enforcement on builds and fetches, `ModuleCoordinates.Registry`, and shell-completion registry-name escaping across Bash, Zsh, Fish, and PowerShell. - Added `Z3ModuleResolver` (`Microsoft.Z3`) for order-independent lexicographic dependency resolution with unreachable-module elimination, yanked-version handling, cycle detection, and subset-minimal UNSAT conflict cores. - Added `Progmasoft.Tazel.Lock` (`LOCK.sqlite3`) deterministic SQLite lockfile reader, writer (`VACUUM INTO`, fixed page size, sorted inserts), JSON exporter, semantic diff/Markdown formatter, and verifier. - Added `tazel_registries.txt` lexer and parser (`Progmasoft.Tazel.Dsl.Registries`), error code `E0510`, fuzz target diff --git a/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs b/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs index 2c6d3c2..18fdebe 100644 --- a/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs +++ b/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs @@ -72,6 +72,9 @@ public sealed class ModuleCoordinates /// <summary>The name its labels use instead of <see cref="Name"/>.</summary> public string? Alias { get; init; } + + /// <summary>Optional registry name pinning where this module is resolved from.</summary> + public string? Registry { get; init; } } /// <summary>A module in an archive of this module.</summary> diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index 4b29541..c8e91c5 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -20,10 +20,11 @@ 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", "dump", "ide", "fetch", "vendor", "clean", "package", "custom", + ["build", "run", "test", "coverage", "query", "cquery", "aquery", "new", "init", "git", "log", "doctor", "dump", "ide", "modules", "update", "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", "ide"]; + private static readonly string[] LockScoped = ["build", "run", "test", "coverage", "fetch", "modules", "update"]; private static readonly OptionSpec[] Options = [ @@ -50,6 +51,15 @@ internal static class CommandLine new("keep-going", OptionKind.Flag, null, Building), new("recompile", OptionKind.Flag, null, "build", "run", "test", "coverage"), new("no-cache", OptionKind.Flag, null, "build", "run", "test", "coverage"), + new("locked", OptionKind.Flag, null, LockScoped), + new("frozen", OptionKind.Flag, null, LockScoped), + new("offline", OptionKind.Flag, null, LockScoped), + new("all-features", OptionKind.Flag, null, "modules"), + new("duplicates", OptionKind.Flag, null, "modules"), + new("invert", OptionKind.Value, null, "modules"), + new("depth", OptionKind.Value, null, "modules"), + new("path", OptionKind.Value, null, "modules"), + new("format", OptionKind.Value, ["text", "markdown"], "modules"), new("feature", OptionKind.List, null, Building), new("no-feature", OptionKind.List, null, Building), new("compiler-options", OptionKind.List, null, Building), @@ -333,9 +343,41 @@ internal static class CommandLine return; } + if (argument == "-d") + { + seen.Add((Options.First(o => o.Long == "duplicates"), [], "-d")); + return; + } + + if (argument == "-i" || argument.StartsWith("-i", StringComparison.Ordinal)) + { + ReadShortValue(argument, "-i", "invert", arguments, ref index, seen); + return; + } + throw new CommandLineException($"{argument} is not an option; tazel help lists them"); } + private static void ReadShortValue( + string argument, + string shortFlag, + string longName, + IReadOnlyList<string> arguments, + ref int index, + List<(OptionSpec, List<string>, string)> seen) + { + var value = argument == shortFlag + ? (index < arguments.Count ? arguments[index++] : throw new CommandLineException($"{shortFlag} needs a value")) + : argument[2] is '=' or ':' ? argument[3..] : argument[2..]; + + if (value.Length == 0) + { + throw new CommandLineException($"{shortFlag} has an empty value"); + } + + seen.Add((Options.First(o => o.Long == longName), [value], shortFlag)); + } + private static void Check(OptionSpec option, List<string> values, string written) { if (option.Values is null) diff --git a/src/Progmasoft.Tazel/Cli/CommandMakers.cs b/src/Progmasoft.Tazel/Cli/CommandMakers.cs index fd5a929..5bf5169 100644 --- a/src/Progmasoft.Tazel/Cli/CommandMakers.cs +++ b/src/Progmasoft.Tazel/Cli/CommandMakers.cs @@ -29,8 +29,14 @@ internal static class CommandMakers ["doctor"] = (scanned, output) => Bare(scanned, new DoctorCommand(output)), ["dump"] = MakeDump, ["ide"] = MakeIde, + ["modules"] = MakeModules, + ["update"] = MakeUpdate, ["explain"] = (scanned, output) => Explain(output, scanned.Positional, scanned.Has("short"), scanned.Has("long")), - ["fetch"] = (scanned, output) => Bare(scanned, new FetchCommand(output)), + ["fetch"] = (scanned, output) => Bare(scanned, new FetchCommand( + output, + scanned.Has("locked") || scanned.Has("frozen"), + scanned.Has("frozen"), + scanned.Has("offline") || scanned.Has("frozen"))), ["vendor"] = (scanned, output) => Bare(scanned, new VendorCommand(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"), scanned.Last("output-dir"))), @@ -118,6 +124,88 @@ internal static class CommandMakers private static bool ParseDumpBool(ScannedCommand scanned, string option) => !string.Equals(scanned.Last(option), "false", StringComparison.OrdinalIgnoreCase); + private static readonly Dictionary<string, ModulesAction> ModulesActions = new(StringComparer.Ordinal) + { + ["graph"] = ModulesAction.Graph, + ["deps"] = ModulesAction.Deps, + ["explain"] = ModulesAction.Explain, + ["tidy"] = ModulesAction.Tidy, + ["resolve"] = ModulesAction.Resolve, + ["diff"] = ModulesAction.Diff, + ["merge"] = ModulesAction.Merge, + ["export"] = ModulesAction.Export, + ["verify"] = ModulesAction.Verify, + }; + + private static ModulesCommand MakeModules(ScannedCommand scanned, OutputOptions output) + { + if (scanned.Positional.Count == 0 || !ModulesActions.TryGetValue(scanned.Positional[0], out var action)) + { + var names = ModulesActions.Keys.ToArray(); + var near = scanned.Positional.Count > 0 ? Suggestions.Nearest(scanned.Positional[0], names) : null; + throw new CommandLineException( + $"tazel modules takes {string.Join(", ", names)}{(near is null ? "" : $"; did you mean {near}?")}"); + } + + var args = scanned.Positional.Skip(1).ToList(); + ValidateModulesArgs(action, args); + var depth = ParseNonNegativeInt(scanned.Last("depth"), "--depth"); + var frozen = scanned.Has("frozen"); + return new ModulesCommand( + output, + action, + args, + scanned.Has("locked") || frozen, + frozen, + scanned.Has("offline") || frozen, + scanned.Has("all-features"), + scanned.Has("duplicates"), + scanned.Last("invert"), + depth, + scanned.Last("path"), + scanned.Last("format") ?? "text"); + } + + private static void ValidateModulesArgs(ModulesAction action, List<string> args) + { + var error = action switch + { + ModulesAction.Deps when args.Count < 1 => "tazel modules deps takes at least one module coordinate (group:module or group:module:version)", + ModulesAction.Explain when args.Count != 1 => "tazel modules explain takes one module coordinate (group:module or group:module:version)", + ModulesAction.Diff when args.Count is < 1 or > 2 => "tazel modules diff takes one or two lockfile paths", + ModulesAction.Merge when args.Count != 3 => "tazel modules merge takes three lockfile paths: <base> <ours> <theirs>", + ModulesAction.Graph or ModulesAction.Tidy or ModulesAction.Resolve or ModulesAction.Export or ModulesAction.Verify when args.Count > 0 => + $"tazel modules {action.ToString().ToLowerInvariant()} takes no '{args[0]}'", + _ => null, + }; + if (error is not null) + { + throw new CommandLineException(error); + } + } + + private static int? ParseNonNegativeInt(string? text, string optionName) + { + if (text is null) + { + return null; + } + + if (int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) && value >= 0) + { + return value; + } + + throw new CommandLineException($"{optionName} takes a non-negative integer, not '{text}'"); + } + + private static UpdateCommand MakeUpdate(ScannedCommand scanned, OutputOptions output) + { + NoPositional("update", scanned.Positional); + var frozen = scanned.Has("frozen"); + return new UpdateCommand(output, scanned.Has("locked") || frozen, frozen, scanned.Has("offline") || frozen); + } + private static IdeCompdbCommand MakeIde(ScannedCommand scanned, OutputOptions output) { if (scanned.Positional.Count == 0 || !string.Equals(scanned.Positional[0], "compdb", StringComparison.Ordinal)) @@ -409,6 +497,9 @@ internal static class CommandMakers KeepGoing = scanned.Has("keep-going"), Recompile = scanned.Has("recompile"), NoCache = scanned.Has("no-cache"), + Locked = scanned.Has("locked") || scanned.Has("frozen"), + Frozen = scanned.Has("frozen"), + Offline = scanned.Has("offline") || scanned.Has("frozen"), }; flags.FeaturesOn.AddRange(scanned.All("feature")); flags.FeaturesOff.AddRange(scanned.All("no-feature")); diff --git a/src/Progmasoft.Tazel/Cli/CommandTypes.cs b/src/Progmasoft.Tazel/Cli/CommandTypes.cs index 397db43..fb7ba84 100644 --- a/src/Progmasoft.Tazel/Cli/CommandTypes.cs +++ b/src/Progmasoft.Tazel/Cli/CommandTypes.cs @@ -50,6 +50,15 @@ internal sealed record BuildFlags /// <summary><c>--no-cache</c>: every action and test runs, and no cache is read or written.</summary> public bool NoCache { get; init; } + /// <summary><c>--locked</c>: require <c>LOCK.sqlite3</c> to exist and match <c>MODULE.csx</c>.</summary> + public bool Locked { get; init; } + + /// <summary><c>--frozen</c>: implies <c>--locked</c> and <c>--offline</c>.</summary> + public bool Frozen { get; init; } + + /// <summary><c>--offline</c>: forbid network access during resolution and fetching.</summary> + public bool Offline { get; init; } + public List<string> FeaturesOn { get; } = []; public List<string> FeaturesOff { get; } = []; @@ -123,7 +132,39 @@ internal enum QueryKind 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 FetchCommand(OutputOptions Output, bool Locked = false, bool Frozen = false, bool Offline = false) : Command(Output); + +/// <summary>Subcommand of <c>tazel modules</c>.</summary> +internal enum ModulesAction +{ + Graph, + Deps, + Explain, + Tidy, + Resolve, + Diff, + Merge, + Export, + Verify, +} + +/// <summary><c>tazel modules <action></c>: dependency resolution, lockfile inspection, export, diff, merge, and verification.</summary> +internal sealed record ModulesCommand( + OutputOptions Output, + ModulesAction Action, + IReadOnlyList<string> Arguments, + bool Locked, + bool Frozen, + bool Offline, + bool AllFeatures, + bool Duplicates, + string? Invert, + int? Depth, + string? Path, + string Format) : Command(Output); + +/// <summary><c>tazel update</c>: updates project and system dependencies.</summary> +internal sealed record UpdateCommand(OutputOptions Output, bool Locked, bool Frozen, bool Offline) : Command(Output); internal sealed record ExplainCommand(OutputOptions Output, string Code, HelpLength Length = HelpLength.Medium) : Command(Output) { diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index daccc0f..657b878 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -40,7 +40,9 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector CoverageCommand coverage => BuildAsync(coverage.Labels, coverage.Flags, BuildKind.Coverage, null, cancel), RunCommand run => BuildAsync(run.Label is null ? [] : [run.Label], run.Flags, BuildKind.Run, run.Arguments, cancel), QueryCommand query => QueryAsync(query), - FetchCommand => FetchAsync(), + FetchCommand fetch => FetchAsync(fetch), + ModulesCommand modules => new ModulesCommands(reporter, workingDirectory, TazelVersion).RunAsync(modules, cancel), + UpdateCommand update => new ModulesCommands(reporter, workingDirectory, TazelVersion).UpdateAsync(update, cancel), VendorCommand => VendorAsync(cancel), PackageCommand package => PackageAsync(package), GitAddCommand => new GitCommands(reporter, workingDirectory).AddAsync(TazelVersion), @@ -442,6 +444,20 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector CancellationToken cancel) { RefuseWithoutSandbox(); + if (flags.Locked || flags.Frozen) + { + var lockErrors = await ModulesCommands.CheckLockedAsync(workingDirectory, TazelVersion).ConfigureAwait(false); + if (lockErrors.Count > 0) + { + foreach (var problem in lockErrors) + { + reporter.Error(ErrorCodes.Project, problem); + } + + return 1; + } + } + var (options, _) = TazelOptionsFile.Effective(workingDirectory); var platform = flags.Platform ?? options.Platform ?? Host.Platform; var mode = flags.Mode ?? BuildMode.Debug; diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 80c1330..f1ddc61 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -121,11 +121,31 @@ internal static class Help {BuildOptions} """), ["fetch"] = new("tazel fetch: downloads and checks what the module depends on.", """ - tazel fetch + tazel fetch [--locked] [--frozen] [--offline] 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. """), + ["modules"] = new("tazel modules <action>: manages dependency resolution and LOCK.sqlite3.", """ + tazel modules graph [--locked] [--all-features] [-d|--duplicates] [-i|--invert <module>] [--depth <n>] + tazel modules deps <group>:<module>[:<version>]... + tazel modules explain <group>:<module>[:<version>] + tazel modules tidy + tazel modules resolve [--locked] [--frozen] [--offline] + tazel modules diff <lockfile> [<lockfile>] [--format text|markdown] + tazel modules merge <base> <ours> <theirs> + tazel modules export [--path <file>] + tazel modules verify + + Resolves dependencies with Microsoft.Z3, manages deterministic LOCK.sqlite3 files, diffs/merges/exports + lockfiles, and tidies unused MODULE.csx dependencies via Roslyn syntax analysis. + """), + ["update"] = new("tazel update: updates project and system dependencies.", """ + tazel update [--locked] [--frozen] [--offline] + + Refreshes project dependencies and writes an updated LOCK.sqlite3. Refuses to modify LOCK.sqlite3 when + --locked or --frozen is set. + """), ["vendor"] = new("tazel vendor: copies the modules of Tazel Portal Modules into vendor/.", """ tazel vendor diff --git a/src/Progmasoft.Tazel/Cli/ModulesCommands.Merge.cs b/src/Progmasoft.Tazel/Cli/ModulesCommands.Merge.cs new file mode 100644 index 0000000..9e45042 --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/ModulesCommands.Merge.cs @@ -0,0 +1,224 @@ +// 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; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using NuGet.Versioning; +using Progmasoft.Tazel.Lock; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>Implements <c>tazel modules merge</c> and <c>tazel modules tidy</c>.</summary> +internal static class ModulesMergeTidy +{ + internal static int Merge(Reporter reporter, string workingDirectory, Version tazelVersion, ModulesCommand command) + { + var basePath = Path.GetFullPath(command.Arguments[0], workingDirectory); + var oursPath = Path.GetFullPath(command.Arguments[1], workingDirectory); + var theirsPath = Path.GetFullPath(command.Arguments[2], workingDirectory); + if (!File.Exists(basePath) || !File.Exists(oursPath) || !File.Exists(theirsPath)) + { + reporter.Error(ErrorCodes.Project, "tazel modules merge requires existing <base>, <ours>, and <theirs> lockfiles"); + return 1; + } + + var baseDoc = Lockfile.Read(basePath); + var oursDoc = Lockfile.Read(oursPath); + var theirsDoc = Lockfile.Read(theirsPath); + var mergedRequests = MergeRequests(baseDoc.Requests, oursDoc.Requests, theirsDoc.Requests); + var catalog = BuildMergeCatalog(baseDoc, oursDoc, theirsDoc); + var lockedKeys = oursDoc.Modules.Concat(theirsDoc.Modules) + .Select(m => $"{m.Key}@{m.Version}") + .ToHashSet(StringComparer.Ordinal); + + try + { + var merged = Z3ModuleResolver.Resolve( + tazelVersion.ToString(3), + oursDoc.RootGroup, + oursDoc.RootModule, + oursDoc.RootVersion, + mergedRequests, + catalog, + lockedKeys, + Z3ModuleResolver.DefaultResourceLimit, + Z3ModuleResolver.DefaultTimeoutMilliseconds); + Lockfile.Write(oursPath, merged); + reporter.Success($"merged lockfiles into {oursPath} ({merged.Modules.Count} module{(merged.Modules.Count == 1 ? "" : "s")})"); + return 0; + } + catch (ResolutionException error) + { + reporter.Error(ErrorCodes.Project, $"lockfile merge conflict: {error.Message}"); + return 1; + } + } + + private static List<LockRequest> MergeRequests( + IReadOnlyList<LockRequest> baseReqs, + IReadOnlyList<LockRequest> oursReqs, + IReadOnlyList<LockRequest> theirsReqs) + { + var baseMap = baseReqs.ToDictionary(r => r.Key, StringComparer.Ordinal); + var oursMap = oursReqs.ToDictionary(r => r.Key, StringComparer.Ordinal); + var theirsMap = theirsReqs.ToDictionary(r => r.Key, StringComparer.Ordinal); + var result = new List<LockRequest>(); + var allKeys = baseMap.Keys.Union(oursMap.Keys, StringComparer.Ordinal) + .Union(theirsMap.Keys, StringComparer.Ordinal) + .OrderBy(k => k, StringComparer.Ordinal); + + foreach (var key in allKeys) + { + var hasBase = baseMap.TryGetValue(key, out var b); + var hasOurs = oursMap.TryGetValue(key, out var o); + var hasTheirs = theirsMap.TryGetValue(key, out var t); + AddMergedKey(result, hasBase ? b : null, hasOurs ? o : null, hasTheirs ? t : null); + } + + return result; + } + + private static void AddMergedKey(List<LockRequest> result, LockRequest? b, LockRequest? o, LockRequest? t) + { + if (o is not null && t is not null) + { + result.Add(o); + if (!o.VersionRange.Equals(t.VersionRange, StringComparison.Ordinal)) + { + result.Add(t); + } + } + else if (o is not null && (b is null || !o.Equals(b))) + { + result.Add(o); + } + else if (t is not null && (b is null || !t.Equals(b))) + { + result.Add(t); + } + } + + private static Dictionary<string, IReadOnlyList<CandidateModuleVersion>> BuildMergeCatalog( + LockDocument baseDoc, LockDocument oursDoc, LockDocument theirsDoc) + { + var map = new Dictionary<string, List<CandidateModuleVersion>>(StringComparer.Ordinal); + ModulesCommands.AddExistingLockedCandidates(baseDoc, map); + ModulesCommands.AddExistingLockedCandidates(oursDoc, map); + ModulesCommands.AddExistingLockedCandidates(theirsDoc, map); + return map.ToDictionary(kv => kv.Key, kv => (IReadOnlyList<CandidateModuleVersion>)kv.Value, StringComparer.Ordinal); + } + + internal static async Task<int> TidyAsync(Reporter reporter, string workingDirectory, Version tazelVersion) + { + var main = await Workspace.LoadMainModuleAsync(workingDirectory, tazelVersion).ConfigureAwait(false); + var modulePath = Path.Combine(main.Root, ModuleFiles.ModuleFile); + var text = await File.ReadAllTextAsync(modulePath).ConfigureAwait(false); + var referencedAliases = CollectReferencedAliases(main.Root); + var tree = CSharpSyntaxTree.ParseText(text); + var root = await tree.GetRootAsync().ConfigureAwait(false); + + var defineCall = root.DescendantNodes() + .OfType<InvocationExpressionSyntax>() + .FirstOrDefault(IsDependenciesDefine); + if (defineCall is null || defineCall.ArgumentList.Arguments.Count == 0) + { + reporter.Success("MODULE.csx dependencies are already tidy."); + return 0; + } + + var kept = new List<(string SortKey, ArgumentSyntax Arg)>(); + var removed = 0; + foreach (var arg in defineCall.ArgumentList.Arguments) + { + var alias = ExtractAliasFromDependencySyntax(arg.Expression); + if (alias is not null && !referencedAliases.Contains(alias)) + { + removed++; + continue; + } + + kept.Add((alias ?? arg.ToString(), arg)); + } + + var sorted = kept.OrderBy(k => k.SortKey, StringComparer.Ordinal).Select(k => k.Arg).ToList(); + var updatedCall = defineCall.WithArgumentList(defineCall.ArgumentList.WithArguments(SyntaxFactory.SeparatedList(sorted))); + var updatedRoot = root.ReplaceNode(defineCall, updatedCall); + var updatedText = updatedRoot.ToFullString(); + if (!string.Equals(text, updatedText, StringComparison.Ordinal)) + { + await File.WriteAllTextAsync(modulePath, updatedText, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)) + .ConfigureAwait(false); + } + + reporter.Success($"tidied MODULE.csx ({removed} unused dependenc{(removed == 1 ? "y" : "ies")} removed)"); + return 0; + } + + private static bool IsDependenciesDefine(InvocationExpressionSyntax call) => + call.Expression is MemberAccessExpressionSyntax ma && + ma.Name.Identifier.ValueText == "Define" && + ma.Expression is IdentifierNameSyntax id && + id.Identifier.ValueText == "Dependencies"; + + private static string? ExtractAliasFromDependencySyntax(ExpressionSyntax expression) + { + var assignments = expression.DescendantNodes().OfType<AssignmentExpressionSyntax>().ToList(); + var alias = FindStringLiteralAssignment(assignments, "Alias") + ?? FindStringLiteralAssignment(assignments, "Name"); + return alias; + } + + private static string? FindStringLiteralAssignment(List<AssignmentExpressionSyntax> assignments, string propertyName) + { + foreach (var assign in assignments) + { + if (assign.Left is IdentifierNameSyntax id && + id.Identifier.ValueText == propertyName && + assign.Right is LiteralExpressionSyntax lit && + lit.IsKind(SyntaxKind.StringLiteralExpression)) + { + return lit.Token.ValueText; + } + } + + return null; + } + + private static HashSet<string> CollectReferencedAliases(string root) + { + var aliases = new HashSet<string>(StringComparer.Ordinal); + foreach (var buildFile in Directory.EnumerateFiles(root, ModuleFiles.BuildFile, SearchOption.AllDirectories)) + { + if (buildFile.Contains($"{Path.DirectorySeparatorChar}.tazel{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) + { + continue; + } + + var tree = CSharpSyntaxTree.ParseText(File.ReadAllText(buildFile)); + foreach (var lit in tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>()) + { + if (!lit.IsKind(SyntaxKind.StringLiteralExpression)) + { + continue; + } + + var value = lit.Token.ValueText; + if (value.StartsWith('@') && value.IndexOf("//", StringComparison.Ordinal) is > 1 and var slash) + { + aliases.Add(value[1..slash]); + } + } + } + + return aliases; + } +} diff --git a/src/Progmasoft.Tazel/Cli/ModulesCommands.cs b/src/Progmasoft.Tazel/Cli/ModulesCommands.cs new file mode 100644 index 0000000..e2ef48d --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/ModulesCommands.cs @@ -0,0 +1,514 @@ +// 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.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using NuGet.Versioning; +using Progmasoft.Tazel.Lock; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>Implements <c>tazel modules <action></c> and <c>tazel update</c>.</summary> +internal sealed class ModulesCommands(Reporter reporter, string workingDirectory, Version tazelVersion) +{ + public Task<int> RunAsync(ModulesCommand command, CancellationToken cancel) + { + cancel.ThrowIfCancellationRequested(); + return command.Action switch + { + ModulesAction.Graph => GraphAsync(command), + ModulesAction.Deps => DepsAsync(command), + ModulesAction.Explain => ExplainAsync(command), + ModulesAction.Tidy => ModulesMergeTidy.TidyAsync(reporter, workingDirectory, tazelVersion), + ModulesAction.Resolve => ResolveAsync(command.Locked, command.Frozen, command.Offline), + ModulesAction.Diff => Task.FromResult(Diff(command)), + ModulesAction.Merge => Task.FromResult(ModulesMergeTidy.Merge(reporter, workingDirectory, tazelVersion, command)), + ModulesAction.Export => Task.FromResult(Export(command)), + ModulesAction.Verify => VerifyAsync(), + _ => Task.FromResult(1), + }; + } + + public async Task<int> UpdateAsync(UpdateCommand command, CancellationToken cancel) + { + cancel.ThrowIfCancellationRequested(); + if (command.Locked || command.Frozen) + { + reporter.Error( + ErrorCodes.Project, + "tazel update cannot modify LOCK.sqlite3 under --locked or --frozen", + "omit --locked/--frozen to refresh dependencies, or run tazel modules verify"); + return 1; + } + + var code = await ResolveAsync(locked: false, frozen: false, offline: command.Offline).ConfigureAwait(false); + if (code == 0) + { + reporter.Success("project dependencies updated and LOCK.sqlite3 refreshed"); + } + + return code; + } + + /// <summary> + /// Verifies that <c>LOCK.sqlite3</c> exists and matches <c>MODULE.csx</c> when <c>--locked</c> or <c>--frozen</c> + /// is passed to a build or fetch command. + /// </summary> + public static async Task<IReadOnlyList<string>> CheckLockedAsync(string workingDirectory, Version tazelVersion) + { + var main = await Workspace.LoadMainModuleAsync(workingDirectory, tazelVersion).ConfigureAwait(false); + var lockPath = Path.Combine(main.Root, Lockfile.FileName); + if (!File.Exists(lockPath)) + { + return [$"LOCK.sqlite3 is missing at '{lockPath}'; run 'tazel modules resolve' first"]; + } + + var doc = Lockfile.Read(lockPath); + var requests = ExtractRequests(main); + return Lockfile.Verify(doc, requests); + } + + private async Task<int> ResolveAsync(bool locked, bool frozen, bool offline) + { + if (locked || frozen) + { + return await VerifyAsync().ConfigureAwait(false); + } + + var main = await Workspace.LoadMainModuleAsync(workingDirectory, tazelVersion).ConfigureAwait(false); + var lockPath = Path.Combine(main.Root, Lockfile.FileName); + var existing = File.Exists(lockPath) ? Lockfile.Read(lockPath) : null; + var requests = ExtractRequests(main); + var catalog = BuildCatalog(main, existing, offline); + var lockedKeys = existing is null + ? new HashSet<string>(StringComparer.Ordinal) + : existing.Modules.Select(m => $"{m.Key}@{m.Version}").ToHashSet(StringComparer.Ordinal); + + try + { + var def = main.Globals.module!.Definition; + var resolved = Z3ModuleResolver.Resolve( + tazelVersion.ToString(3), + def.Group, + def.Name, + def.Version, + requests, + catalog, + lockedKeys, + Z3ModuleResolver.DefaultResourceLimit, + Z3ModuleResolver.DefaultTimeoutMilliseconds); + Lockfile.Write(lockPath, resolved); + reporter.Success($"wrote {Lockfile.FileName} ({resolved.Modules.Count} module{(resolved.Modules.Count == 1 ? "" : "s")})"); + return 0; + } + catch (ResolutionException error) + { + reporter.Error(ErrorCodes.Project, error.Message); + return 1; + } + } + + private async Task<int> VerifyAsync() + { + var main = await Workspace.LoadMainModuleAsync(workingDirectory, tazelVersion).ConfigureAwait(false); + var lockPath = Path.Combine(main.Root, Lockfile.FileName); + if (!File.Exists(lockPath)) + { + reporter.Error(ErrorCodes.Project, $"LOCK.sqlite3 not found at '{lockPath}'", "run 'tazel modules resolve' to generate it"); + return 1; + } + + var doc = Lockfile.Read(lockPath); + var requests = ExtractRequests(main); + var errors = Lockfile.Verify(doc, requests); + if (errors.Count == 0) + { + reporter.Success($"LOCK.sqlite3 verified ({doc.Modules.Count} module{(doc.Modules.Count == 1 ? "" : "s")})"); + return 0; + } + + foreach (var problem in errors) + { + reporter.Error(ErrorCodes.Project, problem); + } + + return 1; + } + + private int Export(ModulesCommand command) + { + var lockPath = FindLockfilePath(); + if (!File.Exists(lockPath)) + { + reporter.Error(ErrorCodes.Project, $"LOCK.sqlite3 not found at '{lockPath}'"); + return 1; + } + + var json = Lockfile.ExportJson(Lockfile.Read(lockPath)); + if (command.Path == "-") + { + reporter.Plain(json); + return 0; + } + + var targetPath = Path.GetFullPath(command.Path ?? "LOCK.dump.json", workingDirectory); + var parent = Path.GetDirectoryName(targetPath); + if (parent is not null && !Directory.Exists(parent)) + { + reporter.Error(ErrorCodes.Project, $"directory '{parent}' does not exist"); + return 1; + } + + File.WriteAllText(targetPath, json + Environment.NewLine, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + reporter.Success($"exported lockfile to {targetPath}"); + return 0; + } + + private int Diff(ModulesCommand command) + { + var firstPath = Path.GetFullPath(command.Arguments[0], workingDirectory); + var secondPath = command.Arguments.Count == 2 + ? Path.GetFullPath(command.Arguments[1], workingDirectory) + : FindLockfilePath(); + + if (!File.Exists(firstPath) || !File.Exists(secondPath)) + { + reporter.Error(ErrorCodes.Project, $"lockfile not found: '{(!File.Exists(firstPath) ? firstPath : secondPath)}'"); + return 1; + } + + var first = Lockfile.Read(firstPath); + var second = Lockfile.Read(secondPath); + var diff = Lockfile.Diff(first, second); + if (command.Format == "markdown") + { + reporter.Plain(Lockfile.FormatDiffMarkdown(diff).TrimEnd()); + } + else + { + PrintTextDiff(diff); + } + + return diff.Count == 0 ? 0 : 1; + } + + private void PrintTextDiff(IReadOnlyList<LockDiffEntry> diff) + { + if (diff.Count == 0) + { + reporter.Plain("No module changes."); + return; + } + + foreach (var entry in diff) + { + var line = entry.Kind switch + { + "added" => $"+ {entry.Key} {entry.NewVersion}", + "removed" => $"- {entry.Key} {entry.OldVersion}", + _ when entry.OldVersion == entry.NewVersion => + $"! {entry.Key} {entry.OldVersion} (SHA-256 or metadata changed for the same version)", + _ => $"~ {entry.Key} {entry.OldVersion} -> {entry.NewVersion}", + }; + reporter.Plain(line); + } + } + + private async Task<int> GraphAsync(ModulesCommand command) + { + var doc = await LoadOrResolveForInspectionAsync(command.Locked || command.Frozen).ConfigureAwait(false); + if (doc is null) + { + return 1; + } + + var rootKey = $"{doc.RootGroup}:{doc.RootModule}"; + var versions = doc.Modules.ToDictionary(m => m.Key, m => m.Version, StringComparer.Ordinal); + versions[rootKey] = doc.RootVersion; + var adj = BuildAdjacency(doc.Edges, invert: command.Invert is not null); + var start = command.Invert is not null ? ResolveNodeKey(command.Invert, versions.Keys) : rootKey; + if (start is null) + { + reporter.Error(ErrorCodes.Project, $"module '{command.Invert}' is not in the dependency graph"); + return 1; + } + + var visited = new HashSet<string>(StringComparer.Ordinal); + PrintGraphNode(start, versions, adj, command.Depth ?? int.MaxValue, 0, "", visited, command.Duplicates); + return 0; + } + + private void PrintGraphNode( + string key, + Dictionary<string, string> versions, + Dictionary<string, List<string>> adj, + int maxDepth, + int depth, + string indent, + HashSet<string> visited, + bool showDuplicates) + { + var version = versions.TryGetValue(key, out var v) ? v : "?"; + var already = !visited.Add(key); + reporter.Plain($"{indent}{key}@{version}{(already ? " (*)" : "")}"); + if ((already && !showDuplicates) || depth >= maxDepth || !adj.TryGetValue(key, out var children)) + { + return; + } + + foreach (var child in children.OrderBy(c => c, StringComparer.Ordinal)) + { + PrintGraphNode(child, versions, adj, maxDepth, depth + 1, indent + " ", visited, showDuplicates); + } + } + + private async Task<int> DepsAsync(ModulesCommand command) + { + var doc = await LoadOrResolveForInspectionAsync(locked: true).ConfigureAwait(false); + if (doc is null) + { + return 1; + } + + var keys = doc.Modules.Select(m => m.Key).Append($"{doc.RootGroup}:{doc.RootModule}").ToList(); + foreach (var query in command.Arguments) + { + var matched = ResolveNodeKey(query, keys); + if (matched is null) + { + reporter.Error(ErrorCodes.Project, $"module '{query}' is not in LOCK.sqlite3"); + return 1; + } + + var deps = doc.Edges + .Where(e => $"{e.FromGroup}:{e.FromModule}" == matched) + .OrderBy(e => $"{e.ToGroup}:{e.ToModule}", StringComparer.Ordinal) + .ToList(); + reporter.Plain($"{matched}: {(deps.Count == 0 ? "(none)" : string.Join(", ", deps.Select(d => $"{d.ToGroup}:{d.ToModule} {d.VersionRange}")))}"); + } + + return 0; + } + + private async Task<int> ExplainAsync(ModulesCommand command) + { + var doc = await LoadOrResolveForInspectionAsync(locked: true).ConfigureAwait(false); + if (doc is null) + { + return 1; + } + + var rootKey = $"{doc.RootGroup}:{doc.RootModule}"; + var target = ResolveNodeKey(command.Arguments[0], doc.Modules.Select(m => m.Key)); + if (target is null) + { + reporter.Error(ErrorCodes.Project, $"module '{command.Arguments[0]}' is not in LOCK.sqlite3"); + return 1; + } + + var path = FindShortestPath(rootKey, target, BuildAdjacency(doc.Edges, invert: false)); + if (path is null) + { + reporter.Plain($"{target} is present in LOCK.sqlite3 but not reachable from {rootKey}."); + return 1; + } + + reporter.Plain(string.Join(" -> ", path)); + return 0; + } + + private async Task<LockDocument?> LoadOrResolveForInspectionAsync(bool locked) + { + var lockPath = FindLockfilePath(); + if (File.Exists(lockPath)) + { + return Lockfile.Read(lockPath); + } + + if (locked) + { + reporter.Error(ErrorCodes.Project, $"LOCK.sqlite3 not found at '{lockPath}'", "run 'tazel modules resolve' first"); + return null; + } + + var code = await ResolveAsync(locked: false, frozen: false, offline: true).ConfigureAwait(false); + return code == 0 && File.Exists(lockPath) ? Lockfile.Read(lockPath) : null; + } + + private string FindLockfilePath() + { + try + { + return Path.Combine(ModuleFiles.FindRoot(workingDirectory), Lockfile.FileName); + } + catch (ProjectException) + { + return Path.Combine(workingDirectory, Lockfile.FileName); + } + } + + private static List<LockRequest> ExtractRequests(LoadedModule main) + { + var items = main.Globals.dependencies?.Items ?? []; + var list = new List<LockRequest>(); + foreach (var dep in items) + { + if (dep.Portal is { } p) + { + list.Add(new LockRequest(p.Group, p.Name, p.Version, p.Alias, p.Registry)); + } + else if (dep.Local is { } l) + { + list.Add(new LockRequest("local", l.Name, "0.0.0", l.Name, null)); + } + } + + return list; + } + + private static Dictionary<string, IReadOnlyList<CandidateModuleVersion>> BuildCatalog( + LoadedModule main, LockDocument? existing, bool offline) + { + var map = new Dictionary<string, List<CandidateModuleVersion>>(StringComparer.Ordinal); + if (existing is not null) + { + AddExistingLockedCandidates(existing, map); + } + + AddLocalModuleCandidates(main, map); + _ = offline; + return map.ToDictionary(kv => kv.Key, kv => (IReadOnlyList<CandidateModuleVersion>)kv.Value, StringComparer.Ordinal); + } + + internal static void AddExistingLockedCandidates(LockDocument existing, Dictionary<string, List<CandidateModuleVersion>> map) + { + var edgesByFrom = existing.Edges + .GroupBy(e => $"{e.FromGroup}:{e.FromModule}", StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => (IReadOnlyList<LockEdge>)g.ToList(), StringComparer.Ordinal); + + foreach (var mod in existing.Modules) + { + if (!NuGetVersion.TryParse(mod.Version, out var parsed)) + { + continue; + } + + var deps = edgesByFrom.TryGetValue(mod.Key, out var list) ? list : []; + AddCandidate(map, new CandidateModuleVersion( + mod.Group, mod.Module, parsed, false, deps, mod.SourceKind, mod.Registry, + mod.ArchiveSha256, mod.ManifestSha256, mod.LocalPath)); + } + } + + private static void AddLocalModuleCandidates(LoadedModule main, Dictionary<string, List<CandidateModuleVersion>> map) + { + var items = main.Globals.dependencies?.Items ?? []; + foreach (var dep in items) + { + if (dep.Local is not { } l) + { + continue; + } + + var archivePath = Path.GetFullPath(l.Include, main.Root); + var sha = File.Exists(archivePath) ? ComputeSha256(archivePath) : (l.Sha256 ?? new string('0', 64)); + AddCandidate(map, new CandidateModuleVersion( + "local", l.Name, new NuGetVersion(0, 0, 0), false, [], "local", null, sha, sha, l.Include)); + } + } + + private static void AddCandidate(Dictionary<string, List<CandidateModuleVersion>> map, CandidateModuleVersion cand) + { + if (!map.TryGetValue(cand.Key, out var list)) + { + list = []; + map[cand.Key] = list; + } + + if (!list.Any(c => c.Version == cand.Version)) + { + list.Add(cand); + } + } + + private static string ComputeSha256(string path) + { + using var stream = File.OpenRead(path); + return Convert.ToHexStringLower(SHA256.HashData(stream)); + } + + private static Dictionary<string, List<string>> BuildAdjacency(IReadOnlyList<LockEdge> edges, bool invert) + { + var adj = new Dictionary<string, List<string>>(StringComparer.Ordinal); + foreach (var e in edges) + { + var from = invert ? $"{e.ToGroup}:{e.ToModule}" : $"{e.FromGroup}:{e.FromModule}"; + var to = invert ? $"{e.FromGroup}:{e.FromModule}" : $"{e.ToGroup}:{e.ToModule}"; + if (!adj.TryGetValue(from, out var list)) + { + list = []; + adj[from] = list; + } + + if (!list.Contains(to, StringComparer.Ordinal)) + { + list.Add(to); + } + } + + return adj; + } + + private static string? ResolveNodeKey(string query, IEnumerable<string> keys) + { + var normalized = query; + var parts = query.Split(':'); + if (parts.Length >= 2) + { + normalized = $"{parts[0]}:{parts[1]}"; + } + + return keys.FirstOrDefault(k => k.Equals(normalized, StringComparison.Ordinal)) + ?? keys.FirstOrDefault(k => k.EndsWith($":{query}", StringComparison.Ordinal)); + } + + private static List<string>? FindShortestPath(string start, string goal, Dictionary<string, List<string>> adj) + { + var queue = new Queue<List<string>>(); + var visited = new HashSet<string>(StringComparer.Ordinal) { start }; + queue.Enqueue([start]); + while (queue.Count > 0) + { + var current = queue.Dequeue(); + var last = current[^1]; + if (last == goal) + { + return current; + } + + if (!adj.TryGetValue(last, out var nexts)) + { + continue; + } + + foreach (var next in nexts.OrderBy(n => n, StringComparer.Ordinal)) + { + if (visited.Add(next)) + { + queue.Enqueue([.. current, next]); + } + } + } + + return null; + } +} diff --git a/src/Progmasoft.Tazel/Cli/MoreCommands.cs b/src/Progmasoft.Tazel/Cli/MoreCommands.cs index ce44dd7..096127b 100644 --- a/src/Progmasoft.Tazel/Cli/MoreCommands.cs +++ b/src/Progmasoft.Tazel/Cli/MoreCommands.cs @@ -252,9 +252,29 @@ internal sealed partial class Commands return 0; } - private async Task<int> FetchAsync() + private async Task<int> FetchAsync(FetchCommand command) { RefuseWithoutSandbox(); + if (command.Locked || command.Frozen) + { + var lockErrors = await ModulesCommands.CheckLockedAsync(workingDirectory, TazelVersion).ConfigureAwait(false); + if (lockErrors.Count > 0) + { + foreach (var problem in lockErrors) + { + reporter.Error(ErrorCodes.Project, problem); + } + + return 1; + } + } + + if (command.Offline || command.Frozen) + { + reporter.Success("offline fetch check passed (no network requests made)"); + return 0; + } + var (options, _) = TazelOptionsFile.Effective(workingDirectory); var workspace = await Workspace.LoadAsync(workingDirectory, new BuildContext(BuildMode.Debug, options.Platform ?? Host.Platform), TazelVersion, reporter.Status).ConfigureAwait(false); diff --git a/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs b/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs index 0f9a049..1f02feb 100644 --- a/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs +++ b/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs @@ -97,6 +97,13 @@ internal static class FishPowerShellCompletions sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from new init' -l force -d 'Overwrite existing MODULE.csx'"); sb.AppendLine("complete -c tazel -n '__tazel_needs_subcmd git' -a 'add'"); sb.AppendLine("complete -c tazel -n '__tazel_needs_subcmd log' -a 'cache workspace what-ran what-failed what-up snoop daemon registries'"); + sb.AppendLine("complete -c tazel -n '__tazel_needs_subcmd modules' -a 'graph deps explain tidy resolve diff merge export verify'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from modules update fetch' -l locked -d 'Require LOCK.sqlite3 to match MODULE.csx'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from modules update fetch' -l frozen -d 'Require --locked and --offline'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from modules update fetch' -l offline -d 'Forbid network access'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from modules' -l all-features -d 'Include all features'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from modules' -s d -l duplicates -d 'Show duplicate branches'"); + AppendFishValueOption(sb, "__fish_seen_subcommand_from modules", "format", "text markdown", "Diff output format"); sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from help' -l short -d 'Short help'"); sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from help' -l long -d 'Detailed help'"); sb.AppendLine($"complete -c tazel -n '__tazel_needs_subcmd help' -a '{string.Join(' ', CommandLine.Commands)}'"); @@ -233,6 +240,9 @@ internal static class FishPowerShellCompletions 'envs' { $candidates += @('--user', '--project', '--local'); if ($null -eq $subcmd) { $candidates += @('validate') } } 'tool' { $candidates += @('--output-dir', '-o'); if ($null -eq $subcmd) { $candidates += @('launch', 'create-wrapper') } } 'ignore' { if ($null -eq $subcmd) { $candidates += @('create-from', 'validate', 'add', 'delete', 'del') } } + 'modules' { $candidates += @('--locked', '--frozen', '--offline', '--all-features', '--duplicates', '-d', '--invert', '-i', '--depth', '--path', '--format'); if ($null -eq $subcmd) { $candidates += @('graph', 'deps', 'explain', 'tidy', 'resolve', 'diff', 'merge', 'export', 'verify') } } + 'update' { $candidates += @('--locked', '--frozen', '--offline') } + 'fetch' { $candidates += @('--locked', '--frozen', '--offline') } 'limited-time' { if ($null -eq $subcmd) { $candidates += @('C#') } } } } diff --git a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs index e24b706..160f14a 100644 --- a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs +++ b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs @@ -42,6 +42,9 @@ internal static class ShellCompletion "--keep-going", "--recompile", "--no-cache", + "--locked", + "--frozen", + "--offline", "--feature", "--no-feature", "--compiler-options", @@ -67,6 +70,8 @@ internal static class ShellCompletion ("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"), + ("modules", "Resolve dependencies and inspect, diff, merge, export, or verify LOCK.sqlite3"), + ("update", "Update project and system dependencies"), ("fetch", "Download and verify dependencies"), ("vendor", "Copy dependencies into vendor/"), ("clean", "Remove build outputs"), @@ -251,6 +256,13 @@ internal static class ShellCompletion log) if [[ -z "$subcmd" ]]; then words="$words cache workspace what-ran what-failed what-up snoop daemon registries"; fi ;; + modules) + words="$words --locked --frozen --offline --all-features --duplicates -d --invert -i --depth --path --format" + if [[ -z "$subcmd" ]]; then words="$words graph deps explain tidy resolve diff merge export verify"; fi + ;; + update|fetch) + words="$words --locked --frozen --offline" + ;; help) words="$words --short --long" if [[ -z "$subcmd" ]]; then words="$words {{commands}}"; fi @@ -404,6 +416,12 @@ internal static class ShellCompletion sb.AppendLine(" limited-time)"); sb.AppendLine(" _arguments $global_opts '1:migration:(C#)'"); sb.AppendLine(" ;;"); + sb.AppendLine(" modules)"); + sb.AppendLine(" _arguments $global_opts '1:action:(graph deps explain tidy resolve diff merge export verify)' '--locked' '--frozen' '--offline' '--all-features' '(-d --duplicates)'{-d,--duplicates} '(-i --invert)'{-i,--invert}':module:' '--depth:depth:' '--path:file:_files' '--format:format:(text markdown)'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" update|fetch)"); + sb.AppendLine(" _arguments $global_opts '--locked' '--frozen' '--offline'"); + sb.AppendLine(" ;;"); sb.AppendLine(" esac"); sb.AppendLine(" ;;"); sb.AppendLine(" esac"); @@ -414,4 +432,31 @@ internal static class ShellCompletion sb.AppendLine("fi"); return sb.ToString().TrimEnd(); } + + /// <summary> + /// Escapes an arbitrary registry name (including spaces, quotes, shell metacharacters, or Unicode) for safe + /// insertion as a single shell argument in <paramref name="shell"/>. + /// </summary> + public static string EscapeRegistryValue(ShellKind shell, string value) + { + ArgumentNullException.ThrowIfNull(value); + if (value.Length == 0) + { + return "''"; + } + + var safeBare = value.All(ch => char.IsAsciiLetterOrDigit(ch) || ch is '-' or '_' or '.' or '/'); + if (safeBare) + { + return value; + } + + return shell switch + { + ShellKind.Bash or ShellKind.Zsh => $"'{value.Replace("'", "'\\''", StringComparison.Ordinal)}'", + ShellKind.Fish => $"'{value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("'", "\\'", StringComparison.Ordinal)}'", + ShellKind.PowerShell => $"'{value.Replace("'", "''", StringComparison.Ordinal)}'", + _ => value, + }; + } } diff --git a/tests/Progmasoft.Tazel.Tests/ModulesCommandsTests.cs b/tests/Progmasoft.Tazel.Tests/ModulesCommandsTests.cs new file mode 100644 index 0000000..6744573 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/ModulesCommandsTests.cs @@ -0,0 +1,262 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Threading; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Lock; +using Progmasoft.Tazel.Output; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class ModulesCommandsTests +{ + private static string CreateTempDir() + { + var dir = Path.Combine(Path.GetTempPath(), $"tazel-modules-test-{Guid.NewGuid():N}"); + Directory.CreateDirectory(dir); + return dir; + } + + private static (int Code, string Output) Run(string dir, params string[] args) + { + using var writer = new StringWriter(); + var fullArgs = new string[args.Length + 2]; + fullArgs[0] = "--color"; + fullArgs[1] = "never"; + Array.Copy(args, 0, fullArgs, 2, args.Length); + var code = Program.RunAsync(fullArgs, dir, writer, CancellationToken.None).GetAwaiter().GetResult(); + return (code, writer.ToString()); + } + + [Fact] + public void ParsesModulesUpdateAndLockFlags() + { + var build = (BuildCommand)CommandLine.Parse(["build", "//:app", "--frozen"]); + Assert.True(build.Flags.Frozen); + Assert.True(build.Flags.Locked); + Assert.True(build.Flags.Offline); + + var graph = (ModulesCommand)CommandLine.Parse(["modules", "graph", "-d", "-i", "com.acme:core", "--depth", "2"]); + Assert.Equal(ModulesAction.Graph, graph.Action); + Assert.True(graph.Duplicates); + Assert.Equal("com.acme:core", graph.Invert); + Assert.Equal(2, graph.Depth); + + var diff = (ModulesCommand)CommandLine.Parse(["modules", "diff", "a.sqlite3", "b.sqlite3", "--format", "markdown"]); + Assert.Equal(ModulesAction.Diff, diff.Action); + Assert.Equal("markdown", diff.Format); + + var update = (UpdateCommand)CommandLine.Parse(["update", "--offline"]); + Assert.True(update.Offline); + Assert.False(update.Locked); + } + + [Fact] + public void ResolveVerifyExportGraphDepsExplainAndUpdateWorkEndToEnd() + { + var dir = CreateTempDir(); + try + { + File.WriteAllText(Path.Combine(dir, "MODULE.csx"), """ + using Progmasoft.Tazel.Dsl.Module.Prelude; + module = Module.Define(new() { Group = "com.example", Name = "app", Version = "1.0.0", License = "MIT" }); + """); + + var (resolveCode, _) = Run(dir, "modules", "resolve"); + Assert.Equal(0, resolveCode); + Assert.True(File.Exists(Path.Combine(dir, Lockfile.FileName))); + + var (verifyCode, _) = Run(dir, "modules", "verify"); + Assert.Equal(0, verifyCode); + + var (exportStdCode, exportJson) = Run(dir, "modules", "export", "--path", "-"); + Assert.Equal(0, exportStdCode); + Assert.Contains("\"rootGroup\": \"com.example\"", exportJson, StringComparison.Ordinal); + + var (exportFileCode, _) = Run(dir, "modules", "export"); + Assert.Equal(0, exportFileCode); + Assert.True(File.Exists(Path.Combine(dir, "LOCK.dump.json"))); + + var (missingDirCode, _) = Run(dir, "modules", "export", "--path", "no-such-dir/out.json"); + Assert.Equal(1, missingDirCode); + + var (graphCode, graphOut) = Run(dir, "modules", "graph", "--depth", "1"); + Assert.Equal(0, graphCode); + Assert.Contains("com.example:app@1.0.0", graphOut, StringComparison.Ordinal); + + var (depsCode, depsOut) = Run(dir, "modules", "deps", "com.example:app"); + Assert.Equal(0, depsCode); + Assert.Contains("com.example:app: (none)", depsOut, StringComparison.Ordinal); + + var (updateLockedCode, _) = Run(dir, "update", "--locked"); + Assert.Equal(1, updateLockedCode); + + var (updateCode, _) = Run(dir, "update"); + Assert.Equal(0, updateCode); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Fact] + public void DiffAndExplainDetectVersionAndShaChanges() + { + var dir = CreateTempDir(); + try + { + var shaA = new string('a', 64); + var shaB = new string('b', 64); + var docA = new LockDocument( + "0.5.0", "com.example", "app", "1.0.0", + [new LockRequest("com.acme", "core", "1.0.0", null, "portal-modules")], + [new LockModule("com.acme", "core", "1.0.0", null, "registry", "portal-modules", shaA, shaA, null)], + [new LockEdge("com.example", "app", "com.acme", "core", "1.0.0")]); + var docB = docA with + { + Modules = [docA.Modules[0] with { ArchiveSha256 = shaB }], + }; + + var pathA = Path.Combine(dir, "a.sqlite3"); + var pathB = Path.Combine(dir, "b.sqlite3"); + var rootLock = Path.Combine(dir, Lockfile.FileName); + Lockfile.Write(pathA, docA); + Lockfile.Write(pathB, docB); + Lockfile.Write(rootLock, docA); + + var (sameCode, _) = Run(dir, "modules", "diff", pathA, rootLock); + Assert.Equal(0, sameCode); + + var (shaDiffCode, shaDiffOut) = Run(dir, "modules", "diff", pathA, pathB); + Assert.Equal(1, shaDiffCode); + Assert.Contains("SHA-256", shaDiffOut, StringComparison.Ordinal); + + var (mdCode, mdOut) = Run(dir, "modules", "diff", pathA, pathB, "--format", "markdown"); + Assert.Equal(1, mdCode); + Assert.Contains("| changed | `com.acme:core` |", mdOut, StringComparison.Ordinal); + + var (explainCode, explainOut) = Run(dir, "modules", "explain", "com.acme:core"); + Assert.Equal(0, explainCode); + Assert.Contains("com.example:app -> com.acme:core", explainOut, StringComparison.Ordinal); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Fact] + public void MergeResolvesOneSidedAdditionsAndLeavesOursUntouchedOnConflict() + { + var dir = CreateTempDir(); + try + { + var sha = new string('c', 64); + var baseDoc = new LockDocument("0.5.0", "com.example", "app", "1.0.0", [], [], []); + var oursDoc = new LockDocument( + "0.5.0", "com.example", "app", "1.0.0", + [new LockRequest("com.acme", "a", "1.0.0", null, "portal-modules")], + [new LockModule("com.acme", "a", "1.0.0", null, "registry", "portal-modules", sha, sha, null)], + [new LockEdge("com.example", "app", "com.acme", "a", "1.0.0")]); + var theirsDoc = new LockDocument( + "0.5.0", "com.example", "app", "1.0.0", + [new LockRequest("com.acme", "b", "2.0.0", null, "portal-modules")], + [new LockModule("com.acme", "b", "2.0.0", null, "registry", "portal-modules", sha, sha, null)], + [new LockEdge("com.example", "app", "com.acme", "b", "2.0.0")]); + + var basePath = Path.Combine(dir, "base.sqlite3"); + var oursPath = Path.Combine(dir, "ours.sqlite3"); + var theirsPath = Path.Combine(dir, "theirs.sqlite3"); + Lockfile.Write(basePath, baseDoc); + Lockfile.Write(oursPath, oursDoc); + Lockfile.Write(theirsPath, theirsDoc); + + var (mergeCode, _) = Run(dir, "modules", "merge", basePath, oursPath, theirsPath); + Assert.Equal(0, mergeCode); + + var merged = Lockfile.Read(oursPath); + Assert.Equal(2, merged.Modules.Count); + + var conflictTheirs = new LockDocument( + "0.5.0", "com.example", "app", "1.0.0", + [new LockRequest("com.acme", "a", "2.0.0", null, "portal-modules")], + [new LockModule("com.acme", "a", "2.0.0", null, "registry", "portal-modules", sha, sha, null)], + [new LockEdge("com.example", "app", "com.acme", "a", "2.0.0")]); + Lockfile.Write(oursPath, oursDoc); + Lockfile.Write(theirsPath, conflictTheirs); + var originalBytes = File.ReadAllBytes(oursPath); + + var (conflictCode, _) = Run(dir, "modules", "merge", basePath, oursPath, theirsPath); + Assert.Equal(1, conflictCode); + Assert.Equal(originalBytes, File.ReadAllBytes(oursPath)); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Fact] + public void TidyRemovesUnusedDependenciesAndSortsWithRoslyn() + { + var dir = CreateTempDir(); + try + { + File.WriteAllText(Path.Combine(dir, "MODULE.csx"), """ + // Keep this header comment + using Progmasoft.Tazel.Dsl.Module.Prelude; + module = Module.Define(new() { Group = "com.example", Name = "app", Version = "1.0.0", License = "MIT" }); + dependencies = Dependencies.Define( + Module.From(new() { Group = "com.acme", Name = "zeta", Version = "1.0.0" }), + Module.From(new() { Group = "com.acme", Name = "unused", Version = "1.0.0" }), + Module.From(new() { Group = "com.acme", Name = "alpha", Version = "1.0.0" }) + ); + """); + File.WriteAllText(Path.Combine(dir, "BUILD.csx"), """ + var refs = new[] { "@zeta//:lib", "@alpha//:lib" }; + """); + + var (code, output) = Run(dir, "modules", "tidy"); + Assert.Equal(0, code); + Assert.Contains("1 unused dependency removed", output, StringComparison.Ordinal); + + var updated = File.ReadAllText(Path.Combine(dir, "MODULE.csx")); + Assert.Contains("// Keep this header comment", updated, StringComparison.Ordinal); + Assert.DoesNotContain("unused", updated, StringComparison.Ordinal); + Assert.True(updated.IndexOf("alpha", StringComparison.Ordinal) < updated.IndexOf("zeta", StringComparison.Ordinal)); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Fact] + public void ShellCompletionEscapesRegistryNamesAcrossAllFourShells() + { + Assert.Equal("corp-main", ShellCompletion.EscapeRegistryValue(ShellKind.Bash, "corp-main")); + Assert.Equal("'Title Case'", ShellCompletion.EscapeRegistryValue(ShellKind.Bash, "Title Case")); + Assert.Equal("'Team'\\''s $HOME'", ShellCompletion.EscapeRegistryValue(ShellKind.Bash, "Team's $HOME")); + + Assert.Equal("'Title Case'", ShellCompletion.EscapeRegistryValue(ShellKind.Zsh, "Title Case")); + Assert.Equal("'Team'\\''s Reg'", ShellCompletion.EscapeRegistryValue(ShellKind.Zsh, "Team's Reg")); + + Assert.Equal("'Title Case'", ShellCompletion.EscapeRegistryValue(ShellKind.Fish, "Title Case")); + Assert.Equal("'a\\\\b\\'c'", ShellCompletion.EscapeRegistryValue(ShellKind.Fish, "a\\b'c")); + + Assert.Equal("'Title Case'", ShellCompletion.EscapeRegistryValue(ShellKind.PowerShell, "Title Case")); + Assert.Equal("'Team''s Reg'", ShellCompletion.EscapeRegistryValue(ShellKind.PowerShell, "Team's Reg")); + Assert.Equal("'Türkçe Kayıt'", ShellCompletion.EscapeRegistryValue(ShellKind.PowerShell, "Türkçe Kayıt")); + + foreach (var shell in Enum.GetValues<ShellKind>()) + { + var script = ShellCompletion.Generate(shell); + Assert.Contains("modules", script, StringComparison.Ordinal); + Assert.Contains("update", script, StringComparison.Ordinal); + } + } +}