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);
20 static void opt_failure(const char * mesg, ...) {
23 vfprintf(stderr, mesg, args);
24 fprintf(stderr, "\n");
25 exit(OPT_EXIT_BAD_ARGS);
29 #define OPT_ADD_DEFAULT_ITEM_FLAGS(item, flags) \
31 if (!(flags & OPT_VALUE_FLAGS) && \
32 (item->cls == OPT_CL_CALL || item->cls == OPT_CL_USER)) { \
33 fprintf(stderr, "You MUST specify some of the value flags for the %c/%s item.\n", item->letter, item->name); \
36 else if (!(flags & OPT_VALUE_FLAGS)) \
37 flags |= opt_default_value_flags[item->cls]; \
39 #define OPT_ITEM_FLAGS(item) ((item->flags & OPT_VALUE_FLAGS) ? item->flags : item->flags | opt_default_value_flags[item->cls])
41 const struct opt_section * opt_section_root;
43 #define FOREACHLINE(text) for (const char * begin = (text), * end = (text); (*end) && (end = strchrnul(begin, '\n')); begin = end+1)
45 void opt_help_noexit_internal(const struct opt_section * help) {
49 for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
50 if (item->flags & OPT_NO_HELP) continue;
51 if (item->cls == OPT_CL_SECTION) {
59 FOREACHLINE(item->help)
65 struct opt_section * sect;
66 } sections[sections_cnt];
69 const char *lines[lines_cnt][3];
70 memset(lines, 0, sizeof(lines));
73 int linelengths[3] = { -1, -1, -1 };
75 for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
76 if (item->flags & OPT_NO_HELP) continue;
78 if (item->cls == OPT_CL_HELP) {
83 #define SPLITLINES(text) do { \
86 for (const char * b = begin, * e = begin; (e < end) && (e = strchrnul(b, '\t')) && (e > end ? (e = end) : end); b = e+1) { \
87 lines[line][cell] = b; \
91 if (*e == '\t' && linelengths[cell] < (e - b)) \
92 linelengths[cell] = e-b; \
97 SPLITLINES(item->help);
101 if (item->cls == OPT_CL_SECTION) {
102 sections[s++] = (struct opt_sectlist) { .pos = line, .sect = item->u.section };
106 uns valoff = strchrnul(item->help, '\t') - item->help;
107 uns eol = strchrnul(item->help, '\n') - item->help;
110 #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)))
112 lines[line][1] = stk_printf("--%s%s", item->name, VAL(item));
113 if (linelengths[1] < (int) strlen(lines[line][1]))
114 linelengths[1] = strlen(lines[line][1]);
116 if (linelengths[0] < 0)
120 lines[line][0] = stk_printf("-%c,", item->letter);
121 if (linelengths[0] < (int) strlen(lines[line][0]))
122 linelengths[0] = strlen(lines[line][0]);
127 lines[line][2] = item->help + valoff + 1;
132 if (*(item->help + eol))
133 SPLITLINES(item->help + eol + 1);
138 #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]
139 #define LASTFIELD(k) MIN(strchrnul(lines[i][k], '\t')-lines[i][k],strchrnul(lines[i][k], '\n')-lines[i][k]), lines[i][k]
140 for (int i=0;i<line;i++) {
141 while (s < sections_cnt && sections[s].pos == i) {
142 opt_help_noexit_internal(sections[s].sect);
145 if (lines[i][0] == NULL)
147 else if (linelengths[0] == -1 || lines[i][1] == NULL)
148 printf("%.*s\n", LASTFIELD(0));
149 else if (linelengths[1] == -1 || lines[i][2] == NULL)
150 printf("%-*.*s %.*s\n", FIELD(0), LASTFIELD(1));
152 printf("%-*.*s %-*.*s %.*s\n", FIELD(0), FIELD(1), LASTFIELD(2));
154 while (s < sections_cnt && sections[s].pos == line) {
155 opt_help_noexit_internal(sections[s].sect);
160 struct opt_precomputed {
161 struct opt_precomputed_option {
162 struct opt_item * item;
167 struct opt_precomputed_option * shortopt[256];
171 static struct opt_precomputed_option * opt_find_item_shortopt(int chr, struct opt_precomputed * pre) {
172 struct opt_precomputed_option * candidate = pre->shortopt[chr];
173 if (candidate->count++ && (candidate->flags & OPT_SINGLE))
174 opt_failure("Option %s appeared the second time.", candidate->name);
178 static struct opt_precomputed_option * opt_find_item_longopt(char * str, struct opt_precomputed * pre) {
179 uns len = strlen(str);
180 struct opt_precomputed_option * candidate = NULL;
182 for (int i=0; i<pre->opt_count; i++) {
183 if (!strncmp(pre->opts[i]->name, str, len)) {
184 if (strlen(pre->opts[i]->name) == len) {
185 if (pre->opts[i]->count++ && (pre->opts[i]->flags & OPT_SINGLE))
186 opt_failure("Option %s appeared the second time.", pre->opts[i]->name);
191 opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, pre->opts[i]->name);
193 candidate = pre->opts[i];
195 if (!strncmp("no-", str, 3) && !strncmp(pre->opts[i]->name, str+3, len-3)) {
196 if (strlen(pre->opts[i]->name) == len-3) {
197 if (pre->opts[i]->count++ && (pre->opts[i]->flags & OPT_SINGLE))
198 opt_failure("Option %s appeared the second time.", pre->opts[i]->name);
203 opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, pre->opts[i]->name);
205 candidate = pre->opts[i];
212 opt_failure("Invalid option %s.", str);
215 #define OPT_NAME (longopt ? stk_printf("--%s", opt->name) : stk_printf("-%c", item->letter))
216 static void opt_parse_value(struct opt_precomputed_option * opt, char * value, int longopt) {
217 struct opt_item * item = opt->item;
220 if (!value || !strcasecmp(value, "y") || !strcasecmp(value, "yes") || !strcasecmp(value, "true") || !strcasecmp(value, "1"))
221 *((int *) item->ptr) = 1 ^ (!!(opt->flags & OPT_NEGATIVE));
222 else if (!strcasecmp(value, "n") || !strcasecmp(value, "no") || !strcasecmp(value, "false") || !strcasecmp(value, "0"))
223 *((int *) item->ptr) = 0 ^ (!!(opt->flags & OPT_NEGATIVE));
225 opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): y/n, yes/no, true/false.", OPT_NAME);
230 switch (item->type) {
233 *((int*)item->ptr) = 0;
235 e = cf_parse_int(value, item->ptr);
237 opt_failure("Integer value parsing failed for argument %s: %s", OPT_NAME, e);
241 *((u64*)item->ptr) = 0;
243 e = cf_parse_u64(value, item->ptr);
245 opt_failure("Unsigned 64-bit value parsing failed for argument %s: %s", OPT_NAME, e);
249 *((double*)item->ptr) = NAN;
251 e = cf_parse_double(value, item->ptr);
253 opt_failure("Double value parsing failed for argument %s: %s", OPT_NAME, e);
257 e = cf_parse_ip("0.0.0.0", item->ptr);
259 e = cf_parse_ip(value, item->ptr);
261 opt_failure("IP parsing failed for argument %s: %s", OPT_NAME, e);
267 item->ptr = strdup(value);
275 if (*((int *)item->ptr) != -1)
276 opt_failure("Multiple switches: %s", OPT_NAME);
278 *((int *)item->ptr) = item->u.value;
281 if (opt->flags & OPT_NEGATIVE)
282 (*((int *)item->ptr))--;
284 (*((int *)item->ptr))++;
286 item->u.call(item, value, item->ptr);
291 e = item->u.utype->parser(value, item->ptr);
293 opt_failure("User defined type value parsing failed for argument %s: %s", OPT_NAME, e);
302 static int opt_longopt(char ** argv, int index, struct opt_precomputed * pre) {
304 char * name_in = argv[index] + 2; // skipping the -- on the beginning
305 uns pos = strchrnul(name_in, '=') - name_in;
306 struct opt_precomputed_option * opt = opt_find_item_longopt(strndupa(name_in, pos), pre);
309 if (opt->item->cls == OPT_CL_BOOL && !strncmp(name_in, "no-", 3) && !strncmp(name_in+3, opt->item->name, pos-3))
311 else if (opt->flags & OPT_REQUIRED_VALUE) {
312 if (pos < strlen(name_in))
313 value = name_in + pos + 1;
315 value = argv[index+1];
319 else if (opt->flags & OPT_MAYBE_VALUE) {
320 if (pos < strlen(name_in))
321 value = name_in + pos + 1;
324 if (pos < strlen(name_in))
325 opt_failure("Argument %s must not have any value.", opt->name);
327 opt_parse_value(opt, value, 1);
331 static int opt_shortopt(char ** argv, int index, struct opt_precomputed * pre) {
333 struct opt_precomputed_option * opt;
334 while (argv[index][++chr] && (opt = opt_find_item_shortopt(argv[index][chr], pre))) {
335 if (opt->flags & OPT_NO_VALUE) {
336 opt_parse_value(opt, NULL, 0);
339 if (chr == 1 && (opt->flags & OPT_REQUIRED_VALUE)) {
340 if (argv[index][2]) {
341 opt_parse_value(opt, argv[index] + 2, 0);
345 opt_parse_value(opt, argv[index+1], 0);
349 else if (chr == 1 && (opt->flags & OPT_MAYBE_VALUE)) {
351 opt_parse_value(opt, argv[index] + 2, 0);
353 opt_parse_value(opt, NULL, 0);
355 else if (opt->flags & (OPT_REQUIRED_VALUE | OPT_MAYBE_VALUE)) {
356 if (argv[index][chr+1] || (opt->flags | OPT_MAYBE_VALUE))
357 opt_failure("Option -%c may or must have a value but found inside a bunch of short opts.", opt->item->letter);
359 opt_parse_value(opt, argv[index+1], 0);
365 if (argv[index][chr])
366 opt_failure("Unknown option -%c.", argv[index][chr]);
371 #define OPT_TRAVERSE_SECTIONS \
372 while (item->cls == OPT_CL_SECTION) { \
376 struct opt_stack * new_stk = alloca(sizeof(*new_stk)); \
377 new_stk->prev = stk; \
378 stk->next = new_stk; \
382 item = item->u.section->opt; \
384 if (item->cls == OPT_CL_END) { \
385 if (!stk->prev) break; \
391 void opt_parse(const struct opt_section * options, char ** argv, opt_positional * callback) {
392 opt_section_root = options;
395 struct opt_item * this;
396 struct opt_stack * prev;
397 struct opt_stack * next;
398 } * stk = alloca(sizeof(*stk));
403 struct opt_precomputed * pre = alloca(sizeof(*pre));
404 memset(pre, 0, sizeof (*pre));
408 for (struct opt_item * item = options->opt; ; item++) {
409 OPT_TRAVERSE_SECTIONS;
410 if (item->letter || item->name)
412 if (item->cls == OPT_CL_BOOL)
416 pre->opts = xmalloc(sizeof(*pre->opts) * count);
419 for (struct opt_item * item = options->opt; ; item++) {
420 OPT_TRAVERSE_SECTIONS;
421 if (item->letter || item->name) {
422 struct opt_precomputed_option * opt = xmalloc(sizeof(*opt));
424 opt->flags = item->flags;
426 opt->name = item->name;
427 pre->opts[pre->opt_count++] = opt;
429 pre->shortopt[(int) item->letter] = opt;
430 OPT_ADD_DEFAULT_ITEM_FLAGS(item, opt->flags);
434 int force_positional = 0;
435 for (int i=0;argv[i];i++) {
436 if (argv[i][0] != '-' || force_positional) {
440 if (argv[i][1] == '-') {
441 if (argv[i][2] == '\0')
444 i += opt_longopt(argv, i, pre);
447 i += opt_shortopt(argv, i, pre);
455 #include <ucw/fastbuf.h>
457 static void show_version(struct opt_item * opt UNUSED, const char * value UNUSED, void * data UNUSED) {
458 printf("This is a simple tea boiling console v0.1.\n");
462 struct teapot_temperature {
473 static char * temp_scale_str[] = { "C", "F", "K", "Re", "R" };
475 static enum TEAPOT_TYPE {
480 TEAPOT_UNDEFINED = -1
481 } set = TEAPOT_UNDEFINED;
483 static char * teapot_type_str[] = { "standard", "exclusive", "glass", "hands" };
485 static int english = 0;
486 static char * name = NULL;
487 static int sugar = 0;
488 static int verbose = 1;
489 static int with_gas = 0;
490 static int black_magic = 0;
492 static int water_amount = 0;
494 static const char * teapot_temperature_parser(char * in, void * ptr) {
495 struct teapot_temperature * temp = ptr;
497 const char * err = str_to_int(&temp->value, in, &next, 10);
500 if (!strcmp("C", next))
501 temp->scale = TEMP_CELSIUS;
502 else if (!strcmp("F", next))
503 temp->scale = TEMP_FAHRENHEIT;
504 else if (!strcmp("K", next))
505 temp->scale = TEMP_KELVIN;
506 else if (!strcmp("R", next))
507 temp->scale = TEMP_RANKINE;
508 else if (!strcmp("Re", next))
509 temp->scale = TEMP_REAUMUR;
511 fprintf(stderr, "Unknown scale: %s\n", next);
512 exit(OPT_EXIT_BAD_ARGS);
517 static void teapot_temperature_dumper(struct fastbuf * fb, void * ptr) {
518 struct teapot_temperature * temp = ptr;
519 bprintf(fb, "%d%s", temp->value, temp_scale_str[temp->scale]);
522 static struct cf_user_type teapot_temperature_t = {
523 .size = sizeof(struct teapot_temperature),
524 .name = "teapot_temperature_t",
525 .parser = (cf_parser1*) teapot_temperature_parser,
526 .dumper = (cf_dumper1*) teapot_temperature_dumper
529 static struct opt_section water_options = {
531 OPT_INT('w', "water", water_amount, OPT_REQUIRED | OPT_REQUIRED_VALUE, "<volume>\tAmount of water (in mls)"),
532 OPT_BOOL('G', "with-gas", with_gas, OPT_NO_VALUE, "\tUse water with gas"),
537 static struct opt_section help = {
539 OPT_HELP("A simple tea boiling console."),
540 OPT_HELP("Usage: teapot [options] name-of-the-tea"),
541 OPT_HELP("Black, green or white tea supported as well as fruit or herbal tea."),
542 OPT_HELP("You may specify more kinds of tea, all of them will be boiled for you, in the given order."),
544 OPT_HELP("Options:"),
546 OPT_CALL('V', "version", show_version, NULL, OPT_NO_VALUE, "\tShow the version"),
548 OPT_BOOL('e', "english-style", english, 0, "\tEnglish style (with milk)"),
549 OPT_INT('s', "sugar", sugar, OPT_REQUIRED_VALUE, "<spoons>\tAmount of sugar (in teaspoons)"),
550 OPT_SWITCH(0, "standard-set", set, TEAPOT_STANDARD, 0, "\tStandard teapot"),
551 OPT_SWITCH('x', "exclusive-set", set, TEAPOT_EXCLUSIVE, 0, "\tExclusive teapot"),
552 OPT_SWITCH('g', "glass-set", set, TEAPOT_GLASS, 0, "\tTransparent glass teapot"),
553 OPT_SWITCH('h', "hands", set, TEAPOT_HANDS, 0, "\tUse user's hands as a teapot (a bit dangerous)"),
554 OPT_USER('t', "temperature", temperature, teapot_temperature_t, OPT_REQUIRED_VALUE | OPT_REQUIRED,
555 "<value>\tWanted final temperature of the tea to be served\n"
556 "\t\tSupported scales: Celsius [60C], Fahrenheit [140F],\n"
557 "\t\t Kelvin [350K], Rankine [600R] and Reaumur [50Re]\n"
558 "\t\tOnly integer values allowed."),
559 OPT_INC('v', "verbose", verbose, 0, "\tVerbose (the more -v, the more verbose)"),
560 OPT_INC('q', "quiet", verbose, OPT_NEGATIVE, "\tQuiet (the more -q, the more quiet)"),
561 OPT_INT('b', "black-magic", black_magic, 0, "<strength>\tUse black magic to make the tea extraordinary delicious"),
562 OPT_BOOL('p', "pray", pray, OPT_SINGLE, "\tPray before boiling"),
564 OPT_HELP("Water options:"),
565 OPT_SECTION(water_options),
570 #define MAX_TEA_COUNT 30
571 static char * tea_list[MAX_TEA_COUNT];
572 static int tea_num = 0;
573 static void add_tea(const char * name) {
574 if (tea_num >= MAX_TEA_COUNT) {
575 fprintf(stderr, "Cannot boil more than %d teas.\n", MAX_TEA_COUNT);
576 exit(OPT_EXIT_BAD_ARGS);
578 tea_list[tea_num++] = strdup(name);
581 static void boil_tea(const char * name) {
582 printf("Boiling a tea: %s\n", name);
585 int main(int argc, char ** argv)
587 opt_parse(&help, argv+1, add_tea);
589 printf("Parsed values:\n");
590 printf("English style: %s\n", english ? "yes" : "no");
592 printf("Sugar: %d teaspoons\n", sugar);
594 printf("Chosen teapot: %s\n", teapot_type_str[set]);
595 printf("Temperature: %d%s\n", temperature.value, temp_scale_str[temperature.scale]);
596 printf("Verbosity: %d\n", verbose);
598 printf("Black magic: %d\n", black_magic);
599 printf("Prayer: %s\n", pray ? "yes" : "no");
600 printf("Water amount: %d\n", water_amount);
601 printf("Gas: %s\n", with_gas ? "yes" : "no");
602 for (int i=0; i<tea_num; i++)
603 boil_tea(tea_list[i]);
605 printf("Everything OK. Bye.\n");