New library: argparse, for parsing CLI arguments

Andrey Zherikov andrey.zherikov at gmail.com
Wed Oct 13 23:36:41 UTC 2021


On Wednesday, 13 October 2021 at 16:24:52 UTC, Steven 
Schveighoffer wrote:
> The point is that I shouldn't have to tell the library the name 
> of something that I've already given a name to.
>
> Having them named differently on the command line than the 
> actual field name should still be a possibility (and required 
> in some cases, e.g. the `enum` case above), but honestly, the 
> `Params` struct exists solely to accept command line 
> parameters, there's no compelling need to use alternate names 
> for the command line and the field name. If the library 
> automatically does the right thing by default, then your code 
> becomes simpler and more beautiful.
>
> Not to detract from your library, because I think it's an 
> awesome design to model using structs (one I use all the time), 
> but the API developer in me frowns at lack of DRY. Try to focus 
> on requiring the smallest amount of machinery/attributes 
> possible. Every time you require extraneous pieces to get 
> things to work, it adds another place where errors/confusion 
> can happen.

I got your point. Omitting the name is good suggestion and I'll 
add this.

Regarding the detecting all members and treating them as an 
arguments, I see one issues so far: the struct might have other 
members that are not used in CLI (it can be even functions).
Consider the example when the member is renamed but the struct 
still provides the old name for backward compatibility:
```d
struct T
{
     string name;

     @property string label() const { return name; }
}
pragma(msg, __traits(allMembers, T));   // tuple("name", "label")
```
Another example is when the struct has additional functions 
convenient for the users so it's not clear whether `void foo()` 
is a CLI flag or just a convenient function.

So to implement your suggestion correctly, `argparse` should 
provide a way to opt-out specific members from CLI.

In addition to that, each CLI argument usually has its own help 
text so in most cases each member will have an UDA with this text 
which makes opt-out approach mush less useful. So it sill look 
like this at the end:
```d
struct T
{
     @help("First name")
     string firstName;

     @help("Last name")
     string lastName;

     @skip
     @property string fullName() const { return firstName~" 
"~lastName; }
}
```



More information about the Digitalmars-d-announce mailing list