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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 52 additions & 23 deletions src/Nullean.Make.Fs/FsGraphBuilder.fs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ open System
open Microsoft.FSharp.Reflection
open Nullean.Make
open Nullean.Make.Discovery
open Nullean.Make.Execution

let private toKebabCase = BuildScanner.ToKebabCase

Expand Down Expand Up @@ -39,6 +40,51 @@ let private isStructuralNs (ci: UnionCaseInfo) =
let fs = ci.GetFields()
fs.Length = 1 && FSharpType.IsUnion(fs.[0].PropertyType)

/// The payload record of a case value, or null when the case carries none. A namespace sub-case carries no payload.
let private payloadOf (value: obj) : obj =
if isNull value then null
else
let ci, fields = FSharpValue.GetUnionFields(value, value.GetType())
if fields.Length = 1 && FSharpType.IsRecord(ci.GetFields().[0].PropertyType) then fields.[0] else null

/// The targets of an F# MakeApp: a node's value is the DU case value. `bind` runs again for each value, so a dependency
/// declared as `Test { Filter = Some "Unit" }` runs the body bind returns for that value.
type private FsTargetSource<'TCase when 'TCase : comparison and 'TCase : not null>
(bind: 'TCase -> Definition<'TCase>,
nodeCases: Collections.Generic.Dictionary<TargetNode, 'TCase * UnionCaseInfo>,
resolve: TargetNode -> 'TCase -> TargetNode) =

let refs (node: TargetNode) (deps: 'TCase list) =
deps |> List.map (fun d -> DepRef(resolve node d, box d)) |> ResizeArray

interface Nullean.Make.Execution.ITargetSource with
member _.DefaultValue(node) = box (fst nodeCases.[node])

member _.BindArguments(node, args) =
let defaultValue, caseInfo = nodeCases.[node]
let fields = caseInfo.GetFields()
if fields.Length = 1 && FSharpType.IsRecord(fields.[0].PropertyType) then
FSharpValue.MakeUnion(caseInfo, [| FsDtoBinder.bind fields.[0].PropertyType args |])
else box defaultValue

member _.Describe(node, value) =
let spec = Nullean.Make.Execution.InstanceSpec()
let body (b: FsContext -> unit) =
Func<Threading.CancellationToken, Threading.Tasks.Task>(fun _ -> b sharedCtx; Threading.Tasks.Task.CompletedTask)
match bind (unbox<'TCase> value) with
| FsTarget(_, deps, b, _) ->
spec.Add(Nullean.Make.Execution.StageKind.Requires, refs node deps)
spec.Body <- body b
| FsCommand(_, requires, composes, b) ->
spec.Add(Nullean.Make.Execution.StageKind.Requires, refs node requires)
spec.Add(Nullean.Make.Execution.StageKind.Composes, refs node composes)
b |> Option.iter (fun b -> spec.Body <- body b)
| FsNamespace _ -> ()
spec

member _.FormatValue(node, value) =
Nullean.Make.Execution.ValueDisplay.Differences(payloadOf value, payloadOf (box (fst nodeCases.[node])))

let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null>
(appName: string)
(appDescription: string option)
Expand Down Expand Up @@ -93,6 +139,8 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null>
ci.Name + "." + subCi.Name
else ci.Name
let caseToNode = Collections.Generic.Dictionary<string, TargetNode * 'TCase>()
// Each node's default value, and the case whose payload a value of it carries.
let nodeCases = Collections.Generic.Dictionary<TargetNode, 'TCase * UnionCaseInfo>(HashIdentity.Reference)

// Register one TargetNode. caseInfoForBody drives the SyncBody closure shape.
// For structural namespace sub-cases, caseInfoForBody is the sub-DU's UnionCaseInfo.
Expand All @@ -116,27 +164,6 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null>
elif kind = TargetKind.Command then ""
else toKebabCase (Array.last route)
let fields = caseInfoForBody.GetFields()

let plainBody () =
match def with
| FsTarget(_, _, b, _) -> b sharedCtx
| FsCommand(_, _, _, Some b) -> b sharedCtx
| _ -> ()

// Re-binds CLI args at execution time and re-invokes bind for typed-payload cases.
let payloadBody () =
let payloadType = fields.[0].PropertyType
let targetArgs =
let ctx = MakeContext.Current
if obj.ReferenceEquals(ctx, null) then [||] else ctx.TargetArgs
let payload = FsDtoBinder.bind payloadType targetArgs
let boundCase : 'TCase = FSharpValue.MakeUnion(caseInfoForBody, [| payload |]) :?> 'TCase
match bind boundCase with
| FsTarget(_, _, b, _) -> b sharedCtx
| FsCommand(_, _, _, Some b) -> b sharedCtx
| _ -> ()

let syncBody = Action(if fields.Length = 0 then plainBody else payloadBody)
let dtoType = if fields.Length = 1 && FSharpType.IsRecord(fields.[0].PropertyType)
then fields.[0].PropertyType else null
let node =
Expand All @@ -146,12 +173,12 @@ let buildGraph<'TCase when 'TCase : comparison and 'TCase : not null>
Kind = kind,
Hidden = (match def with FsTarget(_, _, _, true) -> true | _ -> false),
Description = desc,
DtoType = dtoType,
SyncBody = syncBody)
DtoType = dtoType)

graph.Targets.Add(node)
graph.ByRoute.[String.concat "/" route] <- node
caseToNode.[caseKey key] <- (node, key)
nodeCases.[node] <- (key, caseInfoForBody)

// Second pass: create TargetNode for each non-namespace case.
for caseInfo in cases do
Expand Down Expand Up @@ -195,6 +222,8 @@ 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))

