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/stkstring.h>
14 #include <ucw/strtonum.h>
19 static void opt_failure(const char * mesg, ...) FORMAT_CHECK(printf,1,2) NONRET;
20 static void opt_failure(const char * mesg, ...) {
23 vfprintf(stderr, mesg, args);
24 fprintf(stderr, "\n");
26 exit(OPT_EXIT_BAD_ARGS);
30 #define OPT_ADD_DEFAULT_ITEM_FLAGS(item, flags) \
32 if (item->letter >= 256) { \
33 if (flags & OPT_VALUE_FLAGS) \
34 flags &= ~OPT_VALUE_FLAGS; \
35 flags |= OPT_REQUIRED_VALUE; \
37 if (!(flags & OPT_VALUE_FLAGS) && \
38 (item->cls == OPT_CL_CALL || item->cls == OPT_CL_USER)) { \
39 fprintf(stderr, "You MUST specify some of the value flags for the %c/%s item.\n", item->letter, item->name); \
42 else if (!(flags & OPT_VALUE_FLAGS)) \
43 flags |= opt_default_value_flags[item->cls]; \
45 #define OPT_ITEM_FLAGS(item) ((item->flags & OPT_VALUE_FLAGS) ? item->flags : item->flags | opt_default_value_flags[item->cls])
47 const struct opt_section * opt_section_root;
49 #define FOREACHLINE(text) for (const char * begin = (text), * end = (text); (*end) && (end = strchrnul(begin, '\n')); begin = end+1)
51 void opt_help_internal(const struct opt_section * help) {
55 for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
56 if (item->flags & OPT_NO_HELP) continue;
57 if (item->cls == OPT_CL_SECTION) {
65 FOREACHLINE(item->help)
71 struct opt_section * sect;
72 } sections[sections_cnt];
75 const char *lines[lines_cnt][3];
76 memset(lines, 0, sizeof(lines));
79 int linelengths[3] = { -1, -1, -1 };
81 for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
82 if (item->flags & OPT_NO_HELP) continue;
84 if (item->cls == OPT_CL_HELP) {
89 #define SPLITLINES(text) do { \
92 for (const char * b = begin, * e = begin; (e < end) && (e = strchrnul(b, '\t')) && (e > end ? (e = end) : end); b = e+1) { \
93 lines[line][cell] = b; \
97 if (*e == '\t' && linelengths[cell] < (e - b)) \
98 linelengths[cell] = e-b; \
103 SPLITLINES(item->help);
107 if (item->cls == OPT_CL_SECTION) {
108 sections[s++] = (struct opt_sectlist) { .pos = line, .sect = item->u.section };
112 uns valoff = strchrnul(item->help, '\t') - item->help;
113 uns eol = strchrnul(item->help, '\n') - item->help;
116 #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)))
118 lines[line][1] = stk_printf("--%s%s", item->name, VAL(item));
119 if (linelengths[1] < (int) strlen(lines[line][1]))
120 linelengths[1] = strlen(lines[line][1]);
122 if (linelengths[0] < 0)
126 lines[line][0] = stk_printf("-%c,", item->letter);
127 if (linelengths[0] < (int) strlen(lines[line][0]))
128 linelengths[0] = strlen(lines[line][0]);
133 lines[line][2] = item->help + valoff + 1;
138 if (*(item->help + eol))
139 SPLITLINES(item->help + eol + 1);
144 #define FIELD(k) linelengths[k], MIN(strchrnul(lines[i][k], '\t')-lines[i][k],strchrnul(lines[i][k], '\n')-lines[i][k]), lines[i][k]
145 #define LASTFIELD(k) MIN(strchrnul(lines[i][k], '\t')-lines[i][k],strchrnul(lines[i][k], '\n')-lines[i][k]), lines[i][k]
146 for (int i=0;i<line;i++) {
147 while (s < sections_cnt && sections[s].pos == i) {
148 opt_help_internal(sections[s].sect);
151 if (lines[i][0] == NULL)
153 else if (linelengths[0] == -1 || lines[i][1] == NULL)
154 printf("%.*s\n", LASTFIELD(0));
155 else if (linelengths[1] == -1 || lines[i][2] == NULL)
156 printf("%-*.*s %.*s\n", FIELD(0), LASTFIELD(1));
158 printf("%-*.*s %-*.*s %.*s\n", FIELD(0), FIELD(1), LASTFIELD(2));
160 while (s < sections_cnt && sections[s].pos == line) {
161 opt_help_internal(sections[s].sect);
166 static int opt_positional_max = 0;
167 static int opt_positional_count = 0;
169 struct opt_precomputed {
170 struct opt_precomputed_option {
171 struct opt_item * item;
176 struct opt_precomputed_option ** shortopt;
180 static struct opt_precomputed_option * opt_find_item_shortopt(int chr, struct opt_precomputed * pre) {
181 struct opt_precomputed_option * candidate = pre->shortopt[chr];
182 if (candidate->count++ && (candidate->flags & OPT_SINGLE))
183 opt_failure("Option %s appeared the second time.", candidate->name);
187 static struct opt_precomputed_option * opt_find_item_longopt(char * str, struct opt_precomputed * pre) {
188 uns len = strlen(str);
189 struct opt_precomputed_option * candidate = NULL;
191 for (int i=0; i<pre->opt_count; i++) {
192 if (!strncmp(pre->opts[i]->name, str, len)) {
193 if (strlen(pre->opts[i]->name) == len) {
194 if (pre->opts[i]->count++ && (pre->opts[i]->flags & OPT_SINGLE))
195 opt_failure("Option %s appeared the second time.", pre->opts[i]->name);
200 opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, pre->opts[i]->name);
202 candidate = pre->opts[i];
204 if (!strncmp("no-", str, 3) && !strncmp(pre->opts[i]->name, str+3, len-3)) {
205 if (strlen(pre->opts[i]->name) == len-3) {
206 if (pre->opts[i]->count++ && (pre->opts[i]->flags & OPT_SINGLE))
207 opt_failure("Option %s appeared the second time.", pre->opts[i]->name);
212 opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, pre->opts[i]->name);
214 candidate = pre->opts[i];
221 opt_failure("Invalid option %s.", str);
224 #define OPT_NAME (longopt == 2 ? stk_printf("positional arg #%d", opt_positional_count) : (longopt == 1 ? stk_printf("--%s", opt->name) : stk_printf("-%c", item->letter)))
225 static void opt_parse_value(struct opt_precomputed_option * opt, char * value, int longopt) {
226 struct opt_item * item = opt->item;
229 if (!value || !strcasecmp(value, "y") || !strcasecmp(value, "yes") || !strcasecmp(value, "true") || !strcasecmp(value, "1"))
230 *((int *) item->ptr) = 1 ^ (!!(opt->flags & OPT_NEGATIVE));
231 else if (!strcasecmp(value, "n") || !strcasecmp(value, "no") || !strcasecmp(value, "false") || !strcasecmp(value, "0"))
232 *((int *) item->ptr) = 0 ^ (!!(opt->flags & OPT_NEGATIVE));
234 opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): y/n, yes/no, true/false.", OPT_NAME);
239 switch (item->type) {
242 *((int*)item->ptr) = 0;
244 e = cf_parse_int(value, item->ptr);
246 opt_failure("Integer value parsing failed for %s: %s", OPT_NAME, e);
250 *((u64*)item->ptr) = 0;
252 e = cf_parse_u64(value, item->ptr);
254 opt_failure("Unsigned 64-bit value parsing failed for %s: %s", OPT_NAME, e);
258 *((double*)item->ptr) = NAN;
260 e = cf_parse_double(value, item->ptr);
262 opt_failure("Double value parsing failed for %s: %s", OPT_NAME, e);
266 e = cf_parse_ip("0.0.0.0", item->ptr);
268 e = cf_parse_ip(value, item->ptr);
270 opt_failure("IP parsing failed for %s: %s", OPT_NAME, e);
276 *((const char **) (item->ptr)) = xstrdup(value);
284 if (*((int *)item->ptr) != -1)
285 opt_failure("Multiple switches: %s", OPT_NAME);
287 *((int *)item->ptr) = item->u.value;
290 if (opt->flags & OPT_NEGATIVE)
291 (*((int *)item->ptr))--;
293 (*((int *)item->ptr))++;
295 item->u.call(item, value, item->ptr);
300 e = item->u.utype->parser(value, item->ptr);
302 opt_failure("User defined type value parsing failed for %s: %s", OPT_NAME, e);
311 static int opt_longopt(char ** argv, int index, struct opt_precomputed * pre) {
313 char * name_in = argv[index] + 2; // skipping the -- on the beginning
314 uns pos = strchrnul(name_in, '=') - name_in;
315 struct opt_precomputed_option * opt = opt_find_item_longopt(strndupa(name_in, pos), pre);
318 if (opt->item->cls == OPT_CL_BOOL && !strncmp(name_in, "no-", 3) && !strncmp(name_in+3, opt->item->name, pos-3))
320 else if (opt->flags & OPT_REQUIRED_VALUE) {
321 if (pos < strlen(name_in))
322 value = name_in + pos + 1;
324 value = argv[index+1];
326 opt_failure("Argument --%s must have a value but nothing supplied.", opt->name);
330 else if (opt->flags & OPT_MAYBE_VALUE) {
331 if (pos < strlen(name_in))
332 value = name_in + pos + 1;
335 if (pos < strlen(name_in))
336 opt_failure("Argument --%s must not have any value.", opt->name);
338 opt_parse_value(opt, value, 1);
342 static int opt_shortopt(char ** argv, int index, struct opt_precomputed * pre) {
344 struct opt_precomputed_option * opt;
345 while (argv[index][++chr] && (opt = opt_find_item_shortopt(argv[index][chr], pre))) {
346 if (opt->flags & OPT_NO_VALUE) {
347 opt_parse_value(opt, NULL, 0);
350 else if (opt->flags & OPT_REQUIRED_VALUE) {
351 if (chr == 1 && argv[index][2])
352 opt_parse_value(opt, argv[index] + 2, 0);
353 else if (argv[index][chr+1])
354 opt_failure("Option -%c must have a value but found inside a bunch of short opts.", opt->item->letter);
355 else if (!argv[index+1])
356 opt_failure("Option -%c must have a value but nothing supplied.", opt->item->letter);
358 opt_parse_value(opt, argv[index+1], 0);
362 else if (opt->flags & OPT_MAYBE_VALUE) {
363 if (chr == 1 && argv[index][2])
364 opt_parse_value(opt, argv[index] + 2, 0);
366 opt_parse_value(opt, NULL, 0);
373 if (argv[index][chr])
374 opt_failure("Unknown option -%c.", argv[index][chr]);
379 static void opt_positional(char * value, struct opt_precomputed * pre) {
380 opt_positional_count++;
381 struct opt_precomputed_option * opt = opt_find_item_shortopt((opt_positional_count > opt_positional_max ? 256 : opt_positional_count + 256), pre);
383 ASSERT(opt_positional_count > opt_positional_max);
384 opt_failure("Too many positional args.");
387 opt_parse_value(opt, value, 2);
390 #define OPT_TRAVERSE_SECTIONS \
391 while (item->cls == OPT_CL_SECTION) { \
395 struct opt_stack * new_stk = alloca(sizeof(*new_stk)); \
396 new_stk->prev = stk; \
397 stk->next = new_stk; \
401 item = item->u.section->opt; \
403 if (item->cls == OPT_CL_END) { \
404 if (!stk->prev) break; \
410 void opt_parse(const struct opt_section * options, char ** argv) {
411 opt_section_root = options;
414 struct opt_item * this;
415 struct opt_stack * prev;
416 struct opt_stack * next;
417 } * stk = alloca(sizeof(*stk));
422 struct opt_precomputed * pre = alloca(sizeof(*pre));
423 memset(pre, 0, sizeof (*pre));
427 for (struct opt_item * item = options->opt; ; item++) {
428 OPT_TRAVERSE_SECTIONS;
429 if (item->letter || item->name)
431 if (item->cls == OPT_CL_BOOL)
433 if (item->letter > 256)
434 opt_positional_max++;
437 pre->opts = alloca(sizeof(*pre->opts) * count);
438 pre->shortopt = alloca(sizeof(*pre->shortopt) * (opt_positional_max + 257));
439 memset(pre->shortopt, 0, sizeof(*pre->shortopt) * (opt_positional_max + 257));
443 for (struct opt_item * item = options->opt; ; item++) {
444 OPT_TRAVERSE_SECTIONS;
445 if (item->letter || item->name) {
446 struct opt_precomputed_option * opt = xmalloc(sizeof(*opt));
448 opt->flags = item->flags;
450 opt->name = item->name;
451 pre->opts[pre->opt_count++] = opt;
453 pre->shortopt[(int) item->letter] = opt;
454 OPT_ADD_DEFAULT_ITEM_FLAGS(item, opt->flags);
458 int force_positional = 0;
459 for (int i=0;argv[i];i++) {
460 if (argv[i][0] != '-' || force_positional) {
461 opt_positional(argv[i], pre);
464 if (argv[i][1] == '-') {
465 if (argv[i][2] == '\0')
468 i += opt_longopt(argv, i, pre);
471 i += opt_shortopt(argv, i, pre);
473 opt_positional(argv[i], pre);
477 for (int i=0;i<opt_positional_max+257;i++) {
478 if (!pre->shortopt[i])
480 if (!pre->shortopt[i]->count && (pre->shortopt[i]->flags | OPT_REQUIRED))
482 opt_failure("Required option -%c not found.\n", pre->shortopt[i]->item->letter);
484 opt_failure("Required positional argument #%d not found.\n", (i > 256) ? pre->shortopt[i]->item->letter-256 : opt_positional_max+1);
487 for (int i=0;i<pre->opt_count;i++) {
490 if (!pre->opts[i]->count && (pre->opts[i]->flags | OPT_REQUIRED))
491 opt_failure("Required option --%s not found.\n", pre->opts[i]->item->name);
496 #include <ucw/fastbuf.h>
498 static void show_version(struct opt_item * opt UNUSED, const char * value UNUSED, void * data UNUSED) {
499 printf("This is a simple tea boiling console v0.1.\n");
503 struct teapot_temperature {
514 static char * temp_scale_str[] = { "C", "F", "K", "Re", "R" };
516 static enum TEAPOT_TYPE {
521 TEAPOT_UNDEFINED = -1
522 } set = TEAPOT_UNDEFINED;
524 static char * teapot_type_str[] = { "standard", "exclusive", "glass", "hands" };
526 static int english = 0;
527 static int sugar = 0;
528 static int verbose = 1;
529 static int with_gas = 0;
530 static int black_magic = 0;
532 static int water_amount = 0;
533 static char * first_tea = NULL;
535 #define MAX_TEA_COUNT 30
536 static char * tea_list[MAX_TEA_COUNT];
537 static int tea_num = 0;
538 static void add_tea(struct opt_item * opt UNUSED, const char * name, void * data) {
539 char ** tea_list = data;
540 if (tea_num >= MAX_TEA_COUNT) {
541 fprintf(stderr, "Cannot boil more than %d teas.\n", MAX_TEA_COUNT);
542 exit(OPT_EXIT_BAD_ARGS);
544 tea_list[tea_num++] = xstrdup(name);
547 static const char * teapot_temperature_parser(char * in, void * ptr) {
548 struct teapot_temperature * temp = ptr;
550 const char * err = str_to_int(&temp->value, in, &next, 10);
553 if (!strcmp("C", next))
554 temp->scale = TEMP_CELSIUS;
555 else if (!strcmp("F", next))
556 temp->scale = TEMP_FAHRENHEIT;
557 else if (!strcmp("K", next))
558 temp->scale = TEMP_KELVIN;
559 else if (!strcmp("R", next))
560 temp->scale = TEMP_RANKINE;
561 else if (!strcmp("Re", next))
562 temp->scale = TEMP_REAUMUR;
564 fprintf(stderr, "Unknown scale: %s\n", next);
565 exit(OPT_EXIT_BAD_ARGS);
570 static void teapot_temperature_dumper(struct fastbuf * fb, void * ptr) {
571 struct teapot_temperature * temp = ptr;
572 bprintf(fb, "%d%s", temp->value, temp_scale_str[temp->scale]);
575 static struct cf_user_type teapot_temperature_t = {
576 .size = sizeof(struct teapot_temperature),
577 .name = "teapot_temperature_t",
578 .parser = (cf_parser1*) teapot_temperature_parser,
579 .dumper = (cf_dumper1*) teapot_temperature_dumper
582 static struct opt_section water_options = {
584 OPT_INT('w', "water", water_amount, OPT_REQUIRED | OPT_REQUIRED_VALUE, "<volume>\tAmount of water (in mls)"),
585 OPT_BOOL('G', "with-gas", with_gas, OPT_NO_VALUE, "\tUse water with gas"),
590 static struct opt_section help = {
592 OPT_HELP("A simple tea boiling console."),
593 OPT_HELP("Usage: teapot [options] name-of-the-tea"),
594 OPT_HELP("Black, green or white tea supported as well as fruit or herbal tea."),
595 OPT_HELP("You may specify more kinds of tea, all of them will be boiled for you, in the given order."),
597 OPT_HELP("Options:"),
599 OPT_CALL('V', "version", show_version, NULL, OPT_NO_VALUE, "\tShow the version"),
601 OPT_BOOL('e', "english-style", english, 0, "\tEnglish style (with milk)"),
602 OPT_INT('s', "sugar", sugar, OPT_REQUIRED_VALUE, "<spoons>\tAmount of sugar (in teaspoons)"),
603 OPT_SWITCH(0, "standard-set", set, TEAPOT_STANDARD, 0, "\tStandard teapot"),
604 OPT_SWITCH('x', "exclusive-set", set, TEAPOT_EXCLUSIVE, 0, "\tExclusive teapot"),
605 OPT_SWITCH('g', "glass-set", set, TEAPOT_GLASS, 0, "\tTransparent glass teapot"),
606 OPT_SWITCH('h', "hands", set, TEAPOT_HANDS, 0, "\tUse user's hands as a teapot (a bit dangerous)"),
607 OPT_USER('t', "temperature", temperature, teapot_temperature_t, OPT_REQUIRED_VALUE | OPT_REQUIRED,
608 "<value>\tWanted final temperature of the tea to be served\n"
609 "\t\tSupported scales: Celsius [60C], Fahrenheit [140F],\n"
610 "\t\t Kelvin [350K], Rankine [600R] and Reaumur [50Re]\n"
611 "\t\tOnly integer values allowed."),
612 OPT_INC('v', "verbose", verbose, 0, "\tVerbose (the more -v, the more verbose)"),
613 OPT_INC('q', "quiet", verbose, OPT_NEGATIVE, "\tQuiet (the more -q, the more quiet)"),
614 OPT_INT('b', "black-magic", black_magic, 0, "<strength>\tUse black magic to make the tea extraordinary delicious"),
615 OPT_BOOL('p', "pray", pray, OPT_SINGLE, "\tPray before boiling"),
616 OPT_STRING(OPT_POSITIONAL(1), NULL, first_tea, OPT_REQUIRED | OPT_NO_HELP, ""),
617 OPT_CALL(OPT_POSITIONAL_TAIL, NULL, add_tea, &tea_list, OPT_NO_HELP, ""),
619 OPT_HELP("Water options:"),
620 OPT_SECTION(water_options),
625 static void boil_tea(const char * name) {
626 printf("Boiling a tea: %s\n", name);
629 int main(int argc UNUSED, char ** argv)
631 opt_parse(&help, argv+1);
633 printf("Parsed values:\n");
634 printf("English style: %s\n", english ? "yes" : "no");
636 printf("Sugar: %d teaspoons\n", sugar);
638 printf("Chosen teapot: %s\n", teapot_type_str[set]);
639 printf("Temperature: %d%s\n", temperature.value, temp_scale_str[temperature.scale]);
640 printf("Verbosity: %d\n", verbose);
642 printf("Black magic: %d\n", black_magic);
643 printf("Prayer: %s\n", pray ? "yes" : "no");
644 printf("Water amount: %d\n", water_amount);
645 printf("Gas: %s\n", with_gas ? "yes" : "no");
646 printf("First tea: %s\n", first_tea);
647 for (int i=0; i<tea_num; i++)
648 boil_tea(tea_list[i]);
650 printf("Everything OK. Bye.\n");