Merge branch 'jk/config-cleanup'
[alt-git.git] / parse-options.c
blob65fab5bb9dca071fac111705f6cbfc439eeef447
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(_("options '%s' and '%s' cannot be used together"),
283 opt_name, other_opt_name);
284 free(opt_name);
285 free(other_opt_name);
286 return -1;
289 static enum parse_opt_result parse_short_opt(struct parse_opt_ctx_t *p,
290 const struct option *options)
292 const struct option *numopt = NULL;
294 for (; options->type != OPTION_END; options++) {
295 if (options->short_name == *p->opt) {
296 p->opt = p->opt[1] ? p->opt + 1 : NULL;
297 return get_value(p, options, OPT_SHORT);
301 * Handle the numerical option later, explicit one-digit
302 * options take precedence over it.
304 if (options->type == OPTION_NUMBER)
305 numopt = options;
307 if (numopt && isdigit(*p->opt)) {
308 size_t len = 1;
309 char *arg;
310 int rc;
312 while (isdigit(p->opt[len]))
313 len++;
314 arg = xmemdupz(p->opt, len);
315 p->opt = p->opt[len] ? p->opt + len : NULL;
316 if (numopt->callback)
317 rc = (*numopt->callback)(numopt, arg, 0) ? (-1) : 0;
318 else
319 rc = (*numopt->ll_callback)(p, numopt, arg, 0);
320 free(arg);
321 return rc;
323 return PARSE_OPT_UNKNOWN;
326 static int has_string(const char *it, const char **array)
328 while (*array)
329 if (!strcmp(it, *(array++)))
330 return 1;
331 return 0;
334 static int is_alias(struct parse_opt_ctx_t *ctx,
335 const struct option *one_opt,
336 const struct option *another_opt)
338 const char **group;
340 if (!ctx->alias_groups)
341 return 0;
343 if (!one_opt->long_name || !another_opt->long_name)
344 return 0;
346 for (group = ctx->alias_groups; *group; group += 3) {
347 /* it and other are from the same family? */
348 if (has_string(one_opt->long_name, group) &&
349 has_string(another_opt->long_name, group))
350 return 1;
352 return 0;
355 static enum parse_opt_result parse_long_opt(
356 struct parse_opt_ctx_t *p, const char *arg,
357 const struct option *options)
359 const char *arg_end = strchrnul(arg, '=');
360 const struct option *abbrev_option = NULL, *ambiguous_option = NULL;
361 enum opt_parsed abbrev_flags = OPT_LONG, ambiguous_flags = OPT_LONG;
363 for (; options->type != OPTION_END; options++) {
364 const char *rest, *long_name = options->long_name;
365 enum opt_parsed flags = OPT_LONG, opt_flags = OPT_LONG;
367 if (options->type == OPTION_SUBCOMMAND)
368 continue;
369 if (!long_name)
370 continue;
372 again:
373 if (!skip_prefix(arg, long_name, &rest))
374 rest = NULL;
375 if (!rest) {
376 /* abbreviated? */
377 if (!(p->flags & PARSE_OPT_KEEP_UNKNOWN_OPT) &&
378 !strncmp(long_name, arg, arg_end - arg)) {
379 is_abbreviated:
380 if (abbrev_option &&
381 !is_alias(p, abbrev_option, options)) {
383 * If this is abbreviated, it is
384 * ambiguous. So when there is no
385 * exact match later, we need to
386 * error out.
388 ambiguous_option = abbrev_option;
389 ambiguous_flags = abbrev_flags;
391 if (!(flags & OPT_UNSET) && *arg_end)
392 p->opt = arg_end + 1;
393 abbrev_option = options;
394 abbrev_flags = flags ^ opt_flags;
395 continue;
397 /* negation allowed? */
398 if (options->flags & PARSE_OPT_NONEG)
399 continue;
400 /* negated and abbreviated very much? */
401 if (starts_with("no-", arg)) {
402 flags |= OPT_UNSET;
403 goto is_abbreviated;
405 /* negated? */
406 if (!starts_with(arg, "no-")) {
407 if (skip_prefix(long_name, "no-", &long_name)) {
408 opt_flags |= OPT_UNSET;
409 goto again;
411 continue;
413 flags |= OPT_UNSET;
414 if (!skip_prefix(arg + 3, long_name, &rest)) {
415 /* abbreviated and negated? */
416 if (starts_with(long_name, arg + 3))
417 goto is_abbreviated;
418 else
419 continue;
422 if (*rest) {
423 if (*rest != '=')
424 continue;
425 p->opt = rest + 1;
427 return get_value(p, options, flags ^ opt_flags);
430 if (disallow_abbreviated_options && (ambiguous_option || abbrev_option))
431 die("disallowed abbreviated or ambiguous option '%.*s'",
432 (int)(arg_end - arg), arg);
434 if (ambiguous_option) {
435 error(_("ambiguous option: %s "
436 "(could be --%s%s or --%s%s)"),
437 arg,
438 (ambiguous_flags & OPT_UNSET) ? "no-" : "",
439 ambiguous_option->long_name,
440 (abbrev_flags & OPT_UNSET) ? "no-" : "",
441 abbrev_option->long_name);
442 return PARSE_OPT_HELP;
444 if (abbrev_option)
445 return get_value(p, abbrev_option, abbrev_flags);
446 return PARSE_OPT_UNKNOWN;
449 static enum parse_opt_result parse_nodash_opt(struct parse_opt_ctx_t *p,
450 const char *arg,
451 const struct option *options)
453 for (; options->type != OPTION_END; options++) {
454 if (!(options->flags & PARSE_OPT_NODASH))
455 continue;
456 if (options->short_name == arg[0] && arg[1] == '\0')
457 return get_value(p, options, OPT_SHORT);
459 return PARSE_OPT_ERROR;
462 static enum parse_opt_result parse_subcommand(const char *arg,
463 const struct option *options)
465 for (; options->type != OPTION_END; options++)
466 if (options->type == OPTION_SUBCOMMAND &&
467 !strcmp(options->long_name, arg)) {
468 *(parse_opt_subcommand_fn **)options->value = options->subcommand_fn;
469 return PARSE_OPT_SUBCOMMAND;
472 return PARSE_OPT_UNKNOWN;
475 static void check_typos(const char *arg, const struct option *options)
477 if (strlen(arg) < 3)
478 return;
480 if (starts_with(arg, "no-")) {
481 error(_("did you mean `--%s` (with two dashes)?"), arg);
482 exit(129);
485 for (; options->type != OPTION_END; options++) {
486 if (!options->long_name)
487 continue;
488 if (starts_with(options->long_name, arg)) {
489 error(_("did you mean `--%s` (with two dashes)?"), arg);
490 exit(129);
495 static void parse_options_check(const struct option *opts)
497 char short_opts[128];
498 void *subcommand_value = NULL;
500 memset(short_opts, '\0', sizeof(short_opts));
501 for (; opts->type != OPTION_END; opts++) {
502 if ((opts->flags & PARSE_OPT_LASTARG_DEFAULT) &&
503 (opts->flags & PARSE_OPT_OPTARG))
504 optbug(opts, "uses incompatible flags "
505 "LASTARG_DEFAULT and OPTARG");
506 if (opts->short_name) {
507 if (0x7F <= opts->short_name)
508 optbug(opts, "invalid short name");
509 else if (short_opts[opts->short_name]++)
510 optbug(opts, "short name already used");
512 if (opts->flags & PARSE_OPT_NODASH &&
513 ((opts->flags & PARSE_OPT_OPTARG) ||
514 !(opts->flags & PARSE_OPT_NOARG) ||
515 !(opts->flags & PARSE_OPT_NONEG) ||
516 opts->long_name))
517 optbug(opts, "uses feature "
518 "not supported for dashless options");
519 if (opts->type == OPTION_SET_INT && !opts->defval &&
520 opts->long_name && !(opts->flags & PARSE_OPT_NONEG))
521 optbug(opts, "OPTION_SET_INT 0 should not be negatable");
522 switch (opts->type) {
523 case OPTION_COUNTUP:
524 case OPTION_BIT:
525 case OPTION_NEGBIT:
526 case OPTION_SET_INT:
527 case OPTION_NUMBER:
528 if ((opts->flags & PARSE_OPT_OPTARG) ||
529 !(opts->flags & PARSE_OPT_NOARG))
530 optbug(opts, "should not accept an argument");
531 break;
532 case OPTION_CALLBACK:
533 if (!opts->callback && !opts->ll_callback)
534 optbug(opts, "OPTION_CALLBACK needs one callback");
535 else if (opts->callback && opts->ll_callback)
536 optbug(opts, "OPTION_CALLBACK can't have two callbacks");
537 break;
538 case OPTION_LOWLEVEL_CALLBACK:
539 if (!opts->ll_callback)
540 optbug(opts, "OPTION_LOWLEVEL_CALLBACK needs a callback");
541 if (opts->callback)
542 optbug(opts, "OPTION_LOWLEVEL_CALLBACK needs no high level callback");
543 break;
544 case OPTION_ALIAS:
545 optbug(opts, "OPT_ALIAS() should not remain at this point. "
546 "Are you using parse_options_step() directly?\n"
547 "That case is not supported yet.");
548 break;
549 case OPTION_SUBCOMMAND:
550 if (!opts->value || !opts->subcommand_fn)
551 optbug(opts, "OPTION_SUBCOMMAND needs a value and a subcommand function");
552 if (!subcommand_value)
553 subcommand_value = opts->value;
554 else if (subcommand_value != opts->value)
555 optbug(opts, "all OPTION_SUBCOMMANDs need the same value");
556 break;
557 default:
558 ; /* ok. (usually accepts an argument) */
560 if (opts->argh &&
561 strcspn(opts->argh, " _") != strlen(opts->argh))
562 optbug(opts, "multi-word argh should use dash to separate words");
564 BUG_if_bug("invalid 'struct option'");
567 static int has_subcommands(const struct option *options)
569 for (; options->type != OPTION_END; options++)
570 if (options->type == OPTION_SUBCOMMAND)
571 return 1;
572 return 0;
575 static void parse_options_start_1(struct parse_opt_ctx_t *ctx,
576 int argc, const char **argv, const char *prefix,
577 const struct option *options,
578 enum parse_opt_flags flags)
580 ctx->argc = argc;
581 ctx->argv = argv;
582 if (!(flags & PARSE_OPT_ONE_SHOT)) {
583 ctx->argc--;
584 ctx->argv++;
586 ctx->total = ctx->argc;
587 ctx->out = argv;
588 ctx->prefix = prefix;
589 ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
590 ctx->flags = flags;
591 ctx->has_subcommands = has_subcommands(options);
592 if (!ctx->has_subcommands && (flags & PARSE_OPT_SUBCOMMAND_OPTIONAL))
593 BUG("Using PARSE_OPT_SUBCOMMAND_OPTIONAL without subcommands");
594 if (ctx->has_subcommands) {
595 if (flags & PARSE_OPT_STOP_AT_NON_OPTION)
596 BUG("subcommands are incompatible with PARSE_OPT_STOP_AT_NON_OPTION");
597 if (!(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
598 if (flags & PARSE_OPT_KEEP_UNKNOWN_OPT)
599 BUG("subcommands are incompatible with PARSE_OPT_KEEP_UNKNOWN_OPT unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
600 if (flags & PARSE_OPT_KEEP_DASHDASH)
601 BUG("subcommands are incompatible with PARSE_OPT_KEEP_DASHDASH unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
604 if ((flags & PARSE_OPT_KEEP_UNKNOWN_OPT) &&
605 (flags & PARSE_OPT_STOP_AT_NON_OPTION) &&
606 !(flags & PARSE_OPT_ONE_SHOT))
607 BUG("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
608 if ((flags & PARSE_OPT_ONE_SHOT) &&
609 (flags & PARSE_OPT_KEEP_ARGV0))
610 BUG("Can't keep argv0 if you don't have it");
611 parse_options_check(options);
612 build_cmdmode_list(ctx, options);
615 void parse_options_start(struct parse_opt_ctx_t *ctx,
616 int argc, const char **argv, const char *prefix,
617 const struct option *options,
618 enum parse_opt_flags flags)
620 memset(ctx, 0, sizeof(*ctx));
621 parse_options_start_1(ctx, argc, argv, prefix, options, flags);
624 static void show_negated_gitcomp(const struct option *opts, int show_all,
625 int nr_noopts)
627 int printed_dashdash = 0;
629 for (; opts->type != OPTION_END; opts++) {
630 int has_unset_form = 0;
631 const char *name;
633 if (!opts->long_name)
634 continue;
635 if (!show_all &&
636 (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE)))
637 continue;
638 if (opts->flags & PARSE_OPT_NONEG)
639 continue;
641 switch (opts->type) {
642 case OPTION_STRING:
643 case OPTION_FILENAME:
644 case OPTION_INTEGER:
645 case OPTION_MAGNITUDE:
646 case OPTION_CALLBACK:
647 case OPTION_BIT:
648 case OPTION_NEGBIT:
649 case OPTION_COUNTUP:
650 case OPTION_SET_INT:
651 has_unset_form = 1;
652 break;
653 default:
654 break;
656 if (!has_unset_form)
657 continue;
659 if (skip_prefix(opts->long_name, "no-", &name)) {
660 if (nr_noopts < 0)
661 printf(" --%s", name);
662 } else if (nr_noopts >= 0) {
663 if (nr_noopts && !printed_dashdash) {
664 printf(" --");
665 printed_dashdash = 1;
667 printf(" --no-%s", opts->long_name);
668 nr_noopts++;
673 static int show_gitcomp(const struct option *opts, int show_all)
675 const struct option *original_opts = opts;
676 int nr_noopts = 0;
678 for (; opts->type != OPTION_END; opts++) {
679 const char *prefix = "--";
680 const char *suffix = "";
682 if (!opts->long_name)
683 continue;
684 if (!show_all &&
685 (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE | PARSE_OPT_FROM_ALIAS)))
686 continue;
688 switch (opts->type) {
689 case OPTION_SUBCOMMAND:
690 prefix = "";
691 break;
692 case OPTION_GROUP:
693 continue;
694 case OPTION_STRING:
695 case OPTION_FILENAME:
696 case OPTION_INTEGER:
697 case OPTION_MAGNITUDE:
698 case OPTION_CALLBACK:
699 if (opts->flags & PARSE_OPT_NOARG)
700 break;
701 if (opts->flags & PARSE_OPT_OPTARG)
702 break;
703 if (opts->flags & PARSE_OPT_LASTARG_DEFAULT)
704 break;
705 suffix = "=";
706 break;
707 default:
708 break;
710 if (opts->flags & PARSE_OPT_COMP_ARG)
711 suffix = "=";
712 if (starts_with(opts->long_name, "no-"))
713 nr_noopts++;
714 printf("%s%s%s%s", opts == original_opts ? "" : " ",
715 prefix, opts->long_name, suffix);
717 show_negated_gitcomp(original_opts, show_all, -1);
718 show_negated_gitcomp(original_opts, show_all, nr_noopts);
719 fputc('\n', stdout);
720 return PARSE_OPT_COMPLETE;
724 * Scan and may produce a new option[] array, which should be used
725 * instead of the original 'options'.
727 * Right now this is only used to preprocess and substitute
728 * OPTION_ALIAS.
730 * The returned options should be freed using free_preprocessed_options.
732 static struct option *preprocess_options(struct parse_opt_ctx_t *ctx,
733 const struct option *options)
735 struct option *newopt;
736 int i, nr, alias;
737 int nr_aliases = 0;
739 for (nr = 0; options[nr].type != OPTION_END; nr++) {
740 if (options[nr].type == OPTION_ALIAS)
741 nr_aliases++;
744 if (!nr_aliases)
745 return NULL;
747 DUP_ARRAY(newopt, options, nr + 1);
749 /* each alias has two string pointers and NULL */
750 CALLOC_ARRAY(ctx->alias_groups, 3 * (nr_aliases + 1));
752 for (alias = 0, i = 0; i < nr; i++) {
753 int short_name;
754 const char *long_name;
755 const char *source;
756 struct strbuf help = STRBUF_INIT;
757 int j;
759 if (newopt[i].type != OPTION_ALIAS)
760 continue;
762 short_name = newopt[i].short_name;
763 long_name = newopt[i].long_name;
764 source = newopt[i].value;
766 if (!long_name)
767 BUG("An alias must have long option name");
768 strbuf_addf(&help, _("alias of --%s"), source);
770 for (j = 0; j < nr; j++) {
771 const char *name = options[j].long_name;
773 if (!name || strcmp(name, source))
774 continue;
776 if (options[j].type == OPTION_ALIAS)
777 BUG("No please. Nested aliases are not supported.");
779 memcpy(newopt + i, options + j, sizeof(*newopt));
780 newopt[i].short_name = short_name;
781 newopt[i].long_name = long_name;
782 newopt[i].help = strbuf_detach(&help, NULL);
783 newopt[i].flags |= PARSE_OPT_FROM_ALIAS;
784 break;
787 if (j == nr)
788 BUG("could not find source option '%s' of alias '%s'",
789 source, newopt[i].long_name);
790 ctx->alias_groups[alias * 3 + 0] = newopt[i].long_name;
791 ctx->alias_groups[alias * 3 + 1] = options[j].long_name;
792 ctx->alias_groups[alias * 3 + 2] = NULL;
793 alias++;
796 return newopt;
799 static void free_preprocessed_options(struct option *options)
801 int i;
803 if (!options)
804 return;
806 for (i = 0; options[i].type != OPTION_END; i++) {
807 if (options[i].flags & PARSE_OPT_FROM_ALIAS)
808 free((void *)options[i].help);
810 free(options);
813 static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t *,
814 const char * const *,
815 const struct option *,
816 int, int);
818 enum parse_opt_result parse_options_step(struct parse_opt_ctx_t *ctx,
819 const struct option *options,
820 const char * const usagestr[])
822 int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
824 /* we must reset ->opt, unknown short option leave it dangling */
825 ctx->opt = NULL;
827 for (; ctx->argc; ctx->argc--, ctx->argv++) {
828 const char *arg = ctx->argv[0];
830 if (ctx->flags & PARSE_OPT_ONE_SHOT &&
831 ctx->argc != ctx->total)
832 break;
834 if (*arg != '-' || !arg[1]) {
835 if (parse_nodash_opt(ctx, arg, options) == 0)
836 continue;
837 if (!ctx->has_subcommands) {
838 if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
839 return PARSE_OPT_NON_OPTION;
840 ctx->out[ctx->cpidx++] = ctx->argv[0];
841 continue;
843 switch (parse_subcommand(arg, options)) {
844 case PARSE_OPT_SUBCOMMAND:
845 return PARSE_OPT_SUBCOMMAND;
846 case PARSE_OPT_UNKNOWN:
847 if (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)
849 * arg is neither a short or long
850 * option nor a subcommand. Since
851 * this command has a default
852 * operation mode, we have to treat
853 * this arg and all remaining args
854 * as args meant to that default
855 * operation mode.
856 * So we are done parsing.
858 return PARSE_OPT_DONE;
859 error(_("unknown subcommand: `%s'"), arg);
860 usage_with_options(usagestr, options);
861 case PARSE_OPT_COMPLETE:
862 case PARSE_OPT_HELP:
863 case PARSE_OPT_ERROR:
864 case PARSE_OPT_DONE:
865 case PARSE_OPT_NON_OPTION:
866 /* Impossible. */
867 BUG("parse_subcommand() cannot return these");
871 /* lone -h asks for help */
872 if (internal_help && ctx->total == 1 && !strcmp(arg + 1, "h"))
873 goto show_usage;
876 * lone --git-completion-helper and --git-completion-helper-all
877 * are asked by git-completion.bash
879 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper"))
880 return show_gitcomp(options, 0);
881 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper-all"))
882 return show_gitcomp(options, 1);
884 if (arg[1] != '-') {
885 ctx->opt = arg + 1;
886 switch (parse_short_opt(ctx, options)) {
887 case PARSE_OPT_ERROR:
888 return PARSE_OPT_ERROR;
889 case PARSE_OPT_UNKNOWN:
890 if (ctx->opt)
891 check_typos(arg + 1, options);
892 if (internal_help && *ctx->opt == 'h')
893 goto show_usage;
894 goto unknown;
895 case PARSE_OPT_NON_OPTION:
896 case PARSE_OPT_SUBCOMMAND:
897 case PARSE_OPT_HELP:
898 case PARSE_OPT_COMPLETE:
899 BUG("parse_short_opt() cannot return these");
900 case PARSE_OPT_DONE:
901 break;
903 if (ctx->opt)
904 check_typos(arg + 1, options);
905 while (ctx->opt) {
906 switch (parse_short_opt(ctx, options)) {
907 case PARSE_OPT_ERROR:
908 return PARSE_OPT_ERROR;
909 case PARSE_OPT_UNKNOWN:
910 if (internal_help && *ctx->opt == 'h')
911 goto show_usage;
913 /* fake a short option thing to hide the fact that we may have
914 * started to parse aggregated stuff
916 * This is leaky, too bad.
918 ctx->argv[0] = xstrdup(ctx->opt - 1);
919 *(char *)ctx->argv[0] = '-';
920 goto unknown;
921 case PARSE_OPT_NON_OPTION:
922 case PARSE_OPT_SUBCOMMAND:
923 case PARSE_OPT_COMPLETE:
924 case PARSE_OPT_HELP:
925 BUG("parse_short_opt() cannot return these");
926 case PARSE_OPT_DONE:
927 break;
930 continue;
933 if (!arg[2] /* "--" */) {
934 if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
935 ctx->argc--;
936 ctx->argv++;
938 break;
939 } else if (!strcmp(arg + 2, "end-of-options")) {
940 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)) {
941 ctx->argc--;
942 ctx->argv++;
944 break;
947 if (internal_help && !strcmp(arg + 2, "help-all"))
948 return usage_with_options_internal(ctx, usagestr, options, 1, 0);
949 if (internal_help && !strcmp(arg + 2, "help"))
950 goto show_usage;
951 switch (parse_long_opt(ctx, arg + 2, options)) {
952 case PARSE_OPT_ERROR:
953 return PARSE_OPT_ERROR;
954 case PARSE_OPT_UNKNOWN:
955 goto unknown;
956 case PARSE_OPT_HELP:
957 goto show_usage;
958 case PARSE_OPT_NON_OPTION:
959 case PARSE_OPT_SUBCOMMAND:
960 case PARSE_OPT_COMPLETE:
961 BUG("parse_long_opt() cannot return these");
962 case PARSE_OPT_DONE:
963 break;
965 continue;
966 unknown:
967 if (ctx->flags & PARSE_OPT_ONE_SHOT)
968 break;
969 if (ctx->has_subcommands &&
970 (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL) &&
971 (ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)) {
973 * Found an unknown option given to a command with
974 * subcommands that has a default operation mode:
975 * we treat this option and all remaining args as
976 * arguments meant to that default operation mode.
977 * So we are done parsing.
979 return PARSE_OPT_DONE;
981 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT))
982 return PARSE_OPT_UNKNOWN;
983 ctx->out[ctx->cpidx++] = ctx->argv[0];
984 ctx->opt = NULL;
986 return PARSE_OPT_DONE;
988 show_usage:
989 return usage_with_options_internal(ctx, usagestr, options, 0, 0);
992 int parse_options_end(struct parse_opt_ctx_t *ctx)
994 if (ctx->flags & PARSE_OPT_ONE_SHOT)
995 return ctx->total - ctx->argc;
997 MOVE_ARRAY(ctx->out + ctx->cpidx, ctx->argv, ctx->argc);
998 ctx->out[ctx->cpidx + ctx->argc] = NULL;
999 return ctx->cpidx + ctx->argc;
1002 int parse_options(int argc, const char **argv,
1003 const char *prefix,
1004 const struct option *options,
1005 const char * const usagestr[],
1006 enum parse_opt_flags flags)
1008 struct parse_opt_ctx_t ctx;
1009 struct option *real_options;
1011 disallow_abbreviated_options =
1012 git_env_bool("GIT_TEST_DISALLOW_ABBREVIATED_OPTIONS", 0);
1014 memset(&ctx, 0, sizeof(ctx));
1015 real_options = preprocess_options(&ctx, options);
1016 if (real_options)
1017 options = real_options;
1018 parse_options_start_1(&ctx, argc, argv, prefix, options, flags);
1019 switch (parse_options_step(&ctx, options, usagestr)) {
1020 case PARSE_OPT_HELP:
1021 case PARSE_OPT_ERROR:
1022 exit(129);
1023 case PARSE_OPT_COMPLETE:
1024 exit(0);
1025 case PARSE_OPT_NON_OPTION:
1026 case PARSE_OPT_SUBCOMMAND:
1027 break;
1028 case PARSE_OPT_DONE:
1029 if (ctx.has_subcommands &&
1030 !(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
1031 error(_("need a subcommand"));
1032 usage_with_options(usagestr, options);
1034 break;
1035 case PARSE_OPT_UNKNOWN:
1036 if (ctx.argv[0][1] == '-') {
1037 error(_("unknown option `%s'"), ctx.argv[0] + 2);
1038 } else if (isascii(*ctx.opt)) {
1039 error(_("unknown switch `%c'"), *ctx.opt);
1040 } else {
1041 error(_("unknown non-ascii option in string: `%s'"),
1042 ctx.argv[0]);
1044 usage_with_options(usagestr, options);
1047 precompose_argv_prefix(argc, argv, NULL);
1048 free_preprocessed_options(real_options);
1049 free(ctx.alias_groups);
1050 for (struct parse_opt_cmdmode_list *elem = ctx.cmdmode_list; elem;) {
1051 struct parse_opt_cmdmode_list *next = elem->next;
1052 free(elem);
1053 elem = next;
1055 return parse_options_end(&ctx);
1058 static int usage_argh(const struct option *opts, FILE *outfile)
1060 const char *s;
1061 int literal = (opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1062 !opts->argh || !!strpbrk(opts->argh, "()<>[]|");
1063 if (opts->flags & PARSE_OPT_OPTARG)
1064 if (opts->long_name)
1065 s = literal ? "[=%s]" : "[=<%s>]";
1066 else
1067 s = literal ? "[%s]" : "[<%s>]";
1068 else
1069 s = literal ? " %s" : " <%s>";
1070 return utf8_fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
1073 static int usage_indent(FILE *outfile)
1075 return fprintf(outfile, " ");
1078 #define USAGE_OPTS_WIDTH 26
1080 static void usage_padding(FILE *outfile, size_t pos)
1082 if (pos < USAGE_OPTS_WIDTH)
1083 fprintf(outfile, "%*s", USAGE_OPTS_WIDTH - (int)pos, "");
1084 else
1085 fprintf(outfile, "\n%*s", USAGE_OPTS_WIDTH, "");
1088 static const struct option *find_option_by_long_name(const struct option *opts,
1089 const char *long_name)
1091 for (; opts->type != OPTION_END; opts++) {
1092 if (opts->long_name && !strcmp(opts->long_name, long_name))
1093 return opts;
1095 return NULL;
1098 static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t *ctx,
1099 const char * const *usagestr,
1100 const struct option *opts,
1101 int full, int err)
1103 const struct option *all_opts = opts;
1104 FILE *outfile = err ? stderr : stdout;
1105 int need_newline;
1107 const char *usage_prefix = _("usage: %s");
1109 * The translation could be anything, but we can count on
1110 * msgfmt(1)'s --check option to have asserted that "%s" is in
1111 * the translation. So compute the length of the "usage: "
1112 * part. We are assuming that the translator wasn't overly
1113 * clever and used e.g. "%1$s" instead of "%s", there's only
1114 * one "%s" in "usage_prefix" above, so there's no reason to
1115 * do so even with a RTL language.
1117 size_t usage_len = strlen(usage_prefix) - strlen("%s");
1119 * TRANSLATORS: the colon here should align with the
1120 * one in "usage: %s" translation.
1122 const char *or_prefix = _(" or: %s");
1124 * TRANSLATORS: You should only need to translate this format
1125 * string if your language is a RTL language (e.g. Arabic,
1126 * Hebrew etc.), not if it's a LTR language (e.g. German,
1127 * Russian, Chinese etc.).
1129 * When a translated usage string has an embedded "\n" it's
1130 * because options have wrapped to the next line. The line
1131 * after the "\n" will then be padded to align with the
1132 * command name, such as N_("git cmd [opt]\n<8
1133 * spaces>[opt2]"), where the 8 spaces are the same length as
1134 * "git cmd ".
1136 * This format string prints out that already-translated
1137 * line. The "%*s" is whitespace padding to account for the
1138 * padding at the start of the line that we add in this
1139 * function. The "%s" is a line in the (hopefully already
1140 * translated) N_() usage string, which contained embedded
1141 * newlines before we split it up.
1143 const char *usage_continued = _("%*s%s");
1144 const char *prefix = usage_prefix;
1145 int saw_empty_line = 0;
1147 if (!usagestr)
1148 return PARSE_OPT_HELP;
1150 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1151 fprintf(outfile, "cat <<\\EOF\n");
1153 while (*usagestr) {
1154 const char *str = _(*usagestr++);
1155 struct string_list list = STRING_LIST_INIT_DUP;
1156 unsigned int j;
1158 if (!saw_empty_line && !*str)
1159 saw_empty_line = 1;
1161 string_list_split(&list, str, '\n', -1);
1162 for (j = 0; j < list.nr; j++) {
1163 const char *line = list.items[j].string;
1165 if (saw_empty_line && *line)
1166 fprintf_ln(outfile, _(" %s"), line);
1167 else if (saw_empty_line)
1168 fputc('\n', outfile);
1169 else if (!j)
1170 fprintf_ln(outfile, prefix, line);
1171 else
1172 fprintf_ln(outfile, usage_continued,
1173 (int)usage_len, "", line);
1175 string_list_clear(&list, 0);
1177 prefix = or_prefix;
1180 need_newline = 1;
1182 for (; opts->type != OPTION_END; opts++) {
1183 size_t pos;
1184 const char *cp, *np;
1185 const char *positive_name = NULL;
1187 if (opts->type == OPTION_SUBCOMMAND)
1188 continue;
1189 if (opts->type == OPTION_GROUP) {
1190 fputc('\n', outfile);
1191 need_newline = 0;
1192 if (*opts->help)
1193 fprintf(outfile, "%s\n", _(opts->help));
1194 continue;
1196 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
1197 continue;
1199 if (need_newline) {
1200 fputc('\n', outfile);
1201 need_newline = 0;
1204 pos = usage_indent(outfile);
1205 if (opts->short_name) {
1206 if (opts->flags & PARSE_OPT_NODASH)
1207 pos += fprintf(outfile, "%c", opts->short_name);
1208 else
1209 pos += fprintf(outfile, "-%c", opts->short_name);
1211 if (opts->long_name && opts->short_name)
1212 pos += fprintf(outfile, ", ");
1213 if (opts->long_name) {
1214 const char *long_name = opts->long_name;
1215 if ((opts->flags & PARSE_OPT_NONEG) ||
1216 skip_prefix(long_name, "no-", &positive_name))
1217 pos += fprintf(outfile, "--%s", long_name);
1218 else
1219 pos += fprintf(outfile, "--[no-]%s", long_name);
1222 if (opts->type == OPTION_NUMBER)
1223 pos += utf8_fprintf(outfile, _("-NUM"));
1225 if ((opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1226 !(opts->flags & PARSE_OPT_NOARG))
1227 pos += usage_argh(opts, outfile);
1229 if (opts->type == OPTION_ALIAS) {
1230 usage_padding(outfile, pos);
1231 fprintf_ln(outfile, _("alias of --%s"),
1232 (const char *)opts->value);
1233 continue;
1236 for (cp = opts->help ? _(opts->help) : ""; *cp; cp = np) {
1237 np = strchrnul(cp, '\n');
1238 if (*np)
1239 np++;
1240 usage_padding(outfile, pos);
1241 fwrite(cp, 1, np - cp, outfile);
1242 pos = 0;
1244 fputc('\n', outfile);
1246 if (positive_name) {
1247 if (find_option_by_long_name(all_opts, positive_name))
1248 continue;
1249 pos = usage_indent(outfile);
1250 pos += fprintf(outfile, "--%s", positive_name);
1251 usage_padding(outfile, pos);
1252 fprintf_ln(outfile, _("opposite of --no-%s"),
1253 positive_name);
1256 fputc('\n', outfile);
1258 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1259 fputs("EOF\n", outfile);
1261 return PARSE_OPT_HELP;
1264 void NORETURN usage_with_options(const char * const *usagestr,
1265 const struct option *opts)
1267 usage_with_options_internal(NULL, usagestr, opts, 0, 1);
1268 exit(129);
1271 void NORETURN usage_msg_opt(const char *msg,
1272 const char * const *usagestr,
1273 const struct option *options)
1275 die_message("%s\n", msg); /* The extra \n is intentional */
1276 usage_with_options(usagestr, options);
1279 void NORETURN usage_msg_optf(const char * const fmt,
1280 const char * const *usagestr,
1281 const struct option *options, ...)
1283 struct strbuf msg = STRBUF_INIT;
1284 va_list ap;
1285 va_start(ap, options);
1286 strbuf_vaddf(&msg, fmt, ap);
1287 va_end(ap);
1289 usage_msg_opt(msg.buf, usagestr, options);
1292 void die_for_incompatible_opt4(int opt1, const char *opt1_name,
1293 int opt2, const char *opt2_name,
1294 int opt3, const char *opt3_name,
1295 int opt4, const char *opt4_name)
1297 int count = 0;
1298 const char *options[4];
1300 if (opt1)
1301 options[count++] = opt1_name;
1302 if (opt2)
1303 options[count++] = opt2_name;
1304 if (opt3)
1305 options[count++] = opt3_name;
1306 if (opt4)
1307 options[count++] = opt4_name;
1308 switch (count) {
1309 case 4:
1310 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
1311 opt1_name, opt2_name, opt3_name, opt4_name);
1312 break;
1313 case 3:
1314 die(_("options '%s', '%s', and '%s' cannot be used together"),
1315 options[0], options[1], options[2]);
1316 break;
1317 case 2:
1318 die(_("options '%s' and '%s' cannot be used together"),
1319 options[0], options[1]);
1320 break;
1321 default:
1322 break;