epage / clapng

A full featured, fast Command Line Argument Parser for Rust
docs.rs/clap
Apache License 2.0
0 stars 0 forks source link

Parse arguments before or after subcommands ambivalently #245

Open epage opened 2 years ago

epage commented 2 years ago

Issue by 9999years Thursday Dec 02, 2021 at 21:14 GMT Originally opened as https://github.com/clap-rs/clap/issues/3056


Please complete the following tasks

Clap Version

2.34, but I don't think this is a feature in 3.0 either.

Describe your use case

I'd like to be able to pass args at any position before or after subcommands. This is a quality-of-live improvement for users of command-line tools.

Consider the following App:

use clap::{App, Arg, Subcommand};
App::new("prog")
    .arg(Arg::with_name("a").short("a"))
    .subcommand(SubCommand::with_name("cmd").arg(Arg::with_name("b").short("b")))

prog -a cmd -b will parse, but prog -a -b cmd and prog cmd -a -b will not. In my opinion, this makes the command-line interface more cumbersome:

Describe the solution you'd like

Adding a clap::AppSettings variant seems like the natural way to alter parsing behavior:

App::new("prog")
    .setting(AppSettings::ArgsBeforeOrAfterSubcommands)
    // ...

Alternatives, if applicable

A more granular API could use an ArgSettings instead:

App::new("prog")
    .arg(Arg::with_name("a").short("a").set(ArgSettings::BeforeOrAfterSubcommands))

Additional Context

I'm not familiar with clap's implementation, and it occurs to me that the parser might be structured such that it would be difficult or resource-intensive to alter the parser to recognize subcommand args before the subcommand token itself.

The parser would have to know about and check all the subcommand-args before parsing, or otherwise determine which subcommand is going to be used -- which I think may be tricky, because determining if bar is a subcommand in prog --foo bar would require knowing if --foo takes a value or not.

This change would also make certain patterns that are currently allowed ambiguous, such as having a top-level argument and a subcommand argument with the same name (and impossible to parse if, for example, one takes a value and the other doesn't).

My immediate questions about this feature request are:

epage commented 2 years ago

Comment by epage Thursday Dec 02, 2021 at 21:26 GMT


While not quite what you are asking for,

(leaving it to others to weigh in on whether this is desirable or not)