From e3ab5c15ec7c8b26ec66b66604871c2d2c224d12 Mon Sep 17 00:00:00 2001 From: Ben Winston Date: Fri, 7 Jun 2024 22:36:45 -0400 Subject: detect unsupported fields while parsing search options --- booki.c | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) (limited to 'booki.c') diff --git a/booki.c b/booki.c index c780c44..aa25090 100644 --- a/booki.c +++ b/booki.c @@ -13,6 +13,28 @@ #define MAX_SEARCH_OPTS 5 +enum DataType { booki_string, booki_number }; + +typedef struct DataField DataField; + +struct DataField { + char* name; + enum DataType type; +}; + +static const DataField BOOK_FIELDS[] = { + { "title", booki_string }, + { "author", booki_string }, + { "isbn", booki_string }, + { "pages", booki_number }, + { "published", booki_number }, + { "language", booki_string }, + { "translator", booki_string }, + { "on", booki_string } +}; + +#define BOOK_FIELDS_COUNT (sizeof(BOOK_FIELDS) / sizeof(BOOK_FIELDS[0])) + /*** helpers ***/ char* characters_from_end(char* str, int len_in_bytes, int number_of_chars) { assert(len_in_bytes >= number_of_chars); @@ -765,13 +787,27 @@ struct search_opt parse_search_options(int argc, char* argv[]) { edit = true; break; case '?': + // detect if we didn't get an operand if (!argv[optind] || argv[optind][0] == '-') { printf("%s requires an operand\n", argv[optind-1]); opt_out.count = -1; return opt_out; } + // detect if we got a field we don't recognize + char* no_dashes = argv[optind-1] + 2; // '--example' -> 'example' + int i = 0; + for (; i < BOOK_FIELDS_COUNT; i++) { + if (strcmp(no_dashes, BOOK_FIELDS[i].name) == 0) + break; + } + if (i == BOOK_FIELDS_COUNT) { + printf("%s is unrecognized\n", argv[optind-1]); + opt_out.count = -1; + return opt_out; + } + // optind points at the argument (one past the option) - opt_out.opts[count] = argv[optind-1] + 2; // '--example' -> 'example' + opt_out.opts[count] = no_dashes; opt_out.args[count] = argv[optind]; count++; break; -- cgit v1.2.3