Commit | Line | Data |
---|---|---|
d50d200a SM |
1 | /* |
2 | * Copyright (C) 2021 Simon Marchi <simon.marchi@efficios.com> | |
3 | * | |
4 | * SPDX-License-Identifier: GPL-2.0-only | |
5 | * | |
6 | */ | |
7 | ||
8 | #ifndef COMMON_ARGPAR_UTILS_H | |
9 | #define COMMON_ARGPAR_UTILS_H | |
10 | ||
d50d200a | 11 | #include <common/argpar/argpar.h> |
28f23191 | 12 | #include <common/macros.hpp> |
c9e313bc | 13 | #include <common/string-utils/format.hpp> |
d50d200a | 14 | |
28f23191 JG |
15 | #include <stdarg.h> |
16 | ||
64803277 SM |
17 | #ifdef __cplusplus |
18 | extern "C" { | |
19 | #endif | |
20 | ||
e776cf47 SM |
21 | #define WHILE_PARSING_ARG_N_ARG_FMT "While parsing argument #%d (`%s`): " |
22 | ||
28f23191 | 23 | enum parse_next_item_status { |
d50d200a SM |
24 | PARSE_NEXT_ITEM_STATUS_OK = 0, |
25 | PARSE_NEXT_ITEM_STATUS_END = 1, | |
26 | PARSE_NEXT_ITEM_STATUS_ERROR = -1, | |
ef9ff9cb | 27 | PARSE_NEXT_ITEM_STATUS_ERROR_MEMORY = -2, |
d50d200a SM |
28 | }; |
29 | ||
30 | /* | |
31 | * Parse the next argpar item using `iter`. | |
32 | * | |
33 | * The item in `*item` is always freed and cleared on entry. | |
34 | * | |
35 | * If an item is parsed successfully, return the new item in `*item` and return | |
36 | * PARSE_NEXT_ITEM_STATUS_OK. | |
37 | * | |
38 | * If the end of the argument list is reached, return | |
39 | * PARSE_NEXT_ITEM_STATUS_END. | |
40 | * | |
41 | * On error, print a descriptive error message and return | |
42 | * PARSE_NEXT_ITEM_STATUS_ERROR. If `context_fmt` is non-NULL, it is formatted | |
43 | * using the following arguments and prepended to the error message. | |
35c4b2b3 | 44 | * Add `argc_offset` to the argument index mentioned in the error message. |
d50d200a SM |
45 | * |
46 | * If `unknown_opt_is_error` is true, an unknown option is considered an error. | |
47 | * Otherwise, it is considered as the end of the argument list. | |
ef9ff9cb SM |
48 | * |
49 | * If `error_out` is given and PARSE_NEXT_ITEM_STATUS_ERROR is returned, set | |
50 | * `*error_out` to the argpar_error object corresponding to the error. The | |
51 | * caller must free the object with `argpar_error_destroy`. | |
d50d200a | 52 | */ |
ef9ff9cb | 53 | ATTR_FORMAT_PRINTF(7, 8) |
d50d200a | 54 | enum parse_next_item_status parse_next_item(struct argpar_iter *iter, |
28f23191 JG |
55 | const struct argpar_item **item, |
56 | int argc_offset, | |
57 | const char **argv, | |
58 | bool unknown_opt_is_error, | |
59 | const struct argpar_error **error_out, | |
60 | const char *context_fmt, | |
61 | ...); | |
d50d200a SM |
62 | |
63 | #ifdef __cplusplus | |
64 | } | |
65 | #endif | |
66 | #endif |