Search code examples
rustclap

What are valid characters and how to escape in clap.rs arguments?


I want to pass in some shape or form a dictionary/map/object into my clap app. I can preprocess the dict to turn it into some csv or whatever. My problem is that I cannot find in clap docs which characters are valid for the argument values and how to escape them. Is this unrelated to clap and instead shell specific?

Can I pass something like

myApp --dicty="a=1,b=3,qwe=yxc"

?


Solution

  • Is this unrelated to clap and instead shell specific?

    Mostly, yes. clap is going to get whatever arguments the shell has determined and will parse that.

    However clap has built-in support for value sets, from the readme:

    • Supports multiple values (i.e. -o <val1> -o <val2> or -o <val1> <val2>)
    • Supports delimited values (i.e. -o=val1,val2,val3, can also change the delimiter)

    If that's not sufficient, then you'll have to define dicty as a String, you will receive the string a=1,b=3,qwe=yxc (I don't think you'll receive the quotes) then you'll have to parse that yourself, either by hand (regex/split/...) or with something more advanced (e.g. the csv crate though that's likely overkill).

    That seems like a somewhat odd option value though.

    FWIW structopt (which builds upon clap to provide a more declarative UI, and should be part of Clap 3) doesn't exactly have support for that sort of things but can be coerced into it relatively easily: https://github.com/TeXitoi/structopt/blob/master/examples/keyvalue.rs

    With some modifications would allow something like

    myApp -D a=1 -D b=3 -D que=yxc
    

    or (though see comments in linked snippet for limitations)

    myApp -D a=1 b=3 que=yxc
    

    to be collected as a vec![("a", "1"), ("b", "3"), ("que", "yxc")] from which creating a hashmap is trivial.