diff options
| author | Ben Winston | 2024-06-07 22:36:45 -0400 |
|---|---|---|
| committer | Ben Winston | 2024-06-07 22:36:45 -0400 |
| commit | e3ab5c15ec7c8b26ec66b66604871c2d2c224d12 (patch) | |
| tree | af1bc36c4232324d981e755a98e09f5778316459 | |
| parent | ea9226df0bd7e820d1dbcad839265f1d5c4a8ff7 (diff) | |
detect unsupported fields while parsing search options
| -rw-r--r-- | booki.c | 38 |
1 files changed, 37 insertions, 1 deletions
@@ -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; |
