parse-options: add support for parsing subcommands

Several Git commands have subcommands to implement mutually exclusive "operation modes", and they usually parse their subcommand argument with a bunch of if-else if statements. Teach parse-options to handle subcommands as well, which will result in shorter and simpler code with consistent error handling and error messages on unknown or missing subcommand, and it will also make possible for our Bash completion script to handle subcommands programmatically. The approach is guided by the following observations: - Most subcommands [1] are implemented in dedicated functions, and most of those functions [2] either have a signature matching the 'int cmd_foo(int argc, const char **argc, const char *prefix)' signature of builtin commands or can be trivially converted to that signature, because they miss only that last prefix parameter or have no parameters at all. - Subcommand arguments only have long form, and they have no double dash prefix, no negated form, and no description, and they don't take any arguments, and can't be abbreviated. - There must be exactly one subcommand among the arguments, or zero if the command has a default operation mode. - All arguments following the subcommand are considered to be arguments of the subcommand, and, conversely, arguments meant for the subcommand may not preceed the subcommand. So in the end subcommand declaration and parsing would look something like this: parse_opt_subcommand_fn *fn = NULL; struct option builtin_commit_graph_options[] = { OPT_STRING(0, "object-dir", &opts.obj_dir, N_("dir"), N_("the object directory to store the graph")), OPT_SUBCOMMAND("verify", &fn, graph_verify), OPT_SUBCOMMAND("write", &fn, graph_write), OPT_END(), }; argc = parse_options(argc, argv, prefix, options, builtin_commit_graph_usage, 0); return fn(argc, argv, prefix); Here each OPT_SUBCOMMAND specifies the name of the subcommand and the function implementing it, and the address of the same 'fn' subcommand function pointer. parse_options() then processes the arguments until it finds the first argument matching one of the subcommands, sets 'fn' to the function associated with that subcommand, and returns, leaving the rest of the arguments unprocessed. If none of the listed subcommands is found among the arguments, parse_options() will show usage and abort. If a command has a default operation mode, 'fn' should be initialized to the function implementing that mode, and parse_options() should be invoked with the PARSE_OPT_SUBCOMMAND_OPTIONAL flag. In this case parse_options() won't error out when not finding any subcommands, but will return leaving 'fn' unchanged. Note that if that default operation mode has any --options, then the PARSE_OPT_KEEP_UNKNOWN_OPT flag is necessary as well (otherwise parse_options() would error out upon seeing the unknown option meant to the default operation mode). Some thoughts about the implementation: - The same pointer to 'fn' must be specified as 'value' for each OPT_SUBCOMMAND, because there can be only one set of mutually exclusive subcommands; parse_options() will BUG() otherwise. There are other ways to tell parse_options() where to put the function associated with the subcommand given on the command line, but I didn't like them: - Change parse_options()'s signature by adding a pointer to subcommand function to be set to the function associated with the given subcommand, affecting all callsites, even those that don't have subcommands. - Introduce a specific parse_options_and_subcommand() variant with that extra funcion parameter. - I decided against automatically calling the subcommand function from within parse_options(), because: - There are commands that have to perform additional actions after option parsing but before calling the function implementing the specified subcommand. - The return code of the subcommand is usually the return code of the git command, but preserving the return code of the automatically called subcommand function would have made the API awkward. - Also add a OPT_SUBCOMMAND_F() variant to allow specifying an option flag: we have two subcommands that are purposefully excluded from completion ('git remote rm' and 'git stash save'), so they'll have to be specified with the PARSE_OPT_NOCOMPLETE flag. - Some of the 'parse_opt_flags' don't make sense with subcommands, and using them is probably just an oversight or misunderstanding. Therefore parse_options() will BUG() when invoked with any of the following flags while the options array contains at least one OPT_SUBCOMMAND: - PARSE_OPT_KEEP_DASHDASH: parse_options() stops parsing arguments when encountering a "--" argument, so it doesn't make sense to expect and keep one before a subcommand, because it would prevent the parsing of the subcommand. However, this flag is allowed in combination with the PARSE_OPT_SUBCOMMAND_OPTIONAL flag, because the double dash might be meaningful for the command's default operation mode, e.g. to disambiguate refs and pathspecs. - PARSE_OPT_STOP_AT_NON_OPTION: As its name suggests, this flag tells parse_options() to stop as soon as it encouners a non-option argument, but subcommands are by definition not options... so how could they be parsed, then?! - PARSE_OPT_KEEP_UNKNOWN: This flag can be used to collect any unknown --options and then pass them to a different command or subsystem. Surely if a command has subcommands, then this functionality should rather be delegated to one of those subcommands, and not performed by the command itself. However, this flag is allowed in combination with the PARSE_OPT_SUBCOMMAND_OPTIONAL flag, making possible to pass --options to the default operation mode. - If the command with subcommands has a default operation mode, then all arguments to the command must preceed the arguments of the subcommand. AFAICT we don't have any commands where this makes a difference, because in those commands either only the command accepts any arguments ('notes' and 'remote'), or only the default subcommand ('reflog' and 'stash'), but never both. - The 'argv' array passed to subcommand functions currently starts with the name of the subcommand. Keep this behavior. AFAICT no subcommand functions depend on the actual content of 'argv[0]', but the parse_options() call handling their options expects that the options start at argv[1]. - To support handling subcommands programmatically in our Bash completion script, 'git cmd --git-completion-helper' will now list both subcommands and regular --options, if any. This means that the completion script will have to separate subcommands (i.e. words without a double dash prefix) from --options on its own, but that's rather easy to do, and it's not much work either, because the number of subcommands a command might have is rather low, and those commands accept only a single --option or none at all. An alternative would be to introduce a separate option that lists only subcommands, but then the completion script would need not one but two git invocations and command substitutions for commands with subcommands. Note that this change doesn't affect the behavior of our Bash completion script, because when completing the --option of a command with subcommands, e.g. for 'git notes --<TAB>', then all subcommands will be filtered out anyway, as none of them will match the word to be completed starting with that double dash prefix. [1] Except 'git rerere', because many of its subcommands are implemented in the bodies of the if-else if statements parsing the command's subcommand argument. [2] Except 'credential', 'credential-store' and 'fsmonitor--daemon', because some of the functions implementing their subcommands take special parameters. Signed-off-by: SZEDER Gábor <szeder.dev@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

