parse-options: convert "command mode" to a flag
[git] / parse-options.c
1 #include "git-compat-util.h"
2 #include "parse-options.h"
3 #include "cache.h"
4 #include "config.h"
5 #include "commit.h"
6 #include "color.h"
7 #include "utf8.h"
8
9 static int disallow_abbreviated_options;
10
11 #define OPT_SHORT 1
12 #define OPT_UNSET 2
13
14 int optbug(const struct option *opt, const char *reason)
15 {
16         if (opt->long_name) {
17                 if (opt->short_name)
18                         return error("BUG: switch '%c' (--%s) %s",
19                                      opt->short_name, opt->long_name, reason);
20                 return error("BUG: option '%s' %s", opt->long_name, reason);
21         }
22         return error("BUG: switch '%c' %s", opt->short_name, reason);
23 }
24
25 static enum parse_opt_result get_arg(struct parse_opt_ctx_t *p,
26                                      const struct option *opt,
27                                      int flags, const char **arg)
28 {
29         if (p->opt) {
30                 *arg = p->opt;
31                 p->opt = NULL;
32         } else if (p->argc == 1 && (opt->flags & PARSE_OPT_LASTARG_DEFAULT)) {
33                 *arg = (const char *)opt->defval;
34         } else if (p->argc > 1) {
35                 p->argc--;
36                 *arg = *++p->argv;
37         } else
38                 return error(_("%s requires a value"), optname(opt, flags));
39         return 0;
40 }
41
42 static void fix_filename(const char *prefix, const char **file)
43 {
44         if (!file || !*file || !prefix || is_absolute_path(*file)
45             || !strcmp("-", *file))
46                 return;
47         *file = prefix_filename(prefix, *file);
48 }
49
50 static enum parse_opt_result opt_command_mode_error(
51         const struct option *opt,
52         const struct option *all_opts,
53         int flags)
54 {
55         const struct option *that;
56         struct strbuf that_name = STRBUF_INIT;
57
58         /*
59          * Find the other option that was used to set the variable
60          * already, and report that this is not compatible with it.
61          */
62         for (that = all_opts; that->type != OPTION_END; that++) {
63                 if (that == opt ||
64                     !(that->flags & PARSE_OPT_CMDMODE) ||
65                     that->value != opt->value ||
66                     that->defval != *(int *)opt->value)
67                         continue;
68
69                 if (that->long_name)
70                         strbuf_addf(&that_name, "--%s", that->long_name);
71                 else
72                         strbuf_addf(&that_name, "-%c", that->short_name);
73                 error(_("%s is incompatible with %s"),
74                       optname(opt, flags), that_name.buf);
75                 strbuf_release(&that_name);
76                 return PARSE_OPT_ERROR;
77         }
78         return error(_("%s : incompatible with something else"),
79                      optname(opt, flags));
80 }
81
82 static enum parse_opt_result get_value(struct parse_opt_ctx_t *p,
83                                        const struct option *opt,
84                                        const struct option *all_opts,
85                                        int flags)
86 {
87         const char *s, *arg;
88         const int unset = flags & OPT_UNSET;
89         int err;
90
91         if (unset && p->opt)
92                 return error(_("%s takes no value"), optname(opt, flags));
93         if (unset && (opt->flags & PARSE_OPT_NONEG))
94                 return error(_("%s isn't available"), optname(opt, flags));
95         if (!(flags & OPT_SHORT) && p->opt && (opt->flags & PARSE_OPT_NOARG))
96                 return error(_("%s takes no value"), optname(opt, flags));
97
98         /*
99          * Giving the same mode option twice, although unnecessary,
100          * is not a grave error, so let it pass.
101          */
102         if ((opt->flags & PARSE_OPT_CMDMODE) &&
103             *(int *)opt->value && *(int *)opt->value != opt->defval)
104                 return opt_command_mode_error(opt, all_opts, flags);
105
106         switch (opt->type) {
107         case OPTION_LOWLEVEL_CALLBACK:
108                 return opt->ll_callback(p, opt, NULL, unset);
109
110         case OPTION_BIT:
111                 if (unset)
112                         *(int *)opt->value &= ~opt->defval;
113                 else
114                         *(int *)opt->value |= opt->defval;
115                 return 0;
116
117         case OPTION_NEGBIT:
118                 if (unset)
119                         *(int *)opt->value |= opt->defval;
120                 else
121                         *(int *)opt->value &= ~opt->defval;
122                 return 0;
123
124         case OPTION_BITOP:
125                 if (unset)
126                         BUG("BITOP can't have unset form");
127                 *(int *)opt->value &= ~opt->extra;
128                 *(int *)opt->value |= opt->defval;
129                 return 0;
130
131         case OPTION_COUNTUP:
132                 if (*(int *)opt->value < 0)
133                         *(int *)opt->value = 0;
134                 *(int *)opt->value = unset ? 0 : *(int *)opt->value + 1;
135                 return 0;
136
137         case OPTION_SET_INT:
138                 *(int *)opt->value = unset ? 0 : 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         {
165                 const char *p_arg = NULL;
166                 int p_unset;
167
168                 if (unset)
169                         p_unset = 1;
170                 else if (opt->flags & PARSE_OPT_NOARG)
171                         p_unset = 0;
172                 else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
173                         p_unset = 0;
174                 else if (get_arg(p, opt, flags, &arg))
175                         return -1;
176                 else {
177                         p_unset = 0;
178                         p_arg = arg;
179                 }
180                 if (opt->callback)
181                         return (*opt->callback)(opt, p_arg, p_unset) ? (-1) : 0;
182                 else
183                         return (*opt->ll_callback)(p, opt, p_arg, p_unset);
184         }
185         case OPTION_INTEGER:
186                 if (unset) {
187                         *(int *)opt->value = 0;
188                         return 0;
189                 }
190                 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
191                         *(int *)opt->value = opt->defval;
192                         return 0;
193                 }
194                 if (get_arg(p, opt, flags, &arg))
195                         return -1;
196                 if (!*arg)
197                         return error(_("%s expects a numerical value"),
198                                      optname(opt, flags));
199                 *(int *)opt->value = strtol(arg, (char **)&s, 10);
200                 if (*s)
201                         return error(_("%s expects a numerical value"),
202                                      optname(opt, flags));
203                 return 0;
204
205         case OPTION_MAGNITUDE:
206                 if (unset) {
207                         *(unsigned long *)opt->value = 0;
208                         return 0;
209                 }
210                 if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
211                         *(unsigned long *)opt->value = opt->defval;
212                         return 0;
213                 }
214                 if (get_arg(p, opt, flags, &arg))
215                         return -1;
216                 if (!git_parse_ulong(arg, opt->value))
217                         return error(_("%s expects a non-negative integer value"
218                                        " with an optional k/m/g suffix"),
219                                      optname(opt, flags));
220                 return 0;
221
222         default:
223                 BUG("opt->type %d should not happen", opt->type);
224         }
225 }
226
227 static enum parse_opt_result parse_short_opt(struct parse_opt_ctx_t *p,
228                                              const struct option *options)
229 {
230         const struct option *all_opts = options;
231         const struct option *numopt = NULL;
232
233         for (; options->type != OPTION_END; options++) {
234                 if (options->short_name == *p->opt) {
235                         p->opt = p->opt[1] ? p->opt + 1 : NULL;
236                         return get_value(p, options, all_opts, OPT_SHORT);
237                 }
238
239                 /*
240                  * Handle the numerical option later, explicit one-digit
241                  * options take precedence over it.
242                  */
243                 if (options->type == OPTION_NUMBER)
244                         numopt = options;
245         }
246         if (numopt && isdigit(*p->opt)) {
247                 size_t len = 1;
248                 char *arg;
249                 int rc;
250
251                 while (isdigit(p->opt[len]))
252                         len++;
253                 arg = xmemdupz(p->opt, len);
254                 p->opt = p->opt[len] ? p->opt + len : NULL;
255                 if (numopt->callback)
256                         rc = (*numopt->callback)(numopt, arg, 0) ? (-1) : 0;
257                 else
258                         rc = (*numopt->ll_callback)(p, numopt, arg, 0);
259                 free(arg);
260                 return rc;
261         }
262         return PARSE_OPT_UNKNOWN;
263 }
264
265 static int has_string(const char *it, const char **array)
266 {
267         while (*array)
268                 if (!strcmp(it, *(array++)))
269                         return 1;
270         return 0;
271 }
272
273 static int is_alias(struct parse_opt_ctx_t *ctx,
274                     const struct option *one_opt,
275                     const struct option *another_opt)
276 {
277         const char **group;
278
279         if (!ctx->alias_groups)
280                 return 0;
281
282         if (!one_opt->long_name || !another_opt->long_name)
283                 return 0;
284
285         for (group = ctx->alias_groups; *group; group += 3) {
286                 /* it and other are from the same family? */
287                 if (has_string(one_opt->long_name, group) &&
288                     has_string(another_opt->long_name, group))
289                         return 1;
290         }
291         return 0;
292 }
293
294 static enum parse_opt_result parse_long_opt(
295         struct parse_opt_ctx_t *p, const char *arg,
296         const struct option *options)
297 {
298         const struct option *all_opts = options;
299         const char *arg_end = strchrnul(arg, '=');
300         const struct option *abbrev_option = NULL, *ambiguous_option = NULL;
301         int abbrev_flags = 0, ambiguous_flags = 0;
302
303         for (; options->type != OPTION_END; options++) {
304                 const char *rest, *long_name = options->long_name;
305                 int flags = 0, opt_flags = 0;
306
307                 if (!long_name)
308                         continue;
309
310 again:
311                 if (!skip_prefix(arg, long_name, &rest))
312                         rest = NULL;
313                 if (options->type == OPTION_ARGUMENT) {
314                         if (!rest)
315                                 continue;
316                         if (*rest == '=')
317                                 return error(_("%s takes no value"),
318                                              optname(options, flags));
319                         if (*rest)
320                                 continue;
321                         if (options->value)
322                                 *(int *)options->value = options->defval;
323                         p->out[p->cpidx++] = arg - 2;
324                         return PARSE_OPT_DONE;
325                 }
326                 if (!rest) {
327                         /* abbreviated? */
328                         if (!(p->flags & PARSE_OPT_KEEP_UNKNOWN) &&
329                             !strncmp(long_name, arg, arg_end - arg)) {
330 is_abbreviated:
331                                 if (abbrev_option &&
332                                     !is_alias(p, abbrev_option, options)) {
333                                         /*
334                                          * If this is abbreviated, it is
335                                          * ambiguous. So when there is no
336                                          * exact match later, we need to
337                                          * error out.
338                                          */
339                                         ambiguous_option = abbrev_option;
340                                         ambiguous_flags = abbrev_flags;
341                                 }
342                                 if (!(flags & OPT_UNSET) && *arg_end)
343                                         p->opt = arg_end + 1;
344                                 abbrev_option = options;
345                                 abbrev_flags = flags ^ opt_flags;
346                                 continue;
347                         }
348                         /* negation allowed? */
349                         if (options->flags & PARSE_OPT_NONEG)
350                                 continue;
351                         /* negated and abbreviated very much? */
352                         if (starts_with("no-", arg)) {
353                                 flags |= OPT_UNSET;
354                                 goto is_abbreviated;
355                         }
356                         /* negated? */
357                         if (!starts_with(arg, "no-")) {
358                                 if (starts_with(long_name, "no-")) {
359                                         long_name += 3;
360                                         opt_flags |= OPT_UNSET;
361                                         goto again;
362                                 }
363                                 continue;
364                         }
365                         flags |= OPT_UNSET;
366                         if (!skip_prefix(arg + 3, long_name, &rest)) {
367                                 /* abbreviated and negated? */
368                                 if (starts_with(long_name, arg + 3))
369                                         goto is_abbreviated;
370                                 else
371                                         continue;
372                         }
373                 }
374                 if (*rest) {
375                         if (*rest != '=')
376                                 continue;
377                         p->opt = rest + 1;
378                 }
379                 return get_value(p, options, all_opts, flags ^ opt_flags);
380         }
381
382         if (disallow_abbreviated_options && (ambiguous_option || abbrev_option))
383                 die("disallowed abbreviated or ambiguous option '%.*s'",
384                     (int)(arg_end - arg), arg);
385
386         if (ambiguous_option) {
387                 error(_("ambiguous option: %s "
388                         "(could be --%s%s or --%s%s)"),
389                         arg,
390                         (ambiguous_flags & OPT_UNSET) ?  "no-" : "",
391                         ambiguous_option->long_name,
392                         (abbrev_flags & OPT_UNSET) ?  "no-" : "",
393                         abbrev_option->long_name);
394                 return PARSE_OPT_HELP;
395         }
396         if (abbrev_option)
397                 return get_value(p, abbrev_option, all_opts, abbrev_flags);
398         return PARSE_OPT_UNKNOWN;
399 }
400
401 static int parse_nodash_opt(struct parse_opt_ctx_t *p, const char *arg,
402                             const struct option *options)
403 {
404         const struct option *all_opts = options;
405
406         for (; options->type != OPTION_END; options++) {
407                 if (!(options->flags & PARSE_OPT_NODASH))
408                         continue;
409                 if (options->short_name == arg[0] && arg[1] == '\0')
410                         return get_value(p, options, all_opts, OPT_SHORT);
411         }
412         return -2;
413 }
414
415 static void check_typos(const char *arg, const struct option *options)
416 {
417         if (strlen(arg) < 3)
418                 return;
419
420         if (starts_with(arg, "no-")) {
421                 error(_("did you mean `--%s` (with two dashes ?)"), arg);
422                 exit(129);
423         }
424
425         for (; options->type != OPTION_END; options++) {
426                 if (!options->long_name)
427                         continue;
428                 if (starts_with(options->long_name, arg)) {
429                         error(_("did you mean `--%s` (with two dashes ?)"), arg);
430                         exit(129);
431                 }
432         }
433 }
434
435 static void parse_options_check(const struct option *opts)
436 {
437         int err = 0;
438         char short_opts[128];
439
440         memset(short_opts, '\0', sizeof(short_opts));
441         for (; opts->type != OPTION_END; opts++) {
442                 if ((opts->flags & PARSE_OPT_LASTARG_DEFAULT) &&
443                     (opts->flags & PARSE_OPT_OPTARG))
444                         err |= optbug(opts, "uses incompatible flags "
445                                         "LASTARG_DEFAULT and OPTARG");
446                 if (opts->short_name) {
447                         if (0x7F <= opts->short_name)
448                                 err |= optbug(opts, "invalid short name");
449                         else if (short_opts[opts->short_name]++)
450                                 err |= optbug(opts, "short name already used");
451                 }
452                 if (opts->flags & PARSE_OPT_NODASH &&
453                     ((opts->flags & PARSE_OPT_OPTARG) ||
454                      !(opts->flags & PARSE_OPT_NOARG) ||
455                      !(opts->flags & PARSE_OPT_NONEG) ||
456                      opts->long_name))
457                         err |= optbug(opts, "uses feature "
458                                         "not supported for dashless options");
459                 switch (opts->type) {
460                 case OPTION_COUNTUP:
461                 case OPTION_BIT:
462                 case OPTION_NEGBIT:
463                 case OPTION_SET_INT:
464                 case OPTION_NUMBER:
465                         if ((opts->flags & PARSE_OPT_OPTARG) ||
466                             !(opts->flags & PARSE_OPT_NOARG))
467                                 err |= optbug(opts, "should not accept an argument");
468                         break;
469                 case OPTION_CALLBACK:
470                         if (!opts->callback && !opts->ll_callback)
471                                 BUG("OPTION_CALLBACK needs one callback");
472                         if (opts->callback && opts->ll_callback)
473                                 BUG("OPTION_CALLBACK can't have two callbacks");
474                         break;
475                 case OPTION_LOWLEVEL_CALLBACK:
476                         if (!opts->ll_callback)
477                                 BUG("OPTION_LOWLEVEL_CALLBACK needs a callback");
478                         if (opts->callback)
479                                 BUG("OPTION_LOWLEVEL_CALLBACK needs no high level callback");
480                         break;
481                 case OPTION_ALIAS:
482                         BUG("OPT_ALIAS() should not remain at this point. "
483                             "Are you using parse_options_step() directly?\n"
484                             "That case is not supported yet.");
485                 default:
486                         ; /* ok. (usually accepts an argument) */
487                 }
488                 if (opts->argh &&
489                     strcspn(opts->argh, " _") != strlen(opts->argh))
490                         err |= optbug(opts, "multi-word argh should use dash to separate words");
491         }
492         if (err)
493                 exit(128);
494 }
495
496 static void parse_options_start_1(struct parse_opt_ctx_t *ctx,
497                                   int argc, const char **argv, const char *prefix,
498                                   const struct option *options, int flags)
499 {
500         ctx->argc = argc;
501         ctx->argv = argv;
502         if (!(flags & PARSE_OPT_ONE_SHOT)) {
503                 ctx->argc--;
504                 ctx->argv++;
505         }
506         ctx->total = ctx->argc;
507         ctx->out   = argv;
508         ctx->prefix = prefix;
509         ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
510         ctx->flags = flags;
511         if ((flags & PARSE_OPT_KEEP_UNKNOWN) &&
512             (flags & PARSE_OPT_STOP_AT_NON_OPTION) &&
513             !(flags & PARSE_OPT_ONE_SHOT))
514                 BUG("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
515         if ((flags & PARSE_OPT_ONE_SHOT) &&
516             (flags & PARSE_OPT_KEEP_ARGV0))
517                 BUG("Can't keep argv0 if you don't have it");
518         parse_options_check(options);
519 }
520
521 void parse_options_start(struct parse_opt_ctx_t *ctx,
522                          int argc, const char **argv, const char *prefix,
523                          const struct option *options, int flags)
524 {
525         memset(ctx, 0, sizeof(*ctx));
526         parse_options_start_1(ctx, argc, argv, prefix, options, flags);
527 }
528
529 static void show_negated_gitcomp(const struct option *opts, int nr_noopts)
530 {
531         int printed_dashdash = 0;
532
533         for (; opts->type != OPTION_END; opts++) {
534                 int has_unset_form = 0;
535                 const char *name;
536
537                 if (!opts->long_name)
538                         continue;
539                 if (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE))
540                         continue;
541                 if (opts->flags & PARSE_OPT_NONEG)
542                         continue;
543
544                 switch (opts->type) {
545                 case OPTION_STRING:
546                 case OPTION_FILENAME:
547                 case OPTION_INTEGER:
548                 case OPTION_MAGNITUDE:
549                 case OPTION_CALLBACK:
550                 case OPTION_BIT:
551                 case OPTION_NEGBIT:
552                 case OPTION_COUNTUP:
553                 case OPTION_SET_INT:
554                         has_unset_form = 1;
555                         break;
556                 default:
557                         break;
558                 }
559                 if (!has_unset_form)
560                         continue;
561
562                 if (skip_prefix(opts->long_name, "no-", &name)) {
563                         if (nr_noopts < 0)
564                                 printf(" --%s", name);
565                 } else if (nr_noopts >= 0) {
566                         if (nr_noopts && !printed_dashdash) {
567                                 printf(" --");
568                                 printed_dashdash = 1;
569                         }
570                         printf(" --no-%s", opts->long_name);
571                         nr_noopts++;
572                 }
573         }
574 }
575
576 static int show_gitcomp(const struct option *opts)
577 {
578         const struct option *original_opts = opts;
579         int nr_noopts = 0;
580
581         for (; opts->type != OPTION_END; opts++) {
582                 const char *suffix = "";
583
584                 if (!opts->long_name)
585                         continue;
586                 if (opts->flags & (PARSE_OPT_HIDDEN | PARSE_OPT_NOCOMPLETE))
587                         continue;
588
589                 switch (opts->type) {
590                 case OPTION_GROUP:
591                         continue;
592                 case OPTION_STRING:
593                 case OPTION_FILENAME:
594                 case OPTION_INTEGER:
595                 case OPTION_MAGNITUDE:
596                 case OPTION_CALLBACK:
597                         if (opts->flags & PARSE_OPT_NOARG)
598                                 break;
599                         if (opts->flags & PARSE_OPT_OPTARG)
600                                 break;
601                         if (opts->flags & PARSE_OPT_LASTARG_DEFAULT)
602                                 break;
603                         suffix = "=";
604                         break;
605                 default:
606                         break;
607                 }
608                 if (opts->flags & PARSE_OPT_COMP_ARG)
609                         suffix = "=";
610                 if (starts_with(opts->long_name, "no-"))
611                         nr_noopts++;
612                 printf(" --%s%s", opts->long_name, suffix);
613         }
614         show_negated_gitcomp(original_opts, -1);
615         show_negated_gitcomp(original_opts, nr_noopts);
616         fputc('\n', stdout);
617         return PARSE_OPT_COMPLETE;
618 }
619
620 /*
621  * Scan and may produce a new option[] array, which should be used
622  * instead of the original 'options'.
623  *
624  * Right now this is only used to preprocess and substitute
625  * OPTION_ALIAS.
626  */
627 static struct option *preprocess_options(struct parse_opt_ctx_t *ctx,
628                                          const struct option *options)
629 {
630         struct option *newopt;
631         int i, nr, alias;
632         int nr_aliases = 0;
633
634         for (nr = 0; options[nr].type != OPTION_END; nr++) {
635                 if (options[nr].type == OPTION_ALIAS)
636                         nr_aliases++;
637         }
638
639         if (!nr_aliases)
640                 return NULL;
641
642         ALLOC_ARRAY(newopt, nr + 1);
643         COPY_ARRAY(newopt, options, nr + 1);
644
645         /* each alias has two string pointers and NULL */
646         CALLOC_ARRAY(ctx->alias_groups, 3 * (nr_aliases + 1));
647
648         for (alias = 0, i = 0; i < nr; i++) {
649                 int short_name;
650                 const char *long_name;
651                 const char *source;
652                 int j;
653
654                 if (newopt[i].type != OPTION_ALIAS)
655                         continue;
656
657                 short_name = newopt[i].short_name;
658                 long_name = newopt[i].long_name;
659                 source = newopt[i].value;
660
661                 if (!long_name)
662                         BUG("An alias must have long option name");
663
664                 for (j = 0; j < nr; j++) {
665                         const char *name = options[j].long_name;
666
667                         if (!name || strcmp(name, source))
668                                 continue;
669
670                         if (options[j].type == OPTION_ALIAS)
671                                 BUG("No please. Nested aliases are not supported.");
672
673                         /*
674                          * NEEDSWORK: this is a bit inconsistent because
675                          * usage_with_options() on the original options[] will print
676                          * help string as "alias of %s" but "git cmd -h" will
677                          * print the original help string.
678                          */
679                         memcpy(newopt + i, options + j, sizeof(*newopt));
680                         newopt[i].short_name = short_name;
681                         newopt[i].long_name = long_name;
682                         break;
683                 }
684
685                 if (j == nr)
686                         BUG("could not find source option '%s' of alias '%s'",
687                             source, newopt[i].long_name);
688                 ctx->alias_groups[alias * 3 + 0] = newopt[i].long_name;
689                 ctx->alias_groups[alias * 3 + 1] = options[j].long_name;
690                 ctx->alias_groups[alias * 3 + 2] = NULL;
691                 alias++;
692         }
693
694         return newopt;
695 }
696
697 static int usage_with_options_internal(struct parse_opt_ctx_t *,
698                                        const char * const *,
699                                        const struct option *, int, int);
700
701 int parse_options_step(struct parse_opt_ctx_t *ctx,
702                        const struct option *options,
703                        const char * const usagestr[])
704 {
705         int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
706
707         /* we must reset ->opt, unknown short option leave it dangling */
708         ctx->opt = NULL;
709
710         for (; ctx->argc; ctx->argc--, ctx->argv++) {
711                 const char *arg = ctx->argv[0];
712
713                 if (ctx->flags & PARSE_OPT_ONE_SHOT &&
714                     ctx->argc != ctx->total)
715                         break;
716
717                 if (*arg != '-' || !arg[1]) {
718                         if (parse_nodash_opt(ctx, arg, options) == 0)
719                                 continue;
720                         if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
721                                 return PARSE_OPT_NON_OPTION;
722                         ctx->out[ctx->cpidx++] = ctx->argv[0];
723                         continue;
724                 }
725
726                 /* lone -h asks for help */
727                 if (internal_help && ctx->total == 1 && !strcmp(arg + 1, "h"))
728                         goto show_usage;
729
730                 /* lone --git-completion-helper is asked by git-completion.bash */
731                 if (ctx->total == 1 && !strcmp(arg + 1, "-git-completion-helper"))
732                         return show_gitcomp(options);
733
734                 if (arg[1] != '-') {
735                         ctx->opt = arg + 1;
736                         switch (parse_short_opt(ctx, options)) {
737                         case PARSE_OPT_ERROR:
738                                 return PARSE_OPT_ERROR;
739                         case PARSE_OPT_UNKNOWN:
740                                 if (ctx->opt)
741                                         check_typos(arg + 1, options);
742                                 if (internal_help && *ctx->opt == 'h')
743                                         goto show_usage;
744                                 goto unknown;
745                         case PARSE_OPT_NON_OPTION:
746                         case PARSE_OPT_HELP:
747                         case PARSE_OPT_COMPLETE:
748                                 BUG("parse_short_opt() cannot return these");
749                         case PARSE_OPT_DONE:
750                                 break;
751                         }
752                         if (ctx->opt)
753                                 check_typos(arg + 1, options);
754                         while (ctx->opt) {
755                                 switch (parse_short_opt(ctx, options)) {
756                                 case PARSE_OPT_ERROR:
757                                         return PARSE_OPT_ERROR;
758                                 case PARSE_OPT_UNKNOWN:
759                                         if (internal_help && *ctx->opt == 'h')
760                                                 goto show_usage;
761
762                                         /* fake a short option thing to hide the fact that we may have
763                                          * started to parse aggregated stuff
764                                          *
765                                          * This is leaky, too bad.
766                                          */
767                                         ctx->argv[0] = xstrdup(ctx->opt - 1);
768                                         *(char *)ctx->argv[0] = '-';
769                                         goto unknown;
770                                 case PARSE_OPT_NON_OPTION:
771                                 case PARSE_OPT_COMPLETE:
772                                 case PARSE_OPT_HELP:
773                                         BUG("parse_short_opt() cannot return these");
774                                 case PARSE_OPT_DONE:
775                                         break;
776                                 }
777                         }
778                         continue;
779                 }
780
781                 if (!arg[2] /* "--" */ ||
782                     !strcmp(arg + 2, "end-of-options")) {
783                         if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
784                                 ctx->argc--;
785                                 ctx->argv++;
786                         }
787                         break;
788                 }
789
790                 if (internal_help && !strcmp(arg + 2, "help-all"))
791                         return usage_with_options_internal(ctx, usagestr, options, 1, 0);
792                 if (internal_help && !strcmp(arg + 2, "help"))
793                         goto show_usage;
794                 switch (parse_long_opt(ctx, arg + 2, options)) {
795                 case PARSE_OPT_ERROR:
796                         return PARSE_OPT_ERROR;
797                 case PARSE_OPT_UNKNOWN:
798                         goto unknown;
799                 case PARSE_OPT_HELP:
800                         goto show_usage;
801                 case PARSE_OPT_NON_OPTION:
802                 case PARSE_OPT_COMPLETE:
803                         BUG("parse_long_opt() cannot return these");
804                 case PARSE_OPT_DONE:
805                         break;
806                 }
807                 continue;
808 unknown:
809                 if (ctx->flags & PARSE_OPT_ONE_SHOT)
810                         break;
811                 if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN))
812                         return PARSE_OPT_UNKNOWN;
813                 ctx->out[ctx->cpidx++] = ctx->argv[0];
814                 ctx->opt = NULL;
815         }
816         return PARSE_OPT_DONE;
817
818  show_usage:
819         return usage_with_options_internal(ctx, usagestr, options, 0, 0);
820 }
821
822 int parse_options_end(struct parse_opt_ctx_t *ctx)
823 {
824         if (ctx->flags & PARSE_OPT_ONE_SHOT)
825                 return ctx->total - ctx->argc;
826
827         MOVE_ARRAY(ctx->out + ctx->cpidx, ctx->argv, ctx->argc);
828         ctx->out[ctx->cpidx + ctx->argc] = NULL;
829         return ctx->cpidx + ctx->argc;
830 }
831
832 int parse_options(int argc, const char **argv, const char *prefix,
833                   const struct option *options, const char * const usagestr[],
834                   int flags)
835 {
836         struct parse_opt_ctx_t ctx;
837         struct option *real_options;
838
839         disallow_abbreviated_options =
840                 git_env_bool("GIT_TEST_DISALLOW_ABBREVIATED_OPTIONS", 0);
841
842         memset(&ctx, 0, sizeof(ctx));
843         real_options = preprocess_options(&ctx, options);
844         if (real_options)
845                 options = real_options;
846         parse_options_start_1(&ctx, argc, argv, prefix, options, flags);
847         switch (parse_options_step(&ctx, options, usagestr)) {
848         case PARSE_OPT_HELP:
849         case PARSE_OPT_ERROR:
850                 exit(129);
851         case PARSE_OPT_COMPLETE:
852                 exit(0);
853         case PARSE_OPT_NON_OPTION:
854         case PARSE_OPT_DONE:
855                 break;
856         default: /* PARSE_OPT_UNKNOWN */
857                 if (ctx.argv[0][1] == '-') {
858                         error(_("unknown option `%s'"), ctx.argv[0] + 2);
859                 } else if (isascii(*ctx.opt)) {
860                         error(_("unknown switch `%c'"), *ctx.opt);
861                 } else {
862                         error(_("unknown non-ascii option in string: `%s'"),
863                               ctx.argv[0]);
864                 }
865                 usage_with_options(usagestr, options);
866         }
867
868         precompose_argv(argc, argv);
869         free(real_options);
870         free(ctx.alias_groups);
871         return parse_options_end(&ctx);
872 }
873
874 static int usage_argh(const struct option *opts, FILE *outfile)
875 {
876         const char *s;
877         int literal = (opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
878                 !opts->argh || !!strpbrk(opts->argh, "()<>[]|");
879         if (opts->flags & PARSE_OPT_OPTARG)
880                 if (opts->long_name)
881                         s = literal ? "[=%s]" : "[=<%s>]";
882                 else
883                         s = literal ? "[%s]" : "[<%s>]";
884         else
885                 s = literal ? " %s" : " <%s>";
886         return utf8_fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
887 }
888
889 #define USAGE_OPTS_WIDTH 24
890 #define USAGE_GAP         2
891
892 static int usage_with_options_internal(struct parse_opt_ctx_t *ctx,
893                                        const char * const *usagestr,
894                                        const struct option *opts, int full, int err)
895 {
896         FILE *outfile = err ? stderr : stdout;
897         int need_newline;
898
899         if (!usagestr)
900                 return PARSE_OPT_HELP;
901
902         if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
903                 fprintf(outfile, "cat <<\\EOF\n");
904
905         fprintf_ln(outfile, _("usage: %s"), _(*usagestr++));
906         while (*usagestr && **usagestr)
907                 /*
908                  * TRANSLATORS: the colon here should align with the
909                  * one in "usage: %s" translation.
910                  */
911                 fprintf_ln(outfile, _("   or: %s"), _(*usagestr++));
912         while (*usagestr) {
913                 if (**usagestr)
914                         fprintf_ln(outfile, _("    %s"), _(*usagestr));
915                 else
916                         fputc('\n', outfile);
917                 usagestr++;
918         }
919
920         need_newline = 1;
921
922         for (; opts->type != OPTION_END; opts++) {
923                 size_t pos;
924                 int pad;
925
926                 if (opts->type == OPTION_GROUP) {
927                         fputc('\n', outfile);
928                         need_newline = 0;
929                         if (*opts->help)
930                                 fprintf(outfile, "%s\n", _(opts->help));
931                         continue;
932                 }
933                 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
934                         continue;
935
936                 if (need_newline) {
937                         fputc('\n', outfile);
938                         need_newline = 0;
939                 }
940
941                 pos = fprintf(outfile, "    ");
942                 if (opts->short_name) {
943                         if (opts->flags & PARSE_OPT_NODASH)
944                                 pos += fprintf(outfile, "%c", opts->short_name);
945                         else
946                                 pos += fprintf(outfile, "-%c", opts->short_name);
947                 }
948                 if (opts->long_name && opts->short_name)
949                         pos += fprintf(outfile, ", ");
950                 if (opts->long_name)
951                         pos += fprintf(outfile, "--%s", opts->long_name);
952                 if (opts->type == OPTION_NUMBER)
953                         pos += utf8_fprintf(outfile, _("-NUM"));
954
955                 if ((opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
956                     !(opts->flags & PARSE_OPT_NOARG))
957                         pos += usage_argh(opts, outfile);
958
959                 if (pos <= USAGE_OPTS_WIDTH)
960                         pad = USAGE_OPTS_WIDTH - pos;
961                 else {
962                         fputc('\n', outfile);
963                         pad = USAGE_OPTS_WIDTH;
964                 }
965                 if (opts->type == OPTION_ALIAS) {
966                         fprintf(outfile, "%*s", pad + USAGE_GAP, "");
967                         fprintf_ln(outfile, _("alias of --%s"),
968                                    (const char *)opts->value);
969                         continue;
970                 }
971                 fprintf(outfile, "%*s%s\n", pad + USAGE_GAP, "", _(opts->help));
972         }
973         fputc('\n', outfile);
974
975         if (!err && ctx && ctx->flags & PARSE_OPT_SHELL_EVAL)
976                 fputs("EOF\n", outfile);
977
978         return PARSE_OPT_HELP;
979 }
980
981 void NORETURN usage_with_options(const char * const *usagestr,
982                         const struct option *opts)
983 {
984         usage_with_options_internal(NULL, usagestr, opts, 0, 1);
985         exit(129);
986 }
987
988 void NORETURN usage_msg_opt(const char *msg,
989                    const char * const *usagestr,
990                    const struct option *options)
991 {
992         fprintf(stderr, "fatal: %s\n\n", msg);
993         usage_with_options(usagestr, options);
994 }
995
996 const char *optname(const struct option *opt, int flags)
997 {
998         static struct strbuf sb = STRBUF_INIT;
999
1000         strbuf_reset(&sb);
1001         if (flags & OPT_SHORT)
1002                 strbuf_addf(&sb, "switch `%c'", opt->short_name);
1003         else if (flags & OPT_UNSET)
1004                 strbuf_addf(&sb, "option `no-%s'", opt->long_name);
1005         else
1006                 strbuf_addf(&sb, "option `%s'", opt->long_name);
1007
1008         return sb.buf;
1009 }