]> mj.ucw.cz Git - libucw.git/blob - ucw/opt.c
Opt: fixed checking --no args and OPT_SINGLE
[libucw.git] / ucw / opt.c
1 /*
2  *      UCW Library -- Parsing of command line options
3  *
4  *      (c) 2013 Jan Moskyto Matejka <mq@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include <ucw/lib.h>
11 #include <ucw/opt.h>
12 #include <ucw/conf.h>
13 #include <ucw/stkstring.h>
14 #include <ucw/strtonum.h>
15
16 #include <alloca.h>
17 #include <math.h>
18
19 static void opt_failure(const char * mesg, ...) FORMAT_CHECK(printf,1,2);
20 static void opt_failure(const char * mesg, ...) {
21   va_list args;
22   va_start(args, mesg);
23   vfprintf(stderr, mesg, args);
24   fprintf(stderr, "\n");
25   exit(OPT_EXIT_BAD_ARGS);
26   va_end(args);
27 }
28
29 #define OPT_ADD_DEFAULT_ITEM_FLAGS(item, flags) \
30   do { \
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); \
34       ASSERT(0); \
35     } \
36     else if (!(flags & OPT_VALUE_FLAGS)) \
37       flags |= opt_default_value_flags[item->cls]; \
38   } while (0)
39 #define OPT_ITEM_FLAGS(item) ((item->flags & OPT_VALUE_FLAGS) ? item->flags : item->flags | opt_default_value_flags[item->cls])
40
41 const struct opt_section * opt_section_root;
42
43 #define FOREACHLINE(text) for (const char * begin = (text), * end = (text); (*end) && (end = strchrnul(begin, '\n')); begin = end+1)
44
45 void opt_help_noexit_internal(const struct opt_section * help) {
46   int sections_cnt = 0;
47   int lines_cnt = 0;
48
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) {
52       sections_cnt++;
53       continue;
54     }
55     if (!*(item->help)) {
56       lines_cnt++;
57       continue;
58     }
59     FOREACHLINE(item->help)
60       lines_cnt++;
61   }
62
63   struct opt_sectlist {
64     int pos;
65     struct opt_section * sect;
66   } sections[sections_cnt];
67   int s = 0;
68
69   const char *lines[lines_cnt][3];
70   memset(lines, 0, sizeof(lines));
71   int line = 0;
72
73   int linelengths[3] = { -1, -1, -1 };
74
75   for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
76     if (item->flags & OPT_NO_HELP) continue;
77
78     if (item->cls == OPT_CL_HELP) {
79       if (!*(item->help)) {
80         line++;
81         continue;
82       }
83 #define SPLITLINES(text) do { \
84       FOREACHLINE(text) { \
85         int cell = 0; \
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; \
88           if (cell >= 2) \
89             break; \
90           else \
91             if (*e == '\t' && linelengths[cell] < (e - b)) \
92               linelengths[cell] = e-b; \
93           cell++; \
94         } \
95         line++; \
96       } } while (0)
97       SPLITLINES(item->help);
98       continue;
99     }
100
101     if (item->cls == OPT_CL_SECTION) {
102       sections[s++] = (struct opt_sectlist) { .pos = line, .sect = item->u.section };
103       continue;
104     }
105
106     uns valoff = strchrnul(item->help, '\t') - item->help;
107     uns eol = strchrnul(item->help, '\n') - item->help;
108     if (valoff > eol)
109       valoff = eol;
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)))
111     if (item->name) {
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]);
115       lines[line][0] = "";
116       if (linelengths[0] < 0)
117         linelengths[0] = 0;
118     }
119     if (item->letter) {
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]);
123     }
124 #undef VAL
125
126     if (eol > valoff) {
127       lines[line][2] = item->help + valoff + 1;
128     }
129
130     line++;
131
132     if (*(item->help + eol))
133       SPLITLINES(item->help + eol + 1);
134   }
135 #undef SPLITLINES
136
137   s = 0;
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);
143       s++;
144     }
145     if (lines[i][0] == NULL)
146       printf("\n");
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));
151     else
152       printf("%-*.*s  %-*.*s  %.*s\n", FIELD(0), FIELD(1), LASTFIELD(2));
153   }
154   while (s < sections_cnt && sections[s].pos == line) {
155     opt_help_noexit_internal(sections[s].sect);
156     s++;
157   }
158 }
159
160 struct opt_precomputed {
161   struct opt_precomputed_option {
162     struct opt_item * item;
163     const char * name;
164     short flags;
165     short count;
166   } ** opts;
167   struct opt_precomputed_option * shortopt[256];
168   short opt_count;
169 };
170
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);
175   return candidate;
176 }
177
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;
181
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);
187
188         return pre->opts[i];
189       }
190       if (candidate)
191         opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, pre->opts[i]->name);
192       else
193         candidate = pre->opts[i];
194     }
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);
199
200         return pre->opts[i];
201       }
202       if (candidate)
203         opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, pre->opts[i]->name);
204       else
205         candidate = pre->opts[i];
206     }
207   }
208
209   if (candidate)
210     return candidate;
211
212   opt_failure("Invalid option %s.", str);
213 }
214
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;
218   switch (item->cls) {
219     case OPT_CL_BOOL:
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));
224       else
225         opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): y/n, yes/no, true/false.", OPT_NAME);
226       break;
227     case OPT_CL_STATIC:
228       {
229         char * e = NULL;
230         switch (item->type) {
231           case CT_INT:
232             if (!value)
233               *((int*)item->ptr) = 0;
234             else
235               e = cf_parse_int(value, item->ptr);
236             if (e)
237               opt_failure("Integer value parsing failed for argument %s: %s", OPT_NAME, e);
238             break;
239           case CT_U64:
240             if (!value)
241               *((u64*)item->ptr) = 0;
242             else
243               e = cf_parse_u64(value, item->ptr);
244             if (e)
245               opt_failure("Unsigned 64-bit value parsing failed for argument %s: %s", OPT_NAME, e);
246             break;
247           case CT_DOUBLE:
248             if (!value)
249               *((double*)item->ptr) = NAN;
250             else
251               e = cf_parse_double(value, item->ptr);
252             if (e)
253               opt_failure("Double value parsing failed for argument %s: %s", OPT_NAME, e);
254             break;
255           case CT_IP:
256             if (!value)
257               e = cf_parse_ip("0.0.0.0", item->ptr);
258             else
259               e = cf_parse_ip(value, item->ptr);
260             if (e)
261               opt_failure("IP parsing failed for argument %s: %s", OPT_NAME, e);
262             break;
263           case CT_STRING:
264             if (!value)
265               item->ptr = NULL;
266             else
267               item->ptr = strdup(value);
268             break;
269           default:
270             ASSERT(0);
271         }
272         break;
273       }
274     case OPT_CL_SWITCH:
275       if (*((int *)item->ptr) != -1)
276         opt_failure("Multiple switches: %s", OPT_NAME);
277       else
278         *((int *)item->ptr) = item->u.value;
279       break;
280     case OPT_CL_INC:
281       if (opt->flags & OPT_NEGATIVE)
282         (*((int *)item->ptr))--;
283       else
284         (*((int *)item->ptr))++;
285     case OPT_CL_CALL:
286       item->u.call(item, value, item->ptr);
287       break;
288     case OPT_CL_USER:
289       {
290         char * e = NULL;
291         e = item->u.utype->parser(value, item->ptr);
292         if (e)
293           opt_failure("User defined type value parsing failed for argument %s: %s", OPT_NAME, e);
294         break;
295       }
296     default:
297       ASSERT(0);
298   }
299 }
300 #undef OPT_NAME
301
302 static int opt_longopt(char ** argv, int index, struct opt_precomputed * pre) {
303   int eaten = 0;
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);
307   char * value = NULL;
308
309   if (opt->item->cls == OPT_CL_BOOL && !strncmp(name_in, "no-", 3) && !strncmp(name_in+3, opt->item->name, pos-3))
310     value = "n";
311   else if (opt->flags & OPT_REQUIRED_VALUE) {
312     if (pos < strlen(name_in))
313       value = name_in + pos + 1;
314     else {
315       value = argv[index+1];
316       eaten++;
317     }
318   }
319   else if (opt->flags & OPT_MAYBE_VALUE) {
320     if (pos < strlen(name_in))
321       value = name_in + pos + 1;
322   }
323   else {
324     if (pos < strlen(name_in))
325       opt_failure("Argument %s must not have any value.", opt->name);
326   }
327   opt_parse_value(opt, value, 1);
328   return eaten;
329 }
330
331 static int opt_shortopt(char ** argv, int index, struct opt_precomputed * pre) {
332   int chr = 0;
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);
337       continue;
338     }
339     if (chr == 1 && (opt->flags & OPT_REQUIRED_VALUE)) {
340       if (argv[index][2]) {
341         opt_parse_value(opt, argv[index] + 2, 0);
342         return 0;
343       }
344       else {
345         opt_parse_value(opt, argv[index+1], 0);
346         return 1;
347       }
348     }
349     else if (chr == 1 && (opt->flags & OPT_MAYBE_VALUE)) {
350       if (argv[index][2])
351         opt_parse_value(opt, argv[index] + 2, 0);
352       else
353         opt_parse_value(opt, NULL, 0);
354     }
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);
358       else {
359         opt_parse_value(opt, argv[index+1], 0);
360         return 1;
361       }
362     }
363   }
364
365   if (argv[index][chr])
366     opt_failure("Unknown option -%c.", argv[index][chr]);
367   
368   return 0;
369 }
370
371 #define OPT_TRAVERSE_SECTIONS \
372     while (item->cls == OPT_CL_SECTION) { \
373       if (stk->next) \
374         stk = stk->next; \
375       else { \
376         struct opt_stack * new_stk = alloca(sizeof(*new_stk)); \
377         new_stk->prev = stk; \
378         stk->next = new_stk; \
379         stk = new_stk; \
380       } \
381       stk->this = item; \
382       item = item->u.section->opt; \
383     } \
384     if (item->cls == OPT_CL_END) { \
385       if (!stk->prev) break; \
386       item = stk->this; \
387       stk = stk->prev; \
388       continue; \
389     }
390
391 void opt_parse(const struct opt_section * options, char ** argv, opt_positional * callback) {
392   opt_section_root = options;
393
394   struct opt_stack {
395     struct opt_item * this;
396     struct opt_stack * prev;
397     struct opt_stack * next;
398   } * stk = alloca(sizeof(*stk));
399   stk->this = NULL;
400   stk->prev = NULL;
401   stk->next = NULL;
402
403   struct opt_precomputed * pre = alloca(sizeof(*pre));
404   memset(pre, 0, sizeof (*pre));
405
406   int count = 0;
407
408   for (struct opt_item * item = options->opt; ; item++) {
409     OPT_TRAVERSE_SECTIONS;
410     if (item->letter || item->name)
411       count++;
412     if (item->cls == OPT_CL_BOOL)
413       count++;
414   }
415   
416   pre->opts = xmalloc(sizeof(*pre->opts) * count);
417   pre->opt_count = 0;
418
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));
423       opt->item = item;
424       opt->flags = item->flags;
425       opt->count = 0;
426       opt->name = item->name;
427       pre->opts[pre->opt_count++] = opt;
428       if (item->letter)
429         pre->shortopt[(int) item->letter] = opt;
430       OPT_ADD_DEFAULT_ITEM_FLAGS(item, opt->flags);
431     }
432   }
433
434   int force_positional = 0;
435   for (int i=0;argv[i];i++) {
436     if (argv[i][0] != '-' || force_positional) {
437       callback(argv[i]);
438     }
439     else {
440       if (argv[i][1] == '-') {
441         if (argv[i][2] == '\0')
442           force_positional++;
443         else
444           i += opt_longopt(argv, i, pre);
445       }
446       else if (argv[i][1])
447         i += opt_shortopt(argv, i, pre);
448       else
449         callback(argv[i]);
450     }
451   }
452 }
453
454 #ifdef TEST
455 #include <ucw/fastbuf.h>
456
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");
459   exit(EXIT_SUCCESS);
460 }
461
462 struct teapot_temperature {
463   enum {
464     TEMP_CELSIUS = 0,
465     TEMP_FAHRENHEIT,
466     TEMP_KELVIN,
467     TEMP_REAUMUR,
468     TEMP_RANKINE
469   } scale;
470   int value;
471 } temperature;
472
473 static char * temp_scale_str[] = { "C", "F", "K", "Re", "R" };
474
475 static enum TEAPOT_TYPE {
476   TEAPOT_STANDARD = 0,
477   TEAPOT_EXCLUSIVE,
478   TEAPOT_GLASS,
479   TEAPOT_HANDS,
480   TEAPOT_UNDEFINED = -1
481 } set = TEAPOT_UNDEFINED;
482
483 static char * teapot_type_str[] = { "standard", "exclusive", "glass", "hands" };
484
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;
491 static int pray = 0;
492 static int water_amount = 0;
493
494 static const char * teapot_temperature_parser(char * in, void * ptr) {
495   struct teapot_temperature * temp = ptr;
496   const char * next;
497   const char * err = str_to_int(&temp->value, in, &next, 10);
498   if (err)
499     return err;
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;
510   else {
511     fprintf(stderr, "Unknown scale: %s\n", next);
512     exit(OPT_EXIT_BAD_ARGS);
513   }
514   return NULL;
515 }
516
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]);
520 }
521
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
527 };
528
529 static struct opt_section water_options = {
530   OPT_ITEMS {
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"),
533     OPT_END
534   }
535 };
536
537 static struct opt_section help = {
538   OPT_ITEMS {
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."),
543     OPT_HELP(""),
544     OPT_HELP("Options:"),
545     OPT_HELP_OPTION,
546     OPT_CALL('V', "version", show_version, NULL, OPT_NO_VALUE, "\tShow the version"),
547     OPT_HELP(""),
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"),
563     OPT_HELP(""),
564     OPT_HELP("Water options:"),
565     OPT_SECTION(water_options),
566     OPT_END
567   }
568 };
569
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);
577   }
578   tea_list[tea_num++] = strdup(name);
579 }
580
581 static void boil_tea(const char * name) {
582   printf("Boiling a tea: %s\n", name);
583 }
584
585 int main(int argc, char ** argv)
586 {
587   opt_parse(&help, argv+1, add_tea);
588
589   printf("Parsed values:\n");
590   printf("English style: %s\n", english ? "yes" : "no");
591   if (sugar)
592     printf("Sugar: %d teaspoons\n", sugar);
593   if (set != -1)
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);
597   if (black_magic)
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]);
604
605   printf("Everything OK. Bye.\n");
606 }
607
608 #endif