af7f2d01d55333fa4e7ea89203f638ccbebb1e52
   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
  90/*
  91 * Take an element of a pathspec and check for magic signatures.
  92 * Append the result to the prefix. Return the magic bitmap.
  93 *
  94 * For now, we only parse the syntax and throw out anything other than
  95 * "top" magic.
  96 *
  97 * NEEDSWORK: This needs to be rewritten when we start migrating
  98 * get_pathspec() users to use the "struct pathspec" interface.  For
  99 * example, a pathspec element may be marked as case-insensitive, but
 100 * the prefix part must always match literally, and a single stupid
 101 * string cannot express such a case.
 102 */
 103static unsigned prefix_pathspec(struct pathspec_item *item, unsigned flags,
 104                                const char *prefix, int prefixlen,
 105                                const char *elt)
 106{
 107        static int literal_global = -1;
 108        static int glob_global = -1;
 109        static int noglob_global = -1;
 110        static int icase_global = -1;
 111        unsigned magic = 0, element_magic = 0, global_magic = 0;
 112        const char *copyfrom = elt;
 113        char *match;
 114        int i, pathspec_prefix = -1;
 115
 116        if (literal_global < 0)
 117                literal_global = git_env_bool(GIT_LITERAL_PATHSPECS_ENVIRONMENT, 0);
 118        if (literal_global)
 119                global_magic |= PATHSPEC_LITERAL;
 120
 121        if (glob_global < 0)
 122                glob_global = git_env_bool(GIT_GLOB_PATHSPECS_ENVIRONMENT, 0);
 123        if (glob_global)
 124                global_magic |= PATHSPEC_GLOB;
 125
 126        if (noglob_global < 0)
 127                noglob_global = git_env_bool(GIT_NOGLOB_PATHSPECS_ENVIRONMENT, 0);
 128
 129        if (glob_global && noglob_global)
 130                die(_("global 'glob' and 'noglob' pathspec settings are incompatible"));
 131
 132
 133        if (icase_global < 0)
 134                icase_global = git_env_bool(GIT_ICASE_PATHSPECS_ENVIRONMENT, 0);
 135        if (icase_global)
 136                global_magic |= PATHSPEC_ICASE;
 137
 138        if ((global_magic & PATHSPEC_LITERAL) &&
 139            (global_magic & ~PATHSPEC_LITERAL))
 140                die(_("global 'literal' pathspec setting is incompatible "
 141                      "with all other global pathspec settings"));
 142
 143        if (flags & PATHSPEC_LITERAL_PATH)
 144                global_magic = 0;
 145
 146        if (elt[0] != ':' || literal_global ||
 147            (flags & PATHSPEC_LITERAL_PATH)) {
 148                ; /* nothing to do */
 149        } else if (elt[1] == '(') {
 150                /* longhand */
 151                const char *nextat;
 152                for (copyfrom = elt + 2;
 153                     *copyfrom && *copyfrom != ')';
 154                     copyfrom = nextat) {
 155                        size_t len = strcspn(copyfrom, ",)");
 156                        if (copyfrom[len] == ',')
 157                                nextat = copyfrom + len + 1;
 158                        else
 159                                /* handle ')' and '\0' */
 160                                nextat = copyfrom + len;
 161                        if (!len)
 162                                continue;
 163                        for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
 164                                if (strlen(pathspec_magic[i].name) == len &&
 165                                    !strncmp(pathspec_magic[i].name, copyfrom, len)) {
 166                                        element_magic |= pathspec_magic[i].bit;
 167                                        break;
 168                                }
 169                                if (starts_with(copyfrom, "prefix:")) {
 170                                        char *endptr;
 171                                        pathspec_prefix = strtol(copyfrom + 7,
 172                                                                 &endptr, 10);
 173                                        if (endptr - copyfrom != len)
 174                                                die(_("invalid parameter for pathspec magic 'prefix'"));
 175                                        /* "i" would be wrong, but it does not matter */
 176                                        break;
 177                                }
 178                        }
 179                        if (ARRAY_SIZE(pathspec_magic) <= i)
 180                                die(_("Invalid pathspec magic '%.*s' in '%s'"),
 181                                    (int) len, copyfrom, elt);
 182                }
 183                if (*copyfrom != ')')
 184                        die(_("Missing ')' at the end of pathspec magic in '%s'"), elt);
 185                copyfrom++;
 186        } else {
 187                /* shorthand */
 188                for (copyfrom = elt + 1;
 189                     *copyfrom && *copyfrom != ':';
 190                     copyfrom++) {
 191                        char ch = *copyfrom;
 192
 193                        if (!is_pathspec_magic(ch))
 194                                break;
 195                        for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
 196                                if (pathspec_magic[i].mnemonic == ch) {
 197                                        element_magic |= pathspec_magic[i].bit;
 198                                        break;
 199                                }
 200                        if (ARRAY_SIZE(pathspec_magic) <= i)
 201                                die(_("Unimplemented pathspec magic '%c' in '%s'"),
 202                                    ch, elt);
 203                }
 204                if (*copyfrom == ':')
 205                        copyfrom++;
 206        }
 207
 208        magic |= element_magic;
 209
 210        /* --noglob-pathspec adds :(literal) _unless_ :(glob) is specified */
 211        if (noglob_global && !(magic & PATHSPEC_GLOB))
 212                global_magic |= PATHSPEC_LITERAL;
 213
 214        /* --glob-pathspec is overridden by :(literal) */
 215        if ((global_magic & PATHSPEC_GLOB) && (magic & PATHSPEC_LITERAL))
 216                global_magic &= ~PATHSPEC_GLOB;
 217
 218        magic |= global_magic;
 219
 220        if (pathspec_prefix >= 0 &&
 221            (prefixlen || (prefix && *prefix)))
 222                die("BUG: 'prefix' magic is supposed to be used at worktree's root");
 223
 224        if ((magic & PATHSPEC_LITERAL) && (magic & PATHSPEC_GLOB))
 225                die(_("%s: 'literal' and 'glob' are incompatible"), elt);
 226
 227        if (pathspec_prefix >= 0) {
 228                match = xstrdup(copyfrom);
 229                prefixlen = pathspec_prefix;
 230        } else if (magic & PATHSPEC_FROMTOP) {
 231                match = xstrdup(copyfrom);
 232                prefixlen = 0;
 233        } else {
 234                match = prefix_path_gently(prefix, prefixlen, &prefixlen, copyfrom);
 235                if (!match)
 236                        die(_("%s: '%s' is outside repository"), elt, copyfrom);
 237        }
 238        item->match = match;
 239        /*
 240         * Prefix the pathspec (keep all magic) and assign to
 241         * original. Useful for passing to another command.
 242         */
 243        if ((flags & PATHSPEC_PREFIX_ORIGIN) &&
 244            prefixlen && !literal_global) {
 245                struct strbuf sb = STRBUF_INIT;
 246
 247                /* Preserve the actual prefix length of each pattern */
 248                prefix_magic(&sb, prefixlen, element_magic);
 249
 250                strbuf_addstr(&sb, match);
 251                item->original = strbuf_detach(&sb, NULL);
 252        } else {
 253                item->original = xstrdup(elt);
 254        }
 255        item->len = strlen(item->match);
 256        item->prefix = prefixlen;
 257
 258        if ((flags & PATHSPEC_STRIP_SUBMODULE_SLASH_CHEAP) &&
 259            (item->len >= 1 && item->match[item->len - 1] == '/') &&
 260            (i = cache_name_pos(item->match, item->len - 1)) >= 0 &&
 261            S_ISGITLINK(active_cache[i]->ce_mode)) {
 262                item->len--;
 263                match[item->len] = '\0';
 264        }
 265
 266        if (flags & PATHSPEC_STRIP_SUBMODULE_SLASH_EXPENSIVE)
 267                for (i = 0; i < active_nr; i++) {
 268                        struct cache_entry *ce = active_cache[i];
 269                        int ce_len = ce_namelen(ce);
 270
 271                        if (!S_ISGITLINK(ce->ce_mode))
 272                                continue;
 273
 274                        if (item->len <= ce_len || match[ce_len] != '/' ||
 275                            memcmp(ce->name, match, ce_len))
 276                                continue;
 277                        if (item->len == ce_len + 1) {
 278                                /* strip trailing slash */
 279                                item->len--;
 280                                match[item->len] = '\0';
 281                        } else
 282                                die (_("Pathspec '%s' is in submodule '%.*s'"),
 283                                     elt, ce_len, ce->name);
 284                }
 285
 286        if (magic & PATHSPEC_LITERAL)
 287                item->nowildcard_len = item->len;
 288        else {
 289                item->nowildcard_len = simple_length(item->match);
 290                if (item->nowildcard_len < prefixlen)
 291                        item->nowildcard_len = prefixlen;
 292        }
 293        item->flags = 0;
 294        if (magic & PATHSPEC_GLOB) {
 295                /*
 296                 * FIXME: should we enable ONESTAR in _GLOB for
 297                 * pattern "* * / * . c"?
 298                 */
 299        } else {
 300                if (item->nowildcard_len < item->len &&
 301                    item->match[item->nowildcard_len] == '*' &&
 302                    no_wildcard(item->match + item->nowildcard_len + 1))
 303                        item->flags |= PATHSPEC_ONESTAR;
 304        }
 305
 306        /* sanity checks, pathspec matchers assume these are sane */
 307        assert(item->nowildcard_len <= item->len &&
 308               item->prefix         <= item->len);
 309        return magic;
 310}
 311
 312static int pathspec_item_cmp(const void *a_, const void *b_)
 313{
 314        struct pathspec_item *a, *b;
 315
 316        a = (struct pathspec_item *)a_;
 317        b = (struct pathspec_item *)b_;
 318        return strcmp(a->match, b->match);
 319}
 320
 321static void NORETURN unsupported_magic(const char *pattern,
 322                                       unsigned magic)
 323{
 324        struct strbuf sb = STRBUF_INIT;
 325        int i;
 326        for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
 327                const struct pathspec_magic *m = pathspec_magic + i;
 328                if (!(magic & m->bit))
 329                        continue;
 330                if (sb.len)
 331                        strbuf_addstr(&sb, ", ");
 332
 333                if (m->mnemonic)
 334                        strbuf_addf(&sb, _("'%s' (mnemonic: '%c')"),
 335                                    m->name, m->mnemonic);
 336                else
 337                        strbuf_addf(&sb, "'%s'", m->name);
 338        }
 339        /*
 340         * We may want to substitute "this command" with a command
 341         * name. E.g. when add--interactive dies when running
 342         * "checkout -p"
 343         */
 344        die(_("%s: pathspec magic not supported by this command: %s"),
 345            pattern, sb.buf);
 346}
 347
 348/*
 349 * Given command line arguments and a prefix, convert the input to
 350 * pathspec. die() if any magic in magic_mask is used.
 351 */
 352void parse_pathspec(struct pathspec *pathspec,
 353                    unsigned magic_mask, unsigned flags,
 354                    const char *prefix, const char **argv)
 355{
 356        struct pathspec_item *item;
 357        const char *entry = argv ? *argv : NULL;
 358        int i, n, prefixlen, warn_empty_string, nr_exclude = 0;
 359
 360        memset(pathspec, 0, sizeof(*pathspec));
 361
 362        if (flags & PATHSPEC_MAXDEPTH_VALID)
 363                pathspec->magic |= PATHSPEC_MAXDEPTH;
 364
 365        /* No arguments, no prefix -> no pathspec */
 366        if (!entry && !prefix)
 367                return;
 368
 369        if ((flags & PATHSPEC_PREFER_CWD) &&
 370            (flags & PATHSPEC_PREFER_FULL))
 371                die("BUG: PATHSPEC_PREFER_CWD and PATHSPEC_PREFER_FULL are incompatible");
 372
 373        /* No arguments with prefix -> prefix pathspec */
 374        if (!entry) {
 375                if (flags & PATHSPEC_PREFER_FULL)
 376                        return;
 377
 378                if (!(flags & PATHSPEC_PREFER_CWD))
 379                        die("BUG: PATHSPEC_PREFER_CWD requires arguments");
 380
 381                pathspec->items = item = xcalloc(1, sizeof(*item));
 382                item->match = xstrdup(prefix);
 383                item->original = xstrdup(prefix);
 384                item->nowildcard_len = item->len = strlen(prefix);
 385                item->prefix = item->len;
 386                pathspec->nr = 1;
 387                return;
 388        }
 389
 390        n = 0;
 391        warn_empty_string = 1;
 392        while (argv[n]) {
 393                if (*argv[n] == '\0' && warn_empty_string) {
 394                        warning(_("empty strings as pathspecs will be made invalid in upcoming releases. "
 395                                  "please use . instead if you meant to match all paths"));
 396                        warn_empty_string = 0;
 397                }
 398                n++;
 399        }
 400
 401        pathspec->nr = n;
 402        ALLOC_ARRAY(pathspec->items, n);
 403        item = pathspec->items;
 404        prefixlen = prefix ? strlen(prefix) : 0;
 405
 406        for (i = 0; i < n; i++) {
 407                entry = argv[i];
 408
 409                item[i].magic = prefix_pathspec(item + i, flags,
 410                                                prefix, prefixlen, entry);
 411                if ((flags & PATHSPEC_LITERAL_PATH) &&
 412                    !(magic_mask & PATHSPEC_LITERAL))
 413                        item[i].magic |= PATHSPEC_LITERAL;
 414                if (item[i].magic & PATHSPEC_EXCLUDE)
 415                        nr_exclude++;
 416                if (item[i].magic & magic_mask)
 417                        unsupported_magic(entry, item[i].magic & magic_mask);
 418
 419                if ((flags & PATHSPEC_SYMLINK_LEADING_PATH) &&
 420                    has_symlink_leading_path(item[i].match, item[i].len)) {
 421                        die(_("pathspec '%s' is beyond a symbolic link"), entry);
 422                }
 423
 424                if (item[i].nowildcard_len < item[i].len)
 425                        pathspec->has_wildcard = 1;
 426                pathspec->magic |= item[i].magic;
 427        }
 428
 429        if (nr_exclude == n)
 430                die(_("There is nothing to exclude from by :(exclude) patterns.\n"
 431                      "Perhaps you forgot to add either ':/' or '.' ?"));
 432
 433
 434        if (pathspec->magic & PATHSPEC_MAXDEPTH) {
 435                if (flags & PATHSPEC_KEEP_ORDER)
 436                        die("BUG: PATHSPEC_MAXDEPTH_VALID and PATHSPEC_KEEP_ORDER are incompatible");
 437                QSORT(pathspec->items, pathspec->nr, pathspec_item_cmp);
 438        }
 439}
 440
 441void copy_pathspec(struct pathspec *dst, const struct pathspec *src)
 442{
 443        int i;
 444
 445        *dst = *src;
 446        ALLOC_ARRAY(dst->items, dst->nr);
 447        COPY_ARRAY(dst->items, src->items, dst->nr);
 448
 449        for (i = 0; i < dst->nr; i++) {
 450                dst->items[i].match = xstrdup(src->items[i].match);
 451                dst->items[i].original = xstrdup(src->items[i].original);
 452        }
 453}
 454
 455void clear_pathspec(struct pathspec *pathspec)
 456{
 457        int i;
 458
 459        for (i = 0; i < pathspec->nr; i++) {
 460                free(pathspec->items[i].match);
 461                free(pathspec->items[i].original);
 462        }
 463        free(pathspec->items);
 464        pathspec->items = NULL;
 465        pathspec->nr = 0;
 466}