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..cf3bf9b --- /dev/null +++ b/tests/Nullean.Make.Tests/ParallelTests.cs @@ -0,0 +1,341 @@ +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"); + } +}