Cocona icon indicating copy to clipboard operation
Cocona copied to clipboard

Global option/flag?

Open Manuel-S opened this issue 3 years ago • 7 comments

I want to control the loglevel based on a command line argument, for example if I provide -v the loglevel would be set to Information.

I didn't find anything in Cocona that would let me do that, besides adding that option to every single command or parsing the command line arguments manually.

What I would like to do is along the lines of:

app.AddFlag("v", () => builder.Logging.SetMinimumLevel(LogLevel.Information))
    .WithDescription("verbose");

or

app.AddGlobal(([Option("v", "verbose")]bool verbose) => if (verbose) builder.Logging.SetMinimumLevel(LogLevel.Information));

Both would be run like a filter before any command, but the difference is that they add options, and would show up in the help like so:

Usage: SubCommandApp [command] [-v]
Usage: SubCommandApp [--help] [--version] [-v]

...

Options:
  -h, --help         Show help message
  -v                 (Global) verbose
  --version          Show version

Manuel-S avatar Feb 08 '22 12:02 Manuel-S

I believe that you are looking for Parameter Sets.

icalvo avatar Feb 08 '22 23:02 icalvo

The point with parameter sets is that I have to repeat the logic in every command, which is something I wanted to avoid.

Manuel-S avatar Feb 09 '22 08:02 Manuel-S

The demand for a global flag such as -v or --verbose is understandable.

However, what I am wondering is how to pass the value of the global flag to the application. This is not a command, nor is it an option of a command. It is more like a filter/middleware before the command is executed.

mayuki avatar Feb 09 '22 11:02 mayuki

Yes, essentially a middleware that can specify options.

Manuel-S avatar Feb 09 '22 11:02 Manuel-S

How about passing the Parameter Set to the command filters? For example as a property of CoconaCommandExecutingContext.

icalvo avatar Feb 09 '22 12:02 icalvo

That would solve the specific problem, but would feel less elegant than defining a middleware because I'd still have unused parameters in every command definition, where it's not immediately clear why they are even there.

Manuel-S avatar Feb 10 '22 13:02 Manuel-S

In the library System.CommandLine designed by Microsoft has a definition of RootCommand that works as simple as a normal command. It accepts options, arguments, sub-command, custom help or whatever a typical command can do. The most special thing seems to be that it has the first priority of an application.

Is it possible, if Cocona implements the RootCommand concept what runs before all other commands?

Code example:

var builder = CoconaApp.CreateBuilder(args, rootCommand, options);
var app = builder.Build();
 
// Or add root command manually
app.AddRootCommand<RootCommand>();
 
app.Run();

voxvanhieu avatar Jan 04 '24 09:01 voxvanhieu