TeXitoi / structopt

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

Short-hands boolean #468

Closed Milo123459 closed 3 years ago

Milo123459 commented 3 years ago

I want to make it so I can do -d or --dry, i know how to do alias' but I don't want to make it so you have to specify true. For example: --dry would mean it is true --dry true would mean it is true without the flag it'd be false.

TeXitoi commented 3 years ago
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
struct Opt {
    #[structopt(long, short, min_values(0), max_values(1), possible_value("true"))]
    dry: bool,
}

fn main() {
    println!("{:?}", Opt::from_args());
}

But I suspect you also want to support -d false, and I don't have the tricky idea just now.

Milo123459 commented 3 years ago

Yes, I do want -d false, and do you mean that's not possible in the lib right now? or, you haven't got it off the top of your head

TeXitoi commented 3 years ago

That's not really made for that, but a workaround might exists.

TeXitoi commented 3 years ago
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
struct Opt {
    #[structopt(long, short)]
    dry: Option<Option<bool>>,
}
impl Opt {
    fn dry(&self) -> bool {
        match self.dry {
            None => false,
            Some(None) => true,
            Some(Some(a)) => a,
        }
    }
}

fn main() {
    println!("{:?}", Opt::from_args().dry());
}

Not so elegant, but works.

Milo123459 commented 3 years ago

Thanks for the help 😉