Add iterator-style API
authorSimon Marchi <simon.marchi@efficios.com>
Sat, 10 Apr 2021 13:51:38 +0000 (09:51 -0400)
committerPhilippe Proulx <eeppeliteloop@gmail.com>
Mon, 31 May 2021 20:13:52 +0000 (16:13 -0400)
commitfc07e5264804963a3de6d1b929a9eb4fd37e49d4
treeeb1b104f6afade79783652a501287c8ad3304605
parenta99ee691baf201d91c8a2f7e727de22e9d4b8bb5
Add iterator-style API

The current API of argpar does not give the user control on when to stop
parsing the arguments.  It either stops at the end of the argument list
or at the first unknown option, if using `fail_on_unknown_opt`.

To make it more convenient to implement "multi-level" command line
interfaces, add an iterator-style API where the user repeatedly calls a
function to get the next item.

By "multi-level" CLI, I mean something like git, where the top-level
command and a subcommand have their own set of options.

    $ top-level --hello there sub-command --hello

For most cases, we could probably work something out by using the
`fail_on_unknown_opt` option combined with the
`argpar_item_non_opt::orig_index` field.  Even if the parsing of the
top-level command goes too far, we can resume the parsing at the index
of the sub-command + 1.  But the example above shows a corner case where
top-level's `--hello` option takes an argument but sub-command's
`--hello` doesn't.  I don't think we could handle this today.

In any case, I think that it's simpler in the end to give a bit more
control to the user and let her get items one by one.  I think it
results in code that is easier to follow.

Using the proposed API, the user starts by creating an argpar_iter
object using argpar_iter_create.  It then calls argpar_iter_parse_next
as much as needed to get one argpar_item at a time.  The returned
argpar_items must be freed with argpar_item_destroy.  In the end, the
argpar_iter must be freed with argpar_iter_destroy.

Testing-wise, I adapted the existing tests to be executed with both
APIs, so the coverage should be pretty good.

Change-Id: I82685672977fbfa96f96bcc678a3e05c6adab76c
Signed-off-by: Simon Marchi <simon.marchi@efficios.com>
argpar/argpar.c
argpar/argpar.h
tests/test_argpar.c
This page took 0.025379 seconds and 4 git commands to generate.