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