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