pathspec.con commit pathspec: create parse_short_magic function (b4bebdc)
   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 short magic
 161 *
 162 * saves all magic in 'magic'
 163 * returns the position in 'elem' after all magic has been parsed
 164 */
 165static const char *parse_short_magic(unsigned *magic, const char *elem)
 166{
 167        const char *pos;
 168
 169        for (pos = elem + 1; *pos && *pos != ':'; pos++) {
 170                char ch = *pos;
 171                int i;
 172
 173                if (!is_pathspec_magic(ch))
 174                        break;
 175
 176                for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
 177                        if (pathspec_magic[i].mnemonic == ch) {
 178                                *magic |= pathspec_magic[i].bit;
 179                                break;
 180                        }
 181                }
 182
 183                if (ARRAY_SIZE(pathspec_magic) <= i)
 184                        die(_("Unimplemented pathspec magic '%c' in '%s'"),
 185                            ch, elem);
 186        }
 187
 188        if (*pos == ':')
 189                pos++;
 190
 191        return pos;
 192}
 193
 194/*
 195 * Take an element of a pathspec and check for magic signatures.
 196 * Append the result to the prefix. Return the magic bitmap.
 197 *
 198 * For now, we only parse the syntax and throw out anything other than
 199 * "top" magic.
 200 *
 201 * NEEDSWORK: This needs to be rewritten when we start migrating
 202 * get_pathspec() users to use the "struct pathspec" interface.  For
 203 * example, a pathspec element may be marked as case-insensitive, but
 204 * the prefix part must always match literally, and a single stupid
 205 * string cannot express such a case.
 206 */
 207static unsigned prefix_pathspec(struct pathspec_item *item, unsigned flags,
 208                                const char *prefix, int prefixlen,
 209                                const char *elt)
 210{
 211        unsigned magic = 0, element_magic = 0;
 212        const char *copyfrom = elt;
 213        char *match;
 214        int i, pathspec_prefix = -1;
 215
 216        if (elt[0] != ':' || get_literal_global() ||
 217            (flags & PATHSPEC_LITERAL_PATH)) {
 218                ; /* nothing to do */
 219        } else if (elt[1] == '(') {
 220                /* longhand */
 221                const char *nextat;
 222                for (copyfrom = elt + 2;
 223                     *copyfrom && *copyfrom != ')';
 224                     copyfrom = nextat) {
 225                        size_t len = strcspn(copyfrom, ",)");
 226                        if (copyfrom[len] == ',')
 227                                nextat = copyfrom + len + 1;
 228                        else
 229                                /* handle ')' and '\0' */
 230                                nextat = copyfrom + len;
 231                        if (!len)
 232                                continue;
 233                        for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
 234                                if (strlen(pathspec_magic[i].name) == len &&
 235                                    !strncmp(pathspec_magic[i].name, copyfrom, len)) {
 236                                        element_magic |= pathspec_magic[i].bit;
 237                                        break;
 238                                }
 239                                if (starts_with(copyfrom, "prefix:")) {
 240                                        char *endptr;
 241                                        pathspec_prefix = strtol(copyfrom + 7,
 242                                                                 &endptr, 10);
 243                                        if (endptr - copyfrom != len)
 244                                                die(_("invalid parameter for pathspec magic 'prefix'"));
 245                                        /* "i" would be wrong, but it does not matter */
 246                                        break;
 247                                }
 248                        }
 249                        if (ARRAY_SIZE(pathspec_magic) <= i)
 250                                die(_("Invalid pathspec magic '%.*s' in '%s'"),
 251                                    (int) len, copyfrom, elt);
 252                }
 253                if (*copyfrom != ')')
 254                        die(_("Missing ')' at the end of pathspec magic in '%s'"), elt);
 255                copyfrom++;
 256        } else {
 257                /* shorthand */
 258                copyfrom = parse_short_magic(&element_magic, elt);
 259        }
 260
 261        magic |= element_magic;
 262
 263        /* PATHSPEC_LITERAL_PATH ignores magic */
 264        if (flags & PATHSPEC_LITERAL_PATH)
 265                magic = PATHSPEC_LITERAL;
 266        else
 267                magic |= get_global_magic(element_magic);
 268
 269        if (pathspec_prefix >= 0 &&
 270            (prefixlen || (prefix && *prefix)))
 271                die("BUG: 'prefix' magic is supposed to be used at worktree's root");
 272
 273        if ((magic & PATHSPEC_LITERAL) && (magic & PATHSPEC_GLOB))
 274                die(_("%s: 'literal' and 'glob' are incompatible"), elt);
 275
 276        if (pathspec_prefix >= 0) {
 277                match = xstrdup(copyfrom);
 278                prefixlen = pathspec_prefix;
 279        } else if (magic & PATHSPEC_FROMTOP) {
 280                match = xstrdup(copyfrom);
 281                prefixlen = 0;
 282        } else {
 283                match = prefix_path_gently(prefix, prefixlen, &prefixlen, copyfrom);
 284                if (!match)
 285                        die(_("%s: '%s' is outside repository"), elt, copyfrom);
 286        }
 287        item->match = match;
 288        /*
 289         * Prefix the pathspec (keep all magic) and assign to
 290         * original. Useful for passing to another command.
 291         */
 292        if ((flags & PATHSPEC_PREFIX_ORIGIN) &&
 293            prefixlen && !get_literal_global()) {
 294                struct strbuf sb = STRBUF_INIT;
 295
 296                /* Preserve the actual prefix length of each pattern */
 297                prefix_magic(&sb, prefixlen, element_magic);
 298
 299                strbuf_addstr(&sb, match);
 300                item->original = strbuf_detach(&sb, NULL);
 301        } else {
 302                item->original = xstrdup(elt);
 303        }
 304        item->len = strlen(item->match);
 305        item->prefix = prefixlen;
 306
 307        if ((flags & PATHSPEC_STRIP_SUBMODULE_SLASH_CHEAP) &&
 308            (item->len >= 1 && item->match[item->len - 1] == '/') &&
 309            (i = cache_name_pos(item->match, item->len - 1)) >= 0 &&
 310            S_ISGITLINK(active_cache[i]->ce_mode)) {
 311                item->len--;
 312                match[item->len] = '\0';
 313        }
 314
 315        if (flags & PATHSPEC_STRIP_SUBMODULE_SLASH_EXPENSIVE)
 316                for (i = 0; i < active_nr; i++) {
 317                        struct cache_entry *ce = active_cache[i];
 318                        int ce_len = ce_namelen(ce);
 319
 320                        if (!S_ISGITLINK(ce->ce_mode))
 321                                continue;
 322
 323                        if (item->len <= ce_len || match[ce_len] != '/' ||
 324                            memcmp(ce->name, match, ce_len))
 325                                continue;
 326                        if (item->len == ce_len + 1) {
 327                                /* strip trailing slash */
 328                                item->len--;
 329                                match[item->len] = '\0';
 330                        } else
 331                                die (_("Pathspec '%s' is in submodule '%.*s'"),
 332                                     elt, ce_len, ce->name);
 333                }
 334
 335        if (magic & PATHSPEC_LITERAL)
 336                item->nowildcard_len = item->len;
 337        else {
 338                item->nowildcard_len = simple_length(item->match);
 339                if (item->nowildcard_len < prefixlen)
 340                        item->nowildcard_len = prefixlen;
 341        }
 342        item->flags = 0;
 343        if (magic & PATHSPEC_GLOB) {
 344                /*
 345                 * FIXME: should we enable ONESTAR in _GLOB for
 346                 * pattern "* * / * . c"?
 347                 */
 348        } else {
 349                if (item->nowildcard_len < item->len &&
 350                    item->match[item->nowildcard_len] == '*' &&
 351                    no_wildcard(item->match + item->nowildcard_len + 1))
 352                        item->flags |= PATHSPEC_ONESTAR;
 353        }
 354
 355        /* sanity checks, pathspec matchers assume these are sane */
 356        assert(item->nowildcard_len <= item->len &&
 357               item->prefix         <= item->len);
 358        return magic;
 359}
 360
 361static int pathspec_item_cmp(const void *a_, const void *b_)
 362{
 363        struct pathspec_item *a, *b;
 364
 365        a = (struct pathspec_item *)a_;
 366        b = (struct pathspec_item *)b_;
 367        return strcmp(a->match, b->match);
 368}
 369
 370static void NORETURN unsupported_magic(const char *pattern,
 371                                       unsigned magic)
 372{
 373        struct strbuf sb = STRBUF_INIT;
 374        int i;
 375        for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
 376                const struct pathspec_magic *m = pathspec_magic + i;
 377                if (!(magic & m->bit))
 378                        continue;
 379                if (sb.len)
 380                        strbuf_addstr(&sb, ", ");
 381
 382                if (m->mnemonic)
 383                        strbuf_addf(&sb, _("'%s' (mnemonic: '%c')"),
 384                                    m->name, m->mnemonic);
 385                else
 386                        strbuf_addf(&sb, "'%s'", m->name);
 387        }
 388        /*
 389         * We may want to substitute "this command" with a command
 390         * name. E.g. when add--interactive dies when running
 391         * "checkout -p"
 392         */
 393        die(_("%s: pathspec magic not supported by this command: %s"),
 394            pattern, sb.buf);
 395}
 396
 397/*
 398 * Given command line arguments and a prefix, convert the input to
 399 * pathspec. die() if any magic in magic_mask is used.
 400 */
 401void parse_pathspec(struct pathspec *pathspec,
 402                    unsigned magic_mask, unsigned flags,
 403                    const char *prefix, const char **argv)
 404{
 405        struct pathspec_item *item;
 406        const char *entry = argv ? *argv : NULL;
 407        int i, n, prefixlen, warn_empty_string, nr_exclude = 0;
 408
 409        memset(pathspec, 0, sizeof(*pathspec));
 410
 411        if (flags & PATHSPEC_MAXDEPTH_VALID)
 412                pathspec->magic |= PATHSPEC_MAXDEPTH;
 413
 414        /* No arguments, no prefix -> no pathspec */
 415        if (!entry && !prefix)
 416                return;
 417
 418        if ((flags & PATHSPEC_PREFER_CWD) &&
 419            (flags & PATHSPEC_PREFER_FULL))
 420                die("BUG: PATHSPEC_PREFER_CWD and PATHSPEC_PREFER_FULL are incompatible");
 421
 422        /* No arguments with prefix -> prefix pathspec */
 423        if (!entry) {
 424                if (flags & PATHSPEC_PREFER_FULL)
 425                        return;
 426
 427                if (!(flags & PATHSPEC_PREFER_CWD))
 428                        die("BUG: PATHSPEC_PREFER_CWD requires arguments");
 429
 430                pathspec->items = item = xcalloc(1, sizeof(*item));
 431                item->match = xstrdup(prefix);
 432                item->original = xstrdup(prefix);
 433                item->nowildcard_len = item->len = strlen(prefix);
 434                item->prefix = item->len;
 435                pathspec->nr = 1;
 436                return;
 437        }
 438
 439        n = 0;
 440        warn_empty_string = 1;
 441        while (argv[n]) {
 442                if (*argv[n] == '\0' && warn_empty_string) {
 443                        warning(_("empty strings as pathspecs will be made invalid in upcoming releases. "
 444                                  "please use . instead if you meant to match all paths"));
 445                        warn_empty_string = 0;
 446                }
 447                n++;
 448        }
 449
 450        pathspec->nr = n;
 451        ALLOC_ARRAY(pathspec->items, n);
 452        item = pathspec->items;
 453        prefixlen = prefix ? strlen(prefix) : 0;
 454
 455        for (i = 0; i < n; i++) {
 456                entry = argv[i];
 457
 458                item[i].magic = prefix_pathspec(item + i, flags,
 459                                                prefix, prefixlen, entry);
 460
 461                if (item[i].magic & PATHSPEC_EXCLUDE)
 462                        nr_exclude++;
 463                if (item[i].magic & magic_mask)
 464                        unsupported_magic(entry, item[i].magic & magic_mask);
 465
 466                if ((flags & PATHSPEC_SYMLINK_LEADING_PATH) &&
 467                    has_symlink_leading_path(item[i].match, item[i].len)) {
 468                        die(_("pathspec '%s' is beyond a symbolic link"), entry);
 469                }
 470
 471                if (item[i].nowildcard_len < item[i].len)
 472                        pathspec->has_wildcard = 1;
 473                pathspec->magic |= item[i].magic;
 474        }
 475
 476        if (nr_exclude == n)
 477                die(_("There is nothing to exclude from by :(exclude) patterns.\n"
 478                      "Perhaps you forgot to add either ':/' or '.' ?"));
 479
 480
 481        if (pathspec->magic & PATHSPEC_MAXDEPTH) {
 482                if (flags & PATHSPEC_KEEP_ORDER)
 483                        die("BUG: PATHSPEC_MAXDEPTH_VALID and PATHSPEC_KEEP_ORDER are incompatible");
 484                QSORT(pathspec->items, pathspec->nr, pathspec_item_cmp);
 485        }
 486}
 487
 488void copy_pathspec(struct pathspec *dst, const struct pathspec *src)
 489{
 490        int i;
 491
 492        *dst = *src;
 493        ALLOC_ARRAY(dst->items, dst->nr);
 494        COPY_ARRAY(dst->items, src->items, dst->nr);
 495
 496        for (i = 0; i < dst->nr; i++) {
 497                dst->items[i].match = xstrdup(src->items[i].match);
 498                dst->items[i].original = xstrdup(src->items[i].original);
 499        }
 500}
 501
 502void clear_pathspec(struct pathspec *pathspec)
 503{
 504        int i;
 505
 506        for (i = 0; i < pathspec->nr; i++) {
 507                free(pathspec->items[i].match);
 508                free(pathspec->items[i].original);
 509        }
 510        free(pathspec->items);
 511        pathspec->items = NULL;
 512        pathspec->nr = 0;
 513}