71e5eaf1b1eb1cfa7ee71ed1c3511889e6405b65
   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                struct cache_entry *ce = active_cache[i];
  36                match_pathspec_depth(pathspec, ce->name, ce_namelen(ce), 0, 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_NOGLOB, '!', "noglob" },
  61 *      { PATHSPEC_ICASE, '\0', "icase" },
  62 *      { PATHSPEC_RECURSIVE, '*', "recursive" },
  63 *      { PATHSPEC_REGEXP, '\0', "regexp" },
  64 *
  65 */
  66
  67static struct pathspec_magic {
  68        unsigned bit;
  69        char mnemonic; /* this cannot be ':'! */
  70        const char *name;
  71} pathspec_magic[] = {
  72        { PATHSPEC_FROMTOP, '/', "top" },
  73};
  74
  75/*
  76 * Take an element of a pathspec and check for magic signatures.
  77 * Append the result to the prefix. Return the magic bitmap.
  78 *
  79 * For now, we only parse the syntax and throw out anything other than
  80 * "top" magic.
  81 *
  82 * NEEDSWORK: This needs to be rewritten when we start migrating
  83 * get_pathspec() users to use the "struct pathspec" interface.  For
  84 * example, a pathspec element may be marked as case-insensitive, but
  85 * the prefix part must always match literally, and a single stupid
  86 * string cannot express such a case.
  87 */
  88static unsigned prefix_pathspec(struct pathspec_item *item,
  89                                unsigned *p_short_magic,
  90                                const char **raw, unsigned flags,
  91                                const char *prefix, int prefixlen,
  92                                const char *elt)
  93{
  94        unsigned magic = 0, short_magic = 0;
  95        const char *copyfrom = elt;
  96        char *match;
  97        int i;
  98
  99        if (elt[0] != ':') {
 100                ; /* nothing to do */
 101        } else if (elt[1] == '(') {
 102                /* longhand */
 103                const char *nextat;
 104                for (copyfrom = elt + 2;
 105                     *copyfrom && *copyfrom != ')';
 106                     copyfrom = nextat) {
 107                        size_t len = strcspn(copyfrom, ",)");
 108                        if (copyfrom[len] == ',')
 109                                nextat = copyfrom + len + 1;
 110                        else
 111                                /* handle ')' and '\0' */
 112                                nextat = copyfrom + len;
 113                        if (!len)
 114                                continue;
 115                        for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
 116                                if (strlen(pathspec_magic[i].name) == len &&
 117                                    !strncmp(pathspec_magic[i].name, copyfrom, len)) {
 118                                        magic |= pathspec_magic[i].bit;
 119                                        break;
 120                                }
 121                        if (ARRAY_SIZE(pathspec_magic) <= i)
 122                                die(_("Invalid pathspec magic '%.*s' in '%s'"),
 123                                    (int) len, copyfrom, elt);
 124                }
 125                if (*copyfrom != ')')
 126                        die(_("Missing ')' at the end of pathspec magic in '%s'"), elt);
 127                copyfrom++;
 128        } else {
 129                /* shorthand */
 130                for (copyfrom = elt + 1;
 131                     *copyfrom && *copyfrom != ':';
 132                     copyfrom++) {
 133                        char ch = *copyfrom;
 134
 135                        if (!is_pathspec_magic(ch))
 136                                break;
 137                        for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
 138                                if (pathspec_magic[i].mnemonic == ch) {
 139                                        short_magic |= pathspec_magic[i].bit;
 140                                        break;
 141                                }
 142                        if (ARRAY_SIZE(pathspec_magic) <= i)
 143                                die(_("Unimplemented pathspec magic '%c' in '%s'"),
 144                                    ch, elt);
 145                }
 146                if (*copyfrom == ':')
 147                        copyfrom++;
 148        }
 149
 150        magic |= short_magic;
 151        *p_short_magic = short_magic;
 152
 153        if (magic & PATHSPEC_FROMTOP) {
 154                match = xstrdup(copyfrom);
 155                prefixlen = 0;
 156        } else {
 157                match = prefix_path_gently(prefix, prefixlen, &prefixlen, copyfrom);
 158                if (!match)
 159                        die(_("%s: '%s' is outside repository"), elt, copyfrom);
 160        }
 161        *raw = item->match = match;
 162        /*
 163         * Prefix the pathspec (keep all magic) and assign to
 164         * original. Useful for passing to another command.
 165         */
 166        if (flags & PATHSPEC_PREFIX_ORIGIN) {
 167                struct strbuf sb = STRBUF_INIT;
 168                strbuf_add(&sb, elt, copyfrom - elt);
 169                strbuf_addstr(&sb, match);
 170                item->original = strbuf_detach(&sb, NULL);
 171        } else
 172                item->original = elt;
 173        item->len = strlen(item->match);
 174        item->prefix = prefixlen;
 175
 176        if ((flags & PATHSPEC_STRIP_SUBMODULE_SLASH_CHEAP) &&
 177            (item->len >= 1 && item->match[item->len - 1] == '/') &&
 178            (i = cache_name_pos(item->match, item->len - 1)) >= 0 &&
 179            S_ISGITLINK(active_cache[i]->ce_mode)) {
 180                item->len--;
 181                match[item->len] = '\0';
 182        }
 183
 184        if (flags & PATHSPEC_STRIP_SUBMODULE_SLASH_EXPENSIVE)
 185                for (i = 0; i < active_nr; i++) {
 186                        struct cache_entry *ce = active_cache[i];
 187                        int ce_len = ce_namelen(ce);
 188
 189                        if (!S_ISGITLINK(ce->ce_mode))
 190                                continue;
 191
 192                        if (item->len <= ce_len || match[ce_len] != '/' ||
 193                            memcmp(ce->name, match, ce_len))
 194                                continue;
 195                        if (item->len == ce_len + 1) {
 196                                /* strip trailing slash */
 197                                item->len--;
 198                                match[item->len] = '\0';
 199                        } else
 200                                die (_("Pathspec '%s' is in submodule '%.*s'"),
 201                                     elt, ce_len, ce->name);
 202                }
 203
 204        if (limit_pathspec_to_literal())
 205                item->nowildcard_len = item->len;
 206        else {
 207                item->nowildcard_len = simple_length(item->match);
 208                if (item->nowildcard_len < prefixlen)
 209                        item->nowildcard_len = prefixlen;
 210        }
 211        item->flags = 0;
 212        if (item->nowildcard_len < item->len &&
 213            item->match[item->nowildcard_len] == '*' &&
 214            no_wildcard(item->match + item->nowildcard_len + 1))
 215                item->flags |= PATHSPEC_ONESTAR;
 216
 217        /* sanity checks, pathspec matchers assume these are sane */
 218        assert(item->nowildcard_len <= item->len &&
 219               item->prefix         <= item->len);
 220        return magic;
 221}
 222
 223static int pathspec_item_cmp(const void *a_, const void *b_)
 224{
 225        struct pathspec_item *a, *b;
 226
 227        a = (struct pathspec_item *)a_;
 228        b = (struct pathspec_item *)b_;
 229        return strcmp(a->match, b->match);
 230}
 231
 232static void NORETURN unsupported_magic(const char *pattern,
 233                                       unsigned magic,
 234                                       unsigned short_magic)
 235{
 236        struct strbuf sb = STRBUF_INIT;
 237        int i, n;
 238        for (n = i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
 239                const struct pathspec_magic *m = pathspec_magic + i;
 240                if (!(magic & m->bit))
 241                        continue;
 242                if (sb.len)
 243                        strbuf_addstr(&sb, " ");
 244                if (short_magic & m->bit)
 245                        strbuf_addf(&sb, "'%c'", m->mnemonic);
 246                else
 247                        strbuf_addf(&sb, "'%s'", m->name);
 248                n++;
 249        }
 250        /*
 251         * We may want to substitute "this command" with a command
 252         * name. E.g. when add--interactive dies when running
 253         * "checkout -p"
 254         */
 255        die(_("%s: pathspec magic not supported by this command: %s"),
 256            pattern, sb.buf);
 257}
 258
 259/*
 260 * Given command line arguments and a prefix, convert the input to
 261 * pathspec. die() if any magic in magic_mask is used.
 262 */
 263void parse_pathspec(struct pathspec *pathspec,
 264                    unsigned magic_mask, unsigned flags,
 265                    const char *prefix, const char **argv)
 266{
 267        struct pathspec_item *item;
 268        const char *entry = argv ? *argv : NULL;
 269        int i, n, prefixlen;
 270
 271        memset(pathspec, 0, sizeof(*pathspec));
 272
 273        if (flags & PATHSPEC_MAXDEPTH_VALID)
 274                pathspec->magic |= PATHSPEC_MAXDEPTH;
 275
 276        /* No arguments, no prefix -> no pathspec */
 277        if (!entry && !prefix)
 278                return;
 279
 280        if ((flags & PATHSPEC_PREFER_CWD) &&
 281            (flags & PATHSPEC_PREFER_FULL))
 282                die("BUG: PATHSPEC_PREFER_CWD and PATHSPEC_PREFER_FULL are incompatible");
 283
 284        /* No arguments with prefix -> prefix pathspec */
 285        if (!entry) {
 286                static const char *raw[2];
 287
 288                if (flags & PATHSPEC_PREFER_FULL)
 289                        return;
 290
 291                if (!(flags & PATHSPEC_PREFER_CWD))
 292                        die("BUG: PATHSPEC_PREFER_CWD requires arguments");
 293
 294                pathspec->items = item = xmalloc(sizeof(*item));
 295                memset(item, 0, sizeof(*item));
 296                item->match = prefix;
 297                item->original = prefix;
 298                item->nowildcard_len = item->len = strlen(prefix);
 299                item->prefix = item->len;
 300                raw[0] = prefix;
 301                raw[1] = NULL;
 302                pathspec->nr = 1;
 303                pathspec->_raw = raw;
 304                return;
 305        }
 306
 307        n = 0;
 308        while (argv[n])
 309                n++;
 310
 311        pathspec->nr = n;
 312        pathspec->items = item = xmalloc(sizeof(*item) * n);
 313        pathspec->_raw = argv;
 314        prefixlen = prefix ? strlen(prefix) : 0;
 315
 316        for (i = 0; i < n; i++) {
 317                unsigned short_magic;
 318                entry = argv[i];
 319
 320                item[i].magic = prefix_pathspec(item + i, &short_magic,
 321                                                argv + i, flags,
 322                                                prefix, prefixlen, entry);
 323                if (item[i].magic & magic_mask)
 324                        unsupported_magic(entry,
 325                                          item[i].magic & magic_mask,
 326                                          short_magic);
 327
 328                if ((flags & PATHSPEC_SYMLINK_LEADING_PATH) &&
 329                    has_symlink_leading_path(item[i].match, item[i].len)) {
 330                        die(_("pathspec '%s' is beyond a symbolic link"), entry);
 331                }
 332
 333                if (item[i].nowildcard_len < item[i].len)
 334                        pathspec->has_wildcard = 1;
 335                pathspec->magic |= item[i].magic;
 336        }
 337
 338
 339        if (pathspec->magic & PATHSPEC_MAXDEPTH) {
 340                if (flags & PATHSPEC_KEEP_ORDER)
 341                        die("BUG: PATHSPEC_MAXDEPTH_VALID and PATHSPEC_KEEP_ORDER are incompatible");
 342                qsort(pathspec->items, pathspec->nr,
 343                      sizeof(struct pathspec_item), pathspec_item_cmp);
 344        }
 345}
 346
 347/*
 348 * N.B. get_pathspec() is deprecated in favor of the "struct pathspec"
 349 * based interface - see pathspec.c:parse_pathspec().
 350 *
 351 * Arguments:
 352 *  - prefix - a path relative to the root of the working tree
 353 *  - pathspec - a list of paths underneath the prefix path
 354 *
 355 * Iterates over pathspec, prepending each path with prefix,
 356 * and return the resulting list.
 357 *
 358 * If pathspec is empty, return a singleton list containing prefix.
 359 *
 360 * If pathspec and prefix are both empty, return an empty list.
 361 *
 362 * This is typically used by built-in commands such as add.c, in order
 363 * to normalize argv arguments provided to the built-in into a list of
 364 * paths to process, all relative to the root of the working tree.
 365 */
 366const char **get_pathspec(const char *prefix, const char **pathspec)
 367{
 368        struct pathspec ps;
 369        parse_pathspec(&ps,
 370                       PATHSPEC_ALL_MAGIC & ~PATHSPEC_FROMTOP,
 371                       PATHSPEC_PREFER_CWD,
 372                       prefix, pathspec);
 373        return ps._raw;
 374}
 375
 376void copy_pathspec(struct pathspec *dst, const struct pathspec *src)
 377{
 378        *dst = *src;
 379        dst->items = xmalloc(sizeof(struct pathspec_item) * dst->nr);
 380        memcpy(dst->items, src->items,
 381               sizeof(struct pathspec_item) * dst->nr);
 382}
 383
 384void free_pathspec(struct pathspec *pathspec)
 385{
 386        free(pathspec->items);
 387        pathspec->items = NULL;
 388}