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))
274 return opterror(opt, "expects an unsigned numerical value", flags);
275 *(unsigned int *)opt->value = strtol(arg, (char **)&s, 10);
277 return opterror(opt, "expects a numerical value", flags);
282 *(long *)opt->value = 0;
285 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
286 *(long *)opt->value = opt->defval;
289 if (get_arg(p, opt, flags, &arg))
291 *(long *)opt->value = strtol(arg, (char **)&s, 10);
293 return opterror(opt, "expects a numerical value", flags);
298 *(u64 *)opt->value = 0;
301 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
302 *(u64 *)opt->value = opt->defval;
305 if (get_arg(p, opt, flags, &arg))
308 return opterror(opt, "expects an unsigned numerical value", flags);
309 *(u64 *)opt->value = strtoull(arg, (char **)&s, 10);
311 return opterror(opt, "expects a numerical value", flags);
315 case OPTION_ARGUMENT:
318 die("should not happen, someone must be hit on the forehead");
322 static int parse_short_opt(struct parse_opt_ctx_t *p, const struct option *options)
325 for (; options->type != OPTION_END; options++) {
326 if (options->short_name == *p->opt) {
327 p->opt = p->opt[1] ? p->opt + 1 : NULL;
328 return get_value(p, options, OPT_SHORT);
332 if (options->parent) {
333 options = options->parent;
340 static int parse_long_opt(struct parse_opt_ctx_t *p, const char *arg,
341 const struct option *options)
343 const char *arg_end = strchr(arg, '=');
344 const struct option *abbrev_option = NULL, *ambiguous_option = NULL;
345 int abbrev_flags = 0, ambiguous_flags = 0;
348 arg_end = arg + strlen(arg);
351 for (; options->type != OPTION_END; options++) {
355 if (!options->long_name)
358 rest = skip_prefix(arg, options->long_name);
359 if (options->type == OPTION_ARGUMENT) {
363 return opterror(options, "takes no value", flags);
366 p->out[p->cpidx++] = arg - 2;
370 if (!prefixcmp(options->long_name, "no-")) {
372 * The long name itself starts with "no-", so
373 * accept the option without "no-" so that users
374 * do not have to enter "no-no-" to get the
377 rest = skip_prefix(arg, options->long_name + 3);
382 /* Abbreviated case */
383 if (!prefixcmp(options->long_name + 3, arg)) {
389 if (!strncmp(options->long_name, arg, arg_end - arg)) {
393 * If this is abbreviated, it is
394 * ambiguous. So when there is no
395 * exact match later, we need to
398 ambiguous_option = abbrev_option;
399 ambiguous_flags = abbrev_flags;
401 if (!(flags & OPT_UNSET) && *arg_end)
402 p->opt = arg_end + 1;
403 abbrev_option = options;
404 abbrev_flags = flags;
407 /* negated and abbreviated very much? */
408 if (!prefixcmp("no-", arg)) {
413 if (strncmp(arg, "no-", 3))
416 rest = skip_prefix(arg + 3, options->long_name);
417 /* abbreviated and negated? */
418 if (!rest && !prefixcmp(options->long_name, arg + 3))
429 return get_value(p, options, flags);
432 if (ambiguous_option) {
434 " Error: Ambiguous option: %s (could be --%s%s or --%s%s)",
436 (ambiguous_flags & OPT_UNSET) ? "no-" : "",
437 ambiguous_option->long_name,
438 (abbrev_flags & OPT_UNSET) ? "no-" : "",
439 abbrev_option->long_name);
443 return get_value(p, abbrev_option, abbrev_flags);
445 if (options->parent) {
446 options = options->parent;
453 static void check_typos(const char *arg, const struct option *options)
458 if (!prefixcmp(arg, "no-")) {
459 fprintf(stderr, " Error: did you mean `--%s` (with two dashes ?)", arg);
463 for (; options->type != OPTION_END; options++) {
464 if (!options->long_name)
466 if (!prefixcmp(options->long_name, arg)) {
467 fprintf(stderr, " Error: did you mean `--%s` (with two dashes ?)", arg);
473 static void parse_options_start(struct parse_opt_ctx_t *ctx,
474 int argc, const char **argv, int flags)
476 memset(ctx, 0, sizeof(*ctx));
477 ctx->argc = argc - 1;
478 ctx->argv = argv + 1;
480 ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
482 if ((flags & PARSE_OPT_KEEP_UNKNOWN) &&
483 (flags & PARSE_OPT_STOP_AT_NON_OPTION))
484 die("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
487 static int usage_with_options_internal(const char * const *,
488 const struct option *, int,
489 struct parse_opt_ctx_t *);
491 static int parse_options_step(struct parse_opt_ctx_t *ctx,
492 const struct option *options,
493 const char * const usagestr[])
495 int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
496 int excl_short_opt = 1;
499 /* we must reset ->opt, unknown short option leave it dangling */
502 for (; ctx->argc; ctx->argc--, ctx->argv++) {
504 if (*arg != '-' || !arg[1]) {
505 if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
507 ctx->out[ctx->cpidx++] = ctx->argv[0];
513 if (internal_help && *ctx->opt == 'h') {
514 return usage_with_options_internal(usagestr, options, 0, ctx);
516 switch (parse_short_opt(ctx, options)) {
518 return parse_options_usage(usagestr, options, arg, 1);
527 check_typos(arg, options);
529 if (internal_help && *ctx->opt == 'h')
530 return usage_with_options_internal(usagestr, options, 0, ctx);
532 switch (parse_short_opt(ctx, options)) {
534 return parse_options_usage(usagestr, options, arg, 1);
536 /* fake a short option thing to hide the fact that we may have
537 * started to parse aggregated stuff
539 * This is leaky, too bad.
541 ctx->argv[0] = strdup(ctx->opt - 1);
542 *(char *)ctx->argv[0] = '-';
553 if (!arg[2]) { /* "--" */
554 if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
562 if (internal_help && !strcmp(arg, "help-all"))
563 return usage_with_options_internal(usagestr, options, 1, ctx);
564 if (internal_help && !strcmp(arg, "help"))
565 return usage_with_options_internal(usagestr, options, 0, ctx);
566 if (!strcmp(arg, "list-opts"))
567 return PARSE_OPT_LIST_OPTS;
568 if (!strcmp(arg, "list-cmds"))
569 return PARSE_OPT_LIST_SUBCMDS;
570 switch (parse_long_opt(ctx, arg, options)) {
572 return parse_options_usage(usagestr, options, arg, 0);
583 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN))
584 return PARSE_OPT_UNKNOWN;
585 ctx->out[ctx->cpidx++] = ctx->argv[0];
588 return PARSE_OPT_DONE;
591 parse_options_usage(usagestr, options, arg, excl_short_opt);
592 if ((excl_short_opt && ctx->excl_opt->short_name) ||
593 ctx->excl_opt->long_name == NULL) {
594 char opt = ctx->excl_opt->short_name;
595 parse_options_usage(NULL, options, &opt, 1);
597 parse_options_usage(NULL, options, ctx->excl_opt->long_name, 0);
599 return PARSE_OPT_HELP;
602 static int parse_options_end(struct parse_opt_ctx_t *ctx)
604 memmove(ctx->out + ctx->cpidx, ctx->argv, ctx->argc * sizeof(*ctx->out));
605 ctx->out[ctx->cpidx + ctx->argc] = NULL;
606 return ctx->cpidx + ctx->argc;
609 int parse_options_subcommand(int argc, const char **argv, const struct option *options,
610 const char *const subcommands[], const char *usagestr[], int flags)
612 struct parse_opt_ctx_t ctx;
614 /* build usage string if it's not provided */
615 if (subcommands && !usagestr[0]) {
618 astrcatf(&buf, "%s %s [<options>] {", subcmd_config.exec_name, argv[0]);
620 for (int i = 0; subcommands[i]; i++) {
623 astrcat(&buf, subcommands[i]);
630 parse_options_start(&ctx, argc, argv, flags);
631 switch (parse_options_step(&ctx, options, usagestr)) {
636 case PARSE_OPT_LIST_OPTS:
637 while (options->type != OPTION_END) {
638 if (options->long_name)
639 printf("--%s ", options->long_name);
644 case PARSE_OPT_LIST_SUBCMDS:
646 for (int i = 0; subcommands[i]; i++)
647 printf("%s ", subcommands[i]);
651 default: /* PARSE_OPT_UNKNOWN */
652 if (ctx.argv[0][1] == '-')
653 astrcatf(&error_buf, "unknown option `%s'",
656 astrcatf(&error_buf, "unknown switch `%c'", *ctx.opt);
657 usage_with_options(usagestr, options);
660 return parse_options_end(&ctx);
663 int parse_options(int argc, const char **argv, const struct option *options,
664 const char * const usagestr[], int flags)
666 return parse_options_subcommand(argc, argv, options, NULL,
667 (const char **) usagestr, flags);
670 #define USAGE_OPTS_WIDTH 24
673 static void print_option_help(const struct option *opts, int full)
678 if (opts->type == OPTION_GROUP) {
681 fprintf(stderr, "%s\n", opts->help);
684 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
686 if (opts->flags & PARSE_OPT_DISABLED)
689 pos = fprintf(stderr, " ");
690 if (opts->short_name)
691 pos += fprintf(stderr, "-%c", opts->short_name);
693 pos += fprintf(stderr, " ");
695 if (opts->long_name && opts->short_name)
696 pos += fprintf(stderr, ", ");
698 pos += fprintf(stderr, "--%s", opts->long_name);
700 switch (opts->type) {
701 case OPTION_ARGUMENT:
706 case OPTION_UINTEGER:
707 if (opts->flags & PARSE_OPT_OPTARG)
709 pos += fprintf(stderr, "[=<n>]");
711 pos += fprintf(stderr, "[<n>]");
713 pos += fprintf(stderr, " <n>");
715 case OPTION_CALLBACK:
716 if (opts->flags & PARSE_OPT_NOARG)
721 if (opts->flags & PARSE_OPT_OPTARG)
723 pos += fprintf(stderr, "[=<%s>]", opts->argh);
725 pos += fprintf(stderr, "[<%s>]", opts->argh);
727 pos += fprintf(stderr, " <%s>", opts->argh);
729 if (opts->flags & PARSE_OPT_OPTARG)
731 pos += fprintf(stderr, "[=...]");
733 pos += fprintf(stderr, "[...]");
735 pos += fprintf(stderr, " ...");
738 default: /* OPTION_{BIT,BOOLEAN,SET_UINT,SET_PTR} */
744 case OPTION_SET_UINT:
749 if (pos <= USAGE_OPTS_WIDTH)
750 pad = USAGE_OPTS_WIDTH - pos;
753 pad = USAGE_OPTS_WIDTH;
755 fprintf(stderr, "%*s%s\n", pad + USAGE_GAP, "", opts->help);
756 if (opts->flags & PARSE_OPT_NOBUILD)
757 fprintf(stderr, "%*s(not built-in because %s)\n",
758 USAGE_OPTS_WIDTH + USAGE_GAP, "",
762 static int option__cmp(const void *va, const void *vb)
764 const struct option *a = va, *b = vb;
765 int sa = tolower(a->short_name), sb = tolower(b->short_name), ret;
775 const char *la = a->long_name ?: "",
776 *lb = b->long_name ?: "";
777 ret = strcmp(la, lb);
783 static struct option *options__order(const struct option *opts)
785 int nr_opts = 0, len;
786 const struct option *o = opts;
787 struct option *ordered;
789 for (o = opts; o->type != OPTION_END; o++)
792 len = sizeof(*o) * (nr_opts + 1);
793 ordered = malloc(len);
796 memcpy(ordered, opts, len);
798 qsort(ordered, nr_opts, sizeof(*o), option__cmp);
803 static bool option__in_argv(const struct option *opt, const struct parse_opt_ctx_t *ctx)
807 for (i = 1; i < ctx->argc; ++i) {
808 const char *arg = ctx->argv[i];
811 if (arg[1] == '\0') {
812 if (arg[0] == opt->short_name)
817 if (opt->long_name && strcmp(opt->long_name, arg) == 0)
820 if (opt->help && strcasestr(opt->help, arg) != NULL)
826 if (arg[1] == opt->short_name ||
827 (arg[1] == '-' && opt->long_name && strcmp(opt->long_name, arg + 2) == 0))
834 static int usage_with_options_internal(const char * const *usagestr,
835 const struct option *opts, int full,
836 struct parse_opt_ctx_t *ctx)
838 struct option *ordered;
841 return PARSE_OPT_HELP;
846 fprintf(stderr, " Error: %s\n", error_buf);
850 fprintf(stderr, "\n Usage: %s\n", *usagestr++);
851 while (*usagestr && **usagestr)
852 fprintf(stderr, " or: %s\n", *usagestr++);
854 fprintf(stderr, "%s%s\n",
855 **usagestr ? " " : "",
860 if (opts->type != OPTION_GROUP)
863 ordered = options__order(opts);
867 for ( ; opts->type != OPTION_END; opts++) {
868 if (ctx && ctx->argc > 1 && !option__in_argv(opts, ctx))
870 print_option_help(opts, full);
877 return PARSE_OPT_HELP;
880 void usage_with_options(const char * const *usagestr,
881 const struct option *opts)
883 usage_with_options_internal(usagestr, opts, 0, NULL);
887 void usage_with_options_msg(const char * const *usagestr,
888 const struct option *opts, const char *fmt, ...)
891 char *tmp = error_buf;
894 if (vasprintf(&error_buf, fmt, ap) == -1)
895 die("vasprintf failed");
900 usage_with_options_internal(usagestr, opts, 0, NULL);
904 int parse_options_usage(const char * const *usagestr,
905 const struct option *opts,
906 const char *optstr, bool short_opt)
911 fprintf(stderr, "\n Usage: %s\n", *usagestr++);
912 while (*usagestr && **usagestr)
913 fprintf(stderr, " or: %s\n", *usagestr++);
915 fprintf(stderr, "%s%s\n",
916 **usagestr ? " " : "",
923 for ( ; opts->type != OPTION_END; opts++) {
925 if (opts->short_name == *optstr) {
926 print_option_help(opts, 0);
932 if (opts->long_name == NULL)
935 if (!prefixcmp(opts->long_name, optstr))
936 print_option_help(opts, 0);
937 if (!prefixcmp("no-", optstr) &&
938 !prefixcmp(opts->long_name, optstr + 3))
939 print_option_help(opts, 0);
942 return PARSE_OPT_HELP;
946 int parse_opt_verbosity_cb(const struct option *opt,
947 const char *arg __maybe_unused,
950 int *target = opt->value;
953 /* --no-quiet, --no-verbose */
955 else if (opt->short_name == 'v') {
969 static struct option *
970 find_option(struct option *opts, int shortopt, const char *longopt)
972 for (; opts->type != OPTION_END; opts++) {
973 if ((shortopt && opts->short_name == shortopt) ||
974 (opts->long_name && longopt &&
975 !strcmp(opts->long_name, longopt)))
981 void set_option_flag(struct option *opts, int shortopt, const char *longopt,
984 struct option *opt = find_option(opts, shortopt, longopt);
991 void set_option_nobuild(struct option *opts, int shortopt,
993 const char *build_opt,
996 struct option *opt = find_option(opts, shortopt, longopt);
1001 opt->flags |= PARSE_OPT_NOBUILD;
1002 opt->flags |= can_skip ? PARSE_OPT_CANSKIP : 0;
1003 opt->build_opt = build_opt;