blame.h: remove unnecessary includes
[git.git] / parse-options.c
blob6054a3ca5ae4e409ab98913b01fd4e4c557c8d0f
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(_("%s is incompatible with %s"), opt_name, other_opt_name);
281 free(opt_name);
282 free(other_opt_name);
283 return -1;
286 static enum parse_opt_result parse_short_opt(struct parse_opt_ctx_t *p,
287 const struct option *options)
289 const struct option *numopt = NULL;
291 for (; options->type != OPTION_END; options++) {
292 if (options->short_name == *p->opt) {
293 p->opt = p->opt[1] ? p->opt + 1 : NULL;
294 return get_value(p, options, OPT_SHORT);
298 * Handle the numerical option later, explicit one-digit
299 * options take precedence over it.
301 if (options->type == OPTION_NUMBER)
302 numopt = options;
304 if (numopt && isdigit(*p->opt)) {
305 size_t len = 1;
306 char *arg;
307 int rc;
309 while (isdigit(p->opt[len]))
310 len++;
311 arg = xmemdupz(p->opt, len);
312 p->opt = p->opt[len] ? p->opt + len : NULL;
313 if (numopt->callback)
314 rc = (*numopt->callback)(numopt, arg, 0) ? (-1) : 0;
315 else
316 rc = (*numopt->ll_callback)(p, numopt, arg, 0);
317 free(arg);
318 return rc;
320 return PARSE_OPT_UNKNOWN;
323 static int has_string(const char *it, const char **array)
325 while (*array)
326 if (!strcmp(it, *(array++)))
327 return 1;
328 return 0;
331 static int is_alias(struct parse_opt_ctx_t *ctx,
332 const struct option *one_opt,
333 const struct option *another_opt)
335 const char **group;
337 if (!ctx->alias_groups)
338 return 0;
340 if (!one_opt->long_name || !another_opt->long_name)
341 return 0;
343 for (group = ctx->alias_groups; *group; group += 3) {
344 /* it and other are from the same family? */
345 if (has_string(one_opt->long_name, group) &&
346 has_string(another_opt->long_name, group))
347 return 1;
349 return 0;
352 static enum parse_opt_result parse_long_opt(
353 struct parse_opt_ctx_t *p, const char *arg,
354 const struct option *options)
356 const char *arg_end = strchrnul(arg, '=');
357 const struct option *abbrev_option = NULL, *ambiguous_option = NULL;
358 enum opt_parsed abbrev_flags = OPT_LONG, ambiguous_flags = OPT_LONG;
360 for (; options->type != OPTION_END; options++) {
361 const char *rest, *long_name = options->long_name;
362 enum opt_parsed flags = OPT_LONG, opt_flags = OPT_LONG;
364 if (options->type == OPTION_SUBCOMMAND)
365 continue;
366 if (!long_name)
367 continue;
369 again:
370 if (!skip_prefix(arg, long_name, &rest))
371 rest = NULL;
372 if (!rest) {
373 /* abbreviated? */
374 if (!(p->flags & PARSE_OPT_KEEP_UNKNOWN_OPT) &&
375 !strncmp(long_name, arg, arg_end - arg)) {
376 is_abbreviated:
377 if (abbrev_option &&
378 !is_alias(p, abbrev_option, options)) {
380 * If this is abbreviated, it is
381 * ambiguous. So when there is no
382 * exact match later, we need to
383 * error out.
385 ambiguous_option = abbrev_option;
386 ambiguous_flags = abbrev_flags;
388 if (!(flags & OPT_UNSET) && *arg_end)
389 p->opt = arg_end + 1;
390 abbrev_option = options;
391 abbrev_flags = flags ^ opt_flags;
392 continue;
394 /* negation allowed? */
395 if (options->flags & PARSE_OPT_NONEG)
396 continue;
397 /* negated and abbreviated very much? */
398 if (starts_with("no-", arg)) {
399 flags |= OPT_UNSET;
400 goto is_abbreviated;
402 /* negated? */
403 if (!starts_with(arg, "no-")) {
404 if (skip_prefix(long_name, "no-", &long_name)) {
405 opt_flags |= OPT_UNSET;
406 goto again;
408 continue;
410 flags |= OPT_UNSET;
411 if (!skip_prefix(arg + 3, long_name, &rest)) {
412 /* abbreviated and negated? */
413 if (starts_with(long_name, arg + 3))
414 goto is_abbreviated;
415 else
416 continue;
419 if (*rest) {
420 if (*rest != '=')
421 continue;
422 p->opt = rest + 1;
424 return get_value(p, options, flags ^ opt_flags);
427 if (disallow_abbreviated_options && (ambiguous_option || abbrev_option))
428 die("disallowed abbreviated or ambiguous option '%.*s'",
429 (int)(arg_end - arg), arg);
431 if (ambiguous_option) {
432 error(_("ambiguous option: %s "
433 "(could be --%s%s or --%s%s)"),
434 arg,
435 (ambiguous_flags & OPT_UNSET) ? "no-" : "",
436 ambiguous_option->long_name,
437 (abbrev_flags & OPT_UNSET) ? "no-" : "",
438 abbrev_option->long_name);
439 return PARSE_OPT_HELP;
441 if (abbrev_option)
442 return get_value(p, abbrev_option, abbrev_flags);
443 return PARSE_OPT_UNKNOWN;
446 static enum parse_opt_result parse_nodash_opt(struct parse_opt_ctx_t *p,
447 const char *arg,
448 const struct option *options)
450 for (; options->type != OPTION_END; options++) {
451 if (!(options->flags & PARSE_OPT_NODASH))
452 continue;
453 if (options->short_name == arg[0] && arg[1] == '\0')
454 return get_value(p, options, OPT_SHORT);
456 return PARSE_OPT_ERROR;
459 static enum parse_opt_result parse_subcommand(const char *arg,
460 const struct option *options)
462 for (; options->type != OPTION_END; options++)
463 if (options->type == OPTION_SUBCOMMAND &&
464 !strcmp(options->long_name, arg)) {
465 *(parse_opt_subcommand_fn **)options->value = options->subcommand_fn;
466 return PARSE_OPT_SUBCOMMAND;
469 return PARSE_OPT_UNKNOWN;
472 static void check_typos(const char *arg, const struct option *options)
474 if (strlen(arg) < 3)
475 return;
477 if (starts_with(arg, "no-")) {
478 error(_("did you mean `--%s` (with two dashes)?"), arg);
479 exit(129);
482 for (; options->type != OPTION_END; options++) {
483 if (!options->long_name)
484 continue;
485 if (starts_with(options->long_name, arg)) {
486 error(_("did you mean `--%s` (with two dashes)?"), arg);
487 exit(129);
492 static void parse_options_check(const struct option *opts)
494 char short_opts[128];
495 void *subcommand_value = NULL;
497 memset(short_opts, '\0', sizeof(short_opts));
498 for (; opts->type != OPTION_END; opts++) {
499 if ((opts->flags & PARSE_OPT_LASTARG_DEFAULT) &&
500 (opts->flags & PARSE_OPT_OPTARG))
501 optbug(opts, "uses incompatible flags "
502 "LASTARG_DEFAULT and OPTARG");
503 if (opts->short_name) {
504 if (0x7F <= opts->short_name)
505 optbug(opts, "invalid short name");
506 else if (short_opts[opts->short_name]++)
507 optbug(opts, "short name already used");
509 if (opts->flags & PARSE_OPT_NODASH &&
510 ((opts->flags & PARSE_OPT_OPTARG) ||
511 !(opts->flags & PARSE_OPT_NOARG) ||
512 !(opts->flags & PARSE_OPT_NONEG) ||
513 opts->long_name))
514 optbug(opts, "uses feature "
515 "not supported for dashless options");
516 if (opts->type == OPTION_SET_INT && !opts->defval &&
517 opts->long_name && !(opts->flags & PARSE_OPT_NONEG))
518 optbug(opts, "OPTION_SET_INT 0 should not be negatable");
519 switch (opts->type) {
520 case OPTION_COUNTUP:
521 case OPTION_BIT:
522 case OPTION_NEGBIT:
523 case OPTION_SET_INT:
524 case OPTION_NUMBER:
525 if ((opts->flags & PARSE_OPT_OPTARG) ||
526 !(opts->flags & PARSE_OPT_NOARG))
527 optbug(opts, "should not accept an argument");
528 break;
529 case OPTION_CALLBACK:
530 if (!opts->callback && !opts->ll_callback)
531 optbug(opts, "OPTION_CALLBACK needs one callback");
532 else if (opts->callback && opts->ll_callback)
533 optbug(opts, "OPTION_CALLBACK can't have two callbacks");
534 break;
535 case OPTION_LOWLEVEL_CALLBACK:
536 if (!opts->ll_callback)
537 optbug(opts, "OPTION_LOWLEVEL_CALLBACK needs a callback");
538 if (opts->callback)
539 optbug(opts, "OPTION_LOWLEVEL_CALLBACK needs no high level callback");
540 break;
541 case OPTION_ALIAS:
542 optbug(opts, "OPT_ALIAS() should not remain at this point. "
543 "Are you using parse_options_step() directly?\n"
544 "That case is not supported yet.");
545 break;
546 case OPTION_SUBCOMMAND:
547 if (!opts->value || !opts->subcommand_fn)
548 optbug(opts, "OPTION_SUBCOMMAND needs a value and a subcommand function");
549 if (!subcommand_value)
550 subcommand_value = opts->value;
551 else if (subcommand_value != opts->value)
552 optbug(opts, "all OPTION_SUBCOMMANDs need the same value");
553 break;
554 default:
555 ; /* ok. (usually accepts an argument) */
557 if (opts->argh &&
558 strcspn(opts->argh, " _") != strlen(opts->argh))
559 optbug(opts, "multi-word argh should use dash to separate words");
561 BUG_if_bug("invalid 'struct option'");
564 static int has_subcommands(const struct option *options)
566 for (; options->type != OPTION_END; options++)
567 if (options->type == OPTION_SUBCOMMAND)
568 return 1;
569 return 0;
572 static void parse_options_start_1(struct parse_opt_ctx_t *ctx,
573 int argc, const char **argv, const char *prefix,
574 const struct option *options,
575 enum parse_opt_flags flags)
577 ctx->argc = argc;
578 ctx->argv = argv;
579 if (!(flags & PARSE_OPT_ONE_SHOT)) {
580 ctx->argc--;
581 ctx->argv++;
583 ctx->total = ctx->argc;
584 ctx->out = argv;
585 ctx->prefix = prefix;
586 ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
587 ctx->flags = flags;
588 ctx->has_subcommands = has_subcommands(options);
589 if (!ctx->has_subcommands && (flags & PARSE_OPT_SUBCOMMAND_OPTIONAL))
590 BUG("Using PARSE_OPT_SUBCOMMAND_OPTIONAL without subcommands");
591 if (ctx->has_subcommands) {
592 if (flags & PARSE_OPT_STOP_AT_NON_OPTION)
593 BUG("subcommands are incompatible with PARSE_OPT_STOP_AT_NON_OPTION");
594 if (!(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
595 if (flags & PARSE_OPT_KEEP_UNKNOWN_OPT)
596 BUG("subcommands are incompatible with PARSE_OPT_KEEP_UNKNOWN_OPT unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
597 if (flags & PARSE_OPT_KEEP_DASHDASH)
598 BUG("subcommands are incompatible with PARSE_OPT_KEEP_DASHDASH unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
601 if ((flags & PARSE_OPT_KEEP_UNKNOWN_OPT) &&
602 (flags & PARSE_OPT_STOP_AT_NON_OPTION) &&
603 !(flags & PARSE_OPT_ONE_SHOT))
604 BUG("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
605 if ((flags & PARSE_OPT_ONE_SHOT) &&
606 (flags & PARSE_OPT_KEEP_ARGV0))
607 BUG("Can't keep argv0 if you don't have it");
608 parse_options_check(options);
609 build_cmdmode_list(ctx, options);
612 void parse_options_start(struct parse_opt_ctx_t *ctx,
613 int argc, const char **argv, const char *prefix,
614 const struct option *options,
615 enum parse_opt_flags flags)
617 memset(ctx, 0, sizeof(*ctx));
618 parse_options_start_1(ctx, argc, argv, prefix, options, flags);
621 static void show_negated_gitcomp(const struct option *opts, int show_all,
622 int nr_noopts)
624 int printed_dashdash = 0;
626 for (; opts->type != OPTION_END; opts++) {
627 int has_unset_form = 0;
628 const char *name;
630 if (!opts->long_name)
631 continue;
632 if (!show_all &&
633 (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE)))
634 continue;
635 if (opts->flags & PARSE_OPT_NONEG)
636 continue;
638 switch (opts->type) {
639 case OPTION_STRING:
640 case OPTION_FILENAME:
641 case OPTION_INTEGER:
642 case OPTION_MAGNITUDE:
643 case OPTION_CALLBACK:
644 case OPTION_BIT:
645 case OPTION_NEGBIT:
646 case OPTION_COUNTUP:
647 case OPTION_SET_INT:
648 has_unset_form = 1;
649 break;
650 default:
651 break;
653 if (!has_unset_form)
654 continue;
656 if (skip_prefix(opts->long_name, "no-", &name)) {
657 if (nr_noopts < 0)
658 printf(" --%s", name);
659 } else if (nr_noopts >= 0) {
660 if (nr_noopts && !printed_dashdash) {
661 printf(" --");
662 printed_dashdash = 1;
664 printf(" --no-%s", opts->long_name);
665 nr_noopts++;
670 static int show_gitcomp(const struct option *opts, int show_all)
672 const struct option *original_opts = opts;
673 int nr_noopts = 0;
675 for (; opts->type != OPTION_END; opts++) {
676 const char *prefix = "--";
677 const char *suffix = "";
679 if (!opts->long_name)
680 continue;
681 if (!show_all &&
682 (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE | PARSE_OPT_FROM_ALIAS)))
683 continue;
685 switch (opts->type) {
686 case OPTION_SUBCOMMAND:
687 prefix = "";
688 break;
689 case OPTION_GROUP:
690 continue;
691 case OPTION_STRING:
692 case OPTION_FILENAME:
693 case OPTION_INTEGER:
694 case OPTION_MAGNITUDE:
695 case OPTION_CALLBACK:
696 if (opts->flags & PARSE_OPT_NOARG)
697 break;
698 if (opts->flags & PARSE_OPT_OPTARG)
699 break;
700 if (opts->flags & PARSE_OPT_LASTARG_DEFAULT)
701 break;
702 suffix = "=";
703 break;
704 default:
705 break;
707 if (opts->flags & PARSE_OPT_COMP_ARG)
708 suffix = "=";
709 if (starts_with(opts->long_name, "no-"))
710 nr_noopts++;
711 printf("%s%s%s%s", opts == original_opts ? "" : " ",
712 prefix, opts->long_name, suffix);
714 show_negated_gitcomp(original_opts, show_all, -1);
715 show_negated_gitcomp(original_opts, show_all, nr_noopts);
716 fputc('\n', stdout);
717 return PARSE_OPT_COMPLETE;
721 * Scan and may produce a new option[] array, which should be used
722 * instead of the original 'options'.
724 * Right now this is only used to preprocess and substitute
725 * OPTION_ALIAS.
727 * The returned options should be freed using free_preprocessed_options.
729 static struct option *preprocess_options(struct parse_opt_ctx_t *ctx,
730 const struct option *options)
732 struct option *newopt;
733 int i, nr, alias;
734 int nr_aliases = 0;
736 for (nr = 0; options[nr].type != OPTION_END; nr++) {
737 if (options[nr].type == OPTION_ALIAS)
738 nr_aliases++;
741 if (!nr_aliases)
742 return NULL;
744 DUP_ARRAY(newopt, options, nr + 1);
746 /* each alias has two string pointers and NULL */
747 CALLOC_ARRAY(ctx->alias_groups, 3 * (nr_aliases + 1));
749 for (alias = 0, i = 0; i < nr; i++) {
750 int short_name;
751 const char *long_name;
752 const char *source;
753 struct strbuf help = STRBUF_INIT;
754 int j;
756 if (newopt[i].type != OPTION_ALIAS)
757 continue;
759 short_name = newopt[i].short_name;
760 long_name = newopt[i].long_name;
761 source = newopt[i].value;
763 if (!long_name)
764 BUG("An alias must have long option name");
765 strbuf_addf(&help, _("alias of --%s"), source);
767 for (j = 0; j < nr; j++) {
768 const char *name = options[j].long_name;
770 if (!name || strcmp(name, source))
771 continue;
773 if (options[j].type == OPTION_ALIAS)
774 BUG("No please. Nested aliases are not supported.");
776 memcpy(newopt + i, options + j, sizeof(*newopt));
777 newopt[i].short_name = short_name;
778 newopt[i].long_name = long_name;
779 newopt[i].help = strbuf_detach(&help, NULL);
780 newopt[i].flags |= PARSE_OPT_FROM_ALIAS;
781 break;
784 if (j == nr)
785 BUG("could not find source option '%s' of alias '%s'",
786 source, newopt[i].long_name);
787 ctx->alias_groups[alias * 3 + 0] = newopt[i].long_name;
788 ctx->alias_groups[alias * 3 + 1] = options[j].long_name;
789 ctx->alias_groups[alias * 3 + 2] = NULL;
790 alias++;
793 return newopt;
796 static void free_preprocessed_options(struct option *options)
798 int i;
800 if (!options)
801 return;
803 for (i = 0; options[i].type != OPTION_END; i++) {
804 if (options[i].flags & PARSE_OPT_FROM_ALIAS)
805 free((void *)options[i].help);
807 free(options);
810 static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t *,
811 const char * const *,
812 const struct option *,
813 int, int);
815 enum parse_opt_result parse_options_step(struct parse_opt_ctx_t *ctx,
816 const struct option *options,
817 const char * const usagestr[])
819 int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
821 /* we must reset ->opt, unknown short option leave it dangling */
822 ctx->opt = NULL;
824 for (; ctx->argc; ctx->argc--, ctx->argv++) {
825 const char *arg = ctx->argv[0];
827 if (ctx->flags & PARSE_OPT_ONE_SHOT &&
828 ctx->argc != ctx->total)
829 break;
831 if (*arg != '-' || !arg[1]) {
832 if (parse_nodash_opt(ctx, arg, options) == 0)
833 continue;
834 if (!ctx->has_subcommands) {
835 if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
836 return PARSE_OPT_NON_OPTION;
837 ctx->out[ctx->cpidx++] = ctx->argv[0];
838 continue;
840 switch (parse_subcommand(arg, options)) {
841 case PARSE_OPT_SUBCOMMAND:
842 return PARSE_OPT_SUBCOMMAND;
843 case PARSE_OPT_UNKNOWN:
844 if (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)
846 * arg is neither a short or long
847 * option nor a subcommand. Since
848 * this command has a default
849 * operation mode, we have to treat
850 * this arg and all remaining args
851 * as args meant to that default
852 * operation mode.
853 * So we are done parsing.
855 return PARSE_OPT_DONE;
856 error(_("unknown subcommand: `%s'"), arg);
857 usage_with_options(usagestr, options);
858 case PARSE_OPT_COMPLETE:
859 case PARSE_OPT_HELP:
860 case PARSE_OPT_ERROR:
861 case PARSE_OPT_DONE:
862 case PARSE_OPT_NON_OPTION:
863 /* Impossible. */
864 BUG("parse_subcommand() cannot return these");
868 /* lone -h asks for help */
869 if (internal_help && ctx->total == 1 && !strcmp(arg + 1, "h"))
870 goto show_usage;
873 * lone --git-completion-helper and --git-completion-helper-all
874 * are asked by git-completion.bash
876 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper"))
877 return show_gitcomp(options, 0);
878 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper-all"))
879 return show_gitcomp(options, 1);
881 if (arg[1] != '-') {
882 ctx->opt = arg + 1;
883 switch (parse_short_opt(ctx, options)) {
884 case PARSE_OPT_ERROR:
885 return PARSE_OPT_ERROR;
886 case PARSE_OPT_UNKNOWN:
887 if (ctx->opt)
888 check_typos(arg + 1, options);
889 if (internal_help && *ctx->opt == 'h')
890 goto show_usage;
891 goto unknown;
892 case PARSE_OPT_NON_OPTION:
893 case PARSE_OPT_SUBCOMMAND:
894 case PARSE_OPT_HELP:
895 case PARSE_OPT_COMPLETE:
896 BUG("parse_short_opt() cannot return these");
897 case PARSE_OPT_DONE:
898 break;
900 if (ctx->opt)
901 check_typos(arg + 1, options);
902 while (ctx->opt) {
903 switch (parse_short_opt(ctx, options)) {
904 case PARSE_OPT_ERROR:
905 return PARSE_OPT_ERROR;
906 case PARSE_OPT_UNKNOWN:
907 if (internal_help && *ctx->opt == 'h')
908 goto show_usage;
910 /* fake a short option thing to hide the fact that we may have
911 * started to parse aggregated stuff
913 * This is leaky, too bad.
915 ctx->argv[0] = xstrdup(ctx->opt - 1);
916 *(char *)ctx->argv[0] = '-';
917 goto unknown;
918 case PARSE_OPT_NON_OPTION:
919 case PARSE_OPT_SUBCOMMAND:
920 case PARSE_OPT_COMPLETE:
921 case PARSE_OPT_HELP:
922 BUG("parse_short_opt() cannot return these");
923 case PARSE_OPT_DONE:
924 break;
927 continue;
930 if (!arg[2] /* "--" */ ||
931 !strcmp(arg + 2, "end-of-options")) {
932 if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
933 ctx->argc--;
934 ctx->argv++;
936 break;
939 if (internal_help && !strcmp(arg + 2, "help-all"))
940 return usage_with_options_internal(ctx, usagestr, options, 1, 0);
941 if (internal_help && !strcmp(arg + 2, "help"))
942 goto show_usage;
943 switch (parse_long_opt(ctx, arg + 2, options)) {
944 case PARSE_OPT_ERROR:
945 return PARSE_OPT_ERROR;
946 case PARSE_OPT_UNKNOWN:
947 goto unknown;
948 case PARSE_OPT_HELP:
949 goto show_usage;
950 case PARSE_OPT_NON_OPTION:
951 case PARSE_OPT_SUBCOMMAND:
952 case PARSE_OPT_COMPLETE:
953 BUG("parse_long_opt() cannot return these");
954 case PARSE_OPT_DONE:
955 break;
957 continue;
958 unknown:
959 if (ctx->flags & PARSE_OPT_ONE_SHOT)
960 break;
961 if (ctx->has_subcommands &&
962 (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL) &&
963 (ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)) {
965 * Found an unknown option given to a command with
966 * subcommands that has a default operation mode:
967 * we treat this option and all remaining args as
968 * arguments meant to that default operation mode.
969 * So we are done parsing.
971 return PARSE_OPT_DONE;
973 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT))
974 return PARSE_OPT_UNKNOWN;
975 ctx->out[ctx->cpidx++] = ctx->argv[0];
976 ctx->opt = NULL;
978 return PARSE_OPT_DONE;
980 show_usage:
981 return usage_with_options_internal(ctx, usagestr, options, 0, 0);
984 int parse_options_end(struct parse_opt_ctx_t *ctx)
986 if (ctx->flags & PARSE_OPT_ONE_SHOT)
987 return ctx->total - ctx->argc;
989 MOVE_ARRAY(ctx->out + ctx->cpidx, ctx->argv, ctx->argc);
990 ctx->out[ctx->cpidx + ctx->argc] = NULL;
991 return ctx->cpidx + ctx->argc;
994 int parse_options(int argc, const char **argv,
995 const char *prefix,
996 const struct option *options,
997 const char * const usagestr[],
998 enum parse_opt_flags flags)
1000 struct parse_opt_ctx_t ctx;
1001 struct option *real_options;
1003 disallow_abbreviated_options =
1004 git_env_bool("GIT_TEST_DISALLOW_ABBREVIATED_OPTIONS", 0);
1006 memset(&ctx, 0, sizeof(ctx));
1007 real_options = preprocess_options(&ctx, options);
1008 if (real_options)
1009 options = real_options;
1010 parse_options_start_1(&ctx, argc, argv, prefix, options, flags);
1011 switch (parse_options_step(&ctx, options, usagestr)) {
1012 case PARSE_OPT_HELP:
1013 case PARSE_OPT_ERROR:
1014 exit(129);
1015 case PARSE_OPT_COMPLETE:
1016 exit(0);
1017 case PARSE_OPT_NON_OPTION:
1018 case PARSE_OPT_SUBCOMMAND:
1019 break;
1020 case PARSE_OPT_DONE:
1021 if (ctx.has_subcommands &&
1022 !(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
1023 error(_("need a subcommand"));
1024 usage_with_options(usagestr, options);
1026 break;
1027 case PARSE_OPT_UNKNOWN:
1028 if (ctx.argv[0][1] == '-') {
1029 error(_("unknown option `%s'"), ctx.argv[0] + 2);
1030 } else if (isascii(*ctx.opt)) {
1031 error(_("unknown switch `%c'"), *ctx.opt);
1032 } else {
1033 error(_("unknown non-ascii option in string: `%s'"),
1034 ctx.argv[0]);
1036 usage_with_options(usagestr, options);
1039 precompose_argv_prefix(argc, argv, NULL);
1040 free_preprocessed_options(real_options);
1041 free(ctx.alias_groups);
1042 for (struct parse_opt_cmdmode_list *elem = ctx.cmdmode_list; elem;) {
1043 struct parse_opt_cmdmode_list *next = elem->next;
1044 free(elem);
1045 elem = next;
1047 return parse_options_end(&ctx);
1050 static int usage_argh(const struct option *opts, FILE *outfile)
1052 const char *s;
1053 int literal = (opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1054 !opts->argh || !!strpbrk(opts->argh, "()<>[]|");
1055 if (opts->flags & PARSE_OPT_OPTARG)
1056 if (opts->long_name)
1057 s = literal ? "[=%s]" : "[=<%s>]";
1058 else
1059 s = literal ? "[%s]" : "[<%s>]";
1060 else
1061 s = literal ? " %s" : " <%s>";
1062 return utf8_fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
1065 static int usage_indent(FILE *outfile)
1067 return fprintf(outfile, " ");
1070 #define USAGE_OPTS_WIDTH 26
1072 static void usage_padding(FILE *outfile, size_t pos)
1074 if (pos < USAGE_OPTS_WIDTH)
1075 fprintf(outfile, "%*s", USAGE_OPTS_WIDTH - (int)pos, "");
1076 else
1077 fprintf(outfile, "\n%*s", USAGE_OPTS_WIDTH, "");
1080 static const struct option *find_option_by_long_name(const struct option *opts,
1081 const char *long_name)
1083 for (; opts->type != OPTION_END; opts++) {
1084 if (opts->long_name && !strcmp(opts->long_name, long_name))
1085 return opts;
1087 return NULL;
1090 static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t *ctx,
1091 const char * const *usagestr,
1092 const struct option *opts,
1093 int full, int err)
1095 const struct option *all_opts = opts;
1096 FILE *outfile = err ? stderr : stdout;
1097 int need_newline;
1099 const char *usage_prefix = _("usage: %s");
1101 * The translation could be anything, but we can count on
1102 * msgfmt(1)'s --check option to have asserted that "%s" is in
1103 * the translation. So compute the length of the "usage: "
1104 * part. We are assuming that the translator wasn't overly
1105 * clever and used e.g. "%1$s" instead of "%s", there's only
1106 * one "%s" in "usage_prefix" above, so there's no reason to
1107 * do so even with a RTL language.
1109 size_t usage_len = strlen(usage_prefix) - strlen("%s");
1111 * TRANSLATORS: the colon here should align with the
1112 * one in "usage: %s" translation.
1114 const char *or_prefix = _(" or: %s");
1116 * TRANSLATORS: You should only need to translate this format
1117 * string if your language is a RTL language (e.g. Arabic,
1118 * Hebrew etc.), not if it's a LTR language (e.g. German,
1119 * Russian, Chinese etc.).
1121 * When a translated usage string has an embedded "\n" it's
1122 * because options have wrapped to the next line. The line
1123 * after the "\n" will then be padded to align with the
1124 * command name, such as N_("git cmd [opt]\n<8
1125 * spaces>[opt2]"), where the 8 spaces are the same length as
1126 * "git cmd ".
1128 * This format string prints out that already-translated
1129 * line. The "%*s" is whitespace padding to account for the
1130 * padding at the start of the line that we add in this
1131 * function. The "%s" is a line in the (hopefully already
1132 * translated) N_() usage string, which contained embedded
1133 * newlines before we split it up.
1135 const char *usage_continued = _("%*s%s");
1136 const char *prefix = usage_prefix;
1137 int saw_empty_line = 0;
1139 if (!usagestr)
1140 return PARSE_OPT_HELP;
1142 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1143 fprintf(outfile, "cat <<\\EOF\n");
1145 while (*usagestr) {
1146 const char *str = _(*usagestr++);
1147 struct string_list list = STRING_LIST_INIT_DUP;
1148 unsigned int j;
1150 if (!saw_empty_line && !*str)
1151 saw_empty_line = 1;
1153 string_list_split(&list, str, '\n', -1);
1154 for (j = 0; j < list.nr; j++) {
1155 const char *line = list.items[j].string;
1157 if (saw_empty_line && *line)
1158 fprintf_ln(outfile, _(" %s"), line);
1159 else if (saw_empty_line)
1160 fputc('\n', outfile);
1161 else if (!j)
1162 fprintf_ln(outfile, prefix, line);
1163 else
1164 fprintf_ln(outfile, usage_continued,
1165 (int)usage_len, "", line);
1167 string_list_clear(&list, 0);
1169 prefix = or_prefix;
1172 need_newline = 1;
1174 for (; opts->type != OPTION_END; opts++) {
1175 size_t pos;
1176 const char *cp, *np;
1177 const char *positive_name = NULL;
1179 if (opts->type == OPTION_SUBCOMMAND)
1180 continue;
1181 if (opts->type == OPTION_GROUP) {
1182 fputc('\n', outfile);
1183 need_newline = 0;
1184 if (*opts->help)
1185 fprintf(outfile, "%s\n", _(opts->help));
1186 continue;
1188 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
1189 continue;
1191 if (need_newline) {
1192 fputc('\n', outfile);
1193 need_newline = 0;
1196 pos = usage_indent(outfile);
1197 if (opts->short_name) {
1198 if (opts->flags & PARSE_OPT_NODASH)
1199 pos += fprintf(outfile, "%c", opts->short_name);
1200 else
1201 pos += fprintf(outfile, "-%c", opts->short_name);
1203 if (opts->long_name && opts->short_name)
1204 pos += fprintf(outfile, ", ");
1205 if (opts->long_name) {
1206 const char *long_name = opts->long_name;
1207 if ((opts->flags & PARSE_OPT_NONEG) ||
1208 skip_prefix(long_name, "no-", &positive_name))
1209 pos += fprintf(outfile, "--%s", long_name);
1210 else
1211 pos += fprintf(outfile, "--[no-]%s", long_name);
1214 if (opts->type == OPTION_NUMBER)
1215 pos += utf8_fprintf(outfile, _("-NUM"));
1217 if ((opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1218 !(opts->flags & PARSE_OPT_NOARG))
1219 pos += usage_argh(opts, outfile);
1221 if (opts->type == OPTION_ALIAS) {
1222 usage_padding(outfile, pos);
1223 fprintf_ln(outfile, _("alias of --%s"),
1224 (const char *)opts->value);
1225 continue;
1228 for (cp = opts->help ? _(opts->help) : ""; *cp; cp = np) {
1229 np = strchrnul(cp, '\n');
1230 if (*np)
1231 np++;
1232 usage_padding(outfile, pos);
1233 fwrite(cp, 1, np - cp, outfile);
1234 pos = 0;
1236 fputc('\n', outfile);
1238 if (positive_name) {
1239 if (find_option_by_long_name(all_opts, positive_name))
1240 continue;
1241 pos = usage_indent(outfile);
1242 pos += fprintf(outfile, "--%s", positive_name);
1243 usage_padding(outfile, pos);
1244 fprintf_ln(outfile, _("opposite of --no-%s"),
1245 positive_name);
1248 fputc('\n', outfile);
1250 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1251 fputs("EOF\n", outfile);
1253 return PARSE_OPT_HELP;
1256 void NORETURN usage_with_options(const char * const *usagestr,
1257 const struct option *opts)
1259 usage_with_options_internal(NULL, usagestr, opts, 0, 1);
1260 exit(129);
1263 void NORETURN usage_msg_opt(const char *msg,
1264 const char * const *usagestr,
1265 const struct option *options)
1267 die_message("%s\n", msg); /* The extra \n is intentional */
1268 usage_with_options(usagestr, options);
1271 void NORETURN usage_msg_optf(const char * const fmt,
1272 const char * const *usagestr,
1273 const struct option *options, ...)
1275 struct strbuf msg = STRBUF_INIT;
1276 va_list ap;
1277 va_start(ap, options);
1278 strbuf_vaddf(&msg, fmt, ap);
1279 va_end(ap);
1281 usage_msg_opt(msg.buf, usagestr, options);
1284 void die_for_incompatible_opt4(int opt1, const char *opt1_name,
1285 int opt2, const char *opt2_name,
1286 int opt3, const char *opt3_name,
1287 int opt4, const char *opt4_name)
1289 int count = 0;
1290 const char *options[4];
1292 if (opt1)
1293 options[count++] = opt1_name;
1294 if (opt2)
1295 options[count++] = opt2_name;
1296 if (opt3)
1297 options[count++] = opt3_name;
1298 if (opt4)
1299 options[count++] = opt4_name;
1300 switch (count) {
1301 case 4:
1302 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
1303 opt1_name, opt2_name, opt3_name, opt4_name);
1304 break;
1305 case 3:
1306 die(_("options '%s', '%s', and '%s' cannot be used together"),
1307 options[0], options[1], options[2]);
1308 break;
1309 case 2:
1310 die(_("options '%s' and '%s' cannot be used together"),
1311 options[0], options[1]);
1312 break;
1313 default:
1314 break;