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