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