]> mj.ucw.cz Git - libucw.git/blob - ucw/opt.c
Opt: Removed my bogus comment
[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/conf-internal.h>
14 #include <ucw/fastbuf.h>
15 #include <ucw/stkstring.h>
16 #include <ucw/strtonum.h>
17
18 #include <alloca.h>
19 #include <math.h>
20
21 // FIXME: Do we need these?
22 int opt_parsed_count = 0;
23 int opt_conf_parsed_count = 0;
24
25 struct opt_precomputed {
26   struct opt_item * item;
27   const char * name;
28   short flags;
29   short count;
30 };
31
32 struct opt_context {
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;
38   short opt_count;
39   short hooks_before_arg_count;
40   short hooks_before_value_count;
41   short hooks_after_value_count;
42   int positional_max;
43   int positional_count;
44 };
45
46 static void opt_failure(const char * mesg, ...) FORMAT_CHECK(printf,1,2) NONRET;
47 static void opt_failure(const char * mesg, ...) {
48   va_list args;
49   va_start(args, mesg);
50   vfprintf(stderr, mesg, args);
51   fprintf(stderr, "\n");
52   opt_usage();
53   exit(OPT_EXIT_BAD_ARGS);
54   va_end(args);         // FIXME: Does this make a sense after exit()?
55 }
56
57 // FIXME: This could be an inline function, couldn't it?
58 #define OPT_ADD_DEFAULT_ITEM_FLAGS(item, flags) \
59   do { \
60     if (item->letter >= 256) { \
61       if (flags & OPT_VALUE_FLAGS) /* FIXME: Redundant condition */ \
62         flags &= ~OPT_VALUE_FLAGS; \
63       flags |= OPT_REQUIRED_VALUE; \
64     } \
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); \
68       ASSERT(0); \
69     } \
70     else if (!(flags & OPT_VALUE_FLAGS)) /* FIXME: Streamline the conditions */ \
71       flags |= opt_default_value_flags[item->cls]; \
72   } while (0)
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])
75
76 const struct opt_section * opt_section_root;
77
78 #define FOREACHLINE(text) for (const char * begin = (text), * end = (text); (*end) && (end = strchrnul(begin, '\n')); begin = end+1)
79
80 static inline uns uns_min(uns x, uns y)
81 {
82   return MIN(x, y);
83 }
84
85 void opt_help_internal(const struct opt_section * help) {
86   int sections_cnt = 0;
87   int lines_cnt = 0;
88
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) {
92       sections_cnt++;
93       continue;
94     }
95     if (!*(item->help)) {
96       lines_cnt++;
97       continue;
98     }
99     FOREACHLINE(item->help)
100       lines_cnt++;
101   }
102
103   struct opt_sectlist {
104     int pos;
105     struct opt_section * sect;
106   } sections[sections_cnt];
107   int s = 0;
108
109   const char *lines[lines_cnt][3];
110   memset(lines, 0, sizeof(lines));
111   int line = 0;
112
113   int linelengths[3] = { -1, -1, -1 };
114
115   for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
116     if (item->flags & OPT_NO_HELP) continue;
117
118     if (item->cls == OPT_CL_HELP) {
119       if (!*(item->help)) {
120         line++;
121         continue;
122       }
123 #define SPLITLINES(text) do { \
124       FOREACHLINE(text) { \
125         int cell = 0; \
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; \
128           if (cell >= 2) \
129             break; \
130           else \
131             if (*e == '\t' && linelengths[cell] < (e - b)) \
132               linelengths[cell] = e-b; \
133           cell++; \
134         } \
135         line++; \
136       } } while (0)
137       SPLITLINES(item->help);
138       continue;
139     }
140
141     if (item->cls == OPT_CL_SECTION) {
142       sections[s++] = (struct opt_sectlist) { .pos = line, .sect = item->u.section };
143       continue;
144     }
145
146     uns valoff = strchrnul(item->help, '\t') - item->help;
147     uns eol = strchrnul(item->help, '\n') - item->help;
148     if (valoff > eol)
149       valoff = eol;
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)))
151     if (item->name) {
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]);
155       lines[line][0] = "";
156       if (linelengths[0] < 0)
157         linelengths[0] = 0;
158     }
159     if (item->letter) {
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]);
163     }
164 #undef VAL
165
166     if (eol > valoff) {
167       lines[line][2] = item->help + valoff + 1;
168     }
169
170     line++;
171
172     if (*(item->help + eol))
173       SPLITLINES(item->help + eol + 1);
174   }
175 #undef SPLITLINES
176
177   s = 0;
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);
183       s++;
184     }
185     if (lines[i][0] == NULL)
186       printf("\n");
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));
191     else
192       printf("%-*.*s  %-*.*s  %.*s\n", FIELD(0), FIELD(1), LASTFIELD(2));
193   }
194   while (s < sections_cnt && sections[s].pos == line) {
195     opt_help_internal(sections[s].sect);
196     s++;
197   }
198 }
199
200 static struct opt_precomputed * opt_find_item_shortopt(struct opt_context * oc, int chr) {
201   struct opt_precomputed * candidate = oc->shortopt[chr];
202   if (!candidate)
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);
206   return candidate;
207 }
208
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;
212
213   for (int i=0; i<oc->opt_count; i++) {
214     if (!oc->opts[i]->name)
215       continue;
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);
220
221         return oc->opts[i];
222       }
223       if (candidate)
224         opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, oc->opts[i]->name);
225       else
226         candidate = oc->opts[i];
227     }
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);
232
233         return oc->opts[i];
234       }
235       if (candidate)
236         opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, oc->opts[i]->name);
237       else
238         candidate = oc->opts[i];
239     }
240   }
241
242   if (candidate)
243     return candidate;
244
245   opt_failure("Invalid option %s.", str);
246 }
247
248 #define OPT_PTR(type) ({ \
249   type * ptr; \
250   if (item->flags & OPT_MULTIPLE) { \
251     struct { \
252       cnode n; \
253       type v; \
254     } * n = xmalloc(sizeof(*n)); \
255     clist_add_tail(item->ptr, &(n->n)); \
256     ptr = &(n->v); \
257   } else \
258     ptr = item->ptr; \
259   ptr; })
260
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);
266
267   switch (item->cls) {
268     case OPT_CL_BOOL:
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));
273       else
274         opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): y/n, yes/no, true/false.", OPT_NAME);
275       break;
276     case OPT_CL_STATIC:
277       {
278         char * e = NULL;
279         switch (item->type) {
280           case CT_INT:
281             if (!value)
282               *OPT_PTR(int) = 0;
283             else
284               e = cf_parse_int(value, OPT_PTR(int));
285             if (e)
286               opt_failure("Integer value parsing failed for %s: %s", OPT_NAME, e);
287             break;
288           case CT_U64:
289             if (!value)
290               *OPT_PTR(u64) = 0;
291             else
292               e = cf_parse_u64(value, OPT_PTR(u64));
293             if (e)
294               opt_failure("Unsigned 64-bit value parsing failed for %s: %s", OPT_NAME, e);
295             break;
296           case CT_DOUBLE:
297             if (!value)
298               *OPT_PTR(double) = NAN;
299             else
300               e = cf_parse_double(value, OPT_PTR(double));
301             if (e)
302               opt_failure("Double value parsing failed for %s: %s", OPT_NAME, e);
303             break;
304           case CT_IP:
305             if (!value)
306               e = cf_parse_ip("0.0.0.0", OPT_PTR(u32));
307             else
308               e = cf_parse_ip(value, OPT_PTR(u32));
309             if (e)
310               opt_failure("IP parsing failed for %s: %s", OPT_NAME, e);
311             break;
312           case CT_STRING:
313             if (!value)
314               *OPT_PTR(const char *) = NULL;
315             else
316               *OPT_PTR(const char *) = xstrdup(value);
317             break;
318           default:
319             ASSERT(0);
320         }
321         break;
322       }
323     case OPT_CL_SWITCH:
324       if (*((int *)item->ptr) != -1)
325         opt_failure("Multiple switches: %s", OPT_NAME);
326       else
327         *((int *)item->ptr) = item->u.value;
328       break;
329     case OPT_CL_INC:
330       if (opt->flags & OPT_NEGATIVE)
331         (*((int *)item->ptr))--;
332       else
333         (*((int *)item->ptr))++;
334       break;
335     case OPT_CL_CALL:
336       item->u.call(item, value, item->ptr);
337       break;
338     case OPT_CL_USER:
339       {
340         char * e = NULL;
341         e = item->u.utype->parser(value, OPT_PTR(void*));
342         if (e)
343           opt_failure("User defined type value parsing failed for %s: %s", OPT_NAME, e);
344         break;
345       }
346     default:
347       ASSERT(0);
348   }
349   opt_parsed_count++;
350
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);
353 }
354 #undef OPT_NAME
355
356 static int opt_longopt(struct opt_context * oc, char ** argv, int index) {
357   int eaten = 0;
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));
361   char * value = NULL;
362
363   if (opt->item->cls == OPT_CL_BOOL && !strncmp(name_in, "no-", 3) && !strncmp(name_in+3, opt->item->name, pos-3))
364     value = "n";
365   else if (opt->flags & OPT_REQUIRED_VALUE) {
366     if (pos < strlen(name_in))
367       value = name_in + pos + 1;
368     else {
369       value = argv[index+1];
370       if (!value)
371         opt_failure("Argument --%s must have a value but nothing supplied.", opt->name);
372       eaten++;
373     }
374   }
375   else if (opt->flags & OPT_MAYBE_VALUE) {
376     if (pos < strlen(name_in))
377       value = name_in + pos + 1;
378   }
379   else {
380     if (pos < strlen(name_in))
381       opt_failure("Argument --%s must not have any value.", opt->name);
382   }
383   opt_parse_value(oc, opt, value, 1);
384   return eaten;
385 }
386
387 static int opt_shortopt(struct opt_context * oc, char ** argv, int index) {
388   int chr = 0;
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);
393     }
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);
397         return 0;
398       }
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);
403       else {
404         opt_parse_value(oc, opt, argv[index+1], 0);
405         return 1;
406       }
407     }
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);
411         return 0;
412       }
413       else
414         opt_parse_value(oc, opt, NULL, 0);
415     }
416     else {
417       ASSERT(0);
418     }
419   }
420
421   if (argv[index][chr])
422     opt_failure("Unknown option -%c.", argv[index][chr]);
423
424   return 0;
425 }
426
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));
430   if (!opt) {
431     ASSERT(oc->positional_count > oc->positional_max);
432     opt_failure("Too many positional args.");
433   }
434
435   opt_parse_value(oc, opt, value, 2);
436 }
437
438 #define OPT_TRAVERSE_SECTIONS \
439     while (item->cls == OPT_CL_SECTION) { \
440       if (stk->next) \
441         stk = stk->next; \
442       else { \
443         struct opt_stack * new_stk = alloca(sizeof(*new_stk)); \
444         new_stk->prev = stk; \
445         stk->next = new_stk; \
446         stk = new_stk; \
447       } \
448       stk->this = item; \
449       item = item->u.section->opt; \
450     } \
451     if (item->cls == OPT_CL_END) { \
452       if (!stk->prev) break; \
453       item = stk->this; \
454       stk = stk->prev; \
455       continue; \
456     }
457
458 void opt_parse(const struct opt_section * options, char ** argv) {
459   struct opt_stack {
460     struct opt_item * this;
461     struct opt_stack * prev;
462     struct opt_stack * next;
463   } * stk = alloca(sizeof(*stk));
464   stk->this = NULL;
465   stk->prev = NULL;
466   stk->next = NULL;
467
468   struct opt_context * oc = alloca(sizeof(*oc));
469   memset(oc, 0, sizeof (*oc));
470
471   int count = 0;
472   int hooks = 0;
473
474   for (struct opt_item * item = options->opt; ; item++) {
475     OPT_TRAVERSE_SECTIONS;
476     if (item->letter || item->name)
477       count++;
478     if (item->cls == OPT_CL_BOOL)
479       count++;
480     if (item->letter > 256)
481       oc->positional_max++;
482     if (item->cls == OPT_CL_HOOK)
483       hooks++;
484   }
485
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);
492
493   oc->hooks_before_arg_count = 0;
494   oc->hooks_before_value_count = 0;
495   oc->hooks_after_value_count = 0;
496
497   oc->opt_count = 0;
498
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));
503       opt->item = item;
504       opt->flags = item->flags;
505       opt->count = 0;
506       opt->name = item->name;
507       oc->opts[oc->opt_count++] = opt;
508       if (item->letter)
509         oc->shortopt[(int) item->letter] = opt;
510       OPT_ADD_DEFAULT_ITEM_FLAGS(item, opt->flags);
511     }
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;
519       else
520         ASSERT(0);
521     }
522   }
523
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]);
530     }
531     else {
532       if (argv[i][1] == '-') {
533         if (argv[i][2] == '\0')
534           force_positional++;
535         else
536           i += opt_longopt(oc, argv, i);
537       }
538       else if (argv[i][1])
539         i += opt_shortopt(oc, argv, i);
540       else
541         opt_positional(oc, argv[i]);
542     }
543   }
544
545   for (int i=0;i<oc->positional_max+257;i++) {
546     if (!oc->shortopt[i])
547       continue;
548     if (!oc->shortopt[i]->count && (oc->shortopt[i]->flags & OPT_REQUIRED))
549       if (i < 256)
550         opt_failure("Required option -%c not found.", oc->shortopt[i]->item->letter);
551       else
552         opt_failure("Required positional argument #%d not found.", (i > 256) ? oc->shortopt[i]->item->letter-256 : oc->positional_max+1);
553   }
554
555   for (int i=0;i<oc->opt_count;i++) {
556     if (!oc->opts[i])
557       continue;
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);
560   }
561 }
562
563 static void opt_conf_end_of_options(struct cf_context *cc) {
564   cf_load_default(cc);
565   if (cc->postpone_commit && cf_close_group())
566     opt_failure("Loading of configuration failed");
567 }
568
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) {
572     case 'S':
573       cf_load_default(cc);
574       if (cf_set(value))
575         opt_failure("Cannot set %s", value);
576       break;
577     case 'C':
578       if (cf_load(value))
579         opt_failure("Cannot load config file %s", value);
580       break;
581 #ifdef CONFIG_UCW_DEBUG
582     case '0':
583       opt_conf_end_of_options(cc);
584       struct fastbuf *b = bfdopen(1, 4096);
585       cf_dump_sections(b);
586       bclose(b);
587       exit(0);
588       break;
589 #endif
590   }
591
592   opt_conf_parsed_count++;
593 }
594
595 void opt_conf_hook_internal(struct opt_item * opt, const char * value UNUSED, void * data UNUSED) {
596   static enum {
597     OPT_CONF_HOOK_BEGIN,
598     OPT_CONF_HOOK_CONFIG,
599     OPT_CONF_HOOK_OTHERS
600   } state = OPT_CONF_HOOK_BEGIN;
601
602   int confopt = 0;
603
604   if (opt->letter == 'S' || opt->letter == 'C' || (opt->name && !strcmp(opt->name, "dumpconfig")))
605     confopt = 1;
606
607   switch (state) {
608     case OPT_CONF_HOOK_BEGIN:
609       if (confopt)
610         state = OPT_CONF_HOOK_CONFIG;
611       else {
612         opt_conf_end_of_options(cf_get_context());
613         state = OPT_CONF_HOOK_OTHERS;
614       }
615       break;
616     case OPT_CONF_HOOK_CONFIG:
617       if (!confopt) {
618         opt_conf_end_of_options(cf_get_context());
619         state = OPT_CONF_HOOK_OTHERS;
620       }
621       break;
622     case OPT_CONF_HOOK_OTHERS:
623       if (confopt)
624         opt_failure("Config options (-C, -S) must stand before other options.");
625       break;
626     default:
627       ASSERT(0);
628   }
629 }