2 * UCW Library -- Parsing of command line options
4 * (c) 2013 Jan Moskyto Matejka <mq@ucw.cz>
5 * (c) 2014 Martin Mares <mj@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
14 #include <ucw/conf-internal.h>
15 #include <ucw/fastbuf.h>
16 #include <ucw/stkstring.h>
17 #include <ucw/strtonum.h>
23 * Value flags defaults
24 * ~~~~~~~~~~~~~~~~~~~~
26 * OPT_NO_VALUE for OPT_BOOL, OPT_SWITCH and OPT_INC
27 * OPT_MAYBE_VALUE for OPT_STRING, OPT_UNS, OPT_INT
28 * Some of the value flags (OPT_NO_VALUE, OPT_MAYBE_VALUE, OPT_REQUIRED_VALUE)
29 * must be specified for OPT_CALL and OPT_USER.
31 static uns opt_default_value_flags[] = {
32 [OPT_CL_BOOL] = OPT_NO_VALUE,
33 [OPT_CL_STATIC] = OPT_MAYBE_VALUE,
34 [OPT_CL_SWITCH] = OPT_NO_VALUE,
35 [OPT_CL_INC] = OPT_NO_VALUE,
42 struct opt_precomputed {
43 struct opt_item * item;
50 struct opt_precomputed * opts;
51 struct opt_precomputed ** shortopt;
52 struct opt_item ** hooks_before_arg;
53 struct opt_item ** hooks_before_value;
54 struct opt_item ** hooks_after_value;
56 short hooks_before_arg_count;
57 short hooks_before_value_count;
58 short hooks_after_value_count;
63 static void opt_failure(const char * mesg, ...) FORMAT_CHECK(printf,1,2) NONRET;
64 static void opt_failure(const char * mesg, ...) {
67 vfprintf(stderr, mesg, args);
68 fprintf(stderr, "\n");
70 exit(OPT_EXIT_BAD_ARGS);
71 va_end(args); // FIXME: Does this make a sense after exit()?
74 #define FOREACHLINE(text) for (const char * begin = (text), * end = (text); (*end) && (end = strchrnul(begin, '\n')); begin = end+1)
76 static inline uns uns_min(uns x, uns y)
81 void opt_help(const struct opt_section * help) {
85 for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
86 if (item->flags & OPT_NO_HELP) continue;
87 if (item->cls == OPT_CL_SECTION) {
95 FOREACHLINE(item->help)
101 struct opt_section * sect;
102 } sections[sections_cnt];
105 const char *lines[lines_cnt][3];
106 memset(lines, 0, sizeof(lines));
109 int linelengths[3] = { -1, -1, -1 };
111 for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
112 if (item->flags & OPT_NO_HELP) continue;
114 if (item->cls == OPT_CL_HELP) {
115 if (!*(item->help)) {
119 #define SPLITLINES(text) do { \
120 FOREACHLINE(text) { \
122 for (const char * b = begin, * e = begin; (e < end) && (e = strchrnul(b, '\t')) && (e > end ? (e = end) : end); b = e+1) { \
123 lines[line][cell] = b; \
127 if (*e == '\t' && linelengths[cell] < (e - b)) \
128 linelengths[cell] = e-b; \
133 SPLITLINES(item->help);
137 if (item->cls == OPT_CL_SECTION) {
138 sections[s++] = (struct opt_sectlist) { .pos = line, .sect = item->u.section };
142 uns valoff = strchrnul(item->help, '\t') - item->help;
143 uns eol = strchrnul(item->help, '\n') - item->help;
146 #define VAL(it) ((it->flags & OPT_REQUIRED_VALUE) ? stk_printf("=%.*s", valoff, item->help) : ((it->flags & OPT_NO_VALUE) ? "" : stk_printf("(=%.*s)", valoff, item->help)))
148 lines[line][1] = stk_printf("--%s%s", item->name, VAL(item));
149 if (linelengths[1] < (int) strlen(lines[line][1]))
150 linelengths[1] = strlen(lines[line][1]);
152 if (linelengths[0] < 0)
156 lines[line][0] = stk_printf("-%c,", item->letter);
157 if (linelengths[0] < (int) strlen(lines[line][0]))
158 linelengths[0] = strlen(lines[line][0]);
163 lines[line][2] = item->help + valoff + 1;
168 if (*(item->help + eol))
169 SPLITLINES(item->help + eol + 1);
174 #define FIELD(k) linelengths[k], uns_min(strchrnul(lines[i][k], '\t') - lines[i][k], strchrnul(lines[i][k], '\n') - lines[i][k]), lines[i][k]
175 #define LASTFIELD(k) uns_min(strchrnul(lines[i][k], '\t') - lines[i][k], strchrnul(lines[i][k], '\n') - lines[i][k]), lines[i][k]
176 for (int i=0;i<line;i++) {
177 while (s < sections_cnt && sections[s].pos == i) {
178 opt_help(sections[s].sect);
181 if (lines[i][0] == NULL)
183 else if (linelengths[0] == -1 || lines[i][1] == NULL)
184 printf("%.*s\n", LASTFIELD(0));
185 else if (linelengths[1] == -1 || lines[i][2] == NULL)
186 printf("%-*.*s %.*s\n", FIELD(0), LASTFIELD(1));
188 printf("%-*.*s %-*.*s %.*s\n", FIELD(0), FIELD(1), LASTFIELD(2));
190 while (s < sections_cnt && sections[s].pos == line) {
191 opt_help(sections[s].sect);
196 static struct opt_precomputed * opt_find_item_longopt(struct opt_context * oc, char * str) {
197 uns len = strlen(str);
198 struct opt_precomputed * candidate = NULL;
200 for (int i=0; i<oc->opt_count; i++) {
201 if (!oc->opts[i].name)
203 if (!strncmp(oc->opts[i].name, str, len)) {
204 if (strlen(oc->opts[i].name) == len) {
205 if (oc->opts[i].count++ && (oc->opts[i].flags & OPT_SINGLE))
206 opt_failure("Option %s appeared the second time.", oc->opts[i].name);
211 opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, oc->opts[i].name);
213 candidate = &oc->opts[i];
215 if (!strncmp("no-", str, 3) && !strncmp(oc->opts[i].name, str+3, len-3)) {
216 if (strlen(oc->opts[i].name) == len-3) {
217 if (oc->opts[i].count++ && (oc->opts[i].flags & OPT_SINGLE))
218 opt_failure("Option %s appeared the second time.", oc->opts[i].name);
223 opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, oc->opts[i].name);
225 candidate = &oc->opts[i];
232 opt_failure("Invalid option %s.", str);
235 #define OPT_PTR(type) ({ \
237 if (item->flags & OPT_MULTIPLE) { \
241 } * n = xmalloc(sizeof(*n)); \
242 clist_add_tail(item->ptr, &(n->n)); \
248 #define OPT_NAME (longopt == 2 ? stk_printf("positional arg #%d", oc->positional_count) : (longopt == 1 ? stk_printf("--%s", opt->name) : stk_printf("-%c", item->letter)))
249 static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * opt, char * value, int longopt) {
250 struct opt_item * item = opt->item;
251 for (int i=0;i<oc->hooks_before_value_count;i++)
252 oc->hooks_before_value[i]->u.call(item, value, oc->hooks_before_value[i]->ptr);
256 if (!value || !strcasecmp(value, "y") || !strcasecmp(value, "yes") || !strcasecmp(value, "true") || !strcasecmp(value, "1"))
257 *((int *) item->ptr) = 1 ^ (!!(opt->flags & OPT_NEGATIVE));
258 else if (!strcasecmp(value, "n") || !strcasecmp(value, "no") || !strcasecmp(value, "false") || !strcasecmp(value, "0"))
259 *((int *) item->ptr) = 0 ^ (!!(opt->flags & OPT_NEGATIVE));
261 opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): y/n, yes/no, true/false.", OPT_NAME);
266 switch (item->type) {
271 e = cf_parse_int(value, OPT_PTR(int));
273 opt_failure("Integer value parsing failed for %s: %s", OPT_NAME, e);
279 e = cf_parse_u64(value, OPT_PTR(u64));
281 opt_failure("Unsigned 64-bit value parsing failed for %s: %s", OPT_NAME, e);
285 *OPT_PTR(double) = NAN;
287 e = cf_parse_double(value, OPT_PTR(double));
289 opt_failure("Double value parsing failed for %s: %s", OPT_NAME, e);
293 e = cf_parse_ip("0.0.0.0", OPT_PTR(u32));
295 e = cf_parse_ip(value, OPT_PTR(u32));
297 opt_failure("IP parsing failed for %s: %s", OPT_NAME, e);
301 *OPT_PTR(const char *) = NULL;
303 *OPT_PTR(const char *) = xstrdup(value);
311 if (*((int *)item->ptr) != -1)
312 opt_failure("Multiple switches: %s", OPT_NAME);
314 *((int *)item->ptr) = item->u.value;
317 if (opt->flags & OPT_NEGATIVE)
318 (*((int *)item->ptr))--;
320 (*((int *)item->ptr))++;
323 item->u.call(item, value, item->ptr);
328 e = item->u.utype->parser(value, OPT_PTR(void*));
330 opt_failure("User defined type value parsing failed for %s: %s", OPT_NAME, e);
337 for (int i=0;i<oc->hooks_after_value_count;i++)
338 oc->hooks_after_value[i]->u.call(item, value, oc->hooks_after_value[i]->ptr);
342 static int opt_longopt(struct opt_context * oc, char ** argv, int index) {
344 char * name_in = argv[index] + 2; // skipping the -- on the beginning
345 uns pos = strchrnul(name_in, '=') - name_in;
346 struct opt_precomputed * opt = opt_find_item_longopt(oc, strndupa(name_in, pos));
349 if (opt->item->cls == OPT_CL_BOOL && !strncmp(name_in, "no-", 3) && !strncmp(name_in+3, opt->item->name, pos-3))
351 else if (opt->flags & OPT_REQUIRED_VALUE) {
352 if (pos < strlen(name_in))
353 value = name_in + pos + 1;
355 value = argv[index+1];
357 opt_failure("Argument --%s must have a value but nothing supplied.", opt->name);
361 else if (opt->flags & OPT_MAYBE_VALUE) {
362 if (pos < strlen(name_in))
363 value = name_in + pos + 1;
366 if (pos < strlen(name_in))
367 opt_failure("Argument --%s must not have any value.", opt->name);
369 opt_parse_value(oc, opt, value, 1);
373 static int opt_shortopt(struct opt_context * oc, char ** argv, int index) {
375 struct opt_precomputed * opt;
378 while (o = argv[index][++chr]) {
379 if (o < 0 || o >= 128)
380 opt_failure("Invalid character 0x%02x in option name. Only ASCII is allowed.", o & 0xff);
381 opt = oc->shortopt[o];
384 opt_failure("Unknown option -%c.", o);
386 if (opt->count && (opt->flags & OPT_SINGLE))
387 opt_failure("Option -%c must be specified at most once.", o);
390 if (opt->flags & OPT_NO_VALUE)
391 opt_parse_value(oc, opt, NULL, 0);
392 else if (opt->flags & OPT_REQUIRED_VALUE) {
393 if (chr == 1 && argv[index][2]) {
394 opt_parse_value(oc, opt, argv[index] + 2, 0);
396 } else if (argv[index][chr+1])
397 opt_failure("Option -%c must have a value, but found inside a bunch of short opts.", o);
398 else if (!argv[index+1])
399 opt_failure("Option -%c must have a value, but nothing supplied.", o);
401 opt_parse_value(oc, opt, argv[index+1], 0);
404 } else if (opt->flags & OPT_MAYBE_VALUE) {
405 if (chr == 1 && argv[index][2]) {
406 opt_parse_value(oc, opt, argv[index] + 2, 0);
409 opt_parse_value(oc, opt, NULL, 0);
418 static void opt_positional(struct opt_context * oc, char * value) {
419 oc->positional_count++;
420 uns id = oc->positional_count > oc->positional_max ? OPT_POSITIONAL_TAIL : OPT_POSITIONAL(oc->positional_count);
421 struct opt_precomputed * opt = oc->shortopt[id];
422 if (!opt || (opt->flags & OPT_SINGLE) && opt->count)
423 opt_failure("Too many positional arguments.");
426 opt_parse_value(oc, opt, value, 2);
430 static void opt_count_items(struct opt_context *oc, const struct opt_section *sec)
432 for (const struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
433 if (item->cls == OPT_CL_SECTION)
434 opt_count_items(oc, item->u.section);
435 else if (item->cls == OPT_CL_HOOK) {
436 if (item->flags & OPT_HOOK_BEFORE_ARG)
437 oc->hooks_before_arg_count++;
438 else if (item->flags & OPT_HOOK_BEFORE_VALUE)
439 oc->hooks_before_value_count++;
440 else if (item->flags & OPT_HOOK_AFTER_VALUE)
441 oc->hooks_after_value_count++;
444 } else if (item->letter || item->name) {
446 if (item->letter > OPT_POSITIONAL_TAIL)
447 oc->positional_max++;
452 static void opt_add_default_flags(struct opt_precomputed *opt)
454 struct opt_item *item = opt->item;
455 uns flags = opt->flags;
457 if (item->letter >= OPT_POSITIONAL_TAIL) {
458 flags &= ~OPT_VALUE_FLAGS;
459 flags |= OPT_REQUIRED_VALUE;
461 if (!(flags & OPT_VALUE_FLAGS)) {
462 ASSERT(item->cls != OPT_CL_CALL && item->cls != OPT_CL_USER);
463 flags |= opt_default_value_flags[item->cls];
469 static void opt_prepare_items(struct opt_context *oc, const struct opt_section *sec)
471 for (struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
472 if (item->cls == OPT_CL_SECTION)
473 opt_prepare_items(oc, item->u.section);
474 else if (item->cls == OPT_CL_HOOK) {
475 if (item->flags & OPT_HOOK_BEFORE_ARG)
476 oc->hooks_before_arg[oc->hooks_before_arg_count++] = item;
477 else if (item->flags & OPT_HOOK_BEFORE_VALUE)
478 oc->hooks_before_value[oc->hooks_before_value_count++] = item;
479 else if (item->flags & OPT_HOOK_AFTER_VALUE)
480 oc->hooks_after_value[oc->hooks_after_value_count++] = item;
483 } else if (item->letter || item->name) {
484 struct opt_precomputed * opt = &oc->opts[oc->opt_count++];
486 opt->flags = item->flags;
488 opt->name = item->name;
490 oc->shortopt[(int) item->letter] = opt;
491 opt_add_default_flags(opt);
496 static void opt_check_required(struct opt_context *oc)
498 for (int i = 0; i < oc->opt_count; i++) {
499 struct opt_precomputed *opt = &oc->opts[i];
500 if (!opt->count && (opt->flags & OPT_REQUIRED)) {
501 struct opt_item *item = opt->item;
502 if (item->letter > OPT_POSITIONAL_TAIL)
503 opt_failure("Required positional argument #%d not found.", i - OPT_POSITIONAL_TAIL);
504 else if (item->letter == OPT_POSITIONAL_TAIL)
505 opt_failure("Required positional argument not found.");
506 else if (item->letter && item->name)
507 opt_failure("Required option -%c/--%s not found.", item->letter, item->name);
508 else if (item->letter)
509 opt_failure("Required option -%c not found.", item->letter);
511 opt_failure("Required option --%s not found.", item->name);
516 void opt_parse(const struct opt_section * options, char ** argv) {
517 struct opt_context * oc = alloca(sizeof(*oc));
518 memset(oc, 0, sizeof (*oc));
520 opt_count_items(oc, options);
521 oc->opts = alloca(sizeof(*oc->opts) * oc->opt_count);
522 oc->shortopt = alloca(sizeof(*oc->shortopt) * (oc->positional_max + 257));
523 memset(oc->shortopt, 0, sizeof(*oc->shortopt) * (oc->positional_max + 257));
524 oc->hooks_before_arg = alloca(sizeof (*oc->hooks_before_arg) * oc->hooks_before_arg_count);
525 oc->hooks_before_value = alloca(sizeof (*oc->hooks_before_value) * oc->hooks_before_value_count);
526 oc->hooks_after_value = alloca(sizeof (*oc->hooks_after_value) * oc->hooks_after_value_count);
529 oc->hooks_before_arg_count = 0;
530 oc->hooks_before_value_count = 0;
531 oc->hooks_after_value_count = 0;
532 opt_prepare_items(oc, options);
534 int force_positional = 0;
535 for (int i = 0; argv[i]; i++) {
537 for (int j = 0; j < oc->hooks_before_arg_count; j++)
538 oc->hooks_before_arg[j]->u.call(NULL, NULL, oc->hooks_before_arg[j]->ptr);
539 if (arg[0] != '-' || force_positional)
540 opt_positional(oc, arg);
546 i += opt_longopt(oc, argv, i);
548 i += opt_shortopt(oc, argv, i);
550 opt_positional(oc, arg);
554 opt_check_required(oc);
557 static void opt_conf_end_of_options(struct cf_context *cc) {
559 if (cc->postpone_commit && cf_close_group())
560 opt_failure("Loading of configuration failed");
563 void opt_conf_internal(struct opt_item * opt, const char * value, void * data UNUSED) {
564 struct cf_context *cc = cf_get_context();
565 switch (opt->letter) {
569 opt_failure("Cannot set %s", value);
573 opt_failure("Cannot load config file %s", value);
575 #ifdef CONFIG_UCW_DEBUG
577 opt_conf_end_of_options(cc);
578 struct fastbuf *b = bfdopen(1, 4096);
587 void opt_conf_hook_internal(struct opt_item * opt, const char * value UNUSED, void * data UNUSED) {
590 OPT_CONF_HOOK_CONFIG,
592 } state = OPT_CONF_HOOK_BEGIN;
596 if (opt->letter == 'S' || opt->letter == 'C' || (opt->name && !strcmp(opt->name, "dumpconfig")))
600 case OPT_CONF_HOOK_BEGIN:
602 state = OPT_CONF_HOOK_CONFIG;
604 opt_conf_end_of_options(cf_get_context());
605 state = OPT_CONF_HOOK_OTHERS;
608 case OPT_CONF_HOOK_CONFIG:
610 opt_conf_end_of_options(cf_get_context());
611 state = OPT_CONF_HOOK_OTHERS;
614 case OPT_CONF_HOOK_OTHERS:
616 opt_failure("Config options (-C, -S) must stand before other options.");