diff --git a/docs/_docset.yml b/docs/_docset.yml index 6c37f89..393d2a0 100644 --- a/docs/_docset.yml +++ b/docs/_docset.yml @@ -49,6 +49,7 @@ toc: - folder: make children: - file: index.md + - file: graph.md - file: wrappers.md - file: mise.md - file: makefile.md diff --git a/docs/make/graph.md b/docs/make/graph.md new file mode 100644 index 0000000..7207a9b --- /dev/null +++ b/docs/make/graph.md @@ -0,0 +1,76 @@ +# Drawing the plan + +`--graph` draws what a run would do, and runs nothing. It plans the run exactly as the target would: it binds the +target's arguments, applies `-s`, and evaluates each `OnlyWhen` condition. A target the run would skip shows as skipped, +with the reason. + +```bash +./build.cs release --graph +``` + +```text +release Test, then pack +├─ requires +│ ├─ pristine-check +│ └─ test +│ └─ build +│ └─ clean +└─ composes + ├─ pkg generate + └─ pkg validate + +Runs: pristine-check → clean → build → test → pkg generate → pkg validate +``` + +`Runs:` lists the targets whose bodies run, in order. A target that two others depend on runs once; the tree draws it +the first time and marks later references `(above)`. + +## Skipped targets + +With `-s`, the named target's gates show as skipped and their own dependencies drop out of the plan: + +```bash +./build.cs release -s --graph +``` + +```text +release Test, then pack +├─ requires +│ ├─ pristine-check skipped: -s +│ └─ test skipped: -s +└─ composes + ├─ pkg generate + └─ pkg validate + +Runs: pkg generate → pkg validate +``` + +A target whose condition is false shows `skipped: its condition is false`. Its dependencies still run, as they do in a +real run. `--graph` evaluates the condition when it draws the plan; a real run evaluates it again just before the +target would start. + +## Dependencies with values + +A dependency that names a value runs with that value, and the plan shows it after the route: + +```text +ci +└─ composes + ├─ test (filter: Unit) + └─ test (filter: Integration) +``` + +Two references with equal values are one target in the plan, and run once. Two references with different values run +once each. Only the target named on the command line binds the command line's arguments. + +## Formats + +| Command | Prints | +|---|---| +| `--graph` or `--graph tree` | The tree and the `Runs:` line | +| `--graph mermaid` | A Mermaid flowchart, with one edge per ordering and skipped targets dashed | +| `--graph json` | The plan as JSON: `roots`, then `targets` in run order with their stages and what each waits for | + +`--graph=mermaid` works too. `--graph` without a target draws every target that nothing else depends on. + +A target's `--help` lists the same order under `Runs:` when the target has dependencies. diff --git a/docs/make/index.md b/docs/make/index.md index db32c53..472372e 100644 --- a/docs/make/index.md +++ b/docs/make/index.md @@ -7,8 +7,11 @@ ./build.cs --help ./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 ``` +[**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 [just](just.md), and let mise hooks keep them up to date. diff --git a/src/Nullean.Make.Fs/MakeApp.fs b/src/Nullean.Make.Fs/MakeApp.fs index 04fec80..8659dd3 100644 --- a/src/Nullean.Make.Fs/MakeApp.fs +++ b/src/Nullean.Make.Fs/MakeApp.fs @@ -41,10 +41,13 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> let mutable singleTarget = false let mutable showHelp = false let mutable showVersion = false + let mutable graph : GraphFormat option = None let mutable i = 0 while i < argv.Length do let arg = argv.[i] - if arg = "-h" || arg = "--help" then showHelp <- true; i <- i + 1 + let graphFormat = GraphOption.TryRead(argv, &i) + if graphFormat.HasValue then graph <- Some graphFormat.Value + elif arg = "-h" || arg = "--help" then showHelp <- true; i <- i + 1 elif arg = "--version" then showVersion <- true; i <- i + 1 elif arg = "-s" || arg = "--single-target" then singleTarget <- true; i <- i + 1 else @@ -72,7 +75,7 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> opt.Set argv.[i] i <- i + 1 | None -> remaining.Add(arg); i <- i + 1 - remaining.ToArray(), singleTarget, showHelp, showVersion + remaining.ToArray(), singleTarget, showHelp, showVersion, graph let resolveRoute (remaining: string[]) (byRoute: Collections.Generic.Dictionary) = let routeTokens = Collections.Generic.List() @@ -161,7 +164,7 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> | Error (code, msg) -> eprintfn "%s" msg return code - | Ok (remaining, singleTarget, showHelp, showVersion) -> + | Ok (remaining, singleTarget, showHelp, showVersion, graphFormat) -> if showVersion then printfn "%s" (entryVersion ()) @@ -196,6 +199,8 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> | Some t -> eprintfn "Unknown target '%s'." t return 2 + | None when graphFormat.IsSome -> + return DepGraphExecutor.DrawWholeGraph(graph, graphFormat.Value) | None -> MakeHelpPrinter.PrintRoot(graph, appName) return 0 @@ -214,6 +219,7 @@ type MakeApp<'TCase when 'TCase : comparison and 'TCase : not null> ParsedArgs( Target = node, TargetArgs = targetArgs, - SingleTarget = singleTarget) + SingleTarget = singleTarget, + Graph = Option.toNullable graphFormat) return! DepGraphExecutor.ExecuteAsync(node, parsed, graph) } diff --git a/src/Nullean.Make.Fs/README.md b/src/Nullean.Make.Fs/README.md index 7547d56..5e5bac8 100644 --- a/src/Nullean.Make.Fs/README.md +++ b/src/Nullean.Make.Fs/README.md @@ -178,6 +178,19 @@ 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. +## Drawing the plan + +`--graph` draws what a run would do and runs nothing. It binds the target's arguments, applies `-s` and evaluates +conditions, so a skipped target shows as skipped: + +``` +build release -s --graph +build release --graph mermaid # or json +``` + +A target's `--help` lists the order its dependencies run in under `Runs:`. See +[Drawing the plan](https://argh.nullean.net/make/graph). + ## mise, make and just `__wrappers sync` writes a mise task include, a Makefile include and a justfile import with one task per target, so diff --git a/src/Nullean.Make/Execution/DepGraphExecutor.cs b/src/Nullean.Make/Execution/DepGraphExecutor.cs index bb2ca0b..8bd4f82 100644 --- a/src/Nullean.Make/Execution/DepGraphExecutor.cs +++ b/src/Nullean.Make/Execution/DepGraphExecutor.cs @@ -5,7 +5,10 @@ namespace Nullean.Make.Execution; internal static class DepGraphExecutor { - /// Binds the named target's arguments, plans the run and executes it. + /// + /// Binds the named target's arguments, plans the run and executes it. With --graph, draws the plan instead + /// and runs nothing. + /// public static async Task ExecuteAsync(TargetNode root, ParsedArgs parsed, BuildGraph graph) { var source = graph.Source ?? throw new InvalidOperationException("The graph has no target source."); @@ -13,16 +16,39 @@ public static async Task ExecuteAsync(TargetNode root, ParsedArgs parsed, B try { var value = source.BindArguments(root, parsed.TargetArgs); - plan = RunPlan.Build([new DepRef(root, value)], source, new PlanOptions(parsed.SingleTarget)); + plan = RunPlan.Build([new DepRef(root, value)], source, new PlanOptions(parsed.SingleTarget, EvaluateConditions: parsed.Graph is not null)); } catch (MakeException ex) { Console.Error.WriteLine(ex.Message); return ex.ExitCode; } + + if (parsed.Graph is { } format) + { + PlanRenderer.Write(plan, format, Console.Out); + return 0; + } return await ExecuteAsync(plan, parsed); } + /// --graph without a target: draws every target nothing else depends on. + public static int DrawWholeGraph(BuildGraph graph, GraphFormat format) + { + var source = graph.Source ?? throw new InvalidOperationException("The graph has no target source."); + try + { + var plan = PlanRenderer.WholeGraph(graph, source, new PlanOptions(SingleTarget: false, EvaluateConditions: true)); + PlanRenderer.Write(plan, format, Console.Out); + return 0; + } + catch (MakeException ex) + { + Console.Error.WriteLine(ex.Message); + return ex.ExitCode; + } + } + public static async Task ExecuteAsync(RunPlan plan, ParsedArgs parsed) { var context = new MakeContext(parsed.GlobalValues, parsed.SingleTarget) { TargetArgs = parsed.TargetArgs }; diff --git a/src/Nullean.Make/Execution/PlanRenderer.cs b/src/Nullean.Make/Execution/PlanRenderer.cs new file mode 100644 index 0000000..d9dd84a --- /dev/null +++ b/src/Nullean.Make/Execution/PlanRenderer.cs @@ -0,0 +1,308 @@ +using System.Text; +using System.Text.Json; +using Nullean.Argh.Help; +using Nullean.Make.Discovery; + +namespace Nullean.Make.Execution; + +/// How --graph draws the plan. +internal enum GraphFormat +{ + /// A tree in the terminal, with the order the targets run in below it. + Tree, + + /// A Mermaid flowchart, for a pull request or the docs. + Mermaid, + + /// The plan as JSON, for tools. + Json +} + +/// Reads --graph, --graph mermaid and --graph=json from the command line. +internal static class GraphOption +{ + public const string Name = "--graph"; + + /// + /// When args[i] is --graph, reads it and an optional format after it, advances + /// past them and returns the format. A word after --graph that is not a format is left for the route. + /// + public static GraphFormat? TryRead(IReadOnlyList args, ref int i) + { + var arg = args[i]; + if (arg.StartsWith(Name + "=", StringComparison.Ordinal)) + { + i++; + return Parse(arg[(Name.Length + 1)..]) ?? + throw new MakeException($"Unknown graph format '{arg[(Name.Length + 1)..]}'. Known: tree, mermaid, json.", 2); + } + if (arg != Name) + return null; + i++; + if (i < args.Count && Parse(args[i]) is { } format) + { + i++; + return format; + } + return GraphFormat.Tree; + } + + private static GraphFormat? Parse(string value) => value.ToLowerInvariant() switch + { + "tree" => GraphFormat.Tree, + "mermaid" => GraphFormat.Mermaid, + "json" => GraphFormat.Json, + _ => null + }; +} + +/// Draws a without running it. +internal static class PlanRenderer +{ + public static void Write(RunPlan plan, GraphFormat format, TextWriter output) + { + switch (format) + { + case GraphFormat.Mermaid: + WriteMermaid(plan, output); + break; + case GraphFormat.Json: + WriteJson(plan, output); + break; + default: + WriteTree(plan, output); + break; + } + } + + /// + /// The plan for the targets nothing else depends on, each with its default value: what the whole build looks like. + /// + public static RunPlan WholeGraph(BuildGraph graph, ITargetSource source, PlanOptions options) + { + var referenced = graph.Targets.SelectMany(t => t.RequiresResolved.Concat(t.ComposesResolved)).ToHashSet(); + var roots = graph.Targets.Where(t => !t.Hidden && !referenced.Contains(t)).Select(t => new DepRef(t, null)).ToList(); + return RunPlan.Build(roots, source, options with { ChainRoots = false }); + } + + /// The targets whose bodies run, in order: what Runs: lists. + public static IEnumerable Running(RunPlan plan) => plan.Instances.Where(i => i.Spec.Body is not null && i.Skipped is null); + + /// clean → build → test. + public static string RunOrder(RunPlan plan) => string.Join(" → ", Running(plan).Select(i => i.Name)); + + /// + /// Each instance's prerequisites without the ones another prerequisite already waits for, so a drawn graph has an + /// edge per real ordering and no transitive ones. + /// + public static Dictionary> DirectPrerequisites(RunPlan plan) + { + var ancestors = new Dictionary>(); + var direct = new Dictionary>(); + foreach (var instance in plan.Instances) + { + var all = new HashSet(); + foreach (var prerequisite in instance.Prerequisites) + { + all.Add(prerequisite); + all.UnionWith(ancestors[prerequisite]); + } + ancestors[instance] = all; + var distinct = instance.Prerequisites.Distinct().ToList(); + direct[instance] = distinct.Where(p => !distinct.Any(q => q != p && ancestors[q].Contains(p))).ToList(); + } + return direct; + } + + // ── tree ────────────────────────────────────────────────────────────────── + + private sealed record Line(string Text, List Children); + + private static void WriteTree(RunPlan plan, TextWriter output) + { + var expanded = new HashSet(); + foreach (var root in plan.Roots) + { + var tree = Build(root, expanded); + var description = root.Node.Description; + output.WriteLine(string.IsNullOrEmpty(description) ? Accent(tree.Text) : $"{Accent(tree.Text)} {description}"); + WriteChildren(tree.Children, "", output); + output.WriteLine(); + } + + // Unrelated roots drawn side by side do not run in one sequence. + if (!plan.Chained && plan.Roots.Count > 1) + return; + var order = RunOrder(plan); + output.WriteLine($"{CliHelpFormatting.Section("Runs:")} {(order.Length == 0 ? "nothing" : order)}"); + } + + private static Line Build(TargetInstance instance, HashSet expanded) + { + var text = instance.Name + Annotation(instance.Skipped); + if (!expanded.Add(instance)) + return new Line(text + Dim(" (above)"), []); + + var children = new List(); + foreach (var kind in new[] { StageKind.Requires, StageKind.Composes }) + { + var lines = new List(); + foreach (var stage in instance.Stages.Where(s => s.Kind == kind)) + { + var items = stage + .Items + .Select(item => item.Instance is null ? new Line(item.Name + Annotation(item.Skipped), []) : Build(item.Instance, expanded)) + .ToList(); + if (stage.Parallel) + lines.Add(new Line(Dim("parallel"), items)); + else + lines.AddRange(items); + } + if (lines.Count == 0) + continue; + + // A target's dependencies hang off it directly; a command says which of its stages -s skips. + if (instance.Node.Kind == TargetKind.Command) + children.Add(new Line(Dim(kind == StageKind.Requires ? "requires" : "composes"), lines)); + else + children.AddRange(lines); + } + return new Line(text, children); + } + + private static void WriteChildren(List children, string indent, TextWriter output) + { + for (var i = 0; i < children.Count; i++) + { + var last = i == children.Count - 1; + output.WriteLine($"{indent}{(last ? "└─ " : "├─ ")}{children[i].Text}"); + WriteChildren(children[i].Children, indent + (last ? " " : "│ "), output); + } + } + + private static string Annotation(SkipReason? reason) => reason switch + { + SkipReason.SingleTarget => Dim(" skipped: -s"), + SkipReason.Condition => Dim(" skipped: its condition is false"), + _ => "" + }; + + private static string Accent(string text) => CliHelpFormatting.Accent(text); + + private static string Dim(string text) => CliHelpFormatting.DocRemarksLine(text); + + // ── mermaid ─────────────────────────────────────────────────────────────── + + private static void WriteMermaid(RunPlan plan, TextWriter output) + { + var ids = new Dictionary(); + foreach (var instance in plan.Instances) + ids[instance] = $"n{ids.Count}"; + + var sb = new StringBuilder(); + var skipped = new List(); + sb.AppendLine("flowchart TD"); + foreach (var instance in plan.Instances) + { + sb.AppendLine($" {ids[instance]}[\"{Escape(instance.Name)}\"]"); + if (instance.Skipped is not null) + skipped.Add(ids[instance]); + } + + var extra = 0; + var direct = DirectPrerequisites(plan); + foreach (var instance in plan.Instances) + { + foreach (var prerequisite in direct[instance]) + sb.AppendLine($" {ids[prerequisite]} --> {ids[instance]}"); + foreach (var item in instance.Stages.SelectMany(s => s.Items).Where(i => i.Instance is null)) + { + var id = $"s{extra++}"; + sb.AppendLine($" {id}[\"{Escape(item.Name)}\"]"); + sb.AppendLine($" {id} -.-> {ids[instance]}"); + skipped.Add(id); + } + } + + if (skipped.Count > 0) + { + sb.AppendLine(" classDef skipped stroke-dasharray: 5 5,color:#888"); + sb.AppendLine($" class {string.Join(",", skipped)} skipped"); + } + output.Write(sb.ToString()); + } + + private static string Escape(string text) => text.Replace("\"", "#quot;"); + + // ── json ────────────────────────────────────────────────────────────────── + + private static void WriteJson(RunPlan plan, TextWriter output) + { + using var stream = new MemoryStream(); + using (var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true })) + { + json.WriteStartObject(); + json.WriteStartArray("roots"); + foreach (var root in plan.Roots) + json.WriteStringValue(root.Name); + json.WriteEndArray(); + + json.WriteStartArray("targets"); + var direct = DirectPrerequisites(plan); + foreach (var instance in plan.Instances) + { + json.WriteStartObject(); + json.WriteString("name", instance.Name); + json.WriteStartArray("route"); + foreach (var segment in instance.Node.Route) + json.WriteStringValue(segment); + json.WriteEndArray(); + json.WriteString("kind", instance.Node.Kind == TargetKind.Command ? "command" : "target"); + json.WriteBoolean("hasBody", instance.Spec.Body is not null); + WriteSkipped(json, instance.Skipped); + json.WriteStartArray("waitsFor"); + foreach (var prerequisite in direct[instance]) + json.WriteStringValue(prerequisite.Name); + json.WriteEndArray(); + json.WriteStartArray("stages"); + foreach (var stage in instance.Stages) + { + json.WriteStartObject(); + json.WriteString("kind", stage.Kind == StageKind.Requires ? "requires" : "composes"); + json.WriteBoolean("parallel", stage.Parallel); + json.WriteStartArray("items"); + foreach (var item in stage.Items) + { + json.WriteStartObject(); + json.WriteString("name", item.Name); + WriteSkipped(json, item.Skipped); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteEndObject(); + } + output.WriteLine(Encoding.UTF8.GetString(stream.ToArray())); + } + + private static void WriteSkipped(Utf8JsonWriter json, SkipReason? reason) + { + switch (reason) + { + case SkipReason.SingleTarget: + json.WriteString("skipped", "single-target"); + break; + case SkipReason.Condition: + json.WriteString("skipped", "condition"); + break; + default: + json.WriteNull("skipped"); + break; + } + } +} diff --git a/src/Nullean.Make/Execution/RunPlan.cs b/src/Nullean.Make/Execution/RunPlan.cs index cbfda54..3216189 100644 --- a/src/Nullean.Make/Execution/RunPlan.cs +++ b/src/Nullean.Make/Execution/RunPlan.cs @@ -45,7 +45,10 @@ internal sealed record PlannedStage(StageKind Kind, bool Parallel, IReadOnlyList internal sealed record PlannedItem(TargetInstance? Instance, string Name, SkipReason? Skipped); /// Options that change which instances the plan contains. -internal sealed record PlanOptions(bool SingleTarget, bool EvaluateConditions = false); +/// 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); /// The instances a run contains, in an order that respects every prerequisite. internal sealed class RunPlan @@ -53,6 +56,9 @@ internal sealed class RunPlan public required IReadOnlyList Roots { get; init; } public required IReadOnlyList Instances { get; init; } + /// True when the roots run one after another; false for a drawing of unrelated roots. + public bool Chained { get; init; } = true; + /// /// 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 @@ -65,12 +71,12 @@ public static RunPlan Build(IReadOnlyList roots, ITargetSource source, P TargetInstance? previous = null; foreach (var root in roots) { - var instance = builder.Visit(root, isRoot: true, previous is null ? [] : [previous]); + var instance = builder.Visit(root, isRoot: true, previous is null || !options.ChainRoots ? [] : [previous]); instance.IsRoot = true; rootInstances.Add(instance); previous = instance; } - return new RunPlan { Roots = rootInstances, Instances = builder.Ordered }; + return new RunPlan { Roots = rootInstances, Instances = builder.Ordered, Chained = options.ChainRoots }; } private sealed class Builder(ITargetSource source, PlanOptions options) diff --git a/src/Nullean.Make/Help/MakeHelpPrinter.cs b/src/Nullean.Make/Help/MakeHelpPrinter.cs index 4897b60..7371955 100644 --- a/src/Nullean.Make/Help/MakeHelpPrinter.cs +++ b/src/Nullean.Make/Help/MakeHelpPrinter.cs @@ -1,5 +1,6 @@ using Nullean.Argh.Help; using Nullean.Make.Discovery; +using Nullean.Make.Execution; using Nullean.Make.Parsing; namespace Nullean.Make.Help; @@ -147,6 +148,7 @@ public static void PrintTarget(TargetNode node, BuildGraph graph, string scriptN foreach (var dep in allDeps) Console.WriteLine($" {string.Join(" ", dep.Route)}"); Console.WriteLine(); + PrintRunOrder(node, graph, scriptName); } PrintGlobalOptions(graph, scriptName); @@ -180,9 +182,33 @@ public static void PrintCommand(TargetNode node, BuildGraph graph, string script Console.WriteLine(); } + PrintRunOrder(node, graph, scriptName); PrintGlobalOptions(graph, scriptName); } + /// + /// Runs: the bodies a bare invocation of the target runs, in order, and where to see the whole plan. Prints + /// nothing when the target has no dependencies to order, or the plan cannot be built. + /// + private static void PrintRunOrder(TargetNode node, BuildGraph graph, string scriptName) + { + if (graph.Source is not { } source || node.RequiresResolved.Count + node.ComposesResolved.Count == 0) + return; + RunPlan plan; + try + { + plan = RunPlan.Build([new DepRef(node, null)], source, new PlanOptions(SingleTarget: false)); + } + catch (MakeException) + { + return; + } + Console.WriteLine($" {CliHelpFormatting.Section("Runs:")}"); + Console.WriteLine($" {PlanRenderer.RunOrder(plan)}"); + Console.WriteLine($" {CliHelpFormatting.DocRemarksLine($"{scriptName} {string.Join(" ", node.Route)} --graph draws the plan")}"); + Console.WriteLine(); + } + private static string CommandSummary(TargetNode node) { var req = node.RequiresResolved.Select(d => string.Join(" ", d.Route)).ToList(); @@ -218,6 +244,7 @@ private static void PrintGlobalOptions(BuildGraph graph, string scriptName) Console.WriteLine($" {CliHelpFormatting.Section("Global options:")}"); Console.WriteLine($" {CliHelpFormatting.Placeholder("-s, --single-target"),-30} Skip prerequisite deps; run only the body / Composes"); Console.WriteLine($" {CliHelpFormatting.Placeholder("-h, --help"),-30} Show this help"); + Console.WriteLine($" {CliHelpFormatting.Placeholder(" --graph []"),-30} Draw what would run and run nothing: tree, mermaid or json"); foreach (var opt in graph.GlobalOptions) { diff --git a/src/Nullean.Make/MakeApp.cs b/src/Nullean.Make/MakeApp.cs index a96aaeb..be71279 100644 --- a/src/Nullean.Make/MakeApp.cs +++ b/src/Nullean.Make/MakeApp.cs @@ -75,6 +75,8 @@ public static class MakeApp if (parsed.Target is null) { + if (parsed.Graph is { } format) + return DepGraphExecutor.DrawWholeGraph(graph, format); MakeHelpPrinter.PrintRoot(graph, scriptName); return 0; } diff --git a/src/Nullean.Make/MakeAppOfT.cs b/src/Nullean.Make/MakeAppOfT.cs index 389c266..1c94b55 100644 --- a/src/Nullean.Make/MakeAppOfT.cs +++ b/src/Nullean.Make/MakeAppOfT.cs @@ -149,9 +149,10 @@ public async Task RunAsync(string[] args) string[] remaining; bool singleTarget, showHelp, showVersion; + GraphFormat? graphFormat; try { - (remaining, singleTarget, showHelp, showVersion) = ExtractGlobals(args); + (remaining, singleTarget, showHelp, showVersion, graphFormat) = ExtractGlobals(args); } catch (MakeException ex) { @@ -189,6 +190,8 @@ public async Task RunAsync(string[] args) Console.Error.WriteLine($"Unknown target '{unknown}'."); return 2; } + if (graphFormat is { } format) + return DepGraphExecutor.DrawWholeGraph(_graph, format); MakeHelpPrinter.PrintRoot(_graph, scriptName); return 0; } @@ -199,7 +202,7 @@ public async Task RunAsync(string[] args) return 2; } - var parsed = new ParsedArgs { Target = targetNode, TargetArgs = targetArgs, SingleTarget = singleTarget, }; + var parsed = new ParsedArgs { Target = targetNode, TargetArgs = targetArgs, SingleTarget = singleTarget, Graph = graphFormat }; return await DepGraphExecutor.ExecuteAsync(targetNode, parsed, _graph); } @@ -253,12 +256,13 @@ private TargetNode ResolveCase(TargetNode from, string caseTypeName) // ── Argv helpers ────────────────────────────────────────────────────────── - private (string[] remaining, bool single, bool help, bool version) ExtractGlobals(string[] argv) + private (string[] remaining, bool single, bool help, bool version, GraphFormat? graph) ExtractGlobals(string[] argv) { var remaining = new List(); var single = false; var help = false; var version = false; + GraphFormat? graph = null; var i = 0; while (i < argv.Length) { @@ -281,6 +285,11 @@ private TargetNode ResolveCase(TargetNode from, string caseTypeName) i++; continue; } + if (GraphOption.TryRead(argv, ref i) is { } format) + { + graph = format; + continue; + } var matched = false; foreach (var opt in _options) @@ -311,7 +320,7 @@ private TargetNode ResolveCase(TargetNode from, string caseTypeName) i++; } } - return (remaining.ToArray(), single, help, version); + return (remaining.ToArray(), single, help, version, graph); } private (string routeKey, string[] targetArgs) ResolveRoute(string[] remaining) diff --git a/src/Nullean.Make/Parsing/ArgvParser.cs b/src/Nullean.Make/Parsing/ArgvParser.cs index 882bb73..3a4923c 100644 --- a/src/Nullean.Make/Parsing/ArgvParser.cs +++ b/src/Nullean.Make/Parsing/ArgvParser.cs @@ -12,6 +12,9 @@ internal sealed class ParsedArgs public bool SingleTarget { get; set; } public bool ShowHelp { get; set; } public bool ShowVersion { get; set; } + + /// Set by --graph: draw the plan in this format and run nothing. + public Execution.GraphFormat? Graph { get; set; } public string? HelpTarget { get; set; } } @@ -117,6 +120,11 @@ private static List ExtractGlobals(string[] args, BuildGraph graph, Make i++; continue; } + if (Execution.GraphOption.TryRead(args, ref i) is { } graphFormat) + { + result.Graph = graphFormat; + continue; + } // Global options var matched = false; diff --git a/src/Nullean.Make/README.md b/src/Nullean.Make/README.md index 8599957..f1a3d13 100644 --- a/src/Nullean.Make/README.md +++ b/src/Nullean.Make/README.md @@ -114,6 +114,19 @@ 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. +## Drawing the plan + +`--graph` draws what a run would do and runs nothing. It binds the target's arguments, applies `-s` and evaluates +conditions, so a skipped target shows as skipped: + +``` +build release -s --graph +build release --graph mermaid # or json +``` + +A target's `--help` lists the order its dependencies run in under `Runs:`. See +[Drawing the plan](https://argh.nullean.net/make/graph). + ## mise, make and just `__wrappers sync` writes one include file per wrapper from the targets, so `mise run test`, `make test` and diff --git a/tests/Nullean.Make.Fs.Tests/GraphTests.fs b/tests/Nullean.Make.Fs.Tests/GraphTests.fs new file mode 100644 index 0000000..c436b52 --- /dev/null +++ b/tests/Nullean.Make.Fs.Tests/GraphTests.fs @@ -0,0 +1,66 @@ +module Nullean.Make.Fs.Tests.GraphTests + +open System +open System.IO +open TUnit.Core +open Nullean.Make.Fs + +type ProbeOptions = { Filter: string option } + +type Drawn = + | Wipe + | Compose + | Probe of ProbeOptions + | Ship + +let private run (args: string list) = + let log = ResizeArray() + let app = MakeApp("build", None) + app.Bind <| function + | Wipe -> target [] { log.Add "wipe" } + | Compose -> target [Wipe] { log.Add "compose" } + | Probe o -> target [Compose] { log.Add $"probe:%A{o.Filter}" } + | Ship -> command { + requires [Probe { Filter = Some "Unit" }] + composes [Wipe] } + let stdout = new StringWriter() + let oldOut, oldErr = Console.Out, Console.Error + Console.SetOut stdout + Console.SetError(new StringWriter()) + try + let exit = app.RunAsync(List.toArray args).GetAwaiter().GetResult() + exit, List.ofSeq log, string stdout + finally + Console.SetOut oldOut + Console.SetError oldErr + +[] +type GraphTests() = + + [] + member _.``Graph draws the plan and runs nothing``() = + let exit, log, stdout = run ["ship"; "--graph"] + Assert.Equal(0, exit) + Assert.Equal([], log) + Assert.Contains("probe (filter: Unit)", stdout) + Assert.Contains("Runs: wipe → compose → probe (filter: Unit)", stdout) + + [] + member _.``Graph shows a gate that single target skips``() = + let _, _, stdout = run ["ship"; "-s"; "--graph"] + Assert.Contains("probe (filter: Unit) skipped: -s", stdout) + Assert.Contains("Runs: wipe", stdout) + + [] + member _.``Graph without a target draws the whole build``() = + let exit, log, stdout = run ["--graph"] + Assert.Equal(0, exit) + Assert.Equal([], log) + // Everything else is a dependency of ship, so ship is the one root. + Assert.Equal(true, stdout.StartsWith "ship") + + [] + member _.``Graph mermaid prints a flowchart``() = + let _, _, stdout = run ["probe"; "--graph"; "mermaid"] + Assert.Contains("flowchart TD", stdout) + Assert.Contains("n0 --> n1", 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 97a1c3d..1893294 100644 --- a/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj +++ b/tests/Nullean.Make.Fs.Tests/Nullean.Make.Fs.Tests.fsproj @@ -15,6 +15,7 @@ + diff --git a/tests/Nullean.Make.Tests/GraphTests.cs b/tests/Nullean.Make.Tests/GraphTests.cs new file mode 100644 index 0000000..179010f --- /dev/null +++ b/tests/Nullean.Make.Tests/GraphTests.cs @@ -0,0 +1,177 @@ +using System.Text.Json; +using AwesomeAssertions; + +namespace Nullean.Make.Tests; + +public record class Wipe; + +public record class Compose; + +public record class Probe(string Filter = ""); + +public record class Ship; + +public union Drawn(Wipe, Compose, Probe, Ship); + +/// --graph draws the plan the same run would execute, and runs nothing. +[NotInParallel] +public class GraphTests +{ + 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( + d => + d.Value switch + { + Wipe => app.Target(() => log.Add("wipe")), + Compose => app.Target([new Wipe()], () => log.Add("compose")), + Probe p => app.Target([new Compose()], () => log.Add($"probe:{p.Filter}")), + Ship => app.Command([new Probe("Unit")], [new Wipe()]), + _ => throw new InvalidOperationException($"unmapped case {d.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 Graph_draws_the_plan_and_runs_nothing() + { + var run = await RunAsync("ship", "--graph"); + run.ExitCode.Should().Be(0); + run.Log.Should().BeEmpty(); + run.Stdout.Should().Contain("├─ requires").And.Contain("└─ composes").And.Contain("probe (filter: Unit)"); + run.Stdout.Should().Contain("Runs: wipe → compose → probe (filter: Unit)"); + } + + [Test] + public async Task Graph_shows_a_gate_that_single_target_skips() + { + var run = await RunAsync("ship", "-s", "--graph"); + run.Stdout.Should().Contain("probe (filter: Unit) skipped: -s"); + run.Stdout.Should().Contain("Runs: wipe"); + run.Stdout.Should().NotContain("compose" + Environment.NewLine); + } + + [Test] + public async Task Graph_binds_the_named_targets_arguments() + { + var run = await RunAsync("probe", "--filter", "Smoke", "--graph"); + run.Stdout.Should().Contain("probe (filter: Smoke)"); + } + + [Test] + public async Task Graph_mermaid_draws_one_edge_per_ordering() + { + var run = await RunAsync("probe", "--graph", "mermaid"); + run.ExitCode.Should().Be(0); + var lines = run.Stdout.Split('\n', StringSplitOptions.TrimEntries); + lines.Should().Contain("flowchart TD"); + lines.Count(l => l.Contains("-->")).Should().Be(2); + } + + [Test] + public async Task Graph_json_lists_the_targets_in_run_order() + { + var run = await RunAsync("ship", "--graph=json"); + run.ExitCode.Should().Be(0); + using var doc = JsonDocument.Parse(run.Stdout); + var names = doc.RootElement.GetProperty("targets").EnumerateArray().Select(t => t.GetProperty("name").GetString()).ToList(); + names.Should().Equal("wipe", "compose", "probe (filter: Unit)", "ship"); + doc.RootElement.GetProperty("roots")[0].GetString().Should().Be("ship"); + } + + [Test] + public async Task Graph_without_a_target_draws_every_target_nothing_depends_on() + { + var run = await RunAsync("--graph"); + run.ExitCode.Should().Be(0); + // Everything else is a dependency of ship, so ship is the one root. + run.Stdout.Should().StartWith("ship"); + run.Log.Should().BeEmpty(); + } + + [Test] + public async Task An_unknown_graph_format_exits_2() + { + var run = await RunAsync("ship", "--graph=dot"); + run.ExitCode.Should().Be(2); + run.Stderr.Should().Contain("Unknown graph format 'dot'"); + } + + [Test] + public async Task Target_help_lists_what_it_runs() + { + var run = await RunAsync("ship", "--help"); + run.Stdout.Should().Contain("Runs:").And.Contain("wipe → compose → probe (filter: Unit)"); + run.Stdout.Should().Contain("--graph []"); + } +} + +public class ConditionalBuild : MakeBuild +{ + [Flag("--skip-lint", Description = "Skip lint")] + public bool SkipLint { get; init; } + + public Target Lint => + _ => _.OnlyWhen(() => !SkipLint).Executes(() => + { }); + + public Target Compile => + _ => _.DependsOn(Lint).Executes(() => + { }); +} + +[NotInParallel] +public class ClassGraphTests +{ + private static async Task<(int Exit, string Stdout)> RunAsync(params string[] args) + { + var stdout = new StringWriter(); + var (oldOut, oldErr) = (Console.Out, Console.Error); + Console.SetOut(stdout); + Console.SetError(new StringWriter()); + try + { + return (await MakeApp.Execute(args), stdout.ToString()); + } + finally + { + Console.SetOut(oldOut); + Console.SetError(oldErr); + } + } + + [Test] + public async Task Graph_evaluates_conditions_and_shows_what_they_skip() + { + var (exit, stdout) = await RunAsync("compile", "--skip-lint", "--graph"); + exit.Should().Be(0); + stdout.Should().Contain("lint skipped: its condition is false"); + stdout.Should().Contain("Runs: compile"); + } + + [Test] + public async Task Graph_shows_a_condition_that_holds_as_running() + { + var (_, stdout) = await RunAsync("compile", "--graph"); + stdout.Should().NotContain("skipped"); + stdout.Should().Contain("Runs: lint → compile"); + } +}