argparse icon indicating copy to clipboard operation
argparse copied to clipboard

Add support for exclusive/dependant arguments

Open f-michaut opened this issue 3 years ago • 3 comments
trafficstars

Some arguments are exclusive. Current workaround is to implement checks after the parsing like so :

[...]
program.parse_args(ac, av);

if (program.is_used("--foo") && program.is_used("--bar")) {
    throw "--foo and --bar are exclusive !";
}

Furthermore, some parameters often require others to be present in order to be meaningfull. Once again, we currently need to check manualy that both are given.


It would be nice to be able to use constructs like this :

program.add_argument("--line").needs("--file");
program.add_argument("--file").exclusive("--ip");
program.add_argument("--ip"); // No need to specify again that they are exclusive
program.add_argument("--port").needs("--ip").default_value(443);

try {
  program.parse_args(ac, av);
} catch (const std::runtime_error& err) {
  std::cerr << "Wrong arguments: " << err.what() << std::endl;
}

Usage :

# Good
./program --file /tmp/file
./program --file /tmp/file --line 25
./program --ip 8.8.8.8
./program --ip 8.8.8.8 --port 80

# Bad
./program --ip 8.8.8.8 --line 25
./program --line 25
./program --port 80
./program --file /tmp/file --port 80
./program --file /tmp/file --ip 8.8.8.8

f-michaut avatar Nov 06 '22 22:11 f-michaut

Added support for mutually exclusive arguments here: https://github.com/p-ranav/argparse/pull/301

p-ranav avatar Nov 04 '23 20:11 p-ranav

Thank you for adding exclusive arguments ! That's very helpfull.

Do you intend to add dependant arguments as well ?

f-michaut avatar Nov 11 '23 21:11 f-michaut

I think so, although I don't have a complete design yet.

p-ranav avatar Nov 12 '23 02:11 p-ranav