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