1 #include <linux/compiler.h>
2 #include <linux/types.h>
8 #include "subcmd-util.h"
9 #include "parse-options.h"
10 #include "subcmd-config.h"
18 static int opterror(const struct option *opt, const char *reason, int flags)
20 if (flags & OPT_SHORT)
21 fprintf(stderr, " Error: switch `%c' %s", opt->short_name, reason);
22 else if (flags & OPT_UNSET)
23 fprintf(stderr, " Error: option `no-%s' %s", opt->long_name, reason);
25 fprintf(stderr, " Error: option `%s' %s", opt->long_name, reason);
30 static const char *skip_prefix(const char *str, const char *prefix)
32 size_t len = strlen(prefix);
33 return strncmp(str, prefix, len) ? NULL : str + len;
36 static void optwarning(const struct option *opt, const char *reason, int flags)
38 if (flags & OPT_SHORT)
39 fprintf(stderr, " Warning: switch `%c' %s", opt->short_name, reason);
40 else if (flags & OPT_UNSET)
41 fprintf(stderr, " Warning: option `no-%s' %s", opt->long_name, reason);
43 fprintf(stderr, " Warning: option `%s' %s", opt->long_name, reason);
46 static int get_arg(struct parse_opt_ctx_t *p, const struct option *opt,
47 int flags, const char **arg)
54 } else if ((opt->flags & PARSE_OPT_LASTARG_DEFAULT) && (p->argc == 1 ||
55 **(p->argv + 1) == '-')) {
56 res = (const char *)opt->defval;
57 } else if (p->argc > 1) {
61 return opterror(opt, "requires a value", flags);
67 static int get_value(struct parse_opt_ctx_t *p,
68 const struct option *opt, int flags)
70 const char *s, *arg = NULL;
71 const int unset = flags & OPT_UNSET;
75 return opterror(opt, "takes no value", flags);
76 if (unset && (opt->flags & PARSE_OPT_NONEG))
77 return opterror(opt, "isn't available", flags);
78 if (opt->flags & PARSE_OPT_DISABLED)
79 return opterror(opt, "is not usable", flags);
81 if (opt->flags & PARSE_OPT_EXCLUSIVE) {
82 if (p->excl_opt && p->excl_opt != opt) {
85 if (((flags & OPT_SHORT) && p->excl_opt->short_name) ||
86 p->excl_opt->long_name == NULL) {
87 snprintf(msg, sizeof(msg), "cannot be used with switch `%c'",
88 p->excl_opt->short_name);
90 snprintf(msg, sizeof(msg), "cannot be used with %s",
91 p->excl_opt->long_name);
93 opterror(opt, msg, flags);
98 if (!(flags & OPT_SHORT) && p->opt) {
100 case OPTION_CALLBACK:
101 if (!(opt->flags & PARSE_OPT_NOARG))
107 case OPTION_SET_UINT:
109 return opterror(opt, "takes no value", flags);
111 case OPTION_ARGUMENT:
115 case OPTION_UINTEGER:
123 if (opt->flags & PARSE_OPT_NOBUILD) {
127 err = snprintf(reason, sizeof(reason),
128 opt->flags & PARSE_OPT_CANSKIP ?
129 "is being ignored because %s " :
130 "is not available because %s",
132 reason[sizeof(reason) - 1] = '\0';
135 strncpy(reason, opt->flags & PARSE_OPT_CANSKIP ?
140 if (!(opt->flags & PARSE_OPT_CANSKIP))
141 return opterror(opt, reason, flags);
146 if (opt->flags & PARSE_OPT_NOARG)
148 if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
155 case OPTION_SET_UINT:
158 case OPTION_ARGUMENT:
162 case OPTION_CALLBACK:
165 case OPTION_UINTEGER:
173 err = get_arg(p, opt, flags, NULL);
177 optwarning(opt, reason, flags);
184 *(int *)opt->value &= ~opt->defval;
186 *(int *)opt->value |= opt->defval;
190 *(bool *)opt->value = unset ? false : true;
192 *(bool *)opt->set = true;
196 *(int *)opt->value = unset ? 0 : *(int *)opt->value + 1;
199 case OPTION_SET_UINT:
200 *(unsigned int *)opt->value = unset ? 0 : opt->defval;
204 *(void **)opt->value = unset ? NULL : (void *)opt->defval;
210 *(const char **)opt->value = NULL;
211 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
212 *(const char **)opt->value = (const char *)opt->defval;
214 err = get_arg(p, opt, flags, (const char **)opt->value);
217 *(bool *)opt->set = true;
219 /* PARSE_OPT_NOEMPTY: Allow NULL but disallow empty string. */
220 if (opt->flags & PARSE_OPT_NOEMPTY) {
221 const char *val = *(const char **)opt->value;
226 /* Similar to unset if we are given an empty string. */
227 if (val[0] == '\0') {
228 *(const char **)opt->value = NULL;
235 case OPTION_CALLBACK:
237 return (*opt->callback)(opt, NULL, 1) ? (-1) : 0;
238 if (opt->flags & PARSE_OPT_NOARG)
239 return (*opt->callback)(opt, NULL, 0) ? (-1) : 0;
240 if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
241 return (*opt->callback)(opt, NULL, 0) ? (-1) : 0;
242 if (get_arg(p, opt, flags, &arg))
244 return (*opt->callback)(opt, arg, 0) ? (-1) : 0;
248 *(int *)opt->value = 0;
251 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
252 *(int *)opt->value = opt->defval;
255 if (get_arg(p, opt, flags, &arg))
257 *(int *)opt->value = strtol(arg, (char **)&s, 10);
259 return opterror(opt, "expects a numerical value", flags);
262 case OPTION_UINTEGER:
264 *(unsigned int *)opt->value = 0;
267 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
268 *(unsigned int *)opt->value = opt->defval;
271 if (get_arg(p, opt, flags, &arg))
273 *(unsigned int *)opt->value = strtol(arg, (char **)&s, 10);
275 return opterror(opt, "expects a numerical value", flags);
280 *(long *)opt->value = 0;
283 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
284 *(long *)opt->value = opt->defval;
287 if (get_arg(p, opt, flags, &arg))
289 *(long *)opt->value = strtol(arg, (char **)&s, 10);
291 return opterror(opt, "expects a numerical value", flags);
296 *(u64 *)opt->value = 0;
299 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
300 *(u64 *)opt->value = opt->defval;
303 if (get_arg(p, opt, flags, &arg))
305 *(u64 *)opt->value = strtoull(arg, (char **)&s, 10);
307 return opterror(opt, "expects a numerical value", flags);
311 case OPTION_ARGUMENT:
314 die("should not happen, someone must be hit on the forehead");
318 static int parse_short_opt(struct parse_opt_ctx_t *p, const struct option *options)
321 for (; options->type != OPTION_END; options++) {
322 if (options->short_name == *p->opt) {
323 p->opt = p->opt[1] ? p->opt + 1 : NULL;
324 return get_value(p, options, OPT_SHORT);
328 if (options->parent) {
329 options = options->parent;
336 static int parse_long_opt(struct parse_opt_ctx_t *p, const char *arg,
337 const struct option *options)
339 const char *arg_end = strchr(arg, '=');
340 const struct option *abbrev_option = NULL, *ambiguous_option = NULL;
341 int abbrev_flags = 0, ambiguous_flags = 0;
344 arg_end = arg + strlen(arg);
347 for (; options->type != OPTION_END; options++) {
351 if (!options->long_name)
354 rest = skip_prefix(arg, options->long_name);
355 if (options->type == OPTION_ARGUMENT) {
359 return opterror(options, "takes no value", flags);
362 p->out[p->cpidx++] = arg - 2;
366 if (!prefixcmp(options->long_name, "no-")) {
368 * The long name itself starts with "no-", so
369 * accept the option without "no-" so that users
370 * do not have to enter "no-no-" to get the
373 rest = skip_prefix(arg, options->long_name + 3);
378 /* Abbreviated case */
379 if (!prefixcmp(options->long_name + 3, arg)) {
385 if (!strncmp(options->long_name, arg, arg_end - arg)) {
389 * If this is abbreviated, it is
390 * ambiguous. So when there is no
391 * exact match later, we need to
394 ambiguous_option = abbrev_option;
395 ambiguous_flags = abbrev_flags;
397 if (!(flags & OPT_UNSET) && *arg_end)
398 p->opt = arg_end + 1;
399 abbrev_option = options;
400 abbrev_flags = flags;
403 /* negated and abbreviated very much? */
404 if (!prefixcmp("no-", arg)) {
409 if (strncmp(arg, "no-", 3))
412 rest = skip_prefix(arg + 3, options->long_name);
413 /* abbreviated and negated? */
414 if (!rest && !prefixcmp(options->long_name, arg + 3))
425 return get_value(p, options, flags);
428 if (ambiguous_option) {
430 " Error: Ambiguous option: %s (could be --%s%s or --%s%s)",
432 (ambiguous_flags & OPT_UNSET) ? "no-" : "",
433 ambiguous_option->long_name,
434 (abbrev_flags & OPT_UNSET) ? "no-" : "",
435 abbrev_option->long_name);
439 return get_value(p, abbrev_option, abbrev_flags);
441 if (options->parent) {
442 options = options->parent;
449 static void check_typos(const char *arg, const struct option *options)
454 if (!prefixcmp(arg, "no-")) {
455 fprintf(stderr, " Error: did you mean `--%s` (with two dashes ?)", arg);
459 for (; options->type != OPTION_END; options++) {
460 if (!options->long_name)
462 if (!prefixcmp(options->long_name, arg)) {
463 fprintf(stderr, " Error: did you mean `--%s` (with two dashes ?)", arg);
469 static void parse_options_start(struct parse_opt_ctx_t *ctx,
470 int argc, const char **argv, int flags)
472 memset(ctx, 0, sizeof(*ctx));
473 ctx->argc = argc - 1;
474 ctx->argv = argv + 1;
476 ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
478 if ((flags & PARSE_OPT_KEEP_UNKNOWN) &&
479 (flags & PARSE_OPT_STOP_AT_NON_OPTION))
480 die("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
483 static int usage_with_options_internal(const char * const *,
484 const struct option *, int,
485 struct parse_opt_ctx_t *);
487 static int parse_options_step(struct parse_opt_ctx_t *ctx,
488 const struct option *options,
489 const char * const usagestr[])
491 int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
492 int excl_short_opt = 1;
495 /* we must reset ->opt, unknown short option leave it dangling */
498 for (; ctx->argc; ctx->argc--, ctx->argv++) {
500 if (*arg != '-' || !arg[1]) {
501 if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
503 ctx->out[ctx->cpidx++] = ctx->argv[0];
509 if (internal_help && *ctx->opt == 'h') {
510 return usage_with_options_internal(usagestr, options, 0, ctx);
512 switch (parse_short_opt(ctx, options)) {
514 return parse_options_usage(usagestr, options, arg, 1);
523 check_typos(arg, options);
525 if (internal_help && *ctx->opt == 'h')
526 return usage_with_options_internal(usagestr, options, 0, ctx);
528 switch (parse_short_opt(ctx, options)) {
530 return parse_options_usage(usagestr, options, arg, 1);
532 /* fake a short option thing to hide the fact that we may have
533 * started to parse aggregated stuff
535 * This is leaky, too bad.
537 ctx->argv[0] = strdup(ctx->opt - 1);
538 *(char *)ctx->argv[0] = '-';
549 if (!arg[2]) { /* "--" */
550 if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
558 if (internal_help && !strcmp(arg, "help-all"))
559 return usage_with_options_internal(usagestr, options, 1, ctx);
560 if (internal_help && !strcmp(arg, "help"))
561 return usage_with_options_internal(usagestr, options, 0, ctx);
562 if (!strcmp(arg, "list-opts"))
563 return PARSE_OPT_LIST_OPTS;
564 if (!strcmp(arg, "list-cmds"))
565 return PARSE_OPT_LIST_SUBCMDS;
566 switch (parse_long_opt(ctx, arg, options)) {
568 return parse_options_usage(usagestr, options, arg, 0);
579 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN))
580 return PARSE_OPT_UNKNOWN;
581 ctx->out[ctx->cpidx++] = ctx->argv[0];
584 return PARSE_OPT_DONE;
587 parse_options_usage(usagestr, options, arg, excl_short_opt);
588 if ((excl_short_opt && ctx->excl_opt->short_name) ||
589 ctx->excl_opt->long_name == NULL) {
590 char opt = ctx->excl_opt->short_name;
591 parse_options_usage(NULL, options, &opt, 1);
593 parse_options_usage(NULL, options, ctx->excl_opt->long_name, 0);
595 return PARSE_OPT_HELP;
598 static int parse_options_end(struct parse_opt_ctx_t *ctx)
600 memmove(ctx->out + ctx->cpidx, ctx->argv, ctx->argc * sizeof(*ctx->out));
601 ctx->out[ctx->cpidx + ctx->argc] = NULL;
602 return ctx->cpidx + ctx->argc;
605 int parse_options_subcommand(int argc, const char **argv, const struct option *options,
606 const char *const subcommands[], const char *usagestr[], int flags)
608 struct parse_opt_ctx_t ctx;
610 /* build usage string if it's not provided */
611 if (subcommands && !usagestr[0]) {
614 astrcatf(&buf, "%s %s [<options>] {", subcmd_config.exec_name, argv[0]);
616 for (int i = 0; subcommands[i]; i++) {
619 astrcat(&buf, subcommands[i]);
626 parse_options_start(&ctx, argc, argv, flags);
627 switch (parse_options_step(&ctx, options, usagestr)) {
632 case PARSE_OPT_LIST_OPTS:
633 while (options->type != OPTION_END) {
634 if (options->long_name)
635 printf("--%s ", options->long_name);
640 case PARSE_OPT_LIST_SUBCMDS:
642 for (int i = 0; subcommands[i]; i++)
643 printf("%s ", subcommands[i]);
647 default: /* PARSE_OPT_UNKNOWN */
648 if (ctx.argv[0][1] == '-')
649 astrcatf(&error_buf, "unknown option `%s'",
652 astrcatf(&error_buf, "unknown switch `%c'", *ctx.opt);
653 usage_with_options(usagestr, options);
656 return parse_options_end(&ctx);
659 int parse_options(int argc, const char **argv, const struct option *options,
660 const char * const usagestr[], int flags)
662 return parse_options_subcommand(argc, argv, options, NULL,
663 (const char **) usagestr, flags);
666 #define USAGE_OPTS_WIDTH 24
669 static void print_option_help(const struct option *opts, int full)
674 if (opts->type == OPTION_GROUP) {
677 fprintf(stderr, "%s\n", opts->help);
680 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
682 if (opts->flags & PARSE_OPT_DISABLED)
685 pos = fprintf(stderr, " ");
686 if (opts->short_name)
687 pos += fprintf(stderr, "-%c", opts->short_name);
689 pos += fprintf(stderr, " ");
691 if (opts->long_name && opts->short_name)
692 pos += fprintf(stderr, ", ");
694 pos += fprintf(stderr, "--%s", opts->long_name);
696 switch (opts->type) {
697 case OPTION_ARGUMENT:
702 case OPTION_UINTEGER:
703 if (opts->flags & PARSE_OPT_OPTARG)
705 pos += fprintf(stderr, "[=<n>]");
707 pos += fprintf(stderr, "[<n>]");
709 pos += fprintf(stderr, " <n>");
711 case OPTION_CALLBACK:
712 if (opts->flags & PARSE_OPT_NOARG)
717 if (opts->flags & PARSE_OPT_OPTARG)
719 pos += fprintf(stderr, "[=<%s>]", opts->argh);
721 pos += fprintf(stderr, "[<%s>]", opts->argh);
723 pos += fprintf(stderr, " <%s>", opts->argh);
725 if (opts->flags & PARSE_OPT_OPTARG)
727 pos += fprintf(stderr, "[=...]");
729 pos += fprintf(stderr, "[...]");
731 pos += fprintf(stderr, " ...");
734 default: /* OPTION_{BIT,BOOLEAN,SET_UINT,SET_PTR} */
740 case OPTION_SET_UINT:
745 if (pos <= USAGE_OPTS_WIDTH)
746 pad = USAGE_OPTS_WIDTH - pos;
749 pad = USAGE_OPTS_WIDTH;
751 fprintf(stderr, "%*s%s\n", pad + USAGE_GAP, "", opts->help);
752 if (opts->flags & PARSE_OPT_NOBUILD)
753 fprintf(stderr, "%*s(not built-in because %s)\n",
754 USAGE_OPTS_WIDTH + USAGE_GAP, "",
758 static int option__cmp(const void *va, const void *vb)
760 const struct option *a = va, *b = vb;
761 int sa = tolower(a->short_name), sb = tolower(b->short_name), ret;
771 const char *la = a->long_name ?: "",
772 *lb = b->long_name ?: "";
773 ret = strcmp(la, lb);
779 static struct option *options__order(const struct option *opts)
781 int nr_opts = 0, len;
782 const struct option *o = opts;
783 struct option *ordered;
785 for (o = opts; o->type != OPTION_END; o++)
788 len = sizeof(*o) * (nr_opts + 1);
789 ordered = malloc(len);
792 memcpy(ordered, opts, len);
794 qsort(ordered, nr_opts, sizeof(*o), option__cmp);
799 static bool option__in_argv(const struct option *opt, const struct parse_opt_ctx_t *ctx)
803 for (i = 1; i < ctx->argc; ++i) {
804 const char *arg = ctx->argv[i];
807 if (arg[1] == '\0') {
808 if (arg[0] == opt->short_name)
813 if (opt->long_name && strcmp(opt->long_name, arg) == 0)
816 if (opt->help && strcasestr(opt->help, arg) != NULL)
822 if (arg[1] == opt->short_name ||
823 (arg[1] == '-' && opt->long_name && strcmp(opt->long_name, arg + 2) == 0))
830 static int usage_with_options_internal(const char * const *usagestr,
831 const struct option *opts, int full,
832 struct parse_opt_ctx_t *ctx)
834 struct option *ordered;
837 return PARSE_OPT_HELP;
842 fprintf(stderr, " Error: %s\n", error_buf);
846 fprintf(stderr, "\n Usage: %s\n", *usagestr++);
847 while (*usagestr && **usagestr)
848 fprintf(stderr, " or: %s\n", *usagestr++);
850 fprintf(stderr, "%s%s\n",
851 **usagestr ? " " : "",
856 if (opts->type != OPTION_GROUP)
859 ordered = options__order(opts);
863 for ( ; opts->type != OPTION_END; opts++) {
864 if (ctx && ctx->argc > 1 && !option__in_argv(opts, ctx))
866 print_option_help(opts, full);
873 return PARSE_OPT_HELP;
876 void usage_with_options(const char * const *usagestr,
877 const struct option *opts)
879 usage_with_options_internal(usagestr, opts, 0, NULL);
883 void usage_with_options_msg(const char * const *usagestr,
884 const struct option *opts, const char *fmt, ...)
887 char *tmp = error_buf;
890 if (vasprintf(&error_buf, fmt, ap) == -1)
891 die("vasprintf failed");
896 usage_with_options_internal(usagestr, opts, 0, NULL);
900 int parse_options_usage(const char * const *usagestr,
901 const struct option *opts,
902 const char *optstr, bool short_opt)
907 fprintf(stderr, "\n Usage: %s\n", *usagestr++);
908 while (*usagestr && **usagestr)
909 fprintf(stderr, " or: %s\n", *usagestr++);
911 fprintf(stderr, "%s%s\n",
912 **usagestr ? " " : "",
919 for ( ; opts->type != OPTION_END; opts++) {
921 if (opts->short_name == *optstr) {
922 print_option_help(opts, 0);
928 if (opts->long_name == NULL)
931 if (!prefixcmp(opts->long_name, optstr))
932 print_option_help(opts, 0);
933 if (!prefixcmp("no-", optstr) &&
934 !prefixcmp(opts->long_name, optstr + 3))
935 print_option_help(opts, 0);
938 return PARSE_OPT_HELP;
942 int parse_opt_verbosity_cb(const struct option *opt,
943 const char *arg __maybe_unused,
946 int *target = opt->value;
949 /* --no-quiet, --no-verbose */
951 else if (opt->short_name == 'v') {
965 static struct option *
966 find_option(struct option *opts, int shortopt, const char *longopt)
968 for (; opts->type != OPTION_END; opts++) {
969 if ((shortopt && opts->short_name == shortopt) ||
970 (opts->long_name && longopt &&
971 !strcmp(opts->long_name, longopt)))
977 void set_option_flag(struct option *opts, int shortopt, const char *longopt,
980 struct option *opt = find_option(opts, shortopt, longopt);
987 void set_option_nobuild(struct option *opts, int shortopt,
989 const char *build_opt,
992 struct option *opt = find_option(opts, shortopt, longopt);
997 opt->flags |= PARSE_OPT_NOBUILD;
998 opt->flags |= can_skip ? PARSE_OPT_CANSKIP : 0;
999 opt->build_opt = build_opt;