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