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