parse-options: factor out register_abbrev() and struct parsed_option
[git.git] / parse-options.c
blob398ebaef1492f0fa4b645792633ca10fc6356325
1 #include "git-compat-util.h"
2 #include "parse-options.h"
3 #include "abspath.h"
4 #include "parse.h"
5 #include "gettext.h"
6 #include "strbuf.h"
7 #include "string-list.h"
8 #include "utf8.h"
10 static int disallow_abbreviated_options;
12 enum opt_parsed {
13 OPT_LONG = 0,
14 OPT_SHORT = 1<<0,
15 OPT_UNSET = 1<<1,
18 static void optbug(const struct option *opt, const char *reason)
20 if (opt->long_name && opt->short_name)
21 bug("switch '%c' (--%s) %s", opt->short_name,
22 opt->long_name, reason);
23 else if (opt->long_name)
24 bug("option '%s' %s", opt->long_name, reason);
25 else
26 bug("switch '%c' %s", opt->short_name, reason);
29 static const char *optname(const struct option *opt, enum opt_parsed flags)
31 static struct strbuf sb = STRBUF_INIT;
33 strbuf_reset(&sb);
34 if (flags & OPT_SHORT)
35 strbuf_addf(&sb, "switch `%c'", opt->short_name);
36 else if (flags & OPT_UNSET)
37 strbuf_addf(&sb, "option `no-%s'", opt->long_name);
38 else if (flags == OPT_LONG)
39 strbuf_addf(&sb, "option `%s'", opt->long_name);
40 else
41 BUG("optname() got unknown flags %d", flags);
43 return sb.buf;
46 static enum parse_opt_result get_arg(struct parse_opt_ctx_t *p,
47 const struct option *opt,
48 enum opt_parsed flags, const char **arg)
50 if (p->opt) {
51 *arg = p->opt;
52 p->opt = NULL;
53 } else if (p->argc == 1 && (opt->flags & PARSE_OPT_LASTARG_DEFAULT)) {
54 *arg = (const char *)opt->defval;
55 } else if (p->argc > 1) {
56 p->argc--;
57 *arg = *++p->argv;
58 } else
59 return error(_("%s requires a value"), optname(opt, flags));
60 return 0;
63 static void fix_filename(const char *prefix, char **file)
65 if (!file || !*file)
66 ; /* leave as NULL */
67 else
68 *file = prefix_filename_except_for_dash(prefix, *file);
71 static enum parse_opt_result do_get_value(struct parse_opt_ctx_t *p,
72 const struct option *opt,
73 enum opt_parsed flags,
74 const char **argp)
76 const char *s, *arg;
77 const int unset = flags & OPT_UNSET;
78 int err;
80 if (unset && p->opt)
81 return error(_("%s takes no value"), optname(opt, flags));
82 if (unset && (opt->flags & PARSE_OPT_NONEG))
83 return error(_("%s isn't available"), optname(opt, flags));
84 if (!(flags & OPT_SHORT) && p->opt && (opt->flags & PARSE_OPT_NOARG))
85 return error(_("%s takes no value"), optname(opt, flags));
87 switch (opt->type) {
88 case OPTION_LOWLEVEL_CALLBACK:
89 return opt->ll_callback(p, opt, NULL, unset);
91 case OPTION_BIT:
92 if (unset)
93 *(int *)opt->value &= ~opt->defval;
94 else
95 *(int *)opt->value |= opt->defval;
96 return 0;
98 case OPTION_NEGBIT:
99 if (unset)
100 *(int *)opt->value |= opt->defval;
101 else
102 *(int *)opt->value &= ~opt->defval;
103 return 0;
105 case OPTION_BITOP:
106 if (unset)
107 BUG("BITOP can't have unset form");
108 *(int *)opt->value &= ~opt->extra;
109 *(int *)opt->value |= opt->defval;
110 return 0;
112 case OPTION_COUNTUP:
113 if (*(int *)opt->value < 0)
114 *(int *)opt->value = 0;
115 *(int *)opt->value = unset ? 0 : *(int *)opt->value + 1;
116 return 0;
118 case OPTION_SET_INT:
119 *(int *)opt->value = unset ? 0 : opt->defval;
120 return 0;
122 case OPTION_STRING:
123 if (unset)
124 *(const char **)opt->value = NULL;
125 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
126 *(const char **)opt->value = (const char *)opt->defval;
127 else
128 return get_arg(p, opt, flags, (const char **)opt->value);
129 return 0;
131 case OPTION_FILENAME:
132 err = 0;
133 if (unset)
134 *(const char **)opt->value = NULL;
135 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
136 *(const char **)opt->value = (const char *)opt->defval;
137 else
138 err = get_arg(p, opt, flags, (const char **)opt->value);
140 if (!err)
141 fix_filename(p->prefix, (char **)opt->value);
142 return err;
144 case OPTION_CALLBACK:
146 const char *p_arg = NULL;
147 int p_unset;
149 if (unset)
150 p_unset = 1;
151 else if (opt->flags & PARSE_OPT_NOARG)
152 p_unset = 0;
153 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
154 p_unset = 0;
155 else if (get_arg(p, opt, flags, &arg))
156 return -1;
157 else {
158 p_unset = 0;
159 p_arg = arg;
161 if (opt->flags & PARSE_OPT_CMDMODE)
162 *argp = p_arg;
163 if (opt->callback)
164 return (*opt->callback)(opt, p_arg, p_unset) ? (-1) : 0;
165 else
166 return (*opt->ll_callback)(p, opt, p_arg, p_unset);
168 case OPTION_INTEGER:
169 if (unset) {
170 *(int *)opt->value = 0;
171 return 0;
173 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
174 *(int *)opt->value = opt->defval;
175 return 0;
177 if (get_arg(p, opt, flags, &arg))
178 return -1;
179 if (!*arg)
180 return error(_("%s expects a numerical value"),
181 optname(opt, flags));
182 *(int *)opt->value = strtol(arg, (char **)&s, 10);
183 if (*s)
184 return error(_("%s expects a numerical value"),
185 optname(opt, flags));
186 return 0;
188 case OPTION_MAGNITUDE:
189 if (unset) {
190 *(unsigned long *)opt->value = 0;
191 return 0;
193 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
194 *(unsigned long *)opt->value = opt->defval;
195 return 0;
197 if (get_arg(p, opt, flags, &arg))
198 return -1;
199 if (!git_parse_ulong(arg, opt->value))
200 return error(_("%s expects a non-negative integer value"
201 " with an optional k/m/g suffix"),
202 optname(opt, flags));
203 return 0;
205 default:
206 BUG("opt->type %d should not happen", opt->type);
210 struct parse_opt_cmdmode_list {
211 int value, *value_ptr;
212 const struct option *opt;
213 const char *arg;
214 enum opt_parsed flags;
215 struct parse_opt_cmdmode_list *next;
218 static void build_cmdmode_list(struct parse_opt_ctx_t *ctx,
219 const struct option *opts)
221 ctx->cmdmode_list = NULL;
223 for (; opts->type != OPTION_END; opts++) {
224 struct parse_opt_cmdmode_list *elem = ctx->cmdmode_list;
225 int *value_ptr = opts->value;
227 if (!(opts->flags & PARSE_OPT_CMDMODE) || !value_ptr)
228 continue;
230 while (elem && elem->value_ptr != value_ptr)
231 elem = elem->next;
232 if (elem)
233 continue;
235 CALLOC_ARRAY(elem, 1);
236 elem->value_ptr = value_ptr;
237 elem->value = *value_ptr;
238 elem->next = ctx->cmdmode_list;
239 ctx->cmdmode_list = elem;
243 static char *optnamearg(const struct option *opt, const char *arg,
244 enum opt_parsed flags)
246 if (flags & OPT_SHORT)
247 return xstrfmt("-%c%s", opt->short_name, arg ? arg : "");
248 return xstrfmt("--%s%s%s%s", flags & OPT_UNSET ? "no-" : "",
249 opt->long_name, arg ? "=" : "", arg ? arg : "");
252 static enum parse_opt_result get_value(struct parse_opt_ctx_t *p,
253 const struct option *opt,
254 enum opt_parsed flags)
256 const char *arg = NULL;
257 enum parse_opt_result result = do_get_value(p, opt, flags, &arg);
258 struct parse_opt_cmdmode_list *elem = p->cmdmode_list;
259 char *opt_name, *other_opt_name;
261 for (; elem; elem = elem->next) {
262 if (*elem->value_ptr == elem->value)
263 continue;
265 if (elem->opt &&
266 (elem->opt->flags | opt->flags) & PARSE_OPT_CMDMODE)
267 break;
269 elem->opt = opt;
270 elem->arg = arg;
271 elem->flags = flags;
272 elem->value = *elem->value_ptr;
275 if (result || !elem)
276 return result;
278 opt_name = optnamearg(opt, arg, flags);
279 other_opt_name = optnamearg(elem->opt, elem->arg, elem->flags);
280 error(_("options '%s' and '%s' cannot be used together"),
281 opt_name, other_opt_name);
282 free(opt_name);
283 free(other_opt_name);
284 return -1;
287 static enum parse_opt_result parse_short_opt(struct parse_opt_ctx_t *p,
288 const struct option *options)
290 const struct option *numopt = NULL;
292 for (; options->type != OPTION_END; options++) {
293 if (options->short_name == *p->opt) {
294 p->opt = p->opt[1] ? p->opt + 1 : NULL;
295 return get_value(p, options, OPT_SHORT);
299 * Handle the numerical option later, explicit one-digit
300 * options take precedence over it.
302 if (options->type == OPTION_NUMBER)
303 numopt = options;
305 if (numopt && isdigit(*p->opt)) {
306 size_t len = 1;
307 char *arg;
308 int rc;
310 while (isdigit(p->opt[len]))
311 len++;
312 arg = xmemdupz(p->opt, len);
313 p->opt = p->opt[len] ? p->opt + len : NULL;
314 if (numopt->callback)
315 rc = (*numopt->callback)(numopt, arg, 0) ? (-1) : 0;
316 else
317 rc = (*numopt->ll_callback)(p, numopt, arg, 0);
318 free(arg);
319 return rc;
321 return PARSE_OPT_UNKNOWN;
324 static int has_string(const char *it, const char **array)
326 while (*array)
327 if (!strcmp(it, *(array++)))
328 return 1;
329 return 0;
332 static int is_alias(struct parse_opt_ctx_t *ctx,
333 const struct option *one_opt,
334 const struct option *another_opt)
336 const char **group;
338 if (!ctx->alias_groups)
339 return 0;
341 if (!one_opt->long_name || !another_opt->long_name)
342 return 0;
344 for (group = ctx->alias_groups; *group; group += 3) {
345 /* it and other are from the same family? */
346 if (has_string(one_opt->long_name, group) &&
347 has_string(another_opt->long_name, group))
348 return 1;
350 return 0;
353 struct parsed_option {
354 const struct option *option;
355 enum opt_parsed flags;
358 static void register_abbrev(struct parse_opt_ctx_t *p,
359 const struct option *option, enum opt_parsed flags,
360 struct parsed_option *abbrev,
361 struct parsed_option *ambiguous)
363 if (p->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)
364 return;
365 if (abbrev->option &&
366 !is_alias(p, abbrev->option, option)) {
368 * If this is abbreviated, it is
369 * ambiguous. So when there is no
370 * exact match later, we need to
371 * error out.
373 ambiguous->option = abbrev->option;
374 ambiguous->flags = abbrev->flags;
376 abbrev->option = option;
377 abbrev->flags = flags;
380 static enum parse_opt_result parse_long_opt(
381 struct parse_opt_ctx_t *p, const char *arg,
382 const struct option *options)
384 const char *arg_end = strchrnul(arg, '=');
385 struct parsed_option abbrev = { .option = NULL, .flags = OPT_LONG };
386 struct parsed_option ambiguous = { .option = NULL, .flags = OPT_LONG };
388 for (; options->type != OPTION_END; options++) {
389 const char *rest, *long_name = options->long_name;
390 enum opt_parsed flags = OPT_LONG, opt_flags = OPT_LONG;
392 if (options->type == OPTION_SUBCOMMAND)
393 continue;
394 if (!long_name)
395 continue;
397 if (!starts_with(arg, "no-") &&
398 !(options->flags & PARSE_OPT_NONEG) &&
399 skip_prefix(long_name, "no-", &long_name))
400 opt_flags |= OPT_UNSET;
402 if (!skip_prefix(arg, long_name, &rest))
403 rest = NULL;
404 if (!rest) {
405 /* abbreviated? */
406 if (!strncmp(long_name, arg, arg_end - arg)) {
407 register_abbrev(p, options, flags ^ opt_flags,
408 &abbrev, &ambiguous);
409 continue;
411 /* negation allowed? */
412 if (options->flags & PARSE_OPT_NONEG)
413 continue;
414 /* negated and abbreviated very much? */
415 if (starts_with("no-", arg)) {
416 flags |= OPT_UNSET;
417 register_abbrev(p, options, flags ^ opt_flags,
418 &abbrev, &ambiguous);
419 continue;
421 /* negated? */
422 if (!starts_with(arg, "no-"))
423 continue;
424 flags |= OPT_UNSET;
425 if (!skip_prefix(arg + 3, long_name, &rest)) {
426 /* abbreviated and negated? */
427 if (!strncmp(long_name, arg + 3,
428 arg_end - arg - 3))
429 register_abbrev(p, options,
430 flags ^ opt_flags,
431 &abbrev, &ambiguous);
432 continue;
435 if (*rest) {
436 if (*rest != '=')
437 continue;
438 p->opt = rest + 1;
440 return get_value(p, options, flags ^ opt_flags);
443 if (disallow_abbreviated_options && (ambiguous.option || abbrev.option))
444 die("disallowed abbreviated or ambiguous option '%.*s'",
445 (int)(arg_end - arg), arg);
447 if (ambiguous.option) {
448 error(_("ambiguous option: %s "
449 "(could be --%s%s or --%s%s)"),
450 arg,
451 (ambiguous.flags & OPT_UNSET) ? "no-" : "",
452 ambiguous.option->long_name,
453 (abbrev.flags & OPT_UNSET) ? "no-" : "",
454 abbrev.option->long_name);
455 return PARSE_OPT_HELP;
457 if (abbrev.option) {
458 if (*arg_end)
459 p->opt = arg_end + 1;
460 return get_value(p, abbrev.option, abbrev.flags);
462 return PARSE_OPT_UNKNOWN;
465 static enum parse_opt_result parse_nodash_opt(struct parse_opt_ctx_t *p,
466 const char *arg,
467 const struct option *options)
469 for (; options->type != OPTION_END; options++) {
470 if (!(options->flags & PARSE_OPT_NODASH))
471 continue;
472 if (options->short_name == arg[0] && arg[1] == '\0')
473 return get_value(p, options, OPT_SHORT);
475 return PARSE_OPT_ERROR;
478 static enum parse_opt_result parse_subcommand(const char *arg,
479 const struct option *options)
481 for (; options->type != OPTION_END; options++)
482 if (options->type == OPTION_SUBCOMMAND &&
483 !strcmp(options->long_name, arg)) {
484 *(parse_opt_subcommand_fn **)options->value = options->subcommand_fn;
485 return PARSE_OPT_SUBCOMMAND;
488 return PARSE_OPT_UNKNOWN;
491 static void check_typos(const char *arg, const struct option *options)
493 if (strlen(arg) < 3)
494 return;
496 if (starts_with(arg, "no-")) {
497 error(_("did you mean `--%s` (with two dashes)?"), arg);
498 exit(129);
501 for (; options->type != OPTION_END; options++) {
502 if (!options->long_name)
503 continue;
504 if (starts_with(options->long_name, arg)) {
505 error(_("did you mean `--%s` (with two dashes)?"), arg);
506 exit(129);
511 static void parse_options_check(const struct option *opts)
513 char short_opts[128];
514 void *subcommand_value = NULL;
516 memset(short_opts, '\0', sizeof(short_opts));
517 for (; opts->type != OPTION_END; opts++) {
518 if ((opts->flags & PARSE_OPT_LASTARG_DEFAULT) &&
519 (opts->flags & PARSE_OPT_OPTARG))
520 optbug(opts, "uses incompatible flags "
521 "LASTARG_DEFAULT and OPTARG");
522 if (opts->short_name) {
523 if (0x7F <= opts->short_name)
524 optbug(opts, "invalid short name");
525 else if (short_opts[opts->short_name]++)
526 optbug(opts, "short name already used");
528 if (opts->flags & PARSE_OPT_NODASH &&
529 ((opts->flags & PARSE_OPT_OPTARG) ||
530 !(opts->flags & PARSE_OPT_NOARG) ||
531 !(opts->flags & PARSE_OPT_NONEG) ||
532 opts->long_name))
533 optbug(opts, "uses feature "
534 "not supported for dashless options");
535 if (opts->type == OPTION_SET_INT && !opts->defval &&
536 opts->long_name && !(opts->flags & PARSE_OPT_NONEG))
537 optbug(opts, "OPTION_SET_INT 0 should not be negatable");
538 switch (opts->type) {
539 case OPTION_COUNTUP:
540 case OPTION_BIT:
541 case OPTION_NEGBIT:
542 case OPTION_SET_INT:
543 case OPTION_NUMBER:
544 if ((opts->flags & PARSE_OPT_OPTARG) ||
545 !(opts->flags & PARSE_OPT_NOARG))
546 optbug(opts, "should not accept an argument");
547 break;
548 case OPTION_CALLBACK:
549 if (!opts->callback && !opts->ll_callback)
550 optbug(opts, "OPTION_CALLBACK needs one callback");
551 else if (opts->callback && opts->ll_callback)
552 optbug(opts, "OPTION_CALLBACK can't have two callbacks");
553 break;
554 case OPTION_LOWLEVEL_CALLBACK:
555 if (!opts->ll_callback)
556 optbug(opts, "OPTION_LOWLEVEL_CALLBACK needs a callback");
557 if (opts->callback)
558 optbug(opts, "OPTION_LOWLEVEL_CALLBACK needs no high level callback");
559 break;
560 case OPTION_ALIAS:
561 optbug(opts, "OPT_ALIAS() should not remain at this point. "
562 "Are you using parse_options_step() directly?\n"
563 "That case is not supported yet.");
564 break;
565 case OPTION_SUBCOMMAND:
566 if (!opts->value || !opts->subcommand_fn)
567 optbug(opts, "OPTION_SUBCOMMAND needs a value and a subcommand function");
568 if (!subcommand_value)
569 subcommand_value = opts->value;
570 else if (subcommand_value != opts->value)
571 optbug(opts, "all OPTION_SUBCOMMANDs need the same value");
572 break;
573 default:
574 ; /* ok. (usually accepts an argument) */
576 if (opts->argh &&
577 strcspn(opts->argh, " _") != strlen(opts->argh))
578 optbug(opts, "multi-word argh should use dash to separate words");
580 BUG_if_bug("invalid 'struct option'");
583 static int has_subcommands(const struct option *options)
585 for (; options->type != OPTION_END; options++)
586 if (options->type == OPTION_SUBCOMMAND)
587 return 1;
588 return 0;
591 static void parse_options_start_1(struct parse_opt_ctx_t *ctx,
592 int argc, const char **argv, const char *prefix,
593 const struct option *options,
594 enum parse_opt_flags flags)
596 ctx->argc = argc;
597 ctx->argv = argv;
598 if (!(flags & PARSE_OPT_ONE_SHOT)) {
599 ctx->argc--;
600 ctx->argv++;
602 ctx->total = ctx->argc;
603 ctx->out = argv;
604 ctx->prefix = prefix;
605 ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
606 ctx->flags = flags;
607 ctx->has_subcommands = has_subcommands(options);
608 if (!ctx->has_subcommands && (flags & PARSE_OPT_SUBCOMMAND_OPTIONAL))
609 BUG("Using PARSE_OPT_SUBCOMMAND_OPTIONAL without subcommands");
610 if (ctx->has_subcommands) {
611 if (flags & PARSE_OPT_STOP_AT_NON_OPTION)
612 BUG("subcommands are incompatible with PARSE_OPT_STOP_AT_NON_OPTION");
613 if (!(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
614 if (flags & PARSE_OPT_KEEP_UNKNOWN_OPT)
615 BUG("subcommands are incompatible with PARSE_OPT_KEEP_UNKNOWN_OPT unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
616 if (flags & PARSE_OPT_KEEP_DASHDASH)
617 BUG("subcommands are incompatible with PARSE_OPT_KEEP_DASHDASH unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
620 if ((flags & PARSE_OPT_KEEP_UNKNOWN_OPT) &&
621 (flags & PARSE_OPT_STOP_AT_NON_OPTION) &&
622 !(flags & PARSE_OPT_ONE_SHOT))
623 BUG("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
624 if ((flags & PARSE_OPT_ONE_SHOT) &&
625 (flags & PARSE_OPT_KEEP_ARGV0))
626 BUG("Can't keep argv0 if you don't have it");
627 parse_options_check(options);
628 build_cmdmode_list(ctx, options);
631 void parse_options_start(struct parse_opt_ctx_t *ctx,
632 int argc, const char **argv, const char *prefix,
633 const struct option *options,
634 enum parse_opt_flags flags)
636 memset(ctx, 0, sizeof(*ctx));
637 parse_options_start_1(ctx, argc, argv, prefix, options, flags);
640 static void show_negated_gitcomp(const struct option *opts, int show_all,
641 int nr_noopts)
643 int printed_dashdash = 0;
645 for (; opts->type != OPTION_END; opts++) {
646 int has_unset_form = 0;
647 const char *name;
649 if (!opts->long_name)
650 continue;
651 if (!show_all &&
652 (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE)))
653 continue;
654 if (opts->flags & PARSE_OPT_NONEG)
655 continue;
657 switch (opts->type) {
658 case OPTION_STRING:
659 case OPTION_FILENAME:
660 case OPTION_INTEGER:
661 case OPTION_MAGNITUDE:
662 case OPTION_CALLBACK:
663 case OPTION_BIT:
664 case OPTION_NEGBIT:
665 case OPTION_COUNTUP:
666 case OPTION_SET_INT:
667 has_unset_form = 1;
668 break;
669 default:
670 break;
672 if (!has_unset_form)
673 continue;
675 if (skip_prefix(opts->long_name, "no-", &name)) {
676 if (nr_noopts < 0)
677 printf(" --%s", name);
678 } else if (nr_noopts >= 0) {
679 if (nr_noopts && !printed_dashdash) {
680 printf(" --");
681 printed_dashdash = 1;
683 printf(" --no-%s", opts->long_name);
684 nr_noopts++;
689 static int show_gitcomp(const struct option *opts, int show_all)
691 const struct option *original_opts = opts;
692 int nr_noopts = 0;
694 for (; opts->type != OPTION_END; opts++) {
695 const char *prefix = "--";
696 const char *suffix = "";
698 if (!opts->long_name)
699 continue;
700 if (!show_all &&
701 (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE | PARSE_OPT_FROM_ALIAS)))
702 continue;
704 switch (opts->type) {
705 case OPTION_SUBCOMMAND:
706 prefix = "";
707 break;
708 case OPTION_GROUP:
709 continue;
710 case OPTION_STRING:
711 case OPTION_FILENAME:
712 case OPTION_INTEGER:
713 case OPTION_MAGNITUDE:
714 case OPTION_CALLBACK:
715 if (opts->flags & PARSE_OPT_NOARG)
716 break;
717 if (opts->flags & PARSE_OPT_OPTARG)
718 break;
719 if (opts->flags & PARSE_OPT_LASTARG_DEFAULT)
720 break;
721 suffix = "=";
722 break;
723 default:
724 break;
726 if (opts->flags & PARSE_OPT_COMP_ARG)
727 suffix = "=";
728 if (starts_with(opts->long_name, "no-"))
729 nr_noopts++;
730 printf("%s%s%s%s", opts == original_opts ? "" : " ",
731 prefix, opts->long_name, suffix);
733 show_negated_gitcomp(original_opts, show_all, -1);
734 show_negated_gitcomp(original_opts, show_all, nr_noopts);
735 fputc('\n', stdout);
736 return PARSE_OPT_COMPLETE;
740 * Scan and may produce a new option[] array, which should be used
741 * instead of the original 'options'.
743 * Right now this is only used to preprocess and substitute
744 * OPTION_ALIAS.
746 * The returned options should be freed using free_preprocessed_options.
748 static struct option *preprocess_options(struct parse_opt_ctx_t *ctx,
749 const struct option *options)
751 struct option *newopt;
752 int i, nr, alias;
753 int nr_aliases = 0;
755 for (nr = 0; options[nr].type != OPTION_END; nr++) {
756 if (options[nr].type == OPTION_ALIAS)
757 nr_aliases++;
760 if (!nr_aliases)
761 return NULL;
763 DUP_ARRAY(newopt, options, nr + 1);
765 /* each alias has two string pointers and NULL */
766 CALLOC_ARRAY(ctx->alias_groups, 3 * (nr_aliases + 1));
768 for (alias = 0, i = 0; i < nr; i++) {
769 int short_name;
770 const char *long_name;
771 const char *source;
772 struct strbuf help = STRBUF_INIT;
773 int j;
775 if (newopt[i].type != OPTION_ALIAS)
776 continue;
778 short_name = newopt[i].short_name;
779 long_name = newopt[i].long_name;
780 source = newopt[i].value;
782 if (!long_name)
783 BUG("An alias must have long option name");
784 strbuf_addf(&help, _("alias of --%s"), source);
786 for (j = 0; j < nr; j++) {
787 const char *name = options[j].long_name;
789 if (!name || strcmp(name, source))
790 continue;
792 if (options[j].type == OPTION_ALIAS)
793 BUG("No please. Nested aliases are not supported.");
795 memcpy(newopt + i, options + j, sizeof(*newopt));
796 newopt[i].short_name = short_name;
797 newopt[i].long_name = long_name;
798 newopt[i].help = strbuf_detach(&help, NULL);
799 newopt[i].flags |= PARSE_OPT_FROM_ALIAS;
800 break;
803 if (j == nr)
804 BUG("could not find source option '%s' of alias '%s'",
805 source, newopt[i].long_name);
806 ctx->alias_groups[alias * 3 + 0] = newopt[i].long_name;
807 ctx->alias_groups[alias * 3 + 1] = options[j].long_name;
808 ctx->alias_groups[alias * 3 + 2] = NULL;
809 alias++;
812 return newopt;
815 static void free_preprocessed_options(struct option *options)
817 int i;
819 if (!options)
820 return;
822 for (i = 0; options[i].type != OPTION_END; i++) {
823 if (options[i].flags & PARSE_OPT_FROM_ALIAS)
824 free((void *)options[i].help);
826 free(options);
829 static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t *,
830 const char * const *,
831 const struct option *,
832 int, int);
834 enum parse_opt_result parse_options_step(struct parse_opt_ctx_t *ctx,
835 const struct option *options,
836 const char * const usagestr[])
838 int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
840 /* we must reset ->opt, unknown short option leave it dangling */
841 ctx->opt = NULL;
843 for (; ctx->argc; ctx->argc--, ctx->argv++) {
844 const char *arg = ctx->argv[0];
846 if (ctx->flags & PARSE_OPT_ONE_SHOT &&
847 ctx->argc != ctx->total)
848 break;
850 if (*arg != '-' || !arg[1]) {
851 if (parse_nodash_opt(ctx, arg, options) == 0)
852 continue;
853 if (!ctx->has_subcommands) {
854 if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
855 return PARSE_OPT_NON_OPTION;
856 ctx->out[ctx->cpidx++] = ctx->argv[0];
857 continue;
859 switch (parse_subcommand(arg, options)) {
860 case PARSE_OPT_SUBCOMMAND:
861 return PARSE_OPT_SUBCOMMAND;
862 case PARSE_OPT_UNKNOWN:
863 if (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)
865 * arg is neither a short or long
866 * option nor a subcommand. Since
867 * this command has a default
868 * operation mode, we have to treat
869 * this arg and all remaining args
870 * as args meant to that default
871 * operation mode.
872 * So we are done parsing.
874 return PARSE_OPT_DONE;
875 error(_("unknown subcommand: `%s'"), arg);
876 usage_with_options(usagestr, options);
877 case PARSE_OPT_COMPLETE:
878 case PARSE_OPT_HELP:
879 case PARSE_OPT_ERROR:
880 case PARSE_OPT_DONE:
881 case PARSE_OPT_NON_OPTION:
882 /* Impossible. */
883 BUG("parse_subcommand() cannot return these");
887 /* lone -h asks for help */
888 if (internal_help && ctx->total == 1 && !strcmp(arg + 1, "h"))
889 goto show_usage;
892 * lone --git-completion-helper and --git-completion-helper-all
893 * are asked by git-completion.bash
895 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper"))
896 return show_gitcomp(options, 0);
897 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper-all"))
898 return show_gitcomp(options, 1);
900 if (arg[1] != '-') {
901 ctx->opt = arg + 1;
902 switch (parse_short_opt(ctx, options)) {
903 case PARSE_OPT_ERROR:
904 return PARSE_OPT_ERROR;
905 case PARSE_OPT_UNKNOWN:
906 if (ctx->opt)
907 check_typos(arg + 1, options);
908 if (internal_help && *ctx->opt == 'h')
909 goto show_usage;
910 goto unknown;
911 case PARSE_OPT_NON_OPTION:
912 case PARSE_OPT_SUBCOMMAND:
913 case PARSE_OPT_HELP:
914 case PARSE_OPT_COMPLETE:
915 BUG("parse_short_opt() cannot return these");
916 case PARSE_OPT_DONE:
917 break;
919 if (ctx->opt)
920 check_typos(arg + 1, options);
921 while (ctx->opt) {
922 switch (parse_short_opt(ctx, options)) {
923 case PARSE_OPT_ERROR:
924 return PARSE_OPT_ERROR;
925 case PARSE_OPT_UNKNOWN:
926 if (internal_help && *ctx->opt == 'h')
927 goto show_usage;
929 /* fake a short option thing to hide the fact that we may have
930 * started to parse aggregated stuff
932 * This is leaky, too bad.
934 ctx->argv[0] = xstrdup(ctx->opt - 1);
935 *(char *)ctx->argv[0] = '-';
936 goto unknown;
937 case PARSE_OPT_NON_OPTION:
938 case PARSE_OPT_SUBCOMMAND:
939 case PARSE_OPT_COMPLETE:
940 case PARSE_OPT_HELP:
941 BUG("parse_short_opt() cannot return these");
942 case PARSE_OPT_DONE:
943 break;
946 continue;
949 if (!arg[2] /* "--" */) {
950 if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
951 ctx->argc--;
952 ctx->argv++;
954 break;
955 } else if (!strcmp(arg + 2, "end-of-options")) {
956 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)) {
957 ctx->argc--;
958 ctx->argv++;
960 break;
963 if (internal_help && !strcmp(arg + 2, "help-all"))
964 return usage_with_options_internal(ctx, usagestr, options, 1, 0);
965 if (internal_help && !strcmp(arg + 2, "help"))
966 goto show_usage;
967 switch (parse_long_opt(ctx, arg + 2, options)) {
968 case PARSE_OPT_ERROR:
969 return PARSE_OPT_ERROR;
970 case PARSE_OPT_UNKNOWN:
971 goto unknown;
972 case PARSE_OPT_HELP:
973 goto show_usage;
974 case PARSE_OPT_NON_OPTION:
975 case PARSE_OPT_SUBCOMMAND:
976 case PARSE_OPT_COMPLETE:
977 BUG("parse_long_opt() cannot return these");
978 case PARSE_OPT_DONE:
979 break;
981 continue;
982 unknown:
983 if (ctx->flags & PARSE_OPT_ONE_SHOT)
984 break;
985 if (ctx->has_subcommands &&
986 (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL) &&
987 (ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)) {
989 * Found an unknown option given to a command with
990 * subcommands that has a default operation mode:
991 * we treat this option and all remaining args as
992 * arguments meant to that default operation mode.
993 * So we are done parsing.
995 return PARSE_OPT_DONE;
997 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT))
998 return PARSE_OPT_UNKNOWN;
999 ctx->out[ctx->cpidx++] = ctx->argv[0];
1000 ctx->opt = NULL;
1002 return PARSE_OPT_DONE;
1004 show_usage:
1005 return usage_with_options_internal(ctx, usagestr, options, 0, 0);
1008 int parse_options_end(struct parse_opt_ctx_t *ctx)
1010 if (ctx->flags & PARSE_OPT_ONE_SHOT)
1011 return ctx->total - ctx->argc;
1013 MOVE_ARRAY(ctx->out + ctx->cpidx, ctx->argv, ctx->argc);
1014 ctx->out[ctx->cpidx + ctx->argc] = NULL;
1015 return ctx->cpidx + ctx->argc;
1018 int parse_options(int argc, const char **argv,
1019 const char *prefix,
1020 const struct option *options,
1021 const char * const usagestr[],
1022 enum parse_opt_flags flags)
1024 struct parse_opt_ctx_t ctx;
1025 struct option *real_options;
1027 disallow_abbreviated_options =
1028 git_env_bool("GIT_TEST_DISALLOW_ABBREVIATED_OPTIONS", 0);
1030 memset(&ctx, 0, sizeof(ctx));
1031 real_options = preprocess_options(&ctx, options);
1032 if (real_options)
1033 options = real_options;
1034 parse_options_start_1(&ctx, argc, argv, prefix, options, flags);
1035 switch (parse_options_step(&ctx, options, usagestr)) {
1036 case PARSE_OPT_HELP:
1037 case PARSE_OPT_ERROR:
1038 exit(129);
1039 case PARSE_OPT_COMPLETE:
1040 exit(0);
1041 case PARSE_OPT_NON_OPTION:
1042 case PARSE_OPT_SUBCOMMAND:
1043 break;
1044 case PARSE_OPT_DONE:
1045 if (ctx.has_subcommands &&
1046 !(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
1047 error(_("need a subcommand"));
1048 usage_with_options(usagestr, options);
1050 break;
1051 case PARSE_OPT_UNKNOWN:
1052 if (ctx.argv[0][1] == '-') {
1053 error(_("unknown option `%s'"), ctx.argv[0] + 2);
1054 } else if (isascii(*ctx.opt)) {
1055 error(_("unknown switch `%c'"), *ctx.opt);
1056 } else {
1057 error(_("unknown non-ascii option in string: `%s'"),
1058 ctx.argv[0]);
1060 usage_with_options(usagestr, options);
1063 precompose_argv_prefix(argc, argv, NULL);
1064 free_preprocessed_options(real_options);
1065 free(ctx.alias_groups);
1066 for (struct parse_opt_cmdmode_list *elem = ctx.cmdmode_list; elem;) {
1067 struct parse_opt_cmdmode_list *next = elem->next;
1068 free(elem);
1069 elem = next;
1071 return parse_options_end(&ctx);
1074 static int usage_argh(const struct option *opts, FILE *outfile)
1076 const char *s;
1077 int literal = (opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1078 !opts->argh || !!strpbrk(opts->argh, "()<>[]|");
1079 if (opts->flags & PARSE_OPT_OPTARG)
1080 if (opts->long_name)
1081 s = literal ? "[=%s]" : "[=<%s>]";
1082 else
1083 s = literal ? "[%s]" : "[<%s>]";
1084 else
1085 s = literal ? " %s" : " <%s>";
1086 return utf8_fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
1089 static int usage_indent(FILE *outfile)
1091 return fprintf(outfile, " ");
1094 #define USAGE_OPTS_WIDTH 26
1096 static void usage_padding(FILE *outfile, size_t pos)
1098 if (pos < USAGE_OPTS_WIDTH)
1099 fprintf(outfile, "%*s", USAGE_OPTS_WIDTH - (int)pos, "");
1100 else
1101 fprintf(outfile, "\n%*s", USAGE_OPTS_WIDTH, "");
1104 static const struct option *find_option_by_long_name(const struct option *opts,
1105 const char *long_name)
1107 for (; opts->type != OPTION_END; opts++) {
1108 if (opts->long_name && !strcmp(opts->long_name, long_name))
1109 return opts;
1111 return NULL;
1114 static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t *ctx,
1115 const char * const *usagestr,
1116 const struct option *opts,
1117 int full, int err)
1119 const struct option *all_opts = opts;
1120 FILE *outfile = err ? stderr : stdout;
1121 int need_newline;
1123 const char *usage_prefix = _("usage: %s");
1125 * The translation could be anything, but we can count on
1126 * msgfmt(1)'s --check option to have asserted that "%s" is in
1127 * the translation. So compute the length of the "usage: "
1128 * part. We are assuming that the translator wasn't overly
1129 * clever and used e.g. "%1$s" instead of "%s", there's only
1130 * one "%s" in "usage_prefix" above, so there's no reason to
1131 * do so even with a RTL language.
1133 size_t usage_len = strlen(usage_prefix) - strlen("%s");
1135 * TRANSLATORS: the colon here should align with the
1136 * one in "usage: %s" translation.
1138 const char *or_prefix = _(" or: %s");
1140 * TRANSLATORS: You should only need to translate this format
1141 * string if your language is a RTL language (e.g. Arabic,
1142 * Hebrew etc.), not if it's a LTR language (e.g. German,
1143 * Russian, Chinese etc.).
1145 * When a translated usage string has an embedded "\n" it's
1146 * because options have wrapped to the next line. The line
1147 * after the "\n" will then be padded to align with the
1148 * command name, such as N_("git cmd [opt]\n<8
1149 * spaces>[opt2]"), where the 8 spaces are the same length as
1150 * "git cmd ".
1152 * This format string prints out that already-translated
1153 * line. The "%*s" is whitespace padding to account for the
1154 * padding at the start of the line that we add in this
1155 * function. The "%s" is a line in the (hopefully already
1156 * translated) N_() usage string, which contained embedded
1157 * newlines before we split it up.
1159 const char *usage_continued = _("%*s%s");
1160 const char *prefix = usage_prefix;
1161 int saw_empty_line = 0;
1163 if (!usagestr)
1164 return PARSE_OPT_HELP;
1166 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1167 fprintf(outfile, "cat <<\\EOF\n");
1169 while (*usagestr) {
1170 const char *str = _(*usagestr++);
1171 struct string_list list = STRING_LIST_INIT_DUP;
1172 unsigned int j;
1174 if (!saw_empty_line && !*str)
1175 saw_empty_line = 1;
1177 string_list_split(&list, str, '\n', -1);
1178 for (j = 0; j < list.nr; j++) {
1179 const char *line = list.items[j].string;
1181 if (saw_empty_line && *line)
1182 fprintf_ln(outfile, _(" %s"), line);
1183 else if (saw_empty_line)
1184 fputc('\n', outfile);
1185 else if (!j)
1186 fprintf_ln(outfile, prefix, line);
1187 else
1188 fprintf_ln(outfile, usage_continued,
1189 (int)usage_len, "", line);
1191 string_list_clear(&list, 0);
1193 prefix = or_prefix;
1196 need_newline = 1;
1198 for (; opts->type != OPTION_END; opts++) {
1199 size_t pos;
1200 const char *cp, *np;
1201 const char *positive_name = NULL;
1203 if (opts->type == OPTION_SUBCOMMAND)
1204 continue;
1205 if (opts->type == OPTION_GROUP) {
1206 fputc('\n', outfile);
1207 need_newline = 0;
1208 if (*opts->help)
1209 fprintf(outfile, "%s\n", _(opts->help));
1210 continue;
1212 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
1213 continue;
1215 if (need_newline) {
1216 fputc('\n', outfile);
1217 need_newline = 0;
1220 pos = usage_indent(outfile);
1221 if (opts->short_name) {
1222 if (opts->flags & PARSE_OPT_NODASH)
1223 pos += fprintf(outfile, "%c", opts->short_name);
1224 else
1225 pos += fprintf(outfile, "-%c", opts->short_name);
1227 if (opts->long_name && opts->short_name)
1228 pos += fprintf(outfile, ", ");
1229 if (opts->long_name) {
1230 const char *long_name = opts->long_name;
1231 if ((opts->flags & PARSE_OPT_NONEG) ||
1232 skip_prefix(long_name, "no-", &positive_name))
1233 pos += fprintf(outfile, "--%s", long_name);
1234 else
1235 pos += fprintf(outfile, "--[no-]%s", long_name);
1238 if (opts->type == OPTION_NUMBER)
1239 pos += utf8_fprintf(outfile, _("-NUM"));
1241 if ((opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1242 !(opts->flags & PARSE_OPT_NOARG))
1243 pos += usage_argh(opts, outfile);
1245 if (opts->type == OPTION_ALIAS) {
1246 usage_padding(outfile, pos);
1247 fprintf_ln(outfile, _("alias of --%s"),
1248 (const char *)opts->value);
1249 continue;
1252 for (cp = opts->help ? _(opts->help) : ""; *cp; cp = np) {
1253 np = strchrnul(cp, '\n');
1254 if (*np)
1255 np++;
1256 usage_padding(outfile, pos);
1257 fwrite(cp, 1, np - cp, outfile);
1258 pos = 0;
1260 fputc('\n', outfile);
1262 if (positive_name) {
1263 if (find_option_by_long_name(all_opts, positive_name))
1264 continue;
1265 pos = usage_indent(outfile);
1266 pos += fprintf(outfile, "--%s", positive_name);
1267 usage_padding(outfile, pos);
1268 fprintf_ln(outfile, _("opposite of --no-%s"),
1269 positive_name);
1272 fputc('\n', outfile);
1274 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1275 fputs("EOF\n", outfile);
1277 return PARSE_OPT_HELP;
1280 void NORETURN usage_with_options(const char * const *usagestr,
1281 const struct option *opts)
1283 usage_with_options_internal(NULL, usagestr, opts, 0, 1);
1284 exit(129);
1287 void NORETURN usage_msg_opt(const char *msg,
1288 const char * const *usagestr,
1289 const struct option *options)
1291 die_message("%s\n", msg); /* The extra \n is intentional */
1292 usage_with_options(usagestr, options);
1295 void NORETURN usage_msg_optf(const char * const fmt,
1296 const char * const *usagestr,
1297 const struct option *options, ...)
1299 struct strbuf msg = STRBUF_INIT;
1300 va_list ap;
1301 va_start(ap, options);
1302 strbuf_vaddf(&msg, fmt, ap);
1303 va_end(ap);
1305 usage_msg_opt(msg.buf, usagestr, options);
1308 void die_for_incompatible_opt4(int opt1, const char *opt1_name,
1309 int opt2, const char *opt2_name,
1310 int opt3, const char *opt3_name,
1311 int opt4, const char *opt4_name)
1313 int count = 0;
1314 const char *options[4];
1316 if (opt1)
1317 options[count++] = opt1_name;
1318 if (opt2)
1319 options[count++] = opt2_name;
1320 if (opt3)
1321 options[count++] = opt3_name;
1322 if (opt4)
1323 options[count++] = opt4_name;
1324 switch (count) {
1325 case 4:
1326 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
1327 opt1_name, opt2_name, opt3_name, opt4_name);
1328 break;
1329 case 3:
1330 die(_("options '%s', '%s', and '%s' cannot be used together"),
1331 options[0], options[1], options[2]);
1332 break;
1333 case 2:
1334 die(_("options '%s' and '%s' cannot be used together"),
1335 options[0], options[1]);
1336 break;
1337 default:
1338 break;