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