2 * UCW Library -- Parsing of command line options
4 * (c) 2013 Jan Moskyto Matejka <mq@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
13 #include <ucw/conf-internal.h>
14 #include <ucw/fastbuf.h>
15 #include <ucw/stkstring.h>
16 #include <ucw/strtonum.h>
21 // FIXME: Do we need these?
22 int opt_parsed_count = 0;
23 int opt_conf_parsed_count = 0;
25 struct opt_precomputed {
26 struct opt_item * item;
33 struct opt_precomputed ** opts;
34 struct opt_precomputed ** shortopt;
35 struct opt_item ** hooks_before_arg;
36 struct opt_item ** hooks_before_value;
37 struct opt_item ** hooks_after_value;
39 short hooks_before_arg_count;
40 short hooks_before_value_count;
41 short hooks_after_value_count;
46 static void opt_failure(const char * mesg, ...) FORMAT_CHECK(printf,1,2) NONRET;
47 static void opt_failure(const char * mesg, ...) {
50 vfprintf(stderr, mesg, args);
51 fprintf(stderr, "\n");
53 exit(OPT_EXIT_BAD_ARGS);
54 va_end(args); // FIXME: Does this make a sense after exit()?
57 // FIXME: This could be an inline function, couldn't it?
58 #define OPT_ADD_DEFAULT_ITEM_FLAGS(item, flags) \
60 if (item->letter >= 256) { \
61 if (flags & OPT_VALUE_FLAGS) /* FIXME: Redundant condition */ \
62 flags &= ~OPT_VALUE_FLAGS; \
63 flags |= OPT_REQUIRED_VALUE; \
65 if (!(flags & OPT_VALUE_FLAGS) && \
66 (item->cls == OPT_CL_CALL || item->cls == OPT_CL_USER)) { \
67 fprintf(stderr, "You MUST specify some of the value flags for the %c/%s item.\n", item->letter, item->name); \
70 else if (!(flags & OPT_VALUE_FLAGS)) /* FIXME: Streamline the conditions */ \
71 flags |= opt_default_value_flags[item->cls]; \
73 // FIXME: Is this still useful? Isn't it better to use OPT_ADD_DEFAULT_ITEM_FLAGS during init?
74 #define OPT_ITEM_FLAGS(item) ((item->flags & OPT_VALUE_FLAGS) ? item->flags : item->flags | opt_default_value_flags[item->cls])
76 const struct opt_section * opt_section_root;
78 #define FOREACHLINE(text) for (const char * begin = (text), * end = (text); (*end) && (end = strchrnul(begin, '\n')); begin = end+1)
80 static inline uns uns_min(uns x, uns y)
85 void opt_help_internal(const struct opt_section * help) {
89 for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
90 if (item->flags & OPT_NO_HELP) continue;
91 if (item->cls == OPT_CL_SECTION) {
99 FOREACHLINE(item->help)
103 struct opt_sectlist {
105 struct opt_section * sect;
106 } sections[sections_cnt];
109 const char *lines[lines_cnt][3];
110 memset(lines, 0, sizeof(lines));
113 int linelengths[3] = { -1, -1, -1 };
115 for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
116 if (item->flags & OPT_NO_HELP) continue;
118 if (item->cls == OPT_CL_HELP) {
119 if (!*(item->help)) {
123 #define SPLITLINES(text) do { \
124 FOREACHLINE(text) { \
126 for (const char * b = begin, * e = begin; (e < end) && (e = strchrnul(b, '\t')) && (e > end ? (e = end) : end); b = e+1) { \
127 lines[line][cell] = b; \
131 if (*e == '\t' && linelengths[cell] < (e - b)) \
132 linelengths[cell] = e-b; \
137 SPLITLINES(item->help);
141 if (item->cls == OPT_CL_SECTION) {
142 sections[s++] = (struct opt_sectlist) { .pos = line, .sect = item->u.section };
146 uns valoff = strchrnul(item->help, '\t') - item->help;
147 uns eol = strchrnul(item->help, '\n') - item->help;
150 #define VAL(it) ((OPT_ITEM_FLAGS(it) & OPT_REQUIRED_VALUE) ? stk_printf("=%.*s", valoff, item->help) : ((OPT_ITEM_FLAGS(it) & OPT_NO_VALUE) ? "" : stk_printf("(=%.*s)", valoff, item->help)))
152 lines[line][1] = stk_printf("--%s%s", item->name, VAL(item));
153 if (linelengths[1] < (int) strlen(lines[line][1]))
154 linelengths[1] = strlen(lines[line][1]);
156 if (linelengths[0] < 0)
160 lines[line][0] = stk_printf("-%c,", item->letter);
161 if (linelengths[0] < (int) strlen(lines[line][0]))
162 linelengths[0] = strlen(lines[line][0]);
167 lines[line][2] = item->help + valoff + 1;
172 if (*(item->help + eol))
173 SPLITLINES(item->help + eol + 1);
178 #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]
179 #define LASTFIELD(k) uns_min(strchrnul(lines[i][k], '\t') - lines[i][k], strchrnul(lines[i][k], '\n') - lines[i][k]), lines[i][k]
180 for (int i=0;i<line;i++) {
181 while (s < sections_cnt && sections[s].pos == i) {
182 opt_help_internal(sections[s].sect);
185 if (lines[i][0] == NULL)
187 else if (linelengths[0] == -1 || lines[i][1] == NULL)
188 printf("%.*s\n", LASTFIELD(0));
189 else if (linelengths[1] == -1 || lines[i][2] == NULL)
190 printf("%-*.*s %.*s\n", FIELD(0), LASTFIELD(1));
192 printf("%-*.*s %-*.*s %.*s\n", FIELD(0), FIELD(1), LASTFIELD(2));
194 while (s < sections_cnt && sections[s].pos == line) {
195 opt_help_internal(sections[s].sect);
200 static struct opt_precomputed * opt_find_item_shortopt(struct opt_context * oc, int chr) {
201 struct opt_precomputed * candidate = oc->shortopt[chr];
203 opt_failure("Invalid option -%c", chr);
204 if (candidate->count++ && (candidate->flags & OPT_SINGLE))
205 opt_failure("Option -%c appeared the second time.", candidate->item->letter);
209 static struct opt_precomputed * opt_find_item_longopt(struct opt_context * oc, char * str) {
210 uns len = strlen(str);
211 struct opt_precomputed * candidate = NULL;
213 for (int i=0; i<oc->opt_count; i++) {
214 if (!oc->opts[i]->name)
216 if (!strncmp(oc->opts[i]->name, str, len)) {
217 if (strlen(oc->opts[i]->name) == len) {
218 if (oc->opts[i]->count++ && (oc->opts[i]->flags & OPT_SINGLE))
219 opt_failure("Option %s appeared the second time.", oc->opts[i]->name);
224 opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, oc->opts[i]->name);
226 candidate = oc->opts[i];
228 if (!strncmp("no-", str, 3) && !strncmp(oc->opts[i]->name, str+3, len-3)) {
229 if (strlen(oc->opts[i]->name) == len-3) {
230 if (oc->opts[i]->count++ && (oc->opts[i]->flags & OPT_SINGLE))
231 opt_failure("Option %s appeared the second time.", oc->opts[i]->name);
236 opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, oc->opts[i]->name);
238 candidate = oc->opts[i];
245 opt_failure("Invalid option %s.", str);
248 #define OPT_PTR(type) ({ \
250 if (item->flags & OPT_MULTIPLE) { \
254 } * n = xmalloc(sizeof(*n)); \
255 clist_add_tail(item->ptr, &(n->n)); \
261 #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)))
262 static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * opt, char * value, int longopt) {
263 struct opt_item * item = opt->item;
264 for (int i=0;i<oc->hooks_before_value_count;i++)
265 oc->hooks_before_value[i]->u.call(item, value, oc->hooks_before_value[i]->ptr);
269 if (!value || !strcasecmp(value, "y") || !strcasecmp(value, "yes") || !strcasecmp(value, "true") || !strcasecmp(value, "1"))
270 *((int *) item->ptr) = 1 ^ (!!(opt->flags & OPT_NEGATIVE));
271 else if (!strcasecmp(value, "n") || !strcasecmp(value, "no") || !strcasecmp(value, "false") || !strcasecmp(value, "0"))
272 *((int *) item->ptr) = 0 ^ (!!(opt->flags & OPT_NEGATIVE));
274 opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): y/n, yes/no, true/false.", OPT_NAME);
279 switch (item->type) {
284 e = cf_parse_int(value, OPT_PTR(int));
286 opt_failure("Integer value parsing failed for %s: %s", OPT_NAME, e);
292 e = cf_parse_u64(value, OPT_PTR(u64));
294 opt_failure("Unsigned 64-bit value parsing failed for %s: %s", OPT_NAME, e);
298 *OPT_PTR(double) = NAN;
300 e = cf_parse_double(value, OPT_PTR(double));
302 opt_failure("Double value parsing failed for %s: %s", OPT_NAME, e);
306 e = cf_parse_ip("0.0.0.0", OPT_PTR(u32));
308 e = cf_parse_ip(value, OPT_PTR(u32));
310 opt_failure("IP parsing failed for %s: %s", OPT_NAME, e);
314 *OPT_PTR(const char *) = NULL;
316 *OPT_PTR(const char *) = xstrdup(value);
324 if (*((int *)item->ptr) != -1)
325 opt_failure("Multiple switches: %s", OPT_NAME);
327 *((int *)item->ptr) = item->u.value;
330 if (opt->flags & OPT_NEGATIVE)
331 (*((int *)item->ptr))--;
333 (*((int *)item->ptr))++;
336 item->u.call(item, value, item->ptr);
341 e = item->u.utype->parser(value, OPT_PTR(void*));
343 opt_failure("User defined type value parsing failed for %s: %s", OPT_NAME, e);
351 for (int i=0;i<oc->hooks_after_value_count;i++)
352 oc->hooks_after_value[i]->u.call(item, value, oc->hooks_after_value[i]->ptr);
356 static int opt_longopt(struct opt_context * oc, char ** argv, int index) {
358 char * name_in = argv[index] + 2; // skipping the -- on the beginning
359 uns pos = strchrnul(name_in, '=') - name_in;
360 struct opt_precomputed * opt = opt_find_item_longopt(oc, strndupa(name_in, pos)); // FIXME: free?
363 if (opt->item->cls == OPT_CL_BOOL && !strncmp(name_in, "no-", 3) && !strncmp(name_in+3, opt->item->name, pos-3))
365 else if (opt->flags & OPT_REQUIRED_VALUE) {
366 if (pos < strlen(name_in))
367 value = name_in + pos + 1;
369 value = argv[index+1];
371 opt_failure("Argument --%s must have a value but nothing supplied.", opt->name);
375 else if (opt->flags & OPT_MAYBE_VALUE) {
376 if (pos < strlen(name_in))
377 value = name_in + pos + 1;
380 if (pos < strlen(name_in))
381 opt_failure("Argument --%s must not have any value.", opt->name);
383 opt_parse_value(oc, opt, value, 1);
387 static int opt_shortopt(struct opt_context * oc, char ** argv, int index) {
389 struct opt_precomputed * opt;
390 while (argv[index][++chr] && (opt = opt_find_item_shortopt(oc, argv[index][chr]))) {
391 if (opt->flags & OPT_NO_VALUE) {
392 opt_parse_value(oc, opt, NULL, 0);
394 else if (opt->flags & OPT_REQUIRED_VALUE) {
395 if (chr == 1 && argv[index][2]) {
396 opt_parse_value(oc, opt, argv[index] + 2, 0);
399 else if (argv[index][chr+1])
400 opt_failure("Option -%c must have a value but found inside a bunch of short opts.", opt->item->letter);
401 else if (!argv[index+1])
402 opt_failure("Option -%c must have a value but nothing supplied.", opt->item->letter);
404 opt_parse_value(oc, opt, argv[index+1], 0);
408 else if (opt->flags & OPT_MAYBE_VALUE) {
409 if (chr == 1 && argv[index][2]) {
410 opt_parse_value(oc, opt, argv[index] + 2, 0);
414 opt_parse_value(oc, opt, NULL, 0);
421 if (argv[index][chr])
422 opt_failure("Unknown option -%c.", argv[index][chr]);
427 static void opt_positional(struct opt_context * oc, char * value) {
428 oc->positional_count++;
429 struct opt_precomputed * opt = opt_find_item_shortopt(oc, (oc->positional_count > oc->positional_max ? 256 : oc->positional_count + 256));
431 ASSERT(oc->positional_count > oc->positional_max);
432 opt_failure("Too many positional args.");
435 opt_parse_value(oc, opt, value, 2);
438 #define OPT_TRAVERSE_SECTIONS \
439 while (item->cls == OPT_CL_SECTION) { \
443 struct opt_stack * new_stk = alloca(sizeof(*new_stk)); \
444 new_stk->prev = stk; \
445 stk->next = new_stk; \
449 item = item->u.section->opt; \
451 if (item->cls == OPT_CL_END) { \
452 if (!stk->prev) break; \
458 void opt_parse(const struct opt_section * options, char ** argv) {
460 struct opt_item * this;
461 struct opt_stack * prev;
462 struct opt_stack * next;
463 } * stk = alloca(sizeof(*stk));
468 struct opt_context * oc = alloca(sizeof(*oc));
469 memset(oc, 0, sizeof (*oc));
474 for (struct opt_item * item = options->opt; ; item++) {
475 OPT_TRAVERSE_SECTIONS;
476 if (item->letter || item->name)
478 if (item->cls == OPT_CL_BOOL)
480 if (item->letter > 256)
481 oc->positional_max++;
482 if (item->cls == OPT_CL_HOOK)
486 oc->opts = alloca(sizeof(*oc->opts) * count);
487 oc->shortopt = alloca(sizeof(*oc->shortopt) * (oc->positional_max + 257));
488 memset(oc->shortopt, 0, sizeof(*oc->shortopt) * (oc->positional_max + 257));
489 oc->hooks_before_arg = alloca(sizeof (*oc->hooks_before_arg) * hooks);
490 oc->hooks_before_value = alloca(sizeof (*oc->hooks_before_value) * hooks);
491 oc->hooks_after_value = alloca(sizeof (*oc->hooks_after_value) * hooks);
493 oc->hooks_before_arg_count = 0;
494 oc->hooks_before_value_count = 0;
495 oc->hooks_after_value_count = 0;
499 for (struct opt_item * item = options->opt; ; item++) {
500 OPT_TRAVERSE_SECTIONS;
501 if (item->letter || item->name) {
502 struct opt_precomputed * opt = xmalloc(sizeof(*opt));
504 opt->flags = item->flags;
506 opt->name = item->name;
507 oc->opts[oc->opt_count++] = opt;
509 oc->shortopt[(int) item->letter] = opt;
510 OPT_ADD_DEFAULT_ITEM_FLAGS(item, opt->flags);
512 if (item->cls == OPT_CL_HOOK) {
513 if (item->flags & OPT_HOOK_BEFORE_ARG)
514 oc->hooks_before_arg[oc->hooks_before_arg_count++] = item;
515 else if (item->flags & OPT_HOOK_BEFORE_VALUE)
516 oc->hooks_before_value[oc->hooks_before_value_count++] = item;
517 else if (item->flags & OPT_HOOK_AFTER_VALUE)
518 oc->hooks_after_value[oc->hooks_after_value_count++] = item;
524 int force_positional = 0;
525 for (int i=0;argv[i];i++) {
526 for (int j=0;j<oc->hooks_before_arg_count;j++)
527 oc->hooks_before_arg[j]->u.call(NULL, NULL, oc->hooks_before_arg[j]->ptr);
528 if (argv[i][0] != '-' || force_positional) {
529 opt_positional(oc, argv[i]);
532 if (argv[i][1] == '-') {
533 if (argv[i][2] == '\0')
536 i += opt_longopt(oc, argv, i);
539 i += opt_shortopt(oc, argv, i);
541 opt_positional(oc, argv[i]);
545 for (int i=0;i<oc->positional_max+257;i++) {
546 if (!oc->shortopt[i])
548 if (!oc->shortopt[i]->count && (oc->shortopt[i]->flags & OPT_REQUIRED))
550 opt_failure("Required option -%c not found.", oc->shortopt[i]->item->letter);
552 opt_failure("Required positional argument #%d not found.", (i > 256) ? oc->shortopt[i]->item->letter-256 : oc->positional_max+1);
555 for (int i=0;i<oc->opt_count;i++) {
558 if (!oc->opts[i]->count && (oc->opts[i]->flags & OPT_REQUIRED))
559 opt_failure("Required option --%s not found.", oc->opts[i]->item->name);
563 static void opt_conf_end_of_options(struct cf_context *cc) {
565 if (cc->postpone_commit && cf_close_group())
566 opt_failure("Loading of configuration failed");
569 void opt_conf_internal(struct opt_item * opt, const char * value, void * data UNUSED) {
570 struct cf_context *cc = cf_get_context();
571 switch (opt->letter) {
575 opt_failure("Cannot set %s", value);
579 opt_failure("Cannot load config file %s", value);
581 #ifdef CONFIG_UCW_DEBUG
583 opt_conf_end_of_options(cc);
584 struct fastbuf *b = bfdopen(1, 4096);
592 opt_conf_parsed_count++;
595 void opt_conf_hook_internal(struct opt_item * opt, const char * value UNUSED, void * data UNUSED) {
598 OPT_CONF_HOOK_CONFIG,
600 } state = OPT_CONF_HOOK_BEGIN;
604 if (opt->letter == 'S' || opt->letter == 'C' || (opt->name && !strcmp(opt->name, "dumpconfig")))
608 case OPT_CONF_HOOK_BEGIN:
610 state = OPT_CONF_HOOK_CONFIG;
612 opt_conf_end_of_options(cf_get_context());
613 state = OPT_CONF_HOOK_OTHERS;
616 case OPT_CONF_HOOK_CONFIG:
618 opt_conf_end_of_options(cf_get_context());
619 state = OPT_CONF_HOOK_OTHERS;
622 case OPT_CONF_HOOK_OTHERS:
624 opt_failure("Config options (-C, -S) must stand before other options.");