SZEDER Gábor committed Aug 19, 2022 at 18:04 UTC fa83cc834dad896e1a48cdea588e690692690b69
9 files changed +419 -9
Documentation/technical/api-parse-options.txt
+40 -1
@@ -8,7 +8,8 @@ Basics
8 ------
9
10 The argument vector `argv[]` may usually contain mandatory or optional
11 -'non-option arguments', e.g. a filename or a branch, and 'options'.
11 +'non-option arguments', e.g. a filename or a branch, 'options', and
12 +'subcommands'.
13 Options are optional arguments that start with a dash and
14 that allow to change the behavior of a command.
15
@@ -48,6 +49,33 @@ The parse-options API allows:
49 option, e.g. `-a -b --option -- --this-is-a-file` indicates that
50 `--this-is-a-file` must not be processed as an option.
51
52 +Subcommands are special in a couple of ways:
53 +
54 +* Subcommands only have long form, and they have no double dash prefix, no
55 + negated form, and no description, and they don't take any arguments, and
56 + can't be abbreviated.
57 +
58 +* There must be exactly one subcommand among the arguments, or zero if the
59 + command has a default operation mode.
60 +
61 +* All arguments following the subcommand are considered to be arguments of
62 + the subcommand, and, conversely, arguments meant for the subcommand may
63 + not preceed the subcommand.
64 +
65 +Therefore, if the options array contains at least one subcommand and
66 +`parse_options()` encounters the first dashless argument, it will either:
67 +
68 +* stop and return, if that dashless argument is a known subcommand, setting
69 + `value` to the function pointer associated with that subcommand, storing
70 + the name of the subcommand in argv[0], and leaving the rest of the
71 + arguments unprocessed, or
72 +
73 +* stop and return, if it was invoked with the `PARSE_OPT_SUBCOMMAND_OPTIONAL`
74 + flag and that dashless argument doesn't match any subcommands, leaving
75 + `value` unchanged and the rest of the arguments unprocessed, or
76 +
77 +* show error and usage, and abort.
78 +
79 Steps to parse options
80 ----------------------
81
@@ -110,6 +138,13 @@ Flags are the bitwise-or of:
138 turns it off and allows one to add custom handlers for these
139 options, or to just leave them unknown.
140
141 +`PARSE_OPT_SUBCOMMAND_OPTIONAL`::
142 + Don't error out when no subcommand is specified.
143 +
144 +Note that `PARSE_OPT_STOP_AT_NON_OPTION` is incompatible with subcommands;
145 +while `PARSE_OPT_KEEP_DASHDASH` and `PARSE_OPT_KEEP_UNKNOWN_OPT` can only be
146 +used with subcommands when combined with `PARSE_OPT_SUBCOMMAND_OPTIONAL`.
147 +
148 Data Structure
149 --------------
150
@@ -241,7 +276,11 @@ There are some macros to easily define options:
276 can be given by the user. `int_var` is set to `enum_val` when the
277 option is used, but an error is reported if other "operating mode"
278 option has already set its value to the same `int_var`.
279 + In new commands consider using subcommands instead.
280
281 +`OPT_SUBCOMMAND(long, &fn_ptr, subcommand_fn)`::
282 + Define a subcommand. `subcommand_fn` is put into `fn_ptr` when
283 + this subcommand is used.
284
285 The last element of the array must be `OPT_END()`.
286
builtin/blame.c
+1
@@ -920,6 +920,7 @@ int cmd_blame(int argc, const char **argv, const char *prefix)
920 break;
921 case PARSE_OPT_HELP:
922 case PARSE_OPT_ERROR:
923 + case PARSE_OPT_SUBCOMMAND:
924 exit(129);
925 case PARSE_OPT_COMPLETE:
926 exit(0);
builtin/shortlog.c
+1
@@ -381,6 +381,7 @@ int cmd_shortlog(int argc, const char **argv, const char *prefix)
381 break;
382 case PARSE_OPT_HELP:
383 case PARSE_OPT_ERROR:
384 + case PARSE_OPT_SUBCOMMAND:
385 exit(129);
386 case PARSE_OPT_COMPLETE:
387 exit(0);
parse-options.c
+107 -6
@@ -324,6 +324,8 @@ static enum parse_opt_result parse_long_opt(
324 const char *rest, *long_name = options->long_name;
325 enum opt_parsed flags = OPT_LONG, opt_flags = OPT_LONG;
326
327 + if (options->type == OPTION_SUBCOMMAND)
328 + continue;
329 if (!long_name)
330 continue;
331
@@ -419,6 +421,19 @@ static enum parse_opt_result parse_nodash_opt(struct parse_opt_ctx_t *p,
421 return PARSE_OPT_ERROR;
422 }
423
424 +static enum parse_opt_result parse_subcommand(const char *arg,
425 + const struct option *options)
426 +{
427 + for (; options->type != OPTION_END; options++)
428 + if (options->type == OPTION_SUBCOMMAND &&
429 + !strcmp(options->long_name, arg)) {
430 + *(parse_opt_subcommand_fn **)options->value = options->subcommand_fn;
431 + return PARSE_OPT_SUBCOMMAND;
432 + }
433 +
434 + return PARSE_OPT_UNKNOWN;
435 +}
436 +
437 static void check_typos(const char *arg, const struct option *options)
438 {
439 if (strlen(arg) < 3)
@@ -442,6 +457,7 @@ static void check_typos(const char *arg, const struct option *options)
457 static void parse_options_check(const struct option *opts)
458 {
459 char short_opts[128];
460 + void *subcommand_value = NULL;
461
462 memset(short_opts, '\0', sizeof(short_opts));
463 for (; opts->type != OPTION_END; opts++) {
@@ -489,6 +505,14 @@ static void parse_options_check(const struct option *opts)
505 "Are you using parse_options_step() directly?\n"
506 "That case is not supported yet.");
507 break;
508 + case OPTION_SUBCOMMAND:
509 + if (!opts->value || !opts->subcommand_fn)
510 + optbug(opts, "OPTION_SUBCOMMAND needs a value and a subcommand function");
511 + if (!subcommand_value)
512 + subcommand_value = opts->value;
513 + else if (subcommand_value != opts->value)
514 + optbug(opts, "all OPTION_SUBCOMMANDs need the same value");
515 + break;
516 default:
517 ; /* ok. (usually accepts an argument) */
518 }
@@ -499,6 +523,14 @@ static void parse_options_check(const struct option *opts)
523 BUG_if_bug("invalid 'struct option'");
524 }
525
526 +static int has_subcommands(const struct option *options)
527 +{
528 + for (; options->type != OPTION_END; options++)
529 + if (options->type == OPTION_SUBCOMMAND)
530 + return 1;
531 + return 0;
532 +}
533 +
534 static void parse_options_start_1(struct parse_opt_ctx_t *ctx,
535 int argc, const char **argv, const char *prefix,
536 const struct option *options,
@@ -515,6 +547,19 @@ static void parse_options_start_1(struct parse_opt_ctx_t *ctx,
547 ctx->prefix = prefix;
548 ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
549 ctx->flags = flags;
550 + ctx->has_subcommands = has_subcommands(options);
551 + if (!ctx->has_subcommands && (flags & PARSE_OPT_SUBCOMMAND_OPTIONAL))
552 + BUG("Using PARSE_OPT_SUBCOMMAND_OPTIONAL without subcommands");
553 + if (ctx->has_subcommands) {
554 + if (flags & PARSE_OPT_STOP_AT_NON_OPTION)
555 + BUG("subcommands are incompatible with PARSE_OPT_STOP_AT_NON_OPTION");
556 + if (!(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
557 + if (flags & PARSE_OPT_KEEP_UNKNOWN_OPT)
558 + BUG("subcommands are incompatible with PARSE_OPT_KEEP_UNKNOWN_OPT unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
559 + if (flags & PARSE_OPT_KEEP_DASHDASH)
560 + BUG("subcommands are incompatible with PARSE_OPT_KEEP_DASHDASH unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
561 + }
562 + }
563 if ((flags & PARSE_OPT_KEEP_UNKNOWN_OPT) &&
564 (flags & PARSE_OPT_STOP_AT_NON_OPTION) &&
565 !(flags & PARSE_OPT_ONE_SHOT))
@@ -589,6 +634,7 @@ static int show_gitcomp(const struct option *opts, int show_all)
634 int nr_noopts = 0;
635
636 for (; opts->type != OPTION_END; opts++) {
637 + const char *prefix = "--";
638 const char *suffix = "";
639
640 if (!opts->long_name)
@@ -598,6 +644,9 @@ static int show_gitcomp(const struct option *opts, int show_all)
644 continue;
645
646 switch (opts->type) {
647 + case OPTION_SUBCOMMAND:
648 + prefix = "";
649 + break;
650 case OPTION_GROUP:
651 continue;
652 case OPTION_STRING:
@@ -620,8 +669,8 @@ static int show_gitcomp(const struct option *opts, int show_all)
669 suffix = "=";
670 if (starts_with(opts->long_name, "no-"))
671 nr_noopts++;
623 - printf("%s--%s%s", opts == original_opts ? "" : " ",
624 - opts->long_name, suffix);
672 + printf("%s%s%s%s", opts == original_opts ? "" : " ",
673 + prefix, opts->long_name, suffix);
674 }
675 show_negated_gitcomp(original_opts, show_all, -1);
676 show_negated_gitcomp(original_opts, show_all, nr_noopts);
@@ -744,10 +793,38 @@ enum parse_opt_result parse_options_step(struct parse_opt_ctx_t *ctx,
793 if (*arg != '-' || !arg[1]) {
794 if (parse_nodash_opt(ctx, arg, options) == 0)
795 continue;
747 - if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
748 - return PARSE_OPT_NON_OPTION;
749 - ctx->out[ctx->cpidx++] = ctx->argv[0];
750 - continue;
796 + if (!ctx->has_subcommands) {
797 + if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
798 + return PARSE_OPT_NON_OPTION;
799 + ctx->out[ctx->cpidx++] = ctx->argv[0];
800 + continue;
801 + }
802 + switch (parse_subcommand(arg, options)) {
803 + case PARSE_OPT_SUBCOMMAND:
804 + return PARSE_OPT_SUBCOMMAND;
805 + case PARSE_OPT_UNKNOWN:
806 + if (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)
807 + /*
808 + * arg is neither a short or long
809 + * option nor a subcommand. Since
810 + * this command has a default
811 + * operation mode, we have to treat
812 + * this arg and all remaining args
813 + * as args meant to that default
814 + * operation mode.
815 + * So we are done parsing.
816 + */
817 + return PARSE_OPT_DONE;
818 + error(_("unknown subcommand: `%s'"), arg);
819 + usage_with_options(usagestr, options);
820 + case PARSE_OPT_COMPLETE:
821 + case PARSE_OPT_HELP:
822 + case PARSE_OPT_ERROR:
823 + case PARSE_OPT_DONE:
824 + case PARSE_OPT_NON_OPTION:
825 + /* Impossible. */
826 + BUG("parse_subcommand() cannot return these");
827 + }
828 }
829
830 /* lone -h asks for help */
@@ -775,6 +852,7 @@ enum parse_opt_result parse_options_step(struct parse_opt_ctx_t *ctx,
852 goto show_usage;
853 goto unknown;
854 case PARSE_OPT_NON_OPTION:
855 + case PARSE_OPT_SUBCOMMAND:
856 case PARSE_OPT_HELP:
857 case PARSE_OPT_COMPLETE:
858 BUG("parse_short_opt() cannot return these");
@@ -800,6 +878,7 @@ enum parse_opt_result parse_options_step(struct parse_opt_ctx_t *ctx,
878 *(char *)ctx->argv[0] = '-';
879 goto unknown;
880 case PARSE_OPT_NON_OPTION:
881 + case PARSE_OPT_SUBCOMMAND:
882 case PARSE_OPT_COMPLETE:
883 case PARSE_OPT_HELP:
884 BUG("parse_short_opt() cannot return these");
@@ -831,6 +910,7 @@ enum parse_opt_result parse_options_step(struct parse_opt_ctx_t *ctx,
910 case PARSE_OPT_HELP:
911 goto show_usage;
912 case PARSE_OPT_NON_OPTION:
913 + case PARSE_OPT_SUBCOMMAND:
914 case PARSE_OPT_COMPLETE:
915 BUG("parse_long_opt() cannot return these");
916 case PARSE_OPT_DONE:
@@ -840,6 +920,18 @@ enum parse_opt_result parse_options_step(struct parse_opt_ctx_t *ctx,
920 unknown:
921 if (ctx->flags & PARSE_OPT_ONE_SHOT)
922 break;
923 + if (ctx->has_subcommands &&
924 + (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL) &&
925 + (ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)) {
926 + /*
927 + * Found an unknown option given to a command with
928 + * subcommands that has a default operation mode:
929 + * we treat this option and all remaining args as
930 + * arguments meant to that default operation mode.
931 + * So we are done parsing.
932 + */
933 + return PARSE_OPT_DONE;
934 + }
935 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT))
936 return PARSE_OPT_UNKNOWN;
937 ctx->out[ctx->cpidx++] = ctx->argv[0];
@@ -885,7 +977,14 @@ int parse_options(int argc, const char **argv,
977 case PARSE_OPT_COMPLETE:
978 exit(0);
979 case PARSE_OPT_NON_OPTION:
980 + case PARSE_OPT_SUBCOMMAND:
981 + break;
982 case PARSE_OPT_DONE:
983 + if (ctx.has_subcommands &&
984 + !(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
985 + error(_("need a subcommand"));
986 + usage_with_options(usagestr, options);
987 + }
988 break;
989 case PARSE_OPT_UNKNOWN:
990 if (ctx.argv[0][1] == '-') {
@@ -1010,6 +1109,8 @@ static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t
1109 size_t pos;
1110 int pad;
1111
1112 + if (opts->type == OPTION_SUBCOMMAND)
1113 + continue;
1114 if (opts->type == OPTION_GROUP) {
1115 fputc('\n', outfile);
1116 need_newline = 0;
parse-options.h
+22 -2
@@ -11,6 +11,7 @@ enum parse_opt_type {
11 OPTION_GROUP,
12 OPTION_NUMBER,
13 OPTION_ALIAS,
14 + OPTION_SUBCOMMAND,
15 /* options with no arguments */
16 OPTION_BIT,
17 OPTION_NEGBIT,
@@ -34,6 +35,7 @@ enum parse_opt_flags {
35 PARSE_OPT_NO_INTERNAL_HELP = 1 << 4,
36 PARSE_OPT_ONE_SHOT = 1 << 5,
37 PARSE_OPT_SHELL_EVAL = 1 << 6,
38 + PARSE_OPT_SUBCOMMAND_OPTIONAL = 1 << 7,
39 };
40
41 enum parse_opt_option_flags {
@@ -56,6 +58,7 @@ enum parse_opt_result {
58 PARSE_OPT_ERROR = -1, /* must be the same as error() */
59 PARSE_OPT_DONE = 0, /* fixed so that "return 0" works */
60 PARSE_OPT_NON_OPTION,
61 + PARSE_OPT_SUBCOMMAND,
62 PARSE_OPT_UNKNOWN
63 };
64
@@ -67,6 +70,9 @@ typedef enum parse_opt_result parse_opt_ll_cb(struct parse_opt_ctx_t *ctx,
70 const struct option *opt,
71 const char *arg, int unset);
72
73 +typedef int parse_opt_subcommand_fn(int argc, const char **argv,
74 + const char *prefix);
75 +
76 /*
77 * `type`::
78 * holds the type of the option, you must have an OPTION_END last in your
@@ -76,7 +82,8 @@ typedef enum parse_opt_result parse_opt_ll_cb(struct parse_opt_ctx_t *ctx,
82 * the character to use as a short option name, '\0' if none.
83 *
84 * `long_name`::
79 - * the long option name, without the leading dashes, NULL if none.
85 + * the long option (without the leading dashes) or subcommand name,
86 + * NULL if none.
87 *
88 * `value`::
89 * stores pointers to the values to be filled.
@@ -93,7 +100,7 @@ typedef enum parse_opt_result parse_opt_ll_cb(struct parse_opt_ctx_t *ctx,
100 *
101 * `help`::
102 * the short help associated to what the option does.
96 - * Must never be NULL (except for OPTION_END).
103 + * Must never be NULL (except for OPTION_END and OPTION_SUBCOMMAND).
104 * OPTION_GROUP uses this pointer to store the group header.
105 * Should be wrapped by N_() for translation.
106 *
@@ -131,6 +138,9 @@ typedef enum parse_opt_result parse_opt_ll_cb(struct parse_opt_ctx_t *ctx,
138 * `ll_callback`::
139 * pointer to the callback to use for OPTION_LOWLEVEL_CALLBACK
140 *
141 + * `subcommand_fn`::
142 + * pointer to a function to use for OPTION_SUBCOMMAND.
143 + * It will be put in value when the subcommand is given on the command line.
144 */
145 struct option {
146 enum parse_opt_type type;
@@ -145,6 +155,7 @@ struct option {
155 intptr_t defval;
156 parse_opt_ll_cb *ll_callback;
157 intptr_t extra;
158 + parse_opt_subcommand_fn *subcommand_fn;
159 };
160
161 #define OPT_BIT_F(s, l, v, h, b, f) { OPTION_BIT, (s), (l), (v), NULL, (h), \
@@ -206,6 +217,14 @@ struct option {
217 #define OPT_ALIAS(s, l, source_long_name) \
218 { OPTION_ALIAS, (s), (l), (source_long_name) }
219
220 +#define OPT_SUBCOMMAND_F(l, v, fn, f) { \
221 + .type = OPTION_SUBCOMMAND, \
222 + .long_name = (l), \
223 + .value = (v), \
224 + .flags = (f), \
225 + .subcommand_fn = (fn) }
226 +#define OPT_SUBCOMMAND(l, v, fn) OPT_SUBCOMMAND_F((l), (v), (fn), 0)
227 +
228 /*
229 * parse_options() will filter out the processed options and leave the
230 * non-option arguments in argv[]. argv0 is assumed program name and
@@ -295,6 +314,7 @@ struct parse_opt_ctx_t {
314 int argc, cpidx, total;
315 const char *opt;
316 enum parse_opt_flags flags;
317 + unsigned has_subcommands;
318 const char *prefix;
319 const char **alias_groups; /* must be in groups of 3 elements! */
320 struct option *updated_options;
t/helper/test-parse-options.c
+61
@@ -238,6 +238,9 @@ static const struct option test_flag_options[] = {
238 OPT_BIT(0, "no-internal-help", &test_flags,
239 "pass PARSE_OPT_NO_INTERNAL_HELP to parse_options()",
240 PARSE_OPT_NO_INTERNAL_HELP),
241 + OPT_BIT(0, "subcommand-optional", &test_flags,
242 + "pass PARSE_OPT_SUBCOMMAND_OPTIONAL to parse_options()",
243 + PARSE_OPT_SUBCOMMAND_OPTIONAL),
244 OPT_END()
245 };
246
@@ -258,3 +261,61 @@ int cmd__parse_options_flags(int argc, const char **argv)
261
262 return parse_options_flags__cmd(argc, argv, test_flags);
263 }
264 +
265 +static int subcmd_one(int argc, const char **argv, const char *prefix)
266 +{
267 + printf("fn: subcmd_one\n");
268 + print_args(argc, argv);
269 + return 0;
270 +}
271 +
272 +static int subcmd_two(int argc, const char **argv, const char *prefix)
273 +{
274 + printf("fn: subcmd_two\n");
275 + print_args(argc, argv);
276 + return 0;
277 +}
278 +
279 +static int parse_subcommand__cmd(int argc, const char **argv,
280 + enum parse_opt_flags test_flags)
281 +{
282 + const char *usage[] = {
283 + "<...> cmd subcmd-one",
284 + "<...> cmd subcmd-two",
285 + NULL
286 + };
287 + parse_opt_subcommand_fn *fn = NULL;
288 + int opt = 0;
289 + struct option options[] = {
290 + OPT_SUBCOMMAND("subcmd-one", &fn, subcmd_one),
291 + OPT_SUBCOMMAND("subcmd-two", &fn, subcmd_two),
292 + OPT_INTEGER('o', "opt", &opt, "an integer option"),
293 + OPT_END()
294 + };
295 +
296 + if (test_flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)
297 + fn = subcmd_one;
298 + argc = parse_options(argc, argv, NULL, options, usage, test_flags);
299 +
300 + printf("opt: %d\n", opt);
301 +
302 + return fn(argc, argv, NULL);
303 +}
304 +
305 +int cmd__parse_subcommand(int argc, const char **argv)
306 +{
307 + const char *usage[] = {
308 + "test-tool parse-subcommand [flag-options] cmd <subcommand>",
309 + NULL
310 + };
311 +
312 + argc = parse_options(argc, argv, NULL, test_flag_options, usage,
313 + PARSE_OPT_STOP_AT_NON_OPTION);
314 +
315 + if (argc == 0 || strcmp(argv[0], "cmd")) {
316 + error("'cmd' is mandatory");
317 + usage_with_options(usage, test_flag_options);
318 + }
319 +
320 + return parse_subcommand__cmd(argc, argv, test_flags);
321 +}
t/helper/test-tool.c
+1
@@ -53,6 +53,7 @@ static struct test_cmd cmds[] = {
53 { "parse-options", cmd__parse_options },
54 { "parse-options-flags", cmd__parse_options_flags },
55 { "parse-pathspec-file", cmd__parse_pathspec_file },
56 + { "parse-subcommand", cmd__parse_subcommand },
57 { "partial-clone", cmd__partial_clone },
58 { "path-utils", cmd__path_utils },
59 { "pcre2-config", cmd__pcre2_config },
t/helper/test-tool.h
+1
@@ -43,6 +43,7 @@ int cmd__pack_mtimes(int argc, const char **argv);
43 int cmd__parse_options(int argc, const char **argv);
44 int cmd__parse_options_flags(int argc, const char **argv);
45 int cmd__parse_pathspec_file(int argc, const char** argv);
46 +int cmd__parse_subcommand(int argc, const char **argv);
47 int cmd__partial_clone(int argc, const char **argv);
48 int cmd__path_utils(int argc, const char **argv);
49 int cmd__pcre2_config(int argc, const char **argv);
t/t0040-parse-options.sh
+185
@@ -526,4 +526,189 @@ test_expect_success 'KEEP_UNKNOWN_OPT | NO_INTERNAL_HELP works' '
526 test_cmp expect actual
527 '
528
529 +test_expect_success 'subcommand - no subcommand shows error and usage' '
530 + test_expect_code 129 test-tool parse-subcommand cmd 2>err &&
531 + grep "^error: need a subcommand" err &&
532 + grep ^usage: err
533 +'
534 +
535 +test_expect_success 'subcommand - subcommand after -- shows error and usage' '
536 + test_expect_code 129 test-tool parse-subcommand cmd -- subcmd-one 2>err &&
537 + grep "^error: need a subcommand" err &&
538 + grep ^usage: err
539 +'
540 +
541 +test_expect_success 'subcommand - subcommand after --end-of-options shows error and usage' '
542 + test_expect_code 129 test-tool parse-subcommand cmd --end-of-options subcmd-one 2>err &&
543 + grep "^error: need a subcommand" err &&
544 + grep ^usage: err
545 +'
546 +
547 +test_expect_success 'subcommand - unknown subcommand shows error and usage' '
548 + test_expect_code 129 test-tool parse-subcommand cmd nope 2>err &&
549 + grep "^error: unknown subcommand: \`nope$SQ" err &&
550 + grep ^usage: err
551 +'
552 +
553 +test_expect_success 'subcommand - subcommands cannot be abbreviated' '
554 + test_expect_code 129 test-tool parse-subcommand cmd subcmd-o 2>err &&
555 + grep "^error: unknown subcommand: \`subcmd-o$SQ$" err &&
556 + grep ^usage: err
557 +'
558 +
559 +test_expect_success 'subcommand - no negated subcommands' '
560 + test_expect_code 129 test-tool parse-subcommand cmd no-subcmd-one 2>err &&
561 + grep "^error: unknown subcommand: \`no-subcmd-one$SQ" err &&
562 + grep ^usage: err
563 +'
564 +
565 +test_expect_success 'subcommand - simple' '
566 + test-tool parse-subcommand cmd subcmd-two >actual &&
567 + cat >expect <<-\EOF &&
568 + opt: 0
569 + fn: subcmd_two
570 + arg 00: subcmd-two
571 + EOF
572 + test_cmp expect actual
573 +'
574 +
575 +test_expect_success 'subcommand - stop parsing at the first subcommand' '
576 + test-tool parse-subcommand cmd --opt=1 subcmd-two subcmd-one --opt=2 >actual &&
577 + cat >expect <<-\EOF &&
578 + opt: 1
579 + fn: subcmd_two
580 + arg 00: subcmd-two
581 + arg 01: subcmd-one
582 + arg 02: --opt=2
583 + EOF
584 + test_cmp expect actual
585 +'
586 +
587 +test_expect_success 'subcommand - KEEP_ARGV0' '
588 + test-tool parse-subcommand --keep-argv0 cmd subcmd-two >actual &&
589 + cat >expect <<-\EOF &&
590 + opt: 0
591 + fn: subcmd_two
592 + arg 00: cmd
593 + arg 01: subcmd-two
594 + EOF
595 + test_cmp expect actual
596 +'
597 +
598 +test_expect_success 'subcommand - SUBCOMMAND_OPTIONAL + subcommand not given' '
599 + test-tool parse-subcommand --subcommand-optional cmd >actual &&
600 + cat >expect <<-\EOF &&
601 + opt: 0
602 + fn: subcmd_one
603 + EOF
604 + test_cmp expect actual
605 +'
606 +
607 +test_expect_success 'subcommand - SUBCOMMAND_OPTIONAL + given subcommand' '
608 + test-tool parse-subcommand --subcommand-optional cmd subcmd-two branch file >actual &&
609 + cat >expect <<-\EOF &&
610 + opt: 0
611 + fn: subcmd_two
612 + arg 00: subcmd-two
613 + arg 01: branch
614 + arg 02: file
615 + EOF
616 + test_cmp expect actual
617 +'
618 +
619 +test_expect_success 'subcommand - SUBCOMMAND_OPTIONAL + subcommand not given + unknown dashless args' '
620 + test-tool parse-subcommand --subcommand-optional cmd branch file >actual &&
621 + cat >expect <<-\EOF &&
622 + opt: 0
623 + fn: subcmd_one
624 + arg 00: branch
625 + arg 01: file
626 + EOF
627 + test_cmp expect actual
628 +'
629 +
630 +test_expect_success 'subcommand - SUBCOMMAND_OPTIONAL + subcommand not given + unknown option' '
631 + test_expect_code 129 test-tool parse-subcommand --subcommand-optional cmd --subcommand-opt 2>err &&
632 + grep "^error: unknown option" err &&
633 + grep ^usage: err
634 +'
635 +
636 +test_expect_success 'subcommand - SUBCOMMAND_OPTIONAL | KEEP_UNKNOWN_OPT + subcommand not given + unknown option' '
637 + test-tool parse-subcommand --subcommand-optional --keep-unknown-opt cmd --subcommand-opt >actual &&
638 + cat >expect <<-\EOF &&
639 + opt: 0
640 + fn: subcmd_one
641 + arg 00: --subcommand-opt
642 + EOF
643 + test_cmp expect actual
644 +'
645 +
646 +test_expect_success 'subcommand - SUBCOMMAND_OPTIONAL | KEEP_UNKNOWN_OPT + subcommand ignored after unknown option' '
647 + test-tool parse-subcommand --subcommand-optional --keep-unknown-opt cmd --subcommand-opt subcmd-two >actual &&
648 + cat >expect <<-\EOF &&
649 + opt: 0
650 + fn: subcmd_one
651 + arg 00: --subcommand-opt
652 + arg 01: subcmd-two
653 + EOF
654 + test_cmp expect actual
655 +'
656 +
657 +test_expect_success 'subcommand - SUBCOMMAND_OPTIONAL | KEEP_UNKNOWN_OPT + command and subcommand options cannot be mixed' '
658 + test-tool parse-subcommand --subcommand-optional --keep-unknown-opt cmd --subcommand-opt branch --opt=1 >actual &&
659 + cat >expect <<-\EOF &&
660 + opt: 0
661 + fn: subcmd_one
662 + arg 00: --subcommand-opt
663 + arg 01: branch
664 + arg 02: --opt=1
665 + EOF
666 + test_cmp expect actual
667 +'
668 +
669 +test_expect_success 'subcommand - SUBCOMMAND_OPTIONAL | KEEP_UNKNOWN_OPT | KEEP_ARGV0' '
670 + test-tool parse-subcommand --subcommand-optional --keep-unknown-opt --keep-argv0 cmd --subcommand-opt branch >actual &&
671 + cat >expect <<-\EOF &&
672 + opt: 0
673 + fn: subcmd_one
674 + arg 00: cmd
675 + arg 01: --subcommand-opt
676 + arg 02: branch
677 + EOF
678 + test_cmp expect actual
679 +'
680 +
681 +test_expect_success 'subcommand - SUBCOMMAND_OPTIONAL | KEEP_UNKNOWN_OPT | KEEP_DASHDASH' '
682 + test-tool parse-subcommand --subcommand-optional --keep-unknown-opt --keep-dashdash cmd -- --subcommand-opt file >actual &&
683 + cat >expect <<-\EOF &&
684 + opt: 0
685 + fn: subcmd_one
686 + arg 00: --
687 + arg 01: --subcommand-opt
688 + arg 02: file
689 + EOF
690 + test_cmp expect actual
691 +'
692 +
693 +test_expect_success 'subcommand - completion helper' '
694 + test-tool parse-subcommand cmd --git-completion-helper >actual &&
695 + echo "subcmd-one subcmd-two --opt= --no-opt" >expect &&
696 + test_cmp expect actual
697 +'
698 +
699 +test_expect_success 'subcommands are incompatible with STOP_AT_NON_OPTION' '
700 + test_must_fail test-tool parse-subcommand --stop-at-non-option cmd subcmd-one 2>err &&
701 + grep ^BUG err
702 +'
703 +
704 +test_expect_success 'subcommands are incompatible with KEEP_UNKNOWN_OPT unless in combination with SUBCOMMAND_OPTIONAL' '
705 + test_must_fail test-tool parse-subcommand --keep-unknown-opt cmd subcmd-two 2>err &&
706 + grep ^BUG err
707 +'
708 +
709 +test_expect_success 'subcommands are incompatible with KEEP_DASHDASH unless in combination with SUBCOMMAND_OPTIONAL' '
710 + test_must_fail test-tool parse-subcommand --keep-dashdash cmd subcmd-two 2>err &&
711 + grep ^BUG err
712 +'
713 +
714 test_done