rebase: disable fork-point by default
[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 #define OPT_SHORT 1
9 #define OPT_UNSET 2
10
11 int optbug(const struct option *opt, const char *reason)
12 {
13         if (opt->long_name) {
14                 if (opt->short_name)
15                         return error("BUG: switch '%c' (--%s) %s",
16                                      opt->short_name, opt->long_name, reason);
17                 return error("BUG: option '%s' %s", opt->long_name, reason);
18         }
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         case OPTION_MAGNITUDE:
191                 if (unset) {
192                         *(unsigned long *)opt->value = 0;
193                         return 0;
194                 }
195                 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
196                         *(unsigned long *)opt->value = opt->defval;
197                         return 0;
198                 }
199                 if (get_arg(p, opt, flags, &arg))
200                         return -1;
201                 if (!git_parse_ulong(arg, opt->value))
202                         return opterror(opt,
203                                 "expects a non-negative integer value with an optional k/m/g suffix",
204                                 flags);
205                 return 0;
206
207         default:
208                 die("should not happen, someone must be hit on the forehead");
209         }
210 }
211
212 static int parse_short_opt(struct parse_opt_ctx_t *p, const struct option *options)
213 {
214         const struct option *all_opts = options;
215         const struct option *numopt = NULL;
216
217         for (; options->type != OPTION_END; options++) {
218                 if (options->short_name == *p->opt) {
219                         p->opt = p->opt[1] ? p->opt + 1 : NULL;
220                         return get_value(p, options, all_opts, OPT_SHORT);
221                 }
222
223                 /*
224                  * Handle the numerical option later, explicit one-digit
225                  * options take precedence over it.
226                  */
227                 if (options->type == OPTION_NUMBER)
228                         numopt = options;
229         }
230         if (numopt && isdigit(*p->opt)) {
231                 size_t len = 1;
232                 char *arg;
233                 int rc;
234
235                 while (isdigit(p->opt[len]))
236                         len++;
237                 arg = xmemdupz(p->opt, len);
238                 p->opt = p->opt[len] ? p->opt + len : NULL;
239                 rc = (*numopt->callback)(numopt, arg, 0) ? (-1) : 0;
240                 free(arg);
241                 return rc;
242         }
243         return -2;
244 }
245
246 static int parse_long_opt(struct parse_opt_ctx_t *p, const char *arg,
247                           const struct option *options)
248 {
249         const struct option *all_opts = options;
250         const char *arg_end = strchrnul(arg, '=');
251         const struct option *abbrev_option = NULL, *ambiguous_option = NULL;
252         int abbrev_flags = 0, ambiguous_flags = 0;
253
254         for (; options->type != OPTION_END; options++) {
255                 const char *rest, *long_name = options->long_name;
256                 int flags = 0, opt_flags = 0;
257
258                 if (!long_name)
259                         continue;
260
261 again:
262                 if (!skip_prefix(arg, long_name, &rest))
263                         rest = NULL;
264                 if (options->type == OPTION_ARGUMENT) {
265                         if (!rest)
266                                 continue;
267                         if (*rest == '=')
268                                 return opterror(options, "takes no value", flags);
269                         if (*rest)
270                                 continue;
271                         p->out[p->cpidx++] = arg - 2;
272                         return 0;
273                 }
274                 if (!rest) {
275                         /* abbreviated? */
276                         if (!strncmp(long_name, arg, arg_end - arg)) {
277 is_abbreviated:
278                                 if (abbrev_option) {
279                                         /*
280                                          * If this is abbreviated, it is
281                                          * ambiguous. So when there is no
282                                          * exact match later, we need to
283                                          * error out.
284                                          */
285                                         ambiguous_option = abbrev_option;
286                                         ambiguous_flags = abbrev_flags;
287                                 }
288                                 if (!(flags & OPT_UNSET) && *arg_end)
289                                         p->opt = arg_end + 1;
290                                 abbrev_option = options;
291                                 abbrev_flags = flags ^ opt_flags;
292                                 continue;
293                         }
294                         /* negation allowed? */
295                         if (options->flags & PARSE_OPT_NONEG)
296                                 continue;
297                         /* negated and abbreviated very much? */
298                         if (starts_with("no-", arg)) {
299                                 flags |= OPT_UNSET;
300                                 goto is_abbreviated;
301                         }
302                         /* negated? */
303                         if (!starts_with(arg, "no-")) {
304                                 if (starts_with(long_name, "no-")) {
305                                         long_name += 3;
306                                         opt_flags |= OPT_UNSET;
307                                         goto again;
308                                 }
309                                 continue;
310                         }
311                         flags |= OPT_UNSET;
312                         if (!skip_prefix(arg + 3, long_name, &rest)) {
313                                 /* abbreviated and negated? */
314                                 if (starts_with(long_name, arg + 3))
315                                         goto is_abbreviated;
316                                 else
317                                         continue;
318                         }
319                 }
320                 if (*rest) {
321                         if (*rest != '=')
322                                 continue;
323                         p->opt = rest + 1;
324                 }
325                 return get_value(p, options, all_opts, flags ^ opt_flags);
326         }
327
328         if (ambiguous_option)
329                 return error("Ambiguous option: %s "
330                         "(could be --%s%s or --%s%s)",
331                         arg,
332                         (ambiguous_flags & OPT_UNSET) ?  "no-" : "",
333                         ambiguous_option->long_name,
334                         (abbrev_flags & OPT_UNSET) ?  "no-" : "",
335                         abbrev_option->long_name);
336         if (abbrev_option)
337                 return get_value(p, abbrev_option, all_opts, abbrev_flags);
338         return -2;
339 }
340
341 static int parse_nodash_opt(struct parse_opt_ctx_t *p, const char *arg,
342                             const struct option *options)
343 {
344         const struct option *all_opts = options;
345
346         for (; options->type != OPTION_END; options++) {
347                 if (!(options->flags & PARSE_OPT_NODASH))
348                         continue;
349                 if (options->short_name == arg[0] && arg[1] == '\0')
350                         return get_value(p, options, all_opts, OPT_SHORT);
351         }
352         return -2;
353 }
354
355 static void check_typos(const char *arg, const struct option *options)
356 {
357         if (strlen(arg) < 3)
358                 return;
359
360         if (starts_with(arg, "no-")) {
361                 error ("did you mean `--%s` (with two dashes ?)", arg);
362                 exit(129);
363         }
364
365         for (; options->type != OPTION_END; options++) {
366                 if (!options->long_name)
367                         continue;
368                 if (starts_with(options->long_name, arg)) {
369                         error ("did you mean `--%s` (with two dashes ?)", arg);
370                         exit(129);
371                 }
372         }
373 }
374
375 static void parse_options_check(const struct option *opts)
376 {
377         int err = 0;
378         char short_opts[128];
379
380         memset(short_opts, '\0', sizeof(short_opts));
381         for (; opts->type != OPTION_END; opts++) {
382                 if ((opts->flags & PARSE_OPT_LASTARG_DEFAULT) &&
383                     (opts->flags & PARSE_OPT_OPTARG))
384                         err |= optbug(opts, "uses incompatible flags "
385                                         "LASTARG_DEFAULT and OPTARG");
386                 if (opts->short_name) {
387                         if (0x7F <= opts->short_name)
388                                 err |= optbug(opts, "invalid short name");
389                         else if (short_opts[opts->short_name]++)
390                                 err |= optbug(opts, "short name already used");
391                 }
392                 if (opts->flags & PARSE_OPT_NODASH &&
393                     ((opts->flags & PARSE_OPT_OPTARG) ||
394                      !(opts->flags & PARSE_OPT_NOARG) ||
395                      !(opts->flags & PARSE_OPT_NONEG) ||
396                      opts->long_name))
397                         err |= optbug(opts, "uses feature "
398                                         "not supported for dashless options");
399                 switch (opts->type) {
400                 case OPTION_COUNTUP:
401                 case OPTION_BIT:
402                 case OPTION_NEGBIT:
403                 case OPTION_SET_INT:
404                 case OPTION_NUMBER:
405                         if ((opts->flags & PARSE_OPT_OPTARG) ||
406                             !(opts->flags & PARSE_OPT_NOARG))
407                                 err |= optbug(opts, "should not accept an argument");
408                 default:
409                         ; /* ok. (usually accepts an argument) */
410                 }
411                 if (opts->argh &&
412                     strcspn(opts->argh, " _") != strlen(opts->argh))
413                         err |= optbug(opts, "multi-word argh should use dash to separate words");
414         }
415         if (err)
416                 exit(128);
417 }
418
419 void parse_options_start(struct parse_opt_ctx_t *ctx,
420                          int argc, const char **argv, const char *prefix,
421                          const struct option *options, int flags)
422 {
423         memset(ctx, 0, sizeof(*ctx));
424         ctx->argc = ctx->total = argc - 1;
425         ctx->argv = argv + 1;
426         ctx->out  = argv;
427         ctx->prefix = prefix;
428         ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
429         ctx->flags = flags;
430         if ((flags & PARSE_OPT_KEEP_UNKNOWN) &&
431             (flags & PARSE_OPT_STOP_AT_NON_OPTION))
432                 die("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
433         parse_options_check(options);
434 }
435
436 static int usage_with_options_internal(struct parse_opt_ctx_t *,
437                                        const char * const *,
438                                        const struct option *, int, int);
439
440 int parse_options_step(struct parse_opt_ctx_t *ctx,
441                        const struct option *options,
442                        const char * const usagestr[])
443 {
444         int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
445         int err = 0;
446
447         /* we must reset ->opt, unknown short option leave it dangling */
448         ctx->opt = NULL;
449
450         for (; ctx->argc; ctx->argc--, ctx->argv++) {
451                 const char *arg = ctx->argv[0];
452
453                 if (*arg != '-' || !arg[1]) {
454                         if (parse_nodash_opt(ctx, arg, options) == 0)
455                                 continue;
456                         if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
457                                 return PARSE_OPT_NON_OPTION;
458                         ctx->out[ctx->cpidx++] = ctx->argv[0];
459                         continue;
460                 }
461
462                 /* lone -h asks for help */
463                 if (internal_help && ctx->total == 1 && !strcmp(arg + 1, "h"))
464                         goto show_usage;
465
466                 if (arg[1] != '-') {
467                         ctx->opt = arg + 1;
468                         switch (parse_short_opt(ctx, options)) {
469                         case -1:
470                                 goto show_usage_error;
471                         case -2:
472                                 if (ctx->opt)
473                                         check_typos(arg + 1, options);
474                                 if (internal_help && *ctx->opt == 'h')
475                                         goto show_usage;
476                                 goto unknown;
477                         }
478                         if (ctx->opt)
479                                 check_typos(arg + 1, options);
480                         while (ctx->opt) {
481                                 switch (parse_short_opt(ctx, options)) {
482                                 case -1:
483                                         goto show_usage_error;
484                                 case -2:
485                                         if (internal_help && *ctx->opt == 'h')
486                                                 goto show_usage;
487
488                                         /* fake a short option thing to hide the fact that we may have
489                                          * started to parse aggregated stuff
490                                          *
491                                          * This is leaky, too bad.
492                                          */
493                                         ctx->argv[0] = xstrdup(ctx->opt - 1);
494                                         *(char *)ctx->argv[0] = '-';
495                                         goto unknown;
496                                 }
497                         }
498                         continue;
499                 }
500
501                 if (!arg[2]) { /* "--" */
502                         if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
503                                 ctx->argc--;
504                                 ctx->argv++;
505                         }
506                         break;
507                 }
508
509                 if (internal_help && !strcmp(arg + 2, "help-all"))
510                         return usage_with_options_internal(ctx, usagestr, options, 1, 0);
511                 if (internal_help && !strcmp(arg + 2, "help"))
512                         goto show_usage;
513                 switch (parse_long_opt(ctx, arg + 2, options)) {
514                 case -1:
515                         goto show_usage_error;
516                 case -2:
517                         goto unknown;
518                 }
519                 continue;
520 unknown:
521                 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN))
522                         return PARSE_OPT_UNKNOWN;
523                 ctx->out[ctx->cpidx++] = ctx->argv[0];
524                 ctx->opt = NULL;
525         }
526         return PARSE_OPT_DONE;
527
528  show_usage_error:
529         err = 1;
530  show_usage:
531         return usage_with_options_internal(ctx, usagestr, options, 0, err);
532 }
533
534 int parse_options_end(struct parse_opt_ctx_t *ctx)
535 {
536         memmove(ctx->out + ctx->cpidx, ctx->argv, ctx->argc * sizeof(*ctx->out));
537         ctx->out[ctx->cpidx + ctx->argc] = NULL;
538         return ctx->cpidx + ctx->argc;
539 }
540
541 int parse_options(int argc, const char **argv, const char *prefix,
542                   const struct option *options, const char * const usagestr[],
543                   int flags)
544 {
545         struct parse_opt_ctx_t ctx;
546
547         parse_options_start(&ctx, argc, argv, prefix, options, flags);
548         switch (parse_options_step(&ctx, options, usagestr)) {
549         case PARSE_OPT_HELP:
550                 exit(129);
551         case PARSE_OPT_NON_OPTION:
552         case PARSE_OPT_DONE:
553                 break;
554         default: /* PARSE_OPT_UNKNOWN */
555                 if (ctx.argv[0][1] == '-') {
556                         error("unknown option `%s'", ctx.argv[0] + 2);
557                 } else if (isascii(*ctx.opt)) {
558                         error("unknown switch `%c'", *ctx.opt);
559                 } else {
560                         error("unknown non-ascii option in string: `%s'",
561                               ctx.argv[0]);
562                 }
563                 usage_with_options(usagestr, options);
564         }
565
566         precompose_argv(argc, argv);
567         return parse_options_end(&ctx);
568 }
569
570 static int usage_argh(const struct option *opts, FILE *outfile)
571 {
572         const char *s;
573         int literal = (opts->flags & PARSE_OPT_LITERAL_ARGHELP) || !opts->argh;
574         if (opts->flags & PARSE_OPT_OPTARG)
575                 if (opts->long_name)
576                         s = literal ? "[=%s]" : "[=<%s>]";
577                 else
578                         s = literal ? "[%s]" : "[<%s>]";
579         else
580                 s = literal ? " %s" : " <%s>";
581         return utf8_fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
582 }
583
584 #define USAGE_OPTS_WIDTH 24
585 #define USAGE_GAP         2
586
587 static int usage_with_options_internal(struct parse_opt_ctx_t *ctx,
588                                        const char * const *usagestr,
589                                        const struct option *opts, int full, int err)
590 {
591         FILE *outfile = err ? stderr : stdout;
592
593         if (!usagestr)
594                 return PARSE_OPT_HELP;
595
596         if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
597                 fprintf(outfile, "cat <<\\EOF\n");
598
599         fprintf_ln(outfile, _("usage: %s"), _(*usagestr++));
600         while (*usagestr && **usagestr)
601                 /* TRANSLATORS: the colon here should align with the
602                    one in "usage: %s" translation */
603                 fprintf_ln(outfile, _("   or: %s"), _(*usagestr++));
604         while (*usagestr) {
605                 if (**usagestr)
606                         fprintf_ln(outfile, _("    %s"), _(*usagestr));
607                 else
608                         putchar('\n');
609                 usagestr++;
610         }
611
612         if (opts->type != OPTION_GROUP)
613                 fputc('\n', outfile);
614
615         for (; opts->type != OPTION_END; opts++) {
616                 size_t pos;
617                 int pad;
618
619                 if (opts->type == OPTION_GROUP) {
620                         fputc('\n', outfile);
621                         if (*opts->help)
622                                 fprintf(outfile, "%s\n", _(opts->help));
623                         continue;
624                 }
625                 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
626                         continue;
627
628                 pos = fprintf(outfile, "    ");
629                 if (opts->short_name) {
630                         if (opts->flags & PARSE_OPT_NODASH)
631                                 pos += fprintf(outfile, "%c", opts->short_name);
632                         else
633                                 pos += fprintf(outfile, "-%c", opts->short_name);
634                 }
635                 if (opts->long_name && opts->short_name)
636                         pos += fprintf(outfile, ", ");
637                 if (opts->long_name)
638                         pos += fprintf(outfile, "--%s", opts->long_name);
639                 if (opts->type == OPTION_NUMBER)
640                         pos += utf8_fprintf(outfile, _("-NUM"));
641
642                 if ((opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
643                     !(opts->flags & PARSE_OPT_NOARG))
644                         pos += usage_argh(opts, outfile);
645
646                 if (pos <= USAGE_OPTS_WIDTH)
647                         pad = USAGE_OPTS_WIDTH - pos;
648                 else {
649                         fputc('\n', outfile);
650                         pad = USAGE_OPTS_WIDTH;
651                 }
652                 fprintf(outfile, "%*s%s\n", pad + USAGE_GAP, "", _(opts->help));
653         }
654         fputc('\n', outfile);
655
656         if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
657                 fputs("EOF\n", outfile);
658
659         return PARSE_OPT_HELP;
660 }
661
662 void NORETURN usage_with_options(const char * const *usagestr,
663                         const struct option *opts)
664 {
665         usage_with_options_internal(NULL, usagestr, opts, 0, 1);
666         exit(129);
667 }
668
669 void NORETURN usage_msg_opt(const char *msg,
670                    const char * const *usagestr,
671                    const struct option *options)
672 {
673         fprintf(stderr, "%s\n\n", msg);
674         usage_with_options(usagestr, options);
675 }