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 *(bool *)opt->set = true;
244 return (*opt->callback)(opt, NULL, 1) ? (-1) : 0;
245 if (opt->flags & PARSE_OPT_NOARG)
246 return (*opt->callback)(opt, NULL, 0) ? (-1) : 0;
247 if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
248 return (*opt->callback)(opt, NULL, 0) ? (-1) : 0;
249 if (get_arg(p, opt, flags, &arg))
251 return (*opt->callback)(opt, arg, 0) ? (-1) : 0;
255 *(int *)opt->value = 0;
258 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
259 *(int *)opt->value = opt->defval;
262 if (get_arg(p, opt, flags, &arg))
264 *(int *)opt->value = strtol(arg, (char **)&s, 10);
266 return opterror(opt, "expects a numerical value", flags);
269 case OPTION_UINTEGER:
271 *(unsigned int *)opt->value = 0;
274 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
275 *(unsigned int *)opt->value = opt->defval;
278 if (get_arg(p, opt, flags, &arg))
281 return opterror(opt, "expects an unsigned numerical value", flags);
282 *(unsigned int *)opt->value = strtol(arg, (char **)&s, 10);
284 return opterror(opt, "expects a numerical value", flags);
289 *(long *)opt->value = 0;
292 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
293 *(long *)opt->value = opt->defval;
296 if (get_arg(p, opt, flags, &arg))
298 *(long *)opt->value = strtol(arg, (char **)&s, 10);
300 return opterror(opt, "expects a numerical value", flags);
305 *(unsigned long *)opt->value = 0;
308 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
309 *(unsigned long *)opt->value = opt->defval;
312 if (get_arg(p, opt, flags, &arg))
314 *(unsigned long *)opt->value = strtoul(arg, (char **)&s, 10);
316 return opterror(opt, "expects a numerical value", flags);
321 *(u64 *)opt->value = 0;
324 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
325 *(u64 *)opt->value = opt->defval;
328 if (get_arg(p, opt, flags, &arg))
331 return opterror(opt, "expects an unsigned numerical value", flags);
332 *(u64 *)opt->value = strtoull(arg, (char **)&s, 10);
334 return opterror(opt, "expects a numerical value", flags);
338 case OPTION_ARGUMENT:
341 die("should not happen, someone must be hit on the forehead");
345 static int parse_short_opt(struct parse_opt_ctx_t *p, const struct option *options)
348 for (; options->type != OPTION_END; options++) {
349 if (options->short_name == *p->opt) {
350 p->opt = p->opt[1] ? p->opt + 1 : NULL;
351 return get_value(p, options, OPT_SHORT);
355 if (options->parent) {
356 options = options->parent;
363 static int parse_long_opt(struct parse_opt_ctx_t *p, const char *arg,
364 const struct option *options)
366 const char *arg_end = strchr(arg, '=');
367 const struct option *abbrev_option = NULL, *ambiguous_option = NULL;
368 int abbrev_flags = 0, ambiguous_flags = 0;
371 arg_end = arg + strlen(arg);
374 for (; options->type != OPTION_END; options++) {
378 if (!options->long_name)
381 rest = skip_prefix(arg, options->long_name);
382 if (options->type == OPTION_ARGUMENT) {
386 return opterror(options, "takes no value", flags);
389 p->out[p->cpidx++] = arg - 2;
393 if (strstarts(options->long_name, "no-")) {
395 * The long name itself starts with "no-", so
396 * accept the option without "no-" so that users
397 * do not have to enter "no-no-" to get the
400 rest = skip_prefix(arg, options->long_name + 3);
405 /* Abbreviated case */
406 if (strstarts(options->long_name + 3, arg)) {
412 if (!strncmp(options->long_name, arg, arg_end - arg)) {
416 * If this is abbreviated, it is
417 * ambiguous. So when there is no
418 * exact match later, we need to
421 ambiguous_option = abbrev_option;
422 ambiguous_flags = abbrev_flags;
424 if (!(flags & OPT_UNSET) && *arg_end)
425 p->opt = arg_end + 1;
426 abbrev_option = options;
427 abbrev_flags = flags;
430 /* negated and abbreviated very much? */
431 if (strstarts("no-", arg)) {
436 if (strncmp(arg, "no-", 3))
439 rest = skip_prefix(arg + 3, options->long_name);
440 /* abbreviated and negated? */
441 if (!rest && strstarts(options->long_name, arg + 3))
452 return get_value(p, options, flags);
455 if (ambiguous_option) {
457 " Error: Ambiguous option: %s (could be --%s%s or --%s%s)\n",
459 (ambiguous_flags & OPT_UNSET) ? "no-" : "",
460 ambiguous_option->long_name,
461 (abbrev_flags & OPT_UNSET) ? "no-" : "",
462 abbrev_option->long_name);
466 return get_value(p, abbrev_option, abbrev_flags);
468 if (options->parent) {
469 options = options->parent;
476 static void check_typos(const char *arg, const struct option *options)
481 if (strstarts(arg, "no-")) {
482 fprintf(stderr, " Error: did you mean `--%s` (with two dashes ?)\n", arg);
486 for (; options->type != OPTION_END; options++) {
487 if (!options->long_name)
489 if (strstarts(options->long_name, arg)) {
490 fprintf(stderr, " Error: did you mean `--%s` (with two dashes ?)\n", arg);
496 static void parse_options_start(struct parse_opt_ctx_t *ctx,
497 int argc, const char **argv, int flags)
499 memset(ctx, 0, sizeof(*ctx));
500 ctx->argc = argc - 1;
501 ctx->argv = argv + 1;
503 ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
505 if ((flags & PARSE_OPT_KEEP_UNKNOWN) &&
506 (flags & PARSE_OPT_STOP_AT_NON_OPTION))
507 die("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
510 static int usage_with_options_internal(const char * const *,
511 const struct option *, int,
512 struct parse_opt_ctx_t *);
514 static int parse_options_step(struct parse_opt_ctx_t *ctx,
515 const struct option *options,
516 const char * const usagestr[])
518 int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
519 int excl_short_opt = 1;
522 /* we must reset ->opt, unknown short option leave it dangling */
525 for (; ctx->argc; ctx->argc--, ctx->argv++) {
527 if (*arg != '-' || !arg[1]) {
528 if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
530 ctx->out[ctx->cpidx++] = ctx->argv[0];
536 if (internal_help && *ctx->opt == 'h') {
537 return usage_with_options_internal(usagestr, options, 0, ctx);
539 switch (parse_short_opt(ctx, options)) {
541 return parse_options_usage(usagestr, options, arg, 1);
550 check_typos(arg, options);
552 if (internal_help && *ctx->opt == 'h')
553 return usage_with_options_internal(usagestr, options, 0, ctx);
555 switch (parse_short_opt(ctx, options)) {
557 return parse_options_usage(usagestr, options, arg, 1);
559 /* fake a short option thing to hide the fact that we may have
560 * started to parse aggregated stuff
562 * This is leaky, too bad.
564 ctx->argv[0] = strdup(ctx->opt - 1);
565 *(char *)ctx->argv[0] = '-';
576 if (!arg[2]) { /* "--" */
577 if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
585 if (internal_help && !strcmp(arg, "help-all"))
586 return usage_with_options_internal(usagestr, options, 1, ctx);
587 if (internal_help && !strcmp(arg, "help"))
588 return usage_with_options_internal(usagestr, options, 0, ctx);
589 if (!strcmp(arg, "list-opts"))
590 return PARSE_OPT_LIST_OPTS;
591 if (!strcmp(arg, "list-cmds"))
592 return PARSE_OPT_LIST_SUBCMDS;
593 switch (parse_long_opt(ctx, arg, options)) {
595 return parse_options_usage(usagestr, options, arg, 0);
606 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN))
607 return PARSE_OPT_UNKNOWN;
608 ctx->out[ctx->cpidx++] = ctx->argv[0];
611 return PARSE_OPT_DONE;
614 parse_options_usage(usagestr, options, arg, excl_short_opt);
615 if ((excl_short_opt && ctx->excl_opt->short_name) ||
616 ctx->excl_opt->long_name == NULL) {
617 char opt = ctx->excl_opt->short_name;
618 parse_options_usage(NULL, options, &opt, 1);
620 parse_options_usage(NULL, options, ctx->excl_opt->long_name, 0);
622 return PARSE_OPT_HELP;
625 static int parse_options_end(struct parse_opt_ctx_t *ctx)
627 memmove(ctx->out + ctx->cpidx, ctx->argv, ctx->argc * sizeof(*ctx->out));
628 ctx->out[ctx->cpidx + ctx->argc] = NULL;
629 return ctx->cpidx + ctx->argc;
632 int parse_options_subcommand(int argc, const char **argv, const struct option *options,
633 const char *const subcommands[], const char *usagestr[], int flags)
635 struct parse_opt_ctx_t ctx;
637 /* build usage string if it's not provided */
638 if (subcommands && !usagestr[0]) {
641 astrcatf(&buf, "%s %s [<options>] {", subcmd_config.exec_name, argv[0]);
643 for (int i = 0; subcommands[i]; i++) {
646 astrcat(&buf, subcommands[i]);
653 parse_options_start(&ctx, argc, argv, flags);
654 switch (parse_options_step(&ctx, options, usagestr)) {
659 case PARSE_OPT_LIST_OPTS:
660 while (options->type != OPTION_END) {
661 if (options->long_name)
662 printf("--%s ", options->long_name);
667 case PARSE_OPT_LIST_SUBCMDS:
669 for (int i = 0; subcommands[i]; i++)
670 printf("%s ", subcommands[i]);
674 default: /* PARSE_OPT_UNKNOWN */
675 if (ctx.argv[0][1] == '-')
676 astrcatf(&error_buf, "unknown option `%s'",
679 astrcatf(&error_buf, "unknown switch `%c'", *ctx.opt);
680 usage_with_options(usagestr, options);
683 return parse_options_end(&ctx);
686 int parse_options(int argc, const char **argv, const struct option *options,
687 const char * const usagestr[], int flags)
689 return parse_options_subcommand(argc, argv, options, NULL,
690 (const char **) usagestr, flags);
693 #define USAGE_OPTS_WIDTH 24
696 static void print_option_help(const struct option *opts, int full)
701 if (opts->type == OPTION_GROUP) {
704 fprintf(stderr, "%s\n", opts->help);
707 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
709 if (opts->flags & PARSE_OPT_DISABLED)
712 pos = fprintf(stderr, " ");
713 if (opts->short_name)
714 pos += fprintf(stderr, "-%c", opts->short_name);
716 pos += fprintf(stderr, " ");
718 if (opts->long_name && opts->short_name)
719 pos += fprintf(stderr, ", ");
721 pos += fprintf(stderr, "--%s", opts->long_name);
723 switch (opts->type) {
724 case OPTION_ARGUMENT:
730 case OPTION_UINTEGER:
731 if (opts->flags & PARSE_OPT_OPTARG)
733 pos += fprintf(stderr, "[=<n>]");
735 pos += fprintf(stderr, "[<n>]");
737 pos += fprintf(stderr, " <n>");
739 case OPTION_CALLBACK:
740 if (opts->flags & PARSE_OPT_NOARG)
745 if (opts->flags & PARSE_OPT_OPTARG)
747 pos += fprintf(stderr, "[=<%s>]", opts->argh);
749 pos += fprintf(stderr, "[<%s>]", opts->argh);
751 pos += fprintf(stderr, " <%s>", opts->argh);
753 if (opts->flags & PARSE_OPT_OPTARG)
755 pos += fprintf(stderr, "[=...]");
757 pos += fprintf(stderr, "[...]");
759 pos += fprintf(stderr, " ...");
762 default: /* OPTION_{BIT,BOOLEAN,SET_UINT,SET_PTR} */
768 case OPTION_SET_UINT:
773 if (pos <= USAGE_OPTS_WIDTH)
774 pad = USAGE_OPTS_WIDTH - pos;
777 pad = USAGE_OPTS_WIDTH;
779 fprintf(stderr, "%*s%s\n", pad + USAGE_GAP, "", opts->help);
780 if (opts->flags & PARSE_OPT_NOBUILD)
781 fprintf(stderr, "%*s(not built-in because %s)\n",
782 USAGE_OPTS_WIDTH + USAGE_GAP, "",
786 static int option__cmp(const void *va, const void *vb)
788 const struct option *a = va, *b = vb;
789 int sa = tolower(a->short_name), sb = tolower(b->short_name), ret;
799 const char *la = a->long_name ?: "",
800 *lb = b->long_name ?: "";
801 ret = strcmp(la, lb);
807 static struct option *options__order(const struct option *opts)
809 int nr_opts = 0, nr_group = 0, len;
810 const struct option *o = opts;
811 struct option *opt, *ordered, *group;
813 for (o = opts; o->type != OPTION_END; o++)
816 len = sizeof(*o) * (nr_opts + 1);
817 ordered = malloc(len);
820 memcpy(ordered, opts, len);
822 /* sort each option group individually */
823 for (opt = group = ordered; opt->type != OPTION_END; opt++) {
824 if (opt->type == OPTION_GROUP) {
825 qsort(group, nr_group, sizeof(*opt), option__cmp);
832 qsort(group, nr_group, sizeof(*opt), option__cmp);
838 static bool option__in_argv(const struct option *opt, const struct parse_opt_ctx_t *ctx)
842 for (i = 1; i < ctx->argc; ++i) {
843 const char *arg = ctx->argv[i];
846 if (arg[1] == '\0') {
847 if (arg[0] == opt->short_name)
852 if (opt->long_name && strcmp(opt->long_name, arg) == 0)
855 if (opt->help && strcasestr(opt->help, arg) != NULL)
861 if (arg[1] == opt->short_name ||
862 (arg[1] == '-' && opt->long_name && strcmp(opt->long_name, arg + 2) == 0))
869 static int usage_with_options_internal(const char * const *usagestr,
870 const struct option *opts, int full,
871 struct parse_opt_ctx_t *ctx)
873 struct option *ordered;
876 return PARSE_OPT_HELP;
881 fprintf(stderr, " Error: %s\n", error_buf);
885 fprintf(stderr, "\n Usage: %s\n", *usagestr++);
886 while (*usagestr && **usagestr)
887 fprintf(stderr, " or: %s\n", *usagestr++);
889 fprintf(stderr, "%s%s\n",
890 **usagestr ? " " : "",
895 if (opts->type != OPTION_GROUP)
898 ordered = options__order(opts);
902 for ( ; opts->type != OPTION_END; opts++) {
903 if (ctx && ctx->argc > 1 && !option__in_argv(opts, ctx))
905 print_option_help(opts, full);
912 return PARSE_OPT_HELP;
915 void usage_with_options(const char * const *usagestr,
916 const struct option *opts)
918 usage_with_options_internal(usagestr, opts, 0, NULL);
922 void usage_with_options_msg(const char * const *usagestr,
923 const struct option *opts, const char *fmt, ...)
926 char *tmp = error_buf;
929 if (vasprintf(&error_buf, fmt, ap) == -1)
930 die("vasprintf failed");
935 usage_with_options_internal(usagestr, opts, 0, NULL);
939 int parse_options_usage(const char * const *usagestr,
940 const struct option *opts,
941 const char *optstr, bool short_opt)
946 fprintf(stderr, "\n Usage: %s\n", *usagestr++);
947 while (*usagestr && **usagestr)
948 fprintf(stderr, " or: %s\n", *usagestr++);
950 fprintf(stderr, "%s%s\n",
951 **usagestr ? " " : "",
958 for ( ; opts->type != OPTION_END; opts++) {
960 if (opts->short_name == *optstr) {
961 print_option_help(opts, 0);
967 if (opts->long_name == NULL)
970 if (strstarts(opts->long_name, optstr))
971 print_option_help(opts, 0);
972 if (strstarts("no-", optstr) &&
973 strstarts(opts->long_name, optstr + 3))
974 print_option_help(opts, 0);
977 return PARSE_OPT_HELP;
981 int parse_opt_verbosity_cb(const struct option *opt,
982 const char *arg __maybe_unused,
985 int *target = opt->value;
988 /* --no-quiet, --no-verbose */
990 else if (opt->short_name == 'v') {
1004 static struct option *
1005 find_option(struct option *opts, int shortopt, const char *longopt)
1007 for (; opts->type != OPTION_END; opts++) {
1008 if ((shortopt && opts->short_name == shortopt) ||
1009 (opts->long_name && longopt &&
1010 !strcmp(opts->long_name, longopt)))
1016 void set_option_flag(struct option *opts, int shortopt, const char *longopt,
1019 struct option *opt = find_option(opts, shortopt, longopt);
1026 void set_option_nobuild(struct option *opts, int shortopt,
1027 const char *longopt,
1028 const char *build_opt,
1031 struct option *opt = find_option(opts, shortopt, longopt);
1036 opt->flags |= PARSE_OPT_NOBUILD;
1037 opt->flags |= can_skip ? PARSE_OPT_CANSKIP : 0;
1038 opt->build_opt = build_opt;