You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Simplify custom parsers and default value factories #2053
Argument<T> provides multiple ways of setting default value: as T, Func<T> and Func<ArgumentResult, T>.
What I don't like is the fact that the last ctor requires the user to define whether given Func<ArgumentResult, T> is a default value provider or a custom parser. It's confusing. We need to find a way of providing Func<ArgumentResult, T> without specifying whether it's a default value provider or just a custom parser.
remove HasDefaultValue and HasCustomParser properties
we don't need isDefault, as users can just assing both properties to the same method
PTAL at the example below and let me know how do you feel about it.
Details
usingSystem.Collections;usingSystem.Runtime.InteropServices;namespaceSymbolCtors{internalclassProgram{staticvoidMain(string[]args){// Sample: "dotnet build"CommanddotnetBuild=newCommand("build"){newArgument<FileInfo?>("file"){Description="The project or solution file to operate on. If a file is not specified, the command will search the current directory for one.",DefaultValueFactory=(argumentResult)=>{FileInfo?first=newDirectoryInfo(Directory.GetCurrentDirectory()).EnumerateFiles("*.sln|*.proj").FirstOrDefault();if(firstisnull){argumentResult.AddError("Unable to find project or a solution file");}returnfirst;}},newOption<bool>("ucr","--ucr","--use-current-runtime"){Description="Use current runtime as the target runtime."},newOption<string>("FRAMEWORK","-f","--framework"){Description="The target framework to build for. The target framework must also be specified in the project file."},newOption<Architecture>("arch","-a","--arch"){Description="The target architecture.",ValueParser=(argumentResult)=>Enum.Parse<Architecture>(argumentResult.Tokens[0]),DefaultValueFactory=(_)=>RuntimeInformation.OSArchitecture,},newOption<string>("os","--os"){Description="The target operating system.",ValueParser=GetOsName,DefaultValueFactory=GetOsName,}};// an example of both a parser and a custom value providerstaticstringGetOsName(ArgumentResultargumentResult){if(argumentResult.Tokens.Count>0){stringprovided=argumentResult.Tokens[0];if(providedis"win" or "lin" or "osx"){returnprovided;}argumentResult.AddError($"Unknown Operating System: {provided}");}returnOperatingSystem.IsWindows()?"win":OperatingSystem.IsLinux()?"lin":"osx";}}}publicclassSymbol{publicstringName{get;}publicstring?Description{get;set;}privateprotectedSymbol(stringname){Name=name;}}publicclassArgument<T>:Symbol{publicArgument(stringname):base(name){}publicFunc<ArgumentResult,T>?DefaultValueFactory{get;set;}publicFunc<ArgumentResult,T>?ValueParser{get;set;}}publicclassOption<T>:Symbol{privatereadonlyArgument<T>_argument;publicOption(stringname,paramsstring[]aliases):base(name){_argument=newArgument<T>(name);}publicFunc<ArgumentResult,T>?DefaultValueFactory{get=>_argument.DefaultValueFactory;set=>_argument.DefaultValueFactory=value;}publicFunc<ArgumentResult,T>?ValueParser{get=>_argument.ValueParser;set=>_argument.ValueParser=value;}}publicclassCommand:Symbol,IEnumerable<Symbol>{privatereadonlyList<Symbol>_symbols;publicCommand(stringname,string?description=null):base(name){}publicvoidAdd(Symbolsymbol)=>_symbols.Add(symbol);publicIEnumerator<Symbol>GetEnumerator()=>_symbols.GetEnumerator();IEnumeratorIEnumerable.GetEnumerator()=>_symbols.GetEnumerator();}publicclassArgumentResult{publicList<string>Tokens{get;}=new();publicvoidAddError(stringerrorMessage){}}}
Per my comment here, I think we can make the API around names and aliases more intuitive by not requiring option constructors to provide both an unprefixed "name" and a mostly-matching prefixed "alias".
The term alias really refers to alternative names, so I think, for example, "--ucr" should be the name and "--use-current-runtime" an (optional) alias, or vice versa. This is the way I think most people understand the concepts. The fact that Option.Name removes the prefix passed to the constructor's name parameter is, at this point, a bug. It's a holdover from the naming convention lookups which were intended to be able to match method parameter names where - and / are invalid characters.
You are right, this example is wrong, it should not work in that way.
It's wrong because I've tried to replace ArgumentHelpName and Name with just Name without having good understanding of how ArgumentHelpName is used by the customers.
After looking at more SDK command help examples I am convinced that we need to keep HelpName.
Arguments:
<PROJECT | SOLUTION> The project or solution file to operate on. If a file is not specified, the command will search
the current directory for one.
Setting Argument.Name to "PROJECT | SOLUTION" feels weird to me.
I would just rename it to HelpName from ArgumentHelpName and make it a part of every Symbol type.
Updated proposal:
Details
usingSystem.Collections;usingSystem.Runtime.InteropServices;namespaceSymbolCtors{internalclassProgram{staticvoidMain(string[]args){// Sample: "dotnet build"CommanddotnetBuild=newCommand("build"){newArgument<FileInfo?>("file"){Description="The project or solution file to operate on. If a file is not specified, the command will search the current directory for one.",HelpName="PROJECT | SOLUTION",DefaultValueFactory=(argumentResult)=>{FileInfo?first=newDirectoryInfo(Directory.GetCurrentDirectory()).EnumerateFiles("*.sln|*.proj").FirstOrDefault();if(firstisnull){argumentResult.AddError("Unable to find project or a solution file");}returnfirst;}},newOption<bool>("--use-current-runtime","--ucr"){Description="Use current runtime as the target runtime."},newOption<string>("--framework","-f"){Description="The target framework to build for. The target framework must also be specified in the project file.",HelpName="FRAMEWORK",},newOption<Architecture>("--arch","-a"){Description="The target architecture.",HelpName="arch",ValueParser=(argumentResult)=>Enum.Parse<Architecture>(argumentResult.Tokens[0]),DefaultValueFactory=(_)=>RuntimeInformation.OSArchitecture,},newOption<string>("--os"){Description="The target operating system.",HelpName="os",ValueParser=GetOsName,DefaultValueFactory=GetOsName,},newOption<bool>("--help"){Description="Show command line help.",// just to show that this syntax would be allowed if Aliases was a mutable collection wiith .Add methodAliases={"-h","-?"}}};// an example of both a parser and a custom value providerstaticstringGetOsName(ArgumentResultargumentResult){if(argumentResult.Tokens.Count>0){stringprovided=argumentResult.Tokens[0];if(providedis"win" or "lin" or "osx"){returnprovided;}argumentResult.AddError($"Unknown Operating System: {provided}");}returnOperatingSystem.IsWindows()?"win":OperatingSystem.IsLinux()?"lin":"osx";}}}publicclassSymbol{publicstringName{get;}publicstring?Description{get;set;}publicstring?HelpName{get;set;}privateprotectedSymbol(stringname){Name=name;}}publicclassArgument<T>:Symbol{publicArgument(stringname):base(name){}publicFunc<ArgumentResult,T>?DefaultValueFactory{get;set;}publicFunc<ArgumentResult,T>?ValueParser{get;set;}}publicclassOption<T>:Symbol{privatereadonlyArgument<T>_argument;privateHashSet<string>?_aliases,_hiddenAliases;publicHashSet<string>Aliases=>_aliases??=new(StringComparer.Ordinal);publicHashSet<string>HiddenAliases=>_hiddenAliases??=new(StringComparer.Ordinal);// Using "params" to avoid forcing users to allocate a new array//// An alternative is having a ctor with optional arguments// public Option(string name, string? firstAlias = null, string? secondAlias = null) : base(name)publicOption(stringname,paramsstring[]aliases):base(name){_argument=newArgument<T>(name);_aliases=newHashSet<string>(aliases,StringComparer.Ordinal);}publicFunc<ArgumentResult,T>?DefaultValueFactory{get=>_argument.DefaultValueFactory;set=>_argument.DefaultValueFactory=value;}publicFunc<ArgumentResult,T>?ValueParser{get=>_argument.ValueParser;set=>_argument.ValueParser=value;}}publicclassCommand:Symbol,IEnumerable<Symbol>{privatereadonlyList<Symbol>_symbols;privateHashSet<string>?_aliases,_hiddenAliases;publicHashSet<string>Aliases=>_aliases??=new(StringComparer.Ordinal);publicHashSet<string>HiddenAliases=>_hiddenAliases??=new(StringComparer.Ordinal);publicCommand(stringname,string?description=null):base(name){Description=description;}publicvoidAdd(Symbolsymbol)=>_symbols.Add(symbol);publicIEnumerator<Symbol>GetEnumerator()=>_symbols.GetEnumerator();IEnumeratorIEnumerable.GetEnumerator()=>_symbols.GetEnumerator();}publicclassArgumentResult{publicList<string>Tokens{get;}=new();publicvoidAddError(stringerrorMessage){}}}
Activity
adamsitnik commentedon Mar 1, 2023
My current best idea is following:
Argument<T>andOption<T>have only a single ctor that always requires the name to be provided in explicit way (Providing name should be mandatory when creating Argument<T> and Option<T> #2051, Introduce ParseResult.GetValue<T>(string name) #2052).params string[]so users don't need to allocate an array in explicit way every time they create anOption.By doing that we can:
HasDefaultValueandHasCustomParserpropertiesisDefault, as users can just assing both properties to the same methodPTAL at the example below and let me know how do you feel about it.
Details
jonsequitur commentedon Mar 1, 2023
Per my comment here, I think we can make the API around names and aliases more intuitive by not requiring option constructors to provide both an unprefixed "name" and a mostly-matching prefixed "alias".
For example, instead of this:
why not this:
The term alias really refers to alternative names, so I think, for example,
"--ucr"should be the name and"--use-current-runtime"an (optional) alias, or vice versa. This is the way I think most people understand the concepts. The fact thatOption.Nameremoves the prefix passed to the constructor'snameparameter is, at this point, a bug. It's a holdover from the naming convention lookups which were intended to be able to match method parameter names where-and/are invalid characters.KalleOlaviNiemitalo commentedon Mar 2, 2023
How do hidden aliases (#1859) fit into this API?
adamsitnik commentedon Mar 2, 2023
@jonsequitur big thanks for a very detailed answer, it was very helpful.
I think that my understanding of what
Option.Namereally is (or what it was supposed to be originally) was wrong because:Nameonly in Help and when creating parse errors, but not for parsing as the main ID.Nameto the collection of aliases and treating it also as an alias (it makes some parts of the code simpler).Should separate
NameandAliasesconcepts, namely don't includeNameinAliasescollection?It would simplify the design of symbol types, as we would not need to check whether given alias can be removed in
RootCommand.RemoveAlias:command-line-api/src/System.CommandLine/RootCommand.cs
Lines 61 to 67 in 1e15ab1
and could be expressed as a single property, which would be a step forward removing
IdentifierSymboltype.public string Name { get; } + public HashSet<string> Aliases { get; } - public IReadOnlyCollection<string> Aliases { get; } - public void AddAlias(string alias) - private protected virtual void RemoveAlias(string alias) - public bool HasAlias(string alias)We would also not need to allocate a hashset of strings for symbols with no aliases (perf).
We could also easily differentiate the name and aliases.
And it would make it way easier to introduce hidden aliases, as it would be just a single new property:
We could also use a very fancy C# syntax:
The downside is that all the consumer of
Aliasesproperty would need to take this into account:+ tokens.Add(command.Name, new Token(command.Name, TokenType.Command, command, Token.ImplicitPosition)); foreach (string commandAlias in command.Aliases) { tokens.Add( commandAlias, new Token(commandAlias, TokenType.Command, command, Token.ImplicitPosition)); }But to be honest I don't expect 99% of our users to be hit by that change.
You are right, this example is wrong, it should not work in that way.
It's wrong because I've tried to replace
ArgumentHelpNameandNamewith justNamewithout having good understanding of howArgumentHelpNameis used by the customers.After looking at more SDK command help examples I am convinced that we need to keep
HelpName.Setting
Argument.Nameto "PROJECT | SOLUTION" feels weird to me.I would just rename it to
HelpNamefromArgumentHelpNameand make it a part of everySymboltype.Updated proposal:
Details