From 09f31782705675bea3041610e3c0375a0b26dd91 Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 12 Nov 2026 08:25:26 +0100 Subject: [PATCH 1/3] Run a dependency with the value it was declared with A dependency such as `Test { Filter = Some "Unit" }` or `new Test("Unit")` ran with the case's defaults in the union and F# surfaces, and with the named target's own arguments in the class and F# surfaces. Each surface now hands the planner a target source, and a run is planned as instances: a target and a value. Equal values run once, different values once each, and only the named target binds the command line. The union app's --version prints the entry assembly's informational version instead of 0.0.0. Co-Authored-By: Claude Opus 5.5 --- src/Nullean.Make.Fs/FsGraphBuilder.fs | 75 ++++++--- .../UnionCaseGenerator.cs | 10 +- src/Nullean.Make/Discovery/BuildGraph.cs | 3 + src/Nullean.Make/Discovery/BuildScanner.cs | 9 +- .../Discovery/ClassTargetSource.cs | 52 ++++++ .../Discovery/TargetBuilderImpl.cs | 14 +- src/Nullean.Make/Discovery/TargetNode.cs | 8 +- .../Execution/DepGraphExecutor.cs | 97 ++++------- src/Nullean.Make/Execution/ExecutionLog.cs | 20 +-- src/Nullean.Make/Execution/RunPlan.cs | 156 ++++++++++++++++++ src/Nullean.Make/Execution/TargetSource.cs | 64 +++++++ src/Nullean.Make/Execution/ValueDisplay.cs | 60 +++++++ src/Nullean.Make/ITargetRef.cs | 23 ++- src/Nullean.Make/MakeAppOfT.cs | 42 +---- src/Nullean.Make/MakeVersion.cs | 15 ++ src/Nullean.Make/UnionGraph/UnionCaseTable.cs | 11 ++ .../UnionGraph/UnionTargetBuilderImpl.cs | 49 +++--- .../UnionGraph/UnionTargetSource.cs | 35 ++++ .../DependencyValueTests.fs | 63 +++++++ tests/Nullean.Make.Fs.Tests/MakeAppTests.fs | 6 +- .../Nullean.Make.Fs.Tests.fsproj | 1 + .../DependencyValueTests.cs | 155 +++++++++++++++++ 22 files changed, 788 insertions(+), 180 deletions(-) create mode 100644 src/Nullean.Make/Discovery/ClassTargetSource.cs create mode 100644 src/Nullean.Make/Execution/RunPlan.cs create mode 100644 src/Nullean.Make/Execution/TargetSource.cs create mode 100644 src/Nullean.Make/Execution/ValueDisplay.cs create mode 100644 src/Nullean.Make/MakeVersion.cs create mode 100644 src/Nullean.Make/UnionGraph/UnionTargetSource.cs create mode 100644 tests/Nullean.Make.Fs.Tests/DependencyValueTests.fs create mode 100644 tests/Nullean.Make.Tests/DependencyValueTests.cs diff --git a/src/Nullean.Make.Fs/FsGraphBuilder.fs b/src/Nullean.Make.Fs/FsGraphBuilder.fs index b093ee5..2549335 100644 --- a/src/Nullean.Make.Fs/FsGraphBuilder.fs +++ b/src/Nullean.Make.Fs/FsGraphBuilder.fs @@ -5,6 +5,7 @@ open System open Microsoft.FSharp.Reflection open Nullean.Make open Nullean.Make.Discovery +open Nullean.Make.Execution let private toKebabCase = BuildScanner.ToKebabCase @@ -39,6 +40,51 @@ let private isStructuralNs (ci: UnionCaseInfo) = let fs = ci.GetFields() fs.Length = 1 && FSharpType.IsUnion(fs.[0].PropertyType) +/// The payload record of a case value, or null when the case carries none. A namespace sub-case carries no payload. +let private payloadOf (value: obj) : obj = + if isNull value then null + else + let ci, fields = FSharpValue.GetUnionFields(value, value.GetType()) + if fields.Length = 1 && FSharpType.IsRecord(ci.GetFields().[0].PropertyType) then fields.[0] else null + +/// The targets of an F# MakeApp: a node's value is the DU case value. `bind` runs again for each value, so a dependency +/// declared as `Test { Filter = Some "Unit" }` runs the body bind returns for that value. +type private FsTargetSource<'TCase when 'TCase : comparison and 'TCase : not null> + (bind: 'TCase -> Definition<'TCase>, + nodeCases: Collections.Generic.Dictionary, + resolve: TargetNode -> 'TCase -> TargetNode) = + + let refs (node: TargetNode) (deps: 'TCase list) = + deps |> List.map (fun d -> DepRef(resolve node d, box d)) |> ResizeArray + + interface Nullean.Make.Execution.ITargetSource with + member _.DefaultValue(node) = box (fst nodeCases.[node]) + + member _.BindArguments(node, args) = + let defaultValue, caseInfo = nodeCases.[node] + let fields = caseInfo.GetFields() + if fields.Length = 1 && FSharpType.IsRecord(fields.[0].PropertyType) then + FSharpValue.MakeUnion(caseInfo, [| FsDtoBinder.bind fields.[0].PropertyType args |]) + else box defaultValue + + member _.Describe(node, value) = + let spec = Nullean.Make.Execution.InstanceSpec() + let body (b: FsContext -> unit) = + Func(fun _ -> b sharedCtx; Threading.Tasks.Task.CompletedTask) + match bind (unbox<'TCase> value) with + | FsTarget(_, deps, b, _) -> + spec.Add(Nullean.Make.Execution.StageKind.Requires, refs node deps) + spec.Body <- body b + | FsCommand(_, requires, composes, b) -> + spec.Add(Nullean.Make.Execution.StageKind.Requires, refs node requires) + spec.Add(Nullean.Make.Execution.StageKind.Composes, refs node composes) + b |> Option.iter (fun b -> spec.Body <- body b) + | FsNamespace _ -> () + spec + + member _.FormatValue(node, value) = + Nullean.Make.Execution.ValueDisplay.Differences(payloadOf value, payloadOf (box (fst nodeCases.[node]))) + let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null> (appName: string) (appDescription: string option) @@ -93,6 +139,8 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null> ci.Name + "." + subCi.Name else ci.Name let caseToNode = Collections.Generic.Dictionary() + // Each node's default value, and the case whose payload a value of it carries. + let nodeCases = Collections.Generic.Dictionary(HashIdentity.Reference) // Register one TargetNode. caseInfoForBody drives the SyncBody closure shape. // For structural namespace sub-cases, caseInfoForBody is the sub-DU's UnionCaseInfo. @@ -116,27 +164,6 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null> elif kind = TargetKind.Command then "" else toKebabCase (Array.last route) let fields = caseInfoForBody.GetFields() - - let plainBody () = - match def with - | FsTarget(_, _, b, _) -> b sharedCtx - | FsCommand(_, _, _, Some b) -> b sharedCtx - | _ -> () - - // Re-binds CLI args at execution time and re-invokes bind for typed-payload cases. - let payloadBody () = - let payloadType = fields.[0].PropertyType - let targetArgs = - let ctx = MakeContext.Current - if obj.ReferenceEquals(ctx, null) then [||] else ctx.TargetArgs - let payload = FsDtoBinder.bind payloadType targetArgs - let boundCase : 'TCase = FSharpValue.MakeUnion(caseInfoForBody, [| payload |]) :?> 'TCase - match bind boundCase with - | FsTarget(_, _, b, _) -> b sharedCtx - | FsCommand(_, _, _, Some b) -> b sharedCtx - | _ -> () - - let syncBody = Action(if fields.Length = 0 then plainBody else payloadBody) let dtoType = if fields.Length = 1 && FSharpType.IsRecord(fields.[0].PropertyType) then fields.[0].PropertyType else null let node = @@ -146,12 +173,12 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null> Kind = kind, Hidden = (match def with FsTarget(_, _, _, true) -> true | _ -> false), Description = desc, - DtoType = dtoType, - SyncBody = syncBody) + DtoType = dtoType) graph.Targets.Add(node) graph.ByRoute.[String.concat "/" route] <- node caseToNode.[caseKey key] <- (node, key) + nodeCases.[node] <- (key, caseInfoForBody) // Second pass: create TargetNode for each non-namespace case. for caseInfo in cases do @@ -195,6 +222,8 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null> for dep in requires do node.RequiresResolved.Add(resolve node dep) for dep in composes do node.ComposesResolved.Add(resolve node dep) + graph.Source <- FsTargetSource<'TCase>(bind, nodeCases, (fun node dep -> resolve node dep)) + match defaultCase with | None -> () | Some d -> diff --git a/src/Nullean.Make.Generator/UnionCaseGenerator.cs b/src/Nullean.Make.Generator/UnionCaseGenerator.cs index 7ce1706..85deaff 100644 --- a/src/Nullean.Make.Generator/UnionCaseGenerator.cs +++ b/src/Nullean.Make.Generator/UnionCaseGenerator.cs @@ -80,7 +80,8 @@ private sealed record UnionTable(string HintName, string Source); foreach (var c in cases) sb.AppendLine($"\t\t\t\t\t{c},"); sb.AppendLine("\t\t\t\t},"); - sb.AppendLine("\t\t\t\tstatic u => Leaf(u.Value));"); + sb.AppendLine("\t\t\t\tstatic u => Leaf(u.Value),"); + sb.AppendLine("\t\t\t\tstatic u => LeafValue(u.Value));"); sb.AppendLine(); sb.AppendLine("\t\tprivate static global::System.Type? Leaf(object? value) => value switch"); sb.AppendLine("\t\t{"); @@ -89,6 +90,13 @@ private sealed record UnionTable(string HintName, string Source); sb.AppendLine($"\t\t\t{nested.ToDisplayString(Fqn)} inner => Leaf(inner.Value),"); sb.AppendLine("\t\t\t_ => value.GetType()"); sb.AppendLine("\t\t};"); + sb.AppendLine(); + sb.AppendLine("\t\tprivate static object? LeafValue(object? value) => value switch"); + sb.AppendLine("\t\t{"); + foreach (var nested in nestedUnions) + sb.AppendLine($"\t\t\t{nested.ToDisplayString(Fqn)} inner => LeafValue(inner.Value),"); + sb.AppendLine("\t\t\t_ => value"); + sb.AppendLine("\t\t};"); sb.AppendLine("\t}"); sb.AppendLine("}"); diff --git a/src/Nullean.Make/Discovery/BuildGraph.cs b/src/Nullean.Make/Discovery/BuildGraph.cs index 1402920..12b7025 100644 --- a/src/Nullean.Make/Discovery/BuildGraph.cs +++ b/src/Nullean.Make/Discovery/BuildGraph.cs @@ -20,5 +20,8 @@ internal sealed class BuildGraph public TargetNode? Default { get; set; } public string AppName { get; set; } = "make"; + + /// Resolves each target's dependencies and body for a value. Set by the surface that built the graph. + public Execution.ITargetSource? Source { get; set; } public string? AppDescription { get; set; } } diff --git a/src/Nullean.Make/Discovery/BuildScanner.cs b/src/Nullean.Make/Discovery/BuildScanner.cs index 3ca9665..2d51832 100644 --- a/src/Nullean.Make/Discovery/BuildScanner.cs +++ b/src/Nullean.Make/Discovery/BuildScanner.cs @@ -19,6 +19,7 @@ public static BuildGraph Scan(TBuild build) where TBuild : MakeBuild ScanTargets(build, typeof(TBuild), graph, Array.Empty()); ScanNestedNamespaces(typeof(TBuild), graph); ResolveDepGraph(graph); + graph.Source = new ClassTargetSource(graph); return graph; } @@ -169,15 +170,15 @@ private static void ResolveDepGraph(BuildGraph graph) { foreach (var node in graph.Targets) { - foreach (var method in node.Requires) + foreach (var reference in node.Requires) { - if (graph.ByMethod.TryGetValue(method, out var dep)) + if (graph.ByMethod.TryGetValue(reference.Method, out var dep)) node.RequiresResolved.Add(dep); } - foreach (var method in node.Composes) + foreach (var reference in node.Composes) { - if (graph.ByMethod.TryGetValue(method, out var dep)) + if (graph.ByMethod.TryGetValue(reference.Method, out var dep)) node.ComposesResolved.Add(dep); } } diff --git a/src/Nullean.Make/Discovery/ClassTargetSource.cs b/src/Nullean.Make/Discovery/ClassTargetSource.cs new file mode 100644 index 0000000..6b71fdb --- /dev/null +++ b/src/Nullean.Make/Discovery/ClassTargetSource.cs @@ -0,0 +1,52 @@ +using Nullean.Make.Execution; +using Nullean.Make.Parsing; + +namespace Nullean.Make.Discovery; + +/// The targets of a class: a node's value is its DTO, or null when it has none. +internal sealed class ClassTargetSource(BuildGraph graph) : ITargetSource +{ + public object? DefaultValue(TargetNode node) => node.DtoType is null ? null : DtoBinder.Bind(node.DtoType, []); + + public object? BindArguments(TargetNode node, string[] args) => node.DtoType is null ? null : DtoBinder.Bind(node.DtoType, args); + + public InstanceSpec Describe(TargetNode node, object? value) + { + var spec = new InstanceSpec { OnlyWhen = node.OnlyWhen }; + spec.Add(StageKind.Requires, Resolve(node.Requires)); + spec.Add(StageKind.Composes, Resolve(node.Composes)); + + if (node.TypedBody is { } typed && node.DtoType is not null) + spec.Body = _ => InvokeTyped(typed, value); + else if (node.AsyncBody is { } asyncBody) + spec.Body = _ => asyncBody(); + else if (node.SyncBody is { } syncBody) + spec.Body = _ => + { + syncBody(); + return Task.CompletedTask; + }; + return spec; + } + + public string? FormatValue(TargetNode node, object? value) => ValueDisplay.Differences(value, DefaultValue(node)); + + /// A reference to a delegate that is not a target of this build resolves to nothing, as it always has. + private List Resolve(List references) => + references.Where(r => graph.ByMethod.ContainsKey(r.Method)).Select(r => new DepRef(graph.ByMethod[r.Method], r.Value)).ToList(); + + /// Invokes an Action<T> or a Func<T, Task> body with the bound DTO. + private static Task InvokeTyped(Delegate body, object? value) + { + try + { + return body.DynamicInvoke(value) as Task ?? Task.CompletedTask; + } + catch (System.Reflection.TargetInvocationException ex) when (ex.InnerException is not null) + { + // Rethrow what the body threw, so a MakeException keeps its exit code and message. + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(ex.InnerException); + throw; + } + } +} diff --git a/src/Nullean.Make/Discovery/TargetBuilderImpl.cs b/src/Nullean.Make/Discovery/TargetBuilderImpl.cs index 4ca15dc..6953e1c 100644 --- a/src/Nullean.Make/Discovery/TargetBuilderImpl.cs +++ b/src/Nullean.Make/Discovery/TargetBuilderImpl.cs @@ -31,7 +31,7 @@ public ITargetBuilder OnlyWhen(Func condition) public ITargetBuilder DependsOn(params TargetRef[] refs) { foreach (var r in refs) - _node.Requires.Add(r.Method); + _node.Requires.Add(r); return this; } @@ -71,7 +71,7 @@ ICommandBuilder ICommandBuilder.OnlyWhen(Func c) ICommandBuilder ICommandBuilder.DependsOn(params TargetRef[] refs) { foreach (var r in refs) - _node.Requires.Add(r.Method); + _node.Requires.Add(r); return this; } @@ -89,14 +89,14 @@ ICommandBuilder ICommandBuilder.Executes(Func body) ICommandBuilder ICommandBuilder.Requires(params TargetRef[] refs) { foreach (var r in refs) - _node.Requires.Add(r.Method); + _node.Requires.Add(r); return this; } ICommandBuilder ICommandBuilder.Composes(params TargetRef[] refs) { foreach (var r in refs) - _node.Composes.Add(r.Method); + _node.Composes.Add(r); return this; } } @@ -135,7 +135,7 @@ public ITargetBuilder OnlyWhen(Func condition) public ITargetBuilder DependsOn(params TargetRef[] refs) { foreach (var r in refs) - _node.Requires.Add(r.Method); + _node.Requires.Add(r); return this; } public ITargetBuilder Executes(Action body) @@ -170,13 +170,13 @@ ITargetBuilder ITargetBuilder.Executes(Func body) ICommandBuilder ICommandBuilder.Requires(params TargetRef[] refs) { foreach (var r in refs) - _node.Requires.Add(r.Method); + _node.Requires.Add(r); return this; } ICommandBuilder ICommandBuilder.Composes(params TargetRef[] refs) { foreach (var r in refs) - _node.Composes.Add(r.Method); + _node.Composes.Add(r); return this; } } diff --git a/src/Nullean.Make/Discovery/TargetNode.cs b/src/Nullean.Make/Discovery/TargetNode.cs index 9917187..5b50c1e 100644 --- a/src/Nullean.Make/Discovery/TargetNode.cs +++ b/src/Nullean.Make/Discovery/TargetNode.cs @@ -21,11 +21,11 @@ internal sealed class TargetNode public Func? OnlyWhen { get; set; } public TargetKind Kind { get; set; } - /// DependsOn / Requires methods — skippable under -s. - public List Requires { get; } = new(); + /// DependsOn / Requires references — skippable under -s. + public List Requires { get; } = new(); - /// Composes methods — always run. - public List Composes { get; } = new(); + /// Composes references — always run. + public List Composes { get; } = new(); /// Sync body; null when async or not set. public Action? SyncBody { get; set; } diff --git a/src/Nullean.Make/Execution/DepGraphExecutor.cs b/src/Nullean.Make/Execution/DepGraphExecutor.cs index 8d6839f..bb2ca0b 100644 --- a/src/Nullean.Make/Execution/DepGraphExecutor.cs +++ b/src/Nullean.Make/Execution/DepGraphExecutor.cs @@ -5,28 +5,49 @@ namespace Nullean.Make.Execution; internal static class DepGraphExecutor { + /// Binds the named target's arguments, plans the run and executes it. public static async Task ExecuteAsync(TargetNode root, ParsedArgs parsed, BuildGraph graph) { - var plan = BuildPlan(root, parsed.SingleTarget); + var source = graph.Source ?? throw new InvalidOperationException("The graph has no target source."); + RunPlan plan; + try + { + var value = source.BindArguments(root, parsed.TargetArgs); + plan = RunPlan.Build([new DepRef(root, value)], source, new PlanOptions(parsed.SingleTarget)); + } + catch (MakeException ex) + { + Console.Error.WriteLine(ex.Message); + return ex.ExitCode; + } + return await ExecuteAsync(plan, parsed); + } + + public static async Task ExecuteAsync(RunPlan plan, ParsedArgs parsed) + { var context = new MakeContext(parsed.GlobalValues, parsed.SingleTarget) { TargetArgs = parsed.TargetArgs }; - foreach (var step in plan) + foreach (var step in plan.Instances) { + // A named command that only sequences other targets has nothing of its own to run. + if (step.IsRoot && step.Spec.Body is null) + continue; + var start = DateTime.UtcNow; ExecutionLog.Starting(step); MakeContext.Current = context; try { - await InvokeStep(step, parsed.TargetArgs); + await InvokeStep(step); } catch (MakeException ex) { - Console.Error.WriteLine($"[make] Target '{string.Join("/", step.Route)}' failed: {ex.Message}"); + Console.Error.WriteLine($"[make] Target '{string.Join("/", step.Node.Route)}' failed: {ex.Message}"); return ex.ExitCode; } catch (Exception ex) { - Console.Error.WriteLine($"[make] Target '{string.Join("/", step.Route)}' failed: {ex.Message}"); + Console.Error.WriteLine($"[make] Target '{string.Join("/", step.Node.Route)}' failed: {ex.Message}"); return 1; } finally @@ -39,73 +60,15 @@ public static async Task ExecuteAsync(TargetNode root, ParsedArgs parsed, B return 0; } - private static async Task InvokeStep(TargetNode step, string[] targetArgs) + private static async Task InvokeStep(TargetInstance step) { - if (step.OnlyWhen is not null && !step.OnlyWhen()) + if (step.Spec.OnlyWhen is not null && !step.Spec.OnlyWhen()) { ExecutionLog.Skipped(step); return; } - if (step.DtoType is not null && step.TypedBody is not null) - { - var dto = DtoBinder.Bind(step.DtoType, targetArgs); - // Invoke Action or Func - var bodyType = step.TypedBody.GetType(); - if (bodyType.IsGenericType) - { - var genDef = bodyType.GetGenericTypeDefinition(); - if (genDef == typeof(Func<,>) && bodyType.GetGenericArguments()[1] == typeof(Task)) - { - var task = (Task)step.TypedBody.DynamicInvoke(dto)!; - await task; - return; - } - } - step.TypedBody.DynamicInvoke(dto); - return; - } - - if (step.AsyncBody is not null) - { - await step.AsyncBody(); - return; - } - - step.SyncBody?.Invoke(); - } - - private static List BuildPlan(TargetNode root, bool singleTarget) - { - var plan = new List(); - var visited = new HashSet(); - - void AddNode(TargetNode node, bool isRoot) - { - if (!visited.Add(node)) - return; - - // Requires: skippable under -s (unless this is the root node itself) - if (!singleTarget || !isRoot) - { - foreach (var dep in node.RequiresResolved) - AddNode(dep, false); - } - - // Composes: always run - foreach (var dep in node.ComposesResolved) - AddNode(dep, false); - - plan.Add(node); - } - - AddNode(root, true); - - // Remove root if it has no body and is a pure command (only composes/requires) - // Keep it if it has a body - if (root.SyncBody is null && root.AsyncBody is null && root.TypedBody is null && plan[^1] == root) - plan.RemoveAt(plan.Count - 1); - - return plan; + if (step.Spec.Body is not null) + await step.Spec.Body(CancellationToken.None); } } diff --git a/src/Nullean.Make/Execution/ExecutionLog.cs b/src/Nullean.Make/Execution/ExecutionLog.cs index 25f9b6e..c9f23d0 100644 --- a/src/Nullean.Make/Execution/ExecutionLog.cs +++ b/src/Nullean.Make/Execution/ExecutionLog.cs @@ -1,25 +1,13 @@ using Nullean.Argh.Help; -using Nullean.Make.Discovery; namespace Nullean.Make.Execution; internal static class ExecutionLog { - public static void Starting(TargetNode node) - { - var name = CliHelpFormatting.Accent(string.Join(" ", node.Route)); - Console.WriteLine($"Starting {name}"); - } + public static void Starting(TargetInstance step) => Console.WriteLine($"Starting {CliHelpFormatting.Accent(step.Name)}"); - public static void Finished(TargetNode node, TimeSpan elapsed) - { - var name = CliHelpFormatting.Accent(string.Join(" ", node.Route)); - Console.WriteLine($"Finished {name} ({elapsed.TotalSeconds:F1}s)"); - } + public static void Finished(TargetInstance step, TimeSpan elapsed) => + Console.WriteLine($"Finished {CliHelpFormatting.Accent(step.Name)} ({elapsed.TotalSeconds:F1}s)"); - public static void Skipped(TargetNode node) - { - var name = CliHelpFormatting.Placeholder(string.Join(" ", node.Route)); - Console.WriteLine($"Skipped {name}"); - } + public static void Skipped(TargetInstance step) => Console.WriteLine($"Skipped {CliHelpFormatting.Placeholder(step.Name)}"); } diff --git a/src/Nullean.Make/Execution/RunPlan.cs b/src/Nullean.Make/Execution/RunPlan.cs new file mode 100644 index 0000000..cbfda54 --- /dev/null +++ b/src/Nullean.Make/Execution/RunPlan.cs @@ -0,0 +1,156 @@ +using Nullean.Make.Discovery; + +namespace Nullean.Make.Execution; + +/// Why a target in the plan does not run. +internal enum SkipReason +{ + /// -s skipped a gate of the named target. + SingleTarget, + + /// Its condition returned , so its body does not run. + Condition +} + +/// One target with one value in a run: it runs once, however many targets depend on it. +internal sealed class TargetInstance +{ + public required TargetNode Node { get; init; } + public required object? Value { get; init; } + public required InstanceSpec Spec { get; init; } + + /// The route, and the value when it is not the default: test (filter: Unit). + public required string Name { get; init; } + + /// Position in the plan. A prerequisite always comes earlier. + public int Order { get; set; } + + /// True for a target named on the command line. + public bool IsRoot { get; set; } + + /// Everything that has to finish before this instance starts: its stages, and what it waits for where it was first reached. + public List Prerequisites { get; } = new(); + + /// The stages as the plan resolved them, for drawing the plan. + public List Stages { get; } = new(); + + /// Set when the planner evaluated the condition and it returned . + public SkipReason? Skipped { get; set; } +} + +/// A stage of an instance with its items resolved. +internal sealed record PlannedStage(StageKind Kind, bool Parallel, IReadOnlyList Items); + +/// An item of a stage: the instance it runs, or the name of one the plan skips. +internal sealed record PlannedItem(TargetInstance? Instance, string Name, SkipReason? Skipped); + +/// Options that change which instances the plan contains. +internal sealed record PlanOptions(bool SingleTarget, bool EvaluateConditions = false); + +/// The instances a run contains, in an order that respects every prerequisite. +internal sealed class RunPlan +{ + public required IReadOnlyList Roots { get; init; } + public required IReadOnlyList Instances { get; init; } + + /// + /// Expands the named targets into instances. Each reference resolves to its node and value; a reference without a + /// value stands for the node's default value. A sequential stage's item waits for the item before it, and every + /// item waits for the stage before it, where the item is first reached. + /// + public static RunPlan Build(IReadOnlyList roots, ITargetSource source, PlanOptions options) + { + var builder = new Builder(source, options); + var rootInstances = new List(); + TargetInstance? previous = null; + foreach (var root in roots) + { + var instance = builder.Visit(root, isRoot: true, previous is null ? [] : [previous]); + instance.IsRoot = true; + rootInstances.Add(instance); + previous = instance; + } + return new RunPlan { Roots = rootInstances, Instances = builder.Ordered }; + } + + private sealed class Builder(ITargetSource source, PlanOptions options) + { + private readonly Dictionary<(TargetNode Node, object? Value), TargetInstance> _instances = new(); + private readonly Dictionary _defaults = new(); + private readonly List _stack = new(); + + public List Ordered { get; } = new(); + + private object? Resolve(DepRef reference) + { + if (reference.Value is not null) + return reference.Value; + if (!_defaults.TryGetValue(reference.Node, out var value)) + _defaults[reference.Node] = value = source.DefaultValue(reference.Node); + return value; + } + + public TargetInstance Visit(DepRef reference, bool isRoot, IReadOnlyList waitFor) + { + var value = Resolve(reference); + var key = (reference.Node, value); + + if (_instances.TryGetValue(key, out var existing)) + { + if (_stack.Contains(existing)) + { + var path = _stack.SkipWhile(i => i != existing).Select(i => i.Name).Append(existing.Name); + throw new MakeException($"Dependency cycle detected: {string.Join(" → ", path)}", 1); + } + return existing; + } + + var spec = source.Describe(reference.Node, value); + var instance = new TargetInstance + { + Node = reference.Node, + Value = value, + Spec = spec, + Name = ValueDisplay.Name(reference.Node, source.FormatValue(reference.Node, value)) + }; + _instances[key] = instance; + instance.Prerequisites.AddRange(waitFor); + + _stack.Add(instance); + IReadOnlyList barrier = []; + foreach (var stage in spec.Stages) + { + var items = new List(); + if (isRoot && options.SingleTarget && stage.Kind == StageKind.Requires) + { + foreach (var item in stage.Items) + items.Add(new PlannedItem(null, ValueDisplay.Name(item.Node, source.FormatValue(item.Node, Resolve(item))), SkipReason.SingleTarget)); + instance.Stages.Add(new PlannedStage(stage.Kind, stage.Parallel, items)); + continue; + } + + var reached = new List(); + TargetInstance? previous = null; + foreach (var item in stage.Items) + { + IReadOnlyList wait = stage.Parallel || previous is null ? barrier : [.. barrier, previous]; + var child = Visit(item, isRoot: false, wait); + items.Add(new PlannedItem(child, child.Name, null)); + reached.Add(child); + previous = child; + } + instance.Stages.Add(new PlannedStage(stage.Kind, stage.Parallel, items)); + instance.Prerequisites.AddRange(reached); + barrier = reached; + } + _stack.RemoveAt(_stack.Count - 1); + + if (options.EvaluateConditions && spec.OnlyWhen is { } condition && !condition()) + instance.Skipped = SkipReason.Condition; + + instance.Order = Ordered.Count; + Ordered.Add(instance); + return instance; + } + } +} diff --git a/src/Nullean.Make/Execution/TargetSource.cs b/src/Nullean.Make/Execution/TargetSource.cs new file mode 100644 index 0000000..4758b99 --- /dev/null +++ b/src/Nullean.Make/Execution/TargetSource.cs @@ -0,0 +1,64 @@ +using Nullean.Make.Discovery; + +namespace Nullean.Make.Execution; + +/// +/// What a surface (the union, the class, the F# DU) tells the +/// planner about its targets. A target runs as an instance: a and a value, the case record +/// or DTO it was named with. Two references to one node with equal values are one instance; with different values, +/// two. +/// +internal interface ITargetSource +{ + /// The value a reference without one stands for. null for a target that takes no arguments. + object? DefaultValue(TargetNode node); + + /// Binds the command-line tokens that followed the route into the node's value. + object? BindArguments(TargetNode node, string[] args); + + /// The instance's dependencies and body, for this value. + InstanceSpec Describe(TargetNode node, object? value); + + /// + /// How the value reads after the route, e.g. filter: Unit: the fields that differ from the default value. + /// null or empty when the value is the default. + /// + string? FormatValue(TargetNode node, object? value); +} + +/// Whether a stage is a gate that -s skips on the named target, or the work it always runs. +internal enum StageKind +{ + /// A target's dependencies, or a command's requires. Skipped on the named target under -s. + Requires, + + /// A command's composes. Always runs. + Composes +} + +/// A reference from one instance to another. A null value stands for the node's default value. +internal readonly record struct DepRef(TargetNode Node, object? Value); + +/// +/// One step in an instance's dependencies. A sequential stage runs its items in order; a parallel stage's items do +/// not wait for each other. Every item waits for the stage before it. +/// +internal sealed record Stage(StageKind Kind, bool Parallel, IReadOnlyList Items); + +/// What an instance needs before it runs, and what it runs. +internal sealed class InstanceSpec +{ + public List Stages { get; } = new(); + + /// The body, or null for a command that only sequences other targets. + public Func? Body { get; set; } + + /// When it returns , the body is skipped. Its dependencies still run. + public Func? OnlyWhen { get; set; } + + public void Add(StageKind kind, IReadOnlyList items, bool parallel = false) + { + if (items.Count > 0) + Stages.Add(new Stage(kind, parallel, items)); + } +} diff --git a/src/Nullean.Make/Execution/ValueDisplay.cs b/src/Nullean.Make/Execution/ValueDisplay.cs new file mode 100644 index 0000000..e8d79aa --- /dev/null +++ b/src/Nullean.Make/Execution/ValueDisplay.cs @@ -0,0 +1,60 @@ +using System.Collections; +using System.Globalization; +using Nullean.Make.Discovery; + +namespace Nullean.Make.Execution; + +/// Formats a target's value as the fields that differ from its default value: filter: Unit, retries: 2. +internal static class ValueDisplay +{ + public static string? Differences(object? value, object? defaults) + { + if (value is null || Equals(value, defaults)) + return null; + + var type = value.GetType(); + if (type.GetConstructors().Length == 0) + return null; + + var parts = new List(); + foreach (var option in DtoOptions.Describe(type)) + { + var property = type.GetProperties().FirstOrDefault( + p => string.Equals(p.Name.Replace("_", ""), option.Name.Replace("-", ""), StringComparison.OrdinalIgnoreCase) + ); + if (property is null || property.GetIndexParameters().Length > 0) + continue; + var current = property.GetValue(value); + var original = defaults is not null && defaults.GetType() == type ? property.GetValue(defaults) : null; + if (Equals(current, original)) + continue; + parts.Add($"{option.Name}: {Format(current)}"); + } + return parts.Count == 0 ? null : string.Join(", ", parts); + } + + /// A value as a user wrote it: F# Some x as x, None and null as none, lists comma-separated. + internal static string Format(object? value) + { + switch (value) + { + case null: + return "none"; + case string s: + return s; + case IFormattable f: + return f.ToString(null, CultureInfo.InvariantCulture); + } + + var type = value.GetType(); + if (type.IsGenericType && type.GetGenericTypeDefinition().Name == "FSharpOption`1") + return Format(type.GetProperty("Value")!.GetValue(value)); + if (value is IEnumerable items) + return string.Join(",", items.Cast().Select(Format)); + return value.ToString() ?? ""; + } + + /// The route as typed, with the value after it in parentheses when it is not the default. + public static string Name(TargetNode node, string? value) => + string.IsNullOrEmpty(value) ? string.Join(" ", node.Route) : $"{string.Join(" ", node.Route)} ({value})"; +} diff --git a/src/Nullean.Make/ITargetRef.cs b/src/Nullean.Make/ITargetRef.cs index a421077..04f818d 100644 --- a/src/Nullean.Make/ITargetRef.cs +++ b/src/Nullean.Make/ITargetRef.cs @@ -11,8 +11,29 @@ public readonly struct TargetRef { internal MethodInfo Method { get; } - internal TargetRef(MethodInfo m) => Method = m; + /// The value the target runs with, or null for its default value. + internal object? Value { get; } + + internal TargetRef(MethodInfo m, object? value = null) + { + Method = m; + Value = value; + } /// Accepts any target or command delegate. Identity is the underlying . public static implicit operator TargetRef(Delegate d) => new(d.Method); } + +/// Names a target with typed arguments together with the value it runs with. +public static class TargetRefExtensions +{ + /// + /// A dependency on that runs it with : + /// .DependsOn(Test.With(new("Unit"))). Two references with equal values run the target once; with different + /// values, once each. + /// + public static TargetRef With(this Target target, T value) => new(target.Method, value); + + /// + public static TargetRef With(this Command command, T value) => new(command.Method, value); +} diff --git a/src/Nullean.Make/MakeAppOfT.cs b/src/Nullean.Make/MakeAppOfT.cs index b6e4b1b..389c266 100644 --- a/src/Nullean.Make/MakeAppOfT.cs +++ b/src/Nullean.Make/MakeAppOfT.cs @@ -128,6 +128,7 @@ public async Task RunAsync(string[] args) BuildGraph(UnionCaseTable.Required); ResolveRouteDeps(); GraphValidator.Validate(_graph); + _graph.Source = new UnionTargetSource(_bind, _caseByNode, ResolveCase); } catch (MakeException ex) { @@ -160,7 +161,7 @@ public async Task RunAsync(string[] args) if (showVersion) { - Console.WriteLine("0.0.0"); + Console.WriteLine(MakeVersion.OfEntryAssembly()); return 0; } @@ -198,9 +199,6 @@ public async Task RunAsync(string[] args) return 2; } - // Wire up execution lambdas for every node (root gets real args, deps get empty args) - WireExecutionBodies(targetNode, targetArgs); - var parsed = new ParsedArgs { Target = targetNode, TargetArgs = targetArgs, SingleTarget = singleTarget, }; return await DepGraphExecutor.ExecuteAsync(targetNode, parsed, _graph); @@ -224,8 +222,8 @@ private void BuildGraph(IReadOnlyList> cases) Description = builder.DescriptionValue ?? Docs.DocDescriptions.ForType(path.CaseType), }; node.Hidden = builder.IsHidden; - node.RouteRequires.AddRange(builder.DepTypeNames); - node.RouteComposes.AddRange(builder.CompTypeNames); + node.RouteRequires.AddRange(builder.Deps.Select(d => d.TypeName)); + node.RouteComposes.AddRange(builder.Comps.Select(d => d.TypeName)); _graph.Targets.Add(node); _caseByNode[node] = path; @@ -236,47 +234,23 @@ private void BuildGraph(IReadOnlyList> cases) private void ResolveRouteDeps() { - var map = _typeNameToRoute!; foreach (var node in _graph.Targets) { foreach (var depName in node.RouteRequires) - node.RequiresResolved.Add(ResolveCase(node, depName, map)); + node.RequiresResolved.Add(ResolveCase(node, depName)); foreach (var compName in node.RouteComposes) - node.ComposesResolved.Add(ResolveCase(node, compName, map)); + node.ComposesResolved.Add(ResolveCase(node, compName)); } } - private TargetNode ResolveCase(TargetNode from, string caseTypeName, Dictionary map) + private TargetNode ResolveCase(TargetNode from, string caseTypeName) { - if (map.TryGetValue(caseTypeName, out var r) && _graph.ByRoute.TryGetValue(r, out var target)) + if (_typeNameToRoute!.TryGetValue(caseTypeName, out var r) && _graph.ByRoute.TryGetValue(r, out var target)) return target; var name = caseTypeName.Length == 0 ? "an empty union value" : $"'{caseTypeName}'"; throw new MakeException($"Target '{string.Join("/", from.Route)}' depends on {name}, which is not a case of {typeof(TUnion).Name}.", 1); } - /// - /// Sets AsyncBody on every node in the dependency plan. - /// The root gets real ; dep nodes get empty args (their - /// case DTOs are constructed with defaults, so their Executes closures see default values). - /// - private void WireExecutionBodies(TargetNode root, string[] targetArgs) - { - foreach (var node in _graph.Targets) - { - var n = node; - var args = ReferenceEquals(n, root) ? targetArgs : Array.Empty(); - n.AsyncBody = async () => - { - if (_bind is null || n.DtoType is null) - return; - var caseInstance = Parsing.DtoBinder.Bind(n.DtoType, args); - var realUnion = _caseByNode[n].Wrap(caseInstance); - var builder2 = (UnionTargetBuilderImpl)_bind!(realUnion); - await builder2.ExecuteAsync(); - }; - } - } - // ── Argv helpers ────────────────────────────────────────────────────────── private (string[] remaining, bool single, bool help, bool version) ExtractGlobals(string[] argv) diff --git a/src/Nullean.Make/MakeVersion.cs b/src/Nullean.Make/MakeVersion.cs new file mode 100644 index 0000000..c86808c --- /dev/null +++ b/src/Nullean.Make/MakeVersion.cs @@ -0,0 +1,15 @@ +using System.Reflection; + +namespace Nullean.Make; + +internal static class MakeVersion +{ + /// The informational version of the build script's assembly, as Argh's own --version prints it. + public static string OfEntryAssembly(Assembly? fallback = null) + { + var assembly = Assembly.GetEntryAssembly() ?? fallback; + if (assembly is null) + return "0.0.0"; + return assembly.GetCustomAttribute()?.InformationalVersion ?? assembly.GetName().Version?.ToString() ?? "0.0.0"; + } +} diff --git a/src/Nullean.Make/UnionGraph/UnionCaseTable.cs b/src/Nullean.Make/UnionGraph/UnionCaseTable.cs index 5a30f5b..616ad9f 100644 --- a/src/Nullean.Make/UnionGraph/UnionCaseTable.cs +++ b/src/Nullean.Make/UnionGraph/UnionCaseTable.cs @@ -19,6 +19,7 @@ public static class UnionCaseTable { internal static IReadOnlyList>? Cases { get; private set; } internal static Func? LeafType { get; private set; } + internal static Func? LeafValue { get; private set; } /// Called by generated code. returns the innermost case type of a union value. public static void Register(UnionCase[] cases, Func leafType) @@ -27,6 +28,16 @@ public static void Register(UnionCase[] cases, Func leafT LeafType = leafType; } + /// + /// Called by generated code. returns the innermost case type of a union value, and + /// the innermost case value itself. + /// + public static void Register(UnionCase[] cases, Func leafType, Func leafValue) + { + Register(cases, leafType); + LeafValue = leafValue; + } + internal static IReadOnlyList> Required => Cases ?? throw new MakeException( diff --git a/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs b/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs index 662e8e4..1b11e81 100644 --- a/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs +++ b/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs @@ -8,6 +8,9 @@ namespace Nullean.Make.UnionGraph; /// calls app.Bind twice: at graph-build time /// (reads Kind/Description/DepTypeNames) and at execution time (reads SyncBody/AsyncBody). /// +/// A dependency on a union case: its case type name, and the case value, or null for the default one. +internal readonly record struct CaseRef(string TypeName, object? Value); + internal sealed class UnionTargetBuilderImpl : IUnionTargetBuilder { private string? _description; @@ -15,8 +18,8 @@ internal sealed class UnionTargetBuilderImpl : IUnionTargetBuilder? _asyncBody; private readonly TargetKind _kind; - private readonly List _depTypeNames = new(); - private readonly List _compTypeNames = new(); + private readonly List _deps = new(); + private readonly List _comps = new(); internal UnionTargetBuilderImpl(TargetKind kind = TargetKind.Target) => _kind = kind; @@ -46,50 +49,50 @@ public IUnionTargetBuilder Executes(Func body) public IUnionTargetBuilder DependsOn(params TUnion[] deps) { foreach (var dep in deps) - _depTypeNames.Add(GetLeafCaseName(dep)); + _deps.Add(ToRef(dep)); return this; } public IUnionTargetBuilder DependsOn() { - _depTypeNames.Add(typeof(T1).Name); + _deps.Add(new CaseRef(typeof(T1).Name, null)); return this; } public IUnionTargetBuilder DependsOn() { - _depTypeNames.Add(typeof(T1).Name); - _depTypeNames.Add(typeof(T2).Name); + _deps.Add(new CaseRef(typeof(T1).Name, null)); + _deps.Add(new CaseRef(typeof(T2).Name, null)); return this; } public IUnionTargetBuilder DependsOn() { - _depTypeNames.Add(typeof(T1).Name); - _depTypeNames.Add(typeof(T2).Name); - _depTypeNames.Add(typeof(T3).Name); + _deps.Add(new CaseRef(typeof(T1).Name, null)); + _deps.Add(new CaseRef(typeof(T2).Name, null)); + _deps.Add(new CaseRef(typeof(T3).Name, null)); return this; } public IUnionTargetBuilder DependsOn() { - _depTypeNames.Add(typeof(T1).Name); - _depTypeNames.Add(typeof(T2).Name); - _depTypeNames.Add(typeof(T3).Name); - _depTypeNames.Add(typeof(T4).Name); + _deps.Add(new CaseRef(typeof(T1).Name, null)); + _deps.Add(new CaseRef(typeof(T2).Name, null)); + _deps.Add(new CaseRef(typeof(T3).Name, null)); + _deps.Add(new CaseRef(typeof(T4).Name, null)); return this; } public IUnionTargetBuilder Composes(params TUnion[] targets) { foreach (var t in targets) - _compTypeNames.Add(GetLeafCaseName(t)); + _comps.Add(ToRef(t)); return this; } public IUnionTargetBuilder Composes() { - _compTypeNames.Add(typeof(T1).Name); + _comps.Add(new CaseRef(typeof(T1).Name, null)); return this; } @@ -100,8 +103,8 @@ public IUnionTargetBuilder Composes() internal bool IsHidden => _hidden; internal Action? SyncBody => _syncBody; internal Func? AsyncBody => _asyncBody; - internal IReadOnlyList DepTypeNames => _depTypeNames; - internal IReadOnlyList CompTypeNames => _compTypeNames; + internal IReadOnlyList Deps => _deps; + internal IReadOnlyList Comps => _comps; internal async Task ExecuteAsync() { @@ -111,7 +114,13 @@ internal async Task ExecuteAsync() _syncBody?.Invoke(); } - /// The innermost case type name of a union value, flat or nested, from the generated case table. - private static string GetLeafCaseName(TUnion dep) => - (UnionCaseTable.LeafType ?? throw new MakeException($"No case table was generated for {typeof(TUnion).Name}.", 1))(dep)?.Name ?? ""; + /// + /// The innermost case of a union value, flat or nested, from the generated case table: its type name, and the case + /// value the dependency runs with. + /// + private static CaseRef ToRef(TUnion dep) + { + var leafType = UnionCaseTable.LeafType ?? throw new MakeException($"No case table was generated for {typeof(TUnion).Name}.", 1); + return new CaseRef(leafType(dep)?.Name ?? "", UnionCaseTable.LeafValue?.Invoke(dep)); + } } diff --git a/src/Nullean.Make/UnionGraph/UnionTargetSource.cs b/src/Nullean.Make/UnionGraph/UnionTargetSource.cs new file mode 100644 index 0000000..a851639 --- /dev/null +++ b/src/Nullean.Make/UnionGraph/UnionTargetSource.cs @@ -0,0 +1,35 @@ +using Nullean.Make.Discovery; +using Nullean.Make.Execution; +using Nullean.Make.Parsing; + +namespace Nullean.Make.UnionGraph; + +/// +/// The targets of a : a node's value is its case record. Bind runs again for each +/// value, so a dependency declared as new Test("Unit") runs the body Bind returns for that case. +/// +internal sealed class UnionTargetSource( + Func> bind, + IReadOnlyDictionary> cases, + Func resolve +) : ITargetSource where TUnion : struct +{ + public object? DefaultValue(TargetNode node) => Leaf(cases[node].CreateDefault()); + + public object? BindArguments(TargetNode node, string[] args) => DtoBinder.Bind(cases[node].CaseType, args); + + public InstanceSpec Describe(TargetNode node, object? value) + { + var builder = (UnionTargetBuilderImpl)bind(value is null ? cases[node].CreateDefault() : cases[node].Wrap(value)); + var spec = new InstanceSpec(); + spec.Add(StageKind.Requires, builder.Deps.Select(d => new DepRef(resolve(node, d.TypeName), d.Value)).ToList()); + spec.Add(StageKind.Composes, builder.Comps.Select(d => new DepRef(resolve(node, d.TypeName), d.Value)).ToList()); + if (builder.SyncBody is not null || builder.AsyncBody is not null) + spec.Body = _ => builder.ExecuteAsync(); + return spec; + } + + public string? FormatValue(TargetNode node, object? value) => ValueDisplay.Differences(value, DefaultValue(node)); + + private static object? Leaf(TUnion value) => UnionCaseTable.LeafValue?.Invoke(value); +} diff --git a/tests/Nullean.Make.Fs.Tests/DependencyValueTests.fs b/tests/Nullean.Make.Fs.Tests/DependencyValueTests.fs new file mode 100644 index 0000000..b825e13 --- /dev/null +++ b/tests/Nullean.Make.Fs.Tests/DependencyValueTests.fs @@ -0,0 +1,63 @@ +module Nullean.Make.Fs.Tests.DependencyValueTests + +open System +open System.IO +open TUnit.Core +open Nullean.Make.Fs + +type SuiteOptions = { Filter: string option } + +type Valued = + | Suite of SuiteOptions + | Gate of SuiteOptions + | Split + | Twice + +type private Run = { ExitCode: int; Log: string list; Stdout: string; Stderr: string } + +let private run (args: string list) = + let log = ResizeArray() + let app = MakeApp("build", None) + app.Bind <| function + | Suite o -> target [] { log.Add $"suite:%A{o.Filter}" } + // Gate takes the same --filter as Suite; its dependency on Suite names no filter. + | Gate o -> target [Suite { Filter = None }] { log.Add $"gate:%A{o.Filter}" } + | Split -> command { composes [Suite { Filter = Some "Unit" }; Suite { Filter = Some "Integration" }] } + | Twice -> command { composes [Suite { Filter = Some "Unit" }; Suite { Filter = Some "Unit" }] } + let stdout, stderr = new StringWriter(), new StringWriter() + let oldOut, oldErr = Console.Out, Console.Error + Console.SetOut stdout + Console.SetError stderr + try + let exit = app.RunAsync(List.toArray args).GetAwaiter().GetResult() + { ExitCode = exit; Log = List.ofSeq log; Stdout = string stdout; Stderr = string stderr } + finally + Console.SetOut oldOut + Console.SetError oldErr + +[] +type DependencyValueTests() = + + [] + member _.``Two references with different values run the target once each``() = + let r = run ["split"] + Assert.Equal(0, r.ExitCode) + Assert.Equal([ "suite:Some \"Unit\""; "suite:Some \"Integration\"" ], r.Log) + + [] + member _.``Two references with equal values run the target once``() = + let r = run ["twice"] + Assert.Equal(0, r.ExitCode) + Assert.Equal([ "suite:Some \"Unit\"" ], r.Log) + + [] + member _.``The named target's arguments do not reach its dependencies``() = + let r = run ["gate"; "--filter"; "Smoke"] + Assert.Equal(0, r.ExitCode) + Assert.Equal([ "suite:None"; "gate:Some \"Smoke\"" ], r.Log) + + [] + member _.``The log names a dependency by its value``() = + let r = run ["split"] + Assert.Contains("suite (filter: Unit)", r.Stdout) + Assert.Contains("suite (filter: Integration)", r.Stdout) diff --git a/tests/Nullean.Make.Fs.Tests/MakeAppTests.fs b/tests/Nullean.Make.Fs.Tests/MakeAppTests.fs index c846110..74013c9 100644 --- a/tests/Nullean.Make.Fs.Tests/MakeAppTests.fs +++ b/tests/Nullean.Make.Fs.Tests/MakeAppTests.fs @@ -55,7 +55,7 @@ let private standard (app: MakeApp) (log: ResizeArray) = | Pkg Generate -> Make.target [] "" <| fun _ -> log.Add "pkg-generate" | Pkg PkgTarget.Validate -> Make.target [] "" <| fun _ -> log.Add "pkg-validate" | Release -> Make.command [Test { Filter = None; Retries = None }] [Pkg Generate; Pkg PkgTarget.Validate] - // A dependency with a non-default payload must still resolve to the Test target. + // A dependency with a non-default payload resolves to the Test target and runs it with that payload. | Focused -> Make.command [Test { Filter = Some "Unit"; Retries = Some 2 }] [] let private okExit (r: Run) = @@ -102,10 +102,10 @@ type MakeAppTests() = Assert.Equal(["clean"; "build:Release:1:Low:dry=False"; "test:None:None"; "pkg-generate"; "pkg-validate"], r.Log) [] - member _.``Dependency with a non default payload resolves``() = + member _.``Dependency with a non default payload runs with that payload``() = let r = runApp standard ["focused"] okExit r - Assert.Contains("test:None:None", r.Log) + Assert.Contains("test:Some \"Unit\":Some 2", r.Log) [] member _.``Namespace help lists the namespace targets``() = diff --git a/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj b/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj index afab900..97a1c3d 100644 --- a/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj +++ b/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj @@ -14,6 +14,7 @@ + diff --git a/tests/Nullean.Make.Tests/DependencyValueTests.cs b/tests/Nullean.Make.Tests/DependencyValueTests.cs new file mode 100644 index 0000000..d56b134 --- /dev/null +++ b/tests/Nullean.Make.Tests/DependencyValueTests.cs @@ -0,0 +1,155 @@ +using AwesomeAssertions; + +namespace Nullean.Make.Tests; + +public record class Suite(string Filter = ""); + +public record class Gate(string Filter = ""); + +public record class Split; + +public record class Twice; + +public union Valued(Suite, Gate, Split, Twice); + +/// A dependency's value is part of its identity: equal values run once, different values once each. +[NotInParallel] +public class DependencyValueTests +{ + private sealed record Run(int ExitCode, IReadOnlyList Log, string Stdout, string Stderr); + + private static async Task RunAsync(params string[] args) + { + var log = new List(); + var app = new MakeApp("build"); + app.Bind( + v => + v.Value switch + { + Suite s => app.Target(() => log.Add($"suite:{s.Filter}")), + // Gate takes the same --filter as Suite; its dependency on Suite names no filter. + Gate g => app.Target([new Suite()], () => log.Add($"gate:{g.Filter}")), + Split => app.Command([], [new Suite("Unit"), new Suite("Integration")]), + Twice => app.Command([], [new Suite("Unit"), new Suite("Unit")]), + _ => throw new InvalidOperationException($"unmapped case {v.Value}") + } + ); + var (stdout, stderr) = (new StringWriter(), new StringWriter()); + var (oldOut, oldErr) = (Console.Out, Console.Error); + Console.SetOut(stdout); + Console.SetError(stderr); + try + { + var exit = await app.RunAsync(args); + return new Run(exit, log, stdout.ToString(), stderr.ToString()); + } + finally + { + Console.SetOut(oldOut); + Console.SetError(oldErr); + } + } + + [Test] + public async Task Two_references_with_different_values_run_the_target_once_each() + { + var run = await RunAsync("split"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("suite:Unit", "suite:Integration"); + } + + [Test] + public async Task Two_references_with_equal_values_run_the_target_once() + { + var run = await RunAsync("twice"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("suite:Unit"); + } + + [Test] + public async Task The_named_targets_arguments_do_not_reach_its_dependencies() + { + var run = await RunAsync("gate", "--filter", "Smoke"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("suite:", "gate:Smoke"); + } + + [Test] + public async Task Version_prints_the_informational_version_of_the_entry_assembly() + { + var run = await RunAsync("--version"); + var expected = System + .Reflection + .CustomAttributeExtensions + .GetCustomAttribute(System.Reflection.Assembly.GetEntryAssembly()!)!.InformationalVersion; + run.Stdout.Trim().Should().Be(expected).And.NotBe("0.0.0"); + } + + [Test] + public async Task The_log_names_a_dependency_by_its_value() + { + var run = await RunAsync("split"); + run.Stdout.Should().Contain("suite (filter: Unit)").And.Contain("suite (filter: Integration)"); + } +} + +public record class SuiteOptions(string Filter = ""); + +public class ValuedBuild : MakeBuild +{ + public static List Log { get; } = new(); + + public Target Suite => _ => _.Executes(o => Log.Add($"suite:{o.Filter}")); + + public Command Split => _ => _.Composes(Suite.With(new("Unit")), Suite.With(new("Integration"))); + + public Command Twice => _ => _.Composes(Suite.With(new("Unit")), Suite.With(new("Unit"))); + + public Target Gate => _ => _.DependsOn(Suite).Executes(o => Log.Add($"gate:{o.Filter}")); +} + +[NotInParallel] +public class ClassDependencyValueTests +{ + private static async Task<(int Exit, List Log)> RunAsync(params string[] args) + { + ValuedBuild.Log.Clear(); + var (oldOut, oldErr) = (Console.Out, Console.Error); + Console.SetOut(new StringWriter()); + Console.SetError(new StringWriter()); + try + { + var exit = await MakeApp.Execute(args); + return (exit, [.. ValuedBuild.Log]); + } + finally + { + Console.SetOut(oldOut); + Console.SetError(oldErr); + } + } + + [Test] + public async Task With_runs_the_target_with_that_value() + { + var (exit, log) = await RunAsync("split"); + exit.Should().Be(0); + log.Should().Equal("suite:Unit", "suite:Integration"); + } + + [Test] + public async Task Equal_values_run_once() + { + var (exit, log) = await RunAsync("twice"); + exit.Should().Be(0); + log.Should().Equal("suite:Unit"); + } + + [Test] + public async Task The_named_targets_arguments_do_not_reach_its_dependencies() + { + var (exit, log) = await RunAsync("gate", "--filter", "Smoke"); + exit.Should().Be(0); + log.Should().Equal("suite:", "gate:Smoke"); + } +} From c226611bcf5c937811b7e9ebd9d1be70362efb5a Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 12 Nov 2026 08:30:27 +0100 Subject: [PATCH 2/3] Document that a dependency runs with the value it names Co-Authored-By: Claude Opus 5.5 --- src/Nullean.Make.Fs/README.md | 2 +- src/Nullean.Make/README.md | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Nullean.Make.Fs/README.md b/src/Nullean.Make.Fs/README.md index 6d7ec28..7547d56 100644 --- a/src/Nullean.Make.Fs/README.md +++ b/src/Nullean.Make.Fs/README.md @@ -142,7 +142,7 @@ A case whose payload is another DU becomes a CLI namespace: `Pkg of PkgTarget` g ## Per-target typed arguments -A case with a record payload binds the record's fields from CLI flags at execution time: `Test of TestOptions` with `{ Filter: string option }` takes `--filter`. A dependency can name any value of the case: `Test { Filter = Some "Unit" }` resolves to the `test` target. +A case with a record payload binds the record's fields from CLI flags: `Test of TestOptions` with `{ Filter: string option }` takes `--filter`. A dependency can name any value of the case: `Test { Filter = Some "Unit" }` runs the `test` target with that value. Two dependencies with equal values run the target once, and with different values once each. Only the target named on the command line binds the command line's flags. ### Positional arguments, forwarded arguments and `--name=value` diff --git a/src/Nullean.Make/README.md b/src/Nullean.Make/README.md index bf3f8b1..8599957 100644 --- a/src/Nullean.Make/README.md +++ b/src/Nullean.Make/README.md @@ -81,6 +81,10 @@ union Target(Clean, Build, Test, Pack, Release); A case record's primary-constructor parameters become the target's flags: `Test(string? Filter = null)` takes `--filter`. +A dependency can name a value: `app.Target([new Test("Unit")], ...)` runs `test` with `Filter = "Unit"`. Two +dependencies with equal values run the target once, and with different values once each. Only the target named on the +command line binds the command line's flags. + `Bind` runs twice per case: once when the app reads the graph, with each parameter at its default (`default` when it has none, such as `Deploy(string Environment)`), and once when the target runs, with the parsed flags. Keep side effects inside the target body. The package's source generator finds each `new MakeApp(...)` and records the union's cases at build time, so the app reads no union by reflection. A `MakeApp` created only through a type parameter has no case table and exits `1` with an error. @@ -164,7 +168,7 @@ and [just](https://argh.nullean.net/make/just). ## Class-based targets -`MakeApp.Execute(args)` discovers targets from a `MakeBuild` class instead: `Target` properties, `[Flag]` and `[GlobalOption]` properties, and nested `Namespace` classes. [`build.cs`](https://github.com/nullean/argh/blob/main/build.cs) in this repository is a complete example. +`MakeApp.Execute(args)` discovers targets from a `MakeBuild` class instead: `Target` properties, `[Flag]` and `[GlobalOption]` properties, and nested `Namespace` classes. A dependency on a `Target` names its value with `With`: `.DependsOn(Test.With(new("Unit")))`. [`build.cs`](https://github.com/nullean/argh/blob/main/build.cs) in this repository is a complete example. For F#, see [`Nullean.Make.Fs`](https://www.nuget.org/packages/Nullean.Make.Fs). From e0902b67a6c56a598718079ccc0b0d5a359ce4d8 Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 12 Nov 2026 08:30:12 +0100 Subject: [PATCH 3/3] Draw the plan with --graph, and list the run order in target help `--graph` plans the run as the target would, with its arguments bound, `-s` applied and conditions evaluated, then draws it and runs nothing. Skipped targets show with the reason. It draws a tree with the run order below it, a Mermaid flowchart or JSON. A target's help lists the order its dependencies run in. Co-Authored-By: Claude Opus 5.5 --- docs/_docset.yml | 1 + docs/make/graph.md | 76 +++++ docs/make/index.md | 3 + src/Nullean.Make.Fs/MakeApp.fs | 14 +- src/Nullean.Make.Fs/README.md | 13 + .../Execution/DepGraphExecutor.cs | 30 +- src/Nullean.Make/Execution/PlanRenderer.cs | 308 ++++++++++++++++++ src/Nullean.Make/Execution/RunPlan.cs | 12 +- src/Nullean.Make/Help/MakeHelpPrinter.cs | 27 ++ src/Nullean.Make/MakeApp.cs | 2 + src/Nullean.Make/MakeAppOfT.cs | 17 +- src/Nullean.Make/Parsing/ArgvParser.cs | 8 + src/Nullean.Make/README.md | 13 + tests/Nullean.Make.Fs.Tests/GraphTests.fs | 66 ++++ .../Nullean.Make.Fs.Tests.fsproj | 1 + tests/Nullean.Make.Tests/GraphTests.cs | 177 ++++++++++ 16 files changed, 755 insertions(+), 13 deletions(-) create mode 100644 docs/make/graph.md create mode 100644 src/Nullean.Make/Execution/PlanRenderer.cs create mode 100644 tests/Nullean.Make.Fs.Tests/GraphTests.fs create mode 100644 tests/Nullean.Make.Tests/GraphTests.cs diff --git a/docs/_docset.yml b/docs/_docset.yml index 6c37f89..393d2a0 100644 --- a/docs/_docset.yml +++ b/docs/_docset.yml @@ -49,6 +49,7 @@ toc: - folder: make children: - file: index.md + - file: graph.md - file: wrappers.md - file: mise.md - file: makefile.md diff --git a/docs/make/graph.md b/docs/make/graph.md new file mode 100644 index 0000000..7207a9b --- /dev/null +++ b/docs/make/graph.md @@ -0,0 +1,76 @@ +# Drawing the plan + +`--graph` draws what a run would do, and runs nothing. It plans the run exactly as the target would: it binds the +target's arguments, applies `-s`, and evaluates each `OnlyWhen` condition. A target the run would skip shows as skipped, +with the reason. + +```bash +./build.cs release --graph +``` + +```text +release Test, then pack +├─ requires +│ ├─ pristine-check +│ └─ test +│ └─ build +│ └─ clean +└─ composes + ├─ pkg generate + └─ pkg validate + +Runs: pristine-check → clean → build → test → pkg generate → pkg validate +``` + +`Runs:` lists the targets whose bodies run, in order. A target that two others depend on runs once; the tree draws it +the first time and marks later references `(above)`. + +## Skipped targets + +With `-s`, the named target's gates show as skipped and their own dependencies drop out of the plan: + +```bash +./build.cs release -s --graph +``` + +```text +release Test, then pack +├─ requires +│ ├─ pristine-check skipped: -s +│ └─ test skipped: -s +└─ composes + ├─ pkg generate + └─ pkg validate + +Runs: pkg generate → pkg validate +``` + +A target whose condition is false shows `skipped: its condition is false`. Its dependencies still run, as they do in a +real run. `--graph` evaluates the condition when it draws the plan; a real run evaluates it again just before the +target would start. + +## Dependencies with values + +A dependency that names a value runs with that value, and the plan shows it after the route: + +```text +ci +└─ composes + ├─ test (filter: Unit) + └─ test (filter: Integration) +``` + +Two references with equal values are one target in the plan, and run once. Two references with different values run +once each. Only the target named on the command line binds the command line's arguments. + +## Formats + +| Command | Prints | +|---|---| +| `--graph` or `--graph tree` | The tree and the `Runs:` line | +| `--graph mermaid` | A Mermaid flowchart, with one edge per ordering and skipped targets dashed | +| `--graph json` | The plan as JSON: `roots`, then `targets` in run order with their stages and what each waits for | + +`--graph=mermaid` works too. `--graph` without a target draws every target that nothing else depends on. + +A target's `--help` lists the same order under `Runs:` when the target has dependencies. diff --git a/docs/make/index.md b/docs/make/index.md index db32c53..472372e 100644 --- a/docs/make/index.md +++ b/docs/make/index.md @@ -7,8 +7,11 @@ ./build.cs --help ./build.cs test --filter Unit ./build.cs release -s # skip the gates, run only the composed targets +./build.cs release --graph # draw the plan and run nothing ``` +[**Drawing the plan**](graph.md) - `--graph` draws what a run would do, skipped targets included, and runs nothing. + [**Wrappers**](wrappers.md) - Generate one task per target for [mise](mise.md), [make](makefile.md) and [just](just.md), and let mise hooks keep them up to date. diff --git a/src/Nullean.Make.Fs/MakeApp.fs b/src/Nullean.Make.Fs/MakeApp.fs index 04fec80..8659dd3 100644 --- a/src/Nullean.Make.Fs/MakeApp.fs +++ b/src/Nullean.Make.Fs/MakeApp.fs @@ -41,10 +41,13 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> let mutable singleTarget = false let mutable showHelp = false let mutable showVersion = false + let mutable graph : GraphFormat option = None let mutable i = 0 while i < argv.Length do let arg = argv.[i] - if arg = "-h" || arg = "--help" then showHelp <- true; i <- i + 1 + let graphFormat = GraphOption.TryRead(argv, &i) + if graphFormat.HasValue then graph <- Some graphFormat.Value + elif arg = "-h" || arg = "--help" then showHelp <- true; i <- i + 1 elif arg = "--version" then showVersion <- true; i <- i + 1 elif arg = "-s" || arg = "--single-target" then singleTarget <- true; i <- i + 1 else @@ -72,7 +75,7 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> opt.Set argv.[i] i <- i + 1 | None -> remaining.Add(arg); i <- i + 1 - remaining.ToArray(), singleTarget, showHelp, showVersion + remaining.ToArray(), singleTarget, showHelp, showVersion, graph let resolveRoute (remaining: string[]) (byRoute: Collections.Generic.Dictionary) = let routeTokens = Collections.Generic.List() @@ -161,7 +164,7 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> | Error (code, msg) -> eprintfn "%s" msg return code - | Ok (remaining, singleTarget, showHelp, showVersion) -> + | Ok (remaining, singleTarget, showHelp, showVersion, graphFormat) -> if showVersion then printfn "%s" (entryVersion ()) @@ -196,6 +199,8 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> | Some t -> eprintfn "Unknown target '%s'." t return 2 + | None when graphFormat.IsSome -> + return DepGraphExecutor.DrawWholeGraph(graph, graphFormat.Value) | None -> MakeHelpPrinter.PrintRoot(graph, appName) return 0 @@ -214,6 +219,7 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> ParsedArgs( Target = node, TargetArgs = targetArgs, - SingleTarget = singleTarget) + SingleTarget = singleTarget, + Graph = Option.toNullable graphFormat) return! DepGraphExecutor.ExecuteAsync(node, parsed, graph) } diff --git a/src/Nullean.Make.Fs/README.md b/src/Nullean.Make.Fs/README.md index 7547d56..5e5bac8 100644 --- a/src/Nullean.Make.Fs/README.md +++ b/src/Nullean.Make.Fs/README.md @@ -178,6 +178,19 @@ let token = app.Option("--token", desc = "API token", defaultVa Read them in target blocks through `.Value`. Help shows each option's type, such as `--config `, and `--token ` for an option type. Both `--token abc` and `--token=abc` work. A value that does not parse, or a missing value, exits `2` before any target runs. Enum options bind by name, ignoring case. +## Drawing the plan + +`--graph` draws what a run would do and runs nothing. It binds the target's arguments, applies `-s` and evaluates +conditions, so a skipped target shows as skipped: + +``` +build release -s --graph +build release --graph mermaid # or json +``` + +A target's `--help` lists the order its dependencies run in under `Runs:`. See +[Drawing the plan](https://argh.nullean.net/make/graph). + ## mise, make and just `__wrappers sync` writes a mise task include, a Makefile include and a justfile import with one task per target, so diff --git a/src/Nullean.Make/Execution/DepGraphExecutor.cs b/src/Nullean.Make/Execution/DepGraphExecutor.cs index bb2ca0b..8bd4f82 100644 --- a/src/Nullean.Make/Execution/DepGraphExecutor.cs +++ b/src/Nullean.Make/Execution/DepGraphExecutor.cs @@ -5,7 +5,10 @@ namespace Nullean.Make.Execution; internal static class DepGraphExecutor { - /// Binds the named target's arguments, plans the run and executes it. + /// + /// Binds the named target's arguments, plans the run and executes it. With --graph, draws the plan instead + /// and runs nothing. + /// public static async Task ExecuteAsync(TargetNode root, ParsedArgs parsed, BuildGraph graph) { var source = graph.Source ?? throw new InvalidOperationException("The graph has no target source."); @@ -13,16 +16,39 @@ public static async Task ExecuteAsync(TargetNode root, ParsedArgs parsed, B try { var value = source.BindArguments(root, parsed.TargetArgs); - plan = RunPlan.Build([new DepRef(root, value)], source, new PlanOptions(parsed.SingleTarget)); + plan = RunPlan.Build([new DepRef(root, value)], source, new PlanOptions(parsed.SingleTarget, EvaluateConditions: parsed.Graph is not null)); } catch (MakeException ex) { Console.Error.WriteLine(ex.Message); return ex.ExitCode; } + + if (parsed.Graph is { } format) + { + PlanRenderer.Write(plan, format, Console.Out); + return 0; + } return await ExecuteAsync(plan, parsed); } + /// --graph without a target: draws every target nothing else depends on. + public static int DrawWholeGraph(BuildGraph graph, GraphFormat format) + { + var source = graph.Source ?? throw new InvalidOperationException("The graph has no target source."); + try + { + var plan = PlanRenderer.WholeGraph(graph, source, new PlanOptions(SingleTarget: false, EvaluateConditions: true)); + PlanRenderer.Write(plan, format, Console.Out); + return 0; + } + catch (MakeException ex) + { + Console.Error.WriteLine(ex.Message); + return ex.ExitCode; + } + } + public static async Task ExecuteAsync(RunPlan plan, ParsedArgs parsed) { var context = new MakeContext(parsed.GlobalValues, parsed.SingleTarget) { TargetArgs = parsed.TargetArgs }; diff --git a/src/Nullean.Make/Execution/PlanRenderer.cs b/src/Nullean.Make/Execution/PlanRenderer.cs new file mode 100644 index 0000000..d9dd84a --- /dev/null +++ b/src/Nullean.Make/Execution/PlanRenderer.cs @@ -0,0 +1,308 @@ +using System.Text; +using System.Text.Json; +using Nullean.Argh.Help; +using Nullean.Make.Discovery; + +namespace Nullean.Make.Execution; + +/// How --graph draws the plan. +internal enum GraphFormat +{ + /// A tree in the terminal, with the order the targets run in below it. + Tree, + + /// A Mermaid flowchart, for a pull request or the docs. + Mermaid, + + /// The plan as JSON, for tools. + Json +} + +/// Reads --graph, --graph mermaid and --graph=json from the command line. +internal static class GraphOption +{ + public const string Name = "--graph"; + + /// + /// When args[i] is --graph, reads it and an optional format after it, advances + /// past them and returns the format. A word after --graph that is not a format is left for the route. + /// + public static GraphFormat? TryRead(IReadOnlyList args, ref int i) + { + var arg = args[i]; + if (arg.StartsWith(Name + "=", StringComparison.Ordinal)) + { + i++; + return Parse(arg[(Name.Length + 1)..]) ?? + throw new MakeException($"Unknown graph format '{arg[(Name.Length + 1)..]}'. Known: tree, mermaid, json.", 2); + } + if (arg != Name) + return null; + i++; + if (i < args.Count && Parse(args[i]) is { } format) + { + i++; + return format; + } + return GraphFormat.Tree; + } + + private static GraphFormat? Parse(string value) => value.ToLowerInvariant() switch + { + "tree" => GraphFormat.Tree, + "mermaid" => GraphFormat.Mermaid, + "json" => GraphFormat.Json, + _ => null + }; +} + +/// Draws a without running it. +internal static class PlanRenderer +{ + public static void Write(RunPlan plan, GraphFormat format, TextWriter output) + { + switch (format) + { + case GraphFormat.Mermaid: + WriteMermaid(plan, output); + break; + case GraphFormat.Json: + WriteJson(plan, output); + break; + default: + WriteTree(plan, output); + break; + } + } + + /// + /// The plan for the targets nothing else depends on, each with its default value: what the whole build looks like. + /// + public static RunPlan WholeGraph(BuildGraph graph, ITargetSource source, PlanOptions options) + { + var referenced = graph.Targets.SelectMany(t => t.RequiresResolved.Concat(t.ComposesResolved)).ToHashSet(); + var roots = graph.Targets.Where(t => !t.Hidden && !referenced.Contains(t)).Select(t => new DepRef(t, null)).ToList(); + return RunPlan.Build(roots, source, options with { ChainRoots = false }); + } + + /// The targets whose bodies run, in order: what Runs: lists. + public static IEnumerable Running(RunPlan plan) => plan.Instances.Where(i => i.Spec.Body is not null && i.Skipped is null); + + /// clean → build → test. + public static string RunOrder(RunPlan plan) => string.Join(" → ", Running(plan).Select(i => i.Name)); + + /// + /// Each instance's prerequisites without the ones another prerequisite already waits for, so a drawn graph has an + /// edge per real ordering and no transitive ones. + /// + public static Dictionary> DirectPrerequisites(RunPlan plan) + { + var ancestors = new Dictionary>(); + var direct = new Dictionary>(); + foreach (var instance in plan.Instances) + { + var all = new HashSet(); + foreach (var prerequisite in instance.Prerequisites) + { + all.Add(prerequisite); + all.UnionWith(ancestors[prerequisite]); + } + ancestors[instance] = all; + var distinct = instance.Prerequisites.Distinct().ToList(); + direct[instance] = distinct.Where(p => !distinct.Any(q => q != p && ancestors[q].Contains(p))).ToList(); + } + return direct; + } + + // ── tree ────────────────────────────────────────────────────────────────── + + private sealed record Line(string Text, List Children); + + private static void WriteTree(RunPlan plan, TextWriter output) + { + var expanded = new HashSet(); + foreach (var root in plan.Roots) + { + var tree = Build(root, expanded); + var description = root.Node.Description; + output.WriteLine(string.IsNullOrEmpty(description) ? Accent(tree.Text) : $"{Accent(tree.Text)} {description}"); + WriteChildren(tree.Children, "", output); + output.WriteLine(); + } + + // Unrelated roots drawn side by side do not run in one sequence. + if (!plan.Chained && plan.Roots.Count > 1) + return; + var order = RunOrder(plan); + output.WriteLine($"{CliHelpFormatting.Section("Runs:")} {(order.Length == 0 ? "nothing" : order)}"); + } + + private static Line Build(TargetInstance instance, HashSet expanded) + { + var text = instance.Name + Annotation(instance.Skipped); + if (!expanded.Add(instance)) + return new Line(text + Dim(" (above)"), []); + + var children = new List(); + foreach (var kind in new[] { StageKind.Requires, StageKind.Composes }) + { + var lines = new List(); + foreach (var stage in instance.Stages.Where(s => s.Kind == kind)) + { + var items = stage + .Items + .Select(item => item.Instance is null ? new Line(item.Name + Annotation(item.Skipped), []) : Build(item.Instance, expanded)) + .ToList(); + if (stage.Parallel) + lines.Add(new Line(Dim("parallel"), items)); + else + lines.AddRange(items); + } + if (lines.Count == 0) + continue; + + // A target's dependencies hang off it directly; a command says which of its stages -s skips. + if (instance.Node.Kind == TargetKind.Command) + children.Add(new Line(Dim(kind == StageKind.Requires ? "requires" : "composes"), lines)); + else + children.AddRange(lines); + } + return new Line(text, children); + } + + private static void WriteChildren(List children, string indent, TextWriter output) + { + for (var i = 0; i < children.Count; i++) + { + var last = i == children.Count - 1; + output.WriteLine($"{indent}{(last ? "└─ " : "├─ ")}{children[i].Text}"); + WriteChildren(children[i].Children, indent + (last ? " " : "│ "), output); + } + } + + private static string Annotation(SkipReason? reason) => reason switch + { + SkipReason.SingleTarget => Dim(" skipped: -s"), + SkipReason.Condition => Dim(" skipped: its condition is false"), + _ => "" + }; + + private static string Accent(string text) => CliHelpFormatting.Accent(text); + + private static string Dim(string text) => CliHelpFormatting.DocRemarksLine(text); + + // ── mermaid ─────────────────────────────────────────────────────────────── + + private static void WriteMermaid(RunPlan plan, TextWriter output) + { + var ids = new Dictionary(); + foreach (var instance in plan.Instances) + ids[instance] = $"n{ids.Count}"; + + var sb = new StringBuilder(); + var skipped = new List(); + sb.AppendLine("flowchart TD"); + foreach (var instance in plan.Instances) + { + sb.AppendLine($" {ids[instance]}[\"{Escape(instance.Name)}\"]"); + if (instance.Skipped is not null) + skipped.Add(ids[instance]); + } + + var extra = 0; + var direct = DirectPrerequisites(plan); + foreach (var instance in plan.Instances) + { + foreach (var prerequisite in direct[instance]) + sb.AppendLine($" {ids[prerequisite]} --> {ids[instance]}"); + foreach (var item in instance.Stages.SelectMany(s => s.Items).Where(i => i.Instance is null)) + { + var id = $"s{extra++}"; + sb.AppendLine($" {id}[\"{Escape(item.Name)}\"]"); + sb.AppendLine($" {id} -.-> {ids[instance]}"); + skipped.Add(id); + } + } + + if (skipped.Count > 0) + { + sb.AppendLine(" classDef skipped stroke-dasharray: 5 5,color:#888"); + sb.AppendLine($" class {string.Join(",", skipped)} skipped"); + } + output.Write(sb.ToString()); + } + + private static string Escape(string text) => text.Replace("\"", "#quot;"); + + // ── json ────────────────────────────────────────────────────────────────── + + private static void WriteJson(RunPlan plan, TextWriter output) + { + using var stream = new MemoryStream(); + using (var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true })) + { + json.WriteStartObject(); + json.WriteStartArray("roots"); + foreach (var root in plan.Roots) + json.WriteStringValue(root.Name); + json.WriteEndArray(); + + json.WriteStartArray("targets"); + var direct = DirectPrerequisites(plan); + foreach (var instance in plan.Instances) + { + json.WriteStartObject(); + json.WriteString("name", instance.Name); + json.WriteStartArray("route"); + foreach (var segment in instance.Node.Route) + json.WriteStringValue(segment); + json.WriteEndArray(); + json.WriteString("kind", instance.Node.Kind == TargetKind.Command ? "command" : "target"); + json.WriteBoolean("hasBody", instance.Spec.Body is not null); + WriteSkipped(json, instance.Skipped); + json.WriteStartArray("waitsFor"); + foreach (var prerequisite in direct[instance]) + json.WriteStringValue(prerequisite.Name); + json.WriteEndArray(); + json.WriteStartArray("stages"); + foreach (var stage in instance.Stages) + { + json.WriteStartObject(); + json.WriteString("kind", stage.Kind == StageKind.Requires ? "requires" : "composes"); + json.WriteBoolean("parallel", stage.Parallel); + json.WriteStartArray("items"); + foreach (var item in stage.Items) + { + json.WriteStartObject(); + json.WriteString("name", item.Name); + WriteSkipped(json, item.Skipped); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteEndObject(); + } + output.WriteLine(Encoding.UTF8.GetString(stream.ToArray())); + } + + private static void WriteSkipped(Utf8JsonWriter json, SkipReason? reason) + { + switch (reason) + { + case SkipReason.SingleTarget: + json.WriteString("skipped", "single-target"); + break; + case SkipReason.Condition: + json.WriteString("skipped", "condition"); + break; + default: + json.WriteNull("skipped"); + break; + } + } +} diff --git a/src/Nullean.Make/Execution/RunPlan.cs b/src/Nullean.Make/Execution/RunPlan.cs index cbfda54..3216189 100644 --- a/src/Nullean.Make/Execution/RunPlan.cs +++ b/src/Nullean.Make/Execution/RunPlan.cs @@ -45,7 +45,10 @@ internal sealed record PlannedStage(StageKind Kind, bool Parallel, IReadOnlyList internal sealed record PlannedItem(TargetInstance? Instance, string Name, SkipReason? Skipped); /// Options that change which instances the plan contains. -internal sealed record PlanOptions(bool SingleTarget, bool EvaluateConditions = false); +/// Skip the named targets' gates, as -s does. +/// Evaluate each condition while planning, so a drawn plan shows what it skips. +/// Run the named targets in order, each after the one before it. +internal sealed record PlanOptions(bool SingleTarget, bool EvaluateConditions = false, bool ChainRoots = true); /// The instances a run contains, in an order that respects every prerequisite. internal sealed class RunPlan @@ -53,6 +56,9 @@ internal sealed class RunPlan public required IReadOnlyList Roots { get; init; } public required IReadOnlyList Instances { get; init; } + /// True when the roots run one after another; false for a drawing of unrelated roots. + public bool Chained { get; init; } = true; + /// /// Expands the named targets into instances. Each reference resolves to its node and value; a reference without a /// value stands for the node's default value. A sequential stage's item waits for the item before it, and every @@ -65,12 +71,12 @@ public static RunPlan Build(IReadOnlyList roots, ITargetSource source, P TargetInstance? previous = null; foreach (var root in roots) { - var instance = builder.Visit(root, isRoot: true, previous is null ? [] : [previous]); + var instance = builder.Visit(root, isRoot: true, previous is null || !options.ChainRoots ? [] : [previous]); instance.IsRoot = true; rootInstances.Add(instance); previous = instance; } - return new RunPlan { Roots = rootInstances, Instances = builder.Ordered }; + return new RunPlan { Roots = rootInstances, Instances = builder.Ordered, Chained = options.ChainRoots }; } private sealed class Builder(ITargetSource source, PlanOptions options) diff --git a/src/Nullean.Make/Help/MakeHelpPrinter.cs b/src/Nullean.Make/Help/MakeHelpPrinter.cs index 4897b60..7371955 100644 --- a/src/Nullean.Make/Help/MakeHelpPrinter.cs +++ b/src/Nullean.Make/Help/MakeHelpPrinter.cs @@ -1,5 +1,6 @@ using Nullean.Argh.Help; using Nullean.Make.Discovery; +using Nullean.Make.Execution; using Nullean.Make.Parsing; namespace Nullean.Make.Help; @@ -147,6 +148,7 @@ public static void PrintTarget(TargetNode node, BuildGraph graph, string scriptN foreach (var dep in allDeps) Console.WriteLine($" {string.Join(" ", dep.Route)}"); Console.WriteLine(); + PrintRunOrder(node, graph, scriptName); } PrintGlobalOptions(graph, scriptName); @@ -180,9 +182,33 @@ public static void PrintCommand(TargetNode node, BuildGraph graph, string script Console.WriteLine(); } + PrintRunOrder(node, graph, scriptName); PrintGlobalOptions(graph, scriptName); } + /// + /// Runs: the bodies a bare invocation of the target runs, in order, and where to see the whole plan. Prints + /// nothing when the target has no dependencies to order, or the plan cannot be built. + /// + private static void PrintRunOrder(TargetNode node, BuildGraph graph, string scriptName) + { + if (graph.Source is not { } source || node.RequiresResolved.Count + node.ComposesResolved.Count == 0) + return; + RunPlan plan; + try + { + plan = RunPlan.Build([new DepRef(node, null)], source, new PlanOptions(SingleTarget: false)); + } + catch (MakeException) + { + return; + } + Console.WriteLine($" {CliHelpFormatting.Section("Runs:")}"); + Console.WriteLine($" {PlanRenderer.RunOrder(plan)}"); + Console.WriteLine($" {CliHelpFormatting.DocRemarksLine($"{scriptName} {string.Join(" ", node.Route)} --graph draws the plan")}"); + Console.WriteLine(); + } + private static string CommandSummary(TargetNode node) { var req = node.RequiresResolved.Select(d => string.Join(" ", d.Route)).ToList(); @@ -218,6 +244,7 @@ private static void PrintGlobalOptions(BuildGraph graph, string scriptName) Console.WriteLine($" {CliHelpFormatting.Section("Global options:")}"); Console.WriteLine($" {CliHelpFormatting.Placeholder("-s, --single-target"),-30} Skip prerequisite deps; run only the body / Composes"); Console.WriteLine($" {CliHelpFormatting.Placeholder("-h, --help"),-30} Show this help"); + Console.WriteLine($" {CliHelpFormatting.Placeholder(" --graph []"),-30} Draw what would run and run nothing: tree, mermaid or json"); foreach (var opt in graph.GlobalOptions) { diff --git a/src/Nullean.Make/MakeApp.cs b/src/Nullean.Make/MakeApp.cs index a96aaeb..be71279 100644 --- a/src/Nullean.Make/MakeApp.cs +++ b/src/Nullean.Make/MakeApp.cs @@ -75,6 +75,8 @@ public static class MakeApp if (parsed.Target is null) { + if (parsed.Graph is { } format) + return DepGraphExecutor.DrawWholeGraph(graph, format); MakeHelpPrinter.PrintRoot(graph, scriptName); return 0; } diff --git a/src/Nullean.Make/MakeAppOfT.cs b/src/Nullean.Make/MakeAppOfT.cs index 389c266..1c94b55 100644 --- a/src/Nullean.Make/MakeAppOfT.cs +++ b/src/Nullean.Make/MakeAppOfT.cs @@ -149,9 +149,10 @@ public async Task RunAsync(string[] args) string[] remaining; bool singleTarget, showHelp, showVersion; + GraphFormat? graphFormat; try { - (remaining, singleTarget, showHelp, showVersion) = ExtractGlobals(args); + (remaining, singleTarget, showHelp, showVersion, graphFormat) = ExtractGlobals(args); } catch (MakeException ex) { @@ -189,6 +190,8 @@ public async Task RunAsync(string[] args) Console.Error.WriteLine($"Unknown target '{unknown}'."); return 2; } + if (graphFormat is { } format) + return DepGraphExecutor.DrawWholeGraph(_graph, format); MakeHelpPrinter.PrintRoot(_graph, scriptName); return 0; } @@ -199,7 +202,7 @@ public async Task RunAsync(string[] args) return 2; } - var parsed = new ParsedArgs { Target = targetNode, TargetArgs = targetArgs, SingleTarget = singleTarget, }; + var parsed = new ParsedArgs { Target = targetNode, TargetArgs = targetArgs, SingleTarget = singleTarget, Graph = graphFormat }; return await DepGraphExecutor.ExecuteAsync(targetNode, parsed, _graph); } @@ -253,12 +256,13 @@ private TargetNode ResolveCase(TargetNode from, string caseTypeName) // ── Argv helpers ────────────────────────────────────────────────────────── - private (string[] remaining, bool single, bool help, bool version) ExtractGlobals(string[] argv) + private (string[] remaining, bool single, bool help, bool version, GraphFormat? graph) ExtractGlobals(string[] argv) { var remaining = new List(); var single = false; var help = false; var version = false; + GraphFormat? graph = null; var i = 0; while (i < argv.Length) { @@ -281,6 +285,11 @@ private TargetNode ResolveCase(TargetNode from, string caseTypeName) i++; continue; } + if (GraphOption.TryRead(argv, ref i) is { } format) + { + graph = format; + continue; + } var matched = false; foreach (var opt in _options) @@ -311,7 +320,7 @@ private TargetNode ResolveCase(TargetNode from, string caseTypeName) i++; } } - return (remaining.ToArray(), single, help, version); + return (remaining.ToArray(), single, help, version, graph); } private (string routeKey, string[] targetArgs) ResolveRoute(string[] remaining) diff --git a/src/Nullean.Make/Parsing/ArgvParser.cs b/src/Nullean.Make/Parsing/ArgvParser.cs index 882bb73..3a4923c 100644 --- a/src/Nullean.Make/Parsing/ArgvParser.cs +++ b/src/Nullean.Make/Parsing/ArgvParser.cs @@ -12,6 +12,9 @@ internal sealed class ParsedArgs public bool SingleTarget { get; set; } public bool ShowHelp { get; set; } public bool ShowVersion { get; set; } + + /// Set by --graph: draw the plan in this format and run nothing. + public Execution.GraphFormat? Graph { get; set; } public string? HelpTarget { get; set; } } @@ -117,6 +120,11 @@ private static List ExtractGlobals(string[] args, BuildGraph graph, Make i++; continue; } + if (Execution.GraphOption.TryRead(args, ref i) is { } graphFormat) + { + result.Graph = graphFormat; + continue; + } // Global options var matched = false; diff --git a/src/Nullean.Make/README.md b/src/Nullean.Make/README.md index 8599957..f1a3d13 100644 --- a/src/Nullean.Make/README.md +++ b/src/Nullean.Make/README.md @@ -114,6 +114,19 @@ A target's description is the summary of its case type's XML doc comment, such a A case that is itself a union becomes a namespace: `union Db(Migrate, Seed)` inside `union Target(..., Db)` gives `db migrate` and `db seed`, and `db --help` lists them. Case type names must be unique across the whole union, including nested unions. +## Drawing the plan + +`--graph` draws what a run would do and runs nothing. It binds the target's arguments, applies `-s` and evaluates +conditions, so a skipped target shows as skipped: + +``` +build release -s --graph +build release --graph mermaid # or json +``` + +A target's `--help` lists the order its dependencies run in under `Runs:`. See +[Drawing the plan](https://argh.nullean.net/make/graph). + ## mise, make and just `__wrappers sync` writes one include file per wrapper from the targets, so `mise run test`, `make test` and diff --git a/tests/Nullean.Make.Fs.Tests/GraphTests.fs b/tests/Nullean.Make.Fs.Tests/GraphTests.fs new file mode 100644 index 0000000..c436b52 --- /dev/null +++ b/tests/Nullean.Make.Fs.Tests/GraphTests.fs @@ -0,0 +1,66 @@ +module Nullean.Make.Fs.Tests.GraphTests + +open System +open System.IO +open TUnit.Core +open Nullean.Make.Fs + +type ProbeOptions = { Filter: string option } + +type Drawn = + | Wipe + | Compose + | Probe of ProbeOptions + | Ship + +let private run (args: string list) = + let log = ResizeArray() + let app = MakeApp("build", None) + app.Bind <| function + | Wipe -> target [] { log.Add "wipe" } + | Compose -> target [Wipe] { log.Add "compose" } + | Probe o -> target [Compose] { log.Add $"probe:%A{o.Filter}" } + | Ship -> command { + requires [Probe { Filter = Some "Unit" }] + composes [Wipe] } + let stdout = new StringWriter() + let oldOut, oldErr = Console.Out, Console.Error + Console.SetOut stdout + Console.SetError(new StringWriter()) + try + let exit = app.RunAsync(List.toArray args).GetAwaiter().GetResult() + exit, List.ofSeq log, string stdout + finally + Console.SetOut oldOut + Console.SetError oldErr + +[] +type GraphTests() = + + [] + member _.``Graph draws the plan and runs nothing``() = + let exit, log, stdout = run ["ship"; "--graph"] + Assert.Equal(0, exit) + Assert.Equal([], log) + Assert.Contains("probe (filter: Unit)", stdout) + Assert.Contains("Runs: wipe → compose → probe (filter: Unit)", stdout) + + [] + member _.``Graph shows a gate that single target skips``() = + let _, _, stdout = run ["ship"; "-s"; "--graph"] + Assert.Contains("probe (filter: Unit) skipped: -s", stdout) + Assert.Contains("Runs: wipe", stdout) + + [] + member _.``Graph without a target draws the whole build``() = + let exit, log, stdout = run ["--graph"] + Assert.Equal(0, exit) + Assert.Equal([], log) + // Everything else is a dependency of ship, so ship is the one root. + Assert.Equal(true, stdout.StartsWith "ship") + + [] + member _.``Graph mermaid prints a flowchart``() = + let _, _, stdout = run ["probe"; "--graph"; "mermaid"] + Assert.Contains("flowchart TD", stdout) + Assert.Contains("n0 --> n1", stdout) diff --git a/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj b/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj index 97a1c3d..1893294 100644 --- a/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj +++ b/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj @@ -15,6 +15,7 @@ + diff --git a/tests/Nullean.Make.Tests/GraphTests.cs b/tests/Nullean.Make.Tests/GraphTests.cs new file mode 100644 index 0000000..179010f --- /dev/null +++ b/tests/Nullean.Make.Tests/GraphTests.cs @@ -0,0 +1,177 @@ +using System.Text.Json; +using AwesomeAssertions; + +namespace Nullean.Make.Tests; + +public record class Wipe; + +public record class Compose; + +public record class Probe(string Filter = ""); + +public record class Ship; + +public union Drawn(Wipe, Compose, Probe, Ship); + +/// --graph draws the plan the same run would execute, and runs nothing. +[NotInParallel] +public class GraphTests +{ + private sealed record Run(int ExitCode, IReadOnlyList Log, string Stdout, string Stderr); + + private static async Task RunAsync(params string[] args) + { + var log = new List(); + var app = new MakeApp("build"); + app.Bind( + d => + d.Value switch + { + Wipe => app.Target(() => log.Add("wipe")), + Compose => app.Target([new Wipe()], () => log.Add("compose")), + Probe p => app.Target([new Compose()], () => log.Add($"probe:{p.Filter}")), + Ship => app.Command([new Probe("Unit")], [new Wipe()]), + _ => throw new InvalidOperationException($"unmapped case {d.Value}") + } + ); + var (stdout, stderr) = (new StringWriter(), new StringWriter()); + var (oldOut, oldErr) = (Console.Out, Console.Error); + Console.SetOut(stdout); + Console.SetError(stderr); + try + { + var exit = await app.RunAsync(args); + return new Run(exit, log, stdout.ToString(), stderr.ToString()); + } + finally + { + Console.SetOut(oldOut); + Console.SetError(oldErr); + } + } + + [Test] + public async Task Graph_draws_the_plan_and_runs_nothing() + { + var run = await RunAsync("ship", "--graph"); + run.ExitCode.Should().Be(0); + run.Log.Should().BeEmpty(); + run.Stdout.Should().Contain("├─ requires").And.Contain("└─ composes").And.Contain("probe (filter: Unit)"); + run.Stdout.Should().Contain("Runs: wipe → compose → probe (filter: Unit)"); + } + + [Test] + public async Task Graph_shows_a_gate_that_single_target_skips() + { + var run = await RunAsync("ship", "-s", "--graph"); + run.Stdout.Should().Contain("probe (filter: Unit) skipped: -s"); + run.Stdout.Should().Contain("Runs: wipe"); + run.Stdout.Should().NotContain("compose" + Environment.NewLine); + } + + [Test] + public async Task Graph_binds_the_named_targets_arguments() + { + var run = await RunAsync("probe", "--filter", "Smoke", "--graph"); + run.Stdout.Should().Contain("probe (filter: Smoke)"); + } + + [Test] + public async Task Graph_mermaid_draws_one_edge_per_ordering() + { + var run = await RunAsync("probe", "--graph", "mermaid"); + run.ExitCode.Should().Be(0); + var lines = run.Stdout.Split('\n', StringSplitOptions.TrimEntries); + lines.Should().Contain("flowchart TD"); + lines.Count(l => l.Contains("-->")).Should().Be(2); + } + + [Test] + public async Task Graph_json_lists_the_targets_in_run_order() + { + var run = await RunAsync("ship", "--graph=json"); + run.ExitCode.Should().Be(0); + using var doc = JsonDocument.Parse(run.Stdout); + var names = doc.RootElement.GetProperty("targets").EnumerateArray().Select(t => t.GetProperty("name").GetString()).ToList(); + names.Should().Equal("wipe", "compose", "probe (filter: Unit)", "ship"); + doc.RootElement.GetProperty("roots")[0].GetString().Should().Be("ship"); + } + + [Test] + public async Task Graph_without_a_target_draws_every_target_nothing_depends_on() + { + var run = await RunAsync("--graph"); + run.ExitCode.Should().Be(0); + // Everything else is a dependency of ship, so ship is the one root. + run.Stdout.Should().StartWith("ship"); + run.Log.Should().BeEmpty(); + } + + [Test] + public async Task An_unknown_graph_format_exits_2() + { + var run = await RunAsync("ship", "--graph=dot"); + run.ExitCode.Should().Be(2); + run.Stderr.Should().Contain("Unknown graph format 'dot'"); + } + + [Test] + public async Task Target_help_lists_what_it_runs() + { + var run = await RunAsync("ship", "--help"); + run.Stdout.Should().Contain("Runs:").And.Contain("wipe → compose → probe (filter: Unit)"); + run.Stdout.Should().Contain("--graph []"); + } +} + +public class ConditionalBuild : MakeBuild +{ + [Flag("--skip-lint", Description = "Skip lint")] + public bool SkipLint { get; init; } + + public Target Lint => + _ => _.OnlyWhen(() => !SkipLint).Executes(() => + { }); + + public Target Compile => + _ => _.DependsOn(Lint).Executes(() => + { }); +} + +[NotInParallel] +public class ClassGraphTests +{ + private static async Task<(int Exit, string Stdout)> RunAsync(params string[] args) + { + var stdout = new StringWriter(); + var (oldOut, oldErr) = (Console.Out, Console.Error); + Console.SetOut(stdout); + Console.SetError(new StringWriter()); + try + { + return (await MakeApp.Execute(args), stdout.ToString()); + } + finally + { + Console.SetOut(oldOut); + Console.SetError(oldErr); + } + } + + [Test] + public async Task Graph_evaluates_conditions_and_shows_what_they_skip() + { + var (exit, stdout) = await RunAsync("compile", "--skip-lint", "--graph"); + exit.Should().Be(0); + stdout.Should().Contain("lint skipped: its condition is false"); + stdout.Should().Contain("Runs: compile"); + } + + [Test] + public async Task Graph_shows_a_condition_that_holds_as_running() + { + var (_, stdout) = await RunAsync("compile", "--graph"); + stdout.Should().NotContain("skipped"); + stdout.Should().Contain("Runs: lint → compile"); + } +}