]> mj.ucw.cz Git - libucw.git/blob - ucw/opt.c
Doc: Release dates
[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 uns 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   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, struct opt_item *item)
56 {
57   opt->item = item;
58   opt->count = 0;
59   opt->name = item->name;
60   uns 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, uns event, struct opt_item *item, char *value)
75 {
76   for (int i = 0; i < oc->hook_count; i++) {
77     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   uns 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 && !strncmp("no-", str, 3) && !strncmp(opt->name, str+3, len-3)) {
98       if (strlen(opt->name) == len-3)
99         return opt;
100     } else
101       continue;
102
103     if (candidate)
104       opt_failure("Ambiguous option --%s: matches both --%s and --%s.", str, candidate->name, opt->name);
105     else
106       candidate = opt;
107   }
108
109   if (candidate)
110     return candidate;
111
112   opt_failure("Invalid option --%s.", str);
113 }
114
115 static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * opt, char * value) {
116   struct opt_item * item = opt->item;
117
118   if (opt->count++ && (opt->flags & OPT_SINGLE))
119     opt_failure("Option %s must be specified at most once.", THIS_OPT);
120
121   if (opt->flags & OPT_LAST_ARG)
122     oc->stop_parsing = 1;
123
124   opt_invoke_hooks(oc, OPT_HOOK_BEFORE_VALUE, item, value);
125
126   switch (item->cls) {
127     case OPT_CL_BOOL:
128       if (!value || !strcasecmp(value, "y") || !strcasecmp(value, "yes") || !strcasecmp(value, "true") || !strcasecmp(value, "1"))
129         *((int *) item->ptr) = 1 ^ (!!(opt->flags & OPT_NEGATIVE));
130       else if (!strcasecmp(value, "n") || !strcasecmp(value, "no") || !strcasecmp(value, "false") || !strcasecmp(value, "0"))
131         *((int *) item->ptr) = 0 ^ (!!(opt->flags & OPT_NEGATIVE));
132       else
133         opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): 1/0, y/n, yes/no, true/false.", THIS_OPT);
134       break;
135     case OPT_CL_STATIC:
136     case OPT_CL_MULTIPLE:
137       {
138         char * e = NULL;
139         void * ptr;
140         if (item->cls == OPT_CL_STATIC)
141           ptr = item->ptr;
142         else
143           ptr = GARY_PUSH_GENERIC(*(void **)item->ptr);
144 #define OPT_PTR(type) ((type *) ptr)
145         switch (item->type) {
146           case CT_INT:
147             if (!value)
148               *OPT_PTR(int) = 0;
149             else
150               e = cf_parse_int(value, OPT_PTR(int));
151             if (e)
152               opt_failure("Integer value parsing failed for %s: %s", THIS_OPT, e);
153             break;
154           case CT_U64:
155             if (!value)
156               *OPT_PTR(u64) = 0;
157             else
158               e = cf_parse_u64(value, OPT_PTR(u64));
159             if (e)
160               opt_failure("Unsigned 64-bit value parsing failed for %s: %s", THIS_OPT, e);
161             break;
162           case CT_DOUBLE:
163             if (!value)
164               *OPT_PTR(double) = NAN;
165             else
166               e = cf_parse_double(value, OPT_PTR(double));
167             if (e)
168               opt_failure("Floating-point value parsing failed for %s: %s", THIS_OPT, e);
169             break;
170           case CT_IP:
171             if (!value)
172               *OPT_PTR(u32) = 0;
173             else
174               e = cf_parse_ip(value, OPT_PTR(u32));
175             if (e)
176               opt_failure("IP address parsing failed for %s: %s", THIS_OPT, e);
177             break;
178           case CT_STRING:
179             if (!value)
180               *OPT_PTR(const char *) = NULL;
181             else
182               *OPT_PTR(const char *) = xstrdup(value);
183             break;
184           case CT_USER:
185               {
186                 char * e = item->u.utype->parser(value, ptr);
187                 if (e)
188                   opt_failure("Cannot parse the value of %s: %s", THIS_OPT, e);
189                 break;
190               }
191           default:
192             ASSERT(0);
193         }
194 #undef OPT_PTR
195         break;
196       }
197     case OPT_CL_SWITCH:
198       if ((opt->flags & OPT_SINGLE) && *((int *)item->ptr) != -1)
199         opt_failure("Multiple switches: %s", THIS_OPT);
200       else
201         *((int *)item->ptr) = item->u.value;
202       break;
203     case OPT_CL_INC:
204       if (opt->flags & OPT_NEGATIVE)
205         (*((int *)item->ptr))--;
206       else
207         (*((int *)item->ptr))++;
208       break;
209     case OPT_CL_CALL:
210       {
211         void *data = (opt->flags & OPT_INTERNAL) ? oc : item->ptr;
212         item->u.call(item, value, data);
213         break;
214       }
215     default:
216       ASSERT(0);
217   }
218
219   opt_invoke_hooks(oc, OPT_HOOK_AFTER_VALUE, item, value);
220 }
221
222 static int opt_longopt(struct opt_context * oc, char ** argv, int index) {
223   int eaten = 0;
224   char * name_in = argv[index] + 2; // skipping the -- on the beginning
225   uns pos = strchrnul(name_in, '=') - name_in;
226   struct opt_precomputed * opt = opt_find_item_longopt(oc, strndupa(name_in, pos));
227   char * value = NULL;
228
229   opt->flags |= OPT_SEEN_AS_LONG;
230
231   if (opt->item->cls == OPT_CL_BOOL && !strncmp(name_in, "no-", 3) && !strncmp(name_in+3, opt->item->name, pos-3)) {
232     if (name_in[pos])
233       opt_failure("Option --%s must not have any value.", name_in);
234     value = "n";
235   } else if (opt->flags & OPT_REQUIRED_VALUE) {
236     if (name_in[pos])
237       value = name_in + pos + 1;
238     else {
239       value = argv[index+1];
240       if (!value)
241         opt_failure("Option %s must have a value, but nothing supplied.", THIS_OPT);
242       eaten++;
243     }
244   } else if (opt->flags & OPT_MAYBE_VALUE) {
245     if (name_in[pos])
246       value = name_in + pos + 1;
247   } else {
248     if (name_in[pos])
249       opt_failure("Option %s must have no value.", THIS_OPT);
250   }
251   opt_parse_value(oc, opt, value);
252   return eaten;
253 }
254
255 static int opt_shortopt(struct opt_context * oc, char ** argv, int index) {
256   int chr = 0;
257   struct opt_precomputed * opt;
258   int o;
259
260   while (o = argv[index][++chr]) {
261     if (o < 0 || o >= 128)
262       opt_failure("Invalid character 0x%02x in option name. Only ASCII is allowed.", o & 0xff);
263     opt = oc->shortopt[o];
264
265     if (!opt)
266       opt_failure("Unknown option -%c.", o);
267
268     opt->flags &= ~OPT_SEEN_AS_LONG;
269
270     if (opt->flags & OPT_NO_VALUE)
271       opt_parse_value(oc, opt, NULL);
272     else if (opt->flags & OPT_REQUIRED_VALUE) {
273       if (argv[index][chr+1]) {
274         opt_parse_value(oc, opt, argv[index] + chr + 1);
275         return 0;
276       } else if (!argv[index+1])
277         opt_failure("Option -%c must have a value, but nothing supplied.", o);
278       else {
279         opt_parse_value(oc, opt, argv[index+1]);
280         return 1;
281       }
282     } else if (opt->flags & OPT_MAYBE_VALUE) {
283       if (argv[index][chr+1]) {
284         opt_parse_value(oc, opt, argv[index] + chr + 1);
285         return 0;
286       } else
287         opt_parse_value(oc, opt, NULL);
288     } else {
289       ASSERT(0);
290     }
291   }
292
293   return 0;
294 }
295
296 static void opt_positional(struct opt_context * oc, char * value) {
297   oc->positional_count++;
298   uns id = oc->positional_count > oc->positional_max ? OPT_POSITIONAL_TAIL : OPT_POSITIONAL(oc->positional_count);
299   struct opt_precomputed * opt = oc->shortopt[id];
300   if (!opt)
301     opt_failure("Too many positional arguments.");
302   else {
303     opt->flags &= OPT_SEEN_AS_LONG;
304     opt_parse_value(oc, opt, value);
305   }
306 }
307
308 static void opt_count_items(struct opt_context *oc, const struct opt_section *sec)
309 {
310   for (const struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
311     if (item->cls == OPT_CL_SECTION)
312       opt_count_items(oc, item->u.section);
313     else if (item->cls == OPT_CL_HOOK)
314       oc->hook_count++;
315     else if (item->letter || item->name) {
316       oc->opt_count++;
317       if (item->letter > OPT_POSITIONAL_TAIL)
318         oc->positional_max++;
319     }
320   }
321 }
322
323 static void opt_prepare_items(struct opt_context *oc, const struct opt_section *sec)
324 {
325   for (struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
326     if (item->cls == OPT_CL_SECTION)
327       opt_prepare_items(oc, item->u.section);
328     else if (item->cls == OPT_CL_HOOK)
329       oc->hooks[oc->hook_count++] = item;
330     else if (item->letter || item->name) {
331       struct opt_precomputed * opt = &oc->opts[oc->opt_count++];
332       opt_precompute(opt, item);
333       if (item->letter)
334         oc->shortopt[(int) item->letter] = opt;
335     }
336   }
337 }
338
339 static void opt_check_required(struct opt_context *oc)
340 {
341   for (int i = 0; i < oc->opt_count; i++) {
342     struct opt_precomputed *opt = &oc->opts[i];
343     if (!opt->count && (opt->flags & OPT_REQUIRED)) {
344       struct opt_item *item = opt->item;
345       if (item->letter > OPT_POSITIONAL_TAIL)
346         opt_failure("Required positional argument #%d not found.", item->letter - OPT_POSITIONAL_TAIL);
347       else if (item->letter == OPT_POSITIONAL_TAIL)
348         opt_failure("Required positional argument not found.");
349       else if (item->letter && item->name)
350         opt_failure("Required option -%c/--%s not found.", item->letter, item->name);
351       else if (item->letter)
352         opt_failure("Required option -%c not found.", item->letter);
353       else
354         opt_failure("Required option --%s not found.", item->name);
355     }
356   }
357 }
358
359 int opt_parse(const struct opt_section * options, char ** argv) {
360   struct opt_context * oc = alloca(sizeof(*oc));
361   memset(oc, 0, sizeof (*oc));
362   oc->options = options;
363
364   opt_count_items(oc, options);
365   oc->opts = alloca(sizeof(*oc->opts) * oc->opt_count);
366   oc->shortopt = alloca(sizeof(*oc->shortopt) * (oc->positional_max + 257));
367   memset(oc->shortopt, 0, sizeof(*oc->shortopt) * (oc->positional_max + 257));
368   oc->hooks = alloca(sizeof (*oc->hooks) * oc->hook_count);
369
370   oc->opt_count = 0;
371   oc->hook_count = 0;
372   opt_prepare_items(oc, options);
373
374   int force_positional = 0;
375   int i;
376   for (i=0; argv[i] && !oc->stop_parsing; i++) {
377     char *arg = argv[i];
378     opt_invoke_hooks(oc, OPT_HOOK_BEFORE_ARG, NULL, NULL);
379     if (arg[0] != '-' || force_positional)
380       opt_positional(oc, arg);
381     else {
382       if (arg[1] == '-') {
383         if (arg[2] == '\0')
384           force_positional++;
385         else
386           i += opt_longopt(oc, argv, i);
387       } else if (arg[1])
388         i += opt_shortopt(oc, argv, i);
389       else
390         opt_positional(oc, arg);
391     }
392   }
393
394   opt_check_required(oc);
395   opt_invoke_hooks(oc, OPT_HOOK_FINAL, NULL, NULL);
396   return i;
397 }