match defaultCase with
| None -> ()
| Some d ->
Expand Down
2 changes: 1 addition & 1 deletion src/Nullean.Make.Fs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ A case whose payload is another DU becomes a CLI namespace: `Pkg of PkgTarget` g

## Per-target typed arguments

A case with a record payload binds the record's fields from CLI flags at execution time: `Test of TestOptions` with `{ Filter: string option }` takes `--filter`. A dependency can name any value of the case: `Test { Filter = Some "Unit" }` resolves to the `test` target.
A case with a record payload binds the record's fields from CLI flags: `Test of TestOptions` with `{ Filter: string option }` takes `--filter`. A dependency can name any value of the case: `Test { Filter = Some "Unit" }` runs the `test` target with that value. Two dependencies with equal values run the target once, and with different values once each. Only the target named on the command line binds the command line's flags.

### Positional arguments, forwarded arguments and `--name=value`

Expand Down
10 changes: 9 additions & 1 deletion src/Nullean.Make.Generator/UnionCaseGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ private sealed record UnionTable(string HintName, string Source);
foreach (var c in cases)
sb.AppendLine($"\t\t\t\t\t{c},");
sb.AppendLine("\t\t\t\t},");
sb.AppendLine("\t\t\t\tstatic u => Leaf(u.Value));");
sb.AppendLine("\t\t\t\tstatic u => Leaf(u.Value),");
sb.AppendLine("\t\t\t\tstatic u => LeafValue(u.Value));");
sb.AppendLine();
sb.AppendLine("\t\tprivate static global::System.Type? Leaf(object? value) => value switch");
sb.AppendLine("\t\t{");
Expand All @@ -89,6 +90,13 @@ private sealed record UnionTable(string HintName, string Source);
sb.AppendLine($"\t\t\t{nested.ToDisplayString(Fqn)} inner => Leaf(inner.Value),");
sb.AppendLine("\t\t\t_ => value.GetType()");
sb.AppendLine("\t\t};");
sb.AppendLine();
sb.AppendLine("\t\tprivate static object? LeafValue(object? value) => value switch");
sb.AppendLine("\t\t{");
foreach (var nested in nestedUnions)
sb.AppendLine($"\t\t\t{nested.ToDisplayString(Fqn)} inner => LeafValue(inner.Value),");
sb.AppendLine("\t\t\t_ => value");
sb.AppendLine("\t\t};");
sb.AppendLine("\t}");
sb.AppendLine("}");

Expand Down
3 changes: 3 additions & 0 deletions src/Nullean.Make/Discovery/BuildGraph.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,8 @@ internal sealed class BuildGraph
public TargetNode? Default { get; set; }

public string AppName { get; set; } = "make";

/// <summary>Resolves each target's dependencies and body for a value. Set by the surface that built the graph.</summary>
public Execution.ITargetSource? Source { get; set; }
public string? AppDescription { get; set; }
}
9 changes: 5 additions & 4 deletions src/Nullean.Make/Discovery/BuildScanner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public static BuildGraph Scan<TBuild>(TBuild build) where TBuild : MakeBuild
ScanTargets(build, typeof(TBuild), graph, Array.Empty<string>());
ScanNestedNamespaces(typeof(TBuild), graph);
ResolveDepGraph(graph);
graph.Source = new ClassTargetSource(graph);

