Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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 @@ -51,6 +51,7 @@ toc:
- file: index.md
- file: graph.md
- file: parallel.md
- file: modifiers.md
- file: wrappers.md
- file: mise.md
- file: makefile.md
Expand Down
3 changes: 3 additions & 0 deletions docs/make/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
[**Running targets side by side**](parallel.md) - Parallel stages, `-j`, `--keep-going`, and the output of targets
that run at once.

[**Conditions, ordering and cleanup**](modifiers.md) - `OnlyWhen`, `After`, `Cleanup`, and checks for environment
variables and tools before the run starts.

[**Drawing the plan**](graph.md) - `--graph` draws what a run would do, skipped targets included, and runs nothing.

[**Wrappers**](wrappers.md) - Generate one task per target for [mise](mise.md), [make](makefile.md) and
Expand Down
82 changes: 82 additions & 0 deletions docs/make/modifiers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Conditions, ordering and cleanup

A target can say when its body runs, what it runs after, what cleans up after it, and what it needs before the run
starts. C# adds them to the builder; F# pipes the target through functions.

```csharp
StartDb => app.Target(() => Exec("docker compose up -d db")).Cleanup(new StopDb()),
Test t => app.Target([new Build(), new StartDb()], () => Exec("dotnet test")).After(new Lint()),
Publish => app.Target(() => Exec("dotnet nuget push build/output/*.nupkg"))
.OnlyWhen(() => !dryRun.Value)
.NeedsEnv("NUGET_API_KEY")
.NeedsTool("docker"),
```

```fsharp

Check warning on line 15 in docs/make/modifiers.md

View workflow job for this annotation

GitHub Actions / docs

Unknown language: fsharp
| StartDb -> target [] { sh $"docker compose up -d db" } |> cleanup [StopDb]
| Test o -> target [Build; StartDb] { sh $"dotnet test" } |> after [Lint]
| Publish -> target [] { sh $"dotnet nuget push build/output/*.nupkg" }
|> onlyWhen (fun () -> not dryRun.Value)
|> needsEnv ["NUGET_API_KEY"]
|> needsTool ["docker"]
|> describe "Push the packages"
```

The `MakeBuild` class has the same methods: `.OnlyWhen(...)`, `.After(Lint)`, `.Cleanup(StopDb)`, `.NeedsEnv(...)` and
`.NeedsTool(...)`.

## Conditions

`OnlyWhen` / `onlyWhen` skips the body when the condition returns false. The target's dependencies still run. The log
shows the target as skipped. `--graph` evaluates the condition to show what it skips; a run evaluates it again just
before the target would start.

## Running after a target without depending on it

`After` / `after` orders a target after another one when both are in the run. It does not add the other target to
the run: `package` alone runs only `package`.

It matters where the plan leaves two targets unordered, such as the targets of a parallel stage:

```csharp
Ci => app.Command().Parallel(new Package(), new Lint()), // package waits for lint
```

A target named with its default value matches the other target with any value; with another value, only that value.
An `After` that contradicts an order the plan already has, such as a composed list that names `package` before
`lint`, is a cycle. The run exits `1` and names the targets involved.

## Cleanup

`Cleanup` / `cleanup` names targets whose bodies run at the end of the run once this target has started, even when
the run fails. Cleanups run newest first, and each runs once however many targets name it. A cleanup runs its body
only, not its dependencies.

```text
Starting start-db
Starting integration
[make] Target 'integration' failed: 2 tests failed
Starting stop-db
Finished stop-db (1.2s)
```

The run keeps the exit code of the failure. When only a cleanup fails, the run exits with the cleanup's exit code.

## What a target needs

`NeedsEnv` / `needsEnv` and `NeedsTool` / `needsTool` name environment variables that must be set and executables
that must be on the `PATH`. The run checks every target it would run before the first one starts, and lists everything
missing:

```text
[make] The run cannot start. It needs:
the environment variable NUGET_API_KEY, for publish
docker on the PATH, for docker image
```

