From 09f31782705675bea3041610e3c0375a0b26dd91 Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 12 Nov 2026 08:25:26 +0100 Subject: [PATCH 1/2] 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/2] 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).