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