]> git.ipfire.org Git - thirdparty/git.git/blob - parse-options.c
Merge branch 'ps/git-repack-doc-fixes'
[thirdparty/git.git] / parse-options.c
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"
11
12 static int disallow_abbreviated_options;
13
14 enum opt_parsed {
15 OPT_LONG = 0,
16 OPT_SHORT = 1<<0,
17 OPT_UNSET = 1<<1,
18 };
19
20 static void optbug(const struct option *opt, const char *reason)
21 {
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);
29 }
30
31 static const char *optname(const struct option *opt, enum opt_parsed flags)
32 {
33 static struct strbuf sb = STRBUF_INIT;
34
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);
44
45 return sb.buf;
46 }
47
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)
51 {
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;
63 }
64
65 static void fix_filename(const char *prefix, char **file)
66 {
67 if (!file || !*file)
68 ; /* leave as NULL */
69 else
70 *file = prefix_filename_except_for_dash(prefix, *file);
71 }
72
73 static enum parse_opt_result opt_command_mode_error(
74 const struct option *opt,
75 const struct option *all_opts,
76 enum opt_parsed flags)
77 {
78 const struct option *that;
79 struct strbuf that_name = STRBUF_INIT;
80
81 /*
82 * Find the other option that was used to set the variable
83 * already, and report that this is not compatible with it.
84 */
85 for (that = all_opts; that->type != OPTION_END; that++) {
86 if (that == opt ||
87 !(that->flags & PARSE_OPT_CMDMODE) ||
88 that->value != opt->value ||
89 that->defval != *(int *)opt->value)
90 continue;
91
92 if (that->long_name)
93 strbuf_addf(&that_name, "--%s", that->long_name);
94 else
95 strbuf_addf(&that_name, "-%c", that->short_name);
96 error(_("%s is incompatible with %s"),
97 optname(opt, flags), that_name.buf);
98 strbuf_release(&that_name);
99 return PARSE_OPT_ERROR;
100 }
101 return error(_("%s : incompatible with something else"),
102 optname(opt, flags));
103 }
104
105 static enum parse_opt_result get_value(struct parse_opt_ctx_t *p,
106 const struct option *opt,
107 const struct option *all_opts,
108 enum opt_parsed flags)
109 {
110 const char *s, *arg;
111 const int unset = flags & OPT_UNSET;
112 int err;
113
114 if (unset && p->opt)
115 return error(_("%s takes no value"), optname(opt, flags));
116 if (unset && (opt->flags & PARSE_OPT_NONEG))
117 return error(_("%s isn't available"), optname(opt, flags));
118 if (!(flags & OPT_SHORT) && p->opt && (opt->flags & PARSE_OPT_NOARG))
119 return error(_("%s takes no value"), optname(opt, flags));
120
121 /*
122 * Giving the same mode option twice, although unnecessary,
123 * is not a grave error, so let it pass.
124 */
125 if ((opt->flags & PARSE_OPT_CMDMODE) &&
126 *(int *)opt->value && *(int *)opt->value != opt->defval)
127 return opt_command_mode_error(opt, all_opts, flags);
128
129 switch (opt->type) {
130 case OPTION_LOWLEVEL_CALLBACK:
131 return opt->ll_callback(p, opt, NULL, unset);
132
133 case OPTION_BIT:
134 if (unset)
135 *(int *)opt->value &= ~opt->defval;
136 else
137 *(int *)opt->value |= opt->defval;
138 return 0;
139
140 case OPTION_NEGBIT:
141 if (unset)
142 *(int *)opt->value |= opt->defval;
143 else
144 *(int *)opt->value &= ~opt->defval;
145 return 0;
146
147 case OPTION_BITOP:
148 if (unset)
149 BUG("BITOP can't have unset form");
150 *(int *)opt->value &= ~opt->extra;
151 *(int *)opt->value |= opt->defval;
152 return 0;
153
154 case OPTION_COUNTUP:
155 if (*(int *)opt->value < 0)
156 *(int *)opt->value = 0;
157 *(int *)opt->value = unset ? 0 : *(int *)opt->value + 1;
158 return 0;
159
160 case OPTION_SET_INT:
161 *(int *)opt->value = unset ? 0 : opt->defval;
162 return 0;
163
164 case OPTION_STRING:
165 if (unset)
166 *(const char **)opt->value = NULL;
167 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
168 *(const char **)opt->value = (const char *)opt->defval;
169 else
170 return get_arg(p, opt, flags, (const char **)opt->value);
171 return 0;
172
173 case OPTION_FILENAME:
174 err = 0;
175 if (unset)
176 *(const char **)opt->value = NULL;
177 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
178 *(const char **)opt->value = (const char *)opt->defval;
179 else
180 err = get_arg(p, opt, flags, (const char **)opt->value);
181
182 if (!err)
183 fix_filename(p->prefix, (char **)opt->value);
184 return err;
185
186 case OPTION_CALLBACK:
187 {
188 const char *p_arg = NULL;
189 int p_unset;
190
191 if (unset)
192 p_unset = 1;
193 else if (opt->flags & PARSE_OPT_NOARG)
194 p_unset = 0;
195 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
196 p_unset = 0;
197 else if (get_arg(p, opt, flags, &arg))
198 return -1;
199 else {
200 p_unset = 0;
201 p_arg = arg;
202 }
203 if (opt->callback)
204 return (*opt->callback)(opt, p_arg, p_unset) ? (-1) : 0;
205 else
206 return (*opt->ll_callback)(p, opt, p_arg, p_unset);
207 }
208 case OPTION_INTEGER:
209 if (unset) {
210 *(int *)opt->value = 0;
211 return 0;
212 }
213 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
214 *(int *)opt->value = opt->defval;
215 return 0;
216 }
217 if (get_arg(p, opt, flags, &arg))
218 return -1;
219 if (!*arg)
220 return error(_("%s expects a numerical value"),
221 optname(opt, flags));
222 *(int *)opt->value = strtol(arg, (char **)&s, 10);
223 if (*s)
224 return error(_("%s expects a numerical value"),
225 optname(opt, flags));
226 return 0;
227
228 case OPTION_MAGNITUDE:
229 if (unset) {
230 *(unsigned long *)opt->value = 0;
231 return 0;
232 }
233 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
234 *(unsigned long *)opt->value = opt->defval;
235 return 0;
236 }
237 if (get_arg(p, opt, flags, &arg))
238 return -1;
239 if (!git_parse_ulong(arg, opt->value))
240 return error(_("%s expects a non-negative integer value"
241 " with an optional k/m/g suffix"),
242 optname(opt, flags));
243 return 0;
244
245 default:
246 BUG("opt->type %d should not happen", opt->type);
247 }
248 }
249
250 static enum parse_opt_result parse_short_opt(struct parse_opt_ctx_t *p,
251 const struct option *options)
252 {
253 const struct option *all_opts = options;
254 const struct option *numopt = NULL;
255
256 for (; options->type != OPTION_END; options++) {
257 if (options->short_name == *p->opt) {
258 p->opt = p->opt[1] ? p->opt + 1 : NULL;
259 return get_value(p, options, all_opts, OPT_SHORT);
260 }
261
262 /*
263 * Handle the numerical option later, explicit one-digit
264 * options take precedence over it.
265 */
266 if (options->type == OPTION_NUMBER)
267 numopt = options;
268 }
269 if (numopt && isdigit(*p->opt)) {
270 size_t len = 1;
271 char *arg;
272 int rc;
273
274 while (isdigit(p->opt[len]))
275 len++;
276 arg = xmemdupz(p->opt, len);
277 p->opt = p->opt[len] ? p->opt + len : NULL;
278 if (numopt->callback)
279 rc = (*numopt->callback)(numopt, arg, 0) ? (-1) : 0;
280 else
281 rc = (*numopt->ll_callback)(p, numopt, arg, 0);
282 free(arg);
283 return rc;
284 }
285 return PARSE_OPT_UNKNOWN;
286 }
287
288 static int has_string(const char *it, const char **array)
289 {
290 while (*array)
291 if (!strcmp(it, *(array++)))
292 return 1;
293 return 0;
294 }
295
296 static int is_alias(struct parse_opt_ctx_t *ctx,
297 const struct option *one_opt,
298 const struct option *another_opt)
299 {
300 const char **group;
301
302 if (!ctx->alias_groups)
303 return 0;
304
305 if (!one_opt->long_name || !another_opt->long_name)
306 return 0;
307
308 for (group = ctx->alias_groups; *group; group += 3) {
309 /* it and other are from the same family? */
310 if (has_string(one_opt->long_name, group) &&
311 has_string(another_opt->long_name, group))
312 return 1;
313 }
314 return 0;
315 }
316
317 static enum parse_opt_result parse_long_opt(
318 struct parse_opt_ctx_t *p, const char *arg,
319 const struct option *options)
320 {
321 const struct option *all_opts = options;
322 const char *arg_end = strchrnul(arg, '=');
323 const struct option *abbrev_option = NULL, *ambiguous_option = NULL;
324 enum opt_parsed abbrev_flags = OPT_LONG, ambiguous_flags = OPT_LONG;
325
326 for (; options->type != OPTION_END; options++) {
327 const char *rest, *long_name = options->long_name;
328 enum opt_parsed flags = OPT_LONG, opt_flags = OPT_LONG;
329
330 if (options->type == OPTION_SUBCOMMAND)
331 continue;
332 if (!long_name)
333 continue;
334
335 again:
336 if (!skip_prefix(arg, long_name, &rest))
337 rest = NULL;
338 if (!rest) {
339 /* abbreviated? */
340 if (!(p->flags & PARSE_OPT_KEEP_UNKNOWN_OPT) &&
341 !strncmp(long_name, arg, arg_end - arg)) {
342 is_abbreviated:
343 if (abbrev_option &&
344 !is_alias(p, abbrev_option, options)) {
345 /*
346 * If this is abbreviated, it is
347 * ambiguous. So when there is no
348 * exact match later, we need to
349 * error out.
350 */
351 ambiguous_option = abbrev_option;
352 ambiguous_flags = abbrev_flags;
353 }
354 if (!(flags & OPT_UNSET) && *arg_end)
355 p->opt = arg_end + 1;
356 abbrev_option = options;
357 abbrev_flags = flags ^ opt_flags;
358 continue;
359 }
360 /* negation allowed? */
361 if (options->flags & PARSE_OPT_NONEG)
362 continue;
363 /* negated and abbreviated very much? */
364 if (starts_with("no-", arg)) {
365 flags |= OPT_UNSET;
366 goto is_abbreviated;
367 }
368 /* negated? */
369 if (!starts_with(arg, "no-")) {
370 if (skip_prefix(long_name, "no-", &long_name)) {
371 opt_flags |= OPT_UNSET;
372 goto again;
373 }
374 continue;
375 }
376 flags |= OPT_UNSET;
377 if (!skip_prefix(arg + 3, long_name, &rest)) {
378 /* abbreviated and negated? */
379 if (starts_with(long_name, arg + 3))
380 goto is_abbreviated;
381 else
382 continue;
383 }
384 }
385 if (*rest) {
386 if (*rest != '=')
387 continue;
388 p->opt = rest + 1;
389 }
390 return get_value(p, options, all_opts, flags ^ opt_flags);
391 }
392
393 if (disallow_abbreviated_options && (ambiguous_option || abbrev_option))
394 die("disallowed abbreviated or ambiguous option '%.*s'",
395 (int)(arg_end - arg), arg);
396
397 if (ambiguous_option) {
398 error(_("ambiguous option: %s "
399 "(could be --%s%s or --%s%s)"),
400 arg,
401 (ambiguous_flags & OPT_UNSET) ? "no-" : "",
402 ambiguous_option->long_name,
403 (abbrev_flags & OPT_UNSET) ? "no-" : "",
404 abbrev_option->long_name);
405 return PARSE_OPT_HELP;
406 }
407 if (abbrev_option)
408 return get_value(p, abbrev_option, all_opts, abbrev_flags);
409 return PARSE_OPT_UNKNOWN;
410 }
411
412 static enum parse_opt_result parse_nodash_opt(struct parse_opt_ctx_t *p,
413 const char *arg,
414 const struct option *options)
415 {
416 const struct option *all_opts = options;
417
418 for (; options->type != OPTION_END; options++) {
419 if (!(options->flags & PARSE_OPT_NODASH))
420 continue;
421 if (options->short_name == arg[0] && arg[1] == '\0')
422 return get_value(p, options, all_opts, OPT_SHORT);
423 }
424 return PARSE_OPT_ERROR;
425 }
426
427 static enum parse_opt_result parse_subcommand(const char *arg,
428 const struct option *options)
429 {
430 for (; options->type != OPTION_END; options++)
431 if (options->type == OPTION_SUBCOMMAND &&
432 !strcmp(options->long_name, arg)) {
433 *(parse_opt_subcommand_fn **)options->value = options->subcommand_fn;
434 return PARSE_OPT_SUBCOMMAND;
435 }
436
437 return PARSE_OPT_UNKNOWN;
438 }
439
440 static void check_typos(const char *arg, const struct option *options)
441 {
442 if (strlen(arg) < 3)
443 return;
444
445 if (starts_with(arg, "no-")) {
446 error(_("did you mean `--%s` (with two dashes)?"), arg);
447 exit(129);
448 }
449
450 for (; options->type != OPTION_END; options++) {
451 if (!options->long_name)
452 continue;
453 if (starts_with(options->long_name, arg)) {
454 error(_("did you mean `--%s` (with two dashes)?"), arg);
455 exit(129);
456 }
457 }
458 }
459
460 static void parse_options_check(const struct option *opts)
461 {
462 char short_opts[128];
463 void *subcommand_value = NULL;
464
465 memset(short_opts, '\0', sizeof(short_opts));
466 for (; opts->type != OPTION_END; opts++) {
467 if ((opts->flags & PARSE_OPT_LASTARG_DEFAULT) &&
468 (opts->flags & PARSE_OPT_OPTARG))
469 optbug(opts, "uses incompatible flags "
470 "LASTARG_DEFAULT and OPTARG");
471 if (opts->short_name) {
472 if (0x7F <= opts->short_name)
473 optbug(opts, "invalid short name");
474 else if (short_opts[opts->short_name]++)
475 optbug(opts, "short name already used");
476 }
477 if (opts->flags & PARSE_OPT_NODASH &&
478 ((opts->flags & PARSE_OPT_OPTARG) ||
479 !(opts->flags & PARSE_OPT_NOARG) ||
480 !(opts->flags & PARSE_OPT_NONEG) ||
481 opts->long_name))
482 optbug(opts, "uses feature "
483 "not supported for dashless options");
484 if (opts->type == OPTION_SET_INT && !opts->defval &&
485 opts->long_name && !(opts->flags & PARSE_OPT_NONEG))
486 optbug(opts, "OPTION_SET_INT 0 should not be negatable");
487 switch (opts->type) {
488 case OPTION_COUNTUP:
489 case OPTION_BIT:
490 case OPTION_NEGBIT:
491 case OPTION_SET_INT:
492 case OPTION_NUMBER:
493 if ((opts->flags & PARSE_OPT_OPTARG) ||
494 !(opts->flags & PARSE_OPT_NOARG))
495 optbug(opts, "should not accept an argument");
496 break;
497 case OPTION_CALLBACK:
498 if (!opts->callback && !opts->ll_callback)
499 optbug(opts, "OPTION_CALLBACK needs one callback");
500 else if (opts->callback && opts->ll_callback)
501 optbug(opts, "OPTION_CALLBACK can't have two callbacks");
502 break;
503 case OPTION_LOWLEVEL_CALLBACK:
504 if (!opts->ll_callback)
505 optbug(opts, "OPTION_LOWLEVEL_CALLBACK needs a callback");
506 if (opts->callback)
507 optbug(opts, "OPTION_LOWLEVEL_CALLBACK needs no high level callback");
508 break;
509 case OPTION_ALIAS:
510 optbug(opts, "OPT_ALIAS() should not remain at this point. "
511 "Are you using parse_options_step() directly?\n"
512 "That case is not supported yet.");
513 break;
514 case OPTION_SUBCOMMAND:
515 if (!opts->value || !opts->subcommand_fn)
516 optbug(opts, "OPTION_SUBCOMMAND needs a value and a subcommand function");
517 if (!subcommand_value)
518 subcommand_value = opts->value;
519 else if (subcommand_value != opts->value)
520 optbug(opts, "all OPTION_SUBCOMMANDs need the same value");
521 break;
522 default:
523 ; /* ok. (usually accepts an argument) */
524 }
525 if (opts->argh &&
526 strcspn(opts->argh, " _") != strlen(opts->argh))
527 optbug(opts, "multi-word argh should use dash to separate words");
528 }
529 BUG_if_bug("invalid 'struct option'");
530 }
531
532 static int has_subcommands(const struct option *options)
533 {
534 for (; options->type != OPTION_END; options++)
535 if (options->type == OPTION_SUBCOMMAND)
536 return 1;
537 return 0;
538 }
539
540 static void parse_options_start_1(struct parse_opt_ctx_t *ctx,
541 int argc, const char **argv, const char *prefix,
542 const struct option *options,
543 enum parse_opt_flags flags)
544 {
545 ctx->argc = argc;
546 ctx->argv = argv;
547 if (!(flags & PARSE_OPT_ONE_SHOT)) {
548 ctx->argc--;
549 ctx->argv++;
550 }
551 ctx->total = ctx->argc;
552 ctx->out = argv;
553 ctx->prefix = prefix;
554 ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
555 ctx->flags = flags;
556 ctx->has_subcommands = has_subcommands(options);
557 if (!ctx->has_subcommands && (flags & PARSE_OPT_SUBCOMMAND_OPTIONAL))
558 BUG("Using PARSE_OPT_SUBCOMMAND_OPTIONAL without subcommands");
559 if (ctx->has_subcommands) {
560 if (flags & PARSE_OPT_STOP_AT_NON_OPTION)
561 BUG("subcommands are incompatible with PARSE_OPT_STOP_AT_NON_OPTION");
562 if (!(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
563 if (flags & PARSE_OPT_KEEP_UNKNOWN_OPT)
564 BUG("subcommands are incompatible with PARSE_OPT_KEEP_UNKNOWN_OPT unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
565 if (flags & PARSE_OPT_KEEP_DASHDASH)
566 BUG("subcommands are incompatible with PARSE_OPT_KEEP_DASHDASH unless in combination with PARSE_OPT_SUBCOMMAND_OPTIONAL");
567 }
568 }
569 if ((flags & PARSE_OPT_KEEP_UNKNOWN_OPT) &&
570 (flags & PARSE_OPT_STOP_AT_NON_OPTION) &&
571 !(flags & PARSE_OPT_ONE_SHOT))
572 BUG("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
573 if ((flags & PARSE_OPT_ONE_SHOT) &&
574 (flags & PARSE_OPT_KEEP_ARGV0))
575 BUG("Can't keep argv0 if you don't have it");
576 parse_options_check(options);
577 }
578
579 void parse_options_start(struct parse_opt_ctx_t *ctx,
580 int argc, const char **argv, const char *prefix,
581 const struct option *options,
582 enum parse_opt_flags flags)
583 {
584 memset(ctx, 0, sizeof(*ctx));
585 parse_options_start_1(ctx, argc, argv, prefix, options, flags);
586 }
587
588 static void show_negated_gitcomp(const struct option *opts, int show_all,
589 int nr_noopts)
590 {
591 int printed_dashdash = 0;
592
593 for (; opts->type != OPTION_END; opts++) {
594 int has_unset_form = 0;
595 const char *name;
596
597 if (!opts->long_name)
598 continue;
599 if (!show_all &&
600 (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE)))
601 continue;
602 if (opts->flags & PARSE_OPT_NONEG)
603 continue;
604
605 switch (opts->type) {
606 case OPTION_STRING:
607 case OPTION_FILENAME:
608 case OPTION_INTEGER:
609 case OPTION_MAGNITUDE:
610 case OPTION_CALLBACK:
611 case OPTION_BIT:
612 case OPTION_NEGBIT:
613 case OPTION_COUNTUP:
614 case OPTION_SET_INT:
615 has_unset_form = 1;
616 break;
617 default:
618 break;
619 }
620 if (!has_unset_form)
621 continue;
622
623 if (skip_prefix(opts->long_name, "no-", &name)) {
624 if (nr_noopts < 0)
625 printf(" --%s", name);
626 } else if (nr_noopts >= 0) {
627 if (nr_noopts && !printed_dashdash) {
628 printf(" --");
629 printed_dashdash = 1;
630 }
631 printf(" --no-%s", opts->long_name);
632 nr_noopts++;
633 }
634 }
635 }
636
637 static int show_gitcomp(const struct option *opts, int show_all)
638 {
639 const struct option *original_opts = opts;
640 int nr_noopts = 0;
641
642 for (; opts->type != OPTION_END; opts++) {
643 const char *prefix = "--";
644 const char *suffix = "";
645
646 if (!opts->long_name)
647 continue;
648 if (!show_all &&
649 (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE | PARSE_OPT_FROM_ALIAS)))
650 continue;
651
652 switch (opts->type) {
653 case OPTION_SUBCOMMAND:
654 prefix = "";
655 break;
656 case OPTION_GROUP:
657 continue;
658 case OPTION_STRING:
659 case OPTION_FILENAME:
660 case OPTION_INTEGER:
661 case OPTION_MAGNITUDE:
662 case OPTION_CALLBACK:
663 if (opts->flags & PARSE_OPT_NOARG)
664 break;
665 if (opts->flags & PARSE_OPT_OPTARG)
666 break;
667 if (opts->flags & PARSE_OPT_LASTARG_DEFAULT)
668 break;
669 suffix = "=";
670 break;
671 default:
672 break;
673 }
674 if (opts->flags & PARSE_OPT_COMP_ARG)
675 suffix = "=";
676 if (starts_with(opts->long_name, "no-"))
677 nr_noopts++;
678 printf("%s%s%s%s", opts == original_opts ? "" : " ",
679 prefix, opts->long_name, suffix);
680 }
681 show_negated_gitcomp(original_opts, show_all, -1);
682 show_negated_gitcomp(original_opts, show_all, nr_noopts);
683 fputc('\n', stdout);
684 return PARSE_OPT_COMPLETE;
685 }
686
687 /*
688 * Scan and may produce a new option[] array, which should be used
689 * instead of the original 'options'.
690 *
691 * Right now this is only used to preprocess and substitute
692 * OPTION_ALIAS.
693 *
694 * The returned options should be freed using free_preprocessed_options.
695 */
696 static struct option *preprocess_options(struct parse_opt_ctx_t *ctx,
697 const struct option *options)
698 {
699 struct option *newopt;
700 int i, nr, alias;
701 int nr_aliases = 0;
702
703 for (nr = 0; options[nr].type != OPTION_END; nr++) {
704 if (options[nr].type == OPTION_ALIAS)
705 nr_aliases++;
706 }
707
708 if (!nr_aliases)
709 return NULL;
710
711 DUP_ARRAY(newopt, options, nr + 1);
712
713 /* each alias has two string pointers and NULL */
714 CALLOC_ARRAY(ctx->alias_groups, 3 * (nr_aliases + 1));
715
716 for (alias = 0, i = 0; i < nr; i++) {
717 int short_name;
718 const char *long_name;
719 const char *source;
720 struct strbuf help = STRBUF_INIT;
721 int j;
722
723 if (newopt[i].type != OPTION_ALIAS)
724 continue;
725
726 short_name = newopt[i].short_name;
727 long_name = newopt[i].long_name;
728 source = newopt[i].value;
729
730 if (!long_name)
731 BUG("An alias must have long option name");
732 strbuf_addf(&help, _("alias of --%s"), source);
733
734 for (j = 0; j < nr; j++) {
735 const char *name = options[j].long_name;
736
737 if (!name || strcmp(name, source))
738 continue;
739
740 if (options[j].type == OPTION_ALIAS)
741 BUG("No please. Nested aliases are not supported.");
742
743 memcpy(newopt + i, options + j, sizeof(*newopt));
744 newopt[i].short_name = short_name;
745 newopt[i].long_name = long_name;
746 newopt[i].help = strbuf_detach(&help, NULL);
747 newopt[i].flags |= PARSE_OPT_FROM_ALIAS;
748 break;
749 }
750
751 if (j == nr)
752 BUG("could not find source option '%s' of alias '%s'",
753 source, newopt[i].long_name);
754 ctx->alias_groups[alias * 3 + 0] = newopt[i].long_name;
755 ctx->alias_groups[alias * 3 + 1] = options[j].long_name;
756 ctx->alias_groups[alias * 3 + 2] = NULL;
757 alias++;
758 }
759
760 return newopt;
761 }
762
763 static void free_preprocessed_options(struct option *options)
764 {
765 int i;
766
767 if (!options)
768 return;
769
770 for (i = 0; options[i].type != OPTION_END; i++) {
771 if (options[i].flags & PARSE_OPT_FROM_ALIAS)
772 free((void *)options[i].help);
773 }
774 free(options);
775 }
776
777 static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t *,
778 const char * const *,
779 const struct option *,
780 int, int);
781
782 enum parse_opt_result parse_options_step(struct parse_opt_ctx_t *ctx,
783 const struct option *options,
784 const char * const usagestr[])
785 {
786 int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
787
788 /* we must reset ->opt, unknown short option leave it dangling */
789 ctx->opt = NULL;
790
791 for (; ctx->argc; ctx->argc--, ctx->argv++) {
792 const char *arg = ctx->argv[0];
793
794 if (ctx->flags & PARSE_OPT_ONE_SHOT &&
795 ctx->argc != ctx->total)
796 break;
797
798 if (*arg != '-' || !arg[1]) {
799 if (parse_nodash_opt(ctx, arg, options) == 0)
800 continue;
801 if (!ctx->has_subcommands) {
802 if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
803 return PARSE_OPT_NON_OPTION;
804 ctx->out[ctx->cpidx++] = ctx->argv[0];
805 continue;
806 }
807 switch (parse_subcommand(arg, options)) {
808 case PARSE_OPT_SUBCOMMAND:
809 return PARSE_OPT_SUBCOMMAND;
810 case PARSE_OPT_UNKNOWN:
811 if (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)
812 /*
813 * arg is neither a short or long
814 * option nor a subcommand. Since
815 * this command has a default
816 * operation mode, we have to treat
817 * this arg and all remaining args
818 * as args meant to that default
819 * operation mode.
820 * So we are done parsing.
821 */
822 return PARSE_OPT_DONE;
823 error(_("unknown subcommand: `%s'"), arg);
824 usage_with_options(usagestr, options);
825 case PARSE_OPT_COMPLETE:
826 case PARSE_OPT_HELP:
827 case PARSE_OPT_ERROR:
828 case PARSE_OPT_DONE:
829 case PARSE_OPT_NON_OPTION:
830 /* Impossible. */
831 BUG("parse_subcommand() cannot return these");
832 }
833 }
834
835 /* lone -h asks for help */
836 if (internal_help && ctx->total == 1 && !strcmp(arg + 1, "h"))
837 goto show_usage;
838
839 /*
840 * lone --git-completion-helper and --git-completion-helper-all
841 * are asked by git-completion.bash
842 */
843 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper"))
844 return show_gitcomp(options, 0);
845 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper-all"))
846 return show_gitcomp(options, 1);
847
848 if (arg[1] != '-') {
849 ctx->opt = arg + 1;
850 switch (parse_short_opt(ctx, options)) {
851 case PARSE_OPT_ERROR:
852 return PARSE_OPT_ERROR;
853 case PARSE_OPT_UNKNOWN:
854 if (ctx->opt)
855 check_typos(arg + 1, options);
856 if (internal_help && *ctx->opt == 'h')
857 goto show_usage;
858 goto unknown;
859 case PARSE_OPT_NON_OPTION:
860 case PARSE_OPT_SUBCOMMAND:
861 case PARSE_OPT_HELP:
862 case PARSE_OPT_COMPLETE:
863 BUG("parse_short_opt() cannot return these");
864 case PARSE_OPT_DONE:
865 break;
866 }
867 if (ctx->opt)
868 check_typos(arg + 1, options);
869 while (ctx->opt) {
870 switch (parse_short_opt(ctx, options)) {
871 case PARSE_OPT_ERROR:
872 return PARSE_OPT_ERROR;
873 case PARSE_OPT_UNKNOWN:
874 if (internal_help && *ctx->opt == 'h')
875 goto show_usage;
876
877 /* fake a short option thing to hide the fact that we may have
878 * started to parse aggregated stuff
879 *
880 * This is leaky, too bad.
881 */
882 ctx->argv[0] = xstrdup(ctx->opt - 1);
883 *(char *)ctx->argv[0] = '-';
884 goto unknown;
885 case PARSE_OPT_NON_OPTION:
886 case PARSE_OPT_SUBCOMMAND:
887 case PARSE_OPT_COMPLETE:
888 case PARSE_OPT_HELP:
889 BUG("parse_short_opt() cannot return these");
890 case PARSE_OPT_DONE:
891 break;
892 }
893 }
894 continue;
895 }
896
897 if (!arg[2] /* "--" */ ||
898 !strcmp(arg + 2, "end-of-options")) {
899 if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
900 ctx->argc--;
901 ctx->argv++;
902 }
903 break;
904 }
905
906 if (internal_help && !strcmp(arg + 2, "help-all"))
907 return usage_with_options_internal(ctx, usagestr, options, 1, 0);
908 if (internal_help && !strcmp(arg + 2, "help"))
909 goto show_usage;
910 switch (parse_long_opt(ctx, arg + 2, options)) {
911 case PARSE_OPT_ERROR:
912 return PARSE_OPT_ERROR;
913 case PARSE_OPT_UNKNOWN:
914 goto unknown;
915 case PARSE_OPT_HELP:
916 goto show_usage;
917 case PARSE_OPT_NON_OPTION:
918 case PARSE_OPT_SUBCOMMAND:
919 case PARSE_OPT_COMPLETE:
920 BUG("parse_long_opt() cannot return these");
921 case PARSE_OPT_DONE:
922 break;
923 }
924 continue;
925 unknown:
926 if (ctx->flags & PARSE_OPT_ONE_SHOT)
927 break;
928 if (ctx->has_subcommands &&
929 (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL) &&
930 (ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)) {
931 /*
932 * Found an unknown option given to a command with
933 * subcommands that has a default operation mode:
934 * we treat this option and all remaining args as
935 * arguments meant to that default operation mode.
936 * So we are done parsing.
937 */
938 return PARSE_OPT_DONE;
939 }
940 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT))
941 return PARSE_OPT_UNKNOWN;
942 ctx->out[ctx->cpidx++] = ctx->argv[0];
943 ctx->opt = NULL;
944 }
945 return PARSE_OPT_DONE;
946
947 show_usage:
948 return usage_with_options_internal(ctx, usagestr, options, 0, 0);
949 }
950
951 int parse_options_end(struct parse_opt_ctx_t *ctx)
952 {
953 if (ctx->flags & PARSE_OPT_ONE_SHOT)
954 return ctx->total - ctx->argc;
955
956 MOVE_ARRAY(ctx->out + ctx->cpidx, ctx->argv, ctx->argc);
957 ctx->out[ctx->cpidx + ctx->argc] = NULL;
958 return ctx->cpidx + ctx->argc;
959 }
960
961 int parse_options(int argc, const char **argv,
962 const char *prefix,
963 const struct option *options,
964 const char * const usagestr[],
965 enum parse_opt_flags flags)
966 {
967 struct parse_opt_ctx_t ctx;
968 struct option *real_options;
969
970 disallow_abbreviated_options =
971 git_env_bool("GIT_TEST_DISALLOW_ABBREVIATED_OPTIONS", 0);
972
973 memset(&ctx, 0, sizeof(ctx));
974 real_options = preprocess_options(&ctx, options);
975 if (real_options)
976 options = real_options;
977 parse_options_start_1(&ctx, argc, argv, prefix, options, flags);
978 switch (parse_options_step(&ctx, options, usagestr)) {
979 case PARSE_OPT_HELP:
980 case PARSE_OPT_ERROR:
981 exit(129);
982 case PARSE_OPT_COMPLETE:
983 exit(0);
984 case PARSE_OPT_NON_OPTION:
985 case PARSE_OPT_SUBCOMMAND:
986 break;
987 case PARSE_OPT_DONE:
988 if (ctx.has_subcommands &&
989 !(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
990 error(_("need a subcommand"));
991 usage_with_options(usagestr, options);
992 }
993 break;
994 case PARSE_OPT_UNKNOWN:
995 if (ctx.argv[0][1] == '-') {
996 error(_("unknown option `%s'"), ctx.argv[0] + 2);
997 } else if (isascii(*ctx.opt)) {
998 error(_("unknown switch `%c'"), *ctx.opt);
999 } else {
1000 error(_("unknown non-ascii option in string: `%s'"),
1001 ctx.argv[0]);
1002 }
1003 usage_with_options(usagestr, options);
1004 }
1005
1006 precompose_argv_prefix(argc, argv, NULL);
1007 free_preprocessed_options(real_options);
1008 free(ctx.alias_groups);
1009 return parse_options_end(&ctx);
1010 }
1011
1012 static int usage_argh(const struct option *opts, FILE *outfile)
1013 {
1014 const char *s;
1015 int literal = (opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1016 !opts->argh || !!strpbrk(opts->argh, "()<>[]|");
1017 if (opts->flags & PARSE_OPT_OPTARG)
1018 if (opts->long_name)
1019 s = literal ? "[=%s]" : "[=<%s>]";
1020 else
1021 s = literal ? "[%s]" : "[<%s>]";
1022 else
1023 s = literal ? " %s" : " <%s>";
1024 return utf8_fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
1025 }
1026
1027 static int usage_indent(FILE *outfile)
1028 {
1029 return fprintf(outfile, " ");
1030 }
1031
1032 #define USAGE_OPTS_WIDTH 26
1033
1034 static void usage_padding(FILE *outfile, size_t pos)
1035 {
1036 if (pos < USAGE_OPTS_WIDTH)
1037 fprintf(outfile, "%*s", USAGE_OPTS_WIDTH - (int)pos, "");
1038 else
1039 fprintf(outfile, "\n%*s", USAGE_OPTS_WIDTH, "");
1040 }
1041
1042 static const struct option *find_option_by_long_name(const struct option *opts,
1043 const char *long_name)
1044 {
1045 for (; opts->type != OPTION_END; opts++) {
1046 if (opts->long_name && !strcmp(opts->long_name, long_name))
1047 return opts;
1048 }
1049 return NULL;
1050 }
1051
1052 static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t *ctx,
1053 const char * const *usagestr,
1054 const struct option *opts,
1055 int full, int err)
1056 {
1057 const struct option *all_opts = opts;
1058 FILE *outfile = err ? stderr : stdout;
1059 int need_newline;
1060
1061 const char *usage_prefix = _("usage: %s");
1062 /*
1063 * The translation could be anything, but we can count on
1064 * msgfmt(1)'s --check option to have asserted that "%s" is in
1065 * the translation. So compute the length of the "usage: "
1066 * part. We are assuming that the translator wasn't overly
1067 * clever and used e.g. "%1$s" instead of "%s", there's only
1068 * one "%s" in "usage_prefix" above, so there's no reason to
1069 * do so even with a RTL language.
1070 */
1071 size_t usage_len = strlen(usage_prefix) - strlen("%s");
1072 /*
1073 * TRANSLATORS: the colon here should align with the
1074 * one in "usage: %s" translation.
1075 */
1076 const char *or_prefix = _(" or: %s");
1077 /*
1078 * TRANSLATORS: You should only need to translate this format
1079 * string if your language is a RTL language (e.g. Arabic,
1080 * Hebrew etc.), not if it's a LTR language (e.g. German,
1081 * Russian, Chinese etc.).
1082 *
1083 * When a translated usage string has an embedded "\n" it's
1084 * because options have wrapped to the next line. The line
1085 * after the "\n" will then be padded to align with the
1086 * command name, such as N_("git cmd [opt]\n<8
1087 * spaces>[opt2]"), where the 8 spaces are the same length as
1088 * "git cmd ".
1089 *
1090 * This format string prints out that already-translated
1091 * line. The "%*s" is whitespace padding to account for the
1092 * padding at the start of the line that we add in this
1093 * function. The "%s" is a line in the (hopefully already
1094 * translated) N_() usage string, which contained embedded
1095 * newlines before we split it up.
1096 */
1097 const char *usage_continued = _("%*s%s");
1098 const char *prefix = usage_prefix;
1099 int saw_empty_line = 0;
1100
1101 if (!usagestr)
1102 return PARSE_OPT_HELP;
1103
1104 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1105 fprintf(outfile, "cat <<\\EOF\n");
1106
1107 while (*usagestr) {
1108 const char *str = _(*usagestr++);
1109 struct string_list list = STRING_LIST_INIT_DUP;
1110 unsigned int j;
1111
1112 if (!saw_empty_line && !*str)
1113 saw_empty_line = 1;
1114
1115 string_list_split(&list, str, '\n', -1);
1116 for (j = 0; j < list.nr; j++) {
1117 const char *line = list.items[j].string;
1118
1119 if (saw_empty_line && *line)
1120 fprintf_ln(outfile, _(" %s"), line);
1121 else if (saw_empty_line)
1122 fputc('\n', outfile);
1123 else if (!j)
1124 fprintf_ln(outfile, prefix, line);
1125 else
1126 fprintf_ln(outfile, usage_continued,
1127 (int)usage_len, "", line);
1128 }
1129 string_list_clear(&list, 0);
1130
1131 prefix = or_prefix;
1132 }
1133
1134 need_newline = 1;
1135
1136 for (; opts->type != OPTION_END; opts++) {
1137 size_t pos;
1138 const char *cp, *np;
1139 const char *positive_name = NULL;
1140
1141 if (opts->type == OPTION_SUBCOMMAND)
1142 continue;
1143 if (opts->type == OPTION_GROUP) {
1144 fputc('\n', outfile);
1145 need_newline = 0;
1146 if (*opts->help)
1147 fprintf(outfile, "%s\n", _(opts->help));
1148 continue;
1149 }
1150 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
1151 continue;
1152
1153 if (need_newline) {
1154 fputc('\n', outfile);
1155 need_newline = 0;
1156 }
1157
1158 pos = usage_indent(outfile);
1159 if (opts->short_name) {
1160 if (opts->flags & PARSE_OPT_NODASH)
1161 pos += fprintf(outfile, "%c", opts->short_name);
1162 else
1163 pos += fprintf(outfile, "-%c", opts->short_name);
1164 }
1165 if (opts->long_name && opts->short_name)
1166 pos += fprintf(outfile, ", ");
1167 if (opts->long_name) {
1168 const char *long_name = opts->long_name;
1169 if ((opts->flags & PARSE_OPT_NONEG) ||
1170 skip_prefix(long_name, "no-", &positive_name))
1171 pos += fprintf(outfile, "--%s", long_name);
1172 else
1173 pos += fprintf(outfile, "--[no-]%s", long_name);
1174 }
1175
1176 if (opts->type == OPTION_NUMBER)
1177 pos += utf8_fprintf(outfile, _("-NUM"));
1178
1179 if ((opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1180 !(opts->flags & PARSE_OPT_NOARG))
1181 pos += usage_argh(opts, outfile);
1182
1183 if (opts->type == OPTION_ALIAS) {
1184 usage_padding(outfile, pos);
1185 fprintf_ln(outfile, _("alias of --%s"),
1186 (const char *)opts->value);
1187 continue;
1188 }
1189
1190 for (cp = opts->help ? _(opts->help) : ""; *cp; cp = np) {
1191 np = strchrnul(cp, '\n');
1192 if (*np)
1193 np++;
1194 usage_padding(outfile, pos);
1195 fwrite(cp, 1, np - cp, outfile);
1196 pos = 0;
1197 }
1198 fputc('\n', outfile);
1199
1200 if (positive_name) {
1201 if (find_option_by_long_name(all_opts, positive_name))
1202 continue;
1203 pos = usage_indent(outfile);
1204 pos += fprintf(outfile, "--%s", positive_name);
1205 usage_padding(outfile, pos);
1206 fprintf_ln(outfile, _("opposite of --no-%s"),
1207 positive_name);
1208 }
1209 }
1210 fputc('\n', outfile);
1211
1212 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1213 fputs("EOF\n", outfile);
1214
1215 return PARSE_OPT_HELP;
1216 }
1217
1218 void NORETURN usage_with_options(const char * const *usagestr,
1219 const struct option *opts)
1220 {
1221 usage_with_options_internal(NULL, usagestr, opts, 0, 1);
1222 exit(129);
1223 }
1224
1225 void NORETURN usage_msg_opt(const char *msg,
1226 const char * const *usagestr,
1227 const struct option *options)
1228 {
1229 die_message("%s\n", msg); /* The extra \n is intentional */
1230 usage_with_options(usagestr, options);
1231 }
1232
1233 void NORETURN usage_msg_optf(const char * const fmt,
1234 const char * const *usagestr,
1235 const struct option *options, ...)
1236 {
1237 struct strbuf msg = STRBUF_INIT;
1238 va_list ap;
1239 va_start(ap, options);
1240 strbuf_vaddf(&msg, fmt, ap);
1241 va_end(ap);
1242
1243 usage_msg_opt(msg.buf, usagestr, options);
1244 }
1245
1246 void die_for_incompatible_opt4(int opt1, const char *opt1_name,
1247 int opt2, const char *opt2_name,
1248 int opt3, const char *opt3_name,
1249 int opt4, const char *opt4_name)
1250 {
1251 int count = 0;
1252 const char *options[4];
1253
1254 if (opt1)
1255 options[count++] = opt1_name;
1256 if (opt2)
1257 options[count++] = opt2_name;
1258 if (opt3)
1259 options[count++] = opt3_name;
1260 if (opt4)
1261 options[count++] = opt4_name;
1262 switch (count) {
1263 case 4:
1264 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
1265 opt1_name, opt2_name, opt3_name, opt4_name);
1266 break;
1267 case 3:
1268 die(_("options '%s', '%s', and '%s' cannot be used together"),
1269 options[0], options[1], options[2]);
1270 break;
1271 case 2:
1272 die(_("options '%s' and '%s' cannot be used together"),
1273 options[0], options[1]);
1274 break;
1275 default:
1276 break;
1277 }
1278 }