debian: new upstream release
[git/debian.git] / parse-options.c
blobe0c94b0546b5487c5b324c4c2b76d668289e8b10
1 #include "git-compat-util.h"
2 #include "parse-options.h"
3 #include "abspath.h"
4 #include "parse.h"
5 #include "commit.h"
6 #include "color.h"
7 #include "gettext.h"
8 #include "strbuf.h"
9 #include "string-list.h"
10 #include "utf8.h"
12 static int disallow_abbreviated_options;
14 enum opt_parsed {
15 OPT_LONG = 0,
16 OPT_SHORT = 1<<0,
17 OPT_UNSET = 1<<1,
20 static void optbug(const struct option *opt, const char *reason)
22 if (opt->long_name && opt->short_name)
23 bug("switch '%c' (--%s) %s", opt->short_name,
24 opt->long_name, reason);
25 else if (opt->long_name)
26 bug("option '%s' %s", opt->long_name, reason);
27 else
28 bug("switch '%c' %s", opt->short_name, reason);
31 static const char *optname(const struct option *opt, enum opt_parsed flags)
33 static struct strbuf sb = STRBUF_INIT;
35 strbuf_reset(&sb);
36 if (flags & OPT_SHORT)
37 strbuf_addf(&sb, "switch `%c'", opt->short_name);
38 else if (flags & OPT_UNSET)
39 strbuf_addf(&sb, "option `no-%s'", opt->long_name);
40 else if (flags == OPT_LONG)
41 strbuf_addf(&sb, "option `%s'", opt->long_name);
42 else
43 BUG("optname() got unknown flags %d", flags);
45 return sb.buf;
48 static enum parse_opt_result get_arg(struct parse_opt_ctx_t *p,
49 const struct option *opt,
50 enum opt_parsed flags, const char **arg)
52 if (p->opt) {
53 *arg = p->opt;
54 p->opt = NULL;
55 } else if (p->argc == 1 && (opt->flags & PARSE_OPT_LASTARG_DEFAULT)) {
56 *arg = (const char *)opt->defval;
57 } else if (p->argc > 1) {
58 p->argc--;
59 *arg = *++p->argv;
60 } else
61 return error(_("%s requires a value"), optname(opt, flags));
62 return 0;
65 static void fix_filename(const char *prefix, char **file)
67 if (!file || !*file)
68 ; /* leave as NULL */
69 else
70 *file = prefix_filename_except_for_dash(prefix, *file);
73 static enum parse_opt_result do_get_value(struct parse_opt_ctx_t *p,
74 const struct option *opt,
75 enum opt_parsed flags,
76 const char **argp)
78 const char *s, *arg;
79 const int unset = flags & OPT_UNSET;
80 int err;
82 if (unset && p->opt)
83 return error(_("%s takes no value"), optname(opt, flags));
84 if (unset && (opt->flags & PARSE_OPT_NONEG))
85 return error(_("%s isn't available"), optname(opt, flags));
86 if (!(flags & OPT_SHORT) && p->opt && (opt->flags & PARSE_OPT_NOARG))
87 return error(_("%s takes no value"), optname(opt, flags));
89 switch (opt->type) {
90 case OPTION_LOWLEVEL_CALLBACK:
91 return opt->ll_callback(p, opt, NULL, unset);
93 case OPTION_BIT:
94 if (unset)
95 *(int *)opt->value &= ~opt->defval;
96 else
97 *(int *)opt->value |= opt->defval;
98 return 0;
100 case OPTION_NEGBIT:
101 if (unset)
102 *(int *)opt->value |= opt->defval;
103 else
104 *(int *)opt->value &= ~opt->defval;
105 return 0;
107 case OPTION_BITOP:
108 if (unset)
109 BUG("BITOP can't have unset form");
110 *(int *)opt->value &= ~opt->extra;
111 *(int *)opt->value |= opt->defval;
112 return 0;
114 case OPTION_COUNTUP:
115 if (*(int *)opt->value < 0)
116 *(int *)opt->value = 0;
117 *(int *)opt->value = unset ? 0 : *(int *)opt->value + 1;
118 return 0;
120 case OPTION_SET_INT:
121 *(int *)opt->value = unset ? 0 : opt->defval;
122 return 0;
124 case OPTION_STRING:
125 if (unset)
126 *(const char **)opt->value = NULL;
127 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
128 *(const char **)opt->value = (const char *)opt->defval;
129 else
130 return get_arg(p, opt, flags, (const char **)opt->value);
131 return 0;
133 case OPTION_FILENAME:
134 err = 0;
135 if (unset)
136 *(const char **)opt->value = NULL;
137 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
138 *(const char **)opt->value = (const char *)opt->defval;
139 else
140 err = get_arg(p, opt, flags, (const char **)opt->value);
142 if (!err)
143 fix_filename(p->prefix, (char **)opt->value);
144 return err;
146 case OPTION_CALLBACK:
148 const char *p_arg = NULL;
149 int p_unset;
151 if (unset)
152 p_unset = 1;
153 else if (opt->flags & PARSE_OPT_NOARG)
154 p_unset = 0;
155 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
156 p_unset = 0;
157 else if (get_arg(p, opt, flags, &arg))
158 return -1;
159 else {
160 p_unset = 0;
161 p_arg = arg;
163 if (opt->flags & PARSE_OPT_CMDMODE)
164 *argp = p_arg;
165 if (opt->callback)
166 return (*opt->callback)(opt, p_arg, p_unset) ? (-1) : 0;
167 else
168 return (*opt->ll_callback)(p, opt, p_arg, p_unset);
170 case OPTION_INTEGER:
171 if (unset) {
172 *(int *)opt->value = 0;
173 return 0;
175 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
176 *(int *)opt->value = opt->defval;
177 return 0;
179 if (get_arg(p, opt, flags, &arg))
180 return -1;
181 if (!*arg)
182 return error(_("%s expects a numerical value"),
183 optname(opt, flags));
184 *(int *)opt->value = strtol(arg, (char **)&s, 10);
185 if (*s)
186 return error(_("%s expects a numerical value"),
187 optname(opt, flags));
188 return 0;
190 case OPTION_MAGNITUDE:
191 if (unset) {
192 *(unsigned long *)opt->value = 0;
193 return 0;
195 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
196 *(unsigned long *)opt->value = opt->defval;
197 return 0;
199 if (get_arg(p, opt, flags, &arg))
200 return -1;
201 if (!git_parse_ulong(arg, opt->value))
202 return error(_("%s expects a non-negative integer value"
203 " with an optional k/m/g suffix"),
204 optname(opt, flags));
205 return 0;
207 default:
208 BUG("opt->type %d should not happen", opt->type);
212 struct parse_opt_cmdmode_list {
213 int value, *value_ptr;
214 const struct option *opt;
215 const char *arg;
216 enum opt_parsed flags;
217 struct parse_opt_cmdmode_list *next;
220 static void build_cmdmode_list(struct parse_opt_ctx_t *ctx,
221 const struct option *opts)
223 ctx->cmdmode_list = NULL;
225 for (; opts->type != OPTION_END; opts++) {
226 struct parse_opt_cmdmode_list *elem = ctx->cmdmode_list;
227 int *value_ptr = opts->value;
229 if (!(opts->flags & PARSE_OPT_CMDMODE) || !value_ptr)
230 continue;
232 while (elem && elem->value_ptr != value_ptr)
233 elem = elem->next;
234 if (elem)
235 continue;
237 CALLOC_ARRAY(elem, 1);
238 elem->value_ptr = value_ptr;
239 elem->value = *value_ptr;
240 elem->next = ctx->cmdmode_list;
241 ctx->cmdmode_list = elem;
245 static char *optnamearg(const struct option *opt, const char *arg,
246 enum opt_parsed flags)
248 if (flags & OPT_SHORT)
249 return xstrfmt("-%c%s", opt->short_name, arg ? arg : "");
250 return xstrfmt("--%s%s%s%s", flags & OPT_UNSET ? "no-" : "",
251 opt->long_name, arg ? "=" : "", arg ? arg : "");
254 static enum parse_opt_result get_value(struct parse_opt_ctx_t *p,
255 const struct option *opt,
256 enum opt_parsed flags)
258 const char *arg = NULL;
259 enum parse_opt_result result = do_get_value(p, opt, flags, &arg);
260 struct parse_opt_cmdmode_list *elem = p->cmdmode_list;
261 char *opt_name, *other_opt_name;
263 for (; elem; elem = elem->next) {
264 if (*elem->value_ptr == elem->value)
265 continue;
267 if (elem->opt &&
268 (elem->opt->flags | opt->flags) & PARSE_OPT_CMDMODE)
269 break;
271 elem->opt = opt;
272 elem->arg = arg;
273 elem->flags = flags;
274 elem->value = *elem->value_ptr;
277 if (result || !elem)
278 return result;
280 opt_name = optnamearg(opt, arg, flags);
281 other_opt_name = optnamearg(elem->opt, elem->arg, elem->flags);
282 error(_("%s is incompatible with %s"), opt_name, other_opt_name);
283 free(opt_name);
284 free(other_opt_name);
285 return -1;
288 static enum parse_opt_result parse_short_opt(struct parse_opt_ctx_t *p,
289 const struct option *options)
291 const struct option *numopt = NULL;
293 for (; options->type != OPTION_END; options++) {
294 if (options->short_name == *p->opt) {
295 p->opt = p->opt[1] ? p->opt + 1 : NULL;
296 return get_value(p, options, OPT_SHORT);
300 * Handle the numerical option later, explicit one-digit
301 * options take precedence over it.
303 if (options->type == OPTION_NUMBER)
304 numopt = options;
306 if (numopt && isdigit(*p->opt)) {
307 size_t len = 1;
308 char *arg;
309 int rc;
311 while (isdigit(p->opt[len]))
312 len++;
313 arg = xmemdupz(p->opt, len);
314 p->opt = p->opt[len] ? p->opt + len : NULL;
315 if (numopt->callback)
316 rc = (*numopt->callback)(numopt, arg, 0) ? (-1) : 0;
317 else
318 rc = (*numopt->ll_callback)(p, numopt, arg, 0);
319 free(arg);
320 return rc;
322 return PARSE_OPT_UNKNOWN;
325 static int has_string(const char *it, const char **array)
327 while (*array)
328 if (!strcmp(it, *(array++)))
329 return 1;
330 return 0;
333 static int is_alias(struct parse_opt_ctx_t *ctx,
334 const struct option *one_opt,
335 const struct option *another_opt)
337 const char **group;
339 if (!ctx->alias_groups)
340 return 0;
342 if (!one_opt->long_name || !another_opt->long_name)
343 return 0;
345 for (group = ctx->alias_groups; *group; group += 3) {
346 /* it and other are from the same family? */
347 if (has_string(one_opt->long_name, group) &&
348 has_string(another_opt->long_name, group))
349 return 1;
351 return 0;
354 static enum parse_opt_result parse_long_opt(
355 struct parse_opt_ctx_t *p, const char *arg,
356 const struct option *options)
358 const char *arg_end = strchrnul(arg, '=');
359 const struct option *abbrev_option = NULL, *ambiguous_option = NULL;
360 enum opt_parsed abbrev_flags = OPT_LONG, ambiguous_flags = OPT_LONG;
362 for (; options->type != OPTION_END; options++) {
363 const char *rest, *long_name = options->long_name;
364 enum opt_parsed flags = OPT_LONG, opt_flags = OPT_LONG;
366 if (options->type == OPTION_SUBCOMMAND)
367 continue;
368 if (!long_name)
369 continue;
371 again:
372 if (!skip_prefix(arg, long_name, &rest))
373 rest = NULL;
374 if (!rest) {
375 /* abbreviated? */
376 if (!(p->flags & PARSE_OPT_KEEP_UNKNOWN_OPT) &&
377 !strncmp(long_name, arg, arg_end - arg)) {
378 is_abbreviated:
379 if (abbrev_option &&
380 !is_alias(p, abbrev_option, options)) {
382 * If this is abbreviated, it is
383 * ambiguous. So when there is no
384 * exact match later, we need to
385 * error out.
387 ambiguous_option = abbrev_option;
388 ambiguous_flags = abbrev_flags;
390 if (!(flags & OPT_UNSET) && *arg_end)
391 p->opt = arg_end + 1;
392 abbrev_option = options;
393 abbrev_flags = flags ^ opt_flags;
394 continue;
396 /* negation allowed? */
397 if (options->flags & PARSE_OPT_NONEG)
398 continue;
399 /* negated and abbreviated very much? */
400 if (starts_with("no-", arg)) {
401 flags |= OPT_UNSET;
402 goto is_abbreviated;
404 /* negated? */
405 if (!starts_with(arg, "no-")) {
406 if (skip_prefix(long_name, "no-", &long_name)) {
407 opt_flags |= OPT_UNSET;
408 goto again;
410 continue;
412 flags |= OPT_UNSET;
413 if (!skip_prefix(arg + 3, long_name, &rest)) {
414 /* abbreviated and negated? */
415 if (starts_with(long_name, arg + 3))
416 goto is_abbreviated;
417 else
418 continue;
421 if (*rest) {
422 if (*rest != '=')
423 continue;
424 p->opt = rest + 1;
426 return get_value(p, options, flags ^ opt_flags);
429 if (disallow_abbreviated_options && (ambiguous_option || abbrev_option))
430 die("disallowed abbreviated or ambiguous option '%.*s'",
431 (int)(arg_end - arg), arg);
433 if (ambiguous_option) {
434 error(_("ambiguous option: %s "
435 "(could be --%s%s or --%s%s)"),
436 arg,
437 (ambiguous_flags & OPT_UNSET) ? "no-" : "",
438 ambiguous_option->long_name,
439 (abbrev_flags & OPT_UNSET) ? "no-" : "",
440 abbrev_option->long_name);
441 return PARSE_OPT_HELP;
443 if (abbrev_option)
444 return get_value(p, abbrev_option, abbrev_flags);
445 return PARSE_OPT_UNKNOWN;
448 static enum parse_opt_result parse_nodash_opt(struct parse_opt_ctx_t *p,
449 const char *arg,
450 const struct option *options)
452 for (; options->type != OPTION_END; options++) {
453 if (!(options->flags & PARSE_OPT_NODASH))
454 continue;
455 if (options->short_name == arg[0] && arg[1] == '\0')
456 return get_value(p, options, OPT_SHORT);
458 return PARSE_OPT_ERROR;
461 static enum parse_opt_result parse_subcommand(const char *arg,
462 const struct option *options)
464 for (; options->type != OPTION_END; options++)
465 if (options->type == OPTION_SUBCOMMAND &&
466 !strcmp(options->long_name, arg)) {
467 *(parse_opt_subcommand_fn **)options->value = options->subcommand_fn;
468 return PARSE_OPT_SUBCOMMAND;
471 return PARSE_OPT_UNKNOWN;
474 static void check_typos(const char *arg, const struct option *options)
476 if (strlen(arg) < 3)
477 return;
479 if (starts_with(arg, "no-")) {
480 error(_("did you mean `--%s` (with two dashes)?"), arg);
481 exit(129);
484 for (; options->type != OPTION_END; options++) {
485 if (!options->long_name)
486 continue;
487 if (starts_with(options->long_name, arg)) {
488 error(_("did you mean `--%s` (with two dashes)?"), arg);
489 exit(129);
494 static void parse_options_check(const struct option *opts)
496 char short_opts[128];
497 void *subcommand_value = NULL;
499 memset(short_opts, '\0', sizeof(short_opts));
500 for (; opts->type != OPTION_END; opts++) {
501 if ((opts->flags & PARSE_OPT_LASTARG_DEFAULT) &&
502 (opts->flags & PARSE_OPT_OPTARG))
503 optbug(opts, "uses incompatible flags "
504 "LASTARG_DEFAULT and OPTARG");
505 if (opts->short_name) {
506 if (0x7F <= opts->short_name)
507 optbug(opts, "invalid short name");
508 else if (short_opts[opts->short_name]++)
509 optbug(opts, "short name already used");
511 if (opts->flags & PARSE_OPT_NODASH &&
512 ((opts->flags & PARSE_OPT_OPTARG) ||
513 !(opts->flags & PARSE_OPT_NOARG) ||
514 !(opts->flags & PARSE_OPT_NONEG) ||
515 opts->long_name))
516 optbug(opts, "uses feature "
517 "not supported for dashless options");
518 if (opts->type == OPTION_SET_INT && !opts->defval &&
519 opts->long_name && !(opts->flags & PARSE_OPT_NONEG))
520 optbug(opts, "OPTION_SET_INT 0 should not be negatable");
521 switch (opts->type) {
522 case OPTION_COUNTUP:
523 case OPTION_BIT:
524 case OPTION_NEGBIT:
525 case OPTION_SET_INT:
526 case OPTION_NUMBER:
527 if ((opts->flags & PARSE_OPT_OPTARG) ||
528 !(opts->flags & PARSE_OPT_NOARG))
529 optbug(opts, "should not accept an argument");
530 break;
531 case OPTION_CALLBACK:
532 if (!opts->callback && !opts->ll_callback)
533 optbug(opts, "OPTION_CALLBACK needs one callback");
534 else if (opts->callback && opts->ll_callback)
535 optbug(opts, "OPTION_CALLBACK can't have two callbacks");
536 break;
537 case OPTION_LOWLEVEL_CALLBACK:
538 if (!opts->ll_callback)
539 optbug(opts, "OPTION_LOWLEVEL_CALLBACK needs a callback");
540 if (opts->callback)
541 optbug(opts, "OPTION_LOWLEVEL_CALLBACK needs no high level callback");
542 break;
543 case OPTION_ALIAS:
544 optbug(opts, "OPT_ALIAS() should not remain at this point. "
545 "Are you using parse_options_step() directly?\n"
546 "That case is not supported yet.");
547 break;
548 case OPTION_SUBCOMMAND:
549 if (!opts->value || !opts->subcommand_fn)
550 optbug(opts, "OPTION_SUBCOMMAND needs a value and a subcommand function");
551 if (!subcommand_value)
552 subcommand_value = opts->value;
553 else if (subcommand_value != opts->value)
554 optbug(opts, "all OPTION_SUBCOMMANDs need the same value");
555 break;
556 default:
557 ; /* ok. (usually accepts an argument) */
559 if (opts->argh &&
560 strcspn(opts->argh, " _") != strlen(opts->argh))
561 optbug(opts, "multi-word argh should use dash to separate words");
563 BUG_if_bug("invalid 'struct option'");
566 static int has_subcommands(const struct option *options)
568 for (; options->type != OPTION_END; options++)
569 if (options->type == OPTION_SUBCOMMAND)
570 return 1;
571 return 0;
574 static void parse_options_start_1(struct parse_opt_ctx_t *ctx,
575 int argc, const char **argv, const char *prefix,
576 const struct option *options,
577 enum parse_opt_flags flags)
579 ctx->argc = argc;
580 ctx->argv = argv;
581 if (!(flags & PARSE_OPT_ONE_SHOT)) {
582 ctx->argc--;
583 ctx->argv++;
585 ctx->total = ctx->argc;
586 ctx->out = argv;
587 ctx->prefix = prefix;
588 ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
589 ctx->flags = flags;
590 ctx->has_subcommands = has_subcommands(options);
591 if (!ctx->has_subcommands && (flags & PARSE_OPT_SUBCOMMAND_OPTIONAL))
592 BUG("Using PARSE_OPT_SUBCOMMAND_OPTIONAL without subcommands");
593 if (ctx->has_subcommands) {
594 if (flags & PARSE_OPT_STOP_AT_NON_OPTION)
595 BUG("subcommands are incompatible with PARSE_OPT_STOP_AT_NON_OPTION");
596 if (!(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
597 if (flags & PARSE_OPT_KEEP_UNKNOWN_OPT)
598 BUG("subcommands are incompatible with PARSE_OPT_KEEP_UNKNOWN_OPT unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
599 if (flags & PARSE_OPT_KEEP_DASHDASH)
600 BUG("subcommands are incompatible with PARSE_OPT_KEEP_DASHDASH unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
603 if ((flags & PARSE_OPT_KEEP_UNKNOWN_OPT) &&
604 (flags & PARSE_OPT_STOP_AT_NON_OPTION) &&
605 !(flags & PARSE_OPT_ONE_SHOT))
606 BUG("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
607 if ((flags & PARSE_OPT_ONE_SHOT) &&
608 (flags & PARSE_OPT_KEEP_ARGV0))
609 BUG("Can't keep argv0 if you don't have it");
610 parse_options_check(options);
611 build_cmdmode_list(ctx, options);
614 void parse_options_start(struct parse_opt_ctx_t *ctx,
615 int argc, const char **argv, const char *prefix,
616 const struct option *options,
617 enum parse_opt_flags flags)
619 memset(ctx, 0, sizeof(*ctx));
620 parse_options_start_1(ctx, argc, argv, prefix, options, flags);
623 static void show_negated_gitcomp(const struct option *opts, int show_all,
624 int nr_noopts)
626 int printed_dashdash = 0;
628 for (; opts->type != OPTION_END; opts++) {
629 int has_unset_form = 0;
630 const char *name;
632 if (!opts->long_name)
633 continue;
634 if (!show_all &&
635 (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE)))
636 continue;
637 if (opts->flags & PARSE_OPT_NONEG)
638 continue;
640 switch (opts->type) {
641 case OPTION_STRING:
642 case OPTION_FILENAME:
643 case OPTION_INTEGER:
644 case OPTION_MAGNITUDE:
645 case OPTION_CALLBACK:
646 case OPTION_BIT:
647 case OPTION_NEGBIT:
648 case OPTION_COUNTUP:
649 case OPTION_SET_INT:
650 has_unset_form = 1;
651 break;
652 default:
653 break;
655 if (!has_unset_form)
656 continue;
658 if (skip_prefix(opts->long_name, "no-", &name)) {
659 if (nr_noopts < 0)
660 printf(" --%s", name);
661 } else if (nr_noopts >= 0) {
662 if (nr_noopts && !printed_dashdash) {
663 printf(" --");
664 printed_dashdash = 1;
666 printf(" --no-%s", opts->long_name);
667 nr_noopts++;
672 static int show_gitcomp(const struct option *opts, int show_all)
674 const struct option *original_opts = opts;
675 int nr_noopts = 0;
677 for (; opts->type != OPTION_END; opts++) {
678 const char *prefix = "--";
679 const char *suffix = "";
681 if (!opts->long_name)
682 continue;
683 if (!show_all &&
684 (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE | PARSE_OPT_FROM_ALIAS)))
685 continue;
687 switch (opts->type) {
688 case OPTION_SUBCOMMAND:
689 prefix = "";
690 break;
691 case OPTION_GROUP:
692 continue;
693 case OPTION_STRING:
694 case OPTION_FILENAME:
695 case OPTION_INTEGER:
696 case OPTION_MAGNITUDE:
697 case OPTION_CALLBACK:
698 if (opts->flags & PARSE_OPT_NOARG)
699 break;
700 if (opts->flags & PARSE_OPT_OPTARG)
701 break;
702 if (opts->flags & PARSE_OPT_LASTARG_DEFAULT)
703 break;
704 suffix = "=";
705 break;
706 default:
707 break;
709 if (opts->flags & PARSE_OPT_COMP_ARG)
710 suffix = "=";
711 if (starts_with(opts->long_name, "no-"))
712 nr_noopts++;
713 printf("%s%s%s%s", opts == original_opts ? "" : " ",
714 prefix, opts->long_name, suffix);
716 show_negated_gitcomp(original_opts, show_all, -1);
717 show_negated_gitcomp(original_opts, show_all, nr_noopts);
718 fputc('\n', stdout);
719 return PARSE_OPT_COMPLETE;
723 * Scan and may produce a new option[] array, which should be used
724 * instead of the original 'options'.
726 * Right now this is only used to preprocess and substitute
727 * OPTION_ALIAS.
729 * The returned options should be freed using free_preprocessed_options.
731 static struct option *preprocess_options(struct parse_opt_ctx_t *ctx,
732 const struct option *options)
734 struct option *newopt;
735 int i, nr, alias;
736 int nr_aliases = 0;
738 for (nr = 0; options[nr].type != OPTION_END; nr++) {
739 if (options[nr].type == OPTION_ALIAS)
740 nr_aliases++;
743 if (!nr_aliases)
744 return NULL;
746 DUP_ARRAY(newopt, options, nr + 1);
748 /* each alias has two string pointers and NULL */
749 CALLOC_ARRAY(ctx->alias_groups, 3 * (nr_aliases + 1));
751 for (alias = 0, i = 0; i < nr; i++) {
752 int short_name;
753 const char *long_name;
754 const char *source;
755 struct strbuf help = STRBUF_INIT;
756 int j;
758 if (newopt[i].type != OPTION_ALIAS)
759 continue;
761 short_name = newopt[i].short_name;
762 long_name = newopt[i].long_name;
763 source = newopt[i].value;
765 if (!long_name)
766 BUG("An alias must have long option name");
767 strbuf_addf(&help, _("alias of --%s"), source);
769 for (j = 0; j < nr; j++) {
770 const char *name = options[j].long_name;
772 if (!name || strcmp(name, source))
773 continue;
775 if (options[j].type == OPTION_ALIAS)
776 BUG("No please. Nested aliases are not supported.");
778 memcpy(newopt + i, options + j, sizeof(*newopt));
779 newopt[i].short_name = short_name;
780 newopt[i].long_name = long_name;
781 newopt[i].help = strbuf_detach(&help, NULL);
782 newopt[i].flags |= PARSE_OPT_FROM_ALIAS;
783 break;
786 if (j == nr)
787 BUG("could not find source option '%s' of alias '%s'",
788 source, newopt[i].long_name);
789 ctx->alias_groups[alias * 3 + 0] = newopt[i].long_name;
790 ctx->alias_groups[alias * 3 + 1] = options[j].long_name;
791 ctx->alias_groups[alias * 3 + 2] = NULL;
792 alias++;
795 return newopt;
798 static void free_preprocessed_options(struct option *options)
800 int i;
802 if (!options)
803 return;
805 for (i = 0; options[i].type != OPTION_END; i++) {
806 if (options[i].flags & PARSE_OPT_FROM_ALIAS)
807 free((void *)options[i].help);
809 free(options);
812 static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t *,
813 const char * const *,
814 const struct option *,
815 int, int);
817 enum parse_opt_result parse_options_step(struct parse_opt_ctx_t *ctx,
818 const struct option *options,
819 const char * const usagestr[])
821 int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
823 /* we must reset ->opt, unknown short option leave it dangling */
824 ctx->opt = NULL;
826 for (; ctx->argc; ctx->argc--, ctx->argv++) {
827 const char *arg = ctx->argv[0];
829 if (ctx->flags & PARSE_OPT_ONE_SHOT &&
830 ctx->argc != ctx->total)
831 break;
833 if (*arg != '-' || !arg[1]) {
834 if (parse_nodash_opt(ctx, arg, options) == 0)
835 continue;
836 if (!ctx->has_subcommands) {
837 if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
838 return PARSE_OPT_NON_OPTION;
839 ctx->out[ctx->cpidx++] = ctx->argv[0];
840 continue;
842 switch (parse_subcommand(arg, options)) {
843 case PARSE_OPT_SUBCOMMAND:
844 return PARSE_OPT_SUBCOMMAND;
845 case PARSE_OPT_UNKNOWN:
846 if (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)
848 * arg is neither a short or long
849 * option nor a subcommand. Since
850 * this command has a default
851 * operation mode, we have to treat
852 * this arg and all remaining args
853 * as args meant to that default
854 * operation mode.
855 * So we are done parsing.
857 return PARSE_OPT_DONE;
858 error(_("unknown subcommand: `%s'"), arg);
859 usage_with_options(usagestr, options);
860 case PARSE_OPT_COMPLETE:
861 case PARSE_OPT_HELP:
862 case PARSE_OPT_ERROR:
863 case PARSE_OPT_DONE:
864 case PARSE_OPT_NON_OPTION:
865 /* Impossible. */
866 BUG("parse_subcommand() cannot return these");
870 /* lone -h asks for help */
871 if (internal_help && ctx->total == 1 && !strcmp(arg + 1, "h"))
872 goto show_usage;
875 * lone --git-completion-helper and --git-completion-helper-all
876 * are asked by git-completion.bash
878 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper"))
879 return show_gitcomp(options, 0);
880 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper-all"))
881 return show_gitcomp(options, 1);
883 if (arg[1] != '-') {
884 ctx->opt = arg + 1;
885 switch (parse_short_opt(ctx, options)) {
886 case PARSE_OPT_ERROR:
887 return PARSE_OPT_ERROR;
888 case PARSE_OPT_UNKNOWN:
889 if (ctx->opt)
890 check_typos(arg + 1, options);
891 if (internal_help && *ctx->opt == 'h')
892 goto show_usage;
893 goto unknown;
894 case PARSE_OPT_NON_OPTION:
895 case PARSE_OPT_SUBCOMMAND:
896 case PARSE_OPT_HELP:
897 case PARSE_OPT_COMPLETE:
898 BUG("parse_short_opt() cannot return these");
899 case PARSE_OPT_DONE:
900 break;
902 if (ctx->opt)
903 check_typos(arg + 1, options);
904 while (ctx->opt) {
905 switch (parse_short_opt(ctx, options)) {
906 case PARSE_OPT_ERROR:
907 return PARSE_OPT_ERROR;
908 case PARSE_OPT_UNKNOWN:
909 if (internal_help && *ctx->opt == 'h')
910 goto show_usage;
912 /* fake a short option thing to hide the fact that we may have
913 * started to parse aggregated stuff
915 * This is leaky, too bad.
917 ctx->argv[0] = xstrdup(ctx->opt - 1);
918 *(char *)ctx->argv[0] = '-';
919 goto unknown;
920 case PARSE_OPT_NON_OPTION:
921 case PARSE_OPT_SUBCOMMAND:
922 case PARSE_OPT_COMPLETE:
923 case PARSE_OPT_HELP:
924 BUG("parse_short_opt() cannot return these");
925 case PARSE_OPT_DONE:
926 break;
929 continue;
932 if (!arg[2] /* "--" */ ||
933 !strcmp(arg + 2, "end-of-options")) {
934 if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
935 ctx->argc--;
936 ctx->argv++;
938 break;
941 if (internal_help && !strcmp(arg + 2, "help-all"))
942 return usage_with_options_internal(ctx, usagestr, options, 1, 0);
943 if (internal_help && !strcmp(arg + 2, "help"))
944 goto show_usage;
945 switch (parse_long_opt(ctx, arg + 2, options)) {
946 case PARSE_OPT_ERROR:
947 return PARSE_OPT_ERROR;
948 case PARSE_OPT_UNKNOWN:
949 goto unknown;
950 case PARSE_OPT_HELP:
951 goto show_usage;
952 case PARSE_OPT_NON_OPTION:
953 case PARSE_OPT_SUBCOMMAND:
954 case PARSE_OPT_COMPLETE:
955 BUG("parse_long_opt() cannot return these");
956 case PARSE_OPT_DONE:
957 break;
959 continue;
960 unknown:
961 if (ctx->flags & PARSE_OPT_ONE_SHOT)
962 break;
963 if (ctx->has_subcommands &&
964 (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL) &&
965 (ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)) {
967 * Found an unknown option given to a command with
968 * subcommands that has a default operation mode:
969 * we treat this option and all remaining args as
970 * arguments meant to that default operation mode.
971 * So we are done parsing.
973 return PARSE_OPT_DONE;
975 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT))
976 return PARSE_OPT_UNKNOWN;
977 ctx->out[ctx->cpidx++] = ctx->argv[0];
978 ctx->opt = NULL;
980 return PARSE_OPT_DONE;
982 show_usage:
983 return usage_with_options_internal(ctx, usagestr, options, 0, 0);
986 int parse_options_end(struct parse_opt_ctx_t *ctx)
988 if (ctx->flags & PARSE_OPT_ONE_SHOT)
989 return ctx->total - ctx->argc;
991 MOVE_ARRAY(ctx->out + ctx->cpidx, ctx->argv, ctx->argc);
992 ctx->out[ctx->cpidx + ctx->argc] = NULL;
993 return ctx->cpidx + ctx->argc;
996 int parse_options(int argc, const char **argv,
997 const char *prefix,
998 const struct option *options,
999 const char * const usagestr[],
1000 enum parse_opt_flags flags)
1002 struct parse_opt_ctx_t ctx;
1003 struct option *real_options;
1005 disallow_abbreviated_options =
1006 git_env_bool("GIT_TEST_DISALLOW_ABBREVIATED_OPTIONS", 0);
1008 memset(&ctx, 0, sizeof(ctx));
1009 real_options = preprocess_options(&ctx, options);
1010 if (real_options)
1011 options = real_options;
1012 parse_options_start_1(&ctx, argc, argv, prefix, options, flags);
1013 switch (parse_options_step(&ctx, options, usagestr)) {
1014 case PARSE_OPT_HELP:
1015 case PARSE_OPT_ERROR:
1016 exit(129);
1017 case PARSE_OPT_COMPLETE:
1018 exit(0);
1019 case PARSE_OPT_NON_OPTION:
1020 case PARSE_OPT_SUBCOMMAND:
1021 break;
1022 case PARSE_OPT_DONE:
1023 if (ctx.has_subcommands &&
1024 !(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
1025 error(_("need a subcommand"));
1026 usage_with_options(usagestr, options);
1028 break;
1029 case PARSE_OPT_UNKNOWN:
1030 if (ctx.argv[0][1] == '-') {
1031 error(_("unknown option `%s'"), ctx.argv[0] + 2);
1032 } else if (isascii(*ctx.opt)) {
1033 error(_("unknown switch `%c'"), *ctx.opt);
1034 } else {
1035 error(_("unknown non-ascii option in string: `%s'"),
1036 ctx.argv[0]);
1038 usage_with_options(usagestr, options);
1041 precompose_argv_prefix(argc, argv, NULL);
1042 free_preprocessed_options(real_options);
1043 free(ctx.alias_groups);
1044 for (struct parse_opt_cmdmode_list *elem = ctx.cmdmode_list; elem;) {
1045 struct parse_opt_cmdmode_list *next = elem->next;
1046 free(elem);
1047 elem = next;
1049 return parse_options_end(&ctx);
1052 static int usage_argh(const struct option *opts, FILE *outfile)
1054 const char *s;
1055 int literal = (opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1056 !opts->argh || !!strpbrk(opts->argh, "()<>[]|");
1057 if (opts->flags & PARSE_OPT_OPTARG)
1058 if (opts->long_name)
1059 s = literal ? "[=%s]" : "[=<%s>]";
1060 else
1061 s = literal ? "[%s]" : "[<%s>]";
1062 else
1063 s = literal ? " %s" : " <%s>";
1064 return utf8_fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
1067 static int usage_indent(FILE *outfile)
1069 return fprintf(outfile, " ");
1072 #define USAGE_OPTS_WIDTH 26
1074 static void usage_padding(FILE *outfile, size_t pos)
1076 if (pos < USAGE_OPTS_WIDTH)
1077 fprintf(outfile, "%*s", USAGE_OPTS_WIDTH - (int)pos, "");
1078 else
1079 fprintf(outfile, "\n%*s", USAGE_OPTS_WIDTH, "");
1082 static const struct option *find_option_by_long_name(const struct option *opts,
1083 const char *long_name)
1085 for (; opts->type != OPTION_END; opts++) {
1086 if (opts->long_name && !strcmp(opts->long_name, long_name))
1087 return opts;
1089 return NULL;
1092 static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t *ctx,
1093 const char * const *usagestr,
1094 const struct option *opts,
1095 int full, int err)
1097 const struct option *all_opts = opts;
1098 FILE *outfile = err ? stderr : stdout;
1099 int need_newline;
1101 const char *usage_prefix = _("usage: %s");
1103 * The translation could be anything, but we can count on
1104 * msgfmt(1)'s --check option to have asserted that "%s" is in
1105 * the translation. So compute the length of the "usage: "
1106 * part. We are assuming that the translator wasn't overly
1107 * clever and used e.g. "%1$s" instead of "%s", there's only
1108 * one "%s" in "usage_prefix" above, so there's no reason to
1109 * do so even with a RTL language.
1111 size_t usage_len = strlen(usage_prefix) - strlen("%s");
1113 * TRANSLATORS: the colon here should align with the
1114 * one in "usage: %s" translation.
1116 const char *or_prefix = _(" or: %s");
1118 * TRANSLATORS: You should only need to translate this format
1119 * string if your language is a RTL language (e.g. Arabic,
1120 * Hebrew etc.), not if it's a LTR language (e.g. German,
1121 * Russian, Chinese etc.).
1123 * When a translated usage string has an embedded "\n" it's
1124 * because options have wrapped to the next line. The line
1125 * after the "\n" will then be padded to align with the
1126 * command name, such as N_("git cmd [opt]\n<8
1127 * spaces>[opt2]"), where the 8 spaces are the same length as
1128 * "git cmd ".
1130 * This format string prints out that already-translated
1131 * line. The "%*s" is whitespace padding to account for the
1132 * padding at the start of the line that we add in this
1133 * function. The "%s" is a line in the (hopefully already
1134 * translated) N_() usage string, which contained embedded
1135 * newlines before we split it up.
1137 const char *usage_continued = _("%*s%s");
1138 const char *prefix = usage_prefix;
1139 int saw_empty_line = 0;
1141 if (!usagestr)
1142 return PARSE_OPT_HELP;
1144 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1145 fprintf(outfile, "cat <<\\EOF\n");
1147 while (*usagestr) {
1148 const char *str = _(*usagestr++);
1149 struct string_list list = STRING_LIST_INIT_DUP;
1150 unsigned int j;
1152 if (!saw_empty_line && !*str)
1153 saw_empty_line = 1;
1155 string_list_split(&list, str, '\n', -1);
1156 for (j = 0; j < list.nr; j++) {
1157 const char *line = list.items[j].string;
1159 if (saw_empty_line && *line)
1160 fprintf_ln(outfile, _(" %s"), line);
1161 else if (saw_empty_line)
1162 fputc('\n', outfile);
1163 else if (!j)
1164 fprintf_ln(outfile, prefix, line);
1165 else
1166 fprintf_ln(outfile, usage_continued,
1167 (int)usage_len, "", line);
1169 string_list_clear(&list, 0);
1171 prefix = or_prefix;
1174 need_newline = 1;
1176 for (; opts->type != OPTION_END; opts++) {
1177 size_t pos;
1178 const char *cp, *np;
1179 const char *positive_name = NULL;
1181 if (opts->type == OPTION_SUBCOMMAND)
1182 continue;
1183 if (opts->type == OPTION_GROUP) {
1184 fputc('\n', outfile);
1185 need_newline = 0;
1186 if (*opts->help)
1187 fprintf(outfile, "%s\n", _(opts->help));
1188 continue;
1190 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
1191 continue;
1193 if (need_newline) {
1194 fputc('\n', outfile);
1195 need_newline = 0;
1198 pos = usage_indent(outfile);
1199 if (opts->short_name) {
1200 if (opts->flags & PARSE_OPT_NODASH)
1201 pos += fprintf(outfile, "%c", opts->short_name);
1202 else
1203 pos += fprintf(outfile, "-%c", opts->short_name);
1205 if (opts->long_name && opts->short_name)
1206 pos += fprintf(outfile, ", ");
1207 if (opts->long_name) {
1208 const char *long_name = opts->long_name;
1209 if ((opts->flags & PARSE_OPT_NONEG) ||
1210 skip_prefix(long_name, "no-", &positive_name))
1211 pos += fprintf(outfile, "--%s", long_name);
1212 else
1213 pos += fprintf(outfile, "--[no-]%s", long_name);
1216 if (opts->type == OPTION_NUMBER)
1217 pos += utf8_fprintf(outfile, _("-NUM"));
1219 if ((opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1220 !(opts->flags & PARSE_OPT_NOARG))
1221 pos += usage_argh(opts, outfile);
1223 if (opts->type == OPTION_ALIAS) {
1224 usage_padding(outfile, pos);
1225 fprintf_ln(outfile, _("alias of --%s"),
1226 (const char *)opts->value);
1227 continue;
1230 for (cp = opts->help ? _(opts->help) : ""; *cp; cp = np) {
1231 np = strchrnul(cp, '\n');
1232 if (*np)
1233 np++;
1234 usage_padding(outfile, pos);
1235 fwrite(cp, 1, np - cp, outfile);
1236 pos = 0;
1238 fputc('\n', outfile);
1240 if (positive_name) {
1241 if (find_option_by_long_name(all_opts, positive_name))
1242 continue;
1243 pos = usage_indent(outfile);
1244 pos += fprintf(outfile, "--%s", positive_name);
1245 usage_padding(outfile, pos);
1246 fprintf_ln(outfile, _("opposite of --no-%s"),
1247 positive_name);
1250 fputc('\n', outfile);
1252 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1253 fputs("EOF\n", outfile);
1255 return PARSE_OPT_HELP;
1258 void NORETURN usage_with_options(const char * const *usagestr,
1259 const struct option *opts)
1261 usage_with_options_internal(NULL, usagestr, opts, 0, 1);
1262 exit(129);
1265 void NORETURN usage_msg_opt(const char *msg,
1266 const char * const *usagestr,
1267 const struct option *options)
1269 die_message("%s\n", msg); /* The extra \n is intentional */
1270 usage_with_options(usagestr, options);
1273 void NORETURN usage_msg_optf(const char * const fmt,
1274 const char * const *usagestr,
1275 const struct option *options, ...)
1277 struct strbuf msg = STRBUF_INIT;
1278 va_list ap;
1279 va_start(ap, options);
1280 strbuf_vaddf(&msg, fmt, ap);
1281 va_end(ap);
1283 usage_msg_opt(msg.buf, usagestr, options);
1286 void die_for_incompatible_opt4(int opt1, const char *opt1_name,
1287 int opt2, const char *opt2_name,
1288 int opt3, const char *opt3_name,
1289 int opt4, const char *opt4_name)
1291 int count = 0;
1292 const char *options[4];
1294 if (opt1)
1295 options[count++] = opt1_name;
1296 if (opt2)
1297 options[count++] = opt2_name;
1298 if (opt3)
1299 options[count++] = opt3_name;
1300 if (opt4)
1301 options[count++] = opt4_name;
1302 switch (count) {
1303 case 4:
1304 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
1305 opt1_name, opt2_name, opt3_name, opt4_name);
1306 break;
1307 case 3:
1308 die(_("options '%s', '%s', and '%s' cannot be used together"),
1309 options[0], options[1], options[2]);
1310 break;
1311 case 2:
1312 die(_("options '%s' and '%s' cannot be used together"),
1313 options[0], options[1]);
1314 break;
1315 default:
1316 break;