diff --git a/Directory.Packages.props b/Directory.Packages.props index 6c07cf7..05ec229 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -7,8 +7,8 @@ - - + + 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/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/src/Nullean.Make/Wrappers/WrapperModel.cs b/src/Nullean.Make/Wrappers/WrapperModel.cs index 79a8e86..20c8e08 100644 --- a/src/Nullean.Make/Wrappers/WrapperModel.cs +++ b/src/Nullean.Make/Wrappers/WrapperModel.cs @@ -32,7 +32,18 @@ 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.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.) diff --git a/tests/Nullean.Make.Tests/WrapperTests.cs b/tests/Nullean.Make.Tests/WrapperTests.cs index 62ebe77..c36ea6a 100644 --- a/tests/Nullean.Make.Tests/WrapperTests.cs +++ b/tests/Nullean.Make.Tests/WrapperTests.cs @@ -36,6 +36,16 @@ 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 +103,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 +130,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 +147,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 +161,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" '''