pathspec.con commit pathspec: create parse_element_magic helper (1b6112c)
   1#include "cache.h"
   2#include "dir.h"
   3#include "pathspec.h"
   4
   5/*
   6 * Finds which of the given pathspecs match items in the index.
   7 *
   8 * For each pathspec, sets the corresponding entry in the seen[] array
   9 * (which should be specs items long, i.e. the same size as pathspec)
  10 * to the nature of the "closest" (i.e. most specific) match found for
  11 * that pathspec in the index, if it was a closer type of match than
  12 * the existing entry.  As an optimization, matching is skipped
  13 * altogether if seen[] already only contains non-zero entries.
  14 *
  15 * If seen[] has not already been written to, it may make sense
  16 * to use find_pathspecs_matching_against_index() instead.
  17 */
  18void add_pathspec_matches_against_index(const struct pathspec *pathspec,
  19                                        char *seen)
  20{
  21        int num_unmatched = 0, i;
  22
  23        /*
  24         * Since we are walking the index as if we were walking the directory,
  25         * we have to mark the matched pathspec as seen; otherwise we will
  26         * mistakenly think that the user gave a pathspec that did not match
  27         * anything.
  28         */
  29        for (i = 0; i < pathspec->nr; i++)
  30                if (!seen[i])
  31                        num_unmatched++;
  32        if (!num_unmatched)
  33                return;
  34        for (i = 0; i < active_nr; i++) {
  35                const struct cache_entry *ce = active_cache[i];
  36                ce_path_match(ce, pathspec, seen);
  37        }
  38}
  39
  40/*
  41 * Finds which of the given pathspecs match items in the index.
  42 *
  43 * This is a one-shot wrapper around add_pathspec_matches_against_index()
  44 * which allocates, populates, and returns a seen[] array indicating the
  45 * nature of the "closest" (i.e. most specific) matches which each of the
  46 * given pathspecs achieves against all items in the index.
  47 */
  48char *find_pathspecs_matching_against_index(const struct pathspec *pathspec)
  49{
  50        char *seen = xcalloc(pathspec->nr, 1);
  51        add_pathspec_matches_against_index(pathspec, seen);
  52        return seen;
  53}
  54
  55/*
  56 * Magic pathspec
  57 *
  58 * Possible future magic semantics include stuff like:
  59 *
  60 *      { PATHSPEC_RECURSIVE, '*', "recursive" },
  61 *      { PATHSPEC_REGEXP, '\0', "regexp" },
  62 *
  63 */
  64
  65static struct pathspec_magic {
  66        unsigned bit;
  67        char mnemonic; /* this cannot be ':'! */
  68        const char *name;
  69} pathspec_magic[] = {
  70        { PATHSPEC_FROMTOP, '/', "top" },
  71        { PATHSPEC_LITERAL,   0, "literal" },
  72        { PATHSPEC_GLOB,   '\0', "glob" },
  73        { PATHSPEC_ICASE,  '\0', "icase" },
  74        { PATHSPEC_EXCLUDE, '!', "exclude" },
  75};
  76
  77static void prefix_magic(struct strbuf *sb, int prefixlen, unsigned magic)
  78{
  79        int i;
  80        strbuf_addstr(sb, ":(");
  81        for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
  82                if (magic & pathspec_magic[i].bit) {
  83                        if (sb->buf[sb->len - 1] != '(')
  84                                strbuf_addch(sb, ',');
  85                        strbuf_addstr(sb, pathspec_magic[i].name);
  86                }
  87        strbuf_addf(sb, ",prefix:%d)", prefixlen);
  88}
  89
  90static inline int get_literal_global(void)
  91{
  92        static int literal = -1;
  93
  94        if (literal < 0)
  95                literal = git_env_bool(GIT_LITERAL_PATHSPECS_ENVIRONMENT, 0);
  96
  97        return literal;
  98}
  99
 100static inline int get_glob_global(void)
 101{
 102        static int glob = -1;
 103
 104        if (glob < 0)
 105                glob = git_env_bool(GIT_GLOB_PATHSPECS_ENVIRONMENT, 0);
 106
 107        return glob;
 108}
 109
 110static inline int get_noglob_global(void)
 111{
 112        static int noglob = -1;
 113
 114        if (noglob < 0)
 115                noglob = git_env_bool(GIT_NOGLOB_PATHSPECS_ENVIRONMENT, 0);
 116
 117        return noglob;
 118}
 119
 120static inline int get_icase_global(void)
 121{
 122        static int icase = -1;
 123
 124        if (icase < 0)
 125                icase = git_env_bool(GIT_ICASE_PATHSPECS_ENVIRONMENT, 0);
 126
 127        return icase;
 128}
 129
 130static int get_global_magic(int element_magic)
 131{
 132        int global_magic = 0;
 133
 134        if (get_literal_global())
 135                global_magic |= PATHSPEC_LITERAL;
 136
 137        /* --glob-pathspec is overridden by :(literal) */
 138        if (get_glob_global() && !(element_magic & PATHSPEC_LITERAL))
 139                global_magic |= PATHSPEC_GLOB;
 140
 141        if (get_glob_global() && get_noglob_global())
 142                die(_("global 'glob' and 'noglob' pathspec settings are incompatible"));
 143
 144        if (get_icase_global())
 145                global_magic |= PATHSPEC_ICASE;
 146
 147        if ((global_magic & PATHSPEC_LITERAL) &&
 148            (global_magic & ~PATHSPEC_LITERAL))
 149                die(_("global 'literal' pathspec setting is incompatible "
 150                      "with all other global pathspec settings"));
 151
 152        /* --noglob-pathspec adds :(literal) _unless_ :(glob) is specified */
 153        if (get_noglob_global() && !(element_magic & PATHSPEC_GLOB))
 154                global_magic |= PATHSPEC_LITERAL;
 155
 156        return global_magic;
 157}
 158
 159/*
 160 * Parse the pathspec element looking for long magic
 161 *
 162 * saves all magic in 'magic'
 163 * if prefix magic is used, save the prefix length in 'prefix_len'
 164 * returns the position in 'elem' after all magic has been parsed
 165 */
 166static const char *parse_long_magic(unsigned *magic, int *prefix_len,
 167                                    const char *elem)
 168{
 169        const char *pos;
 170        const char *nextat;
 171
 172        for (pos = elem + 2; *pos && *pos != ')'; pos = nextat) {
 173                size_t len = strcspn(pos, ",)");
 174                int i;
 175
 176                if (pos[len] == ',')
 177                        nextat = pos + len + 1; /* handle ',' */
 178                else
 179                        nextat = pos + len; /* handle ')' and '\0' */
 180
 181                if (!len)
 182                        continue;
 183
 184                if (starts_with(pos, "prefix:")) {
 185                        char *endptr;
 186                        *prefix_len = strtol(pos + 7, &endptr, 10);
 187                        if (endptr - pos != len)
 188                                die(_("invalid parameter for pathspec magic 'prefix'"));
 189                        continue;
 190                }
 191
 192                for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
 193                        if (strlen(pathspec_magic[i].name) == len &&
 194                            !strncmp(pathspec_magic[i].name, pos, len)) {
 195                                *magic |= pathspec_magic[i].bit;
 196                                break;
 197                        }
 198                }
 199
 200                if (ARRAY_SIZE(pathspec_magic) <= i)
 201                        die(_("Invalid pathspec magic '%.*s' in '%s'"),
 202                            (int) len, pos, elem);
 203        }
 204
 205        if (*pos != ')')
 206                die(_("Missing ')' at the end of pathspec magic in '%s'"),
 207                    elem);
 208        pos++;
 209
 210        return pos;
 211}
 212
 213/*
 214 * Parse the pathspec element looking for short magic
 215 *
 216 * saves all magic in 'magic'
 217 * returns the position in 'elem' after all magic has been parsed
 218 */
 219static const char *parse_short_magic(unsigned *magic, const char *elem)
 220{
 221        const char *pos;
 222
 223        for (pos = elem + 1; *pos && *pos != ':'; pos++) {
 224                char ch = *pos;
 225                int i;
 226
 227                if (!is_pathspec_magic(ch))
 228                        break;
 229
 230                for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
 231                        if (pathspec_magic[i].mnemonic == ch) {
 232                                *magic |= pathspec_magic[i].bit;
 233                                break;
 234                        }
 235                }
 236
 237                if (ARRAY_SIZE(pathspec_magic) <= i)
 238                        die(_("Unimplemented pathspec magic '%c' in '%s'"),
 239                            ch, elem);
 240        }
 241
 242        if (*pos == ':')
 243                pos++;
 244
 245        return pos;
 246}
 247
 248static const char *parse_element_magic(unsigned *magic, int *prefix_len,
 249                                       const char *elem)
 250{
 251        if (elem[0] != ':' || get_literal_global())
 252                return elem; /* nothing to do */
 253        else if (elem[1] == '(')
 254                /* longhand */
 255                return parse_long_magic(magic, prefix_len, elem);
 256        else
 257                /* shorthand */
 258                return parse_short_magic(magic, elem);
 259}
 260
 261/*
 262 * Take an element of a pathspec and check for magic signatures.
 263 * Append the result to the prefix. Return the magic bitmap.
 264 *
 265 * For now, we only parse the syntax and throw out anything other than
 266 * "top" magic.
 267 *
 268 * NEEDSWORK: This needs to be rewritten when we start migrating
 269 * get_pathspec() users to use the "struct pathspec" interface.  For
 270 * example, a pathspec element may be marked as case-insensitive, but
 271 * the prefix part must always match literally, and a single stupid
 272 * string cannot express such a case.
 273 */
 274static unsigned prefix_pathspec(struct pathspec_item *item, unsigned flags,
 275                                const char *prefix, int prefixlen,
 276                                const char *elt)
 277{
 278        unsigned magic = 0, element_magic = 0;
 279        const char *copyfrom = elt;
 280        char *match;
 281        int i, pathspec_prefix = -1;
 282
 283        /* PATHSPEC_LITERAL_PATH ignores magic */
 284        if (flags & PATHSPEC_LITERAL_PATH) {
 285                magic = PATHSPEC_LITERAL;
 286        } else {
 287                copyfrom = parse_element_magic(&element_magic,
 288                                               &pathspec_prefix,
 289                                               elt);
 290                magic |= element_magic;
 291                magic |= get_global_magic(element_magic);
 292        }
 293
 294        if (pathspec_prefix >= 0 &&
 295            (prefixlen || (prefix && *prefix)))
 296                die("BUG: 'prefix' magic is supposed to be used at worktree's root");
 297
 298        if ((magic & PATHSPEC_LITERAL) && (magic & PATHSPEC_GLOB))
 299                die(_("%s: 'literal' and 'glob' are incompatible"), elt);
 300
 301        if (pathspec_prefix >= 0) {
 302                match = xstrdup(copyfrom);
 303                prefixlen = pathspec_prefix;
 304        } else if (magic & PATHSPEC_FROMTOP) {
 305                match = xstrdup(copyfrom);
 306                prefixlen = 0;
 307        } else {
 308                match = prefix_path_gently(prefix, prefixlen, &prefixlen, copyfrom);
 309                if (!match)
 310                        die(_("%s: '%s' is outside repository"), elt, copyfrom);
 311        }
 312        item->match = match;
 313        /*
 314         * Prefix the pathspec (keep all magic) and assign to
 315         * original. Useful for passing to another command.
 316         */
 317        if ((flags & PATHSPEC_PREFIX_ORIGIN) &&
 318            prefixlen && !get_literal_global()) {
 319                struct strbuf sb = STRBUF_INIT;
 320
 321                /* Preserve the actual prefix length of each pattern */
 322                prefix_magic(&sb, prefixlen, element_magic);
 323
 324                strbuf_addstr(&sb, match);
 325                item->original = strbuf_detach(&sb, NULL);
 326        } else {
 327                item->original = xstrdup(elt);
 328        }
 329        item->len = strlen(item->match);
 330        item->prefix = prefixlen;
 331
 332        if ((flags & PATHSPEC_STRIP_SUBMODULE_SLASH_CHEAP) &&
 333            (item->len >= 1 && item->match[item->len - 1] == '/') &&
 334            (i = cache_name_pos(item->match, item->len - 1)) >= 0 &&
 335            S_ISGITLINK(active_cache[i]->ce_mode)) {
 336                item->len--;
 337                match[item->len] = '\0';
 338        }
 339
 340        if (flags & PATHSPEC_STRIP_SUBMODULE_SLASH_EXPENSIVE)
 341                for (i = 0; i < active_nr; i++) {
 342                        struct cache_entry *ce = active_cache[i];
 343                        int ce_len = ce_namelen(ce);
 344
 345                        if (!S_ISGITLINK(ce->ce_mode))
 346                                continue;
 347
 348                        if (item->len <= ce_len || match[ce_len] != '/' ||
 349                            memcmp(ce->name, match, ce_len))
 350                                continue;
 351                        if (item->len == ce_len + 1) {
 352                                /* strip trailing slash */
 353                                item->len--;
 354                                match[item->len] = '\0';
 355                        } else
 356                                die (_("Pathspec '%s' is in submodule '%.*s'"),
 357                                     elt, ce_len, ce->name);
 358                }
 359
 360        if (magic & PATHSPEC_LITERAL)
 361                item->nowildcard_len = item->len;
 362        else {
 363                item->nowildcard_len = simple_length(item->match);
 364                if (item->nowildcard_len < prefixlen)
 365                        item->nowildcard_len = prefixlen;
 366        }
 367        item->flags = 0;
 368        if (magic & PATHSPEC_GLOB) {
 369                /*
 370                 * FIXME: should we enable ONESTAR in _GLOB for
 371                 * pattern "* * / * . c"?
 372                 */
 373        } else {
 374                if (item->nowildcard_len < item->len &&
 375                    item->match[item->nowildcard_len] == '*' &&
 376                    no_wildcard(item->match + item->nowildcard_len + 1))
 377                        item->flags |= PATHSPEC_ONESTAR;
 378        }
 379
 380        /* sanity checks, pathspec matchers assume these are sane */
 381        assert(item->nowildcard_len <= item->len &&
 382               item->prefix         <= item->len);
 383        return magic;
 384}
 385
 386static int pathspec_item_cmp(const void *a_, const void *b_)
 387{
 388        struct pathspec_item *a, *b;
 389
 390        a = (struct pathspec_item *)a_;
 391        b = (struct pathspec_item *)b_;
 392        return strcmp(a->match, b->match);
 393}
 394
 395static void NORETURN unsupported_magic(const char *pattern,
 396                                       unsigned magic)
 397{
 398        struct strbuf sb = STRBUF_INIT;
 399        int i;
 400        for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
 401                const struct pathspec_magic *m = pathspec_magic + i;
 402                if (!(magic & m->bit))
 403                        continue;
 404                if (sb.len)
 405                        strbuf_addstr(&sb, ", ");
 406
 407                if (m->mnemonic)
 408                        strbuf_addf(&sb, _("'%s' (mnemonic: '%c')"),
 409                                    m->name, m->mnemonic);
 410                else
 411                        strbuf_addf(&sb, "'%s'", m->name);
 412        }
 413        /*
 414         * We may want to substitute "this command" with a command
 415         * name. E.g. when add--interactive dies when running
 416         * "checkout -p"
 417         */
 418        die(_("%s: pathspec magic not supported by this command: %s"),
 419            pattern, sb.buf);
 420}
 421
 422/*
 423 * Given command line arguments and a prefix, convert the input to
 424 * pathspec. die() if any magic in magic_mask is used.
 425 */
 426void parse_pathspec(struct pathspec *pathspec,
 427                    unsigned magic_mask, unsigned flags,
 428                    const char *prefix, const char **argv)
 429{
 430        struct pathspec_item *item;
 431        const char *entry = argv ? *argv : NULL;
 432        int i, n, prefixlen, warn_empty_string, nr_exclude = 0;
 433
 434        memset(pathspec, 0, sizeof(*pathspec));
 435
 436        if (flags & PATHSPEC_MAXDEPTH_VALID)
 437                pathspec->magic |= PATHSPEC_MAXDEPTH;
 438
 439        /* No arguments, no prefix -> no pathspec */
 440        if (!entry && !prefix)
 441                return;
 442
 443        if ((flags & PATHSPEC_PREFER_CWD) &&
 444            (flags & PATHSPEC_PREFER_FULL))
 445                die("BUG: PATHSPEC_PREFER_CWD and PATHSPEC_PREFER_FULL are incompatible");
 446
 447        /* No arguments with prefix -> prefix pathspec */
 448        if (!entry) {
 449                if (flags & PATHSPEC_PREFER_FULL)
 450                        return;
 451
 452                if (!(flags & PATHSPEC_PREFER_CWD))
 453                        die("BUG: PATHSPEC_PREFER_CWD requires arguments");
 454
 455                pathspec->items = item = xcalloc(1, sizeof(*item));
 456                item->match = xstrdup(prefix);
 457                item->original = xstrdup(prefix);
 458                item->nowildcard_len = item->len = strlen(prefix);
 459                item->prefix = item->len;
 460                pathspec->nr = 1;
 461                return;
 462        }
 463
 464        n = 0;
 465        warn_empty_string = 1;
 466        while (argv[n]) {
 467                if (*argv[n] == '\0' && warn_empty_string) {
 468                        warning(_("empty strings as pathspecs will be made invalid in upcoming releases. "
 469                                  "please use . instead if you meant to match all paths"));
 470                        warn_empty_string = 0;
 471                }
 472                n++;
 473        }
 474
 475        pathspec->nr = n;
 476        ALLOC_ARRAY(pathspec->items, n);
 477        item = pathspec->items;
 478        prefixlen = prefix ? strlen(prefix) : 0;
 479
 480        for (i = 0; i < n; i++) {
 481                entry = argv[i];
 482
 483                item[i].magic = prefix_pathspec(item + i, flags,
 484                                                prefix, prefixlen, entry);
 485
 486                if (item[i].magic & PATHSPEC_EXCLUDE)
 487                        nr_exclude++;
 488                if (item[i].magic & magic_mask)
 489                        unsupported_magic(entry, item[i].magic & magic_mask);
 490
 491                if ((flags & PATHSPEC_SYMLINK_LEADING_PATH) &&
 492                    has_symlink_leading_path(item[i].match, item[i].len)) {
 493                        die(_("pathspec '%s' is beyond a symbolic link"), entry);
 494                }
 495
 496                if (item[i].nowildcard_len < item[i].len)
 497                        pathspec->has_wildcard = 1;
 498                pathspec->magic |= item[i].magic;
 499        }
 500
 501        if (nr_exclude == n)
 502                die(_("There is nothing to exclude from by :(exclude) patterns.\n"
 503                      "Perhaps you forgot to add either ':/' or '.' ?"));
 504
 505
 506        if (pathspec->magic & PATHSPEC_MAXDEPTH) {
 507                if (flags & PATHSPEC_KEEP_ORDER)
 508                        die("BUG: PATHSPEC_MAXDEPTH_VALID and PATHSPEC_KEEP_ORDER are incompatible");
 509                QSORT(pathspec->items, pathspec->nr, pathspec_item_cmp);
 510        }
 511}
 512
 513void copy_pathspec(struct pathspec *dst, const struct pathspec *src)
 514{
 515        int i;
 516
 517        *dst = *src;
 518        ALLOC_ARRAY(dst->items, dst->nr);
 519        COPY_ARRAY(dst->items, src->items, dst->nr);
 520
 521        for (i = 0; i < dst->nr; i++) {
 522                dst->items[i].match = xstrdup(src->items[i].match);
 523                dst->items[i].original = xstrdup(src->items[i].original);
 524        }
 525}
 526
 527void clear_pathspec(struct pathspec *pathspec)
 528{
 529        int i;
 530
 531        for (i = 0; i < pathspec->nr; i++) {
 532                free(pathspec->items[i].match);
 533                free(pathspec->items[i].original);
 534        }
 535        free(pathspec->items);
 536        pathspec->items = NULL;
 537        pathspec->nr = 0;
 538}