Merge branch 'jk/unused-params-even-more'
[git] / parse-options.c
1 #include "git-compat-util.h"
2 #include "parse-options.h"
3 #include "cache.h"
4 #include "config.h"
5 #include "commit.h"
6 #include "color.h"
7 #include "utf8.h"
8
9 static int disallow_abbreviated_options;
10
11 #define OPT_SHORT 1
12 #define OPT_UNSET 2
13
14 int optbug(const struct option *opt, const char *reason)
15 {
16         if (opt->long_name) {
17                 if (opt->short_name)
18                         return error("BUG: switch '%c' (--%s) %s",
19                                      opt->short_name, opt->long_name, reason);
20                 return error("BUG: option '%s' %s", opt->long_name, reason);
21         }
22         return error("BUG: switch '%c' %s", opt->short_name, reason);
23 }
24
25 static enum parse_opt_result get_arg(struct parse_opt_ctx_t *p,
26                                      const struct option *opt,
27                                      int flags, const char **arg)
28 {
29         if (p->opt) {
30                 *arg = p->opt;
31                 p->opt = NULL;
32         } else if (p->argc == 1 && (opt->flags & PARSE_OPT_LASTARG_DEFAULT)) {
33                 *arg = (const char *)opt->defval;
34         } else if (p->argc > 1) {
35                 p->argc--;
36                 *arg = *++p->argv;
37         } else
38                 return error(_("%s requires a value"), optname(opt, flags));
39         return 0;
40 }
41
42 static void fix_filename(const char *prefix, const char **file)
43 {
44         if (!file || !*file || !prefix || is_absolute_path(*file)
45             || !strcmp("-", *file))
46                 return;
47         *file = prefix_filename(prefix, *file);
48 }
49
50 static enum parse_opt_result opt_command_mode_error(
51         const struct option *opt,
52         const struct option *all_opts,
53         int flags)
54 {
55         const struct option *that;
56         struct strbuf that_name = STRBUF_INIT;
57
58         /*
59          * Find the other option that was used to set the variable
60          * already, and report that this is not compatible with it.
61          */
62         for (that = all_opts; that->type != OPTION_END; that++) {
63                 if (that == opt ||
64                     that->type != OPTION_CMDMODE ||
65                     that->value != opt->value ||
66                     that->defval != *(int *)opt->value)
67                         continue;
68
69                 if (that->long_name)
70                         strbuf_addf(&that_name, "--%s", that->long_name);
71                 else
72                         strbuf_addf(&that_name, "-%c", that->short_name);
73                 error(_("%s is incompatible with %s"),
74                       optname(opt, flags), that_name.buf);
75                 strbuf_release(&that_name);
76                 return PARSE_OPT_ERROR;
77         }
78         return error(_("%s : incompatible with something else"),
79                      optname(opt, flags));
80 }
81
82 static enum parse_opt_result get_value(struct parse_opt_ctx_t *p,
83                                        const struct option *opt,
84                                        const struct option *all_opts,
85                                        int flags)
86 {
87         const char *s, *arg;
88         const int unset = flags & OPT_UNSET;
89         int err;
90
91         if (unset && p->opt)
92                 return error(_("%s takes no value"), optname(opt, flags));
93         if (unset && (opt->flags & PARSE_OPT_NONEG))
94                 return error(_("%s isn't available"), optname(opt, flags));
95         if (!(flags & OPT_SHORT) && p->opt && (opt->flags & PARSE_OPT_NOARG))
96                 return error(_("%s takes no value"), optname(opt, flags));
97
98         switch (opt->type) {
99         case OPTION_LOWLEVEL_CALLBACK:
100                 return opt->ll_callback(p, opt, NULL, unset);
101
102         case OPTION_BIT:
103                 if (unset)
104                         *(int *)opt->value &= ~opt->defval;
105                 else
106                         *(int *)opt->value |= opt->defval;
107                 return 0;
108
109         case OPTION_NEGBIT:
110                 if (unset)
111                         *(int *)opt->value |= opt->defval;
112                 else
113                         *(int *)opt->value &= ~opt->defval;
114                 return 0;
115
116         case OPTION_BITOP:
117                 if (unset)
118                         BUG("BITOP can't have unset form");
119                 *(int *)opt->value &= ~opt->extra;
120                 *(int *)opt->value |= opt->defval;
121                 return 0;
122
123         case OPTION_COUNTUP:
124                 if (*(int *)opt->value < 0)
125                         *(int *)opt->value = 0;
126                 *(int *)opt->value = unset ? 0 : *(int *)opt->value + 1;
127                 return 0;
128
129         case OPTION_SET_INT:
130                 *(int *)opt->value = unset ? 0 : opt->defval;
131                 return 0;
132
133         case OPTION_CMDMODE:
134                 /*
135                  * Giving the same mode option twice, although is unnecessary,
136                  * is not a grave error, so let it pass.
137                  */
138                 if (*(int *)opt->value && *(int *)opt->value != opt->defval)
139                         return opt_command_mode_error(opt, all_opts, flags);
140                 *(int *)opt->value = opt->defval;
141                 return 0;
142
143         case OPTION_STRING:
144                 if (unset)
145                         *(const char **)opt->value = NULL;
146                 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
147                         *(const char **)opt->value = (const char *)opt->defval;
148                 else
149                         return get_arg(p, opt, flags, (const char **)opt->value);
150                 return 0;
151
152         case OPTION_FILENAME:
153                 err = 0;
154                 if (unset)
155                         *(const char **)opt->value = NULL;
156                 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
157                         *(const char **)opt->value = (const char *)opt->defval;
158                 else
159                         err = get_arg(p, opt, flags, (const char **)opt->value);
160
161                 if (!err)
162                         fix_filename(p->prefix, (const char **)opt->value);
163                 return err;
164
165         case OPTION_CALLBACK:
166         {
167                 const char *p_arg = NULL;
168                 int p_unset;
169
170                 if (unset)
171                         p_unset = 1;
172                 else if (opt->flags & PARSE_OPT_NOARG)
173                         p_unset = 0;
174                 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
175                         p_unset = 0;
176                 else if (get_arg(p, opt, flags, &arg))
177                         return -1;
178                 else {
179                         p_unset = 0;
180                         p_arg = arg;
181                 }
182                 if (opt->callback)
183                         return (*opt->callback)(opt, p_arg, p_unset) ? (-1) : 0;
184                 else
185                         return (*opt->ll_callback)(p, opt, p_arg, p_unset);
186         }
187         case OPTION_INTEGER:
188                 if (unset) {
189                         *(int *)opt->value = 0;
190                         return 0;
191                 }
192                 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
193                         *(int *)opt->value = opt->defval;
194                         return 0;
195                 }
196                 if (get_arg(p, opt, flags, &arg))
197                         return -1;
198                 *(int *)opt->value = strtol(arg, (char **)&s, 10);
199                 if (*s)
200                         return error(_("%s expects a numerical value"),
201                                      optname(opt, flags));
202                 return 0;
203
204         case OPTION_MAGNITUDE:
205                 if (unset) {
206                         *(unsigned long *)opt->value = 0;
207                         return 0;
208                 }
209                 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
210                         *(unsigned long *)opt->value = opt->defval;
211                         return 0;
212                 }
213                 if (get_arg(p, opt, flags, &arg))
214                         return -1;
215                 if (!git_parse_ulong(arg, opt->value))
216                         return error(_("%s expects a non-negative integer value"
217                                        " with an optional k/m/g suffix"),
218                                      optname(opt, flags));
219                 return 0;
220
221         default:
222                 BUG("opt->type %d should not happen", opt->type);
223         }
224 }
225
226 static enum parse_opt_result parse_short_opt(struct parse_opt_ctx_t *p,
227                                              const struct option *options)
228 {
229         const struct option *all_opts = options;
230         const struct option *numopt = NULL;
231
232         for (; options->type != OPTION_END; options++) {
233                 if (options->short_name == *p->opt) {
234                         p->opt = p->opt[1] ? p->opt + 1 : NULL;
235                         return get_value(p, options, all_opts, OPT_SHORT);
236                 }
237
238                 /*
239                  * Handle the numerical option later, explicit one-digit
240                  * options take precedence over it.
241                  */
242                 if (options->type == OPTION_NUMBER)
243                         numopt = options;
244         }
245         if (numopt && isdigit(*p->opt)) {
246                 size_t len = 1;
247                 char *arg;
248                 int rc;
249
250                 while (isdigit(p->opt[len]))
251                         len++;
252                 arg = xmemdupz(p->opt, len);
253                 p->opt = p->opt[len] ? p->opt + len : NULL;
254                 if (numopt->callback)
255                         rc = (*numopt->callback)(numopt, arg, 0) ? (-1) : 0;
256                 else
257                         rc = (*numopt->ll_callback)(p, numopt, arg, 0);
258                 free(arg);
259                 return rc;
260         }
261         return PARSE_OPT_UNKNOWN;
262 }
263
264 static enum parse_opt_result parse_long_opt(
265         struct parse_opt_ctx_t *p, const char *arg,
266         const struct option *options)
267 {
268         const struct option *all_opts = options;
269         const char *arg_end = strchrnul(arg, '=');
270         const struct option *abbrev_option = NULL, *ambiguous_option = NULL;
271         int abbrev_flags = 0, ambiguous_flags = 0;
272
273         for (; options->type != OPTION_END; options++) {
274                 const char *rest, *long_name = options->long_name;
275                 int flags = 0, opt_flags = 0;
276
277                 if (!long_name)
278                         continue;
279
280 again:
281                 if (!skip_prefix(arg, long_name, &rest))
282                         rest = NULL;
283                 if (options->type == OPTION_ARGUMENT) {
284                         if (!rest)
285                                 continue;
286                         if (*rest == '=')
287                                 return error(_("%s takes no value"),
288                                              optname(options, flags));
289                         if (*rest)
290                                 continue;
291                         p->out[p->cpidx++] = arg - 2;
292                         return PARSE_OPT_DONE;
293                 }
294                 if (!rest) {
295                         /* abbreviated? */
296                         if (!(p->flags & PARSE_OPT_KEEP_UNKNOWN) &&
297                             !strncmp(long_name, arg, arg_end - arg)) {
298 is_abbreviated:
299                                 if (abbrev_option) {
300                                         /*
301                                          * If this is abbreviated, it is
302                                          * ambiguous. So when there is no
303                                          * exact match later, we need to
304                                          * error out.
305                                          */
306                                         ambiguous_option = abbrev_option;
307                                         ambiguous_flags = abbrev_flags;
308                                 }
309                                 if (!(flags & OPT_UNSET) && *arg_end)
310                                         p->opt = arg_end + 1;
311                                 abbrev_option = options;
312                                 abbrev_flags = flags ^ opt_flags;
313                                 continue;
314                         }
315                         /* negation allowed? */
316                         if (options->flags & PARSE_OPT_NONEG)
317                                 continue;
318                         /* negated and abbreviated very much? */
319                         if (starts_with("no-", arg)) {
320                                 flags |= OPT_UNSET;
321                                 goto is_abbreviated;
322                         }
323                         /* negated? */
324                         if (!starts_with(arg, "no-")) {
325                                 if (starts_with(long_name, "no-")) {
326                                         long_name += 3;
327                                         opt_flags |= OPT_UNSET;
328                                         goto again;
329                                 }
330                                 continue;
331                         }
332                         flags |= OPT_UNSET;
333                         if (!skip_prefix(arg + 3, long_name, &rest)) {
334                                 /* abbreviated and negated? */
335                                 if (starts_with(long_name, arg + 3))
336                                         goto is_abbreviated;
337                                 else
338                                         continue;
339                         }
340                 }
341                 if (*rest) {
342                         if (*rest != '=')
343                                 continue;
344                         p->opt = rest + 1;
345                 }
346                 return get_value(p, options, all_opts, flags ^ opt_flags);
347         }
348
349         if (disallow_abbreviated_options && (ambiguous_option || abbrev_option))
350                 die("disallowed abbreviated or ambiguous option '%.*s'",
351                     (int)(arg_end - arg), arg);
352
353         if (ambiguous_option) {
354                 error(_("ambiguous option: %s "
355                         "(could be --%s%s or --%s%s)"),
356                         arg,
357                         (ambiguous_flags & OPT_UNSET) ?  "no-" : "",
358                         ambiguous_option->long_name,
359                         (abbrev_flags & OPT_UNSET) ?  "no-" : "",
360                         abbrev_option->long_name);
361                 return PARSE_OPT_HELP;
362         }
363         if (abbrev_option)
364                 return get_value(p, abbrev_option, all_opts, abbrev_flags);
365         return PARSE_OPT_UNKNOWN;
366 }
367
368 static int parse_nodash_opt(struct parse_opt_ctx_t *p, const char *arg,
369                             const struct option *options)
370 {
371         const struct option *all_opts = options;
372
373         for (; options->type != OPTION_END; options++) {
374                 if (!(options->flags & PARSE_OPT_NODASH))
375                         continue;
376                 if (options->short_name == arg[0] && arg[1] == '\0')
377                         return get_value(p, options, all_opts, OPT_SHORT);
378         }
379         return -2;
380 }
381
382 static void check_typos(const char *arg, const struct option *options)
383 {
384         if (strlen(arg) < 3)
385                 return;
386
387         if (starts_with(arg, "no-")) {
388                 error(_("did you mean `--%s` (with two dashes ?)"), arg);
389                 exit(129);
390         }
391
392         for (; options->type != OPTION_END; options++) {
393                 if (!options->long_name)
394                         continue;
395                 if (starts_with(options->long_name, arg)) {
396                         error(_("did you mean `--%s` (with two dashes ?)"), arg);
397                         exit(129);
398                 }
399         }
400 }
401
402 static void parse_options_check(const struct option *opts)
403 {
404         int err = 0;
405         char short_opts[128];
406
407         memset(short_opts, '\0', sizeof(short_opts));
408         for (; opts->type != OPTION_END; opts++) {
409                 if ((opts->flags & PARSE_OPT_LASTARG_DEFAULT) &&
410                     (opts->flags & PARSE_OPT_OPTARG))
411                         err |= optbug(opts, "uses incompatible flags "
412                                         "LASTARG_DEFAULT and OPTARG");
413                 if (opts->short_name) {
414                         if (0x7F <= opts->short_name)
415                                 err |= optbug(opts, "invalid short name");
416                         else if (short_opts[opts->short_name]++)
417                                 err |= optbug(opts, "short name already used");
418                 }
419                 if (opts->flags & PARSE_OPT_NODASH &&
420                     ((opts->flags & PARSE_OPT_OPTARG) ||
421                      !(opts->flags & PARSE_OPT_NOARG) ||
422                      !(opts->flags & PARSE_OPT_NONEG) ||
423                      opts->long_name))
424                         err |= optbug(opts, "uses feature "
425                                         "not supported for dashless options");
426                 switch (opts->type) {
427                 case OPTION_COUNTUP:
428                 case OPTION_BIT:
429                 case OPTION_NEGBIT:
430                 case OPTION_SET_INT:
431                 case OPTION_NUMBER:
432                         if ((opts->flags & PARSE_OPT_OPTARG) ||
433                             !(opts->flags & PARSE_OPT_NOARG))
434                                 err |= optbug(opts, "should not accept an argument");
435                         break;
436                 case OPTION_CALLBACK:
437                         if (!opts->callback && !opts->ll_callback)
438                                 BUG("OPTION_CALLBACK needs one callback");
439                         if (opts->callback && opts->ll_callback)
440                                 BUG("OPTION_CALLBACK can't have two callbacks");
441                         break;
442                 case OPTION_LOWLEVEL_CALLBACK:
443                         if (!opts->ll_callback)
444                                 BUG("OPTION_LOWLEVEL_CALLBACK needs a callback");
445                         if (opts->callback)
446                                 BUG("OPTION_LOWLEVEL_CALLBACK needs no high level callback");
447                         break;
448                 default:
449                         ; /* ok. (usually accepts an argument) */
450                 }
451                 if (opts->argh &&
452                     strcspn(opts->argh, " _") != strlen(opts->argh))
453                         err |= optbug(opts, "multi-word argh should use dash to separate words");
454         }
455         if (err)
456                 exit(128);
457 }
458
459 void parse_options_start(struct parse_opt_ctx_t *ctx,
460                          int argc, const char **argv, const char *prefix,
461                          const struct option *options, int flags)
462 {
463         memset(ctx, 0, sizeof(*ctx));
464         ctx->argc = argc;
465         ctx->argv = argv;
466         if (!(flags & PARSE_OPT_ONE_SHOT)) {
467                 ctx->argc--;
468                 ctx->argv++;
469         }
470         ctx->total = ctx->argc;
471         ctx->out   = argv;
472         ctx->prefix = prefix;
473         ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
474         ctx->flags = flags;
475         if ((flags & PARSE_OPT_KEEP_UNKNOWN) &&
476             (flags & PARSE_OPT_STOP_AT_NON_OPTION) &&
477             !(flags & PARSE_OPT_ONE_SHOT))
478                 BUG("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
479         if ((flags & PARSE_OPT_ONE_SHOT) &&
480             (flags & PARSE_OPT_KEEP_ARGV0))
481                 BUG("Can't keep argv0 if you don't have it");
482         parse_options_check(options);
483 }
484
485 static void show_negated_gitcomp(const struct option *opts, int nr_noopts)
486 {
487         int printed_dashdash = 0;
488
489         for (; opts->type != OPTION_END; opts++) {
490                 int has_unset_form = 0;
491                 const char *name;
492
493                 if (!opts->long_name)
494                         continue;
495                 if (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE))
496                         continue;
497                 if (opts->flags & PARSE_OPT_NONEG)
498                         continue;
499
500                 switch (opts->type) {
501                 case OPTION_STRING:
502                 case OPTION_FILENAME:
503                 case OPTION_INTEGER:
504                 case OPTION_MAGNITUDE:
505                 case OPTION_CALLBACK:
506                 case OPTION_BIT:
507                 case OPTION_NEGBIT:
508                 case OPTION_COUNTUP:
509                 case OPTION_SET_INT:
510                         has_unset_form = 1;
511                         break;
512                 default:
513                         break;
514                 }
515                 if (!has_unset_form)
516                         continue;
517
518                 if (skip_prefix(opts->long_name, "no-", &name)) {
519                         if (nr_noopts < 0)
520                                 printf(" --%s", name);
521                 } else if (nr_noopts >= 0) {
522                         if (nr_noopts && !printed_dashdash) {
523                                 printf(" --");
524                                 printed_dashdash = 1;
525                         }
526                         printf(" --no-%s", opts->long_name);
527                         nr_noopts++;
528                 }
529         }
530 }
531
532 static int show_gitcomp(const struct option *opts)
533 {
534         const struct option *original_opts = opts;
535         int nr_noopts = 0;
536
537         for (; opts->type != OPTION_END; opts++) {
538                 const char *suffix = "";
539
540                 if (!opts->long_name)
541                         continue;
542                 if (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE))
543                         continue;
544
545                 switch (opts->type) {
546                 case OPTION_GROUP:
547                         continue;
548                 case OPTION_STRING:
549                 case OPTION_FILENAME:
550                 case OPTION_INTEGER:
551                 case OPTION_MAGNITUDE:
552                 case OPTION_CALLBACK:
553                         if (opts->flags & PARSE_OPT_NOARG)
554                                 break;
555                         if (opts->flags & PARSE_OPT_OPTARG)
556                                 break;
557                         if (opts->flags & PARSE_OPT_LASTARG_DEFAULT)
558                                 break;
559                         suffix = "=";
560                         break;
561                 default:
562                         break;
563                 }
564                 if (opts->flags & PARSE_OPT_COMP_ARG)
565                         suffix = "=";
566                 if (starts_with(opts->long_name, "no-"))
567                         nr_noopts++;
568                 printf(" --%s%s", opts->long_name, suffix);
569         }
570         show_negated_gitcomp(original_opts, -1);
571         show_negated_gitcomp(original_opts, nr_noopts);
572         fputc('\n', stdout);
573         return PARSE_OPT_COMPLETE;
574 }
575
576 static int usage_with_options_internal(struct parse_opt_ctx_t *,
577                                        const char * const *,
578                                        const struct option *, int, int);
579
580 int parse_options_step(struct parse_opt_ctx_t *ctx,
581                        const struct option *options,
582                        const char * const usagestr[])
583 {
584         int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
585
586         /* we must reset ->opt, unknown short option leave it dangling */
587         ctx->opt = NULL;
588
589         for (; ctx->argc; ctx->argc--, ctx->argv++) {
590                 const char *arg = ctx->argv[0];
591
592                 if (ctx->flags & PARSE_OPT_ONE_SHOT &&
593                     ctx->argc != ctx->total)
594                         break;
595
596                 if (*arg != '-' || !arg[1]) {
597                         if (parse_nodash_opt(ctx, arg, options) == 0)
598                                 continue;
599                         if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
600                                 return PARSE_OPT_NON_OPTION;
601                         ctx->out[ctx->cpidx++] = ctx->argv[0];
602                         continue;
603                 }
604
605                 /* lone -h asks for help */
606                 if (internal_help && ctx->total == 1 && !strcmp(arg + 1, "h"))
607                         goto show_usage;
608
609                 /* lone --git-completion-helper is asked by git-completion.bash */
610                 if (ctx->total == 1 && !strcmp(arg + 1, "-git-completion-helper"))
611                         return show_gitcomp(options);
612
613                 if (arg[1] != '-') {
614                         ctx->opt = arg + 1;
615                         switch (parse_short_opt(ctx, options)) {
616                         case PARSE_OPT_ERROR:
617                                 return PARSE_OPT_ERROR;
618                         case PARSE_OPT_UNKNOWN:
619                                 if (ctx->opt)
620                                         check_typos(arg + 1, options);
621                                 if (internal_help && *ctx->opt == 'h')
622                                         goto show_usage;
623                                 goto unknown;
624                         case PARSE_OPT_NON_OPTION:
625                         case PARSE_OPT_HELP:
626                         case PARSE_OPT_COMPLETE:
627                                 BUG("parse_short_opt() cannot return these");
628                         case PARSE_OPT_DONE:
629                                 break;
630                         }
631                         if (ctx->opt)
632                                 check_typos(arg + 1, options);
633                         while (ctx->opt) {
634                                 switch (parse_short_opt(ctx, options)) {
635                                 case PARSE_OPT_ERROR:
636                                         return PARSE_OPT_ERROR;
637                                 case PARSE_OPT_UNKNOWN:
638                                         if (internal_help && *ctx->opt == 'h')
639                                                 goto show_usage;
640
641                                         /* fake a short option thing to hide the fact that we may have
642                                          * started to parse aggregated stuff
643                                          *
644                                          * This is leaky, too bad.
645                                          */
646                                         ctx->argv[0] = xstrdup(ctx->opt - 1);
647                                         *(char *)ctx->argv[0] = '-';
648                                         goto unknown;
649                                 case PARSE_OPT_NON_OPTION:
650                                 case PARSE_OPT_COMPLETE:
651                                 case PARSE_OPT_HELP:
652                                         BUG("parse_short_opt() cannot return these");
653                                 case PARSE_OPT_DONE:
654                                         break;
655                                 }
656                         }
657                         continue;
658                 }
659
660                 if (!arg[2]) { /* "--" */
661                         if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
662                                 ctx->argc--;
663                                 ctx->argv++;
664                         }
665                         break;
666                 }
667
668                 if (internal_help && !strcmp(arg + 2, "help-all"))
669                         return usage_with_options_internal(ctx, usagestr, options, 1, 0);
670                 if (internal_help && !strcmp(arg + 2, "help"))
671                         goto show_usage;
672                 switch (parse_long_opt(ctx, arg + 2, options)) {
673                 case PARSE_OPT_ERROR:
674                         return PARSE_OPT_ERROR;
675                 case PARSE_OPT_UNKNOWN:
676                         goto unknown;
677                 case PARSE_OPT_HELP:
678                         goto show_usage;
679                 case PARSE_OPT_NON_OPTION:
680                 case PARSE_OPT_COMPLETE:
681                         BUG("parse_long_opt() cannot return these");
682                 case PARSE_OPT_DONE:
683                         break;
684                 }
685                 continue;
686 unknown:
687                 if (ctx->flags & PARSE_OPT_ONE_SHOT)
688                         break;
689                 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN))
690                         return PARSE_OPT_UNKNOWN;
691                 ctx->out[ctx->cpidx++] = ctx->argv[0];
692                 ctx->opt = NULL;
693         }
694         return PARSE_OPT_DONE;
695
696  show_usage:
697         return usage_with_options_internal(ctx, usagestr, options, 0, 0);
698 }
699
700 int parse_options_end(struct parse_opt_ctx_t *ctx)
701 {
702         if (ctx->flags & PARSE_OPT_ONE_SHOT)
703                 return ctx->total - ctx->argc;
704
705         MOVE_ARRAY(ctx->out + ctx->cpidx, ctx->argv, ctx->argc);
706         ctx->out[ctx->cpidx + ctx->argc] = NULL;
707         return ctx->cpidx + ctx->argc;
708 }
709
710 int parse_options(int argc, const char **argv, const char *prefix,
711                   const struct option *options, const char * const usagestr[],
712                   int flags)
713 {
714         struct parse_opt_ctx_t ctx;
715
716         disallow_abbreviated_options =
717                 git_env_bool("GIT_TEST_DISALLOW_ABBREVIATED_OPTIONS", 0);
718
719         parse_options_start(&ctx, argc, argv, prefix, options, flags);
720         switch (parse_options_step(&ctx, options, usagestr)) {
721         case PARSE_OPT_HELP:
722         case PARSE_OPT_ERROR:
723                 exit(129);
724         case PARSE_OPT_COMPLETE:
725                 exit(0);
726         case PARSE_OPT_NON_OPTION:
727         case PARSE_OPT_DONE:
728                 break;
729         default: /* PARSE_OPT_UNKNOWN */
730                 if (ctx.argv[0][1] == '-') {
731                         error(_("unknown option `%s'"), ctx.argv[0] + 2);
732                 } else if (isascii(*ctx.opt)) {
733                         error(_("unknown switch `%c'"), *ctx.opt);
734                 } else {
735                         error(_("unknown non-ascii option in string: `%s'"),
736                               ctx.argv[0]);
737                 }
738                 usage_with_options(usagestr, options);
739         }
740
741         precompose_argv(argc, argv);
742         return parse_options_end(&ctx);
743 }
744
745 static int usage_argh(const struct option *opts, FILE *outfile)
746 {
747         const char *s;
748         int literal = (opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
749                 !opts->argh || !!strpbrk(opts->argh, "()<>[]|");
750         if (opts->flags & PARSE_OPT_OPTARG)
751                 if (opts->long_name)
752                         s = literal ? "[=%s]" : "[=<%s>]";
753                 else
754                         s = literal ? "[%s]" : "[<%s>]";
755         else
756                 s = literal ? " %s" : " <%s>";
757         return utf8_fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
758 }
759
760 #define USAGE_OPTS_WIDTH 24
761 #define USAGE_GAP         2
762
763 static int usage_with_options_internal(struct parse_opt_ctx_t *ctx,
764                                        const char * const *usagestr,
765                                        const struct option *opts, int full, int err)
766 {
767         FILE *outfile = err ? stderr : stdout;
768         int need_newline;
769
770         if (!usagestr)
771                 return PARSE_OPT_HELP;
772
773         if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
774                 fprintf(outfile, "cat <<\\EOF\n");
775
776         fprintf_ln(outfile, _("usage: %s"), _(*usagestr++));
777         while (*usagestr && **usagestr)
778                 /*
779                  * TRANSLATORS: the colon here should align with the
780                  * one in "usage: %s" translation.
781                  */
782                 fprintf_ln(outfile, _("   or: %s"), _(*usagestr++));
783         while (*usagestr) {
784                 if (**usagestr)
785                         fprintf_ln(outfile, _("    %s"), _(*usagestr));
786                 else
787                         fputc('\n', outfile);
788                 usagestr++;
789         }
790
791         need_newline = 1;
792
793         for (; opts->type != OPTION_END; opts++) {
794                 size_t pos;
795                 int pad;
796
797                 if (opts->type == OPTION_GROUP) {
798                         fputc('\n', outfile);
799                         need_newline = 0;
800                         if (*opts->help)
801                                 fprintf(outfile, "%s\n", _(opts->help));
802                         continue;
803                 }
804                 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
805                         continue;
806
807                 if (need_newline) {
808                         fputc('\n', outfile);
809                         need_newline = 0;
810                 }
811
812                 pos = fprintf(outfile, "    ");
813                 if (opts->short_name) {
814                         if (opts->flags & PARSE_OPT_NODASH)
815                                 pos += fprintf(outfile, "%c", opts->short_name);
816                         else
817                                 pos += fprintf(outfile, "-%c", opts->short_name);
818                 }
819                 if (opts->long_name && opts->short_name)
820                         pos += fprintf(outfile, ", ");
821                 if (opts->long_name)
822                         pos += fprintf(outfile, "--%s", opts->long_name);
823                 if (opts->type == OPTION_NUMBER)
824                         pos += utf8_fprintf(outfile, _("-NUM"));
825
826                 if ((opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
827                     !(opts->flags & PARSE_OPT_NOARG))
828                         pos += usage_argh(opts, outfile);
829
830                 if (pos <= USAGE_OPTS_WIDTH)
831                         pad = USAGE_OPTS_WIDTH - pos;
832                 else {
833                         fputc('\n', outfile);
834                         pad = USAGE_OPTS_WIDTH;
835                 }
836                 fprintf(outfile, "%*s%s\n", pad + USAGE_GAP, "", _(opts->help));
837         }
838         fputc('\n', outfile);
839
840         if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
841                 fputs("EOF\n", outfile);
842
843         return PARSE_OPT_HELP;
844 }
845
846 void NORETURN usage_with_options(const char * const *usagestr,
847                         const struct option *opts)
848 {
849         usage_with_options_internal(NULL, usagestr, opts, 0, 1);
850         exit(129);
851 }
852
853 void NORETURN usage_msg_opt(const char *msg,
854                    const char * const *usagestr,
855                    const struct option *options)
856 {
857         fprintf(stderr, "fatal: %s\n\n", msg);
858         usage_with_options(usagestr, options);
859 }
860
861 const char *optname(const struct option *opt, int flags)
862 {
863         static struct strbuf sb = STRBUF_INIT;
864
865         strbuf_reset(&sb);
866         if (flags & OPT_SHORT)
867                 strbuf_addf(&sb, "switch `%c'", opt->short_name);
868         else if (flags & OPT_UNSET)
869                 strbuf_addf(&sb, "option `no-%s'", opt->long_name);
870         else
871                 strbuf_addf(&sb, "option `%s'", opt->long_name);
872
873         return sb.buf;
874 }