Skip to content

Introduce CliAction, make it possible for every Symbol to define one #2095

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Mar 16, 2023
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
2 changes: 1 addition & 1 deletion samples/HostingPlayground/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ private static CommandLineBuilder BuildCommandLine()
IsRequired = true
}
};
root.Handler = CommandHandler.Create<GreeterOptions, IHost>(Run);
root.Action = CommandHandler.Create<GreeterOptions, IHost>(Run);
return new CommandLineBuilder(root);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,8 @@ System.CommandLine.NamingConventionBinder
public static System.Void AddModelBinder(this System.CommandLine.Binding.BindingContext bindingContext, ModelBinder binder)
public static System.CommandLine.Binding.BindingContext GetBindingContext(this System.CommandLine.Invocation.InvocationContext ctx)
public static ModelBinder GetOrCreateModelBinder(this System.CommandLine.Binding.BindingContext bindingContext, System.CommandLine.Binding.IValueDescriptor valueDescriptor)
public abstract class BindingHandler, System.CommandLine.ICommandHandler
public abstract class BindingHandler : System.CommandLine.CliAction
public System.CommandLine.Binding.BindingContext GetBindingContext(System.CommandLine.Invocation.InvocationContext invocationContext)
public System.Int32 Invoke(System.CommandLine.Invocation.InvocationContext context)
public System.Threading.Tasks.Task<System.Int32> InvokeAsync(System.CommandLine.Invocation.InvocationContext context, System.Threading.CancellationToken cancellationToken = null)
public System.CommandLine.Binding.BindingContext SetBindingContext(System.CommandLine.Binding.BindingContext bindingContext)
public static class CommandHandler
public static BindingHandler Create(System.Delegate delegate)
Expand Down Expand Up @@ -115,7 +113,7 @@ System.CommandLine.NamingConventionBinder
.ctor()
public System.Void BindMemberFromValue<TValue>(Expression<Func<TModel,TValue>> property, System.CommandLine.Binding.IValueDescriptor valueDescriptor)
public System.Void BindMemberFromValue<TValue>(Expression<Func<TModel,TValue>> property, Func<System.CommandLine.Binding.BindingContext,TValue> getValue)
public class ModelBindingCommandHandler : BindingHandler, System.CommandLine.ICommandHandler
public class ModelBindingCommandHandler : BindingHandler
public System.Void BindParameter(System.Reflection.ParameterInfo param, System.CommandLine.Argument argument)
public System.Void BindParameter(System.Reflection.ParameterInfo param, System.CommandLine.Option option)
public System.Int32 Invoke(System.CommandLine.Invocation.InvocationContext context)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,15 @@ System.CommandLine
public static Argument<System.IO.DirectoryInfo> AcceptExistingOnly(this Argument<System.IO.DirectoryInfo> argument)
public static Argument<System.IO.FileSystemInfo> AcceptExistingOnly(this Argument<System.IO.FileSystemInfo> argument)
public static Argument<T> AcceptExistingOnly<T>(this Argument<T> argument)
public abstract class CliAction
public System.Int32 Invoke(System.CommandLine.Invocation.InvocationContext context)
public System.Threading.Tasks.Task<System.Int32> InvokeAsync(System.CommandLine.Invocation.InvocationContext context, System.Threading.CancellationToken cancellationToken = null)
public class Command : Symbol, System.Collections.Generic.IEnumerable<Symbol>, System.Collections.IEnumerable
.ctor(System.String name, System.String description = null)
public CliAction Action { get; set; }
public System.Collections.Generic.ICollection<System.String> Aliases { get; }
public System.Collections.Generic.IList<Argument> Arguments { get; }
public System.Collections.Generic.IEnumerable<Symbol> Children { get; }
public ICommandHandler Handler { get; set; }
public System.Collections.Generic.IList<Option> Options { get; }
public System.Collections.Generic.IList<Command> Subcommands { get; }
public System.Boolean TreatUnmatchedTokensAsErrors { get; set; }
Expand All @@ -50,8 +53,8 @@ System.CommandLine
public System.Collections.Generic.IEnumerator<Symbol> GetEnumerator()
public ParseResult Parse(System.Collections.Generic.IReadOnlyList<System.String> args, CommandLineConfiguration configuration = null)
public ParseResult Parse(System.String commandLine, CommandLineConfiguration configuration = null)
public System.Void SetHandler(System.Func<System.CommandLine.Invocation.InvocationContext,System.Int32> handler)
public System.Void SetHandler(System.Func<System.CommandLine.Invocation.InvocationContext,System.Threading.CancellationToken,System.Threading.Tasks.Task<System.Int32>> handler)
public System.Void SetAction(System.Action<System.CommandLine.Invocation.InvocationContext> action)
public System.Void SetAction(System.Func<System.CommandLine.Invocation.InvocationContext,System.Threading.CancellationToken,System.Threading.Tasks.Task> action)
public static class CommandExtensions
public static System.Int32 Invoke(this Command command, System.String[] args, IConsole console = null)
public static System.Int32 Invoke(this Command command, System.String commandLine, IConsole console = null)
Expand Down Expand Up @@ -104,17 +107,14 @@ System.CommandLine
public static System.Void Write(this IConsole console, System.String value)
public static System.Void WriteLine(this IConsole console, System.String value)
public class Directive : Symbol
.ctor(System.String name, System.Func<System.CommandLine.Invocation.InvocationContext,System.Int32> syncHandler = null, System.Func<System.CommandLine.Invocation.InvocationContext,System.Threading.CancellationToken,System.Threading.Tasks.Task<System.Int32>> asyncHandler = null)
.ctor(System.String name)
public CliAction Action { get; set; }
public System.Collections.Generic.IEnumerable<System.CommandLine.Completions.CompletionItem> GetCompletions(System.CommandLine.Completions.CompletionContext context)
public System.Void SetAsynchronousHandler(System.Func<System.CommandLine.Invocation.InvocationContext,System.Threading.CancellationToken,System.Threading.Tasks.Task<System.Int32>> handler)
public System.Void SetSynchronousHandler(System.Func<System.CommandLine.Invocation.InvocationContext,System.Int32> handler)
public class EnvironmentVariablesDirective : Directive
.ctor()
public interface ICommandHandler
public System.Int32 Invoke(System.CommandLine.Invocation.InvocationContext context)
public System.Threading.Tasks.Task<System.Int32> InvokeAsync(System.CommandLine.Invocation.InvocationContext context, System.Threading.CancellationToken cancellationToken = null)
public interface IConsole : System.CommandLine.IO.IStandardError, System.CommandLine.IO.IStandardIn, System.CommandLine.IO.IStandardOut
public abstract class Option : Symbol, System.CommandLine.Binding.IValueDescriptor
public CliAction Action { get; set; }
public System.Collections.Generic.ICollection<System.String> Aliases { get; }
public System.Boolean AllowMultipleArgumentsPerToken { get; set; }
public System.Boolean AppliesToSelfAndChildren { get; set; }
Expand All @@ -140,6 +140,7 @@ System.CommandLine
public class ParseDirective : Directive
.ctor(System.Int32 errorExitCode = 1)
public class ParseResult
public CliAction Action { get; }
public System.CommandLine.Parsing.CommandResult CommandResult { get; }
public CommandLineConfiguration Configuration { get; }
public System.Collections.Generic.IReadOnlyList<System.CommandLine.Parsing.ParseError> Errors { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,10 @@ private static RootCommand BuildCommand()
stringOption
};

