From 09f31782705675bea3041610e3c0375a0b26dd91 Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 12 Nov 2026 08:25:26 +0100 Subject: [PATCH 01/11] 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 02/11] 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 03/11] 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"); + } +} From b85d6427b449ab19981c0ae66a2e03c4ab19045b Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 12 Nov 2026 08:43:27 +0100 Subject: [PATCH 04/11] Run a command's parallel stages side by side A command declares a stage whose targets run at once: `.Parallel(...)` in C#, `concurrently [...]` in F#, where `parallel` is reserved. The run starts each target once everything it waits for has finished, up to `-j` targets at a time. The first failure cancels the targets still running; `-k` lets the ones that do not depend on it finish. While targets run side by side their output carries their names, or `--output grouped` writes each target's lines together. Lists keep running in order, so a build without a parallel stage runs as before. Co-Authored-By: Claude Opus 5.5 --- docs/_docset.yml | 1 + docs/make/index.md | 3 + docs/make/parallel.md | 97 +++++ src/Nullean.Make.Fs/Builders.fs | 23 +- src/Nullean.Make.Fs/FsGraphBuilder.fs | 9 +- src/Nullean.Make.Fs/MakeApp.fs | 30 +- src/Nullean.Make.Fs/README.md | 14 + src/Nullean.Make.Fs/Types.fs | 7 +- src/Nullean.Make/Command.cs | 7 + src/Nullean.Make/CommandOfT.cs | 3 + .../Discovery/ClassTargetSource.cs | 5 +- .../Discovery/TargetBuilderImpl.cs | 26 +- src/Nullean.Make/Discovery/TargetNode.cs | 20 ++ .../Execution/DepGraphExecutor.cs | 146 +++++++- src/Nullean.Make/Execution/ExecutionLog.cs | 29 +- src/Nullean.Make/Execution/OutputRouter.cs | 138 +++++++ src/Nullean.Make/Execution/RunPlan.cs | 4 +- src/Nullean.Make/Execution/RunSwitches.cs | 65 ++++ src/Nullean.Make/Help/MakeHelpPrinter.cs | 35 +- src/Nullean.Make/MakeAppOfT.cs | 27 +- src/Nullean.Make/MakeContext.cs | 14 + src/Nullean.Make/Parsing/ArgvParser.cs | 17 +- src/Nullean.Make/README.md | 12 + src/Nullean.Make/Shell.cs | 29 +- .../UnionGraph/IUnionTargetBuilder.cs | 20 ++ .../UnionGraph/UnionTargetBuilderImpl.cs | 65 ++-- .../UnionGraph/UnionTargetSource.cs | 7 +- .../Nullean.Make.Fs.Tests.fsproj | 1 + tests/Nullean.Make.Fs.Tests/ParallelTests.fs | 61 ++++ tests/Nullean.Make.Tests/ParallelTests.cs | 337 ++++++++++++++++++ 30 files changed, 1152 insertions(+), 100 deletions(-) create mode 100644 docs/make/parallel.md create mode 100644 src/Nullean.Make/Execution/OutputRouter.cs create mode 100644 src/Nullean.Make/Execution/RunSwitches.cs create mode 100644 tests/Nullean.Make.Fs.Tests/ParallelTests.fs create mode 100644 tests/Nullean.Make.Tests/ParallelTests.cs diff --git a/docs/_docset.yml b/docs/_docset.yml index 393d2a0..fb5c3a3 100644 --- a/docs/_docset.yml +++ b/docs/_docset.yml @@ -50,6 +50,7 @@ toc: children: - file: index.md - file: graph.md + - file: parallel.md - file: wrappers.md - file: mise.md - file: makefile.md diff --git a/docs/make/index.md b/docs/make/index.md index 472372e..5e70e54 100644 --- a/docs/make/index.md +++ b/docs/make/index.md @@ -10,6 +10,9 @@ ./build.cs release --graph # draw the plan and run nothing ``` +[**Running targets side by side**](parallel.md) - Parallel stages, `-j`, `--keep-going`, and the output of targets +that run at once. + [**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 diff --git a/docs/make/parallel.md b/docs/make/parallel.md new file mode 100644 index 0000000..82087b3 --- /dev/null +++ b/docs/make/parallel.md @@ -0,0 +1,97 @@ +# Running targets side by side + +A command's composed targets run in order. A parallel stage runs its targets side by side instead: each starts once +the stages before it have finished, and the stages after it wait for all of them. + +C#, on a `MakeApp`: + +```csharp +Release => app.Command() + .Requires(new Test()) + .Parallel(new PackNuget(), new DocsBuild(), new DockerImage()) + .Composes(new Publish()), +``` + +C#, on a `MakeBuild` class: + +```csharp +public Command Release => _ => _ + .Requires(Test) + .Parallel(PackNuget, DocsBuild, DockerImage) + .Composes(Publish); +``` + +F#, in a `command { }` block, where the operation is `concurrently` because F# reserves `parallel`: + +```fsharp +| Release -> command { + requires [Test { Filter = None }] + concurrently [Pkg Generate; Docs Build; Docker Image] + composes [Publish] } +``` + +Stages run in the order they are declared. Requires always run before the composed stages. A target two stages share +runs once, the first time it is reached. + +`--graph` draws a parallel stage as a `parallel` group. A command's `--help` numbers the targets of one stage the same. + +## How many run at once + +`-j` / `--jobs` caps how many targets run at once. The default is one per processor. `-j 1` runs a parallel stage one +target at a time, in the order it is declared, which helps when the output of two targets is hard to tell apart. + +```bash +./build.cs release -j 4 +./build.cs release -j 1 +``` + +## When a target fails + +The first failure stops the run. The targets still running are cancelled, and no more start. The run exits with the +failed target's exit code. + +`-k` / `--keep-going` lets the targets that do not depend on the failure finish. A target that waits for the failed +one does not start. The run still exits with the first failure's exit code. + +A target body stops when it is cancelled only if it watches for it: + +- `Shell.Exec` watches for it, and stops the process it started. +- An async body can take the token: `app.Target(async ct => await Task.Delay(1000, ct))`, or read + `MakeContext.Current.CancellationToken`. + +## Output + +While targets run side by side, each line of their output carries the target's name: + +```text +Starting pkg generate +Starting docs build +[pkg generate] Successfully created package 'Example.1.0.0.nupkg'. +[docs build] Build succeeded. +Finished docs build (4.1s) +Finished pkg generate (6.3s) + + docs build 4.1s + pkg generate 6.3s + Took 6.4s for 10.4s of work +``` + +`--output grouped` holds a target's lines back and writes them together when it finishes. On GitHub Actions each +target's lines become a collapsible group. + +The summary at the end lists each target's time, and the wall-clock time against their sum. + +A command run with `Shell.Exec` streams its output through the target's lines. Its output is then a pipe, not a +terminal, so a tool that colours only for a terminal prints without colour. A run with one job, or without a parallel +stage, leaves every command on the console as before. + +:::{note} +In F#, `sh` commands inside a `target { }` block run on the console, not through the target's lines, and a failure +elsewhere does not stop them. `printfn` and other `Console` output is prefixed. A parallel F# target finishes the +command it is running when the run stops, and then starts no more. +::: + +## Build options with the same name + +A global option the build declares itself keeps its name. A build with its own `-k` flag keeps it, and `--keep-going` +is the long form left for the switch. diff --git a/src/Nullean.Make.Fs/Builders.fs b/src/Nullean.Make.Fs/Builders.fs index 1f2a644..f688a78 100644 --- a/src/Nullean.Make.Fs/Builders.fs +++ b/src/Nullean.Make.Fs/Builders.fs @@ -37,9 +37,9 @@ type TargetBuilder<'TCase>(dependsOn: 'TCase list, hidden: bool) = member _.Using(resource: 'R :> IDisposable, body: 'R -> ShellStep<'T>) = shell.Using(resource, body) member _.Run(step: ShellStep) : Definition<'TCase> = FsTarget("", dependsOn, (fun _ -> shell.Run step), hidden) -/// What a command { } block collects: its requires, its composes and an optional body. +/// What a command { } block collects: its requires, its composed stages in order and an optional body. [] -type CommandSpec<'TCase> = internal { Requires: 'TCase list; Composes: 'TCase list; Body: (unit -> unit) option } +type CommandSpec<'TCase> = internal { Requires: 'TCase list; Stages: (bool * 'TCase list) list; Body: (unit -> unit) option } /// /// Builds a command from requires (gates, skipped under -s), composes (always run) and an @@ -47,7 +47,8 @@ type CommandSpec<'TCase> = internal { Requires: 'TCase list; Composes: 'TCase li /// /// | Release -> command { /// requires [PristineCheck; Test defaultTest] -/// composes [Pkg Generate; Pkg PkgTarget.Validate] +/// concurrently [Pkg Generate; Docs Build] +/// composes [Pkg PkgTarget.Validate] /// executes ( /// shell { /// let! sha = text $"git rev-parse --short HEAD" @@ -55,18 +56,28 @@ type CommandSpec<'TCase> = internal { Requires: 'TCase list; Composes: 'TCase li /// /// type CommandBuilder() = - member _.Yield(()) : CommandSpec<'TCase> = { Requires = []; Composes = []; Body = None } + member _.Yield(()) : CommandSpec<'TCase> = { Requires = []; Stages = []; Body = None } /// Targets that must succeed first. Skipped under -s. [] member _.Requires(spec: CommandSpec<'TCase>, targets: 'TCase list) = { spec with Requires = spec.Requires @ targets } /// Targets the command always runs, in order. [] - member _.Composes(spec: CommandSpec<'TCase>, targets: 'TCase list) = { spec with Composes = spec.Composes @ targets } + member _.Composes(spec: CommandSpec<'TCase>, targets: 'TCase list) = + match List.rev spec.Stages with + | (false, last) :: earlier -> { spec with Stages = List.rev ((false, last @ targets) :: earlier) } + | _ -> { spec with Stages = spec.Stages @ [false, targets] } + /// + /// Targets that run side by side, as one stage: each starts once the stages before it have finished, and the + /// stages after it wait for all of them. Stages run in the order they are written. -j caps how many run at once. + /// The name is concurrently because F# reserves parallel. + /// + [] + member _.Concurrently(spec: CommandSpec<'TCase>, targets: 'TCase list) = { spec with Stages = spec.Stages @ [true, targets] } /// A body that runs after every composed target. Deferred: nothing in it runs until the command does. [] member _.Executes(spec: CommandSpec<'TCase>, [] body: unit -> unit) = { spec with Body = Some body } member _.Run(spec: CommandSpec<'TCase>) : Definition<'TCase> = - FsCommand("", spec.Requires, spec.Composes, spec.Body |> Option.map (fun body -> fun _ -> body ())) + FsCommand("", spec.Requires, spec.Stages, spec.Body |> Option.map (fun body -> fun _ -> body ())) /// The target and command builders. Descriptions come from the DU case's /// doc comment. [] diff --git a/src/Nullean.Make.Fs/FsGraphBuilder.fs b/src/Nullean.Make.Fs/FsGraphBuilder.fs index 2549335..9c58575 100644 --- a/src/Nullean.Make.Fs/FsGraphBuilder.fs +++ b/src/Nullean.Make.Fs/FsGraphBuilder.fs @@ -75,9 +75,9 @@ type private FsTargetSource<'TCase when 'TCase : comparison and 'TCase : not nul | 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) + | FsCommand(_, requires, stages, b) -> + spec.Add(StageKind.Requires, refs node requires) + for sideBySide, targets in stages do spec.Add(StageKind.Composes, refs node targets, sideBySide) b |> Option.iter (fun b -> spec.Body <- body b) | FsNamespace _ -> () spec @@ -218,7 +218,8 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null> | FsNamespace _ -> () | FsTarget(_, deps, _, _) -> for dep in deps do node.RequiresResolved.Add(resolve node dep) - | FsCommand(_, requires, composes, _) -> + | FsCommand(_, requires, stages, _) -> + let composes = stages |> List.collect snd for dep in requires do node.RequiresResolved.Add(resolve node dep) for dep in composes do node.ComposesResolved.Add(resolve node dep) diff --git a/src/Nullean.Make.Fs/MakeApp.fs b/src/Nullean.Make.Fs/MakeApp.fs index 8659dd3..515c312 100644 --- a/src/Nullean.Make.Fs/MakeApp.fs +++ b/src/Nullean.Make.Fs/MakeApp.fs @@ -36,17 +36,20 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> let mutable _bindFn : ('TCase -> Definition<'TCase>) option = None let mutable _default : 'TCase option = None - let extractGlobals (argv: string[]) = + let declared (name: string) = + _options |> Seq.exists (fun o -> + o.Long = name || "--" + o.Long.TrimStart('-') = name + || (o.Short |> Option.exists (fun s -> s = name || "-" + s.TrimStart('-') = name))) + + let extractGlobals (argv: string[]) (switches: ParsedArgs) = let remaining = Collections.Generic.List() 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] - let graphFormat = GraphOption.TryRead(argv, &i) - if graphFormat.HasValue then graph <- Some graphFormat.Value + if RunSwitches.TryRead(argv, &i, switches, Func declared) then () 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 @@ -75,7 +78,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, graph + remaining.ToArray(), singleTarget, showHelp, showVersion let resolveRoute (remaining: string[]) (byRoute: Collections.Generic.Dictionary) = let routeTokens = Collections.Generic.List() @@ -160,11 +163,13 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> let argv, forwarded = if sep >= 0 then argv.[.. sep - 1], argv.[sep + 1 ..] else argv, [||] - match tryExec (fun () -> extractGlobals argv) with + let switches = ParsedArgs() + match tryExec (fun () -> extractGlobals argv switches) with | Error (code, msg) -> eprintfn "%s" msg return code - | Ok (remaining, singleTarget, showHelp, showVersion, graphFormat) -> + | Ok (remaining, singleTarget, showHelp, showVersion) -> + let graphFormat = Option.ofNullable switches.Graph if showVersion then printfn "%s" (entryVersion ()) @@ -215,11 +220,8 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> eprintfn "Unexpected argument '%s'. Target '%s' takes no arguments." first routeKey return 2 | true, node -> - let parsed = - ParsedArgs( - Target = node, - TargetArgs = targetArgs, - SingleTarget = singleTarget, - Graph = Option.toNullable graphFormat) - return! DepGraphExecutor.ExecuteAsync(node, parsed, graph) + switches.Target <- node + switches.TargetArgs <- targetArgs + switches.SingleTarget <- singleTarget + return! DepGraphExecutor.ExecuteAsync(node, switches, graph) } diff --git a/src/Nullean.Make.Fs/README.md b/src/Nullean.Make.Fs/README.md index 5e5bac8..bbe25f7 100644 --- a/src/Nullean.Make.Fs/README.md +++ b/src/Nullean.Make.Fs/README.md @@ -120,6 +120,20 @@ The first command that fails fails the target, and `RunAsync` returns `1`. composes [Pkg Generate; Pkg Validate] } // the work, always runs ``` +`concurrently [...]` adds a stage whose targets run side by side (F# reserves `parallel`). Stages run in the order +they are written: + +```fsharp +| Release -> command { + requires [Test { Filter = None }] + concurrently [Pkg Generate; Docs Build] + composes [Publish] } +``` + +`-j` / `--jobs` caps how many targets run at once, and `-k` / `--keep-going` lets the targets that do not depend on a +failure finish. `printfn` output of targets running side by side carries their names; `sh` commands keep the console. +See [Running targets side by side](https://argh.nullean.net/make/parallel). + `executes (...)` adds a body that runs after every composed target. Like a target block, it is deferred. Use `shell { }` inside it to run commands: ```fsharp diff --git a/src/Nullean.Make.Fs/Types.fs b/src/Nullean.Make.Fs/Types.fs index 9004533..6f9a5de 100644 --- a/src/Nullean.Make.Fs/Types.fs +++ b/src/Nullean.Make.Fs/Types.fs @@ -41,7 +41,8 @@ type FsContext internal () = type Definition<'TCase> = internal | FsTarget of desc: string * deps: 'TCase list * body: (FsContext -> unit) * hidden: bool - | FsCommand of desc: string * requires: 'TCase list * composes: 'TCase list * body: (FsContext -> unit) option + /// stages: the composed targets in declared order; true marks a stage whose targets run side by side + | FsCommand of desc: string * requires: 'TCase list * stages: (bool * 'TCase list) list * body: (FsContext -> unit) option | FsNamespace of segment: string * desc: string option /// Helpers for building Definition values inside app.Bind. @@ -63,8 +64,8 @@ module Make = /// `requires` entries are skipped under -s; `composes` entries always run. /// Description is auto-generated from the requires/composes graph in help output. let command (requires: 'TCase list) (composes: 'TCase list) : Definition<'TCase> = - FsCommand("", requires, composes, None) + FsCommand("", requires, [false, composes], None) /// Like `command` but with a trailing body that runs after all `composes` entries. let composer (requires: 'TCase list) (composes: 'TCase list) (body: FsContext -> 'r) : Definition<'TCase> = - FsCommand("", requires, composes, Some (fun ctx -> body ctx |> ignore)) + FsCommand("", requires, [false, composes], Some (fun ctx -> body ctx |> ignore)) diff --git a/src/Nullean.Make/Command.cs b/src/Nullean.Make/Command.cs index 829f0da..64c3180 100644 --- a/src/Nullean.Make/Command.cs +++ b/src/Nullean.Make/Command.cs @@ -29,6 +29,13 @@ public interface ICommandBuilder : ITargetBuilder /// Declares the targets that constitute the core work of this command. Always runs. ICommandBuilder Composes(params TargetRef[] refs); + + /// + /// Composes targets that run side by side, as one stage: each starts once the stages before it have finished, and + /// the stages after it wait for all of them. Stages run in the order they are declared. -j caps how many + /// targets run at once. + /// + ICommandBuilder Parallel(params TargetRef[] refs); } /// diff --git a/src/Nullean.Make/CommandOfT.cs b/src/Nullean.Make/CommandOfT.cs index 64f4401..efe14c5 100644 --- a/src/Nullean.Make/CommandOfT.cs +++ b/src/Nullean.Make/CommandOfT.cs @@ -8,6 +8,9 @@ public interface ICommandBuilder : ITargetBuilder /// ICommandBuilder Composes(params TargetRef[] refs); + + /// + ICommandBuilder Parallel(params TargetRef[] refs); } /// diff --git a/src/Nullean.Make/Discovery/ClassTargetSource.cs b/src/Nullean.Make/Discovery/ClassTargetSource.cs index 6b71fdb..01d5507 100644 --- a/src/Nullean.Make/Discovery/ClassTargetSource.cs +++ b/src/Nullean.Make/Discovery/ClassTargetSource.cs @@ -13,8 +13,9 @@ internal sealed class ClassTargetSource(BuildGraph graph) : ITargetSource 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)); + // Requires are gates: they run before the composed stages, whatever order they were declared in. + foreach (var (kind, parallel, items) in node.Stages.OrderBy(s => s.Kind)) + spec.Add(kind, Resolve(items), parallel); if (node.TypedBody is { } typed && node.DtoType is not null) spec.Body = _ => InvokeTyped(typed, value); diff --git a/src/Nullean.Make/Discovery/TargetBuilderImpl.cs b/src/Nullean.Make/Discovery/TargetBuilderImpl.cs index 6953e1c..09214c0 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); + _node.AddReference(Execution.StageKind.Requires, 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); + _node.AddReference(Execution.StageKind.Requires, r); return this; } @@ -89,14 +89,20 @@ ICommandBuilder ICommandBuilder.Executes(Func body) ICommandBuilder ICommandBuilder.Requires(params TargetRef[] refs) { foreach (var r in refs) - _node.Requires.Add(r); + _node.AddReference(Execution.StageKind.Requires, r); + return this; + } + + ICommandBuilder ICommandBuilder.Parallel(params TargetRef[] refs) + { + _node.AddParallel(refs); return this; } ICommandBuilder ICommandBuilder.Composes(params TargetRef[] refs) { foreach (var r in refs) - _node.Composes.Add(r); + _node.AddReference(Execution.StageKind.Composes, r); return this; } } @@ -135,7 +141,7 @@ public ITargetBuilder OnlyWhen(Func condition) public ITargetBuilder DependsOn(params TargetRef[] refs) { foreach (var r in refs) - _node.Requires.Add(r); + _node.AddReference(Execution.StageKind.Requires, r); return this; } public ITargetBuilder Executes(Action body) @@ -170,13 +176,19 @@ ITargetBuilder ITargetBuilder.Executes(Func body) ICommandBuilder ICommandBuilder.Requires(params TargetRef[] refs) { foreach (var r in refs) - _node.Requires.Add(r); + _node.AddReference(Execution.StageKind.Requires, r); return this; } + ICommandBuilder ICommandBuilder.Parallel(params TargetRef[] refs) + { + _node.AddParallel(refs); + return this; + } + ICommandBuilder ICommandBuilder.Composes(params TargetRef[] refs) { foreach (var r in refs) - _node.Composes.Add(r); + _node.AddReference(Execution.StageKind.Composes, r); return this; } } diff --git a/src/Nullean.Make/Discovery/TargetNode.cs b/src/Nullean.Make/Discovery/TargetNode.cs index 5b50c1e..64e8c48 100644 --- a/src/Nullean.Make/Discovery/TargetNode.cs +++ b/src/Nullean.Make/Discovery/TargetNode.cs @@ -27,6 +27,26 @@ internal sealed class TargetNode /// Composes references — always run. public List Composes { get; } = new(); + /// The same references as and , in declared stages. + public List<(Execution.StageKind Kind, bool Parallel, List Items)> Stages { get; } = new(); + + /// Records a reference in its list and in the stages: the last stage when it is of the same kind and sequential. + public void AddReference(Execution.StageKind kind, TargetRef reference, bool parallelStage = false) + { + (kind == Execution.StageKind.Requires ? Requires : Composes).Add(reference); + if (!parallelStage && Stages.Count > 0 && Stages[^1].Kind == kind && !Stages[^1].Parallel) + Stages[^1].Items.Add(reference); + else + Stages.Add((kind, parallelStage, [reference])); + } + + /// Starts a parallel stage of composed references. + public void AddParallel(TargetRef[] references) + { + Composes.AddRange(references); + Stages.Add((Execution.StageKind.Composes, true, [.. references])); + } + /// 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 8bd4f82..a111f96 100644 --- a/src/Nullean.Make/Execution/DepGraphExecutor.cs +++ b/src/Nullean.Make/Execution/DepGraphExecutor.cs @@ -49,44 +49,156 @@ public static int DrawWholeGraph(BuildGraph graph, GraphFormat format) } } + /// + /// Runs the plan. An instance starts once everything it waits for has finished, and at most --jobs run at + /// once, the earliest in the plan first. With one job, or a plan without parallel stages, that is the plan's order. + /// The first failure cancels the targets still running and starts no more, unless --keep-going lets the + /// targets that do not depend on it finish. + /// public static async Task ExecuteAsync(RunPlan plan, ParsedArgs parsed) { var context = new MakeContext(parsed.GlobalValues, parsed.SingleTarget) { TargetArgs = parsed.TargetArgs }; + // A plan without a parallel stage runs one target at a time, in its order, whatever --jobs says. + var concurrent = CanRunSideBySide(plan) && (parsed.Jobs ?? Environment.ProcessorCount) > 1; + var jobs = concurrent ? parsed.Jobs ?? Environment.ProcessorCount : 1; - foreach (var step in plan.Instances) + using var cancellation = new CancellationTokenSource(); + var stdout = Console.Out; + var stderr = Console.Error; + var gate = new object(); + var mode = parsed.Output ?? OutputMode.Prefixed; + if (concurrent) { - // A named command that only sequences other targets has nothing of its own to run. - if (step.IsRoot && step.Spec.Body is null) - continue; + Console.SetOut(new OutputRouter(stdout, error: false)); + Console.SetError(new OutputRouter(stderr, error: true)); + } + + var done = new HashSet(); + var blocked = new HashSet(); + var running = new Dictionary, TargetInstance>(); + var pending = plan.Instances.ToList(); + var failures = new List<(TargetInstance Step, int ExitCode)>(); + var started = DateTime.UtcNow; + var timings = new List<(TargetInstance Step, TimeSpan Elapsed)>(); + + try + { + while (pending.Count > 0 || running.Count > 0) + { + var stopping = failures.Count > 0 && !parsed.KeepGoing; + while (!stopping && running.Count < jobs) + { + // A target that waits for one that failed, or for one that could not run, cannot run either. + foreach (var waiting in pending.Where(p => p.Prerequisites.Any(blocked.Contains)).ToList()) + { + blocked.Add(waiting); + pending.Remove(waiting); + } + var next = pending.FirstOrDefault(p => p.Prerequisites.All(done.Contains)); + if (next is null) + break; + pending.Remove(next); + + // A named command that only sequences other targets has nothing of its own to run. + if (next.IsRoot && next.Spec.Body is null) + { + done.Add(next); + continue; + } + var sink = concurrent ? new TargetSink(next.Name, mode, stdout, stderr, gate) : null; + lock (gate) + ExecutionLog.Starting(next, stdout); + running[RunStep(next, context.ForTarget(cancellation.Token, sink), sink)] = next; + } + + if (running.Count == 0) + break; + + var finished = await Task.WhenAny(running.Keys); + var step = running[finished]; + running.Remove(finished); + var (exitCode, elapsed, message) = await finished; + if (exitCode == 0) + { + done.Add(step); + timings.Add((step, elapsed)); + lock (gate) + ExecutionLog.Finished(step, elapsed, stdout); + continue; + } + + blocked.Add(step); + if (exitCode < 0) + continue; // cancelled because another target failed + + failures.Add((step, exitCode)); + lock (gate) + stderr.WriteLine($"[make] Target '{string.Join("/", step.Node.Route)}' failed: {message}"); + if (!parsed.KeepGoing) + await cancellation.CancelAsync(); + } + } + finally + { + if (concurrent) + { + Console.SetOut(stdout); + Console.SetError(stderr); + } + } + + if (concurrent) + ExecutionLog.Summary(timings, DateTime.UtcNow - started, failures.Select(f => f.Step).ToList(), stdout); + return failures.Count == 0 ? 0 : failures[0].ExitCode; + } + + /// Whether two targets of the plan can ever be ready at once: a parallel stage, or roots that do not chain. + private static bool CanRunSideBySide(RunPlan plan) => + plan.Instances.Any(i => i.Stages.Any(s => s.Parallel && s.Items.Count(item => item.Instance is not null) > 1)) || !plan.Chained && plan.Roots.Count > 1; + + /// + /// Runs one instance on its own task. Returns 0, the exit code of a failure, or -1 when the run's cancellation + /// stopped it. + /// + private static Task<(int ExitCode, TimeSpan Elapsed, string? Message)> RunStep(TargetInstance step, MakeContext context, TargetSink? sink) => + Task.Run(async () => + { var start = DateTime.UtcNow; - ExecutionLog.Starting(step); MakeContext.Current = context; + OutputRouter.Current = sink; try { - await InvokeStep(step); + await InvokeStep(step, context.CancellationToken); + return (0, DateTime.UtcNow - start, (string?)null); + } + catch (OperationCanceledException) when (context.CancellationToken.IsCancellationRequested) + { + return (-1, DateTime.UtcNow - start, null); } catch (MakeException ex) { - Console.Error.WriteLine($"[make] Target '{string.Join("/", step.Node.Route)}' failed: {ex.Message}"); - return ex.ExitCode; + return (ex.ExitCode, DateTime.UtcNow - start, ex.Message); + } + catch (Exception ex) when (context.CancellationToken.IsCancellationRequested) + { + // A body stopped by the cancellation fails with whatever its command threw; that is not a failure of its own. + _ = ex; + return (-1, DateTime.UtcNow - start, null); } catch (Exception ex) { - Console.Error.WriteLine($"[make] Target '{string.Join("/", step.Node.Route)}' failed: {ex.Message}"); - return 1; + return (1, DateTime.UtcNow - start, ex.Message); } finally { + sink?.Complete(); + OutputRouter.Current = null; MakeContext.Current = null; } - ExecutionLog.Finished(step, DateTime.UtcNow - start); - } - - return 0; - } + }); - private static async Task InvokeStep(TargetInstance step) + private static async Task InvokeStep(TargetInstance step, CancellationToken token) { if (step.Spec.OnlyWhen is not null && !step.Spec.OnlyWhen()) { @@ -95,6 +207,6 @@ private static async Task InvokeStep(TargetInstance step) } if (step.Spec.Body is not null) - await step.Spec.Body(CancellationToken.None); + await step.Spec.Body(token); } } diff --git a/src/Nullean.Make/Execution/ExecutionLog.cs b/src/Nullean.Make/Execution/ExecutionLog.cs index c9f23d0..a2ae93a 100644 --- a/src/Nullean.Make/Execution/ExecutionLog.cs +++ b/src/Nullean.Make/Execution/ExecutionLog.cs @@ -4,10 +4,33 @@ namespace Nullean.Make.Execution; internal static class ExecutionLog { - public static void Starting(TargetInstance step) => Console.WriteLine($"Starting {CliHelpFormatting.Accent(step.Name)}"); + public static void Starting(TargetInstance step, TextWriter output) => output.WriteLine($"Starting {CliHelpFormatting.Accent(step.Name)}"); - public static void Finished(TargetInstance step, TimeSpan elapsed) => - Console.WriteLine($"Finished {CliHelpFormatting.Accent(step.Name)} ({elapsed.TotalSeconds:F1}s)"); + public static void Finished(TargetInstance step, TimeSpan elapsed, TextWriter output) => + output.WriteLine($"Finished {CliHelpFormatting.Accent(step.Name)} ({elapsed.TotalSeconds:F1}s)"); public static void Skipped(TargetInstance step) => Console.WriteLine($"Skipped {CliHelpFormatting.Placeholder(step.Name)}"); + + /// + /// After a run in which targets ran side by side: each target's time, and the wall-clock time against their sum, + /// which is what running them side by side saved. + /// + public static void Summary( + IReadOnlyList<(TargetInstance Step, TimeSpan Elapsed)> timings, + TimeSpan wall, + IReadOnlyList failed, + TextWriter output + ) + { + if (timings.Count + failed.Count == 0) + return; + var width = timings.Select(t => t.Step.Name.Length).Concat(failed.Select(f => f.Name.Length)).Max() + 2; + output.WriteLine(); + foreach (var (step, elapsed) in timings) + output.WriteLine($" {step.Name.PadRight(width)}{elapsed.TotalSeconds,7:F1}s"); + foreach (var step in failed) + output.WriteLine($" {step.Name.PadRight(width)} failed"); + var sum = timings.Aggregate(TimeSpan.Zero, (total, t) => total + t.Elapsed); + output.WriteLine($" {CliHelpFormatting.Section("Took")} {wall.TotalSeconds:F1}s for {sum.TotalSeconds:F1}s of work"); + } } diff --git a/src/Nullean.Make/Execution/OutputRouter.cs b/src/Nullean.Make/Execution/OutputRouter.cs new file mode 100644 index 0000000..ec89bc5 --- /dev/null +++ b/src/Nullean.Make/Execution/OutputRouter.cs @@ -0,0 +1,138 @@ +using System.Text; + +namespace Nullean.Make.Execution; + +/// How the output of targets that run at the same time reaches the console. +internal enum OutputMode +{ + /// Each line as it is written, with the target's name in front of it. + Prefixed, + + /// A target's lines held back and written together when it finishes. + Grouped +} + +/// +/// Stands in for and while targets run side by side. A target's +/// task sets ; what it writes goes through the target's sink, and everything else goes straight +/// through. A line is written whole, so lines of two targets never mix. +/// +internal sealed class OutputRouter : TextWriter +{ + private static readonly AsyncLocal _current = new(); + + private readonly TextWriter _inner; + private readonly bool _error; + + public OutputRouter(TextWriter inner, bool error) + { + _inner = inner; + _error = error; + } + + /// The sink of the target whose task is running, or null outside one. + public static TargetSink? Current { get => _current.Value; set => _current.Value = value; } + + public TextWriter Inner => _inner; + + public override Encoding Encoding => _inner.Encoding; + + public override void Write(char value) + { + if (Current is { } sink) + sink.Write(value, _error); + else + _inner.Write(value); + } + + public override void Write(string? value) + { + if (Current is { } sink) + sink.Write(value, _error); + else + _inner.Write(value); + } + + public override void WriteLine(string? value) + { + if (Current is { } sink) + { + sink.Write(value, _error); + sink.Write('\n', _error); + } + else + _inner.WriteLine(value); + } + + public override void Flush() => _inner.Flush(); +} + +/// Collects one target's output into lines, and writes them prefixed or keeps them for the end. +internal sealed class TargetSink(string name, OutputMode mode, TextWriter stdout, TextWriter stderr, object gate) +{ + private readonly StringBuilder _out = new(); + private readonly StringBuilder _err = new(); + private readonly List<(bool Error, string Line)> _held = new(); + + public void Write(char value, bool error) + { + var buffer = error ? _err : _out; + if (value == '\n') + { + Emit(error, buffer.ToString().TrimEnd('\r')); + buffer.Clear(); + } + else + buffer.Append(value); + } + + public void Write(string? value, bool error) + { + if (value is null) + return; + foreach (var c in value) + Write(c, error); + } + + /// A line written by the target's process, which arrives whole. + public void Line(string line, bool error) => Emit(error, line); + + private void Emit(bool error, string line) + { + if (mode == OutputMode.Grouped) + { + lock (_held) + _held.Add((error, line)); + return; + } + lock (gate) + (error ? stderr : stdout).WriteLine($"{CliPrefix(name)}{line}"); + } + + /// Writes what is left in the buffers and, when grouped, every line held back. + public void Complete() + { + if (_out.Length > 0) + Write('\n', false); + if (_err.Length > 0) + Write('\n', true); + if (mode != OutputMode.Grouped) + return; + + lock (gate) + { + var actions = Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true"; + if (actions) + stdout.WriteLine($"::group::{name}"); + lock (_held) + { + foreach (var (isError, line) in _held) + (isError ? stderr : stdout).WriteLine(line); + } + if (actions) + stdout.WriteLine("::endgroup::"); + } + } + + private static string CliPrefix(string name) => Nullean.Argh.Help.CliHelpFormatting.DocRemarksLine($"[{name}] "); +} diff --git a/src/Nullean.Make/Execution/RunPlan.cs b/src/Nullean.Make/Execution/RunPlan.cs index 3216189..8dc7ac1 100644 --- a/src/Nullean.Make/Execution/RunPlan.cs +++ b/src/Nullean.Make/Execution/RunPlan.cs @@ -123,7 +123,9 @@ public TargetInstance Visit(DepRef reference, bool isRoot, IReadOnlyList barrier = []; + // An instance's own dependencies wait for what it waits for: in `composes [a; b]`, b's dependencies start + // after a, not alongside it. + IReadOnlyList barrier = waitFor; foreach (var stage in spec.Stages) { var items = new List(); diff --git a/src/Nullean.Make/Execution/RunSwitches.cs b/src/Nullean.Make/Execution/RunSwitches.cs new file mode 100644 index 0000000..0f2a952 --- /dev/null +++ b/src/Nullean.Make/Execution/RunSwitches.cs @@ -0,0 +1,65 @@ +using System.Globalization; +using Nullean.Make.Parsing; + +namespace Nullean.Make.Execution; + +/// +/// The switches every Make entry point reads besides -s, --help and --version: --graph, +/// -j / --jobs, -k / --keep-going and --output. A global option the build declares +/// under the same name wins, so adding these breaks no script that already uses one of them. +/// +internal static class RunSwitches +{ + /// Reads the switch at args[i] into and advances past it. + /// when args[i] is not one of the switches. + public static bool TryRead(IReadOnlyList args, ref int i, ParsedArgs parsed, Func declaredByBuild) + { + var arg = args[i]; + var name = arg.Split('=', 2)[0]; + if (declaredByBuild(name)) + return false; + + if (GraphOption.TryRead(args, ref i) is { } format) + { + parsed.Graph = format; + return true; + } + + switch (name) + { + case "-j" or "--jobs": + parsed.Jobs = ParseJobs(Value(args, ref i, name)); + return true; + case "-k" or "--keep-going": + parsed.KeepGoing = true; + i++; + return true; + case "--output": + parsed.Output = Value(args, ref i, name).ToLowerInvariant() switch + { + "prefixed" => OutputMode.Prefixed, + "grouped" => OutputMode.Grouped, + var other => throw new MakeException($"Unknown output mode '{other}' for '--output'. Known: prefixed, grouped.", 2) + }; + return true; + } + return false; + } + + /// The value of --name=value or --name value. + private static string Value(IReadOnlyList args, ref int i, string name) + { + var arg = args[i++]; + var eq = arg.IndexOf('='); + if (eq > 0) + return arg[(eq + 1)..]; + if (i >= args.Count) + throw new MakeException($"Missing value for '{name}'.", 2); + return args[i++]; + } + + private static int ParseJobs(string raw) => + int.TryParse(raw, NumberStyles.None, CultureInfo.InvariantCulture, out var jobs) && jobs > 0 + ? jobs + : throw new MakeException($"'--jobs' takes a number of targets greater than 0, not '{raw}'.", 2); +} diff --git a/src/Nullean.Make/Help/MakeHelpPrinter.cs b/src/Nullean.Make/Help/MakeHelpPrinter.cs index 7371955..75f8bcf 100644 --- a/src/Nullean.Make/Help/MakeHelpPrinter.cs +++ b/src/Nullean.Make/Help/MakeHelpPrinter.cs @@ -177,8 +177,13 @@ public static void PrintCommand(TargetNode node, BuildGraph graph, string script if (node.ComposesResolved.Count > 0) { Console.WriteLine($" {CliHelpFormatting.Section("Composes")} (always runs):"); - foreach (var dep in node.ComposesResolved) - Console.WriteLine($" {num++,2}. {CliHelpFormatting.Placeholder(string.Join(" ", dep.Route))}"); + foreach (var (sideBySide, items) in ComposedStages(node, graph)) + { + // The targets of a parallel stage share a number: they start together. + var number = num++; + foreach (var dep in items) + Console.WriteLine($" {number,2}. {CliHelpFormatting.Placeholder(string.Join(" ", dep.Route))}{(sideBySide ? " (parallel)" : "")}"); + } Console.WriteLine(); } @@ -209,6 +214,22 @@ private static void PrintRunOrder(TargetNode node, BuildGraph graph, string scri Console.WriteLine(); } + /// The composed targets by stage, from the graph's source; one sequential stage when it has none. + private static List<(bool Parallel, List Items)> ComposedStages(TargetNode node, BuildGraph graph) + { + if (graph.Source is not { } source) + return [(false, node.ComposesResolved)]; + var spec = source.Describe(node, source.DefaultValue(node)); + var stages = spec.Stages.Where(s => s.Kind == StageKind.Composes).ToList(); + if (!stages.Any(s => s.Parallel)) + return [.. stages.SelectMany(s => s.Items).Select(i => (false, new List { i.Node }))]; + return [ + .. stages.SelectMany( + s => s.Parallel ? [(true, s.Items.Select(i => i.Node).ToList())] : s.Items.Select(i => (false, new List { i.Node })) + ) + ]; + } + private static string CommandSummary(TargetNode node) { var req = node.RequiresResolved.Select(d => string.Join(" ", d.Route)).ToList(); @@ -245,6 +266,16 @@ private static void PrintGlobalOptions(BuildGraph graph, string scriptName) 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"); + // A build option with the same short name wins, so help shows only the long name then. + string Short(string name) => graph.GlobalOptions.Any(o => o.Short?.TrimStart('-') == name) ? " " : $"-{name}, "; + + Console.WriteLine( + $" {CliHelpFormatting.Placeholder($"{Short("j")}--jobs "),-30} How many targets may run at once (default: one per processor)" + ); + Console.WriteLine( + $" {CliHelpFormatting.Placeholder($"{Short("k")}--keep-going"),-30} After a failure, finish the targets that do not depend on it" + ); + Console.WriteLine($" {CliHelpFormatting.Placeholder(" --output "),-30} Output of targets running side by side: prefixed or grouped"); foreach (var opt in graph.GlobalOptions) { diff --git a/src/Nullean.Make/MakeAppOfT.cs b/src/Nullean.Make/MakeAppOfT.cs index 1c94b55..a1d0546 100644 --- a/src/Nullean.Make/MakeAppOfT.cs +++ b/src/Nullean.Make/MakeAppOfT.cs @@ -79,6 +79,9 @@ public UnionOptionRef Option(string longName, string? description = null, /// public IUnionTargetBuilder Target(Func body) => Target().Executes(body); + /// A target whose body receives the run's cancellation token, cancelled when another target fails. + public IUnionTargetBuilder Target(Func body) => Target().Executes(body); + /// A target that runs after (skipped under -s). public IUnionTargetBuilder Target(TUnion[] dependsOn, Action body) => Target().DependsOn(dependsOn).Executes(body); @@ -149,10 +152,10 @@ public async Task RunAsync(string[] args) string[] remaining; bool singleTarget, showHelp, showVersion; - GraphFormat? graphFormat; + var switches = new ParsedArgs(); try { - (remaining, singleTarget, showHelp, showVersion, graphFormat) = ExtractGlobals(args); + (remaining, singleTarget, showHelp, showVersion) = ExtractGlobals(args, switches); } catch (MakeException ex) { @@ -190,7 +193,7 @@ public async Task RunAsync(string[] args) Console.Error.WriteLine($"Unknown target '{unknown}'."); return 2; } - if (graphFormat is { } format) + if (switches.Graph is { } format) return DepGraphExecutor.DrawWholeGraph(_graph, format); MakeHelpPrinter.PrintRoot(_graph, scriptName); return 0; @@ -202,7 +205,10 @@ public async Task RunAsync(string[] args) return 2; } - var parsed = new ParsedArgs { Target = targetNode, TargetArgs = targetArgs, SingleTarget = singleTarget, Graph = graphFormat }; + switches.Target = targetNode; + switches.TargetArgs = targetArgs; + switches.SingleTarget = singleTarget; + var parsed = switches; return await DepGraphExecutor.ExecuteAsync(targetNode, parsed, _graph); } @@ -256,13 +262,12 @@ private TargetNode ResolveCase(TargetNode from, string caseTypeName) // ── Argv helpers ────────────────────────────────────────────────────────── - private (string[] remaining, bool single, bool help, bool version, GraphFormat? graph) ExtractGlobals(string[] argv) + private (string[] remaining, bool single, bool help, bool version) ExtractGlobals(string[] argv, ParsedArgs switches) { var remaining = new List(); var single = false; var help = false; var version = false; - GraphFormat? graph = null; var i = 0; while (i < argv.Length) { @@ -285,11 +290,8 @@ private TargetNode ResolveCase(TargetNode from, string caseTypeName) i++; continue; } - if (GraphOption.TryRead(argv, ref i) is { } format) - { - graph = format; + if (RunSwitches.TryRead(argv, ref i, switches, IsDeclared)) continue; - } var matched = false; foreach (var opt in _options) @@ -320,9 +322,12 @@ private TargetNode ResolveCase(TargetNode from, string caseTypeName) i++; } } - return (remaining.ToArray(), single, help, version, graph); + return (remaining.ToArray(), single, help, version); } + private bool IsDeclared(string name) => + _options.Any(o => o.Long == name || o.Short == name || "--" + o.Long.TrimStart('-') == name || "-" + o.Short?.TrimStart('-') == name); + private (string routeKey, string[] targetArgs) ResolveRoute(string[] remaining) { var tokens = new List(); diff --git a/src/Nullean.Make/MakeContext.cs b/src/Nullean.Make/MakeContext.cs index ea9d893..391f767 100644 --- a/src/Nullean.Make/MakeContext.cs +++ b/src/Nullean.Make/MakeContext.cs @@ -1,4 +1,5 @@ using System.Threading; +using Nullean.Make.Execution; namespace Nullean.Make; @@ -25,6 +26,19 @@ internal MakeContext(Dictionary rawValues, bool singleTarget) /// The raw CLI tokens that followed the route (available to F# payload-case SyncBody closures). public string[] TargetArgs { get; internal set; } = []; + /// + /// Cancelled when another target of the run fails and the run stops. A body that runs for long should pass it on; + /// already does. + /// + public CancellationToken CancellationToken { get; private init; } + + /// Where the target's output goes while targets run side by side, or null when it has the console. + internal TargetSink? Sink { get; private init; } + /// Reads the raw string value for a global option. Returns when not supplied. public string? GetRaw(string longName) => _rawValues.TryGetValue(longName.TrimStart('-'), out var v) ? v : null; + + /// The context one target runs in. + internal MakeContext ForTarget(CancellationToken token, TargetSink? sink) => + new(_rawValues, _singleTarget) { TargetArgs = TargetArgs, CancellationToken = token, Sink = sink }; } diff --git a/src/Nullean.Make/Parsing/ArgvParser.cs b/src/Nullean.Make/Parsing/ArgvParser.cs index 3a4923c..4aed2c5 100644 --- a/src/Nullean.Make/Parsing/ArgvParser.cs +++ b/src/Nullean.Make/Parsing/ArgvParser.cs @@ -15,6 +15,15 @@ internal sealed class ParsedArgs /// Set by --graph: draw the plan in this format and run nothing. public Execution.GraphFormat? Graph { get; set; } + + /// -j / --jobs: how many targets may run at once. null means one per processor. + public int? Jobs { get; set; } + + /// -k / --keep-going: after a failure, let the targets that do not depend on it finish. + public bool KeepGoing { get; set; } + + /// --output: how the output of targets that run side by side reaches the console. + public Execution.OutputMode? Output { get; set; } public string? HelpTarget { get; set; } } @@ -120,11 +129,8 @@ private static List ExtractGlobals(string[] args, BuildGraph graph, Make i++; continue; } - if (Execution.GraphOption.TryRead(args, ref i) is { } graphFormat) - { - result.Graph = graphFormat; + if (Execution.RunSwitches.TryRead(args, ref i, result, n => IsDeclared(graph, n))) continue; - } // Global options var matched = false; @@ -161,6 +167,9 @@ private static List ExtractGlobals(string[] args, BuildGraph graph, Make return remaining; } + private static bool IsDeclared(BuildGraph graph, string name) => + graph.GlobalOptions.Any(o => o.Long == name || o.Short == name || "--" + o.Long.TrimStart('-') == name || "-" + o.Short?.TrimStart('-') == name); + private static void SetProperty(PropertyInfo? prop, MakeBuild build, string raw, string flagName) { if (prop is null) diff --git a/src/Nullean.Make/README.md b/src/Nullean.Make/README.md index f1a3d13..5343e2e 100644 --- a/src/Nullean.Make/README.md +++ b/src/Nullean.Make/README.md @@ -93,6 +93,18 @@ The package's source generator finds each `new MakeApp(...)` and records `app.Command(requires, composes)` sequences other targets. `requires` are gates, such as tests, and `-s` skips them. `composes` always run, in order. An optional third argument is a body that runs last. +`app.Command()` builds the same in stages. `.Parallel(...)` adds a stage whose targets run side by side; the stages +run in the order they are declared: + +```csharp +Release => app.Command().Requires(new Test()).Parallel(new PackNuget(), new DocsBuild()).Composes(new Publish()), +``` + +`-j` / `--jobs` caps how many targets run at once (default: one per processor). The first failure cancels the targets +still running; `-k` / `--keep-going` lets the ones that do not depend on it finish. Output of targets running side by +side carries their names, or `--output grouped` writes each target's lines together. See +[Running targets side by side](https://argh.nullean.net/make/parallel). + ## Running commands `using static Nullean.Make.Shell;` brings in `Exec`: diff --git a/src/Nullean.Make/Shell.cs b/src/Nullean.Make/Shell.cs index e24b1e7..664afad 100644 --- a/src/Nullean.Make/Shell.cs +++ b/src/Nullean.Make/Shell.cs @@ -22,11 +22,36 @@ public static void Exec(string commandLine) var parts = Split(commandLine); if (parts.Count == 0) throw new ArgumentException("The command line is empty.", nameof(commandLine)); - Proc.Exec(parts[0], parts.Skip(1).ToArray()); + Exec(parts[0], parts.Skip(1).ToArray()); } /// Runs with each argument passed as is, with no splitting or quoting. - public static void Exec(string binary, params string[] arguments) => Proc.Exec(binary, arguments); + /// + /// On its own the command shares the console. While targets run side by side, its output goes through the target's + /// prefixed or grouped output instead, and a failing target elsewhere in the run stops it. + /// + public static void Exec(string binary, params string[] arguments) + { + var context = MakeContext.Current; + if (context?.Sink is not { } sink) + { + Proc.Exec(binary, arguments); + return; + } + + context.CancellationToken.ThrowIfCancellationRequested(); + var result = Proc.StartRedirected(new StartArguments(binary, arguments), new SinkLineHandler(sink), context.CancellationToken); + context.CancellationToken.ThrowIfCancellationRequested(); + if (result.ExitCode != 0) + throw new ProcExecException($"Process exited with '{result.ExitCode}' \"{binary} {string.Join(" ", arguments)}\"") { ExitCode = result.ExitCode }; + } + + private sealed class SinkLineHandler(Execution.TargetSink sink) : ProcNet.Std.IConsoleLineHandler + { + public void Handle(ProcNet.Std.LineOut lineOut) => sink.Line(lineOut.Line, lineOut.Error); + + public void Handle(Exception e) => sink.Line(e.Message, true); + } /// Splits a command line the way does. public static IReadOnlyList Split(string commandLine) diff --git a/src/Nullean.Make/UnionGraph/IUnionTargetBuilder.cs b/src/Nullean.Make/UnionGraph/IUnionTargetBuilder.cs index bb18254..ed7b5e9 100644 --- a/src/Nullean.Make/UnionGraph/IUnionTargetBuilder.cs +++ b/src/Nullean.Make/UnionGraph/IUnionTargetBuilder.cs @@ -43,9 +43,29 @@ public interface IUnionTargetBuilder /// Composes targets by case type. IUnionTargetBuilder Composes(); + /// + /// Gates that run before the composed targets, in order, and that -s skips. The same as + /// , named for commands: app.Command().Requires(new Test()).Composes(new Pack()). + /// + IUnionTargetBuilder Requires(params TUnion[] gates); + + /// + /// Composes targets that run side by side, as one stage: each starts once the stages before it have finished, and + /// the stages after it wait for all of them. Stages run in the order they are declared: + /// app.Command().Requires(new Test()).Parallel(new PackNuget(), new PackDocker()).Composes(new Publish()). + /// -j caps how many targets run at once. + /// + IUnionTargetBuilder Parallel(params TUnion[] targets); + /// Registers a synchronous execution body. Closed-over case values are the real CLI-parsed ones at execution time. IUnionTargetBuilder Executes(Action body); /// Registers an asynchronous execution body. IUnionTargetBuilder Executes(Func body); + + /// + /// Registers an asynchronous execution body that receives the run's cancellation token. The token is cancelled when + /// another target fails and the run stops. + /// + IUnionTargetBuilder Executes(Func body); } diff --git a/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs b/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs index 1b11e81..46bfcb1 100644 --- a/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs +++ b/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs @@ -16,10 +16,9 @@ internal sealed class UnionTargetBuilderImpl : IUnionTargetBuilder? _asyncBody; + private Func? _asyncBody; private readonly TargetKind _kind; - private readonly List _deps = new(); - private readonly List _comps = new(); + private readonly List<(Execution.StageKind Kind, bool Parallel, List Items)> _stages = new(); internal UnionTargetBuilderImpl(TargetKind kind = TargetKind.Target) => _kind = kind; @@ -41,58 +40,81 @@ public IUnionTargetBuilder Executes(Action body) return this; } public IUnionTargetBuilder Executes(Func body) + { + _asyncBody = _ => body(); + return this; + } + + public IUnionTargetBuilder Executes(Func body) { _asyncBody = body; return this; } + public IUnionTargetBuilder Requires(params TUnion[] gates) => DependsOn(gates); + + public IUnionTargetBuilder Parallel(params TUnion[] targets) + { + _stages.Add((Execution.StageKind.Composes, true, targets.Select(ToRef).ToList())); + return this; + } + + /// Adds to the last stage when it is of the same kind and sequential, else starts a stage. + private void Append(Execution.StageKind kind, CaseRef reference) + { + if (_stages.Count > 0 && _stages[^1].Kind == kind && !_stages[^1].Parallel) + _stages[^1].Items.Add(reference); + else + _stages.Add((kind, false, [reference])); + } + public IUnionTargetBuilder DependsOn(params TUnion[] deps) { foreach (var dep in deps) - _deps.Add(ToRef(dep)); + Append(Execution.StageKind.Requires, ToRef(dep)); return this; } public IUnionTargetBuilder DependsOn() { - _deps.Add(new CaseRef(typeof(T1).Name, null)); + Append(Execution.StageKind.Requires, new CaseRef(typeof(T1).Name, null)); return this; } public IUnionTargetBuilder DependsOn() { - _deps.Add(new CaseRef(typeof(T1).Name, null)); - _deps.Add(new CaseRef(typeof(T2).Name, null)); + Append(Execution.StageKind.Requires, new CaseRef(typeof(T1).Name, null)); + Append(Execution.StageKind.Requires, new CaseRef(typeof(T2).Name, null)); return this; } public IUnionTargetBuilder DependsOn() { - _deps.Add(new CaseRef(typeof(T1).Name, null)); - _deps.Add(new CaseRef(typeof(T2).Name, null)); - _deps.Add(new CaseRef(typeof(T3).Name, null)); + Append(Execution.StageKind.Requires, new CaseRef(typeof(T1).Name, null)); + Append(Execution.StageKind.Requires, new CaseRef(typeof(T2).Name, null)); + Append(Execution.StageKind.Requires, new CaseRef(typeof(T3).Name, null)); return this; } public IUnionTargetBuilder DependsOn() { - _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)); + Append(Execution.StageKind.Requires, new CaseRef(typeof(T1).Name, null)); + Append(Execution.StageKind.Requires, new CaseRef(typeof(T2).Name, null)); + Append(Execution.StageKind.Requires, new CaseRef(typeof(T3).Name, null)); + Append(Execution.StageKind.Requires, new CaseRef(typeof(T4).Name, null)); return this; } public IUnionTargetBuilder Composes(params TUnion[] targets) { foreach (var t in targets) - _comps.Add(ToRef(t)); + Append(Execution.StageKind.Composes, ToRef(t)); return this; } public IUnionTargetBuilder Composes() { - _comps.Add(new CaseRef(typeof(T1).Name, null)); + Append(Execution.StageKind.Composes, new CaseRef(typeof(T1).Name, null)); return this; } @@ -102,14 +124,15 @@ public IUnionTargetBuilder Composes() internal string? DescriptionValue => _description; internal bool IsHidden => _hidden; internal Action? SyncBody => _syncBody; - internal Func? AsyncBody => _asyncBody; - internal IReadOnlyList Deps => _deps; - internal IReadOnlyList Comps => _comps; + internal Func? AsyncBody => _asyncBody; + internal IReadOnlyList Deps => _stages.Where(s => s.Kind == Execution.StageKind.Requires).SelectMany(s => s.Items).ToList(); + internal IReadOnlyList Comps => _stages.Where(s => s.Kind == Execution.StageKind.Composes).SelectMany(s => s.Items).ToList(); + internal IReadOnlyList<(Execution.StageKind Kind, bool Parallel, List Items)> Stages => _stages; - internal async Task ExecuteAsync() + internal async Task ExecuteAsync(CancellationToken token) { if (_asyncBody is not null) - await _asyncBody(); + await _asyncBody(token); else _syncBody?.Invoke(); } diff --git a/src/Nullean.Make/UnionGraph/UnionTargetSource.cs b/src/Nullean.Make/UnionGraph/UnionTargetSource.cs index a851639..0551d55 100644 --- a/src/Nullean.Make/UnionGraph/UnionTargetSource.cs +++ b/src/Nullean.Make/UnionGraph/UnionTargetSource.cs @@ -22,10 +22,11 @@ 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()); + // Requires are gates: they run before the composed stages, whatever order they were declared in. + foreach (var (kind, parallel, items) in builder.Stages.OrderBy(s => s.Kind)) + spec.Add(kind, items.Select(d => new DepRef(resolve(node, d.TypeName), d.Value)).ToList(), parallel); if (builder.SyncBody is not null || builder.AsyncBody is not null) - spec.Body = _ => builder.ExecuteAsync(); + spec.Body = builder.ExecuteAsync; return spec; } 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 1893294..f10c5ae 100644 --- a/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj +++ b/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj @@ -16,6 +16,7 @@ + diff --git a/tests/Nullean.Make.Fs.Tests/ParallelTests.fs b/tests/Nullean.Make.Fs.Tests/ParallelTests.fs new file mode 100644 index 0000000..7dec8a8 --- /dev/null +++ b/tests/Nullean.Make.Fs.Tests/ParallelTests.fs @@ -0,0 +1,61 @@ +module Nullean.Make.Fs.Tests.ParallelTests + +open System +open System.IO +open System.Threading +open System.Collections.Concurrent +open TUnit.Core +open Nullean.Make.Fs + +type Side = + | Left + | Right + | After + | Both + +let private run (args: string list) = + let log = ConcurrentQueue() + use both = new CountdownEvent(2) + // Left and Right each wait for the other to start: side by side they meet, one after the other they do not. + let meet name = + both.Signal() |> ignore + log.Enqueue(if both.Wait(TimeSpan.FromSeconds 3.) then $"{name}:met" else $"{name}:alone") + let app = MakeApp("build", None) + app.Bind <| function + | Left -> Make.target [] "" (fun _ -> meet "left") + | Right -> Make.target [] "" (fun _ -> meet "right") + | After -> Make.target [] "" (fun _ -> log.Enqueue "after") + | Both -> command { + concurrently [Left; Right] + composes [After] } + 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 ParallelTests() = + + [] + member _.``A concurrently stage runs its targets side by side``() = + let exit, log, _ = run ["both"; "-j"; "2"] + Assert.Equal(0, exit) + Assert.Equal([ "left:met"; "right:met" ], log |> List.take 2 |> List.sort) + Assert.Equal("after", List.last log) + + [] + member _.``One job runs a parallel stage one target at a time``() = + let exit, log, _ = run ["both"; "-j"; "1"] + Assert.Equal(0, exit) + Assert.Equal([ "left:alone"; "right:met"; "after" ], log) + + [] + member _.``Graph draws the parallel stage``() = + let _, _, stdout = run ["both"; "--graph"] + Assert.Contains("parallel", stdout) diff --git a/tests/Nullean.Make.Tests/ParallelTests.cs b/tests/Nullean.Make.Tests/ParallelTests.cs new file mode 100644 index 0000000..cb23532 --- /dev/null +++ b/tests/Nullean.Make.Tests/ParallelTests.cs @@ -0,0 +1,337 @@ +using System.Collections.Concurrent; +using AwesomeAssertions; +using static Nullean.Make.Shell; + +namespace Nullean.Make.Tests; + +public record class Left; + +public record class Right; + +public record class After; + +public record class Broken; + +public record class Slow; + +public record class Both; + +public record class Failing; + +public record class Loud; + +public record class Shelled; + +public record class Gated; + +public union Side(Left, Right, After, Broken, Slow, Both, Failing, Loud, Shelled, Gated); + +/// Targets in a parallel stage run side by side; the stage after waits for all of them. +[NotInParallel] +public class ParallelTests +{ + private sealed record Run(int ExitCode, IReadOnlyList Log, string Stdout, string Stderr, TimeSpan Elapsed); + + /// + /// Left and Right each wait, up to a few seconds, for the other to start. Side by side they meet and log + /// met; one after the other the first gives up and logs alone. + /// + private static async Task RunAsync(params string[] args) + { + var log = new ConcurrentQueue(); + using var both = new CountdownEvent(2); + + void Meet(string name) + { + Console.WriteLine($"{name}-before"); + both.Signal(); + log.Enqueue(both.Wait(TimeSpan.FromSeconds(3)) ? $"{name}:met" : $"{name}:alone"); + Console.WriteLine($"{name}-after"); + } + + var app = new MakeApp("build"); + var gate = app.Flag("--gate", "-k", "A build's own -k"); + app.Bind( + s => + s.Value switch + { + Left => app.Target(() => Meet("left")), + Right => app.Target(() => Meet("right")), + After => app.Target(() => log.Enqueue("after")), + Broken => app.Target(() => throw new MakeException("broken on purpose", 3)), + Slow => + app.Target(async ct => + { + await Task.Delay(TimeSpan.FromSeconds(20), ct); + log.Enqueue("slow:done"); + }), + Both => app.Command().Parallel(new Left(), new Right()).Composes(new After()), + Failing => app.Command().Parallel(new Slow(), new Broken()).Composes(new After()), + Loud => app.Command().Parallel(new Left(), new Right()).Executes(() => Console.WriteLine("loud done")), + Shelled => app.Command().Parallel(new Left(), new Right()), + Gated => app.Target(() => log.Enqueue($"gate:{gate.Value}")), + _ => throw new InvalidOperationException($"unmapped case {s.Value}") + } + ); + + var (stdout, stderr) = (new StringWriter(), new StringWriter()); + var (oldOut, oldErr) = (Console.Out, Console.Error); + Console.SetOut(stdout); + Console.SetError(stderr); + var watch = System.Diagnostics.Stopwatch.StartNew(); + try + { + var exit = await app.RunAsync(args); + return new Run(exit, [.. log], stdout.ToString(), stderr.ToString(), watch.Elapsed); + } + finally + { + Console.SetOut(oldOut); + Console.SetError(oldErr); + } + } + + [Test] + public async Task A_parallel_stage_runs_its_targets_side_by_side() + { + var run = await RunAsync("both", "-j", "2"); + run.ExitCode.Should().Be(0); + run.Log.Take(2).Should().BeEquivalentTo("left:met", "right:met"); + run.Log.Last().Should().Be("after"); + } + + [Test] + public async Task One_job_runs_a_parallel_stage_one_target_at_a_time() + { + var run = await RunAsync("both", "--jobs=1"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("left:alone", "right:met", "after"); + } + + [Test] + public async Task A_failure_cancels_the_targets_still_running_and_starts_no_more() + { + var run = await RunAsync("failing", "-j", "2"); + run.ExitCode.Should().Be(3); + run.Stderr.Should().Contain("Target 'broken' failed: broken on purpose"); + run.Log.Should().NotContain("slow:done").And.NotContain("after"); + run.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(15)); + } + + [Test] + public async Task Keep_going_lets_the_targets_that_do_not_depend_on_a_failure_finish() + { + var run = await RunAsync("failing", "-j", "2", "--keep-going"); + run.ExitCode.Should().Be(3); + run.Log.Should().Contain("slow:done").And.NotContain("after"); + } + + [Test] + public async Task Output_of_targets_running_side_by_side_is_prefixed_with_their_names() + { + var run = await RunAsync("loud", "-j", "2"); + run.ExitCode.Should().Be(0); + run.Stdout.Should().Contain("[loud] loud done"); + run.Stdout.Should().Contain("Took"); + } + + [Test] + public async Task Prefixed_output_interleaves_the_lines_of_targets_running_side_by_side() + { + // Both targets write their first line before either writes its second, so prefixed lines interleave. + var run = await RunAsync("both", "-j", "2"); + var lines = run.Stdout.Split(Environment.NewLine).Select(l => l.Trim()).ToList(); + var before = new[] { lines.IndexOf("[left] left-before"), lines.IndexOf("[right] right-before") }; + var after = new[] { lines.IndexOf("[left] left-after"), lines.IndexOf("[right] right-after") }; + before.Should().NotContain(-1); + before.Max().Should().BeLessThan(after.Min()); + } + + [Test] + public async Task Grouped_output_writes_a_targets_lines_together() + { + var run = await RunAsync("both", "-j", "2", "--output", "grouped"); + run.ExitCode.Should().Be(0); + run.Log.Take(2).Should().BeEquivalentTo("left:met", "right:met"); + var lines = run.Stdout.Split(Environment.NewLine).Select(l => l.Trim()).ToList(); + lines.Should().Contain("left-before").And.NotContain(l => l.StartsWith("[left]")); + lines.IndexOf("left-after").Should().Be(lines.IndexOf("left-before") + 1); + lines.IndexOf("right-after").Should().Be(lines.IndexOf("right-before") + 1); + } + + [Test] + public async Task A_build_option_with_the_same_short_name_wins() + { + var run = await RunAsync("gated", "-k"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("gate:True"); + } + + [Test] + public async Task Jobs_takes_a_number_greater_than_zero() + { + var run = await RunAsync("both", "-j", "0"); + run.ExitCode.Should().Be(2); + run.Stderr.Should().Contain("'--jobs' takes a number of targets greater than 0, not '0'."); + } + + [Test] + public async Task Graph_draws_a_parallel_stage() + { + var run = await RunAsync("both", "--graph"); + run.Stdout.Should().Contain("parallel").And.Contain("Runs: left → right → after"); + } +} + +public record class EchoA; + +public record class EchoB; + +public record class Echoes; + +public union Echoing(EchoA, EchoB, Echoes); + +[NotInParallel] +public class ParallelShellTests +{ + [Test] + public async Task A_command_run_with_exec_goes_through_the_targets_prefixed_output() + { + var app = new MakeApp("build"); + app.Bind( + e => + e.Value switch + { + EchoA => app.Target(() => Exec("dotnet", "--version")), + EchoB => app.Target(() => Exec("dotnet", "--version")), + Echoes => app.Command().Parallel(new EchoA(), new EchoB()), + _ => throw new InvalidOperationException() + } + ); + var stdout = new StringWriter(); + var (oldOut, oldErr) = (Console.Out, Console.Error); + Console.SetOut(stdout); + Console.SetError(new StringWriter()); + try + { + (await app.RunAsync(["echoes", "-j", "2"])).Should().Be(0); + } + finally + { + Console.SetOut(oldOut); + Console.SetError(oldErr); + } + var lines = stdout.ToString().Split('\n'); + lines.Should().Contain(l => l.StartsWith("[echo-a] ") && char.IsDigit(l["[echo-a] ".Length])); + lines.Should().Contain(l => l.StartsWith("[echo-b] ") && char.IsDigit(l["[echo-b] ".Length])); + } +} + +public class ParallelBuild : MakeBuild +{ + public static ConcurrentQueue Log { get; } = new(); + public static CountdownEvent Both { get; set; } = new(2); + + private static void Meet(string name) + { + Both.Signal(); + Log.Enqueue(Both.Wait(TimeSpan.FromSeconds(3)) ? $"{name}:met" : $"{name}:alone"); + } + + public Target Left => _ => _.Executes(() => Meet("left")); + + public Target Right => _ => _.Executes(() => Meet("right")); + + public Target Last => _ => _.Executes(() => Log.Enqueue("last")); + + public Command Both2 => _ => _.Named("both").Parallel(Left, Right).Composes(Last); +} + +[NotInParallel] +public class ClassParallelTests +{ + [Test] + public async Task A_parallel_stage_runs_its_targets_side_by_side() + { + ParallelBuild.Log.Clear(); + ParallelBuild.Both = new CountdownEvent(2); + var (oldOut, oldErr) = (Console.Out, Console.Error); + Console.SetOut(new StringWriter()); + Console.SetError(new StringWriter()); + try + { + (await MakeApp.Execute(["both", "-j", "2"])).Should().Be(0); + } + finally + { + Console.SetOut(oldOut); + Console.SetError(oldErr); + } + ParallelBuild.Log.Take(2).Should().BeEquivalentTo("left:met", "right:met"); + ParallelBuild.Log.Last().Should().Be("last"); + } +} + +public record class First; + +public record class Second; + +public record class SecondsDependency; + +public record class InOrder; + +public record class Fanned; + +public union Ordered(First, Second, SecondsDependency, InOrder, Fanned); + +/// Only a parallel stage runs targets side by side; a list, and everything a list item depends on, stays in order. +[NotInParallel] +public class OrderTests +{ + private static async Task> RunAsync(params string[] args) + { + var log = new System.Collections.Concurrent.ConcurrentQueue(); + var app = new MakeApp("build"); + app.Bind(o => o.Value switch + { + First => app.Target(async () => + { + log.Enqueue("first:start"); + await Task.Delay(200); + log.Enqueue("first:end"); + }), + SecondsDependency => app.Target(() => log.Enqueue("seconds-dependency")), + Second => app.Target([new SecondsDependency()], () => log.Enqueue("second")), + InOrder => app.Command([], [new First(), new Second()]), + Fanned => app.Command().Composes(new First()).Parallel(new Second(), new SecondsDependency()), + _ => throw new InvalidOperationException() + }); + var (oldOut, oldErr) = (Console.Out, Console.Error); + Console.SetOut(new StringWriter()); + Console.SetError(new StringWriter()); + try + { + (await app.RunAsync(args)).Should().Be(0); + } + finally + { + Console.SetOut(oldOut); + Console.SetError(oldErr); + } + return [.. log]; + } + + [Test] + public async Task A_list_items_dependencies_wait_for_the_item_before_it() + { + var log = await RunAsync("in-order", "-j", "4"); + log.Should().Equal("first:start", "first:end", "seconds-dependency", "second"); + } + + [Test] + public async Task A_parallel_stages_dependencies_wait_for_the_stage_before_it() + { + var log = await RunAsync("fanned", "-j", "4"); + log.Take(2).Should().Equal("first:start", "first:end"); + } +} From 3dcae3dee4533fedc255408a7d3a2aa9e12a51f7 Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 12 Nov 2026 08:51:37 +0100 Subject: [PATCH 05/11] Add conditions, ordering, cleanup and preconditions to every target surface `OnlyWhen` skips a body, and the union and F# surfaces now have it too. `After` orders a target after another in the same run without adding it. `Cleanup` runs targets at the end of the run once a target started, even after a failure. `NeedsEnv` and `NeedsTool` are checked for every target before the first one starts, and the run lists everything missing. F# pipes a target through `onlyWhen`, `after`, `cleanup`, `needsEnv`, `needsTool` and `describe`; `describe` gives an .fsx script its descriptions. Co-Authored-By: Claude Opus 5.5 --- docs/_docset.yml | 1 + docs/make/index.md | 3 + docs/make/modifiers.md | 82 ++++++ src/Nullean.Make.Fs/Builders.fs | 44 +++ src/Nullean.Make.Fs/FsGraphBuilder.fs | 25 +- src/Nullean.Make.Fs/README.md | 18 +- src/Nullean.Make.Fs/Types.fs | 29 ++ src/Nullean.Make/Command.cs | 12 + .../Discovery/ClassTargetSource.cs | 4 + .../Discovery/TargetBuilderImpl.cs | 76 ++++++ src/Nullean.Make/Discovery/TargetNode.cs | 12 + .../Execution/DepGraphExecutor.cs | 46 +++- src/Nullean.Make/Execution/PlanRenderer.cs | 13 + src/Nullean.Make/Execution/RunPlan.cs | 130 ++++++++- src/Nullean.Make/Execution/TargetSource.cs | 12 + src/Nullean.Make/README.md | 15 + src/Nullean.Make/Target.cs | 18 ++ src/Nullean.Make/TargetOfT.cs | 12 + .../UnionGraph/IUnionTargetBuilder.cs | 26 ++ .../UnionGraph/UnionTargetBuilderImpl.cs | 40 +++ .../UnionGraph/UnionTargetSource.cs | 10 + tests/Nullean.Make.Fs.Tests/ModifierTests.fs | 80 ++++++ .../Nullean.Make.Fs.Tests.fsproj | 1 + tests/Nullean.Make.Tests/ModifierTests.cs | 258 ++++++++++++++++++ 24 files changed, 959 insertions(+), 8 deletions(-) create mode 100644 docs/make/modifiers.md create mode 100644 tests/Nullean.Make.Fs.Tests/ModifierTests.fs create mode 100644 tests/Nullean.Make.Tests/ModifierTests.cs diff --git a/docs/_docset.yml b/docs/_docset.yml index fb5c3a3..7fc58a5 100644 --- a/docs/_docset.yml +++ b/docs/_docset.yml @@ -51,6 +51,7 @@ toc: - file: index.md - file: graph.md - file: parallel.md + - file: modifiers.md - file: wrappers.md - file: mise.md - file: makefile.md diff --git a/docs/make/index.md b/docs/make/index.md index 5e70e54..ae9a94f 100644 --- a/docs/make/index.md +++ b/docs/make/index.md @@ -13,6 +13,9 @@ [**Running targets side by side**](parallel.md) - Parallel stages, `-j`, `--keep-going`, and the output of targets that run at once. +[**Conditions, ordering and cleanup**](modifiers.md) - `OnlyWhen`, `After`, `Cleanup`, and checks for environment +variables and tools before the run starts. + [**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 diff --git a/docs/make/modifiers.md b/docs/make/modifiers.md new file mode 100644 index 0000000..b88ca3f --- /dev/null +++ b/docs/make/modifiers.md @@ -0,0 +1,82 @@ +# Conditions, ordering and cleanup + +A target can say when its body runs, what it runs after, what cleans up after it, and what it needs before the run +starts. C# adds them to the builder; F# pipes the target through functions. + +```csharp +StartDb => app.Target(() => Exec("docker compose up -d db")).Cleanup(new StopDb()), +Test t => app.Target([new Build(), new StartDb()], () => Exec("dotnet test")).After(new Lint()), +Publish => app.Target(() => Exec("dotnet nuget push build/output/*.nupkg")) + .OnlyWhen(() => !dryRun.Value) + .NeedsEnv("NUGET_API_KEY") + .NeedsTool("docker"), +``` + +```fsharp +| StartDb -> target [] { sh $"docker compose up -d db" } |> cleanup [StopDb] +| Test o -> target [Build; StartDb] { sh $"dotnet test" } |> after [Lint] +| Publish -> target [] { sh $"dotnet nuget push build/output/*.nupkg" } + |> onlyWhen (fun () -> not dryRun.Value) + |> needsEnv ["NUGET_API_KEY"] + |> needsTool ["docker"] + |> describe "Push the packages" +``` + +The `MakeBuild` class has the same methods: `.OnlyWhen(...)`, `.After(Lint)`, `.Cleanup(StopDb)`, `.NeedsEnv(...)` and +`.NeedsTool(...)`. + +## Conditions + +`OnlyWhen` / `onlyWhen` skips the body when the condition returns false. The target's dependencies still run. The log +shows the target as skipped. `--graph` evaluates the condition to show what it skips; a run evaluates it again just +before the target would start. + +## Running after a target without depending on it + +`After` / `after` orders a target after another one when both are in the run. It does not add the other target to +the run: `package` alone runs only `package`. + +It matters where the plan leaves two targets unordered, such as the targets of a parallel stage: + +```csharp +Ci => app.Command().Parallel(new Package(), new Lint()), // package waits for lint +``` + +A target named with its default value matches the other target with any value; with another value, only that value. +An `After` that contradicts an order the plan already has, such as a composed list that names `package` before +`lint`, is a cycle. The run exits `1` and names the targets involved. + +## Cleanup + +`Cleanup` / `cleanup` names targets whose bodies run at the end of the run once this target has started, even when +the run fails. Cleanups run newest first, and each runs once however many targets name it. A cleanup runs its body +only, not its dependencies. + +```text +Starting start-db +Starting integration +[make] Target 'integration' failed: 2 tests failed +Starting stop-db +Finished stop-db (1.2s) +``` + +The run keeps the exit code of the failure. When only a cleanup fails, the run exits with the cleanup's exit code. + +## What a target needs + +`NeedsEnv` / `needsEnv` and `NeedsTool` / `needsTool` name environment variables that must be set and executables +that must be on the `PATH`. The run checks every target it would run before the first one starts, and lists everything +missing: + +```text +[make] The run cannot start. It needs: + the environment variable NUGET_API_KEY, for publish + docker on the PATH, for docker image +``` + +A target whose condition is false needs nothing. `--graph` lists what is missing under `Missing:` and runs nothing. + +## Descriptions in F# scripts + +A target's description comes from the `///` comment on its case, read from the XML documentation file. An `.fsx` +script has no such file. `|> describe "..."` sets the description in the script itself. diff --git a/src/Nullean.Make.Fs/Builders.fs b/src/Nullean.Make.Fs/Builders.fs index f688a78..d257a9b 100644 --- a/src/Nullean.Make.Fs/Builders.fs +++ b/src/Nullean.Make.Fs/Builders.fs @@ -101,3 +101,47 @@ module MakeBuilders = /// A command that sequences other targets. See CommandBuilder. let command = CommandBuilder() + +/// +/// Pipe a target or command through these to add to it: +/// +/// | Publish -> target [] { sh $"dotnet nuget push build/output/*.nupkg" } +/// |> onlyWhen (fun () -> not dryRun.Value) +/// |> needsEnv ["NUGET_API_KEY"] +/// |> describe "Push the packages" +/// +/// +[] +module MakeModifiers = + /// + /// Skips the body when returns false. The dependencies still run. --graph + /// evaluates it to show what it skips; a run evaluates it again just before the target would start. + /// + let onlyWhen (condition: unit -> bool) (definition: Definition<'TCase>) = + definition |> Modifiers.add (fun m -> { m with OnlyWhen = Some condition }) + + /// + /// Runs after when they are in the same run, without adding them to it. A case with its + /// default payload matches the target with any payload; with another payload, only that payload. + /// + let after (targets: 'TCase list) (definition: Definition<'TCase>) = + definition |> Modifiers.add (fun m -> { m with After = m.After @ targets }) + + /// + /// Targets whose bodies run at the end of the run, newest first, once this target has started, even when the run + /// fails. A cleanup runs its body only, and once however many targets name it. + /// + let cleanup (targets: 'TCase list) (definition: Definition<'TCase>) = + definition |> Modifiers.add (fun m -> { m with Cleanup = m.Cleanup @ targets }) + + /// Environment variables that must be set. The run checks them before anything starts, and lists every one missing. + let needsEnv (variables: string list) (definition: Definition<'TCase>) = + definition |> Modifiers.add (fun m -> { m with NeedsEnv = m.NeedsEnv @ variables }) + + /// Executables that must be on the PATH. The run checks them before anything starts, and lists every one missing. + let needsTool (tools: string list) (definition: Definition<'TCase>) = + definition |> Modifiers.add (fun m -> { m with NeedsTool = m.NeedsTool @ tools }) + + /// The description help shows, for a script without an XML documentation file such as an .fsx. + let describe (description: string) (definition: Definition<'TCase>) = + definition |> Modifiers.add (fun m -> { m with Description = Some description }) diff --git a/src/Nullean.Make.Fs/FsGraphBuilder.fs b/src/Nullean.Make.Fs/FsGraphBuilder.fs index 9c58575..f5655e3 100644 --- a/src/Nullean.Make.Fs/FsGraphBuilder.fs +++ b/src/Nullean.Make.Fs/FsGraphBuilder.fs @@ -71,7 +71,15 @@ type private FsTargetSource<'TCase when 'TCase : comparison and 'TCase : not nul 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 + let definition, modifiers = Modifiers.unwrap (bind (unbox<'TCase> value)) + spec.OnlyWhen <- modifiers.OnlyWhen |> Option.map (fun f -> Func f) |> Option.toObj + // A case named with its default payload in `after` matches the target with any payload. + let defaultOf (d: 'TCase) = let n = resolve node d in if box d = box (fst nodeCases.[n]) then null else box d + spec.After.AddRange(modifiers.After |> List.map (fun d -> DepRef(resolve node d, defaultOf d))) + spec.Cleanup.AddRange(refs node modifiers.Cleanup) + spec.NeedsEnv.AddRange(modifiers.NeedsEnv) + spec.NeedsTool.AddRange(modifiers.NeedsTool) + match definition with | FsTarget(_, deps, b, _) -> spec.Add(Nullean.Make.Execution.StageKind.Requires, refs node deps) spec.Body <- body b @@ -79,7 +87,7 @@ type private FsTargetSource<'TCase when 'TCase : comparison and 'TCase : not nul spec.Add(StageKind.Requires, refs node requires) for sideBySide, targets in stages do spec.Add(StageKind.Composes, refs node targets, sideBySide) b |> Option.iter (fun b -> spec.Body <- body b) - | FsNamespace _ -> () + | FsNamespace _ | FsWith _ -> () spec member _.FormatValue(node, value) = @@ -93,6 +101,10 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null> (optionDecls: (string * string option * string option * bool * Type option) list) : BuildGraph = + // The source sees modifiers; everything here reads the target or command they wrap. + let bindWithModifiers = bind + let bind (v: 'TCase) = fst (Modifiers.unwrap (bindWithModifiers v)) + let graph = BuildGraph() graph.AppName <- appName graph.AppDescription <- match appDescription with Some d -> d | None -> null @@ -147,7 +159,10 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null> // NOTE: namespace sub-cases must be parameterless; payload sub-DUs are not supported. let registerNode (route: string[]) (def: Definition<'TCase>) (caseInfoForBody: UnionCaseInfo) (key: 'TCase) = let kind = match def with | FsCommand _ -> TargetKind.Command | _ -> TargetKind.Target - let explicitDesc = match def with | FsTarget(d,_,_,_) | FsCommand(d,_,_,_) -> d | _ -> "" + let explicitDesc = + match (snd (Modifiers.unwrap (bindWithModifiers key))).Description with + | Some d -> d + | None -> match def with | FsTarget(d,_,_,_) | FsCommand(d,_,_,_) -> d | _ -> "" // No explicit description: use the case's /// doc comment (T:. in the XML doc file). let rawDesc = if not (String.IsNullOrEmpty explicitDesc) then explicitDesc @@ -215,7 +230,7 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null> raise (MakeException($"Target '{route}' depends on '{caseKey dep}', which is not a target or command.", 1)) for KeyValue(_, (node, tcase)) in caseToNode do match bind tcase with - | FsNamespace _ -> () + | FsNamespace _ | FsWith _ -> () | FsTarget(_, deps, _, _) -> for dep in deps do node.RequiresResolved.Add(resolve node dep) | FsCommand(_, requires, stages, _) -> @@ -223,7 +238,7 @@ 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)) + graph.Source <- FsTargetSource<'TCase>(bindWithModifiers, nodeCases, (fun node dep -> resolve node dep)) match defaultCase with | None -> () diff --git a/src/Nullean.Make.Fs/README.md b/src/Nullean.Make.Fs/README.md index bbe25f7..9fda02e 100644 --- a/src/Nullean.Make.Fs/README.md +++ b/src/Nullean.Make.Fs/README.md @@ -146,9 +146,25 @@ See [Running targets side by side](https://argh.nullean.net/make/parallel). printfn $"published {sha}" }) } ``` +## Conditions, ordering and cleanup + +Pipe a target or command through these: + +```fsharp +| StartDb -> target [] { sh $"docker compose up -d db" } |> cleanup [StopDb] // at the end, even after a failure +| Package -> target [] { sh $"dotnet pack" } |> after [Lint] // after lint when both run +| Publish -> target [] { sh $"dotnet nuget push" } + |> onlyWhen (fun () -> not dryRun.Value) // skip the body; the dependencies still run + |> needsEnv ["NUGET_API_KEY"] // checked before anything starts + |> needsTool ["docker"] + |> describe "Push the packages" // for an .fsx script without an XML doc file +``` + +See [Conditions, ordering and cleanup](https://argh.nullean.net/make/modifiers). + ## Descriptions from doc comments -A target's description is the `///` doc comment on its DU case. The comment is read from the XML documentation file, so the build project needs `true`. A `.fsx` script produces no documentation file. In a script, pass a description with `Make.target` (below), or the target shows its name. +A target's description is the `///` doc comment on its DU case. The comment is read from the XML documentation file, so the build project needs `true`. A `.fsx` script produces no documentation file. In a script, pipe the target through `describe "..."`, or the target shows its name. ## Namespaces via nested DUs diff --git a/src/Nullean.Make.Fs/Types.fs b/src/Nullean.Make.Fs/Types.fs index 6f9a5de..b27f034 100644 --- a/src/Nullean.Make.Fs/Types.fs +++ b/src/Nullean.Make.Fs/Types.fs @@ -44,6 +44,35 @@ type Definition<'TCase> = /// stages: the composed targets in declared order; true marks a stage whose targets run side by side | FsCommand of desc: string * requires: 'TCase list * stages: (bool * 'TCase list) list * body: (FsContext -> unit) option | FsNamespace of segment: string * desc: string option + /// A target or command with what onlyWhen, after, cleanup, needsEnv, needsTool and describe added to it + | FsWith of inner: Definition<'TCase> * modifiers: Modifiers<'TCase> + +/// What the pipe functions add to a target or command. +and [] Modifiers<'TCase> = + internal + { OnlyWhen: (unit -> bool) option + After: 'TCase list + Cleanup: 'TCase list + NeedsEnv: string list + NeedsTool: string list + Description: string option } + +module internal Modifiers = + let empty<'TCase> : Modifiers<'TCase> = + { OnlyWhen = None; After = []; Cleanup = []; NeedsEnv = []; NeedsTool = []; Description = None } + + /// Adds to a definition's modifiers, wrapping it the first time. + let add (f: Modifiers<'TCase> -> Modifiers<'TCase>) (definition: Definition<'TCase>) = + match definition with + | FsWith(inner, modifiers) -> FsWith(inner, f modifiers) + | FsNamespace _ -> invalidArg "definition" "A namespace has no body to modify." + | inner -> FsWith(inner, f empty) + + /// The definition without its modifiers, and the modifiers. + let unwrap (definition: Definition<'TCase>) = + match definition with + | FsWith(inner, modifiers) -> inner, modifiers + | inner -> inner, empty /// Helpers for building Definition values inside app.Bind. module Make = diff --git a/src/Nullean.Make/Command.cs b/src/Nullean.Make/Command.cs index 64c3180..66e357f 100644 --- a/src/Nullean.Make/Command.cs +++ b/src/Nullean.Make/Command.cs @@ -18,6 +18,18 @@ public interface ICommandBuilder : ITargetBuilder /// new ICommandBuilder DependsOn(params TargetRef[] refs); + /// + new ICommandBuilder After(params TargetRef[] refs); + + /// + new ICommandBuilder Cleanup(params TargetRef[] refs); + + /// + new ICommandBuilder NeedsEnv(params string[] variables); + + /// + new ICommandBuilder NeedsTool(params string[] tools); + /// new ICommandBuilder Executes(Action body); diff --git a/src/Nullean.Make/Discovery/ClassTargetSource.cs b/src/Nullean.Make/Discovery/ClassTargetSource.cs index 01d5507..5fe93b3 100644 --- a/src/Nullean.Make/Discovery/ClassTargetSource.cs +++ b/src/Nullean.Make/Discovery/ClassTargetSource.cs @@ -13,6 +13,10 @@ internal sealed class ClassTargetSource(BuildGraph graph) : ITargetSource public InstanceSpec Describe(TargetNode node, object? value) { var spec = new InstanceSpec { OnlyWhen = node.OnlyWhen }; + spec.After.AddRange(Resolve(node.After)); + spec.Cleanup.AddRange(Resolve(node.Cleanup)); + spec.NeedsEnv.AddRange(node.NeedsEnv); + spec.NeedsTool.AddRange(node.NeedsTool); // Requires are gates: they run before the composed stages, whatever order they were declared in. foreach (var (kind, parallel, items) in node.Stages.OrderBy(s => s.Kind)) spec.Add(kind, Resolve(items), parallel); diff --git a/src/Nullean.Make/Discovery/TargetBuilderImpl.cs b/src/Nullean.Make/Discovery/TargetBuilderImpl.cs index 09214c0..8d3cfa3 100644 --- a/src/Nullean.Make/Discovery/TargetBuilderImpl.cs +++ b/src/Nullean.Make/Discovery/TargetBuilderImpl.cs @@ -35,6 +35,30 @@ public ITargetBuilder DependsOn(params TargetRef[] refs) return this; } + public ITargetBuilder After(params TargetRef[] refs) + { + _node.After.AddRange(refs); + return this; + } + + public ITargetBuilder Cleanup(params TargetRef[] refs) + { + _node.Cleanup.AddRange(refs); + return this; + } + + public ITargetBuilder NeedsEnv(params string[] variables) + { + _node.NeedsEnv.AddRange(variables); + return this; + } + + public ITargetBuilder NeedsTool(params string[] tools) + { + _node.NeedsTool.AddRange(tools); + return this; + } + public ITargetBuilder Executes(Action body) { _node.SyncBody = body; @@ -75,6 +99,30 @@ ICommandBuilder ICommandBuilder.DependsOn(params TargetRef[] refs) return this; } + ICommandBuilder ICommandBuilder.After(params TargetRef[] refs) + { + _node.After.AddRange(refs); + return this; + } + + ICommandBuilder ICommandBuilder.Cleanup(params TargetRef[] refs) + { + _node.Cleanup.AddRange(refs); + return this; + } + + ICommandBuilder ICommandBuilder.NeedsEnv(params string[] variables) + { + _node.NeedsEnv.AddRange(variables); + return this; + } + + ICommandBuilder ICommandBuilder.NeedsTool(params string[] tools) + { + _node.NeedsTool.AddRange(tools); + return this; + } + ICommandBuilder ICommandBuilder.Executes(Action body) { _node.SyncBody = body; @@ -144,6 +192,30 @@ public ITargetBuilder DependsOn(params TargetRef[] refs) _node.AddReference(Execution.StageKind.Requires, r); return this; } + public ITargetBuilder After(params TargetRef[] refs) + { + _node.After.AddRange(refs); + return this; + } + + public ITargetBuilder Cleanup(params TargetRef[] refs) + { + _node.Cleanup.AddRange(refs); + return this; + } + + public ITargetBuilder NeedsEnv(params string[] variables) + { + _node.NeedsEnv.AddRange(variables); + return this; + } + + public ITargetBuilder NeedsTool(params string[] tools) + { + _node.NeedsTool.AddRange(tools); + return this; + } + public ITargetBuilder Executes(Action body) { _node.TypedBody = body; @@ -161,6 +233,10 @@ public ITargetBuilder Executes(Func body) ITargetBuilder ITargetBuilder.Hidden() => Hidden(); ITargetBuilder ITargetBuilder.OnlyWhen(Func c) => OnlyWhen(c); ITargetBuilder ITargetBuilder.DependsOn(params TargetRef[] refs) => DependsOn(refs); + ITargetBuilder ITargetBuilder.After(params TargetRef[] refs) => After(refs); + ITargetBuilder ITargetBuilder.Cleanup(params TargetRef[] refs) => Cleanup(refs); + ITargetBuilder ITargetBuilder.NeedsEnv(params string[] variables) => NeedsEnv(variables); + ITargetBuilder ITargetBuilder.NeedsTool(params string[] tools) => NeedsTool(tools); ITargetBuilder ITargetBuilder.Executes(Action body) { _node.SyncBody = body; diff --git a/src/Nullean.Make/Discovery/TargetNode.cs b/src/Nullean.Make/Discovery/TargetNode.cs index 64e8c48..c3b2e7b 100644 --- a/src/Nullean.Make/Discovery/TargetNode.cs +++ b/src/Nullean.Make/Discovery/TargetNode.cs @@ -19,6 +19,18 @@ internal sealed class TargetNode public string? Description { get; set; } public bool Hidden { get; set; } public Func? OnlyWhen { get; set; } + + /// Targets this one runs after when they are in the same run. + public List After { get; } = new(); + + /// Targets whose bodies run at the end of the run once this one started. + public List Cleanup { get; } = new(); + + /// Environment variables that must be set before the run starts. + public List NeedsEnv { get; } = new(); + + /// Executables that must be on the PATH before the run starts. + public List NeedsTool { get; } = new(); public TargetKind Kind { get; set; } /// DependsOn / Requires references — skippable under -s. diff --git a/src/Nullean.Make/Execution/DepGraphExecutor.cs b/src/Nullean.Make/Execution/DepGraphExecutor.cs index a111f96..1716858 100644 --- a/src/Nullean.Make/Execution/DepGraphExecutor.cs +++ b/src/Nullean.Make/Execution/DepGraphExecutor.cs @@ -58,6 +58,17 @@ public static int DrawWholeGraph(BuildGraph graph, GraphFormat format) public static async Task ExecuteAsync(RunPlan plan, ParsedArgs parsed) { var context = new MakeContext(parsed.GlobalValues, parsed.SingleTarget) { TargetArgs = parsed.TargetArgs }; + + // Fail before anything runs, rather than at the target that needs what is missing. + var missing = plan.MissingPreconditions(); + if (missing.Count > 0) + { + Console.Error.WriteLine("[make] The run cannot start. It needs:"); + foreach (var (instance, what) in missing) + Console.Error.WriteLine($" {what}, for {instance.Name}"); + return 1; + } + // A plan without a parallel stage runs one target at a time, in its order, whatever --jobs says. var concurrent = CanRunSideBySide(plan) && (parsed.Jobs ?? Environment.ProcessorCount) > 1; var jobs = concurrent ? parsed.Jobs ?? Environment.ProcessorCount : 1; @@ -80,6 +91,7 @@ public static async Task ExecuteAsync(RunPlan plan, ParsedArgs parsed) var failures = new List<(TargetInstance Step, int ExitCode)>(); var started = DateTime.UtcNow; var timings = new List<(TargetInstance Step, TimeSpan Elapsed)>(); + var startOrder = new List(); try { @@ -106,6 +118,7 @@ public static async Task ExecuteAsync(RunPlan plan, ParsedArgs parsed) continue; } + startOrder.Add(next); var sink = concurrent ? new TargetSink(next.Name, mode, stdout, stderr, gate) : null; lock (gate) ExecutionLog.Starting(next, stdout); @@ -148,9 +161,40 @@ public static async Task ExecuteAsync(RunPlan plan, ParsedArgs parsed) } } + var cleanupExit = await RunCleanups(plan, startOrder, context); + if (concurrent) ExecutionLog.Summary(timings, DateTime.UtcNow - started, failures.Select(f => f.Step).ToList(), stdout); - return failures.Count == 0 ? 0 : failures[0].ExitCode; + return failures.Count > 0 ? failures[0].ExitCode : cleanupExit; + } + + /// + /// Runs the cleanup targets of every instance that started, newest first, each once, whether the run failed or not. + /// A cleanup runs its body only. Returns the exit code of the first cleanup that failed, or 0. + /// + private static async Task RunCleanups(RunPlan plan, List startOrder, MakeContext context) + { + var exitCode = 0; + var ran = new HashSet(); + for (var i = startOrder.Count - 1; i >= 0; i--) + { + if (!plan.Cleanups.TryGetValue(startOrder[i], out var cleanups)) + continue; + foreach (var cleanup in cleanups.Where(ran.Add)) + { + ExecutionLog.Starting(cleanup, Console.Out); + var (code, elapsed, message) = await RunStep(cleanup, context.ForTarget(CancellationToken.None, null), null); + if (code == 0) + { + ExecutionLog.Finished(cleanup, elapsed, Console.Out); + continue; + } + Console.Error.WriteLine($"[make] Cleanup '{string.Join("/", cleanup.Node.Route)}' failed: {message}"); + if (exitCode == 0) + exitCode = code; + } + } + return exitCode; } /// Whether two targets of the plan can ever be ready at once: a parallel stage, or roots that do not chain. diff --git a/src/Nullean.Make/Execution/PlanRenderer.cs b/src/Nullean.Make/Execution/PlanRenderer.cs index d9dd84a..74398a9 100644 --- a/src/Nullean.Make/Execution/PlanRenderer.cs +++ b/src/Nullean.Make/Execution/PlanRenderer.cs @@ -134,7 +134,13 @@ private static void WriteTree(RunPlan plan, TextWriter output) if (!plan.Chained && plan.Roots.Count > 1) return; var order = RunOrder(plan); + var cleanups = plan.Cleanups.Values.SelectMany(c => c).Distinct().Select(c => c.Name).ToList(); + if (cleanups.Count > 0) + order += $", then cleanup: {string.Join(", ", cleanups)}"; output.WriteLine($"{CliHelpFormatting.Section("Runs:")} {(order.Length == 0 ? "nothing" : order)}"); + + foreach (var (instance, what) in plan.MissingPreconditions()) + output.WriteLine($"{CliHelpFormatting.Section("Missing:")} {what}, for {instance.Name}"); } private static Line Build(TargetInstance instance, HashSet expanded) @@ -142,6 +148,11 @@ private static Line Build(TargetInstance instance, HashSet expan var text = instance.Name + Annotation(instance.Skipped); if (!expanded.Add(instance)) return new Line(text + Dim(" (above)"), []); + if (instance.Spec.After.Count > 0) + text += Dim($" after {string.Join(", ", instance.Spec.After.Select(a => string.Join(" ", a.Node.Route)))}"); + var needs = instance.Spec.NeedsEnv.Concat(instance.Spec.NeedsTool).ToList(); + if (needs.Count > 0) + text += Dim($" needs {string.Join(", ", needs)}"); var children = new List(); foreach (var kind in new[] { StageKind.Requires, StageKind.Composes }) @@ -167,6 +178,8 @@ private static Line Build(TargetInstance instance, HashSet expan else children.AddRange(lines); } + if (instance.Spec.Cleanup.Count > 0) + children.Add(new Line(Dim("cleanup, at the end"), [.. instance.Spec.Cleanup.Select(c => new Line(string.Join(" ", c.Node.Route), []))])); return new Line(text, children); } diff --git a/src/Nullean.Make/Execution/RunPlan.cs b/src/Nullean.Make/Execution/RunPlan.cs index 8dc7ac1..6c17496 100644 --- a/src/Nullean.Make/Execution/RunPlan.cs +++ b/src/Nullean.Make/Execution/RunPlan.cs @@ -59,6 +59,36 @@ internal sealed class RunPlan /// True when the roots run one after another; false for a drawing of unrelated roots. public bool Chained { get; init; } = true; + /// For each instance with cleanup targets, the instances that run at the end of the run once it started. + public IReadOnlyDictionary> Cleanups + { + get; + init; + } = new Dictionary>(); + + /// + /// What the run needs and does not have: an environment variable that is not set, or an executable not on the + /// PATH, for each instance whose body would run. A target whose condition is false needs nothing. + /// + public IReadOnlyList<(TargetInstance Instance, string Missing)> MissingPreconditions() + { + var missing = new List<(TargetInstance, string)>(); + foreach (var instance in Instances.Concat(Cleanups.Values.SelectMany(c => c)).Distinct()) + { + if (instance.Skipped is not null || instance.Spec.Body is null) + continue; + if (instance.Spec.NeedsEnv.Count + instance.Spec.NeedsTool.Count == 0) + continue; + if (instance.Spec.OnlyWhen is { } condition && !condition()) + continue; + foreach (var variable in instance.Spec.NeedsEnv.Where(v => string.IsNullOrEmpty(Environment.GetEnvironmentVariable(v)))) + missing.Add((instance, $"the environment variable {variable}")); + foreach (var tool in instance.Spec.NeedsTool.Where(t => !Preconditions.OnPath(t))) + missing.Add((instance, $"{tool} on the PATH")); + } + return missing; + } + /// /// 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 @@ -76,7 +106,8 @@ public static RunPlan Build(IReadOnlyList roots, ITargetSource source, P rootInstances.Add(instance); previous = instance; } - return new RunPlan { Roots = rootInstances, Instances = builder.Ordered, Chained = options.ChainRoots }; + var ordered = builder.ApplyAfter(); + return new RunPlan { Roots = rootInstances, Instances = ordered, Chained = options.ChainRoots, Cleanups = builder.ResolveCleanups(ordered) }; } private sealed class Builder(ITargetSource source, PlanOptions options) @@ -87,6 +118,79 @@ private sealed class Builder(ITargetSource source, PlanOptions options) public List Ordered { get; } = new(); + /// + /// Adds what each instance runs after, among the instances in the run, and orders the plan again: the earliest + /// instance whose prerequisites have all been placed comes next. + /// + public List ApplyAfter() + { + var any = false; + foreach (var instance in Ordered) + { + foreach (var reference in instance.Spec.After) + { + // A reference without a value matches the target with any value. + var matches = Ordered.Where( + i => i.Node == reference.Node && (reference.Value is null || Equals(i.Value, reference.Value)) && i != instance + ); + foreach (var match in matches) + { + instance.Prerequisites.Add(match); + any = true; + } + } + } + if (!any) + return Ordered; + + var placed = new HashSet(); + var result = new List(); + var remaining = Ordered.ToList(); + while (remaining.Count > 0) + { + var next = remaining.FirstOrDefault(i => i.Prerequisites.All(placed.Contains)); + if (next is null) + { + var stuck = remaining.Select(i => i.Name); + throw new MakeException($"The order the targets ask for has a cycle; none of these can go first: {string.Join(", ", stuck)}", 1); + } + remaining.Remove(next); + placed.Add(next); + next.Order = result.Count; + result.Add(next); + } + return result; + } + + /// The cleanup instances of each instance that declares some. A cleanup runs its body only, not its dependencies. + public Dictionary> ResolveCleanups(List ordered) + { + var cleanups = new Dictionary>(); + var shared = new Dictionary<(TargetNode, object?), TargetInstance>(); + foreach (var instance in ordered.Where(i => i.Spec.Cleanup.Count > 0)) + { + var list = new List(); + foreach (var reference in instance.Spec.Cleanup) + { + var value = Resolve(reference); + if (!shared.TryGetValue((reference.Node, value), out var cleanup)) + { + cleanup = new TargetInstance + { + Node = reference.Node, + Value = value, + Spec = source.Describe(reference.Node, value), + Name = ValueDisplay.Name(reference.Node, source.FormatValue(reference.Node, value)) + }; + shared[(reference.Node, value)] = cleanup; + } + list.Add(cleanup); + } + cleanups[instance] = list; + } + return cleanups; + } + private object? Resolve(DepRef reference) { if (reference.Value is not null) @@ -162,3 +266,27 @@ public TargetInstance Visit(DepRef reference, bool isRoot, IReadOnlyListChecks the things a target says it needs before the run starts. +internal static class Preconditions +{ + /// Whether is an executable on the PATH, with PATHEXT on Windows. + public static bool OnPath(string tool) + { + if (Path.IsPathRooted(tool)) + return File.Exists(tool); + var extensions = OperatingSystem.IsWindows() + ? (Environment.GetEnvironmentVariable("PATHEXT") ?? ".EXE;.CMD;.BAT").Split(';', StringSplitOptions.RemoveEmptyEntries).Prepend("") + : [""]; + var path = Environment.GetEnvironmentVariable("PATH") ?? ""; + foreach (var directory in path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + { + foreach (var extension in extensions) + { + if (File.Exists(Path.Combine(directory, tool + extension))) + return true; + } + } + return false; + } +} diff --git a/src/Nullean.Make/Execution/TargetSource.cs b/src/Nullean.Make/Execution/TargetSource.cs index 4758b99..ca0ab0c 100644 --- a/src/Nullean.Make/Execution/TargetSource.cs +++ b/src/Nullean.Make/Execution/TargetSource.cs @@ -56,6 +56,18 @@ internal sealed class InstanceSpec /// When it returns , the body is skipped. Its dependencies still run. public Func? OnlyWhen { get; set; } + /// Targets this one runs after when they are in the same run. They do not join the run because of it. + public List After { get; } = new(); + + /// Targets whose bodies run at the end of the run when this one started, even after a failure. + public List Cleanup { get; } = new(); + + /// Environment variables that must be set before the run starts. + public List NeedsEnv { get; } = new(); + + /// Executables that must be on the PATH before the run starts. + public List NeedsTool { get; } = new(); + public void Add(StageKind kind, IReadOnlyList items, bool parallel = false) { if (items.Count > 0) diff --git a/src/Nullean.Make/README.md b/src/Nullean.Make/README.md index 5343e2e..75d3b1b 100644 --- a/src/Nullean.Make/README.md +++ b/src/Nullean.Make/README.md @@ -105,6 +105,21 @@ still running; `-k` / `--keep-going` lets the ones that do not depend on it fini side carries their names, or `--output grouped` writes each target's lines together. See [Running targets side by side](https://argh.nullean.net/make/parallel). +## Conditions, ordering and cleanup + +A target builder takes more than dependencies: + +```csharp +StartDb => app.Target(() => Exec("docker compose up -d db")).Cleanup(new StopDb()), // runs at the end, even after a failure +Package => app.Target(() => Exec("dotnet pack")).After(new Lint()), // after lint when both run; does not add it +Publish => app.Target(() => Exec("dotnet nuget push")) + .OnlyWhen(() => !dryRun.Value) // skip the body; the dependencies still run + .NeedsEnv("NUGET_API_KEY") // checked before anything starts + .NeedsTool("docker"), +``` + +See [Conditions, ordering and cleanup](https://argh.nullean.net/make/modifiers). + ## Running commands `using static Nullean.Make.Shell;` brings in `Exec`: diff --git a/src/Nullean.Make/Target.cs b/src/Nullean.Make/Target.cs index a283a8c..636ee20 100644 --- a/src/Nullean.Make/Target.cs +++ b/src/Nullean.Make/Target.cs @@ -18,6 +18,24 @@ public interface ITargetBuilder /// Declares targets that must succeed before this target's body runs. Skipped under -s. ITargetBuilder DependsOn(params TargetRef[] refs); + /// + /// Runs after when they are in the same run, without adding them to it. A target named + /// without With matches it with any value; with With, only that value. + /// + ITargetBuilder After(params TargetRef[] refs); + + /// + /// Targets whose bodies run at the end of the run, newest first, once this target has started, even when the run + /// fails. A cleanup runs its body only, and once however many targets name it. + /// + ITargetBuilder Cleanup(params TargetRef[] refs); + + /// Environment variables that must be set. The run checks them before anything starts, and lists every one missing. + ITargetBuilder NeedsEnv(params string[] variables); + + /// Executables that must be on the PATH. The run checks them before anything starts, and lists every one missing. + ITargetBuilder NeedsTool(params string[] tools); + /// Executes the given action as this target's body. ITargetBuilder Executes(Action body); diff --git a/src/Nullean.Make/TargetOfT.cs b/src/Nullean.Make/TargetOfT.cs index 4775642..1d0c942 100644 --- a/src/Nullean.Make/TargetOfT.cs +++ b/src/Nullean.Make/TargetOfT.cs @@ -18,6 +18,18 @@ public interface ITargetBuilder : ITargetBuilder /// new ITargetBuilder DependsOn(params TargetRef[] refs); + /// + new ITargetBuilder After(params TargetRef[] refs); + + /// + new ITargetBuilder Cleanup(params TargetRef[] refs); + + /// + new ITargetBuilder NeedsEnv(params string[] variables); + + /// + new ITargetBuilder NeedsTool(params string[] tools); + /// Executes the given action with a bound instance of parsed from CLI tokens. ITargetBuilder Executes(Action body); diff --git a/src/Nullean.Make/UnionGraph/IUnionTargetBuilder.cs b/src/Nullean.Make/UnionGraph/IUnionTargetBuilder.cs index ed7b5e9..8ffaa7b 100644 --- a/src/Nullean.Make/UnionGraph/IUnionTargetBuilder.cs +++ b/src/Nullean.Make/UnionGraph/IUnionTargetBuilder.cs @@ -57,6 +57,32 @@ public interface IUnionTargetBuilder /// IUnionTargetBuilder Parallel(params TUnion[] targets); + /// + /// Skips the body when returns . The dependencies still run. + /// --graph evaluates it to show what it skips; a run evaluates it again just before the target would start. + /// + IUnionTargetBuilder OnlyWhen(Func condition); + + /// + /// Runs after when they are in the same run, without adding them to it: + /// .After(new Lint()) orders this target after lint only when something else runs lint. + /// A case with its default value matches the target with any value; with another value, only that value. + /// + IUnionTargetBuilder After(params TUnion[] targets); + + /// + /// Targets whose bodies run at the end of the run, newest first, once this target has started, even when the run + /// fails: StartDb => app.Target(...).Cleanup(new StopDb()). A cleanup runs its body only, and once + /// however many targets name it. + /// + IUnionTargetBuilder Cleanup(params TUnion[] targets); + + /// Environment variables that must be set. The run checks them before anything starts, and lists every one missing. + IUnionTargetBuilder NeedsEnv(params string[] variables); + + /// Executables that must be on the PATH. The run checks them before anything starts, and lists every one missing. + IUnionTargetBuilder NeedsTool(params string[] tools); + /// Registers a synchronous execution body. Closed-over case values are the real CLI-parsed ones at execution time. IUnionTargetBuilder Executes(Action body); diff --git a/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs b/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs index 46bfcb1..2b01336 100644 --- a/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs +++ b/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs @@ -19,6 +19,11 @@ internal sealed class UnionTargetBuilderImpl : IUnionTargetBuilder? _asyncBody; private readonly TargetKind _kind; private readonly List<(Execution.StageKind Kind, bool Parallel, List Items)> _stages = new(); + private readonly List _after = new(); + private readonly List _cleanup = new(); + private readonly List _needsEnv = new(); + private readonly List _needsTool = new(); + private Func? _onlyWhen; internal UnionTargetBuilderImpl(TargetKind kind = TargetKind.Target) => _kind = kind; @@ -53,6 +58,36 @@ public IUnionTargetBuilder Executes(Func body) public IUnionTargetBuilder Requires(params TUnion[] gates) => DependsOn(gates); + public IUnionTargetBuilder OnlyWhen(Func condition) + { + _onlyWhen = condition; + return this; + } + + public IUnionTargetBuilder After(params TUnion[] targets) + { + _after.AddRange(targets.Select(ToRef)); + return this; + } + + public IUnionTargetBuilder Cleanup(params TUnion[] targets) + { + _cleanup.AddRange(targets.Select(ToRef)); + return this; + } + + public IUnionTargetBuilder NeedsEnv(params string[] variables) + { + _needsEnv.AddRange(variables); + return this; + } + + public IUnionTargetBuilder NeedsTool(params string[] tools) + { + _needsTool.AddRange(tools); + return this; + } + public IUnionTargetBuilder Parallel(params TUnion[] targets) { _stages.Add((Execution.StageKind.Composes, true, targets.Select(ToRef).ToList())); @@ -128,6 +163,11 @@ public IUnionTargetBuilder Composes() internal IReadOnlyList Deps => _stages.Where(s => s.Kind == Execution.StageKind.Requires).SelectMany(s => s.Items).ToList(); internal IReadOnlyList Comps => _stages.Where(s => s.Kind == Execution.StageKind.Composes).SelectMany(s => s.Items).ToList(); internal IReadOnlyList<(Execution.StageKind Kind, bool Parallel, List Items)> Stages => _stages; + internal IReadOnlyList AfterRefs => _after; + internal IReadOnlyList CleanupRefs => _cleanup; + internal IReadOnlyList Env => _needsEnv; + internal IReadOnlyList Tools => _needsTool; + internal Func? Condition => _onlyWhen; internal async Task ExecuteAsync(CancellationToken token) { diff --git a/src/Nullean.Make/UnionGraph/UnionTargetSource.cs b/src/Nullean.Make/UnionGraph/UnionTargetSource.cs index 0551d55..a65362f 100644 --- a/src/Nullean.Make/UnionGraph/UnionTargetSource.cs +++ b/src/Nullean.Make/UnionGraph/UnionTargetSource.cs @@ -27,6 +27,16 @@ public InstanceSpec Describe(TargetNode node, object? value) spec.Add(kind, items.Select(d => new DepRef(resolve(node, d.TypeName), d.Value)).ToList(), parallel); if (builder.SyncBody is not null || builder.AsyncBody is not null) spec.Body = builder.ExecuteAsync; + spec.OnlyWhen = builder.Condition; + // A case named with its default value in After matches the target with any value. + foreach (var d in builder.AfterRefs) + { + var target = resolve(node, d.TypeName); + spec.After.Add(new DepRef(target, Equals(d.Value, DefaultValue(target)) ? null : d.Value)); + } + spec.Cleanup.AddRange(builder.CleanupRefs.Select(d => new DepRef(resolve(node, d.TypeName), d.Value))); + spec.NeedsEnv.AddRange(builder.Env); + spec.NeedsTool.AddRange(builder.Tools); return spec; } diff --git a/tests/Nullean.Make.Fs.Tests/ModifierTests.fs b/tests/Nullean.Make.Fs.Tests/ModifierTests.fs new file mode 100644 index 0000000..1be56a2 --- /dev/null +++ b/tests/Nullean.Make.Fs.Tests/ModifierTests.fs @@ -0,0 +1,80 @@ +module Nullean.Make.Fs.Tests.ModifierTests + +open System +open System.IO +open TUnit.Core +open Nullean.Make.Fs + +type Modified = + | Lint + | Package + | Ci + | StartDb + | StopDb + | Integration + | Push + | Optional + +let private variable = "NULLEAN_MAKE_FS_TEST_PUSH_KEY" + +let private run (args: string list) = + let log = ResizeArray() + let app = MakeApp("build", None) + let skip = app.Flag("--skip-optional") + app.Bind <| function + | Lint -> target [] { log.Add "lint" } + | Package -> target [] { log.Add "package" } |> after [Lint] + | Ci -> command { concurrently [Package; Lint] } + | StartDb -> target [] { log.Add "start-db" } |> cleanup [StopDb] + | StopDb -> target [] { log.Add "stop-db" } + | Integration -> target [StartDb] { failBuild "integration failed" } + | Push -> target [] { log.Add "push" } |> needsEnv [variable] |> describe "Push the packages" + | Optional -> target [Lint] { log.Add "optional" } |> onlyWhen (fun () -> not skip.Value) + 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() + exit, List.ofSeq log, string stdout, string stderr + finally + Console.SetOut oldOut + Console.SetError oldErr + +[] +type ModifierTests() = + + [] + member _.``onlyWhen skips the body but not the dependencies``() = + let exit, log, _, _ = run ["optional"; "--skip-optional"] + Assert.Equal(0, exit) + Assert.Equal([ "lint" ], log) + + [] + member _.``after orders a target after one in the same run``() = + let _, log, _, _ = run ["ci"; "-j"; "4"] + Assert.Equal([ "lint"; "package" ], log) + + [] + member _.``after does not add the target to the run``() = + let _, log, _, _ = run ["package"] + Assert.Equal([ "package" ], log) + + [] + member _.``cleanup runs after a failure``() = + let exit, log, _, _ = run ["integration"] + Assert.Equal(1, exit) + Assert.Equal([ "start-db"; "stop-db" ], log) + + [] + member _.``needsEnv stops the run before anything starts``() = + Environment.SetEnvironmentVariable(variable, null) + let exit, log, _, stderr = run ["push"] + Assert.Equal(1, exit) + Assert.Equal([], log) + Assert.Contains(variable, stderr) + + [] + member _.``describe sets the description help shows``() = + let _, _, stdout, _ = run ["--help"] + Assert.Contains("Push the packages", 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 f10c5ae..dc8b44e 100644 --- a/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj +++ b/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj @@ -17,6 +17,7 @@ + diff --git a/tests/Nullean.Make.Tests/ModifierTests.cs b/tests/Nullean.Make.Tests/ModifierTests.cs new file mode 100644 index 0000000..0f66a26 --- /dev/null +++ b/tests/Nullean.Make.Tests/ModifierTests.cs @@ -0,0 +1,258 @@ +using AwesomeAssertions; + +namespace Nullean.Make.Tests; + +public record class Lint; + +public record class Package; + +public record class Ci; + +public record class StartDb; + +public record class StopDb; + +public record class Integration(bool Fail = false); + +public record class Push; + +public record class Optional; + +public record class Uses; + +public record class Loop1; + +public record class Loop2; + +public record class Loops; + +public union Modified(Lint, Package, Ci, StartDb, StopDb, Integration, Push, Optional, Uses, Loop1, Loop2, Loops); + +/// OnlyWhen, After, Cleanup, NeedsEnv and NeedsTool on a . +[NotInParallel] +public class ModifierTests +{ + internal const string Variable = "NULLEAN_MAKE_TEST_PUSH_KEY"; + + 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"); + var skipOptional = app.Flag("--skip-optional"); + app.Bind( + m => + m.Value switch + { + Lint => app.Target(() => log.Add("lint")), + Package => app.Target(() => log.Add("package")).After(new Lint()), + // A parallel stage leaves the two unordered; After orders them. + Ci => app.Command().Parallel(new Package(), new Lint()), + StartDb => app.Target(() => log.Add("start-db")).Cleanup(new StopDb()), + StopDb => app.Target(() => log.Add("stop-db")), + Integration i => + app.Target([new StartDb()], () => + { + log.Add("integration"); + if (i.Fail) + throw new MakeException("integration failed", 4); + }), + Push => app.Target(() => log.Add("push")).NeedsEnv(Variable).NeedsTool("dotnet"), + Optional => app.Target([new Lint()], () => log.Add("optional")).OnlyWhen(() => !skipOptional.Value), + Uses => app.Target(() => log.Add("uses")).NeedsTool("nullean-make-no-such-tool").NeedsEnv(Variable), + Loop1 => app.Target(() => log.Add("loop1")).After(new Loop2()), + Loop2 => app.Target(() => log.Add("loop2")).After(new Loop1()), + Loops => app.Command([], [new Loop1(), new Loop2()]), + _ => throw new InvalidOperationException($"unmapped case {m.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 A_false_condition_skips_the_body_but_not_the_dependencies() + { + var run = await RunAsync("optional", "--skip-optional"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("lint"); + } + + [Test] + public async Task Graph_shows_what_a_condition_skips() + { + var run = await RunAsync("optional", "--skip-optional", "--graph"); + run.Stdout.Should().Contain("optional skipped: its condition is false"); + } + + [Test] + public async Task After_orders_a_target_after_one_in_the_same_run() + { + var run = await RunAsync("ci", "-j", "4"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("lint", "package"); + } + + [Test] + public async Task After_does_not_add_the_target_to_the_run() + { + var run = await RunAsync("package"); + run.Log.Should().Equal("package"); + } + + [Test] + public async Task After_that_forms_a_cycle_exits_1() + { + var run = await RunAsync("loops"); + run.ExitCode.Should().Be(1); + run.Stderr.Should().Contain("has a cycle"); + run.Log.Should().BeEmpty(); + } + + [Test] + public async Task A_cleanup_runs_at_the_end() + { + var run = await RunAsync("integration"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("start-db", "integration", "stop-db"); + } + + [Test] + public async Task A_cleanup_runs_after_a_failure_and_the_run_keeps_the_failures_exit_code() + { + var run = await RunAsync("integration", "--fail"); + run.ExitCode.Should().Be(4); + run.Log.Should().Equal("start-db", "integration", "stop-db"); + } + + [Test] + public async Task Graph_shows_the_cleanup() + { + var run = await RunAsync("integration", "--graph"); + run.Stdout.Should().Contain("cleanup, at the end").And.Contain("then cleanup: stop-db"); + } + + [Test] + public async Task A_missing_environment_variable_stops_the_run_before_anything_starts() + { + Environment.SetEnvironmentVariable(Variable, null); + var run = await RunAsync("push"); + run.ExitCode.Should().Be(1); + run.Log.Should().BeEmpty(); + run.Stderr.Should().Contain($"the environment variable {Variable}, for push"); + } + + [Test] + public async Task A_set_environment_variable_and_a_tool_on_the_path_let_the_run_start() + { + Environment.SetEnvironmentVariable(Variable, "set"); + try + { + var run = await RunAsync("push"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("push"); + } + finally + { + Environment.SetEnvironmentVariable(Variable, null); + } + } + + [Test] + public async Task Every_missing_precondition_is_listed() + { + Environment.SetEnvironmentVariable(Variable, null); + var run = await RunAsync("uses"); + run.ExitCode.Should().Be(1); + run.Stderr.Should().Contain("nullean-make-no-such-tool on the PATH, for uses").And.Contain($"the environment variable {Variable}, for uses"); + } + + [Test] + public async Task Graph_lists_what_is_missing_and_runs_nothing() + { + Environment.SetEnvironmentVariable(Variable, null); + var run = await RunAsync("uses", "--graph"); + run.ExitCode.Should().Be(0); + run.Stdout.Should().Contain("Missing: nullean-make-no-such-tool on the PATH, for uses"); + } +} + +public class ModifiedBuild : MakeBuild +{ + public static List Log { get; } = new(); + + public Target Lint => _ => _.Executes(() => Log.Add("lint")); + + public Target Package => _ => _.After(Lint).Executes(() => Log.Add("package")); + + public Command Ci => _ => _.Parallel(Package, Lint); + + public Target StopDb => _ => _.Executes(() => Log.Add("stop-db")); + + public Target StartDb => _ => _.Cleanup(StopDb).Executes(() => Log.Add("start-db")); + + public Target Integration => _ => _.DependsOn(StartDb).Executes(() => throw new MakeException("integration failed", 4)); + + public Target Push => _ => _.NeedsEnv(ModifierTests.Variable).Executes(() => Log.Add("push")); +} + +[NotInParallel] +public class ClassModifierTests +{ + private static async Task<(int Exit, List Log, string Stderr)> RunAsync(params string[] args) + { + ModifiedBuild.Log.Clear(); + var stderr = new StringWriter(); + var (oldOut, oldErr) = (Console.Out, Console.Error); + Console.SetOut(new StringWriter()); + Console.SetError(stderr); + try + { + return (await MakeApp.Execute(args), [.. ModifiedBuild.Log], stderr.ToString()); + } + finally + { + Console.SetOut(oldOut); + Console.SetError(oldErr); + } + } + + [Test] + public async Task After_orders_a_target_after_one_in_the_same_run() + { + var (exit, log, _) = await RunAsync("ci"); + exit.Should().Be(0); + log.Should().Equal("lint", "package"); + } + + [Test] + public async Task A_cleanup_runs_after_a_failure() + { + var (exit, log, _) = await RunAsync("integration"); + exit.Should().Be(4); + log.Should().Equal("start-db", "stop-db"); + } + + [Test] + public async Task A_missing_environment_variable_stops_the_run() + { + Environment.SetEnvironmentVariable(ModifierTests.Variable, null); + var (exit, log, stderr) = await RunAsync("push"); + exit.Should().Be(1); + log.Should().BeEmpty(); + stderr.Should().Contain(ModifierTests.Variable); + } +} From 8e2e6fb23045bbb477a2010448f7082574c81332 Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 12 Nov 2026 08:54:50 +0100 Subject: [PATCH 06/11] Run several targets from one command line, and leave targets out with --skip `build lint test --filter Unit pack` runs the three targets in order, sharing their dependencies. Each target takes the arguments up to the next target's name; an option's value and a target's positionals stay with it. `--skip ` leaves a target out of the plan with the dependencies only it needed, and `--graph` shows it as skipped. Co-Authored-By: Claude Opus 5.5 --- docs/_docset.yml | 1 + docs/make/index.md | 4 + docs/make/running.md | 32 +++++ src/Nullean.Make.Fs/MakeApp.fs | 14 +- src/Nullean.Make.Fs/README.md | 9 ++ .../Execution/DepGraphExecutor.cs | 9 +- src/Nullean.Make/Execution/Invocation.cs | 108 +++++++++++++++ src/Nullean.Make/Execution/PlanRenderer.cs | 4 + src/Nullean.Make/Execution/RunPlan.cs | 15 ++- src/Nullean.Make/Execution/RunSwitches.cs | 3 + src/Nullean.Make/Help/MakeHelpPrinter.cs | 3 +- src/Nullean.Make/Parsing/ArgvParser.cs | 3 + src/Nullean.Make/README.md | 9 ++ .../Nullean.Make.Fs.Tests/InvocationTests.fs | 56 ++++++++ .../Nullean.Make.Fs.Tests.fsproj | 1 + tests/Nullean.Make.Tests/InvocationTests.cs | 123 ++++++++++++++++++ tests/Nullean.Make.Tests/ParallelTests.cs | 32 +++-- 17 files changed, 403 insertions(+), 23 deletions(-) create mode 100644 docs/make/running.md create mode 100644 src/Nullean.Make/Execution/Invocation.cs create mode 100644 tests/Nullean.Make.Fs.Tests/InvocationTests.fs create mode 100644 tests/Nullean.Make.Tests/InvocationTests.cs diff --git a/docs/_docset.yml b/docs/_docset.yml index 7fc58a5..f5084fb 100644 --- a/docs/_docset.yml +++ b/docs/_docset.yml @@ -49,6 +49,7 @@ toc: - folder: make children: - file: index.md + - file: running.md - file: graph.md - file: parallel.md - file: modifiers.md diff --git a/docs/make/index.md b/docs/make/index.md index ae9a94f..f48e7bf 100644 --- a/docs/make/index.md +++ b/docs/make/index.md @@ -8,8 +8,12 @@ ./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 +./build.cs lint test pack # several targets, in order, shared dependencies once +./build.cs release --skip docs ``` +[**Choosing what runs**](running.md) - Several targets on one command line, `-s` and `--skip`. + [**Running targets side by side**](parallel.md) - Parallel stages, `-j`, `--keep-going`, and the output of targets that run at once. diff --git a/docs/make/running.md b/docs/make/running.md new file mode 100644 index 0000000..8d98e41 --- /dev/null +++ b/docs/make/running.md @@ -0,0 +1,32 @@ +# Choosing what runs + +## Several targets + +A command line can name several targets. They run in the order they are named, and a dependency they share runs once: + +```bash +./build.cs lint test --filter Unit pack +``` + +Each target takes the arguments up to the next target's name: `test` gets `--filter Unit`. A word stays with the +target before it when it is the value of an option, as in `test --filter pack`, or when that target takes positional +arguments. Everything after `--` stays with the target before it. + +The `make` wrapper starts the script once per target: `make test pack` runs it twice. + +## Leaving targets out + +`-s` / `--single-target` skips the gates of the named target: its dependencies, or a command's requires. + +`--skip ` leaves one target out of the plan, wherever it appears, with the dependencies that only it needed: + +```bash +./build.cs release --skip docs +./build.cs release --skip "pkg validate",docs # several, separated by commas +./build.cs release --skip pkg/validate # pkg/validate and pkg:validate work too +``` + +`--skip` takes a target's name, not a value, so it leaves the target out whatever value it would run with. It exits +`2` for a name that is not a target, with a suggestion, and for a target the command line names itself. + +`--graph` shows what both leave out: `skipped: -s` and `skipped: --skip`. diff --git a/src/Nullean.Make.Fs/MakeApp.fs b/src/Nullean.Make.Fs/MakeApp.fs index 515c312..4829e4a 100644 --- a/src/Nullean.Make.Fs/MakeApp.fs +++ b/src/Nullean.Make.Fs/MakeApp.fs @@ -215,11 +215,17 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> | false, _ -> eprintfn "Unknown target '%s'." routeKey return 2 - | true, node when isNull node.DtoType && targetArgs.Length > 0 -> - let first = if targetArgs.[0] = "--" && targetArgs.Length > 1 then targetArgs.[1] else targetArgs.[0] - eprintfn "Unexpected argument '%s'. Target '%s' takes no arguments." first routeKey - return 2 | true, node -> + // Each target named on the command line gets the tokens up to the next one; one without a record takes none. + let unexpected = + Invocation.Split(node, targetArgs, graph) + |> Seq.tryFind (fun struct (n, args) -> isNull n.DtoType && args.Length > 0) + match unexpected with + | Some (struct (n, args)) -> + let first = if args.[0] = "--" && args.Length > 1 then args.[1] else args.[0] + eprintfn "Unexpected argument '%s'. Target '%s' takes no arguments." first (String.concat "/" n.Route) + return 2 + | None -> switches.Target <- node switches.TargetArgs <- targetArgs switches.SingleTarget <- singleTarget diff --git a/src/Nullean.Make.Fs/README.md b/src/Nullean.Make.Fs/README.md index 9fda02e..488a4d5 100644 --- a/src/Nullean.Make.Fs/README.md +++ b/src/Nullean.Make.Fs/README.md @@ -208,6 +208,15 @@ 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. +## Choosing what runs + +``` +build lint test --filter Unit pack # several targets in order; each takes the arguments up to the next +build release --skip docs # leave a target out, with what only it needed +``` + +See [Choosing what runs](https://argh.nullean.net/make/running). + ## Drawing the plan `--graph` draws what a run would do and runs nothing. It binds the target's arguments, applies `-s` and evaluates diff --git a/src/Nullean.Make/Execution/DepGraphExecutor.cs b/src/Nullean.Make/Execution/DepGraphExecutor.cs index 1716858..72c7753 100644 --- a/src/Nullean.Make/Execution/DepGraphExecutor.cs +++ b/src/Nullean.Make/Execution/DepGraphExecutor.cs @@ -15,8 +15,12 @@ public static async Task ExecuteAsync(TargetNode root, ParsedArgs parsed, B RunPlan plan; try { - var value = source.BindArguments(root, parsed.TargetArgs); - plan = RunPlan.Build([new DepRef(root, value)], source, new PlanOptions(parsed.SingleTarget, EvaluateConditions: parsed.Graph is not null)); + // `build lint test --filter Unit pack` names three targets; each binds its own arguments. + var targets = Invocation.Split(root, parsed.TargetArgs, graph); + parsed.TargetArgs = targets[0].Args; + var roots = targets.Select(t => new DepRef(t.Node, source.BindArguments(t.Node, t.Args))).ToList(); + var skip = Invocation.ResolveSkips(parsed.Skip, graph); + plan = RunPlan.Build(roots, source, new PlanOptions(parsed.SingleTarget, EvaluateConditions: parsed.Graph is not null, Skip: skip)); } catch (MakeException ex) { @@ -39,6 +43,7 @@ public static int DrawWholeGraph(BuildGraph graph, GraphFormat format) try { var plan = PlanRenderer.WholeGraph(graph, source, new PlanOptions(SingleTarget: false, EvaluateConditions: true)); + // --skip is ignored here: the whole graph shows every target. PlanRenderer.Write(plan, format, Console.Out); return 0; } diff --git a/src/Nullean.Make/Execution/Invocation.cs b/src/Nullean.Make/Execution/Invocation.cs new file mode 100644 index 0000000..e7302a7 --- /dev/null +++ b/src/Nullean.Make/Execution/Invocation.cs @@ -0,0 +1,108 @@ +using Nullean.Argh.Matching; +using Nullean.Make.Discovery; + +namespace Nullean.Make.Execution; + +/// Splits a command line that names several targets, such as build lint test --filter Unit pack. +internal static class Invocation +{ + /// + /// Splits the tokens after the first target's route into that target's arguments and the targets after it. A token + /// starts the next target when it names one, is not the value of the option before it, and the current target takes + /// no positional arguments. Everything after -- stays with the current target. + /// + public static List<(TargetNode Node, string[] Args)> Split(TargetNode first, string[] args, BuildGraph graph) + { + var result = new List<(TargetNode Node, string[] Args)>(); + var node = first; + var current = new List(); + var options = Options(node); + for (var i = 0; i < args.Length; i++) + { + var token = args[i]; + if (token == "--") + { + current.AddRange(args[i..]); + break; + } + if (token.StartsWith('-')) + { + current.Add(token); + // The value of an option that takes one stays with it, even when it names a target. + if (!token.Contains('=') && options.TakesValue(token) && i + 1 < args.Length) + current.Add(args[++i]); + continue; + } + if (!options.TakesPositionals && MatchRoute(args, i, graph) is { } next) + { + result.Add((node, [.. current])); + node = next.Node; + options = Options(node); + current = new List(); + i += next.Consumed - 1; + continue; + } + current.Add(token); + } + result.Add((node, [.. current])); + return result; + } + + /// The longest route starting at args[start], such as pkg generate, and how many tokens it took. + private static (TargetNode Node, int Consumed)? MatchRoute(string[] args, int start, BuildGraph graph) + { + (TargetNode, int)? best = null; + var segments = new List(); + for (var i = start; i < args.Length && !args[i].StartsWith('-'); i++) + { + segments.Add(args[i].ToLowerInvariant()); + var key = string.Join("/", segments); + if (graph.ByRoute.TryGetValue(key, out var node)) + best = (node, segments.Count); + else if (!graph.ByRoute.Keys.Any(k => k.StartsWith(key + "/", StringComparison.OrdinalIgnoreCase))) + break; + } + return best; + } + + private sealed record TargetOptions(HashSet ValueOptions, bool TakesPositionals) + { + public bool TakesValue(string token) => ValueOptions.Contains(token.TrimStart('-')); + } + + private static TargetOptions Options(TargetNode node) + { + if (node.DtoType is null) + return new TargetOptions(new HashSet(StringComparer.OrdinalIgnoreCase), false); + var described = DtoOptions.Describe(node.DtoType); + return new TargetOptions( + described + .Where(o => !o.IsPositional && !o.IsRest && !o.IsSwitch && !IsFSharpBoolOption(o.Type)) + .Select(o => o.Name) + .ToHashSet(StringComparer.OrdinalIgnoreCase), + described.Any(o => o.IsPositional) + ); + } + + private static bool IsFSharpBoolOption(Type type) => + type.IsGenericType && type.GetGenericTypeDefinition().Name == "FSharpOption`1" && type.GetGenericArguments()[0] == typeof(bool); + + /// Resolves the targets of --skip, given as pkg generate, pkg/generate or pkg:generate. + public static HashSet ResolveSkips(IEnumerable names, BuildGraph graph) + { + var skipped = new HashSet(); + foreach (var name in names) + { + var key = string.Join("/", name.Split([' ', '/', ':'], StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant(); + if (graph.ByRoute.TryGetValue(key, out var node)) + { + skipped.Add(node); + continue; + } + var suggestions = FuzzyMatch.FindClosest(key, graph.ByRoute.Keys.Select(k => k.Replace('/', ' ')), 3); + var hint = suggestions.Count > 0 ? $" Did you mean '{suggestions[0]}'?" : ""; + throw new MakeException($"Unknown target '{name}' for '--skip'.{hint}", 2); + } + return skipped; + } +} diff --git a/src/Nullean.Make/Execution/PlanRenderer.cs b/src/Nullean.Make/Execution/PlanRenderer.cs index 74398a9..9c7aa15 100644 --- a/src/Nullean.Make/Execution/PlanRenderer.cs +++ b/src/Nullean.Make/Execution/PlanRenderer.cs @@ -197,6 +197,7 @@ private static void WriteChildren(List children, string indent, TextWriter { SkipReason.SingleTarget => Dim(" skipped: -s"), SkipReason.Condition => Dim(" skipped: its condition is false"), + SkipReason.Excluded => Dim(" skipped: --skip"), _ => "" }; @@ -313,6 +314,9 @@ private static void WriteSkipped(Utf8JsonWriter json, SkipReason? reason) case SkipReason.Condition: json.WriteString("skipped", "condition"); break; + case SkipReason.Excluded: + json.WriteString("skipped", "excluded"); + break; default: json.WriteNull("skipped"); break; diff --git a/src/Nullean.Make/Execution/RunPlan.cs b/src/Nullean.Make/Execution/RunPlan.cs index 6c17496..5988a70 100644 --- a/src/Nullean.Make/Execution/RunPlan.cs +++ b/src/Nullean.Make/Execution/RunPlan.cs @@ -9,7 +9,10 @@ internal enum SkipReason SingleTarget, /// Its condition returned , so its body does not run. - Condition + Condition, + + /// --skip left it out of the plan. + Excluded } /// One target with one value in a run: it runs once, however many targets depend on it. @@ -48,7 +51,8 @@ internal sealed record PlannedItem(TargetInstance? Instance, string Name, SkipRe /// 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); +/// Targets --skip leaves out, whatever their value, with the dependencies only they needed. +internal sealed record PlanOptions(bool SingleTarget, bool EvaluateConditions = false, bool ChainRoots = true, IReadOnlySet? Skip = null); /// The instances a run contains, in an order that respects every prerequisite. internal sealed class RunPlan @@ -101,6 +105,8 @@ public static RunPlan Build(IReadOnlyList roots, ITargetSource source, P TargetInstance? previous = null; foreach (var root in roots) { + if (options.Skip?.Contains(root.Node) == true) + throw new MakeException($"'--skip' names '{string.Join(" ", root.Node.Route)}', which the command line runs.", 2); var instance = builder.Visit(root, isRoot: true, previous is null || !options.ChainRoots ? [] : [previous]); instance.IsRoot = true; rootInstances.Add(instance); @@ -245,6 +251,11 @@ public TargetInstance Visit(DepRef reference, bool isRoot, 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)); diff --git a/src/Nullean.Make/Execution/RunSwitches.cs b/src/Nullean.Make/Execution/RunSwitches.cs index 0f2a952..6222795 100644 --- a/src/Nullean.Make/Execution/RunSwitches.cs +++ b/src/Nullean.Make/Execution/RunSwitches.cs @@ -30,6 +30,9 @@ public static bool TryRead(IReadOnlyList args, ref int i, ParsedArgs par case "-j" or "--jobs": parsed.Jobs = ParseJobs(Value(args, ref i, name)); return true; + case "--skip": + parsed.Skip.AddRange(Value(args, ref i, name).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + return true; case "-k" or "--keep-going": parsed.KeepGoing = true; i++; diff --git a/src/Nullean.Make/Help/MakeHelpPrinter.cs b/src/Nullean.Make/Help/MakeHelpPrinter.cs index 75f8bcf..0deea5f 100644 --- a/src/Nullean.Make/Help/MakeHelpPrinter.cs +++ b/src/Nullean.Make/Help/MakeHelpPrinter.cs @@ -22,7 +22,7 @@ public static void PrintRoot(BuildGraph graph, string scriptName) var nsNames = nsTargets.Select(t => t.Route[0]).Distinct().OrderBy(x => x).ToList(); Console.WriteLine($" {CliHelpFormatting.Section("Usage:")}"); - Console.WriteLine($" {scriptName} [options]"); + Console.WriteLine($" {scriptName} [options] [ [options]...]"); if (nsNames.Count > 0) Console.WriteLine($" {scriptName} [options]"); if (graph.Default is { } defaultTarget) @@ -276,6 +276,7 @@ private static void PrintGlobalOptions(BuildGraph graph, string scriptName) $" {CliHelpFormatting.Placeholder($"{Short("k")}--keep-going"),-30} After a failure, finish the targets that do not depend on it" ); Console.WriteLine($" {CliHelpFormatting.Placeholder(" --output "),-30} Output of targets running side by side: prefixed or grouped"); + Console.WriteLine($" {CliHelpFormatting.Placeholder(" --skip "),-30} Leave a target out of the plan, with what only it needed"); foreach (var opt in graph.GlobalOptions) { diff --git a/src/Nullean.Make/Parsing/ArgvParser.cs b/src/Nullean.Make/Parsing/ArgvParser.cs index 4aed2c5..940482a 100644 --- a/src/Nullean.Make/Parsing/ArgvParser.cs +++ b/src/Nullean.Make/Parsing/ArgvParser.cs @@ -24,6 +24,9 @@ internal sealed class ParsedArgs /// --output: how the output of targets that run side by side reaches the console. public Execution.OutputMode? Output { get; set; } + + /// --skip: targets the plan leaves out, with the dependencies only they needed. + public List Skip { get; } = new(); public string? HelpTarget { get; set; } } diff --git a/src/Nullean.Make/README.md b/src/Nullean.Make/README.md index 75d3b1b..b57278d 100644 --- a/src/Nullean.Make/README.md +++ b/src/Nullean.Make/README.md @@ -141,6 +141,15 @@ 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. +## Choosing what runs + +``` +build lint test --filter Unit pack # several targets in order; each takes the arguments up to the next +build release --skip docs # leave a target out, with what only it needed +``` + +See [Choosing what runs](https://argh.nullean.net/make/running). + ## Drawing the plan `--graph` draws what a run would do and runs nothing. It binds the target's arguments, applies `-s` and evaluates diff --git a/tests/Nullean.Make.Fs.Tests/InvocationTests.fs b/tests/Nullean.Make.Fs.Tests/InvocationTests.fs new file mode 100644 index 0000000..451b4b8 --- /dev/null +++ b/tests/Nullean.Make.Fs.Tests/InvocationTests.fs @@ -0,0 +1,56 @@ +module Nullean.Make.Fs.Tests.InvocationTests + +open System +open System.IO +open TUnit.Core +open Nullean.Make.Fs + +type VerifyOptions = { Suite: string option } + +type Called = + | Restore + | Verify of VerifyOptions + | Bundle + | Shipit + +let private run (args: string list) = + let log = ResizeArray() + let app = MakeApp("build", None) + app.Bind <| function + | Restore -> target [] { log.Add "restore" } + | Verify o -> target [Restore] { log.Add $"verify:%A{o.Suite}" } + | Bundle -> target [Restore] { log.Add "bundle" } + | Shipit -> command { + requires [Verify { Suite = None }] + composes [Bundle] } + let stderr = new StringWriter() + let oldOut, oldErr = Console.Out, Console.Error + Console.SetOut(new StringWriter()) + Console.SetError stderr + try + let exit = app.RunAsync(List.toArray args).GetAwaiter().GetResult() + exit, List.ofSeq log, string stderr + finally + Console.SetOut oldOut + Console.SetError oldErr + +[] +type InvocationTests() = + + [] + member _.``Several targets run in order and share their dependencies``() = + let exit, log, _ = run ["bundle"; "verify"; "--suite"; "unit"] + Assert.Equal(0, exit) + Assert.Equal([ "restore"; "bundle"; "verify:Some \"unit\"" ], log) + + [] + member _.``A target without a record still rejects a word that is not a target``() = + let exit, _, stderr = run ["bundle"; "nope"] + Assert.Equal(2, exit) + Assert.Contains("Unexpected argument 'nope'. Target 'bundle' takes no arguments.", stderr) + + [] + member _.``Skip leaves a target out of the plan``() = + let exit, log, _ = run ["shipit"; "--skip"; "verify"] + Assert.Equal(0, exit) + Assert.Equal([ "restore"; "bundle" ], log) 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 dc8b44e..df91327 100644 --- a/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj +++ b/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj @@ -18,6 +18,7 @@ + diff --git a/tests/Nullean.Make.Tests/InvocationTests.cs b/tests/Nullean.Make.Tests/InvocationTests.cs new file mode 100644 index 0000000..6bc783b --- /dev/null +++ b/tests/Nullean.Make.Tests/InvocationTests.cs @@ -0,0 +1,123 @@ +using AwesomeAssertions; +using Nullean.Argh; + +namespace Nullean.Make.Tests; + +public record class Restore; + +public record class Assemble; + +public record class Verify(string Suite = "all", bool Quick = false); + +public record class Bundle; + +public record class Format([Argument] string Path = "."); + +public record class Shipit; + +public record class Sweep; + +public union Called(Restore, Assemble, Verify, Bundle, Format, Shipit, Sweep); + +/// Several targets on one command line, and --skip. +[NotInParallel] +public class InvocationTests +{ + 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( + c => + c.Value switch + { + Restore => app.Target(() => log.Add("restore")), + Assemble => app.Target([new Restore()], () => log.Add("assemble")), + Verify v => app.Target([new Assemble()], () => log.Add($"verify:{v.Suite}:{v.Quick}")), + Bundle => app.Target([new Assemble()], () => log.Add("bundle")), + Format f => app.Target(() => log.Add($"format:{f.Path}")), + Shipit => app.Command([new Verify()], [new Bundle()]), + Sweep => app.Target(() => log.Add("sweep")), + _ => throw new InvalidOperationException($"unmapped case {c.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 Several_targets_run_in_order_and_share_their_dependencies() + { + var run = await RunAsync("sweep", "verify", "bundle"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("sweep", "restore", "assemble", "verify:all:False", "bundle"); + } + + [Test] + public async Task Each_target_binds_the_arguments_up_to_the_next_one() + { + var run = await RunAsync("verify", "--suite", "unit", "--quick", "bundle"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("restore", "assemble", "verify:unit:True", "bundle"); + } + + [Test] + public async Task An_option_value_that_names_a_target_stays_with_the_option() + { + var run = await RunAsync("verify", "--suite", "bundle"); + run.Log.Should().Equal("restore", "assemble", "verify:bundle:False"); + } + + [Test] + public async Task A_target_with_positional_arguments_takes_the_words_after_it() + { + var run = await RunAsync("format", "sweep"); + run.Log.Should().Equal("format:sweep"); + } + + [Test] + public async Task Skip_leaves_a_target_and_what_only_it_needed_out_of_the_plan() + { + var run = await RunAsync("shipit", "--skip", "verify"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("restore", "assemble", "bundle"); + } + + [Test] + public async Task Graph_shows_what_skip_leaves_out() + { + var run = await RunAsync("shipit", "--skip=verify", "--graph"); + run.Stdout.Should().Contain("verify skipped: --skip"); + } + + [Test] + public async Task Skip_of_an_unknown_target_exits_2_with_a_suggestion() + { + var run = await RunAsync("shipit", "--skip", "verfy"); + run.ExitCode.Should().Be(2); + run.Stderr.Should().Contain("Unknown target 'verfy' for '--skip'. Did you mean 'verify'?"); + run.Log.Should().BeEmpty(); + } + + [Test] + public async Task Skip_of_a_target_the_command_line_runs_exits_2() + { + var run = await RunAsync("shipit", "--skip", "shipit"); + run.ExitCode.Should().Be(2); + run.Log.Should().BeEmpty(); + } +} diff --git a/tests/Nullean.Make.Tests/ParallelTests.cs b/tests/Nullean.Make.Tests/ParallelTests.cs index cb23532..cf3bf9b 100644 --- a/tests/Nullean.Make.Tests/ParallelTests.cs +++ b/tests/Nullean.Make.Tests/ParallelTests.cs @@ -292,20 +292,24 @@ private static async Task> RunAsync(params string[] args) { var log = new System.Collections.Concurrent.ConcurrentQueue(); var app = new MakeApp("build"); - app.Bind(o => o.Value switch - { - First => app.Target(async () => - { - log.Enqueue("first:start"); - await Task.Delay(200); - log.Enqueue("first:end"); - }), - SecondsDependency => app.Target(() => log.Enqueue("seconds-dependency")), - Second => app.Target([new SecondsDependency()], () => log.Enqueue("second")), - InOrder => app.Command([], [new First(), new Second()]), - Fanned => app.Command().Composes(new First()).Parallel(new Second(), new SecondsDependency()), - _ => throw new InvalidOperationException() - }); + app.Bind( + o => + o.Value switch + { + First => + app.Target(async () => + { + log.Enqueue("first:start"); + await Task.Delay(200); + log.Enqueue("first:end"); + }), + SecondsDependency => app.Target(() => log.Enqueue("seconds-dependency")), + Second => app.Target([new SecondsDependency()], () => log.Enqueue("second")), + InOrder => app.Command([], [new First(), new Second()]), + Fanned => app.Command().Composes(new First()).Parallel(new Second(), new SecondsDependency()), + _ => throw new InvalidOperationException() + } + ); var (oldOut, oldErr) = (Console.Out, Console.Error); Console.SetOut(new StringWriter()); Console.SetError(new StringWriter()); From 44c34677ea1a8aa92b1d66a23fe2aaeb1396a72f Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 12 Nov 2026 09:49:46 +0100 Subject: [PATCH 07/11] List the run switches in the generated wrappers The mise include's usage spec now lists `--graph`, `-j/--jobs`, `-k/--keep-going`, `--output` and `--skip`, so mise completes them. A build option with the same short name keeps it, as on the command line. Committed wrapper files change, so `__wrappers check` fails until `__wrappers sync` runs once. Co-Authored-By: Claude Opus 5.5 --- docs/make/mise.md | 5 ++++ src/Nullean.Make/Wrappers/WrapperModel.cs | 12 ++++++++- tests/Nullean.Make.Tests/WrapperTests.cs | 32 +++++++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/docs/make/mise.md b/docs/make/mise.md index 4d3bc79..873f786 100644 --- a/docs/make/mise.md +++ b/docs/make/mise.md @@ -32,6 +32,11 @@ run = "dotnet run build.cs -- pkg generate" usage = ''' flag "--configuration " help="string (default: Release)" flag "-s --single-target" help="Skip prerequisite deps; run only the body / Composes" +flag "--graph" help="Draw what would run and run nothing: tree, mermaid or json" +flag "-j --jobs " help="How many targets may run at once (default: one per processor)" +flag "-k --keep-going" help="After a failure, finish the targets that do not depend on it" +flag "--output " help="Output of targets running side by side: prefixed or grouped" +flag "--skip " help="Leave a target out of the plan, with what only it needed" ''' ``` diff --git a/src/Nullean.Make/Wrappers/WrapperModel.cs b/src/Nullean.Make/Wrappers/WrapperModel.cs index 79a8e86..a02baf6 100644 --- a/src/Nullean.Make/Wrappers/WrapperModel.cs +++ b/src/Nullean.Make/Wrappers/WrapperModel.cs @@ -32,7 +32,17 @@ public static WrapperModel From(BuildGraph graph, string run, string? prefix) .Select(t => new WrapperTarget(t.Route, OneLine(t.Description), t.DtoType is null ? Array.Empty() : DtoOptions.Describe(t.DtoType))) .ToList(); - var options = new List { new("--single-target", "-s", "Skip prerequisite deps; run only the body / Composes", true, "bool"), }; + // The switches every Make script reads. A build option with the same short name keeps it, as on the command line. + string? Short(string name) => graph.GlobalOptions.Any(o => o.Short?.TrimStart('-') == name.TrimStart('-')) ? null : name; + var options = new List + { + new("--single-target", "-s", "Skip prerequisite deps; run only the body / Composes", true, "bool"), + new("--graph", null, "Draw what would run and run nothing: tree, mermaid or json", true, "bool"), + new("--jobs", Short("-j"), "How many targets may run at once (default: one per processor)", false, "int"), + new("--keep-going", Short("-k"), "After a failure, finish the targets that do not depend on it", true, "bool"), + new("--output", null, "Output of targets running side by side: prefixed or grouped", false, "string"), + new("--skip", null, "Leave a target out of the plan, with what only it needed", false, "string"), + }; foreach (var o in graph.GlobalOptions) { var valueType = o.Property?.PropertyType ?? o.ValueType; diff --git a/tests/Nullean.Make.Tests/WrapperTests.cs b/tests/Nullean.Make.Tests/WrapperTests.cs index 62ebe77..263b8ff 100644 --- a/tests/Nullean.Make.Tests/WrapperTests.cs +++ b/tests/Nullean.Make.Tests/WrapperTests.cs @@ -36,6 +36,14 @@ public class Schema : Namespace } /// schema-update and schema update are distinct targets but the same just recipe name. +public class KeepBuild : MakeBuild +{ + [Flag("--keep", "-k", Description = "Keep the output")] + public bool Keep { get; init; } + + public Target Clean => _ => _.Executes(() => { }); +} + public class ClashingWrapperBuild : MakeBuild { public Target SchemaUpdate => @@ -93,6 +101,15 @@ public void Dispose() """; + [Test] + public async Task A_build_option_with_the_same_short_name_keeps_it_in_the_mise_include() + { + var (exit, _, stderr) = await RunAsync("sync", "--run", "dotnet run build.cs --", "--only", "mise"); + exit.Should().Be(0, stderr); + var text = FileText("mise-tasks.toml"); + text.Should().Contain("flag \"--keep-going\" help=").And.Contain("flag \"-k --keep\""); + } + [Test] public async Task Sync_writes_the_mise_include() { @@ -111,6 +128,11 @@ public async Task Sync_writes_the_mise_include() run = "dotnet run build.cs -- clean" usage = ''' flag "-s --single-target" help="Skip prerequisite deps; run only the body / Composes" + flag "--graph" help="Draw what would run and run nothing: tree, mermaid or json" + flag "-j --jobs " help="How many targets may run at once (default: one per processor)" + flag "-k --keep-going" help="After a failure, finish the targets that do not depend on it" + flag "--output " help="Output of targets running side by side: prefixed or grouped" + flag "--skip " help="Leave a target out of the plan, with what only it needed" flag "-c --clean-checkout" help="Skip the clean-checkout guard" ''' @@ -123,6 +145,11 @@ public async Task Sync_writes_the_mise_include() flag "--no-restore" help="bool (default: False)" arg "[project]" help="string (default: null)" flag "-s --single-target" help="Skip prerequisite deps; run only the body / Composes" + flag "--graph" help="Draw what would run and run nothing: tree, mermaid or json" + flag "-j --jobs " help="How many targets may run at once (default: one per processor)" + flag "-k --keep-going" help="After a failure, finish the targets that do not depend on it" + flag "--output " help="Output of targets running side by side: prefixed or grouped" + flag "--skip " help="Leave a target out of the plan, with what only it needed" flag "-c --clean-checkout" help="Skip the clean-checkout guard" ''' @@ -132,6 +159,11 @@ public async Task Sync_writes_the_mise_include() run = "dotnet run build.cs -- schema update" usage = ''' flag "-s --single-target" help="Skip prerequisite deps; run only the body / Composes" + flag "--graph" help="Draw what would run and run nothing: tree, mermaid or json" + flag "-j --jobs " help="How many targets may run at once (default: one per processor)" + flag "-k --keep-going" help="After a failure, finish the targets that do not depend on it" + flag "--output " help="Output of targets running side by side: prefixed or grouped" + flag "--skip " help="Leave a target out of the plan, with what only it needed" flag "-c --clean-checkout" help="Skip the clean-checkout guard" ''' From 75bf1c3846979622650f7271e7559b78de68aeb7 Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 12 Nov 2026 08:58:37 +0100 Subject: [PATCH 08/11] Teach the package skills the new target features Co-Authored-By: Claude Opus 5.5 --- src/Nullean.Make.Fs/skills/nullean-make-fs/SKILL.md | 13 +++++++++++-- src/Nullean.Make/skills/nullean-make/SKILL.md | 10 ++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/Nullean.Make.Fs/skills/nullean-make-fs/SKILL.md b/src/Nullean.Make.Fs/skills/nullean-make-fs/SKILL.md index 41f2c49..721a25a 100644 --- a/src/Nullean.Make.Fs/skills/nullean-make-fs/SKILL.md +++ b/src/Nullean.Make.Fs/skills/nullean-make-fs/SKILL.md @@ -71,6 +71,15 @@ let main argv = `executes (shell { ... })` adds a body that runs last. - A record payload is the target's flags (`Test of TestOptions` takes `--filter`). A DU payload is a namespace (`Pkg of PkgTarget` gives `pkg generate`). +- A dependency can name a payload, `Test { Filter = Some "Unit" }`: the target runs with it. Equal payloads run once, + different payloads once each. Only the named target binds the command line. +- `concurrently [A; B]` in a `command { }` block is a stage that runs side by side (F# reserves `parallel`); stages + run in the order written. `-j N` caps targets at once and `-k` keeps going after a failure. `printfn` output is + prefixed with the target's name; `sh` output keeps the console and is not cancelled. +- Pipe a definition through `onlyWhen (fun () -> ...)`, `after [Lint]`, `cleanup [StopDb]`, `needsEnv ["KEY"]`, + `needsTool ["docker"]` and `describe "..."`. +- `build release --graph` (or `--graph mermaid|json`) draws the plan, skipped targets included, and runs nothing. + `build lint test pack` runs several targets; `--skip docs` leaves one out. - Global options: `app.Flag("--verbose", short = "-v", desc = "...")`, `app.Option<'T>(...)`, read with `.Value` inside a block. - ` __wrappers sync --run "dotnet run --project build --"` writes mise, make and just includes with one task per @@ -80,8 +89,8 @@ let main argv = ## Gotchas - Descriptions are the `///` comments on the cases, read from the XML documentation file: the project needs - `true`. A `.fsx` script has none; use - `Make.target deps "description" body` there. + `true`. A `.fsx` script has none; pipe the target through + `describe "..."` there. - `sh $"..."` splits only the literal text; each `{value}` stays one argument. Do not build a command string with `sprintf` and pass it in as one value: it becomes a single argument. Use an `if`, or a list spliced as `{args}`. - Code in the `match` arm outside the block runs when the graph is read, for every case. Put the work inside diff --git a/src/Nullean.Make/skills/nullean-make/SKILL.md b/src/Nullean.Make/skills/nullean-make/SKILL.md index fa39f46..89d1c7f 100644 --- a/src/Nullean.Make/skills/nullean-make/SKILL.md +++ b/src/Nullean.Make/skills/nullean-make/SKILL.md @@ -62,6 +62,16 @@ union Target(Clean, Build, Test, Pkg, Release); - `app.Target(deps, body)`: dependencies run first, once each. `app.Command(requires, composes)` sequences other targets: `requires` are gates, `composes` the work, in order; an optional third argument runs last. - A case record's constructor parameters are that target's flags: `Test(string? Filter = null)` takes `--filter`. +- A dependency can name a value, `app.Target([new Test("Unit")], ...)`: the target runs with it. Equal values run + once, different values once each. Only the named target binds the command line. +- `app.Command().Requires(new Test()).Parallel(new PackNuget(), new Docs()).Composes(new Publish())` runs a stage + side by side; stages run in declared order. `-j N` caps targets at once, `-k` keeps going after a failure, and an + async body can take the cancellation token: `app.Target(async ct => ...)`. +- On a target builder: `.OnlyWhen(() => ...)` skips the body, `.After(new Lint())` orders it after `lint` when both + run, `.Cleanup(new StopDb())` runs at the end even after a failure, `.NeedsEnv("KEY")` / `.NeedsTool("docker")` are + checked before anything starts. +- `./build.cs release --graph` (or `--graph mermaid|json`) draws the plan, skipped targets included, and runs + nothing. `./build.cs lint test pack` runs several targets; `--skip docs` leaves one out. - A nested union is a namespace: `Pkg` gives `pkg generate` and `pkg validate`. Match it with `Pkg { Value: Generate }` and create it with `new Pkg(new Generate())`. - A non-zero exit code from `Exec` fails the target, and `RunAsync` returns `1`. A bad or missing option value From cf94635e70cd033b252a08aeb82819e8d531c435 Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 12 Nov 2026 09:56:38 +0100 Subject: [PATCH 09/11] Stop and prefix F# sh commands in parallel stages A `target { }` block that runs side by side with others now runs its `shell { }` with the run's cancellation token, through Proc.Fs's new `ShellBuilder.Run(step, cancellationToken)`. Its `sh` commands print through `Console.Out`, so their lines carry the target's name, and a failure elsewhere stops them. A run without a parallel stage leaves them on the console. Moves Proc and Proc.Fs to 0.21.0, the first release with that overload. Co-Authored-By: Claude Opus 5.5 --- Directory.Packages.props | 4 +- docs/make/parallel.md | 9 ++-- src/Nullean.Make.Fs/Builders.fs | 11 +++- src/Nullean.Make.Fs/README.md | 3 +- .../skills/nullean-make-fs/SKILL.md | 4 +- tests/Nullean.Make.Fs.Tests/ParallelTests.fs | 54 +++++++++++++++++++ 6 files changed, 73 insertions(+), 12 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 0517c4f..c475124 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -7,8 +7,8 @@ - - + + diff --git a/docs/make/parallel.md b/docs/make/parallel.md index 82087b3..87ed7af 100644 --- a/docs/make/parallel.md +++ b/docs/make/parallel.md @@ -55,7 +55,7 @@ one does not start. The run still exits with the first failure's exit code. A target body stops when it is cancelled only if it watches for it: -- `Shell.Exec` watches for it, and stops the process it started. +- `Shell.Exec` in C#, and `sh` in an F# `target { }` block, watch for it and stop the process they started. - An async body can take the token: `app.Target(async ct => await Task.Delay(1000, ct))`, or read `MakeContext.Current.CancellationToken`. @@ -85,11 +85,8 @@ A command run with `Shell.Exec` streams its output through the target's lines. I terminal, so a tool that colours only for a terminal prints without colour. A run with one job, or without a parallel stage, leaves every command on the console as before. -:::{note} -In F#, `sh` commands inside a `target { }` block run on the console, not through the target's lines, and a failure -elsewhere does not stop them. `printfn` and other `Console` output is prefixed. A parallel F# target finishes the -command it is running when the run stops, and then starts no more. -::: +In F#, the `sh` commands of a `target { }` block running side by side do the same: their lines carry the target's +name, and a failure elsewhere stops them. The `shell { }` inside a command's `executes (...)` runs on the console. ## Build options with the same name diff --git a/src/Nullean.Make.Fs/Builders.fs b/src/Nullean.Make.Fs/Builders.fs index d257a9b..ec6cbed 100644 --- a/src/Nullean.Make.Fs/Builders.fs +++ b/src/Nullean.Make.Fs/Builders.fs @@ -35,7 +35,16 @@ type TargetBuilder<'TCase>(dependsOn: 'TCase list, hidden: bool) = member _.TryWith(body: ShellStep<'T>, handler: exn -> ShellStep<'T>) = shell.TryWith(body, handler) member _.TryFinally(body: ShellStep<'T>, compensation: unit -> unit) = shell.TryFinally(body, compensation) member _.Using(resource: 'R :> IDisposable, body: 'R -> ShellStep<'T>) = shell.Using(resource, body) - member _.Run(step: ShellStep) : Definition<'TCase> = FsTarget("", dependsOn, (fun _ -> shell.Run step), hidden) + member _.Run(step: ShellStep) : Definition<'TCase> = + FsTarget("", dependsOn, (fun _ -> shell.Run(step, TargetBuilder<'TCase>.Token())), hidden) + + /// While targets run side by side, the run's token: a failure elsewhere stops the block, and its commands print + /// through Console.Out, where each line gets the target's name. Otherwise none, so commands keep the console. + static member internal Token() = + match Nullean.Make.MakeContext.Current with + | null -> Threading.CancellationToken.None + | ctx when isNull ctx.Sink -> Threading.CancellationToken.None + | ctx -> ctx.CancellationToken /// What a command { } block collects: its requires, its composed stages in order and an optional body. [] diff --git a/src/Nullean.Make.Fs/README.md b/src/Nullean.Make.Fs/README.md index 488a4d5..396c0b5 100644 --- a/src/Nullean.Make.Fs/README.md +++ b/src/Nullean.Make.Fs/README.md @@ -131,7 +131,8 @@ they are written: ``` `-j` / `--jobs` caps how many targets run at once, and `-k` / `--keep-going` lets the targets that do not depend on a -failure finish. `printfn` output of targets running side by side carries their names; `sh` commands keep the console. +failure finish. Output of targets running side by side, `sh` commands included, carries their names, and a failure +stops the `sh` commands still running. See [Running targets side by side](https://argh.nullean.net/make/parallel). `executes (...)` adds a body that runs after every composed target. Like a target block, it is deferred. Use `shell { }` inside it to run commands: diff --git a/src/Nullean.Make.Fs/skills/nullean-make-fs/SKILL.md b/src/Nullean.Make.Fs/skills/nullean-make-fs/SKILL.md index 721a25a..ed5ba9e 100644 --- a/src/Nullean.Make.Fs/skills/nullean-make-fs/SKILL.md +++ b/src/Nullean.Make.Fs/skills/nullean-make-fs/SKILL.md @@ -74,8 +74,8 @@ let main argv = - A dependency can name a payload, `Test { Filter = Some "Unit" }`: the target runs with it. Equal payloads run once, different payloads once each. Only the named target binds the command line. - `concurrently [A; B]` in a `command { }` block is a stage that runs side by side (F# reserves `parallel`); stages - run in the order written. `-j N` caps targets at once and `-k` keeps going after a failure. `printfn` output is - prefixed with the target's name; `sh` output keeps the console and is not cancelled. + run in the order written. `-j N` caps targets at once and `-k` keeps going after a failure. Output, `sh` included, is + prefixed with the target's name, and a failure elsewhere stops a running `sh`. - Pipe a definition through `onlyWhen (fun () -> ...)`, `after [Lint]`, `cleanup [StopDb]`, `needsEnv ["KEY"]`, `needsTool ["docker"]` and `describe "..."`. - `build release --graph` (or `--graph mermaid|json`) draws the plan, skipped targets included, and runs nothing. diff --git a/tests/Nullean.Make.Fs.Tests/ParallelTests.fs b/tests/Nullean.Make.Fs.Tests/ParallelTests.fs index 7dec8a8..8bd4722 100644 --- a/tests/Nullean.Make.Fs.Tests/ParallelTests.fs +++ b/tests/Nullean.Make.Fs.Tests/ParallelTests.fs @@ -6,6 +6,7 @@ open System.Threading open System.Collections.Concurrent open TUnit.Core open Nullean.Make.Fs +open Proc.Fs type Side = | Left @@ -59,3 +60,56 @@ type ParallelTests() = member _.``Graph draws the parallel stage``() = let _, _, stdout = run ["both"; "--graph"] Assert.Contains("parallel", stdout) + +type Shelled = + | Version + | Sleeper + | Breaker + | Quiet + | Pair + | Doomed + +/// A command that runs for half a minute, on every OS the tests run on. +let private longCommand () = + if OperatingSystem.IsWindows() then "ping", [ "-n"; "30"; "127.0.0.1" ] else "sleep", [ "30" ] + +let private runShelled (args: string list) = + let log = ConcurrentQueue() + let app = MakeApp("build", None) + let binary, longArgs = longCommand () + app.Bind <| function + | Version -> target [] { sh $"dotnet --version" } + | Sleeper -> target [] { + sh $"{binary} {longArgs}" + log.Enqueue "sleeper:done" } + | Breaker -> target [] { failBuild "broken on purpose" } + | Quiet -> target [] { printfn "quiet" } + | Pair -> command { concurrently [Version; Quiet] } + | Doomed -> command { concurrently [Sleeper; Breaker] } + let stdout = new StringWriter() + let oldOut, oldErr = Console.Out, Console.Error + Console.SetOut stdout + Console.SetError(new StringWriter()) + let watch = Diagnostics.Stopwatch.StartNew() + try + let exit = app.RunAsync(List.toArray args).GetAwaiter().GetResult() + exit, List.ofSeq log, string stdout, watch.Elapsed + finally + Console.SetOut oldOut + Console.SetError oldErr + +[] +type ParallelShellTests() = + + [] + member _.``sh output of a target running side by side carries its name``() = + let _, _, stdout, _ = runShelled ["pair"; "-j"; "2"] + let lines = stdout.Split('\n') |> Array.map (fun l -> l.Trim()) + Assert.Equal(true, lines |> Array.exists (fun l -> l.StartsWith "[version] " && Char.IsDigit l.["[version] ".Length])) + + [] + member _.``a failure elsewhere stops a running sh command``() = + let exit, log, _, elapsed = runShelled ["doomed"; "-j"; "2"] + Assert.Equal(1, exit) + Assert.Equal([], log) + Assert.Equal(true, elapsed < TimeSpan.FromSeconds 20.) From 3f7a2a3ac52a0b5e51012bf0edd6b5fd9a04dd89 Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 12 Nov 2026 12:13:58 +0100 Subject: [PATCH 10/11] Format with curb 0.14.1 Co-Authored-By: Claude Opus 5.5 --- src/Nullean.Make/Wrappers/WrapperModel.cs | 1 + tests/Nullean.Make.Tests/WrapperTests.cs | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Nullean.Make/Wrappers/WrapperModel.cs b/src/Nullean.Make/Wrappers/WrapperModel.cs index a02baf6..20c8e08 100644 --- a/src/Nullean.Make/Wrappers/WrapperModel.cs +++ b/src/Nullean.Make/Wrappers/WrapperModel.cs @@ -34,6 +34,7 @@ public static WrapperModel From(BuildGraph graph, string run, string? prefix) // The switches every Make script reads. A build option with the same short name keeps it, as on the command line. string? Short(string name) => graph.GlobalOptions.Any(o => o.Short?.TrimStart('-') == name.TrimStart('-')) ? null : name; + var options = new List { new("--single-target", "-s", "Skip prerequisite deps; run only the body / Composes", true, "bool"), diff --git a/tests/Nullean.Make.Tests/WrapperTests.cs b/tests/Nullean.Make.Tests/WrapperTests.cs index 263b8ff..c36ea6a 100644 --- a/tests/Nullean.Make.Tests/WrapperTests.cs +++ b/tests/Nullean.Make.Tests/WrapperTests.cs @@ -41,7 +41,9 @@ public class KeepBuild : MakeBuild [Flag("--keep", "-k", Description = "Keep the output")] public bool Keep { get; init; } - public Target Clean => _ => _.Executes(() => { }); + public Target Clean => + _ => _.Executes(() => + { }); } public class ClashingWrapperBuild : MakeBuild From ff05d772234da1676a10b16a15fd4f272bb48db8 Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 12 Nov 2026 12:14:07 +0100 Subject: [PATCH 11/11] Format with curb 0.14.1 Co-Authored-By: Claude Opus 5.5 --- tests/Nullean.Make.Tests/ParallelTests.cs | 32 +++++++++++++---------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/tests/Nullean.Make.Tests/ParallelTests.cs b/tests/Nullean.Make.Tests/ParallelTests.cs index cb23532..cf3bf9b 100644 --- a/tests/Nullean.Make.Tests/ParallelTests.cs +++ b/tests/Nullean.Make.Tests/ParallelTests.cs @@ -292,20 +292,24 @@ private static async Task> RunAsync(params string[] args) { var log = new System.Collections.Concurrent.ConcurrentQueue(); var app = new MakeApp("build"); - app.Bind(o => o.Value switch - { - First => app.Target(async () => - { - log.Enqueue("first:start"); - await Task.Delay(200); - log.Enqueue("first:end"); - }), - SecondsDependency => app.Target(() => log.Enqueue("seconds-dependency")), - Second => app.Target([new SecondsDependency()], () => log.Enqueue("second")), - InOrder => app.Command([], [new First(), new Second()]), - Fanned => app.Command().Composes(new First()).Parallel(new Second(), new SecondsDependency()), - _ => throw new InvalidOperationException() - }); + app.Bind( + o => + o.Value switch + { + First => + app.Target(async () => + { + log.Enqueue("first:start"); + await Task.Delay(200); + log.Enqueue("first:end"); + }), + SecondsDependency => app.Target(() => log.Enqueue("seconds-dependency")), + Second => app.Target([new SecondsDependency()], () => log.Enqueue("second")), + InOrder => app.Command([], [new First(), new Second()]), + Fanned => app.Command().Composes(new First()).Parallel(new Second(), new SecondsDependency()), + _ => throw new InvalidOperationException() + } + ); var (oldOut, oldErr) = (Console.Out, Console.Error); Console.SetOut(new StringWriter()); Console.SetError(new StringWriter());