]> mj.ucw.cz Git - libucw.git/blob - ucw/opt.c
Xtype docs: Fixed a typo
[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  *      (c) 2014 Martin Mares <mj@ucw.cz>
6  *      (c) 2014 Pavel Charvat <pchar@ucw.cz>
7  *
8  *      This software may be freely distributed and used according to the terms
9  *      of the GNU Lesser General Public License.
10  */
11
12 #include <ucw/lib.h>
13 #include <ucw/opt.h>
14 #include <ucw/opt-internal.h>
15 #include <ucw/gary.h>
16 #include <ucw/stkstring.h>
17 #include <ucw/strtonum.h>
18
19 #include <alloca.h>
20 #include <math.h>
21
22 static uint opt_default_value_flags[] = {
23     [OPT_CL_BOOL] = OPT_NO_VALUE,
24     [OPT_CL_STATIC] = OPT_MAYBE_VALUE,
25     [OPT_CL_MULTIPLE] = OPT_REQUIRED_VALUE,
26     [OPT_CL_SWITCH] = OPT_NO_VALUE,
27     [OPT_CL_INC] = OPT_NO_VALUE,
28     [OPT_CL_CALL] = 0,
29     [OPT_CL_SECTION] = 0,
30     [OPT_CL_HELP] = 0
31 };
32
33 void opt_failure(const char * mesg, ...) {
34   va_list args;
35   va_start(args, mesg);
36   vfprintf(stderr, mesg, args);
37   fprintf(stderr, "\nRun with --help for more information.\n");
38   exit(OPT_EXIT_BAD_ARGS);
39 }
40
41 static char *opt_name(struct opt_context *oc, struct opt_precomputed *opt)
42 {
43   const struct opt_item *item = opt->item;
44   char *res;
45   if (item->letter >= OPT_POSITIONAL_TAIL)
46     res = stk_printf("positional argument #%d", oc->positional_count);
47   else if (opt->flags & OPT_SEEN_AS_LONG)
48     res = stk_printf("--%s", opt->name);
49   else
50     res = stk_printf("-%c", item->letter);
51   return xstrdup(res);
52 }
53
54 #define THIS_OPT opt_name(oc, opt)
55
56 void opt_precompute(struct opt_precomputed *opt, const struct opt_item *item)
57 {
58   opt->item = item;
59   opt->count = 0;
60   opt->name = item->name;
61   uint flags = item->flags;
62
63   if (item->letter >= OPT_POSITIONAL_TAIL) {
64     flags &= ~OPT_VALUE_FLAGS;
65     flags |= OPT_REQUIRED_VALUE;
66   }
67   if (!(flags & OPT_VALUE_FLAGS)) {
68     ASSERT(item->cls != OPT_CL_CALL);
69     flags |= opt_default_value_flags[item->cls];
70   }
71
72   opt->flags = flags;
73 }
74
75 static void opt_invoke_hooks(struct opt_context *oc, uint event, const struct opt_item *item, char *value)
76 {
77   for (int i = 0; i < oc->hook_count; i++) {
78     const struct opt_item *hook = oc->hooks[i];
79     if (hook->flags & event) {
80       void *data = (hook->flags & OPT_HOOK_INTERNAL) ? oc : hook->ptr;
81       hook->u.hook(item, event, value, data);
82     }
83   }
84 }
85
86 static struct opt_precomputed * opt_find_item_longopt(struct opt_context * oc, char * str) {
87   uint len = strlen(str);
88   struct opt_precomputed * candidate = NULL;
89
90   for (int i = 0; i < oc->opt_count; i++) {
91     struct opt_precomputed *opt = &oc->opts[i];
92     if (!opt->name)
93       continue;
94
95     if (!strncmp(opt->name, str, len)) {
96       if (strlen(opt->name) == len)
97         return opt;
98     } else if (opt->item->cls == OPT_CL_BOOL) {
99       if (opt->flags & OPT_NEGATIVE) {
100         // If the option is called no-X, match X as well
101         if (!strncmp("no-", opt->name, 3) && !strncmp(opt->name+3, str, len)) {
102           if (strlen(opt->name) == len+3)
103             return opt;
104         } else
105           continue;
106       } else {
107         // Match no-X as well
108         if (!strncmp("no-", str, 3) && !strncmp(opt->name, str+3, len-3)) {
109           if (strlen(opt->name) == len-3)
110             return opt;
111         } else
112           continue;
113       }
114     } else
115       continue;
116
117     if (candidate)
118       opt_failure("Ambiguous option --%s: matches both --%s and --%s.", str, candidate->name, opt->name);
119     else
120       candidate = opt;
121   }
122
123   if (candidate)
124     return candidate;
125
126   opt_failure("Invalid option --%s.", str);
127 }
128
129 static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * opt, char * value) {
130   const struct opt_item * item = opt->item;
131
132   if (opt->count++ && (opt->flags & OPT_SINGLE))
133     opt_failure("Option %s must be specified at most once.", THIS_OPT);
134
135   if (opt->flags & OPT_LAST_ARG)
136     oc->stop_parsing = 1;
137
138   opt_invoke_hooks(oc, OPT_HOOK_BEFORE_VALUE, item, value);
139
140   switch (item->cls) {
141     case OPT_CL_BOOL:
142       if (!value || !strcasecmp(value, "y") || !strcasecmp(value, "yes") || !strcasecmp(value, "true") || !strcasecmp(value, "1"))
143         *((int *) item->ptr) = 1 ^ (!!(opt->flags & OPT_NEGATIVE));
144       else if (!strcasecmp(value, "n") || !strcasecmp(value, "no") || !strcasecmp(value, "false") || !strcasecmp(value, "0"))
145         *((int *) item->ptr) = 0 ^ (!!(opt->flags & OPT_NEGATIVE));
146       else
147         opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): 1/0, y/n, yes/no, true/false.", THIS_OPT);
148       break;
149     case OPT_CL_STATIC:
150     case OPT_CL_MULTIPLE:
151       {
152         char * e = NULL;
153         void * ptr;
154         if (item->cls == OPT_CL_STATIC)
155           ptr = item->ptr;
156         else
157           ptr = GARY_PUSH_GENERIC(*(void **)item->ptr);
158 #define OPT_PTR(type) ((type *) ptr)
159         switch (item->type) {
160           case CT_INT:
161             if (!value)
162               *OPT_PTR(int) = 0;
163             else
164               e = cf_parse_int(value, OPT_PTR(int));
165             if (e)
166               opt_failure("Integer value parsing failed for %s: %s", THIS_OPT, e);
167             break;
168           case CT_U64:
169             if (!value)
170               *OPT_PTR(u64) = 0;
171             else
172               e = cf_parse_u64(value, OPT_PTR(u64));
173             if (e)
174               opt_failure("Unsigned 64-bit value parsing failed for %s: %s", THIS_OPT, e);
175             break;
176           case CT_DOUBLE:
177             if (!value)
178               *OPT_PTR(double) = NAN;
179             else
180               e = cf_parse_double(value, OPT_PTR(double));
181             if (e)
182               opt_failure("Floating-point value parsing failed for %s: %s", THIS_OPT, e);
183             break;
184           case CT_IP:
185             if (!value)
186               *OPT_PTR(u32) = 0;
187             else
188               e = cf_parse_ip(value, OPT_PTR(u32));
189             if (e)
190               opt_failure("IP address parsing failed for %s: %s", THIS_OPT, e);
191             break;
192           case CT_STRING:
193             if (!value)
194               *OPT_PTR(const char *) = NULL;
195             else
196               *OPT_PTR(const char *) = xstrdup(value);
197             break;
198           case CT_USER:
199               {
200                 char * e = item->u.utype->parser(value, ptr);
201                 if (e)
202                   opt_failure("Cannot parse the value of %s: %s", THIS_OPT, e);
203                 break;
204               }
205           case CT_XTYPE:
206               {
207                 const char * e = item->u.xtype->parse(value, ptr, cf_get_pool());
208                 if (e)
209                   opt_failure("Cannot parse the value of %s: %s", THIS_OPT, e);
210                 break;
211               }
212           default:
213             ASSERT(0);
214         }
215 #undef OPT_PTR
216         break;
217       }
218     case OPT_CL_SWITCH:
219       if ((opt->flags & OPT_SINGLE) && *((int *)item->ptr) != -1)
220         opt_failure("Multiple switches: %s", THIS_OPT);
221       else
222         *((int *)item->ptr) = item->u.value;
223       break;
224     case OPT_CL_INC:
225       if (opt->flags & OPT_NEGATIVE)
226         (*((int *)item->ptr))--;
227       else
228         (*((int *)item->ptr))++;
229       break;
230     case OPT_CL_CALL:
231       {
232         void *data = (opt->flags & OPT_INTERNAL) ? oc : item->ptr;
233         item->u.call(item, value, data);
234         break;
235       }
236     case OPT_CL_BREAK:
237       oc->stop_parsing = 2;
238       break;
239     default:
240       ASSERT(0);
241   }
242
243   opt_invoke_hooks(oc, OPT_HOOK_AFTER_VALUE, item, value);
244 }
245
246 static int opt_longopt(struct opt_context * oc, char ** argv, int index) {
247   int eaten = 0;
248   char * name_in = argv[index] + 2; // skipping the -- on the beginning
249   uint pos = strchrnul(name_in, '=') - name_in;
250   struct opt_precomputed * opt = opt_find_item_longopt(oc, strndupa(name_in, pos));
251   char * value = NULL;
252
253   opt->flags |= OPT_SEEN_AS_LONG;
254
255   if (opt->item->cls == OPT_CL_BOOL &&
256       ((opt->flags & OPT_NEGATIVE)
257          ? (!strncmp(opt->item->name, "no-", 3) && !strncmp(name_in, opt->item->name + 3, pos-3))
258          : (!strncmp(name_in, "no-", 3) && !strncmp(name_in+3, opt->item->name, pos-3)))) {
259     if (name_in[pos])
260       opt_failure("Option --%s must not have any value.", name_in);
261     value = "n";
262   } else if (opt->flags & OPT_REQUIRED_VALUE) {
263     if (name_in[pos])
264       value = name_in + pos + 1;
265     else {
266       value = argv[index+1];
267       if (!value)
268         opt_failure("Option %s must have a value, but nothing supplied.", THIS_OPT);
269       eaten++;
270     }
271   } else if (opt->flags & OPT_MAYBE_VALUE) {
272     if (name_in[pos])
273       value = name_in + pos + 1;
274   } else {
275     if (name_in[pos])
276       opt_failure("Option %s must have no value.", THIS_OPT);
277   }
278   opt_parse_value(oc, opt, value);
279   return eaten;
280 }
281
282 static int opt_shortopt(struct opt_context * oc, char ** argv, int index) {
283   int chr = 0;
284   struct opt_precomputed * opt;
285   int o;
286
287   while (o = argv[index][++chr]) {
288     if (o < 0 || o >= 128)
289       opt_failure("Invalid character 0x%02x in option name. Only ASCII is allowed.", o & 0xff);
290     opt = oc->shortopt[o];
291
292     if (!opt)
293       opt_failure("Unknown option -%c.", o);
294
295     opt->flags &= ~OPT_SEEN_AS_LONG;
296
297     if (opt->flags & OPT_NO_VALUE)
298       opt_parse_value(oc, opt, NULL);
299     else if (opt->flags & OPT_REQUIRED_VALUE) {
300       if (argv[index][chr+1]) {
301         opt_parse_value(oc, opt, argv[index] + chr + 1);
302         return 0;
303       } else if (!argv[index+1])
304         opt_failure("Option -%c must have a value, but nothing supplied.", o);
305       else {
306         opt_parse_value(oc, opt, argv[index+1]);
307         return 1;
308       }
309     } else if (opt->flags & OPT_MAYBE_VALUE) {
310       if (argv[index][chr+1]) {
311         opt_parse_value(oc, opt, argv[index] + chr + 1);
312         return 0;
313       } else
314         opt_parse_value(oc, opt, NULL);
315     } else {
316       ASSERT(0);
317     }
318   }
319
320   return 0;
321 }
322
323 static void opt_positional(struct opt_context * oc, char * value) {
324   oc->positional_count++;
325   uint id = oc->positional_count > oc->positional_max ? OPT_POSITIONAL_TAIL : OPT_POSITIONAL(oc->positional_count);
326   struct opt_precomputed * opt = oc->shortopt[id];
327   if (!opt)
328     opt_failure("Too many positional arguments.");
329   else {
330     opt->flags &= ~OPT_SEEN_AS_LONG;
331     opt_parse_value(oc, opt, value);
332   }
333 }
334
335 static void opt_count_items(struct opt_context *oc, const struct opt_section *sec)
336 {
337   for (const struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
338     if (item->cls == OPT_CL_SECTION)
339       opt_count_items(oc, item->u.section);
340     else if (item->cls == OPT_CL_HOOK)
341       oc->hook_count++;
342     else if (item->letter || item->name) {
343       oc->opt_count++;
344       if (item->letter > OPT_POSITIONAL_TAIL)
345         oc->positional_max++;
346     }
347   }
348 }
349
350 static void opt_prepare_items(struct opt_context *oc, const struct opt_section *sec)
351 {
352   for (const struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
353     if (item->cls == OPT_CL_SECTION)
354       opt_prepare_items(oc, item->u.section);
355     else if (item->cls == OPT_CL_HOOK)
356       oc->hooks[oc->hook_count++] = item;
357     else if (item->letter || item->name) {
358       struct opt_precomputed * opt = &oc->opts[oc->opt_count++];
359       opt_precompute(opt, item);
360       if (item->letter)
361         oc->shortopt[(int) item->letter] = opt;
362     }
363   }
364 }
365
366 static void opt_check_required(struct opt_context *oc)
367 {
368   for (int i = 0; i < oc->opt_count; i++) {
369     struct opt_precomputed *opt = &oc->opts[i];
370     if (!opt->count && (opt->flags & OPT_REQUIRED)) {
371       const struct opt_item *item = opt->item;
372       if (item->letter > OPT_POSITIONAL_TAIL)
373         opt_failure("Required positional argument #%d not found.", item->letter - OPT_POSITIONAL_TAIL);
374       else if (item->letter == OPT_POSITIONAL_TAIL)
375         opt_failure("Required positional argument not found.");
376       else if (item->letter && item->name)
377         opt_failure("Required option -%c/--%s not found.", item->letter, item->name);
378       else if (item->letter)
379         opt_failure("Required option -%c not found.", item->letter);
380       else
381         opt_failure("Required option --%s not found.", item->name);
382     }
383   }
384 }
385
386 int opt_parse(const struct opt_section * options, char ** argv) {
387   struct opt_context * oc = alloca(sizeof(*oc));
388   memset(oc, 0, sizeof (*oc));
389   oc->options = options;
390
391   opt_count_items(oc, options);
392   oc->opts = alloca(sizeof(*oc->opts) * oc->opt_count);
393   oc->shortopt = alloca(sizeof(*oc->shortopt) * (oc->positional_max + OPT_POSITIONAL_TAIL + 1));
394   memset(oc->shortopt, 0, sizeof(*oc->shortopt) * (oc->positional_max + OPT_POSITIONAL_TAIL + 1));
395   oc->hooks = alloca(sizeof (*oc->hooks) * oc->hook_count);
396
397   oc->opt_count = 0;
398   oc->hook_count = 0;
399   opt_prepare_items(oc, options);
400
401   int force_positional = 0;
402   int i, start_i = 0;
403   for (i=0; argv[i] && !oc->stop_parsing; i++) {
404     start_i = i;
405     char *arg = argv[i];
406     opt_invoke_hooks(oc, OPT_HOOK_BEFORE_ARG, NULL, NULL);
407     if (arg[0] != '-' || force_positional)
408       opt_positional(oc, arg);
409     else {
410       if (arg[1] == '-') {
411         if (arg[2] == '\0')
412           force_positional++;
413         else
414           i += opt_longopt(oc, argv, i);
415       } else if (arg[1])
416         i += opt_shortopt(oc, argv, i);
417       else
418         opt_positional(oc, arg);
419     }
420   }
421
422   opt_check_required(oc);
423   opt_invoke_hooks(oc, OPT_HOOK_FINAL, NULL, NULL);
424   return (oc->stop_parsing < 2 ? i : start_i);
425 }