return graph;
}
Expand Down Expand Up @@ -169,15 +170,15 @@ private static void ResolveDepGraph(BuildGraph graph)
{
foreach (var node in graph.Targets)
{
foreach (var method in node.Requires)
foreach (var reference in node.Requires)
{
if (graph.ByMethod.TryGetValue(method, out var dep))
if (graph.ByMethod.TryGetValue(reference.Method, out var dep))
node.RequiresResolved.Add(dep);
}

foreach (var method in node.Composes)
foreach (var reference in node.Composes)
{
if (graph.ByMethod.TryGetValue(method, out var dep))
if (graph.ByMethod.TryGetValue(reference.Method, out var dep))
node.ComposesResolved.Add(dep);
}
}
Expand Down
52 changes: 52 additions & 0 deletions src/Nullean.Make/Discovery/ClassTargetSource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using Nullean.Make.Execution;
using Nullean.Make.Parsing;

namespace Nullean.Make.Discovery;

/// <summary>The targets of a <see cref="MakeBuild"/> class: a node's value is its DTO, or <c>null</c> when it has none.</summary>
internal sealed class ClassTargetSource(BuildGraph graph) : ITargetSource
{
public object? DefaultValue(TargetNode node) => node.DtoType is null ? null : DtoBinder.Bind(node.DtoType, []);

public object? BindArguments(TargetNode node, string[] args) => node.DtoType is null ? null : DtoBinder.Bind(node.DtoType, args);

public InstanceSpec Describe(TargetNode node, object? value)
{
var spec = new InstanceSpec { OnlyWhen = node.OnlyWhen };
spec.Add(StageKind.Requires, Resolve(node.Requires));
spec.Add(StageKind.Composes, Resolve(node.Composes));

if (node.TypedBody is { } typed && node.DtoType is not null)
spec.Body = _ => InvokeTyped(typed, value);
else if (node.AsyncBody is { } asyncBody)
spec.Body = _ => asyncBody();
else if (node.SyncBody is { } syncBody)
spec.Body = _ =>
{
syncBody();
return Task.CompletedTask;
};
return spec;
}

public string? FormatValue(TargetNode node, object? value) => ValueDisplay.Differences(value, DefaultValue(node));

/// <summary>A reference to a delegate that is not a target of this build resolves to nothing, as it always has.</summary>
private List<DepRef> Resolve(List<TargetRef> references) =>
references.Where(r => graph.ByMethod.ContainsKey(r.Method)).Select(r => new DepRef(graph.ByMethod[r.Method], r.Value)).ToList();

/// <summary>Invokes an <c>Action&lt;T&gt;</c> or a <c>Func&lt;T, Task&gt;</c> body with the bound DTO.</summary>
private static Task InvokeTyped(Delegate body, object? value)
{
try
{
return body.DynamicInvoke(value) as Task ?? Task.CompletedTask;
}
catch (System.Reflection.TargetInvocationException ex) when (ex.InnerException is not null)
{
// Rethrow what the body threw, so a MakeException keeps its exit code and message.
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(ex.InnerException);
throw;
}
}
}
14 changes: 7 additions & 7 deletions src/Nullean.Make/Discovery/TargetBuilderImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public ITargetBuilder OnlyWhen(Func<bool> condition)
public ITargetBuilder DependsOn(params TargetRef[] refs)
{
foreach (var r in refs)
_node.Requires.Add(r.Method);
_node.Requires.Add(r);
return this;
}

Expand Down Expand Up @@ -71,7 +71,7 @@ ICommandBuilder ICommandBuilder.OnlyWhen(Func<bool> c)
ICommandBuilder ICommandBuilder.DependsOn(params TargetRef[] refs)
{
foreach (var r in refs)
_node.Requires.Add(r.Method);
_node.Requires.Add(r);
return this;
}

Expand All @@ -89,14 +89,14 @@ ICommandBuilder ICommandBuilder.Executes(Func<Task> body)
ICommandBuilder ICommandBuilder.Requires(params TargetRef[] refs)
{
foreach (var r in refs)
_node.Requires.Add(r.Method);
_node.Requires.Add(r);
return this;
}

ICommandBuilder ICommandBuilder.Composes(params TargetRef[] refs)
{
foreach (var r in refs)
_node.Composes.Add(r.Method);
_node.Composes.Add(r);
return this;
}
}
Expand Down Expand Up @@ -135,7 +135,7 @@ public ITargetBuilder<T> OnlyWhen(Func<bool> condition)
public ITargetBuilder<T> DependsOn(params TargetRef[] refs)
{
foreach (var r in refs)
_node.Requires.Add(r.Method);
_node.Requires.Add(r);
return this;
}
public ITargetBuilder<T> Executes(Action<T> body)
Expand Down Expand Up @@ -170,13 +170,13 @@ ITargetBuilder ITargetBuilder.Executes(Func<Task> body)
ICommandBuilder<T> ICommandBuilder<T>.Requires(params TargetRef[] refs)
{
foreach (var r in refs)
_node.Requires.Add(r.Method);
_node.Requires.Add(r);
return this;
}
ICommandBuilder<T> ICommandBuilder<T>.Composes(params TargetRef[] refs)
{
foreach (var r in refs)
_node.Composes.Add(r.Method);
_node.Composes.Add(r);
return this;
}
}
8 changes: 4 additions & 4 deletions src/Nullean.Make/Discovery/TargetNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ internal sealed class TargetNode
public Func<bool>? OnlyWhen { get; set; }
public TargetKind Kind { get; set; }

/// <summary>DependsOn / Requires methods — skippable under -s.</summary>
public List<MethodInfo> Requires { get; } = new();
/// <summary>DependsOn / Requires references — skippable under -s.</summary>
public List<TargetRef> Requires { get; } = new();

/// <summary>Composes methods — always run.</summary>
public List<MethodInfo> Composes { get; } = new();
/// <summary>Composes references — always run.</summary>
public List<TargetRef> Composes { get; } = new();

/// <summary>Sync body; null when async or not set.</summary>
public Action? SyncBody { get; set; }
Expand Down
Loading
Loading