Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/_docset.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ toc:
children:
- file: index.md
- file: graph.md
- file: parallel.md
- file: wrappers.md
- file: mise.md
- file: makefile.md
Expand Down
3 changes: 3 additions & 0 deletions docs/make/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
97 changes: 97 additions & 0 deletions docs/make/parallel.md
Original file line number Diff line number Diff line change
@@ -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<TUnion>`:

```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

Check warning on line 26 in docs/make/parallel.md

View workflow job for this annotation

GitHub Actions / docs

Unknown language: 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.
23 changes: 17 additions & 6 deletions src/Nullean.Make.Fs/Builders.fs
Original file line number Diff line number Diff line change
Expand Up @@ -37,36 +37,47 @@ 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<unit>) : Definition<'TCase> = FsTarget("", dependsOn, (fun _ -> shell.Run step), hidden)

/// What a <c>command { }</c> block collects: its requires, its composes and an optional body.
/// What a <c>command { }</c> block collects: its requires, its composed stages in order and an optional body.
[<NoComparison; NoEquality>]
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 }

/// <summary>
/// Builds a command from <c>requires</c> (gates, skipped under <c>-s</c>), <c>composes</c> (always run) and an
/// optional <c>executes</c> body that runs last:
/// <code>
/// | 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"
/// printfn $"released {sha}" }) }
/// </code>
/// </summary>
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.
[<CustomOperation("requires")>]
member _.Requires(spec: CommandSpec<'TCase>, targets: 'TCase list) = { spec with Requires = spec.Requires @ targets }
/// Targets the command always runs, in order.
[<CustomOperation("composes")>]
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] }
/// <summary>
/// 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. <c>-j</c> caps how many run at once.
/// The name is <c>concurrently</c> because F# reserves <c>parallel</c>.
/// </summary>
[<CustomOperation("concurrently")>]
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.
[<CustomOperation("executes")>]
member _.Executes(spec: CommandSpec<'TCase>, [<ProjectionParameter>] 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 ()))

/// <summary>The <c>target</c> and <c>command</c> builders. Descriptions come from the DU case's <c>///</c> doc comment.</summary>
[<AutoOpen>]
Expand Down
9 changes: 5 additions & 4 deletions src/Nullean.Make.Fs/FsGraphBuilder.fs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down
30 changes: 16 additions & 14 deletions src/Nullean.Make.Fs/MakeApp.fs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>()
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<string, bool> 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
Expand Down Expand Up @@ -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<string, TargetNode>) =
let routeTokens = Collections.Generic.List<string>()
Expand Down Expand Up @@ -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 ())
Expand Down Expand Up @@ -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)
}
14 changes: 14 additions & 0 deletions src/Nullean.Make.Fs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions src/Nullean.Make.Fs/Types.fs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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))
7 changes: 7 additions & 0 deletions src/Nullean.Make/Command.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ public interface ICommandBuilder : ITargetBuilder

/// <summary>Declares the targets that constitute the core work of this command. Always runs.</summary>
ICommandBuilder Composes(params TargetRef[] refs);

/// <summary>
/// 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. <c>-j</c> caps how many
/// targets run at once.
/// </summary>
ICommandBuilder Parallel(params TargetRef[] refs);
}

/// <summary>
Expand Down
3 changes: 3 additions & 0 deletions src/Nullean.Make/CommandOfT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ public interface ICommandBuilder<T> : ITargetBuilder<T>

/// <inheritdoc cref="ICommandBuilder.Composes"/>
ICommandBuilder<T> Composes(params TargetRef[] refs);

/// <inheritdoc cref="ICommandBuilder.Parallel"/>
ICommandBuilder<T> Parallel(params TargetRef[] refs);
}

/// <summary>
Expand Down
5 changes: 3 additions & 2 deletions src/Nullean.Make/Discovery/ClassTargetSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading