Start the 2.48 cycle
[git/gitster.git] / parse-options.c
blob33bfba0ed4a0eaad1bb3ce61876d6c01b6d2c6aa
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 char *fix_filename(const char *prefix, const char *file)
65 if (!file || !*file)
66 return NULL;
67 else
68 return 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:
133 const char *value;
135 FREE_AND_NULL(*(char **)opt->value);
137 err = 0;
139 if (unset)
140 value = NULL;
141 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
142 value = (const char *) opt->defval;
143 else
144 err = get_arg(p, opt, flags, &value);
146 if (!err)
147 *(char **)opt->value = fix_filename(p->prefix, value);
148 return err;
150 case OPTION_CALLBACK:
152 const char *p_arg = NULL;
153 int p_unset;
155 if (unset)
156 p_unset = 1;
157 else if (opt->flags & PARSE_OPT_NOARG)
158 p_unset = 0;
159 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
160 p_unset = 0;
161 else if (get_arg(p, opt, flags, &arg))
162 return -1;
163 else {
164 p_unset = 0;
165 p_arg = arg;
167 if (opt->flags & PARSE_OPT_CMDMODE)
168 *argp = p_arg;
169 if (opt->callback)
170 return (*opt->callback)(opt, p_arg, p_unset) ? (-1) : 0;
171 else
172 return (*opt->ll_callback)(p, opt, p_arg, p_unset);
174 case OPTION_INTEGER:
175 if (unset) {
176 *(int *)opt->value = 0;
177 return 0;
179 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
180 *(int *)opt->value = opt->defval;
181 return 0;
183 if (get_arg(p, opt, flags, &arg))
184 return -1;
185 if (!*arg)
186 return error(_("%s expects a numerical value"),
187 optname(opt, flags));
188 *(int *)opt->value = strtol(arg, (char **)&s, 10);
189 if (*s)
190 return error(_("%s expects a numerical value"),
191 optname(opt, flags));
192 return 0;
194 case OPTION_MAGNITUDE:
195 if (unset) {
196 *(unsigned long *)opt->value = 0;
197 return 0;
199 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
200 *(unsigned long *)opt->value = opt->defval;
201 return 0;
203 if (get_arg(p, opt, flags, &arg))
204 return -1;
205 if (!git_parse_ulong(arg, opt->value))
206 return error(_("%s expects a non-negative integer value"
207 " with an optional k/m/g suffix"),
208 optname(opt, flags));
209 return 0;
211 default:
212 BUG("opt->type %d should not happen", opt->type);
216 struct parse_opt_cmdmode_list {
217 int value, *value_ptr;
218 const struct option *opt;
219 const char *arg;
220 enum opt_parsed flags;
221 struct parse_opt_cmdmode_list *next;
224 static void build_cmdmode_list(struct parse_opt_ctx_t *ctx,
225 const struct option *opts)
227 ctx->cmdmode_list = NULL;
229 for (; opts->type != OPTION_END; opts++) {
230 struct parse_opt_cmdmode_list *elem = ctx->cmdmode_list;
231 int *value_ptr = opts->value;
233 if (!(opts->flags & PARSE_OPT_CMDMODE) || !value_ptr)
234 continue;
236 while (elem && elem->value_ptr != value_ptr)
237 elem = elem->next;
238 if (elem)
239 continue;
241 CALLOC_ARRAY(elem, 1);
242 elem->value_ptr = value_ptr;
243 elem->value = *value_ptr;
244 elem->next = ctx->cmdmode_list;
245 ctx->cmdmode_list = elem;
249 static char *optnamearg(const struct option *opt, const char *arg,
250 enum opt_parsed flags)
252 if (flags & OPT_SHORT)
253 return xstrfmt("-%c%s", opt->short_name, arg ? arg : "");
254 return xstrfmt("--%s%s%s%s", flags & OPT_UNSET ? "no-" : "",
255 opt->long_name, arg ? "=" : "", arg ? arg : "");
258 static enum parse_opt_result get_value(struct parse_opt_ctx_t *p,
259 const struct option *opt,
260 enum opt_parsed flags)
262 const char *arg = NULL;
263 enum parse_opt_result result = do_get_value(p, opt, flags, &arg);
264 struct parse_opt_cmdmode_list *elem = p->cmdmode_list;
265 char *opt_name, *other_opt_name;
267 for (; elem; elem = elem->next) {
268 if (*elem->value_ptr == elem->value)
269 continue;
271 if (elem->opt &&
272 (elem->opt->flags | opt->flags) & PARSE_OPT_CMDMODE)
273 break;
275 elem->opt = opt;
276 elem->arg = arg;
277 elem->flags = flags;
278 elem->value = *elem->value_ptr;
281 if (result || !elem)
282 return result;
284 opt_name = optnamearg(opt, arg, flags);
285 other_opt_name = optnamearg(elem->opt, elem->arg, elem->flags);
286 error(_("options '%s' and '%s' cannot be used together"),
287 opt_name, other_opt_name);
288 free(opt_name);
289 free(other_opt_name);
290 return -1;
293 static enum parse_opt_result parse_short_opt(struct parse_opt_ctx_t *p,
294 const struct option *options)
296 const struct option *numopt = NULL;
298 for (; options->type != OPTION_END; options++) {
299 if (options->short_name == *p->opt) {
300 p->opt = p->opt[1] ? p->opt + 1 : NULL;
301 return get_value(p, options, OPT_SHORT);
305 * Handle the numerical option later, explicit one-digit
306 * options take precedence over it.
308 if (options->type == OPTION_NUMBER)
309 numopt = options;
311 if (numopt && isdigit(*p->opt)) {
312 size_t len = 1;
313 char *arg;
314 int rc;
316 while (isdigit(p->opt[len]))
317 len++;
318 arg = xmemdupz(p->opt, len);
319 p->opt = p->opt[len] ? p->opt + len : NULL;
320 if (numopt->callback)
321 rc = (*numopt->callback)(numopt, arg, 0) ? (-1) : 0;
322 else
323 rc = (*numopt->ll_callback)(p, numopt, arg, 0);
324 free(arg);
325 return rc;
327 return PARSE_OPT_UNKNOWN;
330 static int has_string(const char *it, const char **array)
332 while (*array)
333 if (!strcmp(it, *(array++)))
334 return 1;
335 return 0;
338 static int is_alias(struct parse_opt_ctx_t *ctx,
339 const struct option *one_opt,
340 const struct option *another_opt)
342 const char **group;
344 if (!ctx->alias_groups)
345 return 0;
347 if (!one_opt->long_name || !another_opt->long_name)
348 return 0;
350 for (group = ctx->alias_groups; *group; group += 3) {
351 /* it and other are from the same family? */
352 if (has_string(one_opt->long_name, group) &&
353 has_string(another_opt->long_name, group))
354 return 1;
356 return 0;
359 struct parsed_option {
360 const struct option *option;
361 enum opt_parsed flags;
364 static void register_abbrev(struct parse_opt_ctx_t *p,
365 const struct option *option, enum opt_parsed flags,
366 struct parsed_option *abbrev,
367 struct parsed_option *ambiguous)
369 if (p->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)
370 return;
371 if (abbrev->option &&
372 !(abbrev->flags == flags && is_alias(p, abbrev->option, option))) {
374 * If this is abbreviated, it is
375 * ambiguous. So when there is no
376 * exact match later, we need to
377 * error out.
379 ambiguous->option = abbrev->option;
380 ambiguous->flags = abbrev->flags;
382 abbrev->option = option;
383 abbrev->flags = flags;
386 static enum parse_opt_result parse_long_opt(
387 struct parse_opt_ctx_t *p, const char *arg,
388 const struct option *options)
390 const char *arg_end = strchrnul(arg, '=');
391 const char *arg_start = arg;
392 enum opt_parsed flags = OPT_LONG;
393 int arg_starts_with_no_no = 0;
394 struct parsed_option abbrev = { .option = NULL, .flags = OPT_LONG };
395 struct parsed_option ambiguous = { .option = NULL, .flags = OPT_LONG };
397 if (skip_prefix(arg_start, "no-", &arg_start)) {
398 if (skip_prefix(arg_start, "no-", &arg_start))
399 arg_starts_with_no_no = 1;
400 else
401 flags |= OPT_UNSET;
404 for (; options->type != OPTION_END; options++) {
405 const char *rest, *long_name = options->long_name;
406 enum opt_parsed opt_flags = OPT_LONG;
407 int allow_unset = !(options->flags & PARSE_OPT_NONEG);
409 if (options->type == OPTION_SUBCOMMAND)
410 continue;
411 if (!long_name)
412 continue;
414 if (skip_prefix(long_name, "no-", &long_name))
415 opt_flags |= OPT_UNSET;
416 else if (arg_starts_with_no_no)
417 continue;
419 if (((flags ^ opt_flags) & OPT_UNSET) && !allow_unset)
420 continue;
422 if (skip_prefix(arg_start, long_name, &rest)) {
423 if (*rest == '=')
424 p->opt = rest + 1;
425 else if (*rest)
426 continue;
427 return get_value(p, options, flags ^ opt_flags);
430 /* abbreviated? */
431 if (!strncmp(long_name, arg_start, arg_end - arg_start))
432 register_abbrev(p, options, flags ^ opt_flags,
433 &abbrev, &ambiguous);
435 /* negated and abbreviated very much? */
436 if (allow_unset && starts_with("no-", arg))
437 register_abbrev(p, options, OPT_UNSET ^ opt_flags,
438 &abbrev, &ambiguous);
441 if (disallow_abbreviated_options && (ambiguous.option || abbrev.option))
442 die("disallowed abbreviated or ambiguous option '%.*s'",
443 (int)(arg_end - arg), arg);
445 if (ambiguous.option) {
446 error(_("ambiguous option: %s "
447 "(could be --%s%s or --%s%s)"),
448 arg,
449 (ambiguous.flags & OPT_UNSET) ? "no-" : "",
450 ambiguous.option->long_name,
451 (abbrev.flags & OPT_UNSET) ? "no-" : "",
452 abbrev.option->long_name);
453 return PARSE_OPT_HELP;
455 if (abbrev.option) {
456 if (*arg_end)
457 p->opt = arg_end + 1;
458 return get_value(p, abbrev.option, abbrev.flags);
460 return PARSE_OPT_UNKNOWN;
463 static enum parse_opt_result parse_nodash_opt(struct parse_opt_ctx_t *p,
464 const char *arg,
465 const struct option *options)
467 for (; options->type != OPTION_END; options++) {
468 if (!(options->flags & PARSE_OPT_NODASH))
469 continue;
470 if (options->short_name == arg[0] && arg[1] == '\0')
471 return get_value(p, options, OPT_SHORT);
473 return PARSE_OPT_ERROR;
476 static enum parse_opt_result parse_subcommand(const char *arg,
477 const struct option *options)
479 for (; options->type != OPTION_END; options++)
480 if (options->type == OPTION_SUBCOMMAND &&
481 !strcmp(options->long_name, arg)) {
482 *(parse_opt_subcommand_fn **)options->value = options->subcommand_fn;
483 return PARSE_OPT_SUBCOMMAND;
486 return PARSE_OPT_UNKNOWN;
489 static void check_typos(const char *arg, const struct option *options)
491 if (strlen(arg) < 3)
492 return;
494 if (starts_with(arg, "no-")) {
495 error(_("did you mean `--%s` (with two dashes)?"), arg);
496 exit(129);
499 for (; options->type != OPTION_END; options++) {
500 if (!options->long_name)
501 continue;
502 if (starts_with(options->long_name, arg)) {
503 error(_("did you mean `--%s` (with two dashes)?"), arg);
504 exit(129);
509 static void parse_options_check(const struct option *opts)
511 char short_opts[128];
512 void *subcommand_value = NULL;
514 memset(short_opts, '\0', sizeof(short_opts));
515 for (; opts->type != OPTION_END; opts++) {
516 if ((opts->flags & PARSE_OPT_LASTARG_DEFAULT) &&
517 (opts->flags & PARSE_OPT_OPTARG))
518 optbug(opts, "uses incompatible flags "
519 "LASTARG_DEFAULT and OPTARG");
520 if (opts->short_name) {
521 if (0x7F <= opts->short_name)
522 optbug(opts, "invalid short name");
523 else if (short_opts[opts->short_name]++)
524 optbug(opts, "short name already used");
526 if (opts->flags & PARSE_OPT_NODASH &&
527 ((opts->flags & PARSE_OPT_OPTARG) ||
528 !(opts->flags & PARSE_OPT_NOARG) ||
529 !(opts->flags & PARSE_OPT_NONEG) ||
530 opts->long_name))
531 optbug(opts, "uses feature "
532 "not supported for dashless options");
533 if (opts->type == OPTION_SET_INT && !opts->defval &&
534 opts->long_name && !(opts->flags & PARSE_OPT_NONEG))
535 optbug(opts, "OPTION_SET_INT 0 should not be negatable");
536 switch (opts->type) {
537 case OPTION_COUNTUP:
538 case OPTION_BIT:
539 case OPTION_NEGBIT:
540 case OPTION_SET_INT:
541 case OPTION_NUMBER:
542 if ((opts->flags & PARSE_OPT_OPTARG) ||
543 !(opts->flags & PARSE_OPT_NOARG))
544 optbug(opts, "should not accept an argument");
545 break;
546 case OPTION_CALLBACK:
547 if (!opts->callback && !opts->ll_callback)
548 optbug(opts, "OPTION_CALLBACK needs one callback");
549 else if (opts->callback && opts->ll_callback)
550 optbug(opts, "OPTION_CALLBACK can't have two callbacks");
551 break;
552 case OPTION_LOWLEVEL_CALLBACK:
553 if (!opts->ll_callback)
554 optbug(opts, "OPTION_LOWLEVEL_CALLBACK needs a callback");
555 if (opts->callback)
556 optbug(opts, "OPTION_LOWLEVEL_CALLBACK needs no high level callback");
557 break;
558 case OPTION_ALIAS:
559 optbug(opts, "OPT_ALIAS() should not remain at this point. "
560 "Are you using parse_options_step() directly?\n"
561 "That case is not supported yet.");
562 break;
563 case OPTION_SUBCOMMAND:
564 if (!opts->value || !opts->subcommand_fn)
565 optbug(opts, "OPTION_SUBCOMMAND needs a value and a subcommand function");
566 if (!subcommand_value)
567 subcommand_value = opts->value;
568 else if (subcommand_value != opts->value)
569 optbug(opts, "all OPTION_SUBCOMMANDs need the same value");
570 break;
571 default:
572 ; /* ok. (usually accepts an argument) */
574 if (opts->argh &&
575 strcspn(opts->argh, " _") != strlen(opts->argh))
576 optbug(opts, "multi-word argh should use dash to separate words");
578 BUG_if_bug("invalid 'struct option'");
581 static int has_subcommands(const struct option *options)
583 for (; options->type != OPTION_END; options++)
584 if (options->type == OPTION_SUBCOMMAND)
585 return 1;
586 return 0;
589 static void parse_options_start_1(struct parse_opt_ctx_t *ctx,
590 int argc, const char **argv, const char *prefix,
591 const struct option *options,
592 enum parse_opt_flags flags)
594 ctx->argc = argc;
595 ctx->argv = argv;
596 if (!(flags & PARSE_OPT_ONE_SHOT)) {
597 ctx->argc--;
598 ctx->argv++;
600 ctx->total = ctx->argc;
601 ctx->out = argv;
602 ctx->prefix = prefix;
603 ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
604 ctx->flags = flags;
605 ctx->has_subcommands = has_subcommands(options);
606 if (!ctx->has_subcommands && (flags & PARSE_OPT_SUBCOMMAND_OPTIONAL))
607 BUG("Using PARSE_OPT_SUBCOMMAND_OPTIONAL without subcommands");
608 if (ctx->has_subcommands) {
609 if (flags & PARSE_OPT_STOP_AT_NON_OPTION)
610 BUG("subcommands are incompatible with PARSE_OPT_STOP_AT_NON_OPTION");
611 if (!(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
612 if (flags & PARSE_OPT_KEEP_UNKNOWN_OPT)
613 BUG("subcommands are incompatible with PARSE_OPT_KEEP_UNKNOWN_OPT unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
614 if (flags & PARSE_OPT_KEEP_DASHDASH)
615 BUG("subcommands are incompatible with PARSE_OPT_KEEP_DASHDASH unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
618 if ((flags & PARSE_OPT_KEEP_UNKNOWN_OPT) &&
619 (flags & PARSE_OPT_STOP_AT_NON_OPTION) &&
620 !(flags & PARSE_OPT_ONE_SHOT))
621 BUG("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
622 if ((flags & PARSE_OPT_ONE_SHOT) &&
623 (flags & PARSE_OPT_KEEP_ARGV0))
624 BUG("Can't keep argv0 if you don't have it");
625 parse_options_check(options);
626 build_cmdmode_list(ctx, options);
629 void parse_options_start(struct parse_opt_ctx_t *ctx,
630 int argc, const char **argv, const char *prefix,
631 const struct option *options,
632 enum parse_opt_flags flags)
634 memset(ctx, 0, sizeof(*ctx));
635 parse_options_start_1(ctx, argc, argv, prefix, options, flags);
638 static void show_negated_gitcomp(const struct option *opts, int show_all,
639 int nr_noopts)
641 int printed_dashdash = 0;
643 for (; opts->type != OPTION_END; opts++) {
644 int has_unset_form = 0;
645 const char *name;
647 if (!opts->long_name)
648 continue;
649 if (!show_all &&
650 (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE)))
651 continue;
652 if (opts->flags & PARSE_OPT_NONEG)
653 continue;
655 switch (opts->type) {
656 case OPTION_STRING:
657 case OPTION_FILENAME:
658 case OPTION_INTEGER:
659 case OPTION_MAGNITUDE:
660 case OPTION_CALLBACK:
661 case OPTION_BIT:
662 case OPTION_NEGBIT:
663 case OPTION_COUNTUP:
664 case OPTION_SET_INT:
665 has_unset_form = 1;
666 break;
667 default:
668 break;
670 if (!has_unset_form)
671 continue;
673 if (skip_prefix(opts->long_name, "no-", &name)) {
674 if (nr_noopts < 0)
675 printf(" --%s", name);
676 } else if (nr_noopts >= 0) {
677 if (nr_noopts && !printed_dashdash) {
678 printf(" --");
679 printed_dashdash = 1;
681 printf(" --no-%s", opts->long_name);
682 nr_noopts++;
687 static int show_gitcomp(const struct option *opts, int show_all)
689 const struct option *original_opts = opts;
690 int nr_noopts = 0;
692 for (; opts->type != OPTION_END; opts++) {
693 const char *prefix = "--";
694 const char *suffix = "";
696 if (!opts->long_name)
697 continue;
698 if (!show_all &&
699 (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE | PARSE_OPT_FROM_ALIAS)))
700 continue;
702 switch (opts->type) {
703 case OPTION_SUBCOMMAND:
704 prefix = "";
705 break;
706 case OPTION_GROUP:
707 continue;
708 case OPTION_STRING:
709 case OPTION_FILENAME:
710 case OPTION_INTEGER:
711 case OPTION_MAGNITUDE:
712 case OPTION_CALLBACK:
713 if (opts->flags & PARSE_OPT_NOARG)
714 break;
715 if (opts->flags & PARSE_OPT_OPTARG)
716 break;
717 if (opts->flags & PARSE_OPT_LASTARG_DEFAULT)
718 break;
719 suffix = "=";
720 break;
721 default:
722 break;
724 if (opts->flags & PARSE_OPT_COMP_ARG)
725 suffix = "=";
726 if (starts_with(opts->long_name, "no-"))
727 nr_noopts++;
728 printf("%s%s%s%s", opts == original_opts ? "" : " ",
729 prefix, opts->long_name, suffix);
731 show_negated_gitcomp(original_opts, show_all, -1);
732 show_negated_gitcomp(original_opts, show_all, nr_noopts);
733 fputc('\n', stdout);
734 return PARSE_OPT_COMPLETE;
738 * Scan and may produce a new option[] array, which should be used
739 * instead of the original 'options'.
741 * Right now this is only used to preprocess and substitute
742 * OPTION_ALIAS.
744 * The returned options should be freed using free_preprocessed_options.
746 static struct option *preprocess_options(struct parse_opt_ctx_t *ctx,
747 const struct option *options)
749 struct option *newopt;
750 int i, nr, alias;
751 int nr_aliases = 0;
753 for (nr = 0; options[nr].type != OPTION_END; nr++) {
754 if (options[nr].type == OPTION_ALIAS)
755 nr_aliases++;
758 if (!nr_aliases)
759 return NULL;
761 DUP_ARRAY(newopt, options, nr + 1);
763 /* each alias has two string pointers and NULL */
764 CALLOC_ARRAY(ctx->alias_groups, 3 * (nr_aliases + 1));
766 for (alias = 0, i = 0; i < nr; i++) {
767 int short_name;
768 const char *long_name;
769 const char *source;
770 struct strbuf help = STRBUF_INIT;
771 int j;
773 if (newopt[i].type != OPTION_ALIAS)
774 continue;
776 short_name = newopt[i].short_name;
777 long_name = newopt[i].long_name;
778 source = newopt[i].value;
780 if (!long_name)
781 BUG("An alias must have long option name");
782 strbuf_addf(&help, _("alias of --%s"), source);
784 for (j = 0; j < nr; j++) {
785 const char *name = options[j].long_name;
787 if (!name || strcmp(name, source))
788 continue;
790 if (options[j].type == OPTION_ALIAS)
791 BUG("No please. Nested aliases are not supported.");
793 memcpy(newopt + i, options + j, sizeof(*newopt));
794 newopt[i].short_name = short_name;
795 newopt[i].long_name = long_name;
796 newopt[i].help = strbuf_detach(&help, NULL);
797 newopt[i].flags |= PARSE_OPT_FROM_ALIAS;
798 break;
801 if (j == nr)
802 BUG("could not find source option '%s' of alias '%s'",
803 source, newopt[i].long_name);
804 ctx->alias_groups[alias * 3 + 0] = newopt[i].long_name;
805 ctx->alias_groups[alias * 3 + 1] = options[j].long_name;
806 ctx->alias_groups[alias * 3 + 2] = NULL;
807 alias++;
810 return newopt;
813 static void free_preprocessed_options(struct option *options)
815 int i;
817 if (!options)
818 return;
820 for (i = 0; options[i].type != OPTION_END; i++) {
821 if (options[i].flags & PARSE_OPT_FROM_ALIAS)
822 free((void *)options[i].help);
824 free(options);
827 static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t *,
828 const char * const *,
829 const struct option *,
830 int, int);
832 enum parse_opt_result parse_options_step(struct parse_opt_ctx_t *ctx,
833 const struct option *options,
834 const char * const usagestr[])
836 int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
838 /* we must reset ->opt, unknown short option leave it dangling */
839 ctx->opt = NULL;
841 for (; ctx->argc; ctx->argc--, ctx->argv++) {
842 const char *arg = ctx->argv[0];
844 if (ctx->flags & PARSE_OPT_ONE_SHOT &&
845 ctx->argc != ctx->total)
846 break;
848 if (*arg != '-' || !arg[1]) {
849 if (parse_nodash_opt(ctx, arg, options) == 0)
850 continue;
851 if (!ctx->has_subcommands) {
852 if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
853 return PARSE_OPT_NON_OPTION;
854 ctx->out[ctx->cpidx++] = ctx->argv[0];
855 continue;
857 switch (parse_subcommand(arg, options)) {
858 case PARSE_OPT_SUBCOMMAND:
859 return PARSE_OPT_SUBCOMMAND;
860 case PARSE_OPT_UNKNOWN:
861 if (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)
863 * arg is neither a short or long
864 * option nor a subcommand. Since
865 * this command has a default
866 * operation mode, we have to treat
867 * this arg and all remaining args
868 * as args meant to that default
869 * operation mode.
870 * So we are done parsing.
872 return PARSE_OPT_DONE;
873 error(_("unknown subcommand: `%s'"), arg);
874 usage_with_options(usagestr, options);
875 case PARSE_OPT_COMPLETE:
876 case PARSE_OPT_HELP:
877 case PARSE_OPT_ERROR:
878 case PARSE_OPT_DONE:
879 case PARSE_OPT_NON_OPTION:
880 /* Impossible. */
881 BUG("parse_subcommand() cannot return these");
885 /* lone -h asks for help */
886 if (internal_help && ctx->total == 1 && !strcmp(arg + 1, "h"))
887 goto show_usage;
890 * lone --git-completion-helper and --git-completion-helper-all
891 * are asked by git-completion.bash
893 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper"))
894 return show_gitcomp(options, 0);
895 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper-all"))
896 return show_gitcomp(options, 1);
898 if (arg[1] != '-') {
899 ctx->opt = arg + 1;
900 switch (parse_short_opt(ctx, options)) {
901 case PARSE_OPT_ERROR:
902 return PARSE_OPT_ERROR;
903 case PARSE_OPT_UNKNOWN:
904 if (ctx->opt)
905 check_typos(arg + 1, options);
906 if (internal_help && *ctx->opt == 'h')
907 goto show_usage;
908 goto unknown;
909 case PARSE_OPT_NON_OPTION:
910 case PARSE_OPT_SUBCOMMAND:
911 case PARSE_OPT_HELP:
912 case PARSE_OPT_COMPLETE:
913 BUG("parse_short_opt() cannot return these");
914 case PARSE_OPT_DONE:
915 break;
917 if (ctx->opt)
918 check_typos(arg + 1, options);
919 while (ctx->opt) {
920 switch (parse_short_opt(ctx, options)) {
921 case PARSE_OPT_ERROR:
922 return PARSE_OPT_ERROR;
923 case PARSE_OPT_UNKNOWN:
924 if (internal_help && *ctx->opt == 'h')
925 goto show_usage;
927 /* fake a short option thing to hide the fact that we may have
928 * started to parse aggregated stuff
930 * This is leaky, too bad.
932 ctx->argv[0] = xstrdup(ctx->opt - 1);
933 *(char *)ctx->argv[0] = '-';
934 goto unknown;
935 case PARSE_OPT_NON_OPTION:
936 case PARSE_OPT_SUBCOMMAND:
937 case PARSE_OPT_COMPLETE:
938 case PARSE_OPT_HELP:
939 BUG("parse_short_opt() cannot return these");
940 case PARSE_OPT_DONE:
941 break;
944 continue;
947 if (!arg[2] /* "--" */) {
948 if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
949 ctx->argc--;
950 ctx->argv++;
952 break;
953 } else if (!strcmp(arg + 2, "end-of-options")) {
954 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)) {
955 ctx->argc--;
956 ctx->argv++;
958 break;
961 if (internal_help && !strcmp(arg + 2, "help-all"))
962 return usage_with_options_internal(ctx, usagestr, options, 1, 0);
963 if (internal_help && !strcmp(arg + 2, "help"))
964 goto show_usage;
965 switch (parse_long_opt(ctx, arg + 2, options)) {
966 case PARSE_OPT_ERROR:
967 return PARSE_OPT_ERROR;
968 case PARSE_OPT_UNKNOWN:
969 goto unknown;
970 case PARSE_OPT_HELP:
971 goto show_usage;
972 case PARSE_OPT_NON_OPTION:
973 case PARSE_OPT_SUBCOMMAND:
974 case PARSE_OPT_COMPLETE:
975 BUG("parse_long_opt() cannot return these");
976 case PARSE_OPT_DONE:
977 break;
979 continue;
980 unknown:
981 if (ctx->flags & PARSE_OPT_ONE_SHOT)
982 break;
983 if (ctx->has_subcommands &&
984 (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL) &&
985 (ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)) {
987 * Found an unknown option given to a command with
988 * subcommands that has a default operation mode:
989 * we treat this option and all remaining args as
990 * arguments meant to that default operation mode.
991 * So we are done parsing.
993 return PARSE_OPT_DONE;
995 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT))
996 return PARSE_OPT_UNKNOWN;
997 ctx->out[ctx->cpidx++] = ctx->argv[0];
998 ctx->opt = NULL;
1000 return PARSE_OPT_DONE;
1002 show_usage:
1003 return usage_with_options_internal(ctx, usagestr, options, 0, 0);
1006 int parse_options_end(struct parse_opt_ctx_t *ctx)
1008 if (ctx->flags & PARSE_OPT_ONE_SHOT)
1009 return ctx->total - ctx->argc;
1011 MOVE_ARRAY(ctx->out + ctx->cpidx, ctx->argv, ctx->argc);
1012 ctx->out[ctx->cpidx + ctx->argc] = NULL;
1013 return ctx->cpidx + ctx->argc;
1016 int parse_options(int argc, const char **argv,
1017 const char *prefix,
1018 const struct option *options,
1019 const char * const usagestr[],
1020 enum parse_opt_flags flags)
1022 struct parse_opt_ctx_t ctx;
1023 struct option *real_options;
1025 disallow_abbreviated_options =
1026 git_env_bool("GIT_TEST_DISALLOW_ABBREVIATED_OPTIONS", 0);
1028 memset(&ctx, 0, sizeof(ctx));
1029 real_options = preprocess_options(&ctx, options);
1030 if (real_options)
1031 options = real_options;
1032 parse_options_start_1(&ctx, argc, argv, prefix, options, flags);
1033 switch (parse_options_step(&ctx, options, usagestr)) {
1034 case PARSE_OPT_HELP:
1035 case PARSE_OPT_ERROR:
1036 exit(129);
1037 case PARSE_OPT_COMPLETE:
1038 exit(0);
1039 case PARSE_OPT_NON_OPTION:
1040 case PARSE_OPT_SUBCOMMAND:
1041 break;
1042 case PARSE_OPT_DONE:
1043 if (ctx.has_subcommands &&
1044 !(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
1045 error(_("need a subcommand"));
1046 usage_with_options(usagestr, options);
1048 break;
1049 case PARSE_OPT_UNKNOWN:
1050 if (ctx.argv[0][1] == '-') {
1051 error(_("unknown option `%s'"), ctx.argv[0] + 2);
1052 } else if (isascii(*ctx.opt)) {
1053 error(_("unknown switch `%c'"), *ctx.opt);
1054 } else {
1055 error(_("unknown non-ascii option in string: `%s'"),
1056 ctx.argv[0]);
1058 usage_with_options(usagestr, options);
1061 precompose_argv_prefix(argc, argv, NULL);
1062 free_preprocessed_options(real_options);
1063 free(ctx.alias_groups);
1064 for (struct parse_opt_cmdmode_list *elem = ctx.cmdmode_list; elem;) {
1065 struct parse_opt_cmdmode_list *next = elem->next;
1066 free(elem);
1067 elem = next;
1069 return parse_options_end(&ctx);
1072 static int usage_argh(const struct option *opts, FILE *outfile)
1074 const char *s;
1075 int literal = (opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1076 !opts->argh || !!strpbrk(opts->argh, "()<>[]|");
1077 if (opts->flags & PARSE_OPT_OPTARG)
1078 if (opts->long_name)
1079 s = literal ? "[=%s]" : "[=<%s>]";
1080 else
1081 s = literal ? "[%s]" : "[<%s>]";
1082 else
1083 s = literal ? " %s" : " <%s>";
1084 return utf8_fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
1087 static int usage_indent(FILE *outfile)
1089 return fprintf(outfile, " ");
1092 #define USAGE_OPTS_WIDTH 26
1094 static void usage_padding(FILE *outfile, size_t pos)
1096 if (pos < USAGE_OPTS_WIDTH)
1097 fprintf(outfile, "%*s", USAGE_OPTS_WIDTH - (int)pos, "");
1098 else
1099 fprintf(outfile, "\n%*s", USAGE_OPTS_WIDTH, "");
1102 static const struct option *find_option_by_long_name(const struct option *opts,
1103 const char *long_name)
1105 for (; opts->type != OPTION_END; opts++) {
1106 if (opts->long_name && !strcmp(opts->long_name, long_name))
1107 return opts;
1109 return NULL;
1112 static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t *ctx,
1113 const char * const *usagestr,
1114 const struct option *opts,
1115 int full, int err)
1117 const struct option *all_opts = opts;
1118 FILE *outfile = err ? stderr : stdout;
1119 int need_newline;
1121 const char *usage_prefix = _("usage: %s");
1123 * The translation could be anything, but we can count on
1124 * msgfmt(1)'s --check option to have asserted that "%s" is in
1125 * the translation. So compute the length of the "usage: "
1126 * part. We are assuming that the translator wasn't overly
1127 * clever and used e.g. "%1$s" instead of "%s", there's only
1128 * one "%s" in "usage_prefix" above, so there's no reason to
1129 * do so even with a RTL language.
1131 size_t usage_len = strlen(usage_prefix) - strlen("%s");
1133 * TRANSLATORS: the colon here should align with the
1134 * one in "usage: %s" translation.
1136 const char *or_prefix = _(" or: %s");
1138 * TRANSLATORS: You should only need to translate this format
1139 * string if your language is a RTL language (e.g. Arabic,
1140 * Hebrew etc.), not if it's a LTR language (e.g. German,
1141 * Russian, Chinese etc.).
1143 * When a translated usage string has an embedded "\n" it's
1144 * because options have wrapped to the next line. The line
1145 * after the "\n" will then be padded to align with the
1146 * command name, such as N_("git cmd [opt]\n<8
1147 * spaces>[opt2]"), where the 8 spaces are the same length as
1148 * "git cmd ".
1150 * This format string prints out that already-translated
1151 * line. The "%*s" is whitespace padding to account for the
1152 * padding at the start of the line that we add in this
1153 * function. The "%s" is a line in the (hopefully already
1154 * translated) N_() usage string, which contained embedded
1155 * newlines before we split it up.
1157 const char *usage_continued = _("%*s%s");
1158 const char *prefix = usage_prefix;
1159 int saw_empty_line = 0;
1161 if (!usagestr)
1162 return PARSE_OPT_HELP;
1164 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1165 fprintf(outfile, "cat <<\\EOF\n");
1167 while (*usagestr) {
1168 const char *str = _(*usagestr++);
1169 struct string_list list = STRING_LIST_INIT_DUP;
1170 unsigned int j;
1172 if (!saw_empty_line && !*str)
1173 saw_empty_line = 1;
1175 string_list_split(&list, str, '\n', -1);
1176 for (j = 0; j < list.nr; j++) {
1177 const char *line = list.items[j].string;
1179 if (saw_empty_line && *line)
1180 fprintf_ln(outfile, _(" %s"), line);
1181 else if (saw_empty_line)
1182 fputc('\n', outfile);
1183 else if (!j)
1184 fprintf_ln(outfile, prefix, line);
1185 else
1186 fprintf_ln(outfile, usage_continued,
1187 (int)usage_len, "", line);
1189 string_list_clear(&list, 0);
1191 prefix = or_prefix;
1194 need_newline = 1;
1196 for (; opts->type != OPTION_END; opts++) {
1197 size_t pos;
1198 const char *cp, *np;
1199 const char *positive_name = NULL;
1201 if (opts->type == OPTION_SUBCOMMAND)
1202 continue;
1203 if (opts->type == OPTION_GROUP) {
1204 fputc('\n', outfile);
1205 need_newline = 0;
1206 if (*opts->help)
1207 fprintf(outfile, "%s\n", _(opts->help));
1208 continue;
1210 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
1211 continue;
1213 if (need_newline) {
1214 fputc('\n', outfile);
1215 need_newline = 0;
1218 pos = usage_indent(outfile);
1219 if (opts->short_name) {
1220 if (opts->flags & PARSE_OPT_NODASH)
1221 pos += fprintf(outfile, "%c", opts->short_name);
1222 else
1223 pos += fprintf(outfile, "-%c", opts->short_name);
1225 if (opts->long_name && opts->short_name)
1226 pos += fprintf(outfile, ", ");
1227 if (opts->long_name) {
1228 const char *long_name = opts->long_name;
1229 if ((opts->flags & PARSE_OPT_NONEG) ||
1230 skip_prefix(long_name, "no-", &positive_name))
1231 pos += fprintf(outfile, "--%s", long_name);
1232 else
1233 pos += fprintf(outfile, "--[no-]%s", long_name);
1236 if (opts->type == OPTION_NUMBER)
1237 pos += utf8_fprintf(outfile, _("-NUM"));
1239 if ((opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1240 !(opts->flags & PARSE_OPT_NOARG))
1241 pos += usage_argh(opts, outfile);
1243 if (opts->type == OPTION_ALIAS) {
1244 usage_padding(outfile, pos);
1245 fprintf_ln(outfile, _("alias of --%s"),
1246 (const char *)opts->value);
1247 continue;
1250 for (cp = opts->help ? _(opts->help) : ""; *cp; cp = np) {
1251 np = strchrnul(cp, '\n');
1252 if (*np)
1253 np++;
1254 usage_padding(outfile, pos);
1255 fwrite(cp, 1, np - cp, outfile);
1256 pos = 0;
1258 fputc('\n', outfile);
1260 if (positive_name) {
1261 if (find_option_by_long_name(all_opts, positive_name))
1262 continue;
1263 pos = usage_indent(outfile);
1264 pos += fprintf(outfile, "--%s", positive_name);
1265 usage_padding(outfile, pos);
1266 fprintf_ln(outfile, _("opposite of --no-%s"),
1267 positive_name);
1270 fputc('\n', outfile);
1272 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1273 fputs("EOF\n", outfile);
1275 return PARSE_OPT_HELP;
1278 void NORETURN usage_with_options(const char * const *usagestr,
1279 const struct option *opts)
1281 usage_with_options_internal(NULL, usagestr, opts, 0, 1);
1282 exit(129);
1285 void NORETURN usage_msg_opt(const char *msg,
1286 const char * const *usagestr,
1287 const struct option *options)
1289 die_message("%s\n", msg); /* The extra \n is intentional */
1290 usage_with_options(usagestr, options);
1293 void NORETURN usage_msg_optf(const char * const fmt,
1294 const char * const *usagestr,
1295 const struct option *options, ...)
1297 struct strbuf msg = STRBUF_INIT;
1298 va_list ap;
1299 va_start(ap, options);
1300 strbuf_vaddf(&msg, fmt, ap);
1301 va_end(ap);
1303 usage_msg_opt(msg.buf, usagestr, options);
1306 void die_for_incompatible_opt4(int opt1, const char *opt1_name,
1307 int opt2, const char *opt2_name,
1308 int opt3, const char *opt3_name,
1309 int opt4, const char *opt4_name)
1311 int count = 0;
1312 const char *options[4];
1314 if (opt1)
1315 options[count++] = opt1_name;
1316 if (opt2)
1317 options[count++] = opt2_name;
1318 if (opt3)
1319 options[count++] = opt3_name;
1320 if (opt4)
1321 options[count++] = opt4_name;
1322 switch (count) {
1323 case 4:
1324 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
1325 opt1_name, opt2_name, opt3_name, opt4_name);
1326 break;
1327 case 3:
1328 die(_("options '%s', '%s', and '%s' cannot be used together"),
1329 options[0], options[1], options[2]);
1330 break;
1331 case 2:
1332 die(_("options '%s' and '%s' cannot be used together"),
1333 options[0], options[1]);
1334 break;
1335 default:
1336 break;