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