diff --git a/docs/_docset.yml b/docs/_docset.yml index 7fc58a5..f5084fb 100644 --- a/docs/_docset.yml +++ b/docs/_docset.yml @@ -49,6 +49,7 @@ toc: - folder: make children: - file: index.md + - file: running.md - file: graph.md - file: parallel.md - file: modifiers.md diff --git a/docs/make/index.md b/docs/make/index.md index ae9a94f..f48e7bf 100644 --- a/docs/make/index.md +++ b/docs/make/index.md @@ -8,8 +8,12 @@ ./build.cs test --filter Unit ./build.cs release -s # skip the gates, run only the composed targets ./build.cs release --graph # draw the plan and run nothing +./build.cs lint test pack # several targets, in order, shared dependencies once +./build.cs release --skip docs ``` +[**Choosing what runs**](running.md) - Several targets on one command line, `-s` and `--skip`. + [**Running targets side by side**](parallel.md) - Parallel stages, `-j`, `--keep-going`, and the output of targets that run at once. diff --git a/docs/make/running.md b/docs/make/running.md new file mode 100644 index 0000000..8d98e41 --- /dev/null +++ b/docs/make/running.md @@ -0,0 +1,32 @@ +# Choosing what runs + +## Several targets + +A command line can name several targets. They run in the order they are named, and a dependency they share runs once: + +```bash +./build.cs lint test --filter Unit pack +``` + +Each target takes the arguments up to the next target's name: `test` gets `--filter Unit`. A word stays with the +target before it when it is the value of an option, as in `test --filter pack`, or when that target takes positional +arguments. Everything after `--` stays with the target before it. + +The `make` wrapper starts the script once per target: `make test pack` runs it twice. + +## Leaving targets out + +`-s` / `--single-target` skips the gates of the named target: its dependencies, or a command's requires. + +`--skip ` leaves one target out of the plan, wherever it appears, with the dependencies that only it needed: + +```bash +./build.cs release --skip docs +./build.cs release --skip "pkg validate",docs # several, separated by commas +./build.cs release --skip pkg/validate # pkg/validate and pkg:validate work too +``` + +`--skip` takes a target's name, not a value, so it leaves the target out whatever value it would run with. It exits +`2` for a name that is not a target, with a suggestion, and for a target the command line names itself. + +`--graph` shows what both leave out: `skipped: -s` and `skipped: --skip`. diff --git a/src/Nullean.Make.Fs/MakeApp.fs b/src/Nullean.Make.Fs/MakeApp.fs index 515c312..4829e4a 100644 --- a/src/Nullean.Make.Fs/MakeApp.fs +++ b/src/Nullean.Make.Fs/MakeApp.fs @@ -215,11 +215,17 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> | false, _ -> eprintfn "Unknown target '%s'." routeKey return 2 - | true, node when isNull node.DtoType && targetArgs.Length > 0 -> - let first = if targetArgs.[0] = "--" && targetArgs.Length > 1 then targetArgs.[1] else targetArgs.[0] - eprintfn "Unexpected argument '%s'. Target '%s' takes no arguments." first routeKey - return 2 | true, node -> + // Each target named on the command line gets the tokens up to the next one; one without a record takes none. + let unexpected = + Invocation.Split(node, targetArgs, graph) + |> Seq.tryFind (fun struct (n, args) -> isNull n.DtoType && args.Length > 0) + match unexpected with + | Some (struct (n, args)) -> + let first = if args.[0] = "--" && args.Length > 1 then args.[1] else args.[0] + eprintfn "Unexpected argument '%s'. Target '%s' takes no arguments." first (String.concat "/" n.Route) + return 2 + | None -> switches.Target <- node switches.TargetArgs <- targetArgs switches.SingleTarget <- singleTarget diff --git a/src/Nullean.Make.Fs/README.md b/src/Nullean.Make.Fs/README.md index 9fda02e..488a4d5 100644 --- a/src/Nullean.Make.Fs/README.md +++ b/src/Nullean.Make.Fs/README.md @@ -208,6 +208,15 @@ let token = app.Option("--token", desc = "API token", defaultVa Read them in target blocks through `.Value`. Help shows each option's type, such as `--config `, and `--token ` for an option type. Both `--token abc` and `--token=abc` work. A value that does not parse, or a missing value, exits `2` before any target runs. Enum options bind by name, ignoring case. +## Choosing what runs + +``` +build lint test --filter Unit pack # several targets in order; each takes the arguments up to the next +build release --skip docs # leave a target out, with what only it needed +``` + +See [Choosing what runs](https://argh.nullean.net/make/running). + ## Drawing the plan `--graph` draws what a run would do and runs nothing. It binds the target's arguments, applies `-s` and evaluates 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 41f2c49..721a25a 100644 --- a/src/Nullean.Make.Fs/skills/nullean-make-fs/SKILL.md +++ b/src/Nullean.Make.Fs/skills/nullean-make-fs/SKILL.md @@ -71,6 +71,15 @@ let main argv = `executes (shell { ... })` adds a body that runs last. - A record payload is the target's flags (`Test of TestOptions` takes `--filter`). A DU payload is a namespace (`Pkg of PkgTarget` gives `pkg generate`). +- 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. +- 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. + `build lint test pack` runs several targets; `--skip docs` leaves one out. - Global options: `app.Flag("--verbose", short = "-v", desc = "...")`, `app.Option<'T>(...)`, read with `.Value` inside a block. - ` __wrappers sync --run "dotnet run --project build --"` writes mise, make and just includes with one task per @@ -80,8 +89,8 @@ let main argv = ## Gotchas - Descriptions are the `///` comments on the cases, read from the XML documentation file: the project needs - `true`. A `.fsx` script has none; use - `Make.target deps "description" body` there. + `true`. A `.fsx` script has none; pipe the target through + `describe "..."` there. - `sh $"..."` splits only the literal text; each `{value}` stays one argument. Do not build a command string with `sprintf` and pass it in as one value: it becomes a single argument. Use an `if`, or a list spliced as `{args}`. - Code in the `match` arm outside the block runs when the graph is read, for every case. Put the work inside diff --git a/src/Nullean.Make/Execution/DepGraphExecutor.cs b/src/Nullean.Make/Execution/DepGraphExecutor.cs index 1716858..72c7753 100644 --- a/src/Nullean.Make/Execution/DepGraphExecutor.cs +++ b/src/Nullean.Make/Execution/DepGraphExecutor.cs @@ -15,8 +15,12 @@ public static async Task ExecuteAsync(TargetNode root, ParsedArgs parsed, B RunPlan plan; try { - var value = source.BindArguments(root, parsed.TargetArgs); - plan = RunPlan.Build([new DepRef(root, value)], source, new PlanOptions(parsed.SingleTarget, EvaluateConditions: parsed.Graph is not null)); + // `build lint test --filter Unit pack` names three targets; each binds its own arguments. + var targets = Invocation.Split(root, parsed.TargetArgs, graph); + parsed.TargetArgs = targets[0].Args; + var roots = targets.Select(t => new DepRef(t.Node, source.BindArguments(t.Node, t.Args))).ToList(); + var skip = Invocation.ResolveSkips(parsed.Skip, graph); + plan = RunPlan.Build(roots, source, new PlanOptions(parsed.SingleTarget, EvaluateConditions: parsed.Graph is not null, Skip: skip)); } catch (MakeException ex) { @@ -39,6 +43,7 @@ public static int DrawWholeGraph(BuildGraph graph, GraphFormat format) try { var plan = PlanRenderer.WholeGraph(graph, source, new PlanOptions(SingleTarget: false, EvaluateConditions: true)); + // --skip is ignored here: the whole graph shows every target. PlanRenderer.Write(plan, format, Console.Out); return 0; } diff --git a/src/Nullean.Make/Execution/Invocation.cs b/src/Nullean.Make/Execution/Invocation.cs new file mode 100644 index 0000000..e7302a7 --- /dev/null +++ b/src/Nullean.Make/Execution/Invocation.cs @@ -0,0 +1,108 @@ +using Nullean.Argh.Matching; +using Nullean.Make.Discovery; + +namespace Nullean.Make.Execution; + +/// Splits a command line that names several targets, such as build lint test --filter Unit pack. +internal static class Invocation +{ + /// + /// Splits the tokens after the first target's route into that target's arguments and the targets after it. A token + /// starts the next target when it names one, is not the value of the option before it, and the current target takes + /// no positional arguments. Everything after -- stays with the current target. + /// + public static List<(TargetNode Node, string[] Args)> Split(TargetNode first, string[] args, BuildGraph graph) + { + var result = new List<(TargetNode Node, string[] Args)>(); + var node = first; + var current = new List(); + var options = Options(node); + for (var i = 0; i < args.Length; i++) + { + var token = args[i]; + if (token == "--") + { + current.AddRange(args[i..]); + break; + } + if (token.StartsWith('-')) + { + current.Add(token); + // The value of an option that takes one stays with it, even when it names a target. + if (!token.Contains('=') && options.TakesValue(token) && i + 1 < args.Length) + current.Add(args[++i]); + continue; + } + if (!options.TakesPositionals && MatchRoute(args, i, graph) is { } next) + { + result.Add((node, [.. current])); + node = next.Node; + options = Options(node); + current = new List(); + i += next.Consumed - 1; + continue; + } + current.Add(token); + } + result.Add((node, [.. current])); + return result; + } + + /// The longest route starting at args[start], such as pkg generate, and how many tokens it took. + private static (TargetNode Node, int Consumed)? MatchRoute(string[] args, int start, BuildGraph graph) + { + (TargetNode, int)? best = null; + var segments = new List(); + for (var i = start; i < args.Length && !args[i].StartsWith('-'); i++) + { + segments.Add(args[i].ToLowerInvariant()); + var key = string.Join("/", segments); + if (graph.ByRoute.TryGetValue(key, out var node)) + best = (node, segments.Count); + else if (!graph.ByRoute.Keys.Any(k => k.StartsWith(key + "/", StringComparison.OrdinalIgnoreCase))) + break; + } + return best; + } + + private sealed record TargetOptions(HashSet ValueOptions, bool TakesPositionals) + { + public bool TakesValue(string token) => ValueOptions.Contains(token.TrimStart('-')); + } + + private static TargetOptions Options(TargetNode node) + { + if (node.DtoType is null) + return new TargetOptions(new HashSet(StringComparer.OrdinalIgnoreCase), false); + var described = DtoOptions.Describe(node.DtoType); + return new TargetOptions( + described + .Where(o => !o.IsPositional && !o.IsRest && !o.IsSwitch && !IsFSharpBoolOption(o.Type)) + .Select(o => o.Name) + .ToHashSet(StringComparer.OrdinalIgnoreCase), + described.Any(o => o.IsPositional) + ); + } + + private static bool IsFSharpBoolOption(Type type) => + type.IsGenericType && type.GetGenericTypeDefinition().Name == "FSharpOption`1" && type.GetGenericArguments()[0] == typeof(bool); + + /// Resolves the targets of --skip, given as pkg generate, pkg/generate or pkg:generate. + public static HashSet ResolveSkips(IEnumerable names, BuildGraph graph) + { + var skipped = new HashSet(); + foreach (var name in names) + { + var key = string.Join("/", name.Split([' ', '/', ':'], StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant(); + if (graph.ByRoute.TryGetValue(key, out var node)) + { + skipped.Add(node); + continue; + } + var suggestions = FuzzyMatch.FindClosest(key, graph.ByRoute.Keys.Select(k => k.Replace('/', ' ')), 3); + var hint = suggestions.Count > 0 ? $" Did you mean '{suggestions[0]}'?" : ""; + throw new MakeException($"Unknown target '{name}' for '--skip'.{hint}", 2); + } + return skipped; + } +} diff --git a/src/Nullean.Make/Execution/PlanRenderer.cs b/src/Nullean.Make/Execution/PlanRenderer.cs index 74398a9..9c7aa15 100644 --- a/src/Nullean.Make/Execution/PlanRenderer.cs +++ b/src/Nullean.Make/Execution/PlanRenderer.cs @@ -197,6 +197,7 @@ private static void WriteChildren(List children, string indent, TextWriter { SkipReason.SingleTarget => Dim(" skipped: -s"), SkipReason.Condition => Dim(" skipped: its condition is false"), + SkipReason.Excluded => Dim(" skipped: --skip"), _ => "" }; @@ -313,6 +314,9 @@ private static void WriteSkipped(Utf8JsonWriter json, SkipReason? reason) case SkipReason.Condition: json.WriteString("skipped", "condition"); break; + case SkipReason.Excluded: + json.WriteString("skipped", "excluded"); + break; default: json.WriteNull("skipped"); break; diff --git a/src/Nullean.Make/Execution/RunPlan.cs b/src/Nullean.Make/Execution/RunPlan.cs index 6c17496..5988a70 100644 --- a/src/Nullean.Make/Execution/RunPlan.cs +++ b/src/Nullean.Make/Execution/RunPlan.cs @@ -9,7 +9,10 @@ internal enum SkipReason SingleTarget, /// Its condition returned , so its body does not run. - Condition + Condition, + + /// --skip left it out of the plan. + Excluded } /// One target with one value in a run: it runs once, however many targets depend on it. @@ -48,7 +51,8 @@ internal sealed record PlannedItem(TargetInstance? Instance, string Name, SkipRe /// Skip the named targets' gates, as -s does. /// Evaluate each condition while planning, so a drawn plan shows what it skips. /// Run the named targets in order, each after the one before it. -internal sealed record PlanOptions(bool SingleTarget, bool EvaluateConditions = false, bool ChainRoots = true); +/// Targets --skip leaves out, whatever their value, with the dependencies only they needed. +internal sealed record PlanOptions(bool SingleTarget, bool EvaluateConditions = false, bool ChainRoots = true, IReadOnlySet? Skip = null); /// The instances a run contains, in an order that respects every prerequisite. internal sealed class RunPlan @@ -101,6 +105,8 @@ public static RunPlan Build(IReadOnlyList roots, ITargetSource source, P TargetInstance? previous = null; foreach (var root in roots) { + if (options.Skip?.Contains(root.Node) == true) + throw new MakeException($"'--skip' names '{string.Join(" ", root.Node.Route)}', which the command line runs.", 2); var instance = builder.Visit(root, isRoot: true, previous is null || !options.ChainRoots ? [] : [previous]); instance.IsRoot = true; rootInstances.Add(instance); @@ -245,6 +251,11 @@ public TargetInstance Visit(DepRef reference, bool isRoot, IReadOnlyList wait = stage.Parallel || previous is null ? barrier : [.. barrier, previous]; var child = Visit(item, isRoot: false, wait); items.Add(new PlannedItem(child, child.Name, null)); diff --git a/src/Nullean.Make/Execution/RunSwitches.cs b/src/Nullean.Make/Execution/RunSwitches.cs index 0f2a952..6222795 100644 --- a/src/Nullean.Make/Execution/RunSwitches.cs +++ b/src/Nullean.Make/Execution/RunSwitches.cs @@ -30,6 +30,9 @@ public static bool TryRead(IReadOnlyList args, ref int i, ParsedArgs par case "-j" or "--jobs": parsed.Jobs = ParseJobs(Value(args, ref i, name)); return true; + case "--skip": + parsed.Skip.AddRange(Value(args, ref i, name).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + return true; case "-k" or "--keep-going": parsed.KeepGoing = true; i++; diff --git a/src/Nullean.Make/Help/MakeHelpPrinter.cs b/src/Nullean.Make/Help/MakeHelpPrinter.cs index 75f8bcf..0deea5f 100644 --- a/src/Nullean.Make/Help/MakeHelpPrinter.cs +++ b/src/Nullean.Make/Help/MakeHelpPrinter.cs @@ -22,7 +22,7 @@ public static void PrintRoot(BuildGraph graph, string scriptName) var nsNames = nsTargets.Select(t => t.Route[0]).Distinct().OrderBy(x => x).ToList(); Console.WriteLine($" {CliHelpFormatting.Section("Usage:")}"); - Console.WriteLine($" {scriptName} [options]"); + Console.WriteLine($" {scriptName} [options] [ [options]...]"); if (nsNames.Count > 0) Console.WriteLine($" {scriptName} [options]"); if (graph.Default is { } defaultTarget) @@ -276,6 +276,7 @@ private static void PrintGlobalOptions(BuildGraph graph, string scriptName) $" {CliHelpFormatting.Placeholder($"{Short("k")}--keep-going"),-30} After a failure, finish the targets that do not depend on it" ); Console.WriteLine($" {CliHelpFormatting.Placeholder(" --output "),-30} Output of targets running side by side: prefixed or grouped"); + Console.WriteLine($" {CliHelpFormatting.Placeholder(" --skip "),-30} Leave a target out of the plan, with what only it needed"); foreach (var opt in graph.GlobalOptions) { diff --git a/src/Nullean.Make/Parsing/ArgvParser.cs b/src/Nullean.Make/Parsing/ArgvParser.cs index 4aed2c5..940482a 100644 --- a/src/Nullean.Make/Parsing/ArgvParser.cs +++ b/src/Nullean.Make/Parsing/ArgvParser.cs @@ -24,6 +24,9 @@ internal sealed class ParsedArgs /// --output: how the output of targets that run side by side reaches the console. public Execution.OutputMode? Output { get; set; } + + /// --skip: targets the plan leaves out, with the dependencies only they needed. + public List Skip { get; } = new(); public string? HelpTarget { get; set; } } diff --git a/src/Nullean.Make/README.md b/src/Nullean.Make/README.md index 75d3b1b..b57278d 100644 --- a/src/Nullean.Make/README.md +++ b/src/Nullean.Make/README.md @@ -141,6 +141,15 @@ A target's description is the summary of its case type's XML doc comment, such a A case that is itself a union becomes a namespace: `union Db(Migrate, Seed)` inside `union Target(..., Db)` gives `db migrate` and `db seed`, and `db --help` lists them. Case type names must be unique across the whole union, including nested unions. +## Choosing what runs + +``` +build lint test --filter Unit pack # several targets in order; each takes the arguments up to the next +build release --skip docs # leave a target out, with what only it needed +``` + +See [Choosing what runs](https://argh.nullean.net/make/running). + ## Drawing the plan `--graph` draws what a run would do and runs nothing. It binds the target's arguments, applies `-s` and evaluates diff --git a/src/Nullean.Make/skills/nullean-make/SKILL.md b/src/Nullean.Make/skills/nullean-make/SKILL.md index fa39f46..89d1c7f 100644 --- a/src/Nullean.Make/skills/nullean-make/SKILL.md +++ b/src/Nullean.Make/skills/nullean-make/SKILL.md @@ -62,6 +62,16 @@ union Target(Clean, Build, Test, Pkg, Release); - `app.Target(deps, body)`: dependencies run first, once each. `app.Command(requires, composes)` sequences other targets: `requires` are gates, `composes` the work, in order; an optional third argument runs last. - A case record's constructor parameters are that target's flags: `Test(string? Filter = null)` takes `--filter`. +- A dependency can name a value, `app.Target([new Test("Unit")], ...)`: the target runs with it. Equal values run + once, different values once each. Only the named target binds the command line. +- `app.Command().Requires(new Test()).Parallel(new PackNuget(), new Docs()).Composes(new Publish())` runs a stage + side by side; stages run in declared order. `-j N` caps targets at once, `-k` keeps going after a failure, and an + async body can take the cancellation token: `app.Target(async ct => ...)`. +- On a target builder: `.OnlyWhen(() => ...)` skips the body, `.After(new Lint())` orders it after `lint` when both + run, `.Cleanup(new StopDb())` runs at the end even after a failure, `.NeedsEnv("KEY")` / `.NeedsTool("docker")` are + checked before anything starts. +- `./build.cs release --graph` (or `--graph mermaid|json`) draws the plan, skipped targets included, and runs + nothing. `./build.cs lint test pack` runs several targets; `--skip docs` leaves one out. - A nested union is a namespace: `Pkg` gives `pkg generate` and `pkg validate`. Match it with `Pkg { Value: Generate }` and create it with `new Pkg(new Generate())`. - A non-zero exit code from `Exec` fails the target, and `RunAsync` returns `1`. A bad or missing option value diff --git a/tests/Nullean.Make.Fs.Tests/InvocationTests.fs b/tests/Nullean.Make.Fs.Tests/InvocationTests.fs new file mode 100644 index 0000000..451b4b8 --- /dev/null +++ b/tests/Nullean.Make.Fs.Tests/InvocationTests.fs @@ -0,0 +1,56 @@ +module Nullean.Make.Fs.Tests.InvocationTests + +open System +open System.IO +open TUnit.Core +open Nullean.Make.Fs + +type VerifyOptions = { Suite: string option } + +type Called = + | Restore + | Verify of VerifyOptions + | Bundle + | Shipit + +let private run (args: string list) = + let log = ResizeArray() + let app = MakeApp("build", None) + app.Bind <| function + | Restore -> target [] { log.Add "restore" } + | Verify o -> target [Restore] { log.Add $"verify:%A{o.Suite}" } + | Bundle -> target [Restore] { log.Add "bundle" } + | Shipit -> command { + requires [Verify { Suite = None }] + composes [Bundle] } + let stderr = new StringWriter() + let oldOut, oldErr = Console.Out, Console.Error + Console.SetOut(new StringWriter()) + Console.SetError stderr + try + let exit = app.RunAsync(List.toArray args).GetAwaiter().GetResult() + exit, List.ofSeq log, string stderr + finally + Console.SetOut oldOut + Console.SetError oldErr + +[] +type InvocationTests() = + + [] + member _.``Several targets run in order and share their dependencies``() = + let exit, log, _ = run ["bundle"; "verify"; "--suite"; "unit"] + Assert.Equal(0, exit) + Assert.Equal([ "restore"; "bundle"; "verify:Some \"unit\"" ], log) + + [] + member _.``A target without a record still rejects a word that is not a target``() = + let exit, _, stderr = run ["bundle"; "nope"] + Assert.Equal(2, exit) + Assert.Contains("Unexpected argument 'nope'. Target 'bundle' takes no arguments.", stderr) + + [] + member _.``Skip leaves a target out of the plan``() = + let exit, log, _ = run ["shipit"; "--skip"; "verify"] + Assert.Equal(0, exit) + Assert.Equal([ "restore"; "bundle" ], log) 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 dc8b44e..df91327 100644 --- a/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj +++ b/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj @@ -18,6 +18,7 @@ + diff --git a/tests/Nullean.Make.Tests/InvocationTests.cs b/tests/Nullean.Make.Tests/InvocationTests.cs new file mode 100644 index 0000000..6bc783b --- /dev/null +++ b/tests/Nullean.Make.Tests/InvocationTests.cs @@ -0,0 +1,123 @@ +using AwesomeAssertions; +using Nullean.Argh; + +namespace Nullean.Make.Tests; + +public record class Restore; + +public record class Assemble; + +public record class Verify(string Suite = "all", bool Quick = false); + +public record class Bundle; + +public record class Format([Argument] string Path = "."); + +public record class Shipit; + +public record class Sweep; + +public union Called(Restore, Assemble, Verify, Bundle, Format, Shipit, Sweep); + +/// Several targets on one command line, and --skip. +[NotInParallel] +public class InvocationTests +{ + 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"); + app.Bind( + c => + c.Value switch + { + Restore => app.Target(() => log.Add("restore")), + Assemble => app.Target([new Restore()], () => log.Add("assemble")), + Verify v => app.Target([new Assemble()], () => log.Add($"verify:{v.Suite}:{v.Quick}")), + Bundle => app.Target([new Assemble()], () => log.Add("bundle")), + Format f => app.Target(() => log.Add($"format:{f.Path}")), + Shipit => app.Command([new Verify()], [new Bundle()]), + Sweep => app.Target(() => log.Add("sweep")), + _ => throw new InvalidOperationException($"unmapped case {c.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 Several_targets_run_in_order_and_share_their_dependencies() + { + var run = await RunAsync("sweep", "verify", "bundle"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("sweep", "restore", "assemble", "verify:all:False", "bundle"); + } + + [Test] + public async Task Each_target_binds_the_arguments_up_to_the_next_one() + { + var run = await RunAsync("verify", "--suite", "unit", "--quick", "bundle"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("restore", "assemble", "verify:unit:True", "bundle"); + } + + [Test] + public async Task An_option_value_that_names_a_target_stays_with_the_option() + { + var run = await RunAsync("verify", "--suite", "bundle"); + run.Log.Should().Equal("restore", "assemble", "verify:bundle:False"); + } + + [Test] + public async Task A_target_with_positional_arguments_takes_the_words_after_it() + { + var run = await RunAsync("format", "sweep"); + run.Log.Should().Equal("format:sweep"); + } + + [Test] + public async Task Skip_leaves_a_target_and_what_only_it_needed_out_of_the_plan() + { + var run = await RunAsync("shipit", "--skip", "verify"); + run.ExitCode.Should().Be(0); + run.Log.Should().Equal("restore", "assemble", "bundle"); + } + + [Test] + public async Task Graph_shows_what_skip_leaves_out() + { + var run = await RunAsync("shipit", "--skip=verify", "--graph"); + run.Stdout.Should().Contain("verify skipped: --skip"); + } + + [Test] + public async Task Skip_of_an_unknown_target_exits_2_with_a_suggestion() + { + var run = await RunAsync("shipit", "--skip", "verfy"); + run.ExitCode.Should().Be(2); + run.Stderr.Should().Contain("Unknown target 'verfy' for '--skip'. Did you mean 'verify'?"); + run.Log.Should().BeEmpty(); + } + + [Test] + public async Task Skip_of_a_target_the_command_line_runs_exits_2() + { + var run = await RunAsync("shipit", "--skip", "shipit"); + run.ExitCode.Should().Be(2); + run.Log.Should().BeEmpty(); + } +}