ArgumentsimprovementsIsFirstOrFlagwill now allow simpler checks to verify if a command was entered as named parameter or vise-versa.HasFlagnow has an overload that accepts aliases.- All overloads and options will be be
CurrentCultureaware.
CliMetadatanow defaults to keeping every property as empty string.- This is so that the global help text will only output the overridden properties.
CliBuilder.ConfigureEmptyInputBehaviorwas removed.- If there is a single command - it will be executed.
- If there are multiple commands - global help text will be shown.
- You can override this behavior simply by using
if (args.Length == 0) args = ["--help"];for example.
- Both
HelpandVersionare no first-class internal commands that the builder injects automatically.Helpwas improved and more accurately displays information.Versionwill now just displayCliMetadata.Versionso make sure to override it for it to function well.
Parserhad many improvements that should result in more consistency, correctness, and better performance.- General performance improvements.
WARNING: This release may contain breaking changes.
- The
Argumentssource collection has been rewritten as aReadOnlyCollection<string>, which cascaded into numerous changes:Parser.ParseArguments(collection-based overloads) now takes a genericIList<string>. This is converted internally to aReadOnlyCollection<string>, which is used as the source forArguments.- As a result,
Parser.Splitnow returns aList<string>. - The
Parser.SplitToListmethod was removed, as it is no longer needed. Arguments.ArgsAsMemoryandArguments.ArgsAsSpanwere also removed. To inspect the source, useArguments.Sourceor obtain a copy as astring[]withArguments.SourceCopy.- The
CliRunner.RunAsyncoverload that previously accepted aReadOnlySpan<string>now accepts anIList<string>instead. This allows implicit casting from bothstring[]andList<string>, which are the most common CLI inputs.
HelpTextgenerators now use aStringBuilderinternally, replacing the previous custom buffer. Since help text generation typically occurs only once during a CLI's lifetime, any potential performance impact is minimal. This also removes some logical size restraints.- Removed
Microsoft.SourceLink.Githubas it is now used implicitly.
These changes enable several improvements:
Sharpifyis no longer a required dependency of this package and has been removed. This package can now be installed as a standalone.- Creating an
Argumentsobject withParser.ParseArgumentsis now much simpler. You can use it directly without commands to create minimal CLIs inProgram.cs. This will be particularly useful with the upcoming.NET 10feature allowing direct execution of.csfiles. (A demo video with examples and best practices will be released when this feature is available.)
- Updated to support NET9 with
Sharpify2.5.0 - Optimized path of
Argumentsforwarding when no positional arguments are present.
- Optimized
Parser:Splitnow rents a buffer the array pool by itself and returns aRentedBufferWriter<string>, this enables greater flexibility in usage, and simplifies the code.- Changed lower level array allocation code to use generalized api to optimize on more platforms.
Arguments.TryGetValueandArguments.TryGetValuesnow have overloads that accept aReadOnlySpan<string> keys, this overload enables much simpler retrieval of parameters that have aliases, for example you might want something like--nameand-nto map to the same value.- If you specify the aliases using the collections expression (i.e
["one", "two"]), since .NET 8, the compiler will generate an inline array for that, which is very efficient, you don't need to create an array yourself. but if you wanted to to you could for example create astatic readonly ReadOnlySpan<string> aliases => new[] { "one", "two" };and pass that instead, the compiler optimizes such case by writing the values directly in the assembly.
- If you specify the aliases using the collections expression (i.e
CliBuildernow has an option to configure arguments case sensitivity usingConfigureArgumentsCaseHandling, by default arguments are case insensitive to prioritize user experience. however, if you want to have parameters that are case sensitive, for instances where you need more short flags likegrepyou can opt in for this feature by setting it to be case sensitive.CliBuildercan now configure how to handle empty inputs withConfigureEmptyInputBehavior, by default it will display the help text and exit, but you can configure it to attempt to proceed with handling the commands, if a single command is used and command name is set to not required, this will execute the command with empty args, otherwise it will display the appropriate error message.- This is a change in behavior, as previously by default an error showing that no command was found was displayed, but seems that showing the help text in those situations is the more common approach in modern CLIs.
- Updated parsing to detect cases where arguments start with
-and are not names of arguments, for example if you required a positional argument of typeintand the input was a negative number (also starts with-), it would've been interpreted as a named argument, now it will be correctly interpreted as a positional argument.- The rule now also checks if the first character following a
-is a digit, if it is, it will not be marked as named argument. Which means - don't use argument names that start with digits (this is a bad practice in general).
- The rule now also checks if the first character following a
- Help text no contains a special case for "version" and "--version" that will just display the version from metadata.
- Help text (from main) now has specialized structure for cases where you only have one command, instead of printing commands and descriptions, it will print the single command usage - the rest will of the whole cli (metadata)
- To support
--versionand add more customization options, nowMetadataandCustomHeaderare independent, and you can configure which is used for help text withSetHelpTextSource(HelpTextSource).Metadatawill be used by default. - The help text portion that used to display instruction to get help text is now shorter and more concise.
Argumentsnow has overload to directly get the values that correspond toTryGetValueoverloads with default values, since defaults values can be returned if no key was found or failed to be parsed, In some case the actual reason is not important and only the value is needed so we now haveGetValuefor this exact reason.
Argumentsnow contains new methodsTryGetValuesandTryGetValues{T}to get arrays from values, there are overloads for regular and positional arguments, each overload requires astring? separatorthat is used to split the value, as with te regular values,Tneeds to implementIParsable{T}.CliBuildernow has a methodShowErrorCodesthat will enable the error codes next toCliRunnererror outputs, that was previously enabled by default, now it will hide them by default to provide a cleaner experience for users, but the builder now can easily configure this for testing, or if you still want the user to see them.
- Rewritten core function of argument forwarding to fix issue that caused non-positional arguments to be removed, now named arguments and flags should not be affected by positional forwarding at all.
- Important note: the
Argsarray that is stored within theArgumentsobject, is never modified and no matter how many positional forwarding iterations have been executed, it maintains the original arguments.
- Important note: the
- Added
Arguments.HasFlag(string)method that could be used to specifically checks for flags.- Previously
Arguments.Contains(string)could be used for this purpose, but it could also returntruefor a named argument, effectively allowing a false-positive.HasFlagprevents this by checking that if it exists, the value is empty, which could only be the case for flags.
- Previously
- Increased buffer size for help-text generation to prevents issues with complex clis.
In case you are writing a cli which has a complex tree to navigate on the way to the execution, such as nested commands, and any single command processing gets verbose, remember that it is possible to create a CliRunner at any point.
This means that you can create objects for the nested commands, inside the top level command you could then forward the positional arguments (or not) if you choose, then use the same builder pattern with CliRunner.CreateBuilder()... and add the nested commands, then execute using the already parsed Arguments object as the CliRunner.RunAsync also has an overload that accepts Arguments.
- Updated core to use
Sharpify2.0.0 - small optimizations
Arguments's internal copy of the parsed args is now an array, this change was necessary to avoid special cases where the backing array was garbage collected leaving a phantom view. To get a read only copy you can use.ArgsAsSpanor.ArgsAsMemoryaccording to your preference or use case.- Improved
Parser's mapping function's stability, and also further reworked it to allow positional arguments after named ones, now positional arguments can be anywhere.- A special case that needs consideration before usage is switches, i.e boolean toggle parameters, as they look like named parameters without values. If such "switch" is followed by a regular value, it will be regarded as a named parameter and its value, as opposed to a switch and a positional argument. Keep this in mind when you decide the arrangement of input arguments, to ensure your input works as intended.
- Switches work well, either when they are followed by other named arguments, or other switches. For simplicity, it is best to leave them as the last arguments.
- Added a new
SynchronousCommandas an alternative toCommand, it is basically syntactic sugar that makes it so you can implement anExecutemethod instead, in which you can return anint, whenasyncis not needed, this can save multiple lines of code that just wrapints inValueTask.FromResultwhich can be quite verbose.
DoNotIncludeMetadataInHelpTextwas removed, instead it will not be included by default.ModifyMetadatawas renamed toWithMetadataand if used, will modify the defaultCliMetadataand include it in the help text.- Added
WithCustomHeader(string)as an alternative to usingCliRunnerMetadata, there will be no exception when both are used, but in that case,CliRunnerMetadatahas priority and will be the only one displayed. - Added
SortCommandsAlphabetically, which if specified will sort the commands alphabetically by name in the general help text, other than the help text, it has virtually no affect. Not specifying this, gives you control over the order, it will be exactly in the order that you added the commands and order of existing collection (if you added any commands via a collection).
- Overloads of
TryGetValue<TEnum>were modified to add an option toignoreCase, to make it more user friendly and still adhere to parameter placement guidelines, more overloads were added.
- Added a
ReadOnlyMemory{string}which is a copy of the arguments split up before being parsed toArguments, it can be retrieved by theArguments.PureArguments, in special cases in which you might create a nested command structure, which requires a partial parsing, then secondary parsing within a command, this can be very powerful as you can create a secondaryCliRunnerand pass any subsequence of those arguments to recreate an input. - Overloads of
Arguments.GetValuewhich take anintaspositional argument, now that parameter renamed to bepositionto better signify what the overloads mean, it is a rather cosmetic change, but nevertheless. - Add a
Arguments.Contains(int)overload to match with the rest of the methods and suitpositional arguments.
- Added missing line break in global help text
- If the single word help is entered, it will now be recognized in place of command name to return the global help text, instead of trying to be parsed as a command.
- Updated
Sharpifydependency and implemented usage of new APIs to aid in maintainability. - Add
DoNotIncludeMetadataInHelpText()inCliBuilderwhich removes the metadata inclusion in the general help text.
- Removed thread-local
StringBuilderfromCliRunner, replaced all usages withStringBufferfromSharpify
- Updated
Sharpifydependency - Slightly improved performance of general help text generator
Initial version - no changes