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 static char *opt_name(struct opt_context *oc, struct opt_precomputed *opt)
76 struct opt_item *item = opt->item;
78 if (item->letter >= OPT_POSITIONAL_TAIL)
79 res = stk_printf("positional argument #%d", oc->positional_count);
80 else if (opt->flags & OPT_SEEN_AS_LONG)
81 res = stk_printf("--%s", opt->name);
83 res = stk_printf("-%c", item->letter);
87 #define THIS_OPT opt_name(oc, opt)
89 #define FOREACHLINE(text) for (const char * begin = (text), * end = (text); (*end) && (end = strchrnul(begin, '\n')); begin = end+1)
91 static inline uns uns_min(uns x, uns y)
96 void opt_help(const struct opt_section * help) {
100 for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
101 if (item->flags & OPT_NO_HELP) continue;
102 if (item->cls == OPT_CL_SECTION) {
106 if (!*(item->help)) {
110 FOREACHLINE(item->help)
114 struct opt_sectlist {
116 struct opt_section * sect;
117 } sections[sections_cnt];
120 const char *lines[lines_cnt][3];
121 memset(lines, 0, sizeof(lines));
124 int linelengths[3] = { -1, -1, -1 };
126 for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
127 if (item->flags & OPT_NO_HELP) continue;
129 if (item->cls == OPT_CL_HELP) {
130 if (!*(item->help)) {
134 #define SPLITLINES(text) do { \
135 FOREACHLINE(text) { \
137 for (const char * b = begin, * e = begin; (e < end) && (e = strchrnul(b, '\t')) && (e > end ? (e = end) : end); b = e+1) { \
138 lines[line][cell] = b; \
142 if (*e == '\t' && linelengths[cell] < (e - b)) \
143 linelengths[cell] = e-b; \
148 SPLITLINES(item->help);
152 if (item->cls == OPT_CL_SECTION) {
153 sections[s++] = (struct opt_sectlist) { .pos = line, .sect = item->u.section };
157 uns valoff = strchrnul(item->help, '\t') - item->help;
158 uns eol = strchrnul(item->help, '\n') - item->help;
161 #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)))
163 lines[line][1] = stk_printf("--%s%s", item->name, VAL(item));
164 if (linelengths[1] < (int) strlen(lines[line][1]))
165 linelengths[1] = strlen(lines[line][1]);
167 if (linelengths[0] < 0)
171 lines[line][0] = stk_printf("-%c,", item->letter);
172 if (linelengths[0] < (int) strlen(lines[line][0]))
173 linelengths[0] = strlen(lines[line][0]);
178 lines[line][2] = item->help + valoff + 1;
183 if (*(item->help + eol))
184 SPLITLINES(item->help + eol + 1);
189 #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]
190 #define LASTFIELD(k) uns_min(strchrnul(lines[i][k], '\t') - lines[i][k], strchrnul(lines[i][k], '\n') - lines[i][k]), lines[i][k]
191 for (int i=0;i<line;i++) {
192 while (s < sections_cnt && sections[s].pos == i) {
193 opt_help(sections[s].sect);
196 if (lines[i][0] == NULL)
198 else if (linelengths[0] == -1 || lines[i][1] == NULL)
199 printf("%.*s\n", LASTFIELD(0));
200 else if (linelengths[1] == -1 || lines[i][2] == NULL)
201 printf("%-*.*s %.*s\n", FIELD(0), LASTFIELD(1));
203 printf("%-*.*s %-*.*s %.*s\n", FIELD(0), FIELD(1), LASTFIELD(2));
205 while (s < sections_cnt && sections[s].pos == line) {
206 opt_help(sections[s].sect);
211 static struct opt_precomputed * opt_find_item_longopt(struct opt_context * oc, char * str) {
212 uns len = strlen(str);
213 struct opt_precomputed * candidate = NULL;
215 for (int i = 0; i < oc->opt_count; i++) {
216 struct opt_precomputed *opt = &oc->opts[i];
220 if (!strncmp(opt->name, str, len)) {
221 if (strlen(opt->name) == len)
223 } else if (opt->item->cls == OPT_CL_BOOL && !strncmp("no-", str, 3) && !strncmp(opt->name, str+3, len-3)) {
224 if (strlen(opt->name) == len-3)
230 opt_failure("Ambiguous option --%s: matches both --%s and --%s.", str, candidate->name, opt->name);
238 opt_failure("Invalid option --%s.", str);
241 // FIXME: Use simple-lists?
242 #define OPT_PTR(type) ({ \
244 if (item->flags & OPT_MULTIPLE) { \
248 } * n = xmalloc(sizeof(*n)); \
249 clist_add_tail(item->ptr, &(n->n)); \
255 static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * opt, char * value) {
256 struct opt_item * item = opt->item;
258 for (int i = 0; i < oc->hooks_before_value_count; i++)
259 oc->hooks_before_value[i]->u.call(item, value, oc->hooks_before_value[i]->ptr);
263 if (!value || !strcasecmp(value, "y") || !strcasecmp(value, "yes") || !strcasecmp(value, "true") || !strcasecmp(value, "1"))
264 *((int *) item->ptr) = 1 ^ (!!(opt->flags & OPT_NEGATIVE));
265 else if (!strcasecmp(value, "n") || !strcasecmp(value, "no") || !strcasecmp(value, "false") || !strcasecmp(value, "0"))
266 *((int *) item->ptr) = 0 ^ (!!(opt->flags & OPT_NEGATIVE));
268 opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): 1/0, y/n, yes/no, true/false.", THIS_OPT);
273 switch (item->type) {
278 e = cf_parse_int(value, OPT_PTR(int));
280 opt_failure("Integer value parsing failed for %s: %s", THIS_OPT, e);
286 e = cf_parse_u64(value, OPT_PTR(u64));
288 opt_failure("Unsigned 64-bit value parsing failed for %s: %s", THIS_OPT, e);
292 *OPT_PTR(double) = NAN;
294 e = cf_parse_double(value, OPT_PTR(double));
296 opt_failure("Floating-point value parsing failed for %s: %s", THIS_OPT, e);
302 e = cf_parse_ip(value, OPT_PTR(u32));
304 opt_failure("IP address parsing failed for %s: %s", THIS_OPT, e);
308 *OPT_PTR(const char *) = NULL;
310 *OPT_PTR(const char *) = xstrdup(value);
318 // FIXME: Really? And who sets the default to -1?
319 if (*((int *)item->ptr) != -1)
320 opt_failure("Multiple switches: %s", THIS_OPT);
322 *((int *)item->ptr) = item->u.value;
325 if (opt->flags & OPT_NEGATIVE)
326 (*((int *)item->ptr))--;
328 (*((int *)item->ptr))++;
331 item->u.call(item, value, item->ptr);
336 e = item->u.utype->parser(value, OPT_PTR(void*));
338 opt_failure("Cannot parse the value of %s: %s", THIS_OPT, e);
345 for (int i = 0;i < oc->hooks_after_value_count; i++)
346 oc->hooks_after_value[i]->u.call(item, value, oc->hooks_after_value[i]->ptr);
349 static int opt_longopt(struct opt_context * oc, char ** argv, int index) {
351 char * name_in = argv[index] + 2; // skipping the -- on the beginning
352 uns pos = strchrnul(name_in, '=') - name_in;
353 struct opt_precomputed * opt = opt_find_item_longopt(oc, strndupa(name_in, pos));
356 opt->flags |= OPT_SEEN_AS_LONG;
358 // FIXME: Move to opt_parse_value()?
359 if (opt->count++ && (opt->flags & OPT_SINGLE))
360 opt_failure("Option %s must be specified at most once.", THIS_OPT);
362 if (opt->item->cls == OPT_CL_BOOL && !strncmp(name_in, "no-", 3) && !strncmp(name_in+3, opt->item->name, pos-3)) {
364 opt_failure("Option --%s must not have any value.", name_in);
366 } else if (opt->flags & OPT_REQUIRED_VALUE) {
368 value = name_in + pos + 1;
370 value = argv[index+1];
372 opt_failure("Option %s must have a value, but nothing supplied.", THIS_OPT);
375 } else if (opt->flags & OPT_MAYBE_VALUE) {
377 value = name_in + pos + 1;
380 opt_failure("Option %s must have no value.", THIS_OPT);
382 opt_parse_value(oc, opt, value);
386 static int opt_shortopt(struct opt_context * oc, char ** argv, int index) {
388 struct opt_precomputed * opt;
391 while (o = argv[index][++chr]) {
392 if (o < 0 || o >= 128)
393 opt_failure("Invalid character 0x%02x in option name. Only ASCII is allowed.", o & 0xff);
394 opt = oc->shortopt[o];
397 opt_failure("Unknown option -%c.", o);
399 opt->flags &= ~OPT_SEEN_AS_LONG;
401 if (opt->count && (opt->flags & OPT_SINGLE))
402 opt_failure("Option -%c must be specified at most once.", o);
405 if (opt->flags & OPT_NO_VALUE)
406 opt_parse_value(oc, opt, NULL);
407 else if (opt->flags & OPT_REQUIRED_VALUE) {
408 if (argv[index][chr+1]) {
409 opt_parse_value(oc, opt, argv[index] + chr + 1);
411 } else if (!argv[index+1])
412 opt_failure("Option -%c must have a value, but nothing supplied.", o);
414 opt_parse_value(oc, opt, argv[index+1]);
417 } else if (opt->flags & OPT_MAYBE_VALUE) {
418 if (argv[index][chr+1]) {
419 opt_parse_value(oc, opt, argv[index] + chr + 1);
422 opt_parse_value(oc, opt, NULL);
431 static void opt_positional(struct opt_context * oc, char * value) {
432 oc->positional_count++;
433 uns id = oc->positional_count > oc->positional_max ? OPT_POSITIONAL_TAIL : OPT_POSITIONAL(oc->positional_count);
434 struct opt_precomputed * opt = oc->shortopt[id];
435 if (!opt || (opt->flags & OPT_SINGLE) && opt->count)
436 opt_failure("Too many positional arguments.");
438 opt->flags &= OPT_SEEN_AS_LONG;
440 opt_parse_value(oc, opt, value);
444 static void opt_count_items(struct opt_context *oc, const struct opt_section *sec)
446 for (const struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
447 if (item->cls == OPT_CL_SECTION)
448 opt_count_items(oc, item->u.section);
449 else if (item->cls == OPT_CL_HOOK) {
450 if (item->flags & OPT_HOOK_BEFORE_ARG)
451 oc->hooks_before_arg_count++;
452 else if (item->flags & OPT_HOOK_BEFORE_VALUE)
453 oc->hooks_before_value_count++;
454 else if (item->flags & OPT_HOOK_AFTER_VALUE)
455 oc->hooks_after_value_count++;
458 } else if (item->letter || item->name) {
460 if (item->letter > OPT_POSITIONAL_TAIL)
461 oc->positional_max++;
466 static void opt_add_default_flags(struct opt_precomputed *opt)
468 struct opt_item *item = opt->item;
469 uns flags = opt->flags;
471 if (item->letter >= OPT_POSITIONAL_TAIL) {
472 flags &= ~OPT_VALUE_FLAGS;
473 flags |= OPT_REQUIRED_VALUE;
475 if (!(flags & OPT_VALUE_FLAGS)) {
476 ASSERT(item->cls != OPT_CL_CALL && item->cls != OPT_CL_USER);
477 flags |= opt_default_value_flags[item->cls];
483 static void opt_prepare_items(struct opt_context *oc, const struct opt_section *sec)
485 for (struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
486 if (item->cls == OPT_CL_SECTION)
487 opt_prepare_items(oc, item->u.section);
488 else if (item->cls == OPT_CL_HOOK) {
489 if (item->flags & OPT_HOOK_BEFORE_ARG)
490 oc->hooks_before_arg[oc->hooks_before_arg_count++] = item;
491 else if (item->flags & OPT_HOOK_BEFORE_VALUE)
492 oc->hooks_before_value[oc->hooks_before_value_count++] = item;
493 else if (item->flags & OPT_HOOK_AFTER_VALUE)
494 oc->hooks_after_value[oc->hooks_after_value_count++] = item;
497 } else if (item->letter || item->name) {
498 struct opt_precomputed * opt = &oc->opts[oc->opt_count++];
500 opt->flags = item->flags;
502 opt->name = item->name;
504 oc->shortopt[(int) item->letter] = opt;
505 opt_add_default_flags(opt);
510 static void opt_check_required(struct opt_context *oc)
512 for (int i = 0; i < oc->opt_count; i++) {
513 struct opt_precomputed *opt = &oc->opts[i];
514 if (!opt->count && (opt->flags & OPT_REQUIRED)) {
515 struct opt_item *item = opt->item;
516 if (item->letter > OPT_POSITIONAL_TAIL)
517 opt_failure("Required positional argument #%d not found.", i - OPT_POSITIONAL_TAIL);
518 else if (item->letter == OPT_POSITIONAL_TAIL)
519 opt_failure("Required positional argument not found.");
520 else if (item->letter && item->name)
521 opt_failure("Required option -%c/--%s not found.", item->letter, item->name);
522 else if (item->letter)
523 opt_failure("Required option -%c not found.", item->letter);
525 opt_failure("Required option --%s not found.", item->name);
530 void opt_parse(const struct opt_section * options, char ** argv) {
531 struct opt_context * oc = alloca(sizeof(*oc));
532 memset(oc, 0, sizeof (*oc));
534 opt_count_items(oc, options);
535 oc->opts = alloca(sizeof(*oc->opts) * oc->opt_count);
536 oc->shortopt = alloca(sizeof(*oc->shortopt) * (oc->positional_max + 257));
537 memset(oc->shortopt, 0, sizeof(*oc->shortopt) * (oc->positional_max + 257));
538 oc->hooks_before_arg = alloca(sizeof (*oc->hooks_before_arg) * oc->hooks_before_arg_count);
539 oc->hooks_before_value = alloca(sizeof (*oc->hooks_before_value) * oc->hooks_before_value_count);
540 oc->hooks_after_value = alloca(sizeof (*oc->hooks_after_value) * oc->hooks_after_value_count);
543 oc->hooks_before_arg_count = 0;
544 oc->hooks_before_value_count = 0;
545 oc->hooks_after_value_count = 0;
546 opt_prepare_items(oc, options);
548 int force_positional = 0;
549 for (int i = 0; argv[i]; i++) {
551 for (int j = 0; j < oc->hooks_before_arg_count; j++)
552 oc->hooks_before_arg[j]->u.call(NULL, NULL, oc->hooks_before_arg[j]->ptr);
553 if (arg[0] != '-' || force_positional)
554 opt_positional(oc, arg);
560 i += opt_longopt(oc, argv, i);
562 i += opt_shortopt(oc, argv, i);
564 opt_positional(oc, arg);
568 opt_check_required(oc);
571 static void opt_conf_end_of_options(struct cf_context *cc) {
573 if (cc->postpone_commit && cf_close_group())
574 opt_failure("Loading of configuration failed");
577 void opt_conf_internal(struct opt_item * opt, const char * value, void * data UNUSED) {
578 struct cf_context *cc = cf_get_context();
579 switch (opt->letter) {
583 opt_failure("Cannot set %s", value);
587 opt_failure("Cannot load config file %s", value);
589 #ifdef CONFIG_UCW_DEBUG
591 opt_conf_end_of_options(cc);
592 struct fastbuf *b = bfdopen(1, 4096);
601 void opt_conf_hook_internal(struct opt_item * opt, const char * value UNUSED, void * data UNUSED) {
604 OPT_CONF_HOOK_CONFIG,
606 } state = OPT_CONF_HOOK_BEGIN;
610 if (opt->letter == 'S' || opt->letter == 'C' || (opt->name && !strcmp(opt->name, "dumpconfig")))
614 case OPT_CONF_HOOK_BEGIN:
616 state = OPT_CONF_HOOK_CONFIG;
618 opt_conf_end_of_options(cf_get_context());
619 state = OPT_CONF_HOOK_OTHERS;
622 case OPT_CONF_HOOK_CONFIG:
624 opt_conf_end_of_options(cf_get_context());
625 state = OPT_CONF_HOOK_OTHERS;
628 case OPT_CONF_HOOK_OTHERS:
630 opt_failure("Config options (-C, -S) must stand before other options.");