2 * UCW Library -- Parsing of command line options
4 * (c) 2013 Jan Moskyto Matejka <mq@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
13 #include <ucw/stkstring.h>
14 #include <ucw/strtonum.h>
18 static void opt_failure(const char * mesg, ...) FORMAT_CHECK(printf,1,2);
19 static void opt_failure(const char * mesg, ...) {
22 stk_vprintf(mesg, args);
23 exit(OPT_EXIT_BAD_ARGS);
27 struct opt_section * opt_section_root;
29 void opt_help_noexit_internal(struct opt_section * help) {
32 for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
33 if (item->flags & OPT_NO_HELP) continue;
34 if (item->cls == OPT_CL_HELP && item->u.help2 == NULL) continue;
35 if (item->cls == OPT_CL_SECTION) continue;
38 if (item->cls == OPT_CL_HELP) { // two-column help line
39 if (first_column < strlen(item->help))
40 first_column = strlen(item->help);
44 if (item->letter) { // will write sth like "-x, --exclusive"
45 linelen = strlen("-x, --") + strlen(item->name);
47 else { // will write sth like "--exclusive"
48 linelen = strlen("--") + strlen(item->name);
51 ASSERT(item->flags & OPT_VALUE_FLAGS);
53 if (item->flags & OPT_REQUIRED_VALUE) {
54 linelen += strlen("=value");
56 else if (item->flags & OPT_MAYBE_VALUE) {
57 linelen += strlen("(=value)");
60 if (linelen > first_column)
61 first_column = linelen;
64 char * spaces = alloca(first_column + 1);
65 char * buf = alloca(first_column + 1);
66 for (uns i=0;i<first_column;i++)
69 spaces[first_column] = 0;
71 #define VAL(it) ((it->flags & OPT_REQUIRED_VALUE) ? "=value" : ((it->flags & OPT_NO_VALUE) ? "" : "(=value)"))
72 for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
73 if (item->flags & OPT_NO_HELP) continue;
75 if (item->cls == OPT_CL_HELP) {
76 fprintf(stderr, "%s", item->help);
77 if (item->u.help2 == NULL)
78 fprintf(stderr, "\n");
80 fprintf(stderr, "%s %s\n", spaces + strlen(item->help), item->u.help2);
82 else if (item->cls == OPT_CL_SECTION) {
83 opt_help_noexit_internal(item->u.section);
85 else if (item->letter) {
86 sprintf(buf, "-%c, --%s%s", item->letter, item->name, VAL(item));
87 fprintf(stderr, "%s%s %s\n", buf, spaces + strlen(buf), item->help);
90 sprintf(buf, "--%s%s", item->name, VAL(item));
91 fprintf(stderr, "%s%s %s\n", buf, spaces + strlen(buf), item->help);
96 struct opt_precomputed {
97 struct opt_precomputed_option {
98 struct opt_item * item;
102 struct opt_precomputed_option * shortopt[256];
106 static struct opt_item * opt_find_item_shortopt(int chr, struct opt_precomputed * opts) {
107 return (opts->shortopt[chr] ? opts->shortopt[chr]->item : NULL);
110 static struct opt_item * opt_find_item_longopt(char * str, struct opt_precomputed * pre) {
111 uns len = strlen(str);
112 struct opt_item * candidate = NULL;
114 for (int i=0; i<pre->opt_count; i++) {
115 if (!strncmp(pre->opts[i]->item->name, str, len)) {
116 if (strlen(pre->opts[i]->item->name) == len) {
117 if (pre->opts[i]->count++ && (pre->opts[i]->flags & OPT_SINGLE))
118 opt_failure("Option %s appeared the second time.\n", pre->opts[i]->item->name);
120 return pre->opts[i]->item;
123 opt_failure("Ambiguous prefix %s: Found matching %s and %s.\n", str, candidate->name, pre->opts[i]->item->name);
125 candidate = pre->opts[i]->item;
132 opt_failure("Invalid option %s.\n", str);
135 #define OPT_NAME (longopt ? stk_printf("--%s", item->name) : stk_printf("-%c", item->letter))
136 static void opt_parse_value(struct opt_item * item, char * value, int longopt) {
139 if (!strcasecmp(value, "y") || !strcasecmp(value, "yes") || !strcasecmp(value, "true") || !strcasecmp(value, "1"))
140 *((int *) item->ptr) = 1;
141 else if (!strcasecmp(value, "n") || !strcasecmp(value, "no") || !strcasecmp(value, "false") || !strcasecmp(value, "0"))
142 *((int *) item->ptr) = 0;
144 opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): y/n, yes/no, true/false.\n", OPT_NAME);
149 switch (item->type) {
151 e = cf_parse_int(value, item->ptr);
153 opt_failure("Integer value parsing failed for argument %s: %s\n", OPT_NAME, e);
156 e = cf_parse_u64(value, item->ptr);
158 opt_failure("Unsigned 64-bit value parsing failed for argument %s: %s\n", OPT_NAME, e);
161 e = cf_parse_double(value, item->ptr);
163 opt_failure("Double value parsing failed for argument %s: %s\n", OPT_NAME, e);
166 e = cf_parse_ip(value, item->ptr);
168 opt_failure("IP parsing failed for argument %s: %s\n", OPT_NAME, e);
171 item->ptr = strdup(value);
179 if (*((int *)item->ptr) != -1)
180 opt_failure("Multiple switches: %s", OPT_NAME);
182 *((int *)item->ptr) = item->u.value;
185 if (item->flags & OPT_DECREMENT)
186 (*((int *)item->ptr))--;
188 (*((int *)item->ptr))++;
190 item->u.call(item, value, item->ptr);
195 e = item->u.utype->parser(value, item->ptr);
197 opt_failure("User defined type value parsing failed for argument %s: %s\n", OPT_NAME, e);
206 static int opt_longopt(char ** argv, int index, struct opt_precomputed * pre) {
208 char * name_in = argv[index] + 2; // skipping the -- on the beginning
209 uns pos = strchrnul(name_in, '=') - name_in;
210 struct opt_item * item = opt_find_item_longopt(strndupa(name_in, pos), pre);
212 if (item->flags & OPT_REQUIRED_VALUE) {
213 if (pos < strlen(name_in))
214 value = name_in + pos + 1;
216 value = argv[index+1];
220 else if (item->flags & OPT_MAYBE_VALUE) {
221 if (pos < strlen(name_in))
222 value = name_in + pos + 1;
225 if (pos < strlen(name_in))
226 opt_failure("Argument %s must not have any value.", item->name);
228 opt_parse_value(item, value, 1);
232 static int opt_shortopt(char ** argv, int index, struct opt_precomputed * pre) {
234 struct opt_item * item;
235 while (argv[index][++chr] && (item = opt_find_item_shortopt(argv[index][chr], pre))) {
236 if (item->flags & OPT_NO_VALUE) {
237 opt_parse_value(item, NULL, 0);
240 if (chr == 1 && (item->flags & OPT_REQUIRED_VALUE)) {
241 if (argv[index][2]) {
242 opt_parse_value(item, argv[index] + 2, 0);
246 opt_parse_value(item, argv[index+1], 0);
250 else if (chr == 1 && (item->flags & OPT_MAYBE_VALUE)) {
252 opt_parse_value(item, argv[index] + 2, 0);
254 opt_parse_value(item, NULL, 0);
256 else if (item->flags & (OPT_REQUIRED_VALUE | OPT_MAYBE_VALUE)) {
257 if (argv[index][chr+1] || (item->flags | OPT_MAYBE_VALUE))
258 opt_failure("Option -%c may or must have a value but found inside a bunch of short opts.", item->letter);
260 opt_parse_value(item, argv[index+1], 0);
266 if (argv[index][chr])
267 opt_failure("Unknown option -%c.", item->letter);
272 #define OPT_TRAVERSE_SECTIONS \
274 while (item->cls == OPT_CL_SECTION) { \
278 struct opt_stack * new_stk = alloca(sizeof(*new_stk)); \
279 new_stk->prev = stk; \
280 stk->next = new_stk; \
284 item = item->u.section->opt; \
286 if (item->cls == OPT_CL_END) { \
294 void opt_parse(const struct opt_section * options, char ** argv, opt_positional * callback) {
296 struct opt_item * this;
297 struct opt_stack * prev;
298 struct opt_stack * next;
299 } * stk = alloca(sizeof(*stk));
304 struct opt_precomputed * pre = alloca(sizeof(*pre));
308 for (struct opt_item * item = options->opt; ; item++) {
309 OPT_TRAVERSE_SECTIONS;
310 if (item->letter || item->name)
314 pre->opts = xmalloc(sizeof(*pre->opts) * count);
317 for (struct opt_item * item = options->opt; ; item++) {
318 OPT_TRAVERSE_SECTIONS;
319 if (item->letter || item->name) {
320 struct opt_precomputed_option * opt = xmalloc(sizeof(*opt));
322 opt->flags = item->flags;
324 pre->opts[pre->opt_count++] = opt;
326 pre->shortopt[(int) item->letter] = opt;
327 if (!(opt->flags & OPT_VALUE_FLAGS) &&
328 (item->cls == OPT_CL_CALL || item->cls == OPT_CL_USER)) {
329 fprintf(stderr, "You MUST specify some of the value flags for the %c/%s item.\n", item->letter, item->name);
333 opt->flags |= opt_default_value_flags[item->cls];
337 int force_positional = 0;
338 for (int i=0;argv[i];i++) {
339 if (argv[i][0] != '-' || force_positional) {
343 if (argv[i][1] == '-') {
344 if (argv[i][2] == '\0')
347 i += opt_longopt(argv, i, pre);
350 i += opt_shortopt(argv, i, pre);
358 #include <ucw/fastbuf.h>
360 static void show_version(struct opt_item * opt UNUSED, const char * value UNUSED, void * data UNUSED) {
361 printf("This is a simple tea boiling console v0.1.\n");
365 struct teapot_temperature {
376 static char * temp_scale_str[] = { "C", "F", "K", "Re", "R" };
378 static enum TEAPOT_TYPE {
383 TEAPOT_UNDEFINED = -1
384 } set = TEAPOT_UNDEFINED;
386 static int english = 0;
387 static char * name = NULL;
388 static int sugar = 0;
389 static int verbose = 1;
390 static int with_gas = 0;
391 static int black_magic = 0;
393 static int water_amount = 0;
395 static const char * teapot_temperature_parser(char * in, void * ptr) {
396 struct teapot_temperature * temp = ptr;
398 const char * err = str_to_int(&temp->value, in, &next, 0);
401 if (!strcmp("C", next))
402 temp->scale = TEMP_CELSIUS;
403 else if (!strcmp("F", next))
404 temp->scale = TEMP_FAHRENHEIT;
405 else if (!strcmp("K", next))
406 temp->scale = TEMP_KELVIN;
407 else if (!strcmp("R", next))
408 temp->scale = TEMP_RANKINE;
409 else if (!strcmp("Re", next))
410 temp->scale = TEMP_REAUMUR;
412 fprintf(stderr, "Unknown scale: %s\n", next);
413 exit(OPT_EXIT_BAD_ARGS);
415 return next + strlen(next);
418 static void teapot_temperature_dumper(struct fastbuf * fb, void * ptr) {
419 struct teapot_temperature * temp = ptr;
420 bprintf(fb, "%d%s", temp->value, temp_scale_str[temp->scale]);
423 static struct cf_user_type teapot_temperature_t = {
424 .size = sizeof(struct teapot_temperature),
425 .name = "teapot_temperature_t",
426 .parser = (cf_parser1*) teapot_temperature_parser,
427 .dumper = (cf_dumper1*) teapot_temperature_dumper
430 static struct opt_section water_options = {
432 OPT_INT('w', "water", water_amount, OPT_REQUIRED | OPT_REQUIRED_VALUE, "Amount of water (in mls)"),
433 OPT_BOOL('G', "with-gas", with_gas, OPT_NO_VALUE, "Use water with gas"),
438 static struct opt_section help = {
440 OPT_HELP("A simple tea boiling console."),
441 OPT_HELP("Usage: teapot [options] name-of-the-tea"),
442 OPT_HELP("Black, green or white tea supported as well as fruit or herbal tea."),
443 OPT_HELP("You may specify more kinds of tea, all of them will be boiled for you, in the given order."),
445 OPT_HELP("Options:"),
447 OPT_CALL('V', "version", show_version, NULL, OPT_NO_VALUE, "Show the version"),
449 OPT_BOOL('e', "english-style", english, 0, "English style (with milk)"),
450 OPT_INT('s', "sugar", sugar, OPT_REQUIRED_VALUE, "Amount of sugar (in teaspoons)"),
451 OPT_SWITCH(0, "standard-set", set, TEAPOT_STANDARD, 0, "Standard teapot"),
452 OPT_SWITCH('x', "exclusive-set", set, TEAPOT_EXCLUSIVE, 0, "Exclusive teapot"),
453 OPT_SWITCH('g', "glass-set", set, TEAPOT_GLASS, 0, "Transparent glass teapot"),
454 OPT_SWITCH('h', "hands", set, TEAPOT_HANDS, 0, "Use user's hands as a teapot (a bit dangerous)"),
455 OPT_USER('t', "temperature", temperature, teapot_temperature_t, OPT_REQUIRED_VALUE,
456 "Wanted final temperature of the tea to be served\n"
457 "\t\tSupported scales:\tCelsius [60C], Fahrenheit [140F],"
458 "\t\t\tKelvin [350K], Rankine [600R] and Reaumur [50Re]"
459 "\t\tOnly integer values allowed."),
460 OPT_INC('v', "verbose", verbose, 0, "Verbose (the more -v, the more verbose)"),
461 OPT_INC('q', "quiet", verbose, OPT_DECREMENT, "Quiet (the more -q, the more quiet)"),
462 OPT_INT('b', "black-magic", black_magic, 0, "Use black magic to make the tea extraordinary delicious"),
463 OPT_BOOL('p', "pray", pray, 0, "Pray before boiling"),
465 OPT_HELP("Water options:"),
466 OPT_SECTION(water_options),
471 #define MAX_TEA_COUNT 30
472 static char * tea_list[MAX_TEA_COUNT];
473 static int tea_num = 0;
474 static void add_tea(const char * name) {
475 if (tea_num >= MAX_TEA_COUNT) {
476 fprintf(stderr, "Cannot boil more than %d teas.\n", MAX_TEA_COUNT);
477 exit(OPT_EXIT_BAD_ARGS);
479 tea_list[tea_num++] = strdup(name);
482 static void boil_tea(const char * name) {
483 printf("Boiling a tea: %s\n", name);
486 int main(int argc, char ** argv)
488 opt_parse(&help, argv, add_tea);
490 for (int i=0; i<tea_num; i++)
491 boil_tea(tea_list[i]);
493 printf("Everything OK. Bye.\n");