Repository navigation
Description
System.CommandLine 2.0 Beta 4
We've been working through feedback on the beta 2 and beta 3 releases of System.CommandLine and now we're ready with beta 4. Here's a quick overview of what's new.
Microsoft Docs
Probably the most important update isn't in the API itself but in the release of preview documentation for System.CommandLine. It's been live now since April and, like the library, is in preview. There's a good deal of API to cover so if there's something that's missing or unclear, please let us know.
SetHandler simplification
The most common feedback we've heard about the SetHandler API introduced in beta 2 is that it's confusing, mainly because you can pass any number of IValueDescriptor<T> instances (e.g. Argument<T>, Option<T>, or BinderBase<T>) to the params IValueDescriptor[] parameter on most of the overloads, and this number can differ from the count of the handler's generic parameters.
I'll use this simple parser setup in the following examples:
var option = new Option<int>("-i");
var argument = new Argument<string>("-s");
var rootCommand = new RootCommand
{
option,
argument
};Here's an example of the old SetHandler signature:
// ⚠️ Now outdated
public static void SetHandler<T1, T2>(
this Command command,
Action<T1, T2> handle,
params IValueDescriptor[] symbols);The expectation was that in the common case, you would call this method like this:
rootCommand.SetHandler(
(int someInt, string someString) => { /* Do something exciting! */ },
option,
argument);But the fact that the final parameter to the old SetHandler methods was a params array meant that the following would compile and then fail at runtime:
// ⚠️ Now outdated
rootCommand.SetHandler((int someInt, string someString) => { /* Do something exciting! */ });The logic behind this method signature was that any handler parameters without a matching IValueDescriptor would be satisfied instead by falling back to BindingContext.GetService. This has been a longstanding way that dependency injection was supported for both System.CommandLine types such as ParseResult as well as for external types. But it's not the common case, and it's confusing.
We've changed the SetHandler methods to require a single IValueDescriptor<T> for each generic parameter T, rather than the previous params array:
public static void SetHandler<T1, T2>(
this Command command,
Action<T1, T2> handle,
IValueDescriptor<T1> symbol1,
IValueDescriptor<T2> symbol2);This has a number of benefits. In addition to making it clearer that you also need to pass the Option<T> and Argument<T> instances corresponding to the generic parameters, it also works with C# type inference to make your code a little more concise. You no longer need to restate the parameter types, because they're inferred:
rootCommand.SetHandler(
(someInt, someString) => { /* Do something exciting! */ },
option,
argument);We've also added overloads accepting InvocationContext, so if you want more detailed access for DI or larger numbers of options and arguments, you can do this:
rootCommand.SetHandler(
(context) => // InvocationContext, but it's inferred so you don't need to specify it.
{
var i = context.ParseResult.GetValueForOption(option);
var s = context.ParseResult.GetValueForArgument(argument);
var someDependency = context.GetService(typeof(ILogger)) as ILogger;
/* Do something exciting! */
});Finally, we've reduced the number of SetHandler overloads. Where before there were overloads supporting up to sixteen generic parameters, they now only go up to eight.
Option and Argument (non-generic) are now abstract
Support has existed since the earliest previews of System.CommandLine for creating non-generic Option and Argument instances that could be late-bound to a handler parameter. For example, an Argument could be created that could later be bound to either a string or an int parameter. This relied heavily on the reflection code that powered CommandHandler.Create, which was moved out of System.CommandLine and into the System.CommandLine.NamingConventionBinder package in beta 2. Fully removing support for this late-binding behavior by making Option and Argument abstract has helped simplify some code, clarify the API, and provided additional performance benefits.
Response file format unification
Response file support is a common feature of a number of command line tools, allowing a token within the command line to be replaced by inlining the contents of a file. You can think of a response file as a sort of configuration file that uses the same grammar as the command line tool itself. For example, given a file called response_file.rsp, the following command line will interpolate the contents of that file into the command line as if you had run it directly:
> myapp @response_file.rsp(The .rsp file extension is another common convention, though you can use any file extension you like).
Until this release, System.CommandLine supported two different formats for response files: line-delimited and space-delimited. Line-delimited response files are more common and thus were the default. If response_file.rsp contained the following:
# Make it verbose
--verbosity
very then it would be treated as though you had run this:
> myapp --verbosity very(Note following a #, the rest of the text on that line is treated as a comment and the parser will ignore it.)
This also provided a mechanism for avoiding the sometimes confusing rules of escaping quotes, which differ from one shell to another. You could produce a single token with a line-delimited response file by putting multiple words on a single line.
If response_file.rsp contained the following:
--greeting
Good morning! then it would be treated as though you had run this:
> myapp --greeting "Good morning!"System.CommandLine also supported another response file format, space-separated, where the content of the response file was expected to be all on a single line and was interpolated verbatim into the command line. This was not commonly used and we decided it would simplify the developer choice and make the behavior clearer for end users to unify the format.
The rules for the new format are as follows:
- Files can have many lines and content is treated as though concatenated into a single line.
- One or more tokens can appear on a single line.
- A line containing
Good morning!will be treated as two tokens,Goodandmorning!. - If multiple tokens are intended to be passed as a single token (e.g.
"Good morning!"), you must enclose them in quotes. - Shell-specific escaping rules are not used for the contents of a response file.
- Any text between a
#symbol and the end of the line is treated as a comment and ignored. - Tokens prefixed with
@can reference additional response files.
Custom token replacement
While we were trying to figure out how to make response file handling simpler, we saw that there are so many variations on how to parse response files that we could never provide a single implementation that could address them all. This could easily become a deal-breaker for people who have older apps that they would like to reimplement using System.CommandLine. So while we were consolidating response file handling, we also decided to generalize and hopefully future-proof the solution by adding a new extensibility point. After all, the core logic of response files is simple: during tokenization, a token beginning with @ is (possibly) replaced by zero or more other tokens.
If the default response file handling doesn't work for you, you can now replace it using the CommandLineBuilder.UseTokenReplacer method. The following example configures the parser to replace @-prefixed tokens with other tokens.
var parser = new CommandLineBuilder(command)
.UseTokenReplacer((string tokenToReplace, out IReadOnlyList<string> replacementTokens, out string errorMessage) =>
{
if (tokenToReplace == "fruits") // note that the leading '@' will already have been removed
{
replacementTokens = new [] { "apple", "banana", "cherry" };
errorMessage = null;
return true;
}
else
{
replacementTokens
errorMessage = null; // no parse error is created
return false; // tokenToReplace is not replaced
}
})
.Build();This token replacement happens prior to parsing, so just as with response files, the new tokens can be parsed as commands, options, or arguments.
If you return true from the token replacer, it will cause the @-prefixed token to be replaced. If you return false, it will be passed along to the parser unchanged, and any value you assign to the errorMessage parameter will be displayed to the user.
Given the above token replacement logic, an app will parse as follows:
> myapp @fruits # is parsed as: myapp apple banana cherry
> myapp @not-fruits # is parsed as: myapp @not-fruits It's worth noting that this behavior is recursive, just as with response files. If a replacement token begins with @, the token replacer will be called again to potentially replace that token.
Added support for NativeAOT compilation
Continuing the work done in beta 3 to make apps built using System.CommandLine trimmable, they can now also be compiled with Native AOT. For more details, you can read about Native AOT compilation in the .NET 7 Preview 3 announcement here: https://devblogs.microsoft.com/dotnet/announcing-dotnet-7-preview-3/#faster-lighter-apps-with-native-aot.
Activity
maxild commentedon Jun 3, 2022
If before beta 4, I used a lambda with "magic" IConsole parameter (for instance
(IConsole console, ...) => { /* code here */ }will I now have to use the InvocationContext based lambda, and use the GetValueForXXXX API to get the parsed option args?jonsequitur commentedon Jun 3, 2022
Yes. We wanted to limit the number of overloads. But it should be straightforward to define your own extension methods if you prefer to have the parameters for both injected objects and bound command line values in the same handler signature.
bording commentedon Jun 3, 2022
@jonsequitur So with beta 4, if I want access to the
IConsoleor a cancellation token, I have to use theInvocationContextoverload, correct?That seems to mean that there no way to use a custom model binder and have access to a cancellation token at the same time.
If that is true, then this seems like an odd backstep to me.
jonsequitur commentedon Jun 4, 2022
@bording The
InvocationContextshould give you access to everything you need. You can get to theIConsoleinstance usingInvocationContext.Consoleand you can get aCancellationToken(triggering Ctrl+C cancellation handling) by callingInvocationContext.GetCancellationToken().bording commentedon Jun 4, 2022
@jonsequitur I think you're missing my point. If I'm using the
InvocationContextoverload, how do I pass in my custom model binder? I've been able to abstract away the creation of several things that require multiple parameters and just get an instance of it in my handler through custom model binders.I'm currently using custom model binders, and injecting an
IConsoleand a cancellation token. In beta 4, it seems like an either/or scenario.bgever commentedon Jun 4, 2022
Before I was able to specify types on the handler that would automatically injected, and would resolve to the services registered in a middleware on startup.
So a Command class would look something like this:
But after this change I'm not able to easily inject both options/arguments and resolved services.
As a workaround, I made a small primitive class to inject services:
That allows me to write the code like this, what looks even cleaner;
SetHandler, andMaybe this type of Injectable helper can be added to the library?
WeihanLi commentedon Jun 4, 2022
Should I use the
Option<bool>instead ofOptionsince the theOptionisabstractnowjonsequitur commentedon Jun 4, 2022
Yes. When you declare options and arguments, you'll need to use
Option<T>andArgument<T>.You can use
OptionandArgument(or their base type,Symbol) when iterating over collections that might contain different generic types ofOption<T>andArgument<T>, e.g.:tomrus88 commentedon Jun 6, 2022
So what should I do now if I used one of removed overloads? I was passing 11 of
Option<T>into SetHandler.wuzzeb commentedon Jun 6, 2022
Now that options are required to be passed to SetHandler (I like this change), how about allowing us to omit also adding them directly to the command. In other words, any option passed to SetHandler is implicitly also added to the root command.
jonsequitur commentedon Jun 6, 2022
We've looked into this and while it works for the simple case, there are a number of cases where this API would lead to ambiguities. I outlined a few here: #1537 (comment)
jonsequitur commentedon Jun 6, 2022
@tomrus88, you can either use a custom
BinderBase<T>or theSetHandleroverloads with a delegate that accepts anInvocationContext. Both approaches are described here: https://docs.microsoft.com/en-us/dotnet/standard/commandline/model-binding#parameter-binding-more-than-8-options-and-argumentsNickStrupat commentedon Jun 7, 2022
Hi folks,
I needed the
CancellationTokenin my handlers but I wanted to use theSetHandlerhelper method. I came up with this class which provides theCancellationTokenas anIValueDescriptor<T>.Run
dotnet run -- name nickand useCTRL+Cbefore the 5 seconds wait is up to see the behaviour.FroggieFrog commentedon Jun 8, 2022
After updating from beta3 to beta4 I have several erros with the following snippet.
error
CS1643"Not all code paths return a value in lambda expression of typeFunc<int, bool, FileInfo, bool, IConsole, Task>"I can fix this by adding
await Task.CompletedTask;before the end and making the lambdaasync.after the first error is fixed there appears error
CS1501"No overload for methodSetHandlertakes 5 arguments"I tried to fix this by replacing
IConsolewithInvocationContext, but with no success.So this is my updated still not working code:
Is this no longer supported or do I use the library wrong?
28 remaining items
jonsequitur commentedon Sep 1, 2022
Many people asked for this so we simply exposed the internal mechanism that was already in place to support injection of System.CommandLine types. To your point, in the straw man example above,
Bind.FromServiceProvideris proposed as a way to wire up DI on a per-command basis and the implementation would be lazy.I expect all of these uses cases to remain intact through any API reworking to come. All three are valid preferences. Currently, the lambda is a shortcut to defining an
ICommandHandlerand matches the signature ofICommandHandler.InvokeAsync(InvocationContext). TheSetHandleroverloads are intended as convenience methods over that method. The same will be true of any source generator-driven approaches (#1829), potentially including attribute-decorated APIs. Attribute-decorated APIs have also been requested a number of times in the past but we've avoided them so as not to build reflection requirements into the parser.lonix1 commentedon Sep 2, 2022
Yes I quickly realised that's the problem here. There are so many stakeholders (many inside MS) and everyone wants something else, according to different design expecations. I don't envy you your job in this, must be tough to keep everyone happy. 😄
I think the lowest common denominator is to design an API that follows the Principle of Least Surprise, and implement weird requirements on top of that.
JamesNK commentedon Oct 17, 2022
IMO I think you should reconsider whether the pattern of
SetHandlerwith generic arguments is a good idea. Every 12 months I have update an app to the latest version of System.Commandline, and each time there is a lot of upgrade pain. I was usingSetHandlerwith generic arguments, which have been made progressively more and more restrictive.It's clear that the handler was originally designed to be dynamic and easy to use, but that conflicts with new requirements to make the library strongly typed and compatible with AOT. Unfortunately
SetHandlerhas had to change so much that it feels like as much work to use as pulling values out of theInvocationContextinside the handler, except more restrictive.Today I had to entirely drop using generic arguments everywhere because I need
InvocationContext. These two features are no longer compatible. A good design should allow for something to become progressively more complex. Recommending using generic arguments withSetHandlerfor simple scenarios, then requiring handlers to be rewritten to get values manually with a context isn't a good experience.Maybe
SetHandlerWithContextis a solution. Or always makeInvocationContextthe first argument, even with generic arguments. Or just not have generic argument overloads and always use the overload that just takes the context.gao-artur commentedon Nov 7, 2022
Thanks @NickStrupat, that worked! But make sure to call
.UseDefaults()on varclb = new CommandLineBuilder(root);otherwise you will lose help, argument validation, error code propagation, and who knows what else. The.UseDefaults()callsCancelOnProcessTerminationinternally so you can omit this from your code.davidcok commentedon Dec 12, 2022
For cases in which the help document describing all the options is quite long, there is a definite need to be able to control when the full help document is shown and when just an error message about the command-line is shown. Cf. #1214
micdah commentedon Mar 14, 2023
I encountered this issue also, but found a way around it.
By looking into the source code a bit for how values for options / arguments are retrieved, I wrote this extension class
With it, I can just
I suppose I could even just add my own extension methods to
Commandwith additionalSetHandlermethods taking more than 8 options / arguments - but this also works.Rather odd to have an arbitrary upper-bound on number of options / arguments, especially set at 8. Would have made sense to at least have a separate overload which allowed any number of options but less readable / friendly as with typed overloads - just to ensure cases where more than 8 is needed, are still possible, if not nearly as "neat" looking.
KalleOlaviNiemitalo commentedon Mar 14, 2023
@micdah, the SetHandler overloads were removed yesterday in #2089. There are now only Command.SetHandler(Action<InvocationContext>) and Command.SetHandler(Func<InvocationContext, CancellationToken, Task>), and the handlers have to query the values from InvocationContext, most conveniently using the InvocationContext.GetValue methods that were added in #1787.
InvocationContext itself is also going to be replaced with ParseResult, according to #2046 (comment).
maxandriani commentedon May 11, 2023
Same to me.
The BindingContext provides the Add Service that we use to register dependencies. But the lack of an IServiceCollection configuration step really difficult my job to register libraries that provides clean and simple extensions methods.
tksrc commentedon Sep 17, 2023
Sorry if asked before but when can we expect a GA release?
vladboss61 commentedon Dec 14, 2023
I think never we have the release of its. :D
We are going to leave in beta version until the end of the world.
tksrc commentedon Dec 14, 2023
Not ideal :)
Adding InvocationContext to overload SetHandler