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 if (opt->count++ && (opt->flags & OPT_SINGLE))
259 opt_failure("Option %s must be specified at most once.", THIS_OPT);
261 for (int i = 0; i < oc->hooks_before_value_count; i++)
262 oc->hooks_before_value[i]->u.call(item, value, oc->hooks_before_value[i]->ptr);
266 if (!value || !strcasecmp(value, "y") || !strcasecmp(value, "yes") || !strcasecmp(value, "true") || !strcasecmp(value, "1"))
267 *((int *) item->ptr) = 1 ^ (!!(opt->flags & OPT_NEGATIVE));
268 else if (!strcasecmp(value, "n") || !strcasecmp(value, "no") || !strcasecmp(value, "false") || !strcasecmp(value, "0"))
269 *((int *) item->ptr) = 0 ^ (!!(opt->flags & OPT_NEGATIVE));
271 opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): 1/0, y/n, yes/no, true/false.", THIS_OPT);
276 switch (item->type) {
281 e = cf_parse_int(value, OPT_PTR(int));
283 opt_failure("Integer value parsing failed for %s: %s", THIS_OPT, e);
289 e = cf_parse_u64(value, OPT_PTR(u64));
291 opt_failure("Unsigned 64-bit value parsing failed for %s: %s", THIS_OPT, e);
295 *OPT_PTR(double) = NAN;
297 e = cf_parse_double(value, OPT_PTR(double));
299 opt_failure("Floating-point value parsing failed for %s: %s", THIS_OPT, e);
305 e = cf_parse_ip(value, OPT_PTR(u32));
307 opt_failure("IP address parsing failed for %s: %s", THIS_OPT, e);
311 *OPT_PTR(const char *) = NULL;
313 *OPT_PTR(const char *) = xstrdup(value);
321 if ((opt->flags & OPT_SINGLE) && *((int *)item->ptr) != -1)
322 opt_failure("Multiple switches: %s", THIS_OPT);
324 *((int *)item->ptr) = item->u.value;
327 if (opt->flags & OPT_NEGATIVE)
328 (*((int *)item->ptr))--;
330 (*((int *)item->ptr))++;
333 item->u.call(item, value, item->ptr);
338 e = item->u.utype->parser(value, OPT_PTR(void*));
340 opt_failure("Cannot parse the value of %s: %s", THIS_OPT, e);
347 for (int i = 0;i < oc->hooks_after_value_count; i++)
348 oc->hooks_after_value[i]->u.call(item, value, oc->hooks_after_value[i]->ptr);
351 static int opt_longopt(struct opt_context * oc, char ** argv, int index) {
353 char * name_in = argv[index] + 2; // skipping the -- on the beginning
354 uns pos = strchrnul(name_in, '=') - name_in;
355 struct opt_precomputed * opt = opt_find_item_longopt(oc, strndupa(name_in, pos));
358 opt->flags |= OPT_SEEN_AS_LONG;
360 if (opt->item->cls == OPT_CL_BOOL && !strncmp(name_in, "no-", 3) && !strncmp(name_in+3, opt->item->name, pos-3)) {
362 opt_failure("Option --%s must not have any value.", name_in);
364 } else if (opt->flags & OPT_REQUIRED_VALUE) {
366 value = name_in + pos + 1;
368 value = argv[index+1];
370 opt_failure("Option %s must have a value, but nothing supplied.", THIS_OPT);
373 } else if (opt->flags & OPT_MAYBE_VALUE) {
375 value = name_in + pos + 1;
378 opt_failure("Option %s must have no value.", THIS_OPT);
380 opt_parse_value(oc, opt, value);
384 static int opt_shortopt(struct opt_context * oc, char ** argv, int index) {
386 struct opt_precomputed * opt;
389 while (o = argv[index][++chr]) {
390 if (o < 0 || o >= 128)
391 opt_failure("Invalid character 0x%02x in option name. Only ASCII is allowed.", o & 0xff);
392 opt = oc->shortopt[o];
395 opt_failure("Unknown option -%c.", o);
397 opt->flags &= ~OPT_SEEN_AS_LONG;
399 if (opt->flags & OPT_NO_VALUE)
400 opt_parse_value(oc, opt, NULL);
401 else if (opt->flags & OPT_REQUIRED_VALUE) {
402 if (argv[index][chr+1]) {
403 opt_parse_value(oc, opt, argv[index] + chr + 1);
405 } else if (!argv[index+1])
406 opt_failure("Option -%c must have a value, but nothing supplied.", o);
408 opt_parse_value(oc, opt, argv[index+1]);
411 } else if (opt->flags & OPT_MAYBE_VALUE) {
412 if (argv[index][chr+1]) {
413 opt_parse_value(oc, opt, argv[index] + chr + 1);
416 opt_parse_value(oc, opt, NULL);
425 static void opt_positional(struct opt_context * oc, char * value) {
426 oc->positional_count++;
427 uns id = oc->positional_count > oc->positional_max ? OPT_POSITIONAL_TAIL : OPT_POSITIONAL(oc->positional_count);
428 struct opt_precomputed * opt = oc->shortopt[id];
430 opt_failure("Too many positional arguments.");
432 opt->flags &= OPT_SEEN_AS_LONG;
433 opt_parse_value(oc, opt, value);
437 static void opt_count_items(struct opt_context *oc, const struct opt_section *sec)
439 for (const struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
440 if (item->cls == OPT_CL_SECTION)
441 opt_count_items(oc, item->u.section);
442 else if (item->cls == OPT_CL_HOOK) {
443 if (item->flags & OPT_HOOK_BEFORE_ARG)
444 oc->hooks_before_arg_count++;
445 else if (item->flags & OPT_HOOK_BEFORE_VALUE)
446 oc->hooks_before_value_count++;
447 else if (item->flags & OPT_HOOK_AFTER_VALUE)
448 oc->hooks_after_value_count++;
451 } else if (item->letter || item->name) {
453 if (item->letter > OPT_POSITIONAL_TAIL)
454 oc->positional_max++;
459 static void opt_add_default_flags(struct opt_precomputed *opt)
461 struct opt_item *item = opt->item;
462 uns flags = opt->flags;
464 if (item->letter >= OPT_POSITIONAL_TAIL) {
465 flags &= ~OPT_VALUE_FLAGS;
466 flags |= OPT_REQUIRED_VALUE;
468 if (!(flags & OPT_VALUE_FLAGS)) {
469 ASSERT(item->cls != OPT_CL_CALL && item->cls != OPT_CL_USER);
470 flags |= opt_default_value_flags[item->cls];
476 static void opt_prepare_items(struct opt_context *oc, const struct opt_section *sec)
478 for (struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
479 if (item->cls == OPT_CL_SECTION)
480 opt_prepare_items(oc, item->u.section);
481 else if (item->cls == OPT_CL_HOOK) {
482 if (item->flags & OPT_HOOK_BEFORE_ARG)
483 oc->hooks_before_arg[oc->hooks_before_arg_count++] = item;
484 else if (item->flags & OPT_HOOK_BEFORE_VALUE)
485 oc->hooks_before_value[oc->hooks_before_value_count++] = item;
486 else if (item->flags & OPT_HOOK_AFTER_VALUE)
487 oc->hooks_after_value[oc->hooks_after_value_count++] = item;
490 } else if (item->letter || item->name) {
491 struct opt_precomputed * opt = &oc->opts[oc->opt_count++];
493 opt->flags = item->flags;
495 opt->name = item->name;
497 oc->shortopt[(int) item->letter] = opt;
498 opt_add_default_flags(opt);
503 static void opt_check_required(struct opt_context *oc)
505 for (int i = 0; i < oc->opt_count; i++) {
506 struct opt_precomputed *opt = &oc->opts[i];
507 if (!opt->count && (opt->flags & OPT_REQUIRED)) {
508 struct opt_item *item = opt->item;
509 if (item->letter > OPT_POSITIONAL_TAIL)
510 opt_failure("Required positional argument #%d not found.", item->letter - OPT_POSITIONAL_TAIL);
511 else if (item->letter == OPT_POSITIONAL_TAIL)
512 opt_failure("Required positional argument not found.");
513 else if (item->letter && item->name)
514 opt_failure("Required option -%c/--%s not found.", item->letter, item->name);
515 else if (item->letter)
516 opt_failure("Required option -%c not found.", item->letter);
518 opt_failure("Required option --%s not found.", item->name);
523 void opt_parse(const struct opt_section * options, char ** argv) {
524 struct opt_context * oc = alloca(sizeof(*oc));
525 memset(oc, 0, sizeof (*oc));
527 opt_count_items(oc, options);
528 oc->opts = alloca(sizeof(*oc->opts) * oc->opt_count);
529 oc->shortopt = alloca(sizeof(*oc->shortopt) * (oc->positional_max + 257));
530 memset(oc->shortopt, 0, sizeof(*oc->shortopt) * (oc->positional_max + 257));
531 oc->hooks_before_arg = alloca(sizeof (*oc->hooks_before_arg) * oc->hooks_before_arg_count);
532 oc->hooks_before_value = alloca(sizeof (*oc->hooks_before_value) * oc->hooks_before_value_count);
533 oc->hooks_after_value = alloca(sizeof (*oc->hooks_after_value) * oc->hooks_after_value_count);
536 oc->hooks_before_arg_count = 0;
537 oc->hooks_before_value_count = 0;
538 oc->hooks_after_value_count = 0;
539 opt_prepare_items(oc, options);
541 int force_positional = 0;
542 for (int i = 0; argv[i]; i++) {
544 for (int j = 0; j < oc->hooks_before_arg_count; j++)
545 oc->hooks_before_arg[j]->u.call(NULL, NULL, oc->hooks_before_arg[j]->ptr);
546 if (arg[0] != '-' || force_positional)
547 opt_positional(oc, arg);
553 i += opt_longopt(oc, argv, i);
555 i += opt_shortopt(oc, argv, i);
557 opt_positional(oc, arg);
561 opt_check_required(oc);
564 static void opt_conf_end_of_options(struct cf_context *cc) {
566 if (cc->postpone_commit && cf_close_group())
567 opt_failure("Loading of configuration failed");
570 void opt_conf_internal(struct opt_item * opt, const char * value, void * data UNUSED) {
571 struct cf_context *cc = cf_get_context();
572 switch (opt->letter) {
576 opt_failure("Cannot set %s", value);
580 opt_failure("Cannot load config file %s", value);
582 #ifdef CONFIG_UCW_DEBUG
584 opt_conf_end_of_options(cc);
585 struct fastbuf *b = bfdopen(1, 4096);
594 void opt_conf_hook_internal(struct opt_item * opt, const char * value UNUSED, void * data UNUSED) {
597 OPT_CONF_HOOK_CONFIG,
599 } state = OPT_CONF_HOOK_BEGIN;
603 if (opt->letter == 'S' || opt->letter == 'C' || (opt->name && !strcmp(opt->name, "dumpconfig")))
607 case OPT_CONF_HOOK_BEGIN:
609 state = OPT_CONF_HOOK_CONFIG;
611 opt_conf_end_of_options(cf_get_context());
612 state = OPT_CONF_HOOK_OTHERS;
615 case OPT_CONF_HOOK_CONFIG:
617 opt_conf_end_of_options(cf_get_context());
618 state = OPT_CONF_HOOK_OTHERS;
621 case OPT_CONF_HOOK_OTHERS:
623 opt_failure("Config options (-C, -S) must stand before other options.");