1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/compiler.h>
3 #include <linux/string.h>
4 #include <linux/types.h>
10 #include "subcmd-util.h"
11 #include "parse-options.h"
12 #include "subcmd-config.h"
20 static int opterror(const struct option *opt, const char *reason, int flags)
22 if (flags & OPT_SHORT)
23 fprintf(stderr, " Error: switch `%c' %s", opt->short_name, reason);
24 else if (flags & OPT_UNSET)
25 fprintf(stderr, " Error: option `no-%s' %s", opt->long_name, reason);
27 fprintf(stderr, " Error: option `%s' %s", opt->long_name, reason);
32 static const char *skip_prefix(const char *str, const char *prefix)
34 size_t len = strlen(prefix);
35 return strncmp(str, prefix, len) ? NULL : str + len;
38 static void optwarning(const struct option *opt, const char *reason, int flags)
40 if (flags & OPT_SHORT)
41 fprintf(stderr, " Warning: switch `%c' %s", opt->short_name, reason);
42 else if (flags & OPT_UNSET)
43 fprintf(stderr, " Warning: option `no-%s' %s", opt->long_name, reason);
45 fprintf(stderr, " Warning: option `%s' %s", opt->long_name, reason);
48 static int get_arg(struct parse_opt_ctx_t *p, const struct option *opt,
49 int flags, const char **arg)
56 } else if ((opt->flags & PARSE_OPT_LASTARG_DEFAULT) && (p->argc == 1 ||
57 **(p->argv + 1) == '-')) {
58 res = (const char *)opt->defval;
59 } else if (p->argc > 1) {
63 return opterror(opt, "requires a value", flags);
69 static int get_value(struct parse_opt_ctx_t *p,
70 const struct option *opt, int flags)
72 const char *s, *arg = NULL;
73 const int unset = flags & OPT_UNSET;
77 return opterror(opt, "takes no value", flags);
78 if (unset && (opt->flags & PARSE_OPT_NONEG))
79 return opterror(opt, "isn't available", flags);
80 if (opt->flags & PARSE_OPT_DISABLED)
81 return opterror(opt, "is not usable", flags);
83 if (opt->flags & PARSE_OPT_EXCLUSIVE) {
84 if (p->excl_opt && p->excl_opt != opt) {
87 if (((flags & OPT_SHORT) && p->excl_opt->short_name) ||
88 p->excl_opt->long_name == NULL) {
89 snprintf(msg, sizeof(msg), "cannot be used with switch `%c'",
90 p->excl_opt->short_name);
92 snprintf(msg, sizeof(msg), "cannot be used with %s",
93 p->excl_opt->long_name);
95 opterror(opt, msg, flags);
100 if (!(flags & OPT_SHORT) && p->opt) {
102 case OPTION_CALLBACK:
103 if (!(opt->flags & PARSE_OPT_NOARG))
109 case OPTION_SET_UINT:
111 return opterror(opt, "takes no value", flags);
113 case OPTION_ARGUMENT:
117 case OPTION_UINTEGER:
126 if (opt->flags & PARSE_OPT_NOBUILD) {
130 err = snprintf(reason, sizeof(reason),
131 opt->flags & PARSE_OPT_CANSKIP ?
132 "is being ignored because %s " :
133 "is not available because %s",
135 reason[sizeof(reason) - 1] = '\0';
138 strncpy(reason, opt->flags & PARSE_OPT_CANSKIP ?
143 if (!(opt->flags & PARSE_OPT_CANSKIP))
144 return opterror(opt, reason, flags);
149 if (opt->flags & PARSE_OPT_NOARG)
151 if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
158 case OPTION_SET_UINT:
161 case OPTION_ARGUMENT:
165 case OPTION_CALLBACK:
168 case OPTION_UINTEGER:
177 err = get_arg(p, opt, flags, NULL);
181 optwarning(opt, reason, flags);
188 *(int *)opt->value &= ~opt->defval;
190 *(int *)opt->value |= opt->defval;
194 *(bool *)opt->value = unset ? false : true;
196 *(bool *)opt->set = true;
200 *(int *)opt->value = unset ? 0 : *(int *)opt->value + 1;
203 case OPTION_SET_UINT:
204 *(unsigned int *)opt->value = unset ? 0 : opt->defval;
208 *(void **)opt->value = unset ? NULL : (void *)opt->defval;
214 *(const char **)opt->value = NULL;
215 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
216 *(const char **)opt->value = (const char *)opt->defval;
218 err = get_arg(p, opt, flags, (const char **)opt->value);
221 *(bool *)opt->set = true;
223 /* PARSE_OPT_NOEMPTY: Allow NULL but disallow empty string. */
224 if (opt->flags & PARSE_OPT_NOEMPTY) {
225 const char *val = *(const char **)opt->value;
230 /* Similar to unset if we are given an empty string. */
231 if (val[0] == '\0') {
232 *(const char **)opt->value = NULL;
239 case OPTION_CALLBACK:
241 return (*opt->callback)(opt, NULL, 1) ? (-1) : 0;
242 if (opt->flags & PARSE_OPT_NOARG)
243 return (*opt->callback)(opt, NULL, 0) ? (-1) : 0;
244 if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
245 return (*opt->callback)(opt, NULL, 0) ? (-1) : 0;
246 if (get_arg(p, opt, flags, &arg))
248 return (*opt->callback)(opt, arg, 0) ? (-1) : 0;
252 *(int *)opt->value = 0;
255 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
256 *(int *)opt->value = opt->defval;
259 if (get_arg(p, opt, flags, &arg))
261 *(int *)opt->value = strtol(arg, (char **)&s, 10);
263 return opterror(opt, "expects a numerical value", flags);
266 case OPTION_UINTEGER:
268 *(unsigned int *)opt->value = 0;
271 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
272 *(unsigned int *)opt->value = opt->defval;
275 if (get_arg(p, opt, flags, &arg))
278 return opterror(opt, "expects an unsigned numerical value", flags);
279 *(unsigned int *)opt->value = strtol(arg, (char **)&s, 10);
281 return opterror(opt, "expects a numerical value", flags);
286 *(long *)opt->value = 0;
289 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
290 *(long *)opt->value = opt->defval;
293 if (get_arg(p, opt, flags, &arg))
295 *(long *)opt->value = strtol(arg, (char **)&s, 10);
297 return opterror(opt, "expects a numerical value", flags);
302 *(unsigned long *)opt->value = 0;
305 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
306 *(unsigned long *)opt->value = opt->defval;
309 if (get_arg(p, opt, flags, &arg))
311 *(unsigned long *)opt->value = strtoul(arg, (char **)&s, 10);
313 return opterror(opt, "expects a numerical value", flags);
318 *(u64 *)opt->value = 0;
321 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
322 *(u64 *)opt->value = opt->defval;
325 if (get_arg(p, opt, flags, &arg))
328 return opterror(opt, "expects an unsigned numerical value", flags);
329 *(u64 *)opt->value = strtoull(arg, (char **)&s, 10);
331 return opterror(opt, "expects a numerical value", flags);
335 case OPTION_ARGUMENT:
338 die("should not happen, someone must be hit on the forehead");
342 static int parse_short_opt(struct parse_opt_ctx_t *p, const struct option *options)
345 for (; options->type != OPTION_END; options++) {
346 if (options->short_name == *p->opt) {
347 p->opt = p->opt[1] ? p->opt + 1 : NULL;
348 return get_value(p, options, OPT_SHORT);
352 if (options->parent) {
353 options = options->parent;
360 static int parse_long_opt(struct parse_opt_ctx_t *p, const char *arg,
361 const struct option *options)
363 const char *arg_end = strchr(arg, '=');
364 const struct option *abbrev_option = NULL, *ambiguous_option = NULL;
365 int abbrev_flags = 0, ambiguous_flags = 0;
368 arg_end = arg + strlen(arg);
371 for (; options->type != OPTION_END; options++) {
375 if (!options->long_name)
378 rest = skip_prefix(arg, options->long_name);
379 if (options->type == OPTION_ARGUMENT) {
383 return opterror(options, "takes no value", flags);
386 p->out[p->cpidx++] = arg - 2;
390 if (strstarts(options->long_name, "no-")) {
392 * The long name itself starts with "no-", so
393 * accept the option without "no-" so that users
394 * do not have to enter "no-no-" to get the
397 rest = skip_prefix(arg, options->long_name + 3);
402 /* Abbreviated case */
403 if (strstarts(options->long_name + 3, arg)) {
409 if (!strncmp(options->long_name, arg, arg_end - arg)) {
413 * If this is abbreviated, it is
414 * ambiguous. So when there is no
415 * exact match later, we need to
418 ambiguous_option = abbrev_option;
419 ambiguous_flags = abbrev_flags;
421 if (!(flags & OPT_UNSET) && *arg_end)
422 p->opt = arg_end + 1;
423 abbrev_option = options;
424 abbrev_flags = flags;
427 /* negated and abbreviated very much? */
428 if (strstarts("no-", arg)) {
433 if (strncmp(arg, "no-", 3))
436 rest = skip_prefix(arg + 3, options->long_name);
437 /* abbreviated and negated? */
438 if (!rest && strstarts(options->long_name, arg + 3))
449 return get_value(p, options, flags);
452 if (ambiguous_option) {
454 " Error: Ambiguous option: %s (could be --%s%s or --%s%s)\n",
456 (ambiguous_flags & OPT_UNSET) ? "no-" : "",
457 ambiguous_option->long_name,
458 (abbrev_flags & OPT_UNSET) ? "no-" : "",
459 abbrev_option->long_name);
463 return get_value(p, abbrev_option, abbrev_flags);
465 if (options->parent) {
466 options = options->parent;
473 static void check_typos(const char *arg, const struct option *options)
478 if (strstarts(arg, "no-")) {
479 fprintf(stderr, " Error: did you mean `--%s` (with two dashes ?)\n", arg);
483 for (; options->type != OPTION_END; options++) {
484 if (!options->long_name)
486 if (strstarts(options->long_name, arg)) {
487 fprintf(stderr, " Error: did you mean `--%s` (with two dashes ?)\n", arg);
493 static void parse_options_start(struct parse_opt_ctx_t *ctx,
494 int argc, const char **argv, int flags)
496 memset(ctx, 0, sizeof(*ctx));
497 ctx->argc = argc - 1;
498 ctx->argv = argv + 1;
500 ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
502 if ((flags & PARSE_OPT_KEEP_UNKNOWN) &&
503 (flags & PARSE_OPT_STOP_AT_NON_OPTION))
504 die("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
507 static int usage_with_options_internal(const char * const *,
508 const struct option *, int,
509 struct parse_opt_ctx_t *);
511 static int parse_options_step(struct parse_opt_ctx_t *ctx,
512 const struct option *options,
513 const char * const usagestr[])
515 int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
516 int excl_short_opt = 1;
519 /* we must reset ->opt, unknown short option leave it dangling */
522 for (; ctx->argc; ctx->argc--, ctx->argv++) {
524 if (*arg != '-' || !arg[1]) {
525 if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
527 ctx->out[ctx->cpidx++] = ctx->argv[0];
533 if (internal_help && *ctx->opt == 'h') {
534 return usage_with_options_internal(usagestr, options, 0, ctx);
536 switch (parse_short_opt(ctx, options)) {
538 return parse_options_usage(usagestr, options, arg, 1);
547 check_typos(arg, options);
549 if (internal_help && *ctx->opt == 'h')
550 return usage_with_options_internal(usagestr, options, 0, ctx);
552 switch (parse_short_opt(ctx, options)) {
554 return parse_options_usage(usagestr, options, arg, 1);
556 /* fake a short option thing to hide the fact that we may have
557 * started to parse aggregated stuff
559 * This is leaky, too bad.
561 ctx->argv[0] = strdup(ctx->opt - 1);
562 *(char *)ctx->argv[0] = '-';
573 if (!arg[2]) { /* "--" */
574 if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
582 if (internal_help && !strcmp(arg, "help-all"))
583 return usage_with_options_internal(usagestr, options, 1, ctx);
584 if (internal_help && !strcmp(arg, "help"))
585 return usage_with_options_internal(usagestr, options, 0, ctx);
586 if (!strcmp(arg, "list-opts"))
587 return PARSE_OPT_LIST_OPTS;
588 if (!strcmp(arg, "list-cmds"))
589 return PARSE_OPT_LIST_SUBCMDS;
590 switch (parse_long_opt(ctx, arg, options)) {
592 return parse_options_usage(usagestr, options, arg, 0);
603 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN))
604 return PARSE_OPT_UNKNOWN;
605 ctx->out[ctx->cpidx++] = ctx->argv[0];
608 return PARSE_OPT_DONE;
611 parse_options_usage(usagestr, options, arg, excl_short_opt);
612 if ((excl_short_opt && ctx->excl_opt->short_name) ||
613 ctx->excl_opt->long_name == NULL) {
614 char opt = ctx->excl_opt->short_name;
615 parse_options_usage(NULL, options, &opt, 1);
617 parse_options_usage(NULL, options, ctx->excl_opt->long_name, 0);
619 return PARSE_OPT_HELP;
622 static int parse_options_end(struct parse_opt_ctx_t *ctx)
624 memmove(ctx->out + ctx->cpidx, ctx->argv, ctx->argc * sizeof(*ctx->out));
625 ctx->out[ctx->cpidx + ctx->argc] = NULL;
626 return ctx->cpidx + ctx->argc;
629 int parse_options_subcommand(int argc, const char **argv, const struct option *options,
630 const char *const subcommands[], const char *usagestr[], int flags)
632 struct parse_opt_ctx_t ctx;
634 /* build usage string if it's not provided */
635 if (subcommands && !usagestr[0]) {
638 astrcatf(&buf, "%s %s [<options>] {", subcmd_config.exec_name, argv[0]);
640 for (int i = 0; subcommands[i]; i++) {
643 astrcat(&buf, subcommands[i]);
650 parse_options_start(&ctx, argc, argv, flags);
651 switch (parse_options_step(&ctx, options, usagestr)) {
656 case PARSE_OPT_LIST_OPTS:
657 while (options->type != OPTION_END) {
658 if (options->long_name)
659 printf("--%s ", options->long_name);
664 case PARSE_OPT_LIST_SUBCMDS:
666 for (int i = 0; subcommands[i]; i++)
667 printf("%s ", subcommands[i]);
671 default: /* PARSE_OPT_UNKNOWN */
672 if (ctx.argv[0][1] == '-')
673 astrcatf(&error_buf, "unknown option `%s'",
676 astrcatf(&error_buf, "unknown switch `%c'", *ctx.opt);
677 usage_with_options(usagestr, options);
680 return parse_options_end(&ctx);
683 int parse_options(int argc, const char **argv, const struct option *options,
684 const char * const usagestr[], int flags)
686 return parse_options_subcommand(argc, argv, options, NULL,
687 (const char **) usagestr, flags);
690 #define USAGE_OPTS_WIDTH 24
693 static void print_option_help(const struct option *opts, int full)
698 if (opts->type == OPTION_GROUP) {
701 fprintf(stderr, "%s\n", opts->help);
704 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
706 if (opts->flags & PARSE_OPT_DISABLED)
709 pos = fprintf(stderr, " ");
710 if (opts->short_name)
711 pos += fprintf(stderr, "-%c", opts->short_name);
713 pos += fprintf(stderr, " ");
715 if (opts->long_name && opts->short_name)
716 pos += fprintf(stderr, ", ");
718 pos += fprintf(stderr, "--%s", opts->long_name);
720 switch (opts->type) {
721 case OPTION_ARGUMENT:
727 case OPTION_UINTEGER:
728 if (opts->flags & PARSE_OPT_OPTARG)
730 pos += fprintf(stderr, "[=<n>]");
732 pos += fprintf(stderr, "[<n>]");
734 pos += fprintf(stderr, " <n>");
736 case OPTION_CALLBACK:
737 if (opts->flags & PARSE_OPT_NOARG)
742 if (opts->flags & PARSE_OPT_OPTARG)
744 pos += fprintf(stderr, "[=<%s>]", opts->argh);
746 pos += fprintf(stderr, "[<%s>]", opts->argh);
748 pos += fprintf(stderr, " <%s>", opts->argh);
750 if (opts->flags & PARSE_OPT_OPTARG)
752 pos += fprintf(stderr, "[=...]");
754 pos += fprintf(stderr, "[...]");
756 pos += fprintf(stderr, " ...");
759 default: /* OPTION_{BIT,BOOLEAN,SET_UINT,SET_PTR} */
765 case OPTION_SET_UINT:
770 if (pos <= USAGE_OPTS_WIDTH)
771 pad = USAGE_OPTS_WIDTH - pos;
774 pad = USAGE_OPTS_WIDTH;
776 fprintf(stderr, "%*s%s\n", pad + USAGE_GAP, "", opts->help);
777 if (opts->flags & PARSE_OPT_NOBUILD)
778 fprintf(stderr, "%*s(not built-in because %s)\n",
779 USAGE_OPTS_WIDTH + USAGE_GAP, "",
783 static int option__cmp(const void *va, const void *vb)
785 const struct option *a = va, *b = vb;
786 int sa = tolower(a->short_name), sb = tolower(b->short_name), ret;
796 const char *la = a->long_name ?: "",
797 *lb = b->long_name ?: "";
798 ret = strcmp(la, lb);
804 static struct option *options__order(const struct option *opts)
806 int nr_opts = 0, len;
807 const struct option *o = opts;
808 struct option *ordered;
810 for (o = opts; o->type != OPTION_END; o++)
813 len = sizeof(*o) * (nr_opts + 1);
814 ordered = malloc(len);
817 memcpy(ordered, opts, len);
819 qsort(ordered, nr_opts, sizeof(*o), option__cmp);
824 static bool option__in_argv(const struct option *opt, const struct parse_opt_ctx_t *ctx)
828 for (i = 1; i < ctx->argc; ++i) {
829 const char *arg = ctx->argv[i];
832 if (arg[1] == '\0') {
833 if (arg[0] == opt->short_name)
838 if (opt->long_name && strcmp(opt->long_name, arg) == 0)
841 if (opt->help && strcasestr(opt->help, arg) != NULL)
847 if (arg[1] == opt->short_name ||
848 (arg[1] == '-' && opt->long_name && strcmp(opt->long_name, arg + 2) == 0))
855 static int usage_with_options_internal(const char * const *usagestr,
856 const struct option *opts, int full,
857 struct parse_opt_ctx_t *ctx)
859 struct option *ordered;
862 return PARSE_OPT_HELP;
867 fprintf(stderr, " Error: %s\n", error_buf);
871 fprintf(stderr, "\n Usage: %s\n", *usagestr++);
872 while (*usagestr && **usagestr)
873 fprintf(stderr, " or: %s\n", *usagestr++);
875 fprintf(stderr, "%s%s\n",
876 **usagestr ? " " : "",
881 if (opts->type != OPTION_GROUP)
884 ordered = options__order(opts);
888 for ( ; opts->type != OPTION_END; opts++) {
889 if (ctx && ctx->argc > 1 && !option__in_argv(opts, ctx))
891 print_option_help(opts, full);
898 return PARSE_OPT_HELP;
901 void usage_with_options(const char * const *usagestr,
902 const struct option *opts)
904 usage_with_options_internal(usagestr, opts, 0, NULL);
908 void usage_with_options_msg(const char * const *usagestr,
909 const struct option *opts, const char *fmt, ...)
912 char *tmp = error_buf;
915 if (vasprintf(&error_buf, fmt, ap) == -1)
916 die("vasprintf failed");
921 usage_with_options_internal(usagestr, opts, 0, NULL);
925 int parse_options_usage(const char * const *usagestr,
926 const struct option *opts,
927 const char *optstr, bool short_opt)
932 fprintf(stderr, "\n Usage: %s\n", *usagestr++);
933 while (*usagestr && **usagestr)
934 fprintf(stderr, " or: %s\n", *usagestr++);
936 fprintf(stderr, "%s%s\n",
937 **usagestr ? " " : "",
944 for ( ; opts->type != OPTION_END; opts++) {
946 if (opts->short_name == *optstr) {
947 print_option_help(opts, 0);
953 if (opts->long_name == NULL)
956 if (strstarts(opts->long_name, optstr))
957 print_option_help(opts, 0);
958 if (strstarts("no-", optstr) &&
959 strstarts(opts->long_name, optstr + 3))
960 print_option_help(opts, 0);
963 return PARSE_OPT_HELP;
967 int parse_opt_verbosity_cb(const struct option *opt,
968 const char *arg __maybe_unused,
971 int *target = opt->value;
974 /* --no-quiet, --no-verbose */
976 else if (opt->short_name == 'v') {
990 static struct option *
991 find_option(struct option *opts, int shortopt, const char *longopt)
993 for (; opts->type != OPTION_END; opts++) {
994 if ((shortopt && opts->short_name == shortopt) ||
995 (opts->long_name && longopt &&
996 !strcmp(opts->long_name, longopt)))
1002 void set_option_flag(struct option *opts, int shortopt, const char *longopt,
1005 struct option *opt = find_option(opts, shortopt, longopt);
1012 void set_option_nobuild(struct option *opts, int shortopt,
1013 const char *longopt,
1014 const char *build_opt,
1017 struct option *opt = find_option(opts, shortopt, longopt);
1022 opt->flags |= PARSE_OPT_NOBUILD;
1023 opt->flags |= can_skip ? PARSE_OPT_CANSKIP : 0;
1024 opt->build_opt = build_opt;