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