]> mj.ucw.cz Git - libucw.git/blob - ucw/opt.c
d1a19f9bd95f0358845694cf99f14c444e1c9a03
[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 = xstrdup(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       if (!value)
317         opt_failure("Argument --%s must have a value but nothing supplied.", opt->name);
318       eaten++;
319     }
320   }
321   else if (opt->flags & OPT_MAYBE_VALUE) {
322     if (pos < strlen(name_in))
323       value = name_in + pos + 1;
324   }
325   else {
326     if (pos < strlen(name_in))
327       opt_failure("Argument --%s must not have any value.", opt->name);
328   }
329   opt_parse_value(opt, value, 1);
330   return eaten;
331 }
332
333 static int opt_shortopt(char ** argv, int index, struct opt_precomputed * pre) {
334   int chr = 0;
335   struct opt_precomputed_option * opt;
336   while (argv[index][++chr] && (opt = opt_find_item_shortopt(argv[index][chr], pre))) {
337     if (opt->flags & OPT_NO_VALUE) {
338       opt_parse_value(opt, NULL, 0);
339       continue;
340     }
341     else if (opt->flags & OPT_REQUIRED_VALUE) {
342       if (chr == 1 && argv[index][2])
343         opt_parse_value(opt, argv[index] + 2, 0);
344       else if (argv[index][chr+1])
345         opt_failure("Option -%c must have a value but found inside a bunch of short opts.", opt->item->letter);
346       else if (!argv[index+1])
347         opt_failure("Option -%c must have a value but nothing supplied.", opt->item->letter);
348       else {
349         opt_parse_value(opt, argv[index+1], 0);
350         return 1;
351       }
352     }
353     else if (opt->flags & OPT_MAYBE_VALUE) {
354       if (chr == 1 && argv[index][2])
355         opt_parse_value(opt, argv[index] + 2, 0);
356       else
357         opt_parse_value(opt, NULL, 0);
358     }
359     else {
360       ASSERT(0);
361     }
362   }
363
364   if (argv[index][chr])
365     opt_failure("Unknown option -%c.", argv[index][chr]);
366   
367   return 0;
368 }
369
370 #define OPT_TRAVERSE_SECTIONS \
371     while (item->cls == OPT_CL_SECTION) { \
372       if (stk->next) \
373         stk = stk->next; \
374       else { \
375         struct opt_stack * new_stk = alloca(sizeof(*new_stk)); \
376         new_stk->prev = stk; \
377         stk->next = new_stk; \
378         stk = new_stk; \
379       } \
380       stk->this = item; \
381       item = item->u.section->opt; \
382     } \
383     if (item->cls == OPT_CL_END) { \
384       if (!stk->prev) break; \
385       item = stk->this; \
386       stk = stk->prev; \
387       continue; \
388     }
389
390 void opt_parse(const struct opt_section * options, char ** argv, opt_positional * callback) {
391   opt_section_root = options;
392
393   struct opt_stack {
394     struct opt_item * this;
395     struct opt_stack * prev;
396     struct opt_stack * next;
397   } * stk = alloca(sizeof(*stk));
398   stk->this = NULL;
399   stk->prev = NULL;
400   stk->next = NULL;
401
402   struct opt_precomputed * pre = alloca(sizeof(*pre));
403   memset(pre, 0, sizeof (*pre));
404
405   int count = 0;
406
407   for (struct opt_item * item = options->opt; ; item++) {
408     OPT_TRAVERSE_SECTIONS;
409     if (item->letter || item->name)
410       count++;
411     if (item->cls == OPT_CL_BOOL)
412       count++;
413   }
414   
415   pre->opts = xmalloc(sizeof(*pre->opts) * count);
416   pre->opt_count = 0;
417
418   for (struct opt_item * item = options->opt; ; item++) {
419     OPT_TRAVERSE_SECTIONS;
420     if (item->letter || item->name) {
421       struct opt_precomputed_option * opt = xmalloc(sizeof(*opt));
422       opt->item = item;
423       opt->flags = item->flags;
424       opt->count = 0;
425       opt->name = item->name;
426       pre->opts[pre->opt_count++] = opt;
427       if (item->letter)
428         pre->shortopt[(int) item->letter] = opt;
429       OPT_ADD_DEFAULT_ITEM_FLAGS(item, opt->flags);
430     }
431   }
432
433   int force_positional = 0;
434   for (int i=0;argv[i];i++) {
435     if (argv[i][0] != '-' || force_positional) {
436       callback(argv[i]);
437     }
438     else {
439       if (argv[i][1] == '-') {
440         if (argv[i][2] == '\0')
441           force_positional++;
442         else
443           i += opt_longopt(argv, i, pre);
444       }
445       else if (argv[i][1])
446         i += opt_shortopt(argv, i, pre);
447       else
448         callback(argv[i]);
449     }
450   }
451 }
452
453 #ifdef TEST
454 #include <ucw/fastbuf.h>
455
456 static void show_version(struct opt_item * opt UNUSED, const char * value UNUSED, void * data UNUSED) {
457   printf("This is a simple tea boiling console v0.1.\n");
458   exit(EXIT_SUCCESS);
459 }
460
461 struct teapot_temperature {
462   enum {
463     TEMP_CELSIUS = 0,
464     TEMP_FAHRENHEIT,
465     TEMP_KELVIN,
466     TEMP_REAUMUR,
467     TEMP_RANKINE
468   } scale;
469   int value;
470 } temperature;
471
472 static char * temp_scale_str[] = { "C", "F", "K", "Re", "R" };
473
474 static enum TEAPOT_TYPE {
475   TEAPOT_STANDARD = 0,
476   TEAPOT_EXCLUSIVE,
477   TEAPOT_GLASS,
478   TEAPOT_HANDS,
479   TEAPOT_UNDEFINED = -1
480 } set = TEAPOT_UNDEFINED;
481
482 static char * teapot_type_str[] = { "standard", "exclusive", "glass", "hands" };
483
484 static int english = 0;
485 static char * name = NULL;
486 static int sugar = 0;
487 static int verbose = 1;
488 static int with_gas = 0;
489 static int black_magic = 0;
490 static int pray = 0;
491 static int water_amount = 0;
492
493 static const char * teapot_temperature_parser(char * in, void * ptr) {
494   struct teapot_temperature * temp = ptr;
495   const char * next;
496   const char * err = str_to_int(&temp->value, in, &next, 10);
497   if (err)
498     return err;
499   if (!strcmp("C", next))
500     temp->scale = TEMP_CELSIUS;
501   else if (!strcmp("F", next))
502     temp->scale = TEMP_FAHRENHEIT;
503   else if (!strcmp("K", next))
504     temp->scale = TEMP_KELVIN;
505   else if (!strcmp("R", next))
506     temp->scale = TEMP_RANKINE;
507   else if (!strcmp("Re", next))
508     temp->scale = TEMP_REAUMUR;
509   else {
510     fprintf(stderr, "Unknown scale: %s\n", next);
511     exit(OPT_EXIT_BAD_ARGS);
512   }
513   return NULL;
514 }
515
516 static void teapot_temperature_dumper(struct fastbuf * fb, void * ptr) {
517   struct teapot_temperature * temp = ptr;
518   bprintf(fb, "%d%s", temp->value, temp_scale_str[temp->scale]);
519 }
520
521 static struct cf_user_type teapot_temperature_t = {
522   .size = sizeof(struct teapot_temperature),
523   .name = "teapot_temperature_t",
524   .parser = (cf_parser1*) teapot_temperature_parser,
525   .dumper = (cf_dumper1*) teapot_temperature_dumper
526 };
527
528 static struct opt_section water_options = {
529   OPT_ITEMS {
530     OPT_INT('w', "water", water_amount, OPT_REQUIRED | OPT_REQUIRED_VALUE, "<volume>\tAmount of water (in mls)"),
531     OPT_BOOL('G', "with-gas", with_gas, OPT_NO_VALUE, "\tUse water with gas"),
532     OPT_END
533   }
534 };
535
536 static struct opt_section help = {
537   OPT_ITEMS {
538     OPT_HELP("A simple tea boiling console."),
539     OPT_HELP("Usage: teapot [options] name-of-the-tea"),
540     OPT_HELP("Black, green or white tea supported as well as fruit or herbal tea."),
541     OPT_HELP("You may specify more kinds of tea, all of them will be boiled for you, in the given order."),
542     OPT_HELP(""),
543     OPT_HELP("Options:"),
544     OPT_HELP_OPTION,
545     OPT_CALL('V', "version", show_version, NULL, OPT_NO_VALUE, "\tShow the version"),
546     OPT_HELP(""),
547     OPT_BOOL('e', "english-style", english, 0, "\tEnglish style (with milk)"),
548     OPT_INT('s', "sugar", sugar, OPT_REQUIRED_VALUE, "<spoons>\tAmount of sugar (in teaspoons)"),
549     OPT_SWITCH(0, "standard-set", set, TEAPOT_STANDARD, 0, "\tStandard teapot"),
550     OPT_SWITCH('x', "exclusive-set", set, TEAPOT_EXCLUSIVE, 0, "\tExclusive teapot"),
551     OPT_SWITCH('g', "glass-set", set, TEAPOT_GLASS, 0, "\tTransparent glass teapot"),
552     OPT_SWITCH('h', "hands", set, TEAPOT_HANDS, 0, "\tUse user's hands as a teapot (a bit dangerous)"),
553     OPT_USER('t', "temperature", temperature, teapot_temperature_t, OPT_REQUIRED_VALUE | OPT_REQUIRED,
554                   "<value>\tWanted final temperature of the tea to be served\n"
555               "\t\tSupported scales:  Celsius [60C], Fahrenheit [140F],\n"
556               "\t\t                   Kelvin [350K], Rankine [600R] and Reaumur [50Re]\n"
557               "\t\tOnly integer values allowed."),
558     OPT_INC('v', "verbose", verbose, 0, "\tVerbose (the more -v, the more verbose)"),
559     OPT_INC('q', "quiet", verbose, OPT_NEGATIVE, "\tQuiet (the more -q, the more quiet)"),
560     OPT_INT('b', "black-magic", black_magic, 0, "<strength>\tUse black magic to make the tea extraordinary delicious"),
561     OPT_BOOL('p', "pray", pray, OPT_SINGLE, "\tPray before boiling"),
562     OPT_HELP(""),
563     OPT_HELP("Water options:"),
564     OPT_SECTION(water_options),
565     OPT_END
566   }
567 };
568
569 #define MAX_TEA_COUNT 30
570 static char * tea_list[MAX_TEA_COUNT];
571 static int tea_num = 0;
572 static void add_tea(const char * name) {
573   if (tea_num >= MAX_TEA_COUNT) {
574     fprintf(stderr, "Cannot boil more than %d teas.\n", MAX_TEA_COUNT);
575     exit(OPT_EXIT_BAD_ARGS);
576   }
577   tea_list[tea_num++] = xstrdup(name);
578 }
579
580 static void boil_tea(const char * name) {
581   printf("Boiling a tea: %s\n", name);
582 }
583
584 int main(int argc, char ** argv)
585 {
586   opt_parse(&help, argv+1, add_tea);
587
588   printf("Parsed values:\n");
589   printf("English style: %s\n", english ? "yes" : "no");
590   if (sugar)
591     printf("Sugar: %d teaspoons\n", sugar);
592   if (set != -1)
593     printf("Chosen teapot: %s\n", teapot_type_str[set]);
594   printf("Temperature: %d%s\n", temperature.value, temp_scale_str[temperature.scale]);
595   printf("Verbosity: %d\n", verbose);
596   if (black_magic)
597     printf("Black magic: %d\n", black_magic);
598   printf("Prayer: %s\n", pray ? "yes" : "no");
599   printf("Water amount: %d\n", water_amount);
600   printf("Gas: %s\n", with_gas ? "yes" : "no");
601   for (int i=0; i<tea_num; i++)
602     boil_tea(tea_list[i]);
603
604   printf("Everything OK. Bye.\n");
605 }
606
607 #endif