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_ERROR;
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_HELP_ERROR:
1041 case PARSE_OPT_ERROR:
1042 case PARSE_OPT_DONE:
1043 case PARSE_OPT_NON_OPTION:
1044 /* Impossible. */
1045 BUG("parse_subcommand() cannot return these");
1046 }
1047 }
1048
1049 /* lone -h asks for help */
1050 if (internal_help && ctx->total == 1 && !strcmp(arg + 1, "h"))
1051 goto show_usage;
1052
1053 /*
1054 * lone --git-completion-helper and --git-completion-helper-all
1055 * are asked by git-completion.bash
1056 */
1057 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper"))
1058 return show_gitcomp(options, 0);
1059 if (ctx->total == 1 && !strcmp(arg, "--git-completion-helper-all"))
1060 return show_gitcomp(options, 1);
1061
1062 if (arg[1] != '-') {
1063 ctx->opt = arg + 1;
1064 switch (parse_short_opt(ctx, options)) {
1065 case PARSE_OPT_ERROR:
1066 return PARSE_OPT_ERROR;
1067 case PARSE_OPT_UNKNOWN:
1068 if (ctx->opt)
1069 check_typos(arg + 1, options);
1070 if (internal_help && *ctx->opt == 'h')
1071 goto show_usage;
1072 goto unknown;
1073 case PARSE_OPT_NON_OPTION:
1074 case PARSE_OPT_SUBCOMMAND:
1075 case PARSE_OPT_HELP:
1076 case PARSE_OPT_HELP_ERROR:
1077 case PARSE_OPT_COMPLETE:
1078 BUG("parse_short_opt() cannot return these");
1079 case PARSE_OPT_DONE:
1080 break;
1081 }
1082 if (ctx->opt)
1083 check_typos(arg + 1, options);
1084 while (ctx->opt) {
1085 switch (parse_short_opt(ctx, options)) {
1086 case PARSE_OPT_ERROR:
1087 return PARSE_OPT_ERROR;
1088 case PARSE_OPT_UNKNOWN:
1089 if (internal_help && *ctx->opt == 'h')
1090 goto show_usage;
1091
1092 /* fake a short option thing to hide the fact that we may have
1093 * started to parse aggregated stuff
1094 *
1095 * This is leaky, too bad.
1096 */
1097 ctx->argv[0] = xstrdup(ctx->opt - 1);
1098 *(char *)ctx->argv[0] = '-';
1099 goto unknown;
1100 case PARSE_OPT_NON_OPTION:
1101 case PARSE_OPT_SUBCOMMAND:
1102 case PARSE_OPT_COMPLETE:
1103 case PARSE_OPT_HELP:
1104 case PARSE_OPT_HELP_ERROR:
1105 BUG("parse_short_opt() cannot return these");
1106 case PARSE_OPT_DONE:
1107 break;
1108 }
1109 }
1110 continue;
1111 }
1112
1113 if (!arg[2] /* "--" */) {
1114 if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
1115 ctx->argc--;
1116 ctx->argv++;
1117 }
1118 break;
1119 } else if (!strcmp(arg + 2, "end-of-options")) {
1120 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)) {
1121 ctx->argc--;
1122 ctx->argv++;
1123 }
1124 break;
1125 }
1126
1127 if (internal_help && !strcmp(arg + 2, "help-all"))
1128 return usage_with_options_internal(ctx, usagestr, options,
1129 USAGE_FULL, USAGE_TO_STDOUT);
1130 if (internal_help && !strcmp(arg + 2, "help"))
1131 goto show_usage;
1132 switch (parse_long_opt(ctx, arg + 2, options)) {
1133 case PARSE_OPT_ERROR:
1134 return PARSE_OPT_ERROR;
1135 case PARSE_OPT_UNKNOWN:
1136 goto unknown;
1137 case PARSE_OPT_HELP:
1138 goto show_usage;
1139 case PARSE_OPT_HELP_ERROR:
1140 goto show_usage_stderr;
1141 case PARSE_OPT_NON_OPTION:
1142 case PARSE_OPT_SUBCOMMAND:
1143 case PARSE_OPT_COMPLETE:
1144 BUG("parse_long_opt() cannot return these");
1145 case PARSE_OPT_DONE:
1146 break;
1147 }
1148 continue;
1149 unknown:
1150 if (ctx->flags & PARSE_OPT_ONE_SHOT)
1151 break;
1152 if (ctx->has_subcommands &&
1153 (ctx->flags & PARSE_OPT_SUBCOMMAND_OPTIONAL) &&
1154 (ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT)) {
1155 /*
1156 * Found an unknown option given to a command with
1157 * subcommands that have a default operation mode:
1158 * we treat this option and all remaining args as
1159 * arguments meant to that default operation mode.
1160 * So we are done parsing.
1161 */
1162 return PARSE_OPT_DONE;
1163 }
1164 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN_OPT))
1165 return PARSE_OPT_UNKNOWN;
1166 ctx->out[ctx->cpidx++] = ctx->argv[0];
1167 ctx->opt = NULL;
1168 }
1169 return PARSE_OPT_DONE;
1170
1171 show_usage:
1172 return usage_with_options_internal(ctx, usagestr, options,
1173 USAGE_NORMAL, USAGE_TO_STDOUT);
1174 show_usage_stderr:
1175 return usage_with_options_internal(ctx, usagestr, options,
1176 USAGE_NORMAL, USAGE_TO_STDERR);
1177 }
1178
1179 int parse_options_end(struct parse_opt_ctx_t *ctx)
1180 {
1181 if (ctx->flags & PARSE_OPT_ONE_SHOT)
1182 return ctx->total - ctx->argc;
1183
1184 MOVE_ARRAY(ctx->out + ctx->cpidx, ctx->argv, ctx->argc);
1185 ctx->out[ctx->cpidx + ctx->argc] = NULL;
1186 return ctx->cpidx + ctx->argc;
1187 }
1188
1189 int parse_options(int argc, const char **argv,
1190 const char *prefix,
1191 const struct option *options,
1192 const char * const usagestr[],
1193 enum parse_opt_flags flags)
1194 {
1195 struct parse_opt_ctx_t ctx;
1196 struct option *real_options;
1197
1198 disallow_abbreviated_options =
1199 git_env_bool("GIT_TEST_DISALLOW_ABBREVIATED_OPTIONS", 0);
1200
1201 memset(&ctx, 0, sizeof(ctx));
1202 real_options = preprocess_options(&ctx, options);
1203 if (real_options)
1204 options = real_options;
1205 parse_options_start_1(&ctx, argc, argv, prefix, options, flags);
1206 switch (parse_options_step(&ctx, options, usagestr)) {
1207 case PARSE_OPT_HELP:
1208 exit(0);
1209 case PARSE_OPT_HELP_ERROR:
1210 case PARSE_OPT_ERROR:
1211 exit(129);
1212 case PARSE_OPT_COMPLETE:
1213 exit(0);
1214 case PARSE_OPT_NON_OPTION:
1215 case PARSE_OPT_SUBCOMMAND:
1216 break;
1217 case PARSE_OPT_DONE:
1218 if (ctx.has_subcommands &&
1219 !(flags & PARSE_OPT_SUBCOMMAND_OPTIONAL)) {
1220 error(_("need a subcommand"));
1221 usage_with_options(usagestr, options);
1222 }
1223 break;
1224 case PARSE_OPT_UNKNOWN:
1225 if (ctx.argv[0][1] == '-') {
1226 error(_("unknown option `%s'"), ctx.argv[0] + 2);
1227 } else if (isascii(*ctx.opt)) {
1228 error(_("unknown switch `%c'"), *ctx.opt);
1229 } else {
1230 error(_("unknown non-ascii option in string: `%s'"),
1231 ctx.argv[0]);
1232 }
1233 usage_with_options(usagestr, options);
1234 }
1235
1236 precompose_argv_prefix(argc, argv, NULL);
1237 free_preprocessed_options(real_options);
1238 free(ctx.alias_groups);
1239 for (struct parse_opt_cmdmode_list *elem = ctx.cmdmode_list; elem;) {
1240 struct parse_opt_cmdmode_list *next = elem->next;
1241 free(elem);
1242 elem = next;
1243 }
1244 return parse_options_end(&ctx);
1245 }
1246
1247 static int usage_argh(const struct option *opts, FILE *outfile)
1248 {
1249 const char *s;
1250 int literal = (opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1251 !opts->argh || !!strpbrk(opts->argh, "()<>[]|");
1252 if (opts->flags & PARSE_OPT_OPTARG)
1253 if (opts->long_name)
1254 /*
1255 * TRANSLATORS: The "<%s>" part of this string
1256 * stands for an optional value given to a command
1257 * line option in the long form, and "<>" is there
1258 * as a convention to signal that it is a
1259 * placeholder (i.e. the user should substitute it
1260 * with the real value). If your language uses a
1261 * different convention, you can change "<%s>" part
1262 * to match yours, e.g. it might use "|%s|" instead,
1263 * or if the alphabet is different enough it may use
1264 * "%s" without any placeholder signal. Most
1265 * translations leave this message as is.
1266 */
1267 s = literal ? "[=%s]" : _("[=<%s>]");
1268 else
1269 /*
1270 * TRANSLATORS: The "<%s>" part of this string
1271 * stands for an optional value given to a command
1272 * line option in the short form, and "<>" is there
1273 * as a convention to signal that it is a
1274 * placeholder (i.e. the user should substitute it
1275 * with the real value). If your language uses a
1276 * different convention, you can change "<%s>" part
1277 * to match yours, e.g. it might use "|%s|" instead,
1278 * or if the alphabet is different enough it may use
1279 * "%s" without any placeholder signal. Most
1280 * translations leave this message as is.
1281 */
1282 s = literal ? "[%s]" : _("[<%s>]");
1283 else
1284 /*
1285 * TRANSLATORS: The "<%s>" part of this string stands for a
1286 * value given to a command line option, and "<>" is there
1287 * as a convention to signal that it is a placeholder
1288 * (i.e. the user should substitute it with the real value).
1289 * If your language uses a different convention, you can
1290 * change "<%s>" part to match yours, e.g. it might use
1291 * "|%s|" instead, or if the alphabet is different enough it
1292 * may use "%s" without any placeholder signal. Most
1293 * translations leave this message as is.
1294 */
1295 s = literal ? " %s" : _(" <%s>");
1296 return utf8_fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
1297 }
1298
1299 static int usage_indent(FILE *outfile)
1300 {
1301 return fprintf(outfile, " ");
1302 }
1303
1304 #define USAGE_OPTS_WIDTH 26
1305
1306 static void usage_padding(FILE *outfile, size_t pos)
1307 {
1308 if (pos < USAGE_OPTS_WIDTH)
1309 fprintf(outfile, "%*s", USAGE_OPTS_WIDTH - (int)pos, "");
1310 else
1311 fprintf(outfile, "\n%*s", USAGE_OPTS_WIDTH, "");
1312 }
1313
1314 static const struct option *find_option_by_long_name(const struct option *opts,
1315 const char *long_name)
1316 {
1317 for (; opts->type != OPTION_END; opts++) {
1318 if (opts->long_name && !strcmp(opts->long_name, long_name))
1319 return opts;
1320 }
1321 return NULL;
1322 }
1323
1324 static enum parse_opt_result usage_with_options_internal(struct parse_opt_ctx_t *ctx,
1325 const char * const *usagestr,
1326 const struct option *opts,
1327 int full, int err)
1328 {
1329 const struct option *all_opts = opts;
1330 FILE *outfile = err ? stderr : stdout;
1331 int need_newline;
1332
1333 const char *usage_prefix = _("usage: %s");
1334 /*
1335 * The translation could be anything, but we can count on
1336 * msgfmt(1)'s --check option to have asserted that "%s" is in
1337 * the translation. So compute the length of the "usage: "
1338 * part. We are assuming that the translator wasn't overly
1339 * clever and used e.g. "%1$s" instead of "%s", there's only
1340 * one "%s" in "usage_prefix" above, so there's no reason to
1341 * do so even with a RTL language.
1342 */
1343 size_t usage_len = strlen(usage_prefix) - strlen("%s");
1344 /*
1345 * TRANSLATORS: the colon here should align with the
1346 * one in "usage: %s" translation.
1347 */
1348 const char *or_prefix = _(" or: %s");
1349 /*
1350 * TRANSLATORS: You should only need to translate this format
1351 * string if your language is a RTL language (e.g. Arabic,
1352 * Hebrew etc.), not if it's a LTR language (e.g. German,
1353 * Russian, Chinese etc.).
1354 *
1355 * When a translated usage string has an embedded "\n" it's
1356 * because options have wrapped to the next line. The line
1357 * after the "\n" will then be padded to align with the
1358 * command name, such as N_("git cmd [opt]\n<8
1359 * spaces>[opt2]"), where the 8 spaces are the same length as
1360 * "git cmd ".
1361 *
1362 * This format string prints out that already-translated
1363 * line. The "%*s" is whitespace padding to account for the
1364 * padding at the start of the line that we add in this
1365 * function. The "%s" is a line in the (hopefully already
1366 * translated) N_() usage string, which contained embedded
1367 * newlines before we split it up.
1368 */
1369 const char *usage_continued = _("%*s%s");
1370 const char *prefix = usage_prefix;
1371 int saw_empty_line = 0;
1372
1373 parse_options_check_harder(opts);
1374
1375 if (!usagestr)
1376 return err ? PARSE_OPT_HELP_ERROR : PARSE_OPT_HELP;
1377
1378 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1379 fprintf(outfile, "cat <<\\EOF\n");
1380
1381 while (*usagestr) {
1382 const char *str = _(*usagestr++);
1383 struct string_list list = STRING_LIST_INIT_DUP;
1384 unsigned int j;
1385
1386 if (!saw_empty_line && !*str)
1387 saw_empty_line = 1;
1388
1389 string_list_split(&list, str, "\n", -1);
1390 for (j = 0; j < list.nr; j++) {
1391 const char *line = list.items[j].string;
1392
1393 if (saw_empty_line && *line)
1394 fprintf_ln(outfile, _(" %s"), line);
1395 else if (saw_empty_line)
1396 fputc('\n', outfile);
1397 else if (!j)
1398 fprintf_ln(outfile, prefix, line);
1399 else
1400 fprintf_ln(outfile, usage_continued,
1401 (int)usage_len, "", line);
1402 }
1403 string_list_clear(&list, 0);
1404
1405 prefix = or_prefix;
1406 }
1407
1408 need_newline = 1;
1409
1410 for (; opts->type != OPTION_END; opts++) {
1411 size_t pos;
1412 const char *cp, *np;
1413 const char *positive_name = NULL;
1414
1415 if (opts->type == OPTION_SUBCOMMAND)
1416 continue;
1417 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
1418 continue;
1419 if (opts->type == OPTION_GROUP) {
1420 fputc('\n', outfile);
1421 need_newline = 0;
1422 if (*opts->help)
1423 fprintf(outfile, "%s\n", _(opts->help));
1424 continue;
1425 }
1426
1427 if (need_newline) {
1428 fputc('\n', outfile);
1429 need_newline = 0;
1430 }
1431
1432 pos = usage_indent(outfile);
1433 if (opts->short_name) {
1434 if (opts->flags & PARSE_OPT_NODASH)
1435 pos += fprintf(outfile, "%c", opts->short_name);
1436 else
1437 pos += fprintf(outfile, "-%c", opts->short_name);
1438 }
1439 if (opts->long_name && opts->short_name)
1440 pos += fprintf(outfile, ", ");
1441 if (opts->long_name) {
1442 const char *long_name = opts->long_name;
1443 if ((opts->flags & PARSE_OPT_NONEG) ||
1444 skip_prefix(long_name, "no-", &positive_name))
1445 pos += fprintf(outfile, "--%s", long_name);
1446 else
1447 pos += fprintf(outfile, "--[no-]%s", long_name);
1448 }
1449
1450 if (opts->type == OPTION_NUMBER)
1451 pos += utf8_fprintf(outfile, _("-NUM"));
1452
1453 if ((opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
1454 !(opts->flags & PARSE_OPT_NOARG))
1455 pos += usage_argh(opts, outfile);
1456
1457 if (opts->type == OPTION_ALIAS) {
1458 usage_padding(outfile, pos);
1459 fprintf_ln(outfile, _("alias of --%s"),
1460 (const char *)opts->value);
1461 continue;
1462 }
1463
1464 for (cp = opts->help ? _(opts->help) : ""; *cp; cp = np) {
1465 np = strchrnul(cp, '\n');
1466 if (*np)
1467 np++;
1468 usage_padding(outfile, pos);
1469 fwrite(cp, 1, np - cp, outfile);
1470 pos = 0;
1471 }
1472 fputc('\n', outfile);
1473
1474 if (positive_name) {
1475 if (find_option_by_long_name(all_opts, positive_name))
1476 continue;
1477 pos = usage_indent(outfile);
1478 pos += fprintf(outfile, "--%s", positive_name);
1479 usage_padding(outfile, pos);
1480 fprintf_ln(outfile, _("opposite of --no-%s"),
1481 positive_name);
1482 }
1483 }
1484 fputc('\n', outfile);
1485
1486 if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
1487 fputs("EOF\nexit 0\n", outfile);
1488
1489 return err ? PARSE_OPT_HELP_ERROR : PARSE_OPT_HELP;
1490 }
1491
1492 void NORETURN usage_with_options(const char * const *usagestr,
1493 const struct option *opts)
1494 {
1495 usage_with_options_internal(NULL, usagestr, opts,
1496 USAGE_NORMAL, USAGE_TO_STDERR);
1497 exit(129);
1498 }
1499
1500 void show_usage_with_options_if_asked(int ac, const char **av,
1501 const char * const *usagestr,
1502 const struct option *opts)
1503 {
1504 if (ac == 2) {
1505 if (!strcmp(av[1], "-h")) {
1506 usage_with_options_internal(NULL, usagestr, opts,
1507 USAGE_NORMAL, USAGE_TO_STDOUT);
1508 exit(0);
1509 } else if (!strcmp(av[1], "--help-all")) {
1510 usage_with_options_internal(NULL, usagestr, opts,
1511 USAGE_FULL, USAGE_TO_STDOUT);
1512 exit(0);
1513 }
1514 }
1515 }
1516
1517 void NORETURN usage_msg_opt(const char *msg,
1518 const char * const *usagestr,
1519 const struct option *options)
1520 {
1521 die_message("%s\n", msg); /* The extra \n is intentional */
1522 usage_with_options(usagestr, options);
1523 }
1524
1525 void NORETURN usage_msg_optf(const char * const fmt,
1526 const char * const *usagestr,
1527 const struct option *options, ...)
1528 {
1529 struct strbuf msg = STRBUF_INIT;
1530 va_list ap;
1531 va_start(ap, options);
1532 strbuf_vaddf(&msg, fmt, ap);
1533 va_end(ap);
1534
1535 usage_msg_opt(msg.buf, usagestr, options);
1536 }
1537
1538 void die_for_incompatible_opt4(int opt1, const char *opt1_name,
1539 int opt2, const char *opt2_name,
1540 int opt3, const char *opt3_name,
1541 int opt4, const char *opt4_name)
1542 {
1543 int count = 0;
1544 const char *options[4];
1545
1546 if (opt1)
1547 options[count++] = opt1_name;
1548 if (opt2)
1549 options[count++] = opt2_name;
1550 if (opt3)
1551 options[count++] = opt3_name;
1552 if (opt4)
1553 options[count++] = opt4_name;
1554 switch (count) {
1555 case 4:
1556 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
1557 opt1_name, opt2_name, opt3_name, opt4_name);
1558 break;
1559 case 3:
1560 die(_("options '%s', '%s', and '%s' cannot be used together"),
1561 options[0], options[1], options[2]);
1562 break;
1563 case 2:
1564 die(_("options '%s' and '%s' cannot be used together"),
1565 options[0], options[1]);
1566 break;
1567 default:
1568 break;
1569 }
1570 }