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