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