TeXitoi / structopt

Parse command line arguments by defining a struct.
Other
2.71k stars 151 forks source link

question: how do i make an argument apply to all subommands? #442

Closed EverlastingBugstopper closed 4 years ago

EverlastingBugstopper commented 4 years ago

from structopt docs:

structopt also provides support for applications where certain flags need to apply to all subcommands, as well as nested subcommands:

this sounds perfect!! except... the example that follows doesn't particularly describe what i'd expect it to.


i have an app that is built up with subcommands:

#[derive(Debug, StructOpt)]
pub struct MyApp {
    #[structopt(subcommand)]
    command: Command,
}
#[derive(Debug, StructOpt)]
pub enum Command {
    Run(Run),
}

#[derive(Debug, StructOpt)]
pub struct Run {
    #[structopt(subcommand)]
    command: NestedSubcommand,
}

#[derive(Debug, StructOpt)]
pub enum NestedSubcommand {
    Set(u64),
    Clear,
}

What I want to do is to add an argument that can be accepted by any subcommand that alters the log level of the entire app, so my instinct was to just add that field to the MyApp struct at the top level.

#[derive(Debug, StructOpt)]
pub struct MyApp {
    #[structopt(long = "log", short)]
    pub log_level: tracing_core::Level,

    #[structopt(subcommand)]
    command: Command,
}

With this setup, I'd expect to be able to run a command like this: cargo run -- run set 5 --log debug or cargo run -- run clear --log warn, but when I do that, I get error: Found argument '--log' which wasn't expected, or isn't valid in this context

It works just fine if I put the --log at the very front, like this: cargo run -- --log debug run set 5 or cargo run -- --log warn run clear, but... that's not really how I want users to have to specify the argument. Any ideas are super appreciated!

TeXitoi commented 4 years ago

maybe https://docs.rs/clap/2.33.3/clap/struct.Arg.html#method.global ?


#[derive(Debug, StructOpt)]
pub struct MyApp {
    #[structopt(long = "log", short, global = true)]
    pub log_level: tracing_core::Level,

    #[structopt(subcommand)]
    command: Command,
}
EverlastingBugstopper commented 4 years ago

that works perfectly!!!! thanks :smile: