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