Search code examples
rustclap

How do I allow uppercase flags in Clap?


For my RUST program, I am using Clap to parse my command line arguments. I want to let users input flags like so:

my_program -L testfile.txt

I set up my struct like so:

struct Args {
    #[arg(short)]
    L: bool,

    #[arg(short)]
    s: bool,

    name: String,
}

When I test out my program, it gives me this error:

error: Found argument '-L' which wasn't expected, or isn't valid in this context.

I can't use ignore_case() either, since this is a flag and doesn't take a value.

Does anyone know how to solve this problem?


Solution

  • From Arg Attributes in the clap derive documentation:

    short [= <char>]: Arg::short

    • When not present: no short set
    • Without <char>: defaults to first character in the case-converted field name
    use clap::Parser;
    
    #[derive(Parser)]
    #[command(author, version, about, long_about = None)]
    struct Cli {
        #[arg(short = 'L')]
        L: bool,
    
        #[arg(short)]
        s: bool,
    
        name: String,
    }
    
    fn main() {
        let args = Cli::parse();
    }
    

    Built executable help:

    Usage: xxxxxx [OPTIONS] <NAME>
    
    Arguments:
      <NAME>
    
    Options:
      -L
      -s
      -h, --help     Print help information
      -V, --version  Print version information