command.SetHandler(ctx =>
command.SetAction(ctx =>
{
bool boolean = ctx.ParseResult.GetValue(boolOption);
string text = ctx.ParseResult.GetValue(stringOption);

return 0;
});

return command;
Expand Down
2 changes: 1 addition & 1 deletion src/System.CommandLine.DragonFruit/CommandLine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ public static void ConfigureFromMethod(
command.Arguments.Add(ArgumentBuilder.CreateArgument(argsParam));
}

command.Handler = CommandHandler.Create(method, target);
command.Action = CommandHandler.Create(method, target);
}

public static CommandLineBuilder ConfigureHelpFromXmlComments(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace System.CommandLine.Generator
[Generator]
public class CommandHandlerSourceGenerator : ISourceGenerator
{
private const string ICommandHandlerType = "System.CommandLine.ICommandHandler";
private const string CliActionType = "System.CommandLine.CliAction";

public void Execute(GeneratorExecutionContext context)
{
Expand Down Expand Up @@ -74,7 +74,7 @@ private static void GenerateHandlerClass(
int handlerCount)
{
builder.Append($@"
private class GeneratedHandler_{handlerCount} : {ICommandHandlerType}
private class GeneratedHandler_{handlerCount} : {CliActionType}
{{
public GeneratedHandler_{handlerCount}(
{invocation.DelegateType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)} method");
Expand Down Expand Up @@ -115,10 +115,10 @@ private class GeneratedHandler_{handlerCount} : {ICommandHandlerType}
}

builder.Append($@"
public int Invoke(global::System.CommandLine.Invocation.InvocationContext context) => InvokeAsync(context, global::System.Threading.CancellationToken.None).GetAwaiter().GetResult();");
public override int Invoke(global::System.CommandLine.Invocation.InvocationContext context) => InvokeAsync(context, global::System.Threading.CancellationToken.None).GetAwaiter().GetResult();");

builder.Append($@"
public async global::System.Threading.Tasks.Task<int> InvokeAsync(global::System.CommandLine.Invocation.InvocationContext context, global::System.Threading.CancellationToken cancellationToken)
public override async global::System.Threading.Tasks.Task<int> InvokeAsync(global::System.CommandLine.Invocation.InvocationContext context, global::System.Threading.CancellationToken cancellationToken)
{{");
builder.Append($@"
{invocation.InvokeContents()}");
Expand Down Expand Up @@ -170,7 +170,7 @@ private static void GenerateSetHandler(
builder.Append(@"
{");
builder.Append($@"
command.Handler = new GeneratedHandler_{handlerCount}(method");
command.Action = new GeneratedHandler_{handlerCount}(method");

if (methodParameters.Length > 0)
{
Expand Down
18 changes: 9 additions & 9 deletions src/System.CommandLine.Hosting.Tests/HostingHandlerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,17 +134,17 @@ public static async Task Invokes_DerivedClass()
service.StringValue.Should().Be("TEST");
}

public abstract class MyBaseHandler : ICommandHandler
public abstract class MyBaseHandler : CliAction
{
public int IntOption { get; set; } // bound from option
public IConsole Console { get; set; } // bound from DI

public int Invoke(InvocationContext context)
public override int Invoke(InvocationContext context)
{
return Act();
}

public Task<int> InvokeAsync(InvocationContext context, CancellationToken cancellationToken)
public override Task<int> InvokeAsync(InvocationContext context, CancellationToken cancellationToken)
{
return Task.FromResult(Act());
}
Expand All @@ -159,7 +159,7 @@ public MyCommand() : base(name: "mycommand")
Options.Add(new Option<int>("--int-option")); // or nameof(Handler.IntOption).ToKebabCase() if you don't like the string literal
}

public class MyHandler : ICommandHandler
public class MyHandler : CliAction
{
private readonly MyService service;

Expand All @@ -171,13 +171,13 @@ public MyHandler(MyService service)
public int IntOption { get; set; } // bound from option
public IConsole Console { get; set; } // bound from DI

public int Invoke(InvocationContext context)
public override int Invoke(InvocationContext context)
{
service.Value = IntOption;
return IntOption;
}

public Task<int> InvokeAsync(InvocationContext context, CancellationToken cancellationToken)
public override Task<int> InvokeAsync(InvocationContext context, CancellationToken cancellationToken)
{
service.Value = IntOption;
return Task.FromResult(IntOption);
Expand Down Expand Up @@ -209,7 +209,7 @@ public MyOtherCommand() : base(name: "myothercommand")
Arguments.Add(new Argument<string>("One") { Arity = ArgumentArity.ZeroOrOne });
}

public class MyHandler : ICommandHandler
public class MyHandler : CliAction
{
private readonly MyService service;

Expand All @@ -223,9 +223,9 @@ public MyHandler(MyService service)

public string One { get; set; }

public int Invoke(InvocationContext context) => InvokeAsync(context, CancellationToken.None).GetAwaiter().GetResult();
public override int Invoke(InvocationContext context) => InvokeAsync(context, CancellationToken.None).GetAwaiter().GetResult();

public Task<int> InvokeAsync(InvocationContext context, CancellationToken cancellationToken)
public override Task<int> InvokeAsync(InvocationContext context, CancellationToken cancellationToken)
{
service.Value = IntOption;
service.StringValue = One;
Expand Down
12 changes: 6 additions & 6 deletions src/System.CommandLine.Hosting.Tests/HostingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ void Execute(IHost host)
}

var config = new CommandLineBuilder(
new RootCommand { Handler = CommandHandler.Create<IHost>(Execute) }
new RootCommand { Action = CommandHandler.Create<IHost>(Execute) }
)
.UseHost()
.Build();
Expand Down Expand Up @@ -76,7 +76,7 @@ void Execute(IHost host)
}

var config = new CommandLineBuilder(
new RootCommand { Handler = CommandHandler.Create<IHost>(Execute) }
new RootCommand { Action = CommandHandler.Create<IHost>(Execute) }
)
.UseHost()
.Build();
Expand Down Expand Up @@ -108,7 +108,7 @@ void Execute(IHost host)
var config = new CommandLineBuilder(
new RootCommand
{
Handler = CommandHandler.Create<IHost>(Execute),
Action = CommandHandler.Create<IHost>(Execute),
})
.UseHost(host =>
{
Expand Down Expand Up @@ -145,7 +145,7 @@ void Execute(IHost host)
var config = new CommandLineBuilder(
new RootCommand
{
Handler = CommandHandler.Create<IHost>(Execute),
Action = CommandHandler.Create<IHost>(Execute),
})
.UseHost(args =>
{
Expand Down Expand Up @@ -184,7 +184,7 @@ void Execute(IHost host)
var config = new CommandLineBuilder(
new RootCommand
{
Handler = CommandHandler.Create<IHost>(Execute)
Action = CommandHandler.Create<IHost>(Execute)
})
.UseHost()
.Build();
Expand All @@ -203,7 +203,7 @@ public static void UseHost_binds_parsed_arguments_to_options()

var rootCmd = new RootCommand();
rootCmd.Options.Add(new Option<int>($"-{nameof(MyOptions.MyArgument)}"));
rootCmd.Handler = CommandHandler.Create((IHost host) =>
rootCmd.Action = CommandHandler.Create((IHost host) =>
{
options = host.Services
.GetRequiredService<IOptions<MyOptions>>()
Expand Down
12 changes: 6 additions & 6 deletions src/System.CommandLine.Hosting/HostingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public static OptionsBuilder<TOptions> BindCommandLine<TOptions>(

public static IHostBuilder UseCommandHandler<TCommand, THandler>(this IHostBuilder builder)
where TCommand : Command
where THandler : ICommandHandler
where THandler : CliAction
{
return builder.UseCommandHandler(typeof(TCommand), typeof(THandler));
}
Expand All @@ -100,9 +100,9 @@ public static IHostBuilder UseCommandHandler(this IHostBuilder builder, Type com
throw new ArgumentException($"{nameof(commandType)} must be a type of {nameof(Command)}", nameof(handlerType));
}

if (!typeof(ICommandHandler).IsAssignableFrom(handlerType))
if (!typeof(CliAction).IsAssignableFrom(handlerType))
{
throw new ArgumentException($"{nameof(handlerType)} must implement {nameof(ICommandHandler)}", nameof(handlerType));
throw new ArgumentException($"{nameof(handlerType)} must implement {nameof(CliAction)}", nameof(handlerType));
}

if (builder.Properties[typeof(InvocationContext)] is InvocationContext invocation
Expand All @@ -114,10 +114,10 @@ public static IHostBuilder UseCommandHandler(this IHostBuilder builder, Type com
services.AddTransient(handlerType);
});

BindingHandler bindingHandler = CommandHandler.Create(handlerType.GetMethod(nameof(ICommandHandler.InvokeAsync)));
BindingHandler bindingHandler = CommandHandler.Create(handlerType.GetMethod(nameof(CliAction.InvokeAsync)));
// NullBindingHandler that accumulated services registered so far, before handler creation
bindingHandler.SetBindingContext(command.Handler is BindingHandler pre ? pre.GetBindingContext(invocation) : null);
command.Handler = bindingHandler;
bindingHandler.SetBindingContext(command.Action is BindingHandler pre ? pre.GetBindingContext(invocation) : null);
command.Action = bindingHandler;
bindingHandler.GetBindingContext(invocation).AddService(handlerType, c => c.GetService<IHost>().Services.GetService(handlerType));
}

Expand Down
Loading