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