commandlineparser / commandline

The best C# command line parser that brings standardized *nix getopt style, for .NET. Includes F# support
MIT License
4.53k stars 477 forks source link

Is it possible to use repeated non-option-argument options? #631

Open ClaytonHughes opened 4 years ago

ClaytonHughes commented 4 years ago

ssh, tar, and other common tools allow for multiple non-option-argument options and act on their total count. (Implementing this with getopt is pretty trivial).

e.g. tar -cvf and tar -cvvf produce different output.

Is there a way to do this with CommandLine? I did not see anything promising in the documentation or examples/source code I perused, but I may have missed something.

(This might just be related to #594, but the issue there seems to be with repeated options with required option-arguments)

rmunn commented 4 years ago

PR #607 (not yet merged) includes a feature that would enable the use of -vv and similar repeated non-option-argument options. It adds a new Option property called FlagCounter, which should be set on an int property:

[Option('v', "--verbose", FlagCounter=true)]
int Verbose { get; set; }

This will be 0 if the -v option was not passed, 1 if -v was passed, 2 if -vv or -v -v was passed, and so on. If you want dueling --verbose and --quiet options, you could do it like this:

[Option('v', "--verbose", FlagCounter=true)]
int Verbose { get; set; }

[Option('q', "--quiet", FlagCounter=true)]
int Quiet { get; set; }

int Verbosity => Verbose - Quiet;  // C# 6 and up, see https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members#read-only-properties

Then your code could do something like:

if (options.Verbosity > 2) {
    LogDebug();
} else if (options.Verbosity == 2) {
    LogVerbose();
} else if (options.Verbosity == 1) {
    Log();
} else {
    DoNotLogBecauseQuietMode();
}

BTW, if you want to see #607 merged sooner, stop by #601 and express your opinion of whether CommandLineParser should follow the GNU standards (mixed options and non-option arguments by default) or the POSIX standards (stop processing after you find the first non-option argument) by default. That's the current sticking point that's delaying #607 getting merged.

rmunn commented 4 years ago

607 has been closed in favor of #684, which still includes the FlagCounter feature that I described.