A target whose condition is false needs nothing. `--graph` lists what is missing under `Missing:` and runs nothing.

## Descriptions in F# scripts

A target's description comes from the `///` comment on its case, read from the XML documentation file. An `.fsx`
script has no such file. `|> describe "..."` sets the description in the script itself.
44 changes: 44 additions & 0 deletions src/Nullean.Make.Fs/Builders.fs
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,47 @@ module MakeBuilders =

/// A command that sequences other targets. See CommandBuilder.
let command = CommandBuilder()

/// <summary>
/// Pipe a <c>target</c> or <c>command</c> through these to add to it:
/// <code>
/// | Publish -> target [] { sh $"dotnet nuget push build/output/*.nupkg" }
/// |> onlyWhen (fun () -> not dryRun.Value)
/// |> needsEnv ["NUGET_API_KEY"]
/// |> describe "Push the packages"
/// </code>
/// </summary>
[<AutoOpen>]
module MakeModifiers =
/// <summary>
/// Skips the body when <paramref name="condition"/> returns false. The dependencies still run. <c>--graph</c>
/// evaluates it to show what it skips; a run evaluates it again just before the target would start.
/// </summary>
let onlyWhen (condition: unit -> bool) (definition: Definition<'TCase>) =
definition |> Modifiers.add (fun m -> { m with OnlyWhen = Some condition })

/// <summary>
/// Runs after <paramref name="targets"/> when they are in the same run, without adding them to it. A case with its
/// default payload matches the target with any payload; with another payload, only that payload.
/// </summary>
let after (targets: 'TCase list) (definition: Definition<'TCase>) =
definition |> Modifiers.add (fun m -> { m with After = m.After @ targets })

/// <summary>
/// Targets whose bodies run at the end of the run, newest first, once this target has started, even when the run
/// fails. A cleanup runs its body only, and once however many targets name it.
/// </summary>
let cleanup (targets: 'TCase list) (definition: Definition<'TCase>) =
definition |> Modifiers.add (fun m -> { m with Cleanup = m.Cleanup @ targets })

/// Environment variables that must be set. The run checks them before anything starts, and lists every one missing.
let needsEnv (variables: string list) (definition: Definition<'TCase>) =
definition |> Modifiers.add (fun m -> { m with NeedsEnv = m.NeedsEnv @ variables })

/// Executables that must be on the PATH. The run checks them before anything starts, and lists every one missing.
let needsTool (tools: string list) (definition: Definition<'TCase>) =
definition |> Modifiers.add (fun m -> { m with NeedsTool = m.NeedsTool @ tools })

/// The description help shows, for a script without an XML documentation file such as an .fsx.
let describe (description: string) (definition: Definition<'TCase>) =
definition |> Modifiers.add (fun m -> { m with Description = Some description })
25 changes: 20 additions & 5 deletions src/Nullean.Make.Fs/FsGraphBuilder.fs
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,23 @@ type private FsTargetSource<'TCase when 'TCase : comparison and 'TCase : not nul
let spec = Nullean.Make.Execution.InstanceSpec()
let body (b: FsContext -> unit) =
Func<Threading.CancellationToken, Threading.Tasks.Task>(fun _ -> b sharedCtx; Threading.Tasks.Task.CompletedTask)
match bind (unbox<'TCase> value) with
let definition, modifiers = Modifiers.unwrap (bind (unbox<'TCase> value))
spec.OnlyWhen <- modifiers.OnlyWhen |> Option.map (fun f -> Func<bool> f) |> Option.toObj
// A case named with its default payload in `after` matches the target with any payload.
let defaultOf (d: 'TCase) = let n = resolve node d in if box d = box (fst nodeCases.[n]) then null else box d
spec.After.AddRange(modifiers.After |> List.map (fun d -> DepRef(resolve node d, defaultOf d)))
spec.Cleanup.AddRange(refs node modifiers.Cleanup)
spec.NeedsEnv.AddRange(modifiers.NeedsEnv)
spec.NeedsTool.AddRange(modifiers.NeedsTool)
match definition with
| FsTarget(_, deps, b, _) ->
spec.Add(Nullean.Make.Execution.StageKind.Requires, refs node deps)
spec.Body <- body b
| 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 _ -> ()
| FsNamespace _ | FsWith _ -> ()
spec

member _.FormatValue(node, value) =
Expand All @@ -93,6 +101,10 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null>
(optionDecls: (string * string option * string option * bool * Type option) list)
: BuildGraph =

// The source sees modifiers; everything here reads the target or command they wrap.
let bindWithModifiers = bind
let bind (v: 'TCase) = fst (Modifiers.unwrap (bindWithModifiers v))

let graph = BuildGraph()
graph.AppName <- appName
graph.AppDescription <- match appDescription with Some d -> d | None -> null
Expand Down Expand Up @@ -147,7 +159,10 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null>
// NOTE: namespace sub-cases must be parameterless; payload sub-DUs are not supported.
let registerNode (route: string[]) (def: Definition<'TCase>) (caseInfoForBody: UnionCaseInfo) (key: 'TCase) =
let kind = match def with | FsCommand _ -> TargetKind.Command | _ -> TargetKind.Target
let explicitDesc = match def with | FsTarget(d,_,_,_) | FsCommand(d,_,_,_) -> d | _ -> ""
let explicitDesc =
match (snd (Modifiers.unwrap (bindWithModifiers key))).Description with
| Some d -> d
| None -> match def with | FsTarget(d,_,_,_) | FsCommand(d,_,_,_) -> d | _ -> ""
// No explicit description: use the case's /// doc comment (T:<Union>.<Case> in the XML doc file).
let rawDesc =
if not (String.IsNullOrEmpty explicitDesc) then explicitDesc
Expand Down Expand Up @@ -215,15 +230,15 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null>
raise (MakeException($"Target '{route}' depends on '{caseKey dep}', which is not a target or command.", 1))
for KeyValue(_, (node, tcase)) in caseToNode do
match bind tcase with
| FsNamespace _ -> ()
| FsNamespace _ | FsWith _ -> ()
| FsTarget(_, deps, _, _) ->
for dep in deps do node.RequiresResolved.Add(resolve node dep)
| FsCommand(_, requires, stages, _) ->
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)

graph.Source <- FsTargetSource<'TCase>(bind, nodeCases, (fun node dep -> resolve node dep))
graph.Source <- FsTargetSource<'TCase>(bindWithModifiers, nodeCases, (fun node dep -> resolve node dep))

match defaultCase with
| None -> ()
Expand Down
18 changes: 17 additions & 1 deletion src/Nullean.Make.Fs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,25 @@ See [Running targets side by side](https://argh.nullean.net/make/parallel).
printfn $"published {sha}" }) }
```

## Conditions, ordering and cleanup

Pipe a target or command through these:

```fsharp
| StartDb -> target [] { sh $"docker compose up -d db" } |> cleanup [StopDb] // at the end, even after a failure
| Package -> target [] { sh $"dotnet pack" } |> after [Lint] // after lint when both run
| Publish -> target [] { sh $"dotnet nuget push" }
|> onlyWhen (fun () -> not dryRun.Value) // skip the body; the dependencies still run
|> needsEnv ["NUGET_API_KEY"] // checked before anything starts
|> needsTool ["docker"]
|> describe "Push the packages" // for an .fsx script without an XML doc file
```

See [Conditions, ordering and cleanup](https://argh.nullean.net/make/modifiers).

## Descriptions from doc comments

A target's description is the `///` doc comment on its DU case. The comment is read from the XML documentation file, so the build project needs `<GenerateDocumentationFile>true</GenerateDocumentationFile>`. A `.fsx` script produces no documentation file. In a script, pass a description with `Make.target` (below), or the target shows its name.
A target's description is the `///` doc comment on its DU case. The comment is read from the XML documentation file, so the build project needs `<GenerateDocumentationFile>true</GenerateDocumentationFile>`. A `.fsx` script produces no documentation file. In a script, pipe the target through `describe "..."`, or the target shows its name.

## Namespaces via nested DUs

Expand Down
29 changes: 29 additions & 0 deletions src/Nullean.Make.Fs/Types.fs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,35 @@ type Definition<'TCase> =
/// stages: the composed targets in declared order; true marks a stage whose targets run side by side
| FsCommand of desc: string * requires: 'TCase list * stages: (bool * 'TCase list) list * body: (FsContext -> unit) option
| FsNamespace of segment: string * desc: string option
/// A target or command with what onlyWhen, after, cleanup, needsEnv, needsTool and describe added to it
| FsWith of inner: Definition<'TCase> * modifiers: Modifiers<'TCase>

/// What the pipe functions add to a target or command.
and [<NoComparison; NoEquality>] Modifiers<'TCase> =
internal
{ OnlyWhen: (unit -> bool) option
After: 'TCase list
Cleanup: 'TCase list
NeedsEnv: string list
NeedsTool: string list
Description: string option }

module internal Modifiers =
let empty<'TCase> : Modifiers<'TCase> =
{ OnlyWhen = None; After = []; Cleanup = []; NeedsEnv = []; NeedsTool = []; Description = None }

/// Adds to a definition's modifiers, wrapping it the first time.
let add (f: Modifiers<'TCase> -> Modifiers<'TCase>) (definition: Definition<'TCase>) =
match definition with
| FsWith(inner, modifiers) -> FsWith(inner, f modifiers)
| FsNamespace _ -> invalidArg "definition" "A namespace has no body to modify."
| inner -> FsWith(inner, f empty)

/// The definition without its modifiers, and the modifiers.
let unwrap (definition: Definition<'TCase>) =
match definition with
| FsWith(inner, modifiers) -> inner, modifiers
| inner -> inner, empty

/// Helpers for building Definition values inside app.Bind.
module Make =
Expand Down
12 changes: 12 additions & 0 deletions src/Nullean.Make/Command.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@ public interface ICommandBuilder : ITargetBuilder
/// <inheritdoc cref="ITargetBuilder.DependsOn"/>
new ICommandBuilder DependsOn(params TargetRef[] refs);

/// <inheritdoc cref="ITargetBuilder.After"/>
new ICommandBuilder After(params TargetRef[] refs);

/// <inheritdoc cref="ITargetBuilder.Cleanup"/>
new ICommandBuilder Cleanup(params TargetRef[] refs);

/// <inheritdoc cref="ITargetBuilder.NeedsEnv"/>
new ICommandBuilder NeedsEnv(params string[] variables);

/// <inheritdoc cref="ITargetBuilder.NeedsTool"/>
new ICommandBuilder NeedsTool(params string[] tools);

/// <inheritdoc cref="ITargetBuilder.Executes(Action)"/>
new ICommandBuilder Executes(Action body);

Expand Down
4 changes: 4 additions & 0 deletions src/Nullean.Make/Discovery/ClassTargetSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ internal sealed class ClassTargetSource(BuildGraph graph) : ITargetSource
public InstanceSpec Describe(TargetNode node, object? value)
{
var spec = new InstanceSpec { OnlyWhen = node.OnlyWhen };
spec.After.AddRange(Resolve(node.After));
spec.Cleanup.AddRange(Resolve(node.Cleanup));
spec.NeedsEnv.AddRange(node.NeedsEnv);
spec.NeedsTool.AddRange(node.NeedsTool);
// Requires are gates: they run before the composed stages, whatever order they were declared in.
foreach (var (kind, parallel, items) in node.Stages.OrderBy(s => s.Kind))
spec.Add(kind, Resolve(items), parallel);
Expand Down
Loading
Loading