diff --git a/docs/_docset.yml b/docs/_docset.yml index fb5c3a3..7fc58a5 100644 --- a/docs/_docset.yml +++ b/docs/_docset.yml @@ -51,6 +51,7 @@ toc: - file: index.md - file: graph.md - file: parallel.md + - file: modifiers.md - file: wrappers.md - file: mise.md - file: makefile.md diff --git a/docs/make/index.md b/docs/make/index.md index 5e70e54..ae9a94f 100644 --- a/docs/make/index.md +++ b/docs/make/index.md @@ -13,6 +13,9 @@ [**Running targets side by side**](parallel.md) - Parallel stages, `-j`, `--keep-going`, and the output of targets that run at once. +[**Conditions, ordering and cleanup**](modifiers.md) - `OnlyWhen`, `After`, `Cleanup`, and checks for environment +variables and tools before the run starts. + [**Drawing the plan**](graph.md) - `--graph` draws what a run would do, skipped targets included, and runs nothing. [**Wrappers**](wrappers.md) - Generate one task per target for [mise](mise.md), [make](makefile.md) and diff --git a/docs/make/modifiers.md b/docs/make/modifiers.md new file mode 100644 index 0000000..b88ca3f --- /dev/null +++ b/docs/make/modifiers.md @@ -0,0 +1,82 @@ +# Conditions, ordering and cleanup + +A target can say when its body runs, what it runs after, what cleans up after it, and what it needs before the run +starts. C# adds them to the builder; F# pipes the target through functions. + +```csharp +StartDb => app.Target(() => Exec("docker compose up -d db")).Cleanup(new StopDb()), +Test t => app.Target([new Build(), new StartDb()], () => Exec("dotnet test")).After(new Lint()), +Publish => app.Target(() => Exec("dotnet nuget push build/output/*.nupkg")) + .OnlyWhen(() => !dryRun.Value) + .NeedsEnv("NUGET_API_KEY") + .NeedsTool("docker"), +``` + +```fsharp +| StartDb -> target [] { sh $"docker compose up -d db" } |> cleanup [StopDb] +| Test o -> target [Build; StartDb] { sh $"dotnet test" } |> after [Lint] +| Publish -> target [] { sh $"dotnet nuget push build/output/*.nupkg" } + |> onlyWhen (fun () -> not dryRun.Value) + |> needsEnv ["NUGET_API_KEY"] + |> needsTool ["docker"] + |> describe "Push the packages" +``` + +The `MakeBuild` class has the same methods: `.OnlyWhen(...)`, `.After(Lint)`, `.Cleanup(StopDb)`, `.NeedsEnv(...)` and +`.NeedsTool(...)`. + +## Conditions + +`OnlyWhen` / `onlyWhen` skips the body when the condition returns false. The target's dependencies still run. The log +shows the target as skipped. `--graph` evaluates the condition to show what it skips; a run evaluates it again just +before the target would start. + +## Running after a target without depending on it + +`After` / `after` orders a target after another one when both are in the run. It does not add the other target to +the run: `package` alone runs only `package`. + +It matters where the plan leaves two targets unordered, such as the targets of a parallel stage: + +```csharp +Ci => app.Command().Parallel(new Package(), new Lint()), // package waits for lint +``` + +A target named with its default value matches the other target with any value; with another value, only that value. +An `After` that contradicts an order the plan already has, such as a composed list that names `package` before +`lint`, is a cycle. The run exits `1` and names the targets involved. + +## Cleanup + +`Cleanup` / `cleanup` names targets whose bodies run at the end of the run once this target has started, even when +the run fails. Cleanups run newest first, and each runs once however many targets name it. A cleanup runs its body +only, not its dependencies. + +```text +Starting start-db +Starting integration +[make] Target 'integration' failed: 2 tests failed +Starting stop-db +Finished stop-db (1.2s) +``` + +The run keeps the exit code of the failure. When only a cleanup fails, the run exits with the cleanup's exit code. + +## What a target needs + +`NeedsEnv` / `needsEnv` and `NeedsTool` / `needsTool` name environment variables that must be set and executables +that must be on the `PATH`. The run checks every target it would run before the first one starts, and lists everything +missing: + +```text +[make] The run cannot start. It needs: + the environment variable NUGET_API_KEY, for publish + docker on the PATH, for docker image +``` + +A target whose condition is false needs nothing. `--graph` lists what is missing under `Missing:` and runs nothing. + +## Descriptions in F# scripts + +A target's description comes from the `///` comment on its case, read from the XML documentation file. An `.fsx` +script has no such file. `|> describe "..."` sets the description in the script itself. diff --git a/src/Nullean.Make.Fs/Builders.fs b/src/Nullean.Make.Fs/Builders.fs index f688a78..d257a9b 100644 --- a/src/Nullean.Make.Fs/Builders.fs +++ b/src/Nullean.Make.Fs/Builders.fs @@ -101,3 +101,47 @@ module MakeBuilders = /// A command that sequences other targets. See CommandBuilder. let command = CommandBuilder() + +/// +/// Pipe a target or command through these to add to it: +/// +/// | Publish -> target [] { sh $"dotnet nuget push build/output/*.nupkg" } +/// |> onlyWhen (fun () -> not dryRun.Value) +/// |> needsEnv ["NUGET_API_KEY"] +/// |> describe "Push the packages" +/// +/// +[] +module MakeModifiers = + /// + /// Skips the body when returns false. The dependencies still run. --graph + /// evaluates it to show what it skips; a run evaluates it again just before the target would start. + /// + let onlyWhen (condition: unit -> bool) (definition: Definition<'TCase>) = + definition |> Modifiers.add (fun m -> { m with OnlyWhen = Some condition }) + + /// + /// Runs after when they are in the same run, without adding them to it. A case with its + /// default payload matches the target with any payload; with another payload, only that payload. + /// + let after (targets: 'TCase list) (definition: Definition<'TCase>) = + definition |> Modifiers.add (fun m -> { m with After = m.After @ targets }) + + /// + /// Targets whose bodies run at the end of the run, newest first, once this target has started, even when the run + /// fails. A cleanup runs its body only, and once however many targets name it. + /// + let cleanup (targets: 'TCase list) (definition: Definition<'TCase>) = + definition |> Modifiers.add (fun m -> { m with Cleanup = m.Cleanup @ targets }) + + /// Environment variables that must be set. The run checks them before anything starts, and lists every one missing. + let needsEnv (variables: string list) (definition: Definition<'TCase>) = + definition |> Modifiers.add (fun m -> { m with NeedsEnv = m.NeedsEnv @ variables }) + + /// Executables that must be on the PATH. The run checks them before anything starts, and lists every one missing. + let needsTool (tools: string list) (definition: Definition<'TCase>) = + definition |> Modifiers.add (fun m -> { m with NeedsTool = m.NeedsTool @ tools }) + + /// The description help shows, for a script without an XML documentation file such as an .fsx. + let describe (description: string) (definition: Definition<'TCase>) = + definition |> Modifiers.add (fun m -> { m with Description = Some description }) diff --git a/src/Nullean.Make.Fs/FsGraphBuilder.fs b/src/Nullean.Make.Fs/FsGraphBuilder.fs index 9c58575..f5655e3 100644 --- a/src/Nullean.Make.Fs/FsGraphBuilder.fs +++ b/src/Nullean.Make.Fs/FsGraphBuilder.fs @@ -71,7 +71,15 @@ type private FsTargetSource<'TCase when 'TCase : comparison and 'TCase : not nul let spec = Nullean.Make.Execution.InstanceSpec() let body (b: FsContext -> unit) = Func(fun _ -> b sharedCtx; Threading.Tasks.Task.CompletedTask) - match bind (unbox<'TCase> value) with + let definition, modifiers = Modifiers.unwrap (bind (unbox<'TCase> value)) + spec.OnlyWhen <- modifiers.OnlyWhen |> Option.map (fun f -> Func f) |> Option.toObj + // A case named with its default payload in `after` matches the target with any payload. + let defaultOf (d: 'TCase) = let n = resolve node d in if box d = box (fst nodeCases.[n]) then null else box d + spec.After.AddRange(modifiers.After |> List.map (fun d -> DepRef(resolve node d, defaultOf d))) + spec.Cleanup.AddRange(refs node modifiers.Cleanup) + spec.NeedsEnv.AddRange(modifiers.NeedsEnv) + spec.NeedsTool.AddRange(modifiers.NeedsTool) + match definition with | FsTarget(_, deps, b, _) -> spec.Add(Nullean.Make.Execution.StageKind.Requires, refs node deps) spec.Body <- body b @@ -79,7 +87,7 @@ type private FsTargetSource<'TCase when 'TCase : comparison and 'TCase : not nul spec.Add(StageKind.Requires, refs node requires) for sideBySide, targets in stages do spec.Add(StageKind.Composes, refs node targets, sideBySide) b |> Option.iter (fun b -> spec.Body <- body b) - | FsNamespace _ -> () + | FsNamespace _ | FsWith _ -> () spec member _.FormatValue(node, value) = @@ -93,6 +101,10 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null> (optionDecls: (string * string option * string option * bool * Type option) list) : BuildGraph = + // The source sees modifiers; everything here reads the target or command they wrap. + let bindWithModifiers = bind + let bind (v: 'TCase) = fst (Modifiers.unwrap (bindWithModifiers v)) + let graph = BuildGraph() graph.AppName <- appName graph.AppDescription <- match appDescription with Some d -> d | None -> null @@ -147,7 +159,10 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null> // NOTE: namespace sub-cases must be parameterless; payload sub-DUs are not supported. let registerNode (route: string[]) (def: Definition<'TCase>) (caseInfoForBody: UnionCaseInfo) (key: 'TCase) = let kind = match def with | FsCommand _ -> TargetKind.Command | _ -> TargetKind.Target - let explicitDesc = match def with | FsTarget(d,_,_,_) | FsCommand(d,_,_,_) -> d | _ -> "" + let explicitDesc = + match (snd (Modifiers.unwrap (bindWithModifiers key))).Description with + | Some d -> d + | None -> match def with | FsTarget(d,_,_,_) | FsCommand(d,_,_,_) -> d | _ -> "" // No explicit description: use the case's /// doc comment (T:. in the XML doc file). let rawDesc = if not (String.IsNullOrEmpty explicitDesc) then explicitDesc @@ -215,7 +230,7 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null> raise (MakeException($"Target '{route}' depends on '{caseKey dep}', which is not a target or command.", 1)) for KeyValue(_, (node, tcase)) in caseToNode do match bind tcase with - | FsNamespace _ -> () + | FsNamespace _ | FsWith _ -> () | FsTarget(_, deps, _, _) -> for dep in deps do node.RequiresResolved.Add(resolve node dep) | FsCommand(_, requires, stages, _) -> @@ -223,7 +238,7 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null> for dep in requires do node.RequiresResolved.Add(resolve node dep) for dep in composes do node.ComposesResolved.Add(resolve node dep) - graph.Source <- FsTargetSource<'TCase>(bind, nodeCases, (fun node dep -> resolve node dep)) + graph.Source <- FsTargetSource<'TCase>(bindWithModifiers, nodeCases, (fun node dep -> resolve node dep)) match defaultCase with | None -> () diff --git a/src/Nullean.Make.Fs/README.md b/src/Nullean.Make.Fs/README.md index bbe25f7..9fda02e 100644 --- a/src/Nullean.Make.Fs/README.md +++ b/src/Nullean.Make.Fs/README.md @@ -146,9 +146,25 @@ See [Running targets side by side](https://argh.nullean.net/make/parallel). printfn $"published {sha}" }) } ``` +## Conditions, ordering and cleanup + +Pipe a target or command through these: + +```fsharp +| StartDb -> target [] { sh $"docker compose up -d db" } |> cleanup [StopDb] // at the end, even after a failure +| Package -> target [] { sh $"dotnet pack" } |> after [Lint] // after lint when both run +| Publish -> target [] { sh $"dotnet nuget push" } + |> onlyWhen (fun () -> not dryRun.Value) // skip the body; the dependencies still run + |> needsEnv ["NUGET_API_KEY"] // checked before anything starts + |> needsTool ["docker"] + |> describe "Push the packages" // for an .fsx script without an XML doc file +``` + +See [Conditions, ordering and cleanup](https://argh.nullean.net/make/modifiers). + ## Descriptions from doc comments -A target's description is the `///` doc comment on its DU case. The comment is read from the XML documentation file, so the build project needs `true`. A `.fsx` script produces no documentation file. In a script, pass a description with `Make.target` (below), or the target shows its name. +A target's description is the `///` doc comment on its DU case. The comment is read from the XML documentation file, so the build project needs `true`. A `.fsx` script produces no documentation file. In a script, pipe the target through `describe "..."`, or the target shows its name. ## Namespaces via nested DUs diff --git a/src/Nullean.Make.Fs/Types.fs b/src/Nullean.Make.Fs/Types.fs index 6f9a5de..b27f034 100644 --- a/src/Nullean.Make.Fs/Types.fs +++ b/src/Nullean.Make.Fs/Types.fs @@ -44,6 +44,35 @@ type Definition<'TCase> = /// stages: the composed targets in declared order; true marks a stage whose targets run side by side | FsCommand of desc: string * requires: 'TCase list * stages: (bool * 'TCase list) list * body: (FsContext -> unit) option | FsNamespace of segment: string * desc: string option + /// A target or command with what onlyWhen, after, cleanup, needsEnv, needsTool and describe added to it + | FsWith of inner: Definition<'TCase> * modifiers: Modifiers<'TCase> + +/// What the pipe functions add to a target or command. +and [] Modifiers<'TCase> = + internal + { OnlyWhen: (unit -> bool) option + After: 'TCase list + Cleanup: 'TCase list + NeedsEnv: string list + NeedsTool: string list + Description: string option } + +module internal Modifiers = + let empty<'TCase> : Modifiers<'TCase> = + { OnlyWhen = None; After = []; Cleanup = []; NeedsEnv = []; NeedsTool = []; Description = None } + + /// Adds to a definition's modifiers, wrapping it the first time. + let add (f: Modifiers<'TCase> -> Modifiers<'TCase>) (definition: Definition<'TCase>) = + match definition with + | FsWith(inner, modifiers) -> FsWith(inner, f modifiers) + | FsNamespace _ -> invalidArg "definition" "A namespace has no body to modify." + | inner -> FsWith(inner, f empty) + + /// The definition without its modifiers, and the modifiers. + let unwrap (definition: Definition<'TCase>) = + match definition with + | FsWith(inner, modifiers) -> inner, modifiers + | inner -> inner, empty /// Helpers for building Definition values inside app.Bind. module Make = diff --git a/src/Nullean.Make/Command.cs b/src/Nullean.Make/Command.cs index 64c3180..66e357f 100644 --- a/src/Nullean.Make/Command.cs +++ b/src/Nullean.Make/Command.cs @@ -18,6 +18,18 @@ public interface ICommandBuilder : ITargetBuilder /// new ICommandBuilder DependsOn(params TargetRef[] refs); + /// + new ICommandBuilder After(params TargetRef[] refs); + + /// + new ICommandBuilder Cleanup(params TargetRef[] refs); + + /// + new ICommandBuilder NeedsEnv(params string[] variables); + + /// + new ICommandBuilder NeedsTool(params string[] tools); + /// new ICommandBuilder Executes(Action body); diff --git a/src/Nullean.Make/Discovery/ClassTargetSource.cs b/src/Nullean.Make/Discovery/ClassTargetSource.cs index 01d5507..5fe93b3 100644 --- a/src/Nullean.Make/Discovery/ClassTargetSource.cs +++ b/src/Nullean.Make/Discovery/ClassTargetSource.cs @@ -13,6 +13,10 @@ internal sealed class ClassTargetSource(BuildGraph graph) : ITargetSource public InstanceSpec Describe(TargetNode node, object? value) { var spec = new InstanceSpec { OnlyWhen = node.OnlyWhen }; + spec.After.AddRange(Resolve(node.After)); + spec.Cleanup.AddRange(Resolve(node.Cleanup)); + spec.NeedsEnv.AddRange(node.NeedsEnv); + spec.NeedsTool.AddRange(node.NeedsTool); // Requires are gates: they run before the composed stages, whatever order they were declared in. foreach (var (kind, parallel, items) in node.Stages.OrderBy(s => s.Kind)) spec.Add(kind, Resolve(items), parallel); diff --git a/src/Nullean.Make/Discovery/TargetBuilderImpl.cs b/src/Nullean.Make/Discovery/TargetBuilderImpl.cs index 09214c0..8d3cfa3 100644 --- a/src/Nullean.Make/Discovery/TargetBuilderImpl.cs +++ b/src/Nullean.Make/Discovery/TargetBuilderImpl.cs @@ -35,6 +35,30 @@ public ITargetBuilder DependsOn(params TargetRef[] refs) return this; } + public ITargetBuilder After(params TargetRef[] refs) + { + _node.After.AddRange(refs); + return this; + } + + public ITargetBuilder Cleanup(params TargetRef[] refs) + { + _node.Cleanup.AddRange(refs); + return this; + } + + public ITargetBuilder NeedsEnv(params string[] variables) + { + _node.NeedsEnv.AddRange(variables); + return this; + } + + public ITargetBuilder NeedsTool(params string[] tools) + { + _node.NeedsTool.AddRange(tools); + return this; + } + public ITargetBuilder Executes(Action body) { _node.SyncBody = body; @@ -75,6 +99,30 @@ ICommandBuilder ICommandBuilder.DependsOn(params TargetRef[] refs) return this; } + ICommandBuilder ICommandBuilder.After(params TargetRef[] refs) + { + _node.After.AddRange(refs); + return this; + } + + ICommandBuilder ICommandBuilder.Cleanup(params TargetRef[] refs) + { + _node.Cleanup.AddRange(refs); + return this; + } + + ICommandBuilder ICommandBuilder.NeedsEnv(params string[] variables) + { + _node.NeedsEnv.AddRange(variables); + return this; + } + + ICommandBuilder ICommandBuilder.NeedsTool(params string[] tools) + { + _node.NeedsTool.AddRange(tools); + return this; + } + ICommandBuilder ICommandBuilder.Executes(Action body) { _node.SyncBody = body; @@ -144,6 +192,30 @@ public ITargetBuilder DependsOn(params TargetRef[] refs) _node.AddReference(Execution.StageKind.Requires, r); return this; } + public ITargetBuilder After(params TargetRef[] refs) + { + _node.After.AddRange(refs); + return this; + } + + public ITargetBuilder Cleanup(params TargetRef[] refs) + { + _node.Cleanup.AddRange(refs); + return this; + } + + public ITargetBuilder NeedsEnv(params string[] variables) + { + _node.NeedsEnv.AddRange(variables); + return this; + } + + public ITargetBuilder NeedsTool(params string[] tools) + { + _node.NeedsTool.AddRange(tools); + return this; + } + public ITargetBuilder Executes(Action body) { _node.TypedBody = body; @@ -161,6 +233,10 @@ public ITargetBuilder Executes(Func body) ITargetBuilder ITargetBuilder.Hidden() => Hidden(); ITargetBuilder ITargetBuilder.OnlyWhen(Func c) => OnlyWhen(c); ITargetBuilder ITargetBuilder.DependsOn(params TargetRef[] refs) => DependsOn(refs); + ITargetBuilder ITargetBuilder.After(params TargetRef[] refs) => After(refs); + ITargetBuilder ITargetBuilder.Cleanup(params TargetRef[] refs) => Cleanup(refs); + ITargetBuilder ITargetBuilder.NeedsEnv(params string[] variables) => NeedsEnv(variables); + ITargetBuilder ITargetBuilder.NeedsTool(params string[] tools) => NeedsTool(tools); ITargetBuilder ITargetBuilder.Executes(Action body) { _node.SyncBody = body; diff --git a/src/Nullean.Make/Discovery/TargetNode.cs b/src/Nullean.Make/Discovery/TargetNode.cs index 64e8c48..c3b2e7b 100644 --- a/src/Nullean.Make/Discovery/TargetNode.cs +++ b/src/Nullean.Make/Discovery/TargetNode.cs @@ -19,6 +19,18 @@ internal sealed class TargetNode public string? Description { get; set; } public bool Hidden { get; set; } public Func? OnlyWhen { get; set; } + + /// Targets this one runs after when they are in the same run. + public List After { get; } = new(); + + /// Targets whose bodies run at the end of the run once this one started. + public List Cleanup { get; } = new(); + + /// Environment variables that must be set before the run starts. + public List NeedsEnv { get; } = new(); + + /// Executables that must be on the PATH before the run starts. + public List NeedsTool { get; } = new(); public TargetKind Kind { get; set; } /// DependsOn / Requires references — skippable under -s. diff --git a/src/Nullean.Make/Execution/DepGraphExecutor.cs b/src/Nullean.Make/Execution/DepGraphExecutor.cs index a111f96..1716858 100644 --- a/src/Nullean.Make/Execution/DepGraphExecutor.cs +++ b/src/Nullean.Make/Execution/DepGraphExecutor.cs @@ -58,6 +58,17 @@ public static int DrawWholeGraph(BuildGraph graph, GraphFormat format) public static async Task ExecuteAsync(RunPlan plan, ParsedArgs parsed) { var context = new MakeContext(parsed.GlobalValues, parsed.SingleTarget) { TargetArgs = parsed.TargetArgs }; + + // Fail before anything runs, rather than at the target that needs what is missing. + var missing = plan.MissingPreconditions(); + if (missing.Count > 0) + { + Console.Error.WriteLine("[make] The run cannot start. It needs:"); + foreach (var (instance, what) in missing) + Console.Error.WriteLine($" {what}, for {instance.Name}"); + return 1; + } + // A plan without a parallel stage runs one target at a time, in its order, whatever --jobs says. var concurrent = CanRunSideBySide(plan) && (parsed.Jobs ?? Environment.ProcessorCount) > 1; var jobs = concurrent ? parsed.Jobs ?? Environment.ProcessorCount : 1; @@ -80,6 +91,7 @@ public static async Task ExecuteAsync(RunPlan plan, ParsedArgs parsed) var failures = new List<(TargetInstance Step, int ExitCode)>(); var started = DateTime.UtcNow; var timings = new List<(TargetInstance Step, TimeSpan Elapsed)>(); + var startOrder = new List(); try { @@ -106,6 +118,7 @@ public static async Task ExecuteAsync(RunPlan plan, ParsedArgs parsed) continue; } + startOrder.Add(next); var sink = concurrent ? new TargetSink(next.Name, mode, stdout, stderr, gate) : null; lock (gate) ExecutionLog.Starting(next, stdout); @@ -148,9 +161,40 @@ public static async Task ExecuteAsync(RunPlan plan, ParsedArgs parsed) } } + var cleanupExit = await RunCleanups(plan, startOrder, context); + if (concurrent) ExecutionLog.Summary(timings, DateTime.UtcNow - started, failures.Select(f => f.Step).ToList(), stdout); - return failures.Count == 0 ? 0 : failures[0].ExitCode; + return failures.Count > 0 ? failures[0].ExitCode : cleanupExit; + } + + /// + /// Runs the cleanup targets of every instance that started, newest first, each once, whether the run failed or not. + /// A cleanup runs its body only. Returns the exit code of the first cleanup that failed, or 0. + /// + private static async Task RunCleanups(RunPlan plan, List startOrder, MakeContext context) + { + var exitCode = 0; + var ran = new HashSet(); + for (var i = startOrder.Count - 1; i >= 0; i--) + { + if (!plan.Cleanups.TryGetValue(startOrder[i], out var cleanups)) + continue; + foreach (var cleanup in cleanups.Where(ran.Add)) + { + ExecutionLog.Starting(cleanup, Console.Out); + var (code, elapsed, message) = await RunStep(cleanup, context.ForTarget(CancellationToken.None, null), null); + if (code == 0) + { + ExecutionLog.Finished(cleanup, elapsed, Console.Out); + continue; + } + Console.Error.WriteLine($"[make] Cleanup '{string.Join("/", cleanup.Node.Route)}' failed: {message}"); + if (exitCode == 0) + exitCode = code; + } + } + return exitCode; } /// Whether two targets of the plan can ever be ready at once: a parallel stage, or roots that do not chain. diff --git a/src/Nullean.Make/Execution/PlanRenderer.cs b/src/Nullean.Make/Execution/PlanRenderer.cs index d9dd84a..74398a9 100644 --- a/src/Nullean.Make/Execution/PlanRenderer.cs +++ b/src/Nullean.Make/Execution/PlanRenderer.cs @@ -134,7 +134,13 @@ private static void WriteTree(RunPlan plan, TextWriter output) if (!plan.Chained && plan.Roots.Count > 1) return; var order = RunOrder(plan); + var cleanups = plan.Cleanups.Values.SelectMany(c => c).Distinct().Select(c => c.Name).ToList(); + if (cleanups.Count > 0) + order += $", then cleanup: {string.Join(", ", cleanups)}"; output.WriteLine($"{CliHelpFormatting.Section("Runs:")} {(order.Length == 0 ? "nothing" : order)}"); + + foreach (var (instance, what) in plan.MissingPreconditions()) + output.WriteLine($"{CliHelpFormatting.Section("Missing:")} {what}, for {instance.Name}"); } private static Line Build(TargetInstance instance, HashSet expanded) @@ -142,6 +148,11 @@ private static Line Build(TargetInstance instance, HashSet expan var text = instance.Name + Annotation(instance.Skipped); if (!expanded.Add(instance)) return new Line(text + Dim(" (above)"), []); + if (instance.Spec.After.Count > 0) + text += Dim($" after {string.Join(", ", instance.Spec.After.Select(a => string.Join(" ", a.Node.Route)))}"); + var needs = instance.Spec.NeedsEnv.Concat(instance.Spec.NeedsTool).ToList(); + if (needs.Count > 0) + text += Dim($" needs {string.Join(", ", needs)}"); var children = new List(); foreach (var kind in new[] { StageKind.Requires, StageKind.Composes }) @@ -167,6 +178,8 @@ private static Line Build(TargetInstance instance, HashSet expan else children.AddRange(lines); } + if (instance.Spec.Cleanup.Count > 0) + children.Add(new Line(Dim("cleanup, at the end"), [.. instance.Spec.Cleanup.Select(c => new Line(string.Join(" ", c.Node.Route), []))])); return new Line(text, children); } diff --git a/src/Nullean.Make/Execution/RunPlan.cs b/src/Nullean.Make/Execution/RunPlan.cs index 8dc7ac1..6c17496 100644 --- a/src/Nullean.Make/Execution/RunPlan.cs +++ b/src/Nullean.Make/Execution/RunPlan.cs @@ -59,6 +59,36 @@ internal sealed class RunPlan /// True when the roots run one after another; false for a drawing of unrelated roots. public bool Chained { get; init; } = true; + /// For each instance with cleanup targets, the instances that run at the end of the run once it started. + public IReadOnlyDictionary> Cleanups + { + get; + init; + } = new Dictionary>(); + + /// + /// What the run needs and does not have: an environment variable that is not set, or an executable not on the + /// PATH, for each instance whose body would run. A target whose condition is false needs nothing. + /// + public IReadOnlyList<(TargetInstance Instance, string Missing)> MissingPreconditions() + { + var missing = new List<(TargetInstance, string)>(); + foreach (var instance in Instances.Concat(Cleanups.Values.SelectMany(c => c)).Distinct()) + { + if (instance.Skipped is not null || instance.Spec.Body is null) + continue; + if (instance.Spec.NeedsEnv.Count + instance.Spec.NeedsTool.Count == 0) + continue; + if (instance.Spec.OnlyWhen is { } condition && !condition()) + continue; + foreach (var variable in instance.Spec.NeedsEnv.Where(v => string.IsNullOrEmpty(Environment.GetEnvironmentVariable(v)))) + missing.Add((instance, $"the environment variable {variable}")); + foreach (var tool in instance.Spec.NeedsTool.Where(t => !Preconditions.OnPath(t))) + missing.Add((instance, $"{tool} on the PATH")); + } + return missing; + } + /// /// Expands the named targets into instances. Each reference resolves to its node and value; a reference without a /// value stands for the node's default value. A sequential stage's item waits for the item before it, and every @@ -76,7 +106,8 @@ public static RunPlan Build(IReadOnlyList roots, ITargetSource source, P rootInstances.Add(instance); previous = instance; } - return new RunPlan { Roots = rootInstances, Instances = builder.Ordered, Chained = options.ChainRoots }; + var ordered = builder.ApplyAfter(); + return new RunPlan { Roots = rootInstances, Instances = ordered, Chained = options.ChainRoots, Cleanups = builder.ResolveCleanups(ordered) }; } private sealed class Builder(ITargetSource source, PlanOptions options) @@ -87,6 +118,79 @@ private sealed class Builder(ITargetSource source, PlanOptions options) public List Ordered { get; } = new(); + /// + /// Adds what each instance runs after, among the instances in the run, and orders the plan again: the earliest + /// instance whose prerequisites have all been placed comes next. + /// + public List ApplyAfter() + { + var any = false; + foreach (var instance in Ordered) + { + foreach (var reference in instance.Spec.After) + { + // A reference without a value matches the target with any value. + var matches = Ordered.Where( + i => i.Node == reference.Node && (reference.Value is null || Equals(i.Value, reference.Value)) && i != instance + ); + foreach (var match in matches) + { + instance.Prerequisites.Add(match); + any = true; + } + } + } + if (!any) + return Ordered; + + var placed = new HashSet(); + var result = new List(); + var remaining = Ordered.ToList(); + while (remaining.Count > 0) + { + var next = remaining.FirstOrDefault(i => i.Prerequisites.All(placed.Contains)); + if (next is null) + { + var stuck = remaining.Select(i => i.Name); + throw new MakeException($"The order the targets ask for has a cycle; none of these can go first: {string.Join(", ", stuck)}", 1); + } + remaining.Remove(next); + placed.Add(next); + next.Order = result.Count; + result.Add(next); + } + return result; + } + + /// The cleanup instances of each instance that declares some. A cleanup runs its body only, not its dependencies. + public Dictionary> ResolveCleanups(List ordered) + { + var cleanups = new Dictionary>(); + var shared = new Dictionary<(TargetNode, object?), TargetInstance>(); + foreach (var instance in ordered.Where(i => i.Spec.Cleanup.Count > 0)) + { + var list = new List(); + foreach (var reference in instance.Spec.Cleanup) + { + var value = Resolve(reference); + if (!shared.TryGetValue((reference.Node, value), out var cleanup)) + { + cleanup = new TargetInstance + { + Node = reference.Node, + Value = value, + Spec = source.Describe(reference.Node, value), + Name = ValueDisplay.Name(reference.Node, source.FormatValue(reference.Node, value)) + }; + shared[(reference.Node, value)] = cleanup; + } + list.Add(cleanup); + } + cleanups[instance] = list; + } + return cleanups; + } + private object? Resolve(DepRef reference) { if (reference.Value is not null) @@ -162,3 +266,27 @@ public TargetInstance Visit(DepRef reference, bool isRoot, IReadOnlyListChecks the things a target says it needs before the run starts. +internal static class Preconditions +{ + /// Whether is an executable on the PATH, with PATHEXT on Windows. + public static bool OnPath(string tool) + { + if (Path.IsPathRooted(tool)) + return File.Exists(tool); + var extensions = OperatingSystem.IsWindows() + ? (Environment.GetEnvironmentVariable("PATHEXT") ?? ".EXE;.CMD;.BAT").Split(';', StringSplitOptions.RemoveEmptyEntries).Prepend("") + : [""]; + var path = Environment.GetEnvironmentVariable("PATH") ?? ""; + foreach (var directory in path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + { + foreach (var extension in extensions) + { + if (File.Exists(Path.Combine(directory, tool + extension))) + return true; + } + } + return false; + } +} diff --git a/src/Nullean.Make/Execution/TargetSource.cs b/src/Nullean.Make/Execution/TargetSource.cs index 4758b99..ca0ab0c 100644 --- a/src/Nullean.Make/Execution/TargetSource.cs +++ b/src/Nullean.Make/Execution/TargetSource.cs @@ -56,6 +56,18 @@ internal sealed class InstanceSpec /// When it returns , the body is skipped. Its dependencies still run. public Func? OnlyWhen { get; set; } + /// Targets this one runs after when they are in the same run. They do not join the run because of it. + public List After { get; } = new(); + + /// Targets whose bodies run at the end of the run when this one started, even after a failure. + public List Cleanup { get; } = new(); + + /// Environment variables that must be set before the run starts. + public List NeedsEnv { get; } = new(); + + /// Executables that must be on the PATH before the run starts. + public List NeedsTool { get; } = new(); + public void Add(StageKind kind, IReadOnlyList items, bool parallel = false) { if (items.Count > 0) diff --git a/src/Nullean.Make/README.md b/src/Nullean.Make/README.md index 5343e2e..75d3b1b 100644 --- a/src/Nullean.Make/README.md +++ b/src/Nullean.Make/README.md @@ -105,6 +105,21 @@ still running; `-k` / `--keep-going` lets the ones that do not depend on it fini side carries their names, or `--output grouped` writes each target's lines together. See [Running targets side by side](https://argh.nullean.net/make/parallel). +## Conditions, ordering and cleanup + +A target builder takes more than dependencies: + +```csharp +StartDb => app.Target(() => Exec("docker compose up -d db")).Cleanup(new StopDb()), // runs at the end, even after a failure +Package => app.Target(() => Exec("dotnet pack")).After(new Lint()), // after lint when both run; does not add it +Publish => app.Target(() => Exec("dotnet nuget push")) + .OnlyWhen(() => !dryRun.Value) // skip the body; the dependencies still run + .NeedsEnv("NUGET_API_KEY") // checked before anything starts + .NeedsTool("docker"), +``` + +See [Conditions, ordering and cleanup](https://argh.nullean.net/make/modifiers). + ## Running commands `using static Nullean.Make.Shell;` brings in `Exec`: diff --git a/src/Nullean.Make/Target.cs b/src/Nullean.Make/Target.cs index a283a8c..636ee20 100644 --- a/src/Nullean.Make/Target.cs +++ b/src/Nullean.Make/Target.cs @@ -18,6 +18,24 @@ public interface ITargetBuilder /// Declares targets that must succeed before this target's body runs. Skipped under -s. ITargetBuilder DependsOn(params TargetRef[] refs); + /// + /// Runs after when they are in the same run, without adding them to it. A target named + /// without With matches it with any value; with With, only that value. + /// + ITargetBuilder After(params TargetRef[] refs); + + /// + /// Targets whose bodies run at the end of the run, newest first, once this target has started, even when the run + /// fails. A cleanup runs its body only, and once however many targets name it. + /// + ITargetBuilder Cleanup(params TargetRef[] refs); + + /// Environment variables that must be set. The run checks them before anything starts, and lists every one missing. + ITargetBuilder NeedsEnv(params string[] variables); + + /// Executables that must be on the PATH. The run checks them before anything starts, and lists every one missing. + ITargetBuilder NeedsTool(params string[] tools); + /// Executes the given action as this target's body. ITargetBuilder Executes(Action body); diff --git a/src/Nullean.Make/TargetOfT.cs b/src/Nullean.Make/TargetOfT.cs index 4775642..1d0c942 100644 --- a/src/Nullean.Make/TargetOfT.cs +++ b/src/Nullean.Make/TargetOfT.cs @@ -18,6 +18,18 @@ public interface ITargetBuilder : ITargetBuilder /// new ITargetBuilder DependsOn(params TargetRef[] refs); + /// + new ITargetBuilder After(params TargetRef[] refs); + + /// + new ITargetBuilder Cleanup(params TargetRef[] refs); + + /// + new ITargetBuilder NeedsEnv(params string[] variables); + + /// + new ITargetBuilder NeedsTool(params string[] tools); + /// Executes the given action with a bound instance of parsed from CLI tokens. ITargetBuilder Executes(Action body); diff --git a/src/Nullean.Make/UnionGraph/IUnionTargetBuilder.cs b/src/Nullean.Make/UnionGraph/IUnionTargetBuilder.cs index ed7b5e9..8ffaa7b 100644 --- a/src/Nullean.Make/UnionGraph/IUnionTargetBuilder.cs +++ b/src/Nullean.Make/UnionGraph/IUnionTargetBuilder.cs @@ -57,6 +57,32 @@ public interface IUnionTargetBuilder /// IUnionTargetBuilder Parallel(params TUnion[] targets); + /// + /// Skips the body when returns . The dependencies still run. + /// --graph evaluates it to show what it skips; a run evaluates it again just before the target would start. + /// + IUnionTargetBuilder OnlyWhen(Func condition); + + /// + /// Runs after when they are in the same run, without adding them to it: + /// .After(new Lint()) orders this target after lint only when something else runs lint. + /// A case with its default value matches the target with any value; with another value, only that value. + /// + IUnionTargetBuilder After(params TUnion[] targets); + + /// + /// Targets whose bodies run at the end of the run, newest first, once this target has started, even when the run + /// fails: StartDb => app.Target(...).Cleanup(new StopDb()). A cleanup runs its body only, and once + /// however many targets name it. + /// + IUnionTargetBuilder Cleanup(params TUnion[] targets); + + /// Environment variables that must be set. The run checks them before anything starts, and lists every one missing. + IUnionTargetBuilder NeedsEnv(params string[] variables); + + /// Executables that must be on the PATH. The run checks them before anything starts, and lists every one missing. + IUnionTargetBuilder NeedsTool(params string[] tools); + /// Registers a synchronous execution body. Closed-over case values are the real CLI-parsed ones at execution time. IUnionTargetBuilder Executes(Action body); diff --git a/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs b/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs index 46bfcb1..2b01336 100644 --- a/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs +++ b/src/Nullean.Make/UnionGraph/UnionTargetBuilderImpl.cs @@ -19,6 +19,11 @@ internal sealed class UnionTargetBuilderImpl : IUnionTargetBuilder? _asyncBody; private readonly TargetKind _kind; private readonly List<(Execution.StageKind Kind, bool Parallel, List Items)> _stages = new(); + private readonly List _after = new(); + private readonly List _cleanup = new(); + private readonly List _needsEnv = new(); + private readonly List _needsTool = new(); + private Func? _onlyWhen; internal UnionTargetBuilderImpl(TargetKind kind = TargetKind.Target) => _kind = kind; @@ -53,6 +58,36 @@ public IUnionTargetBuilder Executes(Func body) public IUnionTargetBuilder Requires(params TUnion[] gates) => DependsOn(gates); + public IUnionTargetBuilder OnlyWhen(Func condition) + { + _onlyWhen = condition; + return this; + } + + public IUnionTargetBuilder After(params TUnion[] targets) + { + _after.AddRange(targets.Select(ToRef)); + return this; + } + + public IUnionTargetBuilder Cleanup(params TUnion[] targets) + { + _cleanup.AddRange(targets.Select(ToRef)); + return this; + } + + public IUnionTargetBuilder NeedsEnv(params string[] variables) + { + _needsEnv.AddRange(variables); + return this; + } + + public IUnionTargetBuilder NeedsTool(params string[] tools) + { + _needsTool.AddRange(tools); + return this; + } + public IUnionTargetBuilder Parallel(params TUnion[] targets) { _stages.Add((Execution.StageKind.Composes, true, targets.Select(ToRef).ToList())); @@ -128,6 +163,11 @@ public IUnionTargetBuilder Composes() internal IReadOnlyList Deps => _stages.Where(s => s.Kind == Execution.StageKind.Requires).SelectMany(s => s.Items).ToList(); internal IReadOnlyList Comps => _stages.Where(s => s.Kind == Execution.StageKind.Composes).SelectMany(s => s.Items).ToList(); internal IReadOnlyList<(Execution.StageKind Kind, bool Parallel, List Items)> Stages => _stages; + internal IReadOnlyList AfterRefs => _after; + internal IReadOnlyList CleanupRefs => _cleanup; + internal IReadOnlyList Env => _needsEnv; + internal IReadOnlyList Tools => _needsTool; + internal Func? Condition => _onlyWhen; internal async Task ExecuteAsync(CancellationToken token) { diff --git a/src/Nullean.Make/UnionGraph/UnionTargetSource.cs b/src/Nullean.Make/UnionGraph/UnionTargetSource.cs index 0551d55..a65362f 100644 --- a/src/Nullean.Make/UnionGraph/UnionTargetSource.cs +++ b/src/Nullean.Make/UnionGraph/UnionTargetSource.cs @@ -27,6 +27,16 @@ public InstanceSpec Describe(TargetNode node, object? value) spec.Add(kind, items.Select(d => new DepRef(resolve(node, d.TypeName), d.Value)).ToList(), parallel); if (builder.SyncBody is not null || builder.AsyncBody is not null) spec.Body = builder.ExecuteAsync; + spec.OnlyWhen = builder.Condition; + // A case named with its default value in After matches the target with any value. + foreach (var d in builder.AfterRefs) + { + var target = resolve(node, d.TypeName); + spec.After.Add(new DepRef(target, Equals(d.Value, DefaultValue(target)) ? null : d.Value)); + } + spec.Cleanup.AddRange(builder.CleanupRefs.Select(d => new DepRef(resolve(node, d.TypeName), d.Value))); + spec.NeedsEnv.AddRange(builder.Env); + spec.NeedsTool.AddRange(builder.Tools); return spec; } diff --git a/tests/Nullean.Make.Fs.Tests/ModifierTests.fs b/tests/Nullean.Make.Fs.Tests/ModifierTests.fs new file mode 100644 index 0000000..1be56a2 --- /dev/null +++ b/tests/Nullean.Make.Fs.Tests/ModifierTests.fs @@ -0,0 +1,80 @@ +module Nullean.Make.Fs.Tests.ModifierTests + +open System +open System.IO +open TUnit.Core +open Nullean.Make.Fs + +type Modified = + | Lint + | Package + | Ci + | StartDb + | StopDb + | Integration + | Push + | Optional + +let private variable = "NULLEAN_MAKE_FS_TEST_PUSH_KEY" + +let private run (args: string list) = + let log = ResizeArray() + let app = MakeApp("build", None) + let skip = app.Flag("--skip-optional") + app.Bind <| function + | Lint -> target [] { log.Add "lint" } + | Package -> target [] { log.Add "package" } |> after [Lint] + | Ci -> command { concurrently [Package; Lint] } + | StartDb -> target [] { log.Add "start-db" } |> cleanup [StopDb] + | StopDb -> target [] { log.Add "stop-db" } + | Integration -> target [StartDb] { failBuild "integration failed" } + | Push -> target [] { log.Add "push" } |> needsEnv [variable] |> describe "Push the packages" + | Optional -> target [Lint] { log.Add "optional" } |> onlyWhen (fun () -> not skip.Value) + let stdout, stderr = new StringWriter(), new StringWriter() + let oldOut, oldErr = Console.Out, Console.Error + Console.SetOut stdout + Console.SetError stderr + try + let exit = app.RunAsync(List.toArray args).GetAwaiter().GetResult() + exit, List.ofSeq log, string stdout, string stderr + finally + Console.SetOut oldOut + Console.SetError oldErr + +[] +type ModifierTests() = + + [] + member _.``onlyWhen skips the body but not the dependencies``() = + let exit, log, _, _ = run ["optional"; "--skip-optional"] + Assert.Equal(0, exit) + Assert.Equal([ "lint" ], log) + + [] + member _.``after orders a target after one in the same run``() = + let _, log, _, _ = run ["ci"; "-j"; "4"] + Assert.Equal([ "lint"; "package" ], log) + + [] + member _.``after does not add the target to the run``() = + let _, log, _, _ = run ["package"] + Assert.Equal([ "package" ], log) + + [] + member _.``cleanup runs after a failure``() = + let exit, log, _, _ = run ["integration"] + Assert.Equal(1, exit) + Assert.Equal([ "start-db"; "stop-db" ], log) + + [] + member _.``needsEnv stops the run before anything starts``() = + Environment.SetEnvironmentVariable(variable, null) + let exit, log, _, stderr = run ["push"] + Assert.Equal(1, exit) + Assert.Equal([], log) + Assert.Contains(variable, stderr) + + [] + member _.``describe sets the description help shows``() = + let _, _, stdout, _ = run ["--help"] + Assert.Contains("Push the packages", stdout) diff --git a/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj b/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj index f10c5ae..dc8b44e 100644 --- a/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj +++ b/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj @@ -17,6 +17,7 @@ + diff --git a/tests/Nullean.Make.Tests/ModifierTests.cs b/tests/Nullean.Make.Tests/ModifierTests.cs new file mode 100644 index 0000000..0f66a26 --- /dev/null +++ b/tests/Nullean.Make.Tests/ModifierTests.cs @@ -0,0 +1,258 @@ +using AwesomeAssertions; + +namespace Nullean.Make.Tests; + +public record class Lint; + +public record class Package; + +public record class Ci; + +public record class StartDb; + +public record class StopDb; + +public record class Integration(bool Fail = false); + +public record class Push; + +public record class Optional; + +public record class Uses; + +public record class Loop1; + +public record class Loop2; + +public record class Loops; + +public union Modified(Lint, Package, Ci, StartDb, StopDb, Integration, Push, Optional, Uses, Loop1, Loop2, Loops); + +/// OnlyWhen, After, Cleanup, NeedsEnv and NeedsTool on a . +[NotInParallel] +public class ModifierTests +{ + internal const string Variable = "NULLEAN_MAKE_TEST_PUSH_KEY"; + + private sealed record Run(int ExitCode, IReadOnlyList Log, string Stdout, string Stderr); + + private static async Task RunAsync(params string[] args) + { + var log = new List(); + var app = new MakeApp("build"); + var skipOptional = app.Flag("--skip-optional"); + app.Bind( + m => + m.Value switch + { + Lint => app.Target(() => log.Add("lint")), + Package => app.Target(() => log.Add("package")).After(new Lint()), + // A parallel stage leaves the two unordered; After orders them. + Ci => app.Command().Parallel(new Package(), new Lint()), + StartDb => app.Target(() => log.Add("start-db")).Cleanup(new StopDb()), + StopDb => app.Target(() => log.Add("stop-db")), + Integration i => + app.Target([new StartDb()], () => + { + log.Add("integration"); + if (i.Fail) + throw new MakeException("integration failed", 4); + }), + Push => app.Target(() => log.Add("push")).NeedsEnv(Variable).NeedsTool("dotnet"), + Optional => app.Target([new Lint()], () => log.Add("optional")).OnlyWhen(() => !skipOptional.Value), + Uses => app.Target(() => log.Add("uses")).NeedsTool("nullean-make-no-such-tool").NeedsEnv(Variable), + Loop1 => app.Target(() => log.Add("loop1")).After(new Loop2()), + Loop2 => app.Target(() => log.Add("loop2")).After(new Loop1()), + Loops => app.Command([], [new Loop1(), new Loop2()]), + _ => throw new InvalidOperationException($"unmapped case {m.Value}") + } + ); + var (stdout, stderr) = (new StringWriter(), new StringWriter()); + var (oldOut, oldErr) = (Console.Out, Console.Error); + Console.SetOut(stdout); + Console.SetError(stderr); + try + { + var exit = await app.RunAsync(args); + return new Run(exit, log, stdout.ToString(), stderr.ToString()); + } + finally + { + Console.SetOut(oldOut); + Console.SetError(oldErr); + } + } + + [Test] + public async Task A_false_condition_skips_the_body_but_not_the_dependencies() + { + var run = await RunAsync("optional", "--skip-optional"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("lint"); + } + + [Test] + public async Task Graph_shows_what_a_condition_skips() + { + var run = await RunAsync("optional", "--skip-optional", "--graph"); + run.Stdout.Should().Contain("optional skipped: its condition is false"); + } + + [Test] + public async Task After_orders_a_target_after_one_in_the_same_run() + { + var run = await RunAsync("ci", "-j", "4"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("lint", "package"); + } + + [Test] + public async Task After_does_not_add_the_target_to_the_run() + { + var run = await RunAsync("package"); + run.Log.Should().Equal("package"); + } + + [Test] + public async Task After_that_forms_a_cycle_exits_1() + { + var run = await RunAsync("loops"); + run.ExitCode.Should().Be(1); + run.Stderr.Should().Contain("has a cycle"); + run.Log.Should().BeEmpty(); + } + + [Test] + public async Task A_cleanup_runs_at_the_end() + { + var run = await RunAsync("integration"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("start-db", "integration", "stop-db"); + } + + [Test] + public async Task A_cleanup_runs_after_a_failure_and_the_run_keeps_the_failures_exit_code() + { + var run = await RunAsync("integration", "--fail"); + run.ExitCode.Should().Be(4); + run.Log.Should().Equal("start-db", "integration", "stop-db"); + } + + [Test] + public async Task Graph_shows_the_cleanup() + { + var run = await RunAsync("integration", "--graph"); + run.Stdout.Should().Contain("cleanup, at the end").And.Contain("then cleanup: stop-db"); + } + + [Test] + public async Task A_missing_environment_variable_stops_the_run_before_anything_starts() + { + Environment.SetEnvironmentVariable(Variable, null); + var run = await RunAsync("push"); + run.ExitCode.Should().Be(1); + run.Log.Should().BeEmpty(); + run.Stderr.Should().Contain($"the environment variable {Variable}, for push"); + } + + [Test] + public async Task A_set_environment_variable_and_a_tool_on_the_path_let_the_run_start() + { + Environment.SetEnvironmentVariable(Variable, "set"); + try + { + var run = await RunAsync("push"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("push"); + } + finally + { + Environment.SetEnvironmentVariable(Variable, null); + } + } + + [Test] + public async Task Every_missing_precondition_is_listed() + { + Environment.SetEnvironmentVariable(Variable, null); + var run = await RunAsync("uses"); + run.ExitCode.Should().Be(1); + run.Stderr.Should().Contain("nullean-make-no-such-tool on the PATH, for uses").And.Contain($"the environment variable {Variable}, for uses"); + } + + [Test] + public async Task Graph_lists_what_is_missing_and_runs_nothing() + { + Environment.SetEnvironmentVariable(Variable, null); + var run = await RunAsync("uses", "--graph"); + run.ExitCode.Should().Be(0); + run.Stdout.Should().Contain("Missing: nullean-make-no-such-tool on the PATH, for uses"); + } +} + +public class ModifiedBuild : MakeBuild +{ + public static List Log { get; } = new(); + + public Target Lint => _ => _.Executes(() => Log.Add("lint")); + + public Target Package => _ => _.After(Lint).Executes(() => Log.Add("package")); + + public Command Ci => _ => _.Parallel(Package, Lint); + + public Target StopDb => _ => _.Executes(() => Log.Add("stop-db")); + + public Target StartDb => _ => _.Cleanup(StopDb).Executes(() => Log.Add("start-db")); + + public Target Integration => _ => _.DependsOn(StartDb).Executes(() => throw new MakeException("integration failed", 4)); + + public Target Push => _ => _.NeedsEnv(ModifierTests.Variable).Executes(() => Log.Add("push")); +} + +[NotInParallel] +public class ClassModifierTests +{ + private static async Task<(int Exit, List Log, string Stderr)> RunAsync(params string[] args) + { + ModifiedBuild.Log.Clear(); + var stderr = new StringWriter(); + var (oldOut, oldErr) = (Console.Out, Console.Error); + Console.SetOut(new StringWriter()); + Console.SetError(stderr); + try + { + return (await MakeApp.Execute(args), [.. ModifiedBuild.Log], stderr.ToString()); + } + finally + { + Console.SetOut(oldOut); + Console.SetError(oldErr); + } + } + + [Test] + public async Task After_orders_a_target_after_one_in_the_same_run() + { + var (exit, log, _) = await RunAsync("ci"); + exit.Should().Be(0); + log.Should().Equal("lint", "package"); + } + + [Test] + public async Task A_cleanup_runs_after_a_failure() + { + var (exit, log, _) = await RunAsync("integration"); + exit.Should().Be(4); + log.Should().Equal("start-db", "stop-db"); + } + + [Test] + public async Task A_missing_environment_variable_stops_the_run() + { + Environment.SetEnvironmentVariable(ModifierTests.Variable, null); + var (exit, log, stderr) = await RunAsync("push"); + exit.Should().Be(1); + log.Should().BeEmpty(); + stderr.Should().Contain(ModifierTests.Variable); + } +}