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