24f9a0f14a95b55f0d50534b2f0300b3178b6aa2
   1#include "cache.h"
   2#include "tree-walk.h"
   3#include "unpack-trees.h"
   4#include "dir.h"
   5#include "tree.h"
   6#include "pathspec.h"
   7
   8static const char *get_mode(const char *str, unsigned int *modep)
   9{
  10        unsigned char c;
  11        unsigned int mode = 0;
  12
  13        if (*str == ' ')
  14                return NULL;
  15
  16        while ((c = *str++) != ' ') {
  17                if (c < '0' || c > '7')
  18                        return NULL;
  19                mode = (mode << 3) + (c - '0');
  20        }
  21        *modep = mode;
  22        return str;
  23}
  24
  25static void decode_tree_entry(struct tree_desc *desc, const char *buf, unsigned long size)
  26{
  27        const char *path;
  28        unsigned int mode, len;
  29
  30        if (size < 23 || buf[size - 21])
  31                die(_("too-short tree object"));
  32
  33        path = get_mode(buf, &mode);
  34        if (!path)
  35                die(_("malformed mode in tree entry for tree"));
  36        if (!*path)
  37                die(_("empty filename in tree entry for tree"));
  38        len = strlen(path) + 1;
  39
  40        /* Initialize the descriptor entry */
  41        desc->entry.path = path;
  42        desc->entry.mode = canon_mode(mode);
  43        desc->entry.oid  = (const struct object_id *)(path + len);
  44}
  45
  46void init_tree_desc(struct tree_desc *desc, const void *buffer, unsigned long size)
  47{
  48        desc->buffer = buffer;
  49        desc->size = size;
  50        if (size)
  51                decode_tree_entry(desc, buffer, size);
  52}
  53
  54void *fill_tree_descriptor(struct tree_desc *desc, const unsigned char *sha1)
  55{
  56        unsigned long size = 0;
  57        void *buf = NULL;
  58
  59        if (sha1) {
  60                buf = read_object_with_reference(sha1, tree_type, &size, NULL);
  61                if (!buf)
  62                        die("unable to read tree %s", sha1_to_hex(sha1));
  63        }
  64        init_tree_desc(desc, buf, size);
  65        return buf;
  66}
  67
  68static void entry_clear(struct name_entry *a)
  69{
  70        memset(a, 0, sizeof(*a));
  71}
  72
  73static void entry_extract(struct tree_desc *t, struct name_entry *a)
  74{
  75        *a = t->entry;
  76}
  77
  78void update_tree_entry(struct tree_desc *desc)
  79{
  80        const void *buf = desc->buffer;
  81        const unsigned char *end = desc->entry.oid->hash + 20;
  82        unsigned long size = desc->size;
  83        unsigned long len = end - (const unsigned char *)buf;
  84
  85        if (size < len)
  86                die(_("too-short tree file"));
  87        buf = end;
  88        size -= len;
  89        desc->buffer = buf;
  90        desc->size = size;
  91        if (size)
  92                decode_tree_entry(desc, buf, size);
  93}
  94
  95int tree_entry(struct tree_desc *desc, struct name_entry *entry)
  96{
  97        if (!desc->size)
  98                return 0;
  99
 100        *entry = desc->entry;
 101        update_tree_entry(desc);
 102        return 1;
 103}
 104
 105void setup_traverse_info(struct traverse_info *info, const char *base)
 106{
 107        int pathlen = strlen(base);
 108        static struct traverse_info dummy;
 109
 110        memset(info, 0, sizeof(*info));
 111        if (pathlen && base[pathlen-1] == '/')
 112                pathlen--;
 113        info->pathlen = pathlen ? pathlen + 1 : 0;
 114        info->name.path = base;
 115        info->name.oid = (void *)(base + pathlen + 1);
 116        if (pathlen)
 117                info->prev = &dummy;
 118}
 119
 120char *make_traverse_path(char *path, const struct traverse_info *info, const struct name_entry *n)
 121{
 122        int len = tree_entry_len(n);
 123        int pathlen = info->pathlen;
 124
 125        path[pathlen + len] = 0;
 126        for (;;) {
 127                memcpy(path + pathlen, n->path, len);
 128                if (!pathlen)
 129                        break;
 130                path[--pathlen] = '/';
 131                n = &info->name;
 132                len = tree_entry_len(n);
 133                info = info->prev;
 134                pathlen -= len;
 135        }
 136        return path;
 137}
 138
 139struct tree_desc_skip {
 140        struct tree_desc_skip *prev;
 141        const void *ptr;
 142};
 143
 144struct tree_desc_x {
 145        struct tree_desc d;
 146        struct tree_desc_skip *skip;
 147};
 148
 149static int check_entry_match(const char *a, int a_len, const char *b, int b_len)
 150{
 151        /*
 152         * The caller wants to pick *a* from a tree or nothing.
 153         * We are looking at *b* in a tree.
 154         *
 155         * (0) If a and b are the same name, we are trivially happy.
 156         *
 157         * There are three possibilities where *a* could be hiding
 158         * behind *b*.
 159         *
 160         * (1) *a* == "t",   *b* == "ab"  i.e. *b* sorts earlier than *a* no
 161         *                                matter what.
 162         * (2) *a* == "t",   *b* == "t-2" and "t" is a subtree in the tree;
 163         * (3) *a* == "t-2", *b* == "t"   and "t-2" is a blob in the tree.
 164         *
 165         * Otherwise we know *a* won't appear in the tree without
 166         * scanning further.
 167         */
 168
 169        int cmp = name_compare(a, a_len, b, b_len);
 170
 171        /* Most common case first -- reading sync'd trees */
 172        if (!cmp)
 173                return cmp;
 174
 175        if (0 < cmp) {
 176                /* a comes after b; it does not matter if it is case (3)
 177                if (b_len < a_len && !memcmp(a, b, b_len) && a[b_len] < '/')
 178                        return 1;
 179                */
 180                return 1; /* keep looking */
 181        }
 182
 183        /* b comes after a; are we looking at case (2)? */
 184        if (a_len < b_len && !memcmp(a, b, a_len) && b[a_len] < '/')
 185                return 1; /* keep looking */
 186
 187        return -1; /* a cannot appear in the tree */
 188}
 189
 190/*
 191 * From the extended tree_desc, extract the first name entry, while
 192 * paying attention to the candidate "first" name.  Most importantly,
 193 * when looking for an entry, if there are entries that sorts earlier
 194 * in the tree object representation than that name, skip them and
 195 * process the named entry first.  We will remember that we haven't
 196 * processed the first entry yet, and in the later call skip the
 197 * entry we processed early when update_extended_entry() is called.
 198 *
 199 * E.g. if the underlying tree object has these entries:
 200 *
 201 *    blob    "t-1"
 202 *    blob    "t-2"
 203 *    tree    "t"
 204 *    blob    "t=1"
 205 *
 206 * and the "first" asks for "t", remember that we still need to
 207 * process "t-1" and "t-2" but extract "t".  After processing the
 208 * entry "t" from this call, the caller will let us know by calling
 209 * update_extended_entry() that we can remember "t" has been processed
 210 * already.
 211 */
 212
 213static void extended_entry_extract(struct tree_desc_x *t,
 214                                   struct name_entry *a,
 215                                   const char *first,
 216                                   int first_len)
 217{
 218        const char *path;
 219        int len;
 220        struct tree_desc probe;
 221        struct tree_desc_skip *skip;
 222
 223        /*
 224         * Extract the first entry from the tree_desc, but skip the
 225         * ones that we already returned in earlier rounds.
 226         */
 227        while (1) {
 228                if (!t->d.size) {
 229                        entry_clear(a);
 230                        break; /* not found */
 231                }
 232                entry_extract(&t->d, a);
 233                for (skip = t->skip; skip; skip = skip->prev)
 234                        if (a->path == skip->ptr)
 235                                break; /* found */
 236                if (!skip)
 237                        break;
 238                /* We have processed this entry already. */
 239                update_tree_entry(&t->d);
 240        }
 241
 242        if (!first || !a->path)
 243                return;
 244
 245        /*
 246         * The caller wants "first" from this tree, or nothing.
 247         */
 248        path = a->path;
 249        len = tree_entry_len(a);
 250        switch (check_entry_match(first, first_len, path, len)) {
 251        case -1:
 252                entry_clear(a);
 253        case 0:
 254                return;
 255        default:
 256                break;
 257        }
 258
 259        /*
 260         * We need to look-ahead -- we suspect that a subtree whose
 261         * name is "first" may be hiding behind the current entry "path".
 262         */
 263        probe = t->d;
 264        while (probe.size) {
 265                entry_extract(&probe, a);
 266                path = a->path;
 267                len = tree_entry_len(a);
 268                switch (check_entry_match(first, first_len, path, len)) {
 269                case -1:
 270                        entry_clear(a);
 271                case 0:
 272                        return;
 273                default:
 274                        update_tree_entry(&probe);
 275                        break;
 276                }
 277                /* keep looking */
 278        }
 279        entry_clear(a);
 280}
 281
 282static void update_extended_entry(struct tree_desc_x *t, struct name_entry *a)
 283{
 284        if (t->d.entry.path == a->path) {
 285                update_tree_entry(&t->d);
 286        } else {
 287                /* we have returned this entry early */
 288                struct tree_desc_skip *skip = xmalloc(sizeof(*skip));
 289                skip->ptr = a->path;
 290                skip->prev = t->skip;
 291                t->skip = skip;
 292        }
 293}
 294
 295static void free_extended_entry(struct tree_desc_x *t)
 296{
 297        struct tree_desc_skip *p, *s;
 298
 299        for (s = t->skip; s; s = p) {
 300                p = s->prev;
 301                free(s);
 302        }
 303}
 304
 305static inline int prune_traversal(struct name_entry *e,
 306                                  struct traverse_info *info,
 307                                  struct strbuf *base,
 308                                  int still_interesting)
 309{
 310        if (!info->pathspec || still_interesting == 2)
 311                return 2;
 312        if (still_interesting < 0)
 313                return still_interesting;
 314        return tree_entry_interesting(e, base, 0, info->pathspec);
 315}
 316
 317int traverse_trees(int n, struct tree_desc *t, struct traverse_info *info)
 318{
 319        int error = 0;
 320        struct name_entry *entry = xmalloc(n*sizeof(*entry));
 321        int i;
 322        struct tree_desc_x *tx = xcalloc(n, sizeof(*tx));
 323        struct strbuf base = STRBUF_INIT;
 324        int interesting = 1;
 325        char *traverse_path;
 326
 327        for (i = 0; i < n; i++)
 328                tx[i].d = t[i];
 329
 330        if (info->prev) {
 331                strbuf_grow(&base, info->pathlen);
 332                make_traverse_path(base.buf, info->prev, &info->name);
 333                base.buf[info->pathlen-1] = '/';
 334                strbuf_setlen(&base, info->pathlen);
 335                traverse_path = xstrndup(base.buf, info->pathlen);
 336        } else {
 337                traverse_path = xstrndup(info->name.path, info->pathlen);
 338        }
 339        info->traverse_path = traverse_path;
 340        for (;;) {
 341                int trees_used;
 342                unsigned long mask, dirmask;
 343                const char *first = NULL;
 344                int first_len = 0;
 345                struct name_entry *e = NULL;
 346                int len;
 347
 348                for (i = 0; i < n; i++) {
 349                        e = entry + i;
 350                        extended_entry_extract(tx + i, e, NULL, 0);
 351                }
 352
 353                /*
 354                 * A tree may have "t-2" at the current location even
 355                 * though it may have "t" that is a subtree behind it,
 356                 * and another tree may return "t".  We want to grab
 357                 * all "t" from all trees to match in such a case.
 358                 */
 359                for (i = 0; i < n; i++) {
 360                        e = entry + i;
 361                        if (!e->path)
 362                                continue;
 363                        len = tree_entry_len(e);
 364                        if (!first) {
 365                                first = e->path;
 366                                first_len = len;
 367                                continue;
 368                        }
 369                        if (name_compare(e->path, len, first, first_len) < 0) {
 370                                first = e->path;
 371                                first_len = len;
 372                        }
 373                }
 374
 375                if (first) {
 376                        for (i = 0; i < n; i++) {
 377                                e = entry + i;
 378                                extended_entry_extract(tx + i, e, first, first_len);
 379                                /* Cull the ones that are not the earliest */
 380                                if (!e->path)
 381                                        continue;
 382                                len = tree_entry_len(e);
 383                                if (name_compare(e->path, len, first, first_len))
 384                                        entry_clear(e);
 385                        }
 386                }
 387
 388                /* Now we have in entry[i] the earliest name from the trees */
 389                mask = 0;
 390                dirmask = 0;
 391                for (i = 0; i < n; i++) {
 392                        if (!entry[i].path)
 393                                continue;
 394                        mask |= 1ul << i;
 395                        if (S_ISDIR(entry[i].mode))
 396                                dirmask |= 1ul << i;
 397                        e = &entry[i];
 398                }
 399                if (!mask)
 400                        break;
 401                interesting = prune_traversal(e, info, &base, interesting);
 402                if (interesting < 0)
 403                        break;
 404                if (interesting) {
 405                        trees_used = info->fn(n, mask, dirmask, entry, info);
 406                        if (trees_used < 0) {
 407                                error = trees_used;
 408                                if (!info->show_all_errors)
 409                                        break;
 410                        }
 411                        mask &= trees_used;
 412                }
 413                for (i = 0; i < n; i++)
 414                        if (mask & (1ul << i))
 415                                update_extended_entry(tx + i, entry + i);
 416        }
 417        free(entry);
 418        for (i = 0; i < n; i++)
 419                free_extended_entry(tx + i);
 420        free(tx);
 421        free(traverse_path);
 422        info->traverse_path = NULL;
 423        strbuf_release(&base);
 424        return error;
 425}
 426
 427struct dir_state {
 428        void *tree;
 429        unsigned long size;
 430        unsigned char sha1[20];
 431};
 432
 433static int find_tree_entry(struct tree_desc *t, const char *name, unsigned char *result, unsigned *mode)
 434{
 435        int namelen = strlen(name);
 436        while (t->size) {
 437                const char *entry;
 438                const struct object_id *oid;
 439                int entrylen, cmp;
 440
 441                oid = tree_entry_extract(t, &entry, mode);
 442                entrylen = tree_entry_len(&t->entry);
 443                update_tree_entry(t);
 444                if (entrylen > namelen)
 445                        continue;
 446                cmp = memcmp(name, entry, entrylen);
 447                if (cmp > 0)
 448                        continue;
 449                if (cmp < 0)
 450                        break;
 451                if (entrylen == namelen) {
 452                        hashcpy(result, oid->hash);
 453                        return 0;
 454                }
 455                if (name[entrylen] != '/')
 456                        continue;
 457                if (!S_ISDIR(*mode))
 458                        break;
 459                if (++entrylen == namelen) {
 460                        hashcpy(result, oid->hash);
 461                        return 0;
 462                }
 463                return get_tree_entry(oid->hash, name + entrylen, result, mode);
 464        }
 465        return -1;
 466}
 467
 468int get_tree_entry(const unsigned char *tree_sha1, const char *name, unsigned char *sha1, unsigned *mode)
 469{
 470        int retval;
 471        void *tree;
 472        unsigned long size;
 473        unsigned char root[20];
 474
 475        tree = read_object_with_reference(tree_sha1, tree_type, &size, root);
 476        if (!tree)
 477                return -1;
 478
 479        if (name[0] == '\0') {
 480                hashcpy(sha1, root);
 481                free(tree);
 482                return 0;
 483        }
 484
 485        if (!size) {
 486                retval = -1;
 487        } else {
 488                struct tree_desc t;
 489                init_tree_desc(&t, tree, size);
 490                retval = find_tree_entry(&t, name, sha1, mode);
 491        }
 492        free(tree);
 493        return retval;
 494}
 495
 496/*
 497 * This is Linux's built-in max for the number of symlinks to follow.
 498 * That limit, of course, does not affect git, but it's a reasonable
 499 * choice.
 500 */
 501#define GET_TREE_ENTRY_FOLLOW_SYMLINKS_MAX_LINKS 40
 502
 503/**
 504 * Find a tree entry by following symlinks in tree_sha (which is
 505 * assumed to be the root of the repository).  In the event that a
 506 * symlink points outside the repository (e.g. a link to /foo or a
 507 * root-level link to ../foo), the portion of the link which is
 508 * outside the repository will be returned in result_path, and *mode
 509 * will be set to 0.  It is assumed that result_path is uninitialized.
 510 * If there are no symlinks, or the end result of the symlink chain
 511 * points to an object inside the repository, result will be filled in
 512 * with the sha1 of the found object, and *mode will hold the mode of
 513 * the object.
 514 *
 515 * See the code for enum follow_symlink_result for a description of
 516 * the return values.
 517 */
 518enum follow_symlinks_result get_tree_entry_follow_symlinks(unsigned char *tree_sha1, const char *name, unsigned char *result, struct strbuf *result_path, unsigned *mode)
 519{
 520        int retval = MISSING_OBJECT;
 521        struct dir_state *parents = NULL;
 522        size_t parents_alloc = 0;
 523        ssize_t parents_nr = 0;
 524        unsigned char current_tree_sha1[20];
 525        struct strbuf namebuf = STRBUF_INIT;
 526        struct tree_desc t;
 527        int follows_remaining = GET_TREE_ENTRY_FOLLOW_SYMLINKS_MAX_LINKS;
 528        int i;
 529
 530        init_tree_desc(&t, NULL, 0UL);
 531        strbuf_init(result_path, 0);
 532        strbuf_addstr(&namebuf, name);
 533        hashcpy(current_tree_sha1, tree_sha1);
 534
 535        while (1) {
 536                int find_result;
 537                char *first_slash;
 538                char *remainder = NULL;
 539
 540                if (!t.buffer) {
 541                        void *tree;
 542                        unsigned char root[20];
 543                        unsigned long size;
 544                        tree = read_object_with_reference(current_tree_sha1,
 545                                                          tree_type, &size,
 546                                                          root);
 547                        if (!tree)
 548                                goto done;
 549
 550                        ALLOC_GROW(parents, parents_nr + 1, parents_alloc);
 551                        parents[parents_nr].tree = tree;
 552                        parents[parents_nr].size = size;
 553                        hashcpy(parents[parents_nr].sha1, root);
 554                        parents_nr++;
 555
 556                        if (namebuf.buf[0] == '\0') {
 557                                hashcpy(result, root);
 558                                retval = FOUND;
 559                                goto done;
 560                        }
 561
 562                        if (!size)
 563                                goto done;
 564
 565                        /* descend */
 566                        init_tree_desc(&t, tree, size);
 567                }
 568
 569                /* Handle symlinks to e.g. a//b by removing leading slashes */
 570                while (namebuf.buf[0] == '/') {
 571                        strbuf_remove(&namebuf, 0, 1);
 572                }
 573
 574                /* Split namebuf into a first component and a remainder */
 575                if ((first_slash = strchr(namebuf.buf, '/'))) {
 576                        *first_slash = 0;
 577                        remainder = first_slash + 1;
 578                }
 579
 580                if (!strcmp(namebuf.buf, "..")) {
 581                        struct dir_state *parent;
 582                        /*
 583                         * We could end up with .. in the namebuf if it
 584                         * appears in a symlink.
 585                         */
 586
 587                        if (parents_nr == 1) {
 588                                if (remainder)
 589                                        *first_slash = '/';
 590                                strbuf_add(result_path, namebuf.buf,
 591                                           namebuf.len);
 592                                *mode = 0;
 593                                retval = FOUND;
 594                                goto done;
 595                        }
 596                        parent = &parents[parents_nr - 1];
 597                        free(parent->tree);
 598                        parents_nr--;
 599                        parent = &parents[parents_nr - 1];
 600                        init_tree_desc(&t, parent->tree, parent->size);
 601                        strbuf_remove(&namebuf, 0, remainder ? 3 : 2);
 602                        continue;
 603                }
 604
 605                /* We could end up here via a symlink to dir/.. */
 606                if (namebuf.buf[0] == '\0') {
 607                        hashcpy(result, parents[parents_nr - 1].sha1);
 608                        retval = FOUND;
 609                        goto done;
 610                }
 611
 612                /* Look up the first (or only) path component in the tree. */
 613                find_result = find_tree_entry(&t, namebuf.buf,
 614                                              current_tree_sha1, mode);
 615                if (find_result) {
 616                        goto done;
 617                }
 618
 619                if (S_ISDIR(*mode)) {
 620                        if (!remainder) {
 621                                hashcpy(result, current_tree_sha1);
 622                                retval = FOUND;
 623                                goto done;
 624                        }
 625                        /* Descend the tree */
 626                        t.buffer = NULL;
 627                        strbuf_remove(&namebuf, 0,
 628                                      1 + first_slash - namebuf.buf);
 629                } else if (S_ISREG(*mode)) {
 630                        if (!remainder) {
 631                                hashcpy(result, current_tree_sha1);
 632                                retval = FOUND;
 633                        } else {
 634                                retval = NOT_DIR;
 635                        }
 636                        goto done;
 637                } else if (S_ISLNK(*mode)) {
 638                        /* Follow a symlink */
 639                        unsigned long link_len;
 640                        size_t len;
 641                        char *contents, *contents_start;
 642                        struct dir_state *parent;
 643                        enum object_type type;
 644
 645                        if (follows_remaining-- == 0) {
 646                                /* Too many symlinks followed */
 647                                retval = SYMLINK_LOOP;
 648                                goto done;
 649                        }
 650
 651                        /*
 652                         * At this point, we have followed at a least
 653                         * one symlink, so on error we need to report this.
 654                         */
 655                        retval = DANGLING_SYMLINK;
 656
 657                        contents = read_sha1_file(current_tree_sha1, &type,
 658                                                  &link_len);
 659
 660                        if (!contents)
 661                                goto done;
 662
 663                        if (contents[0] == '/') {
 664                                strbuf_addstr(result_path, contents);
 665                                free(contents);
 666                                *mode = 0;
 667                                retval = FOUND;
 668                                goto done;
 669                        }
 670
 671                        if (remainder)
 672                                len = first_slash - namebuf.buf;
 673                        else
 674                                len = namebuf.len;
 675
 676                        contents_start = contents;
 677
 678                        parent = &parents[parents_nr - 1];
 679                        init_tree_desc(&t, parent->tree, parent->size);
 680                        strbuf_splice(&namebuf, 0, len,
 681                                      contents_start, link_len);
 682                        if (remainder)
 683                                namebuf.buf[link_len] = '/';
 684                        free(contents);
 685                }
 686        }
 687done:
 688        for (i = 0; i < parents_nr; i++)
 689                free(parents[i].tree);
 690        free(parents);
 691
 692        strbuf_release(&namebuf);
 693        return retval;
 694}
 695
 696static int match_entry(const struct pathspec_item *item,
 697                       const struct name_entry *entry, int pathlen,
 698                       const char *match, int matchlen,
 699                       enum interesting *never_interesting)
 700{
 701        int m = -1; /* signals that we haven't called strncmp() */
 702
 703        if (item->magic & PATHSPEC_ICASE)
 704                /*
 705                 * "Never interesting" trick requires exact
 706                 * matching. We could do something clever with inexact
 707                 * matching, but it's trickier (and not to forget that
 708                 * strcasecmp is locale-dependent, at least in
 709                 * glibc). Just disable it for now. It can't be worse
 710                 * than the wildcard's codepath of '[Tt][Hi][Is][Ss]'
 711                 * pattern.
 712                 */
 713                *never_interesting = entry_not_interesting;
 714        else if (*never_interesting != entry_not_interesting) {
 715                /*
 716                 * We have not seen any match that sorts later
 717                 * than the current path.
 718                 */
 719
 720                /*
 721                 * Does match sort strictly earlier than path
 722                 * with their common parts?
 723                 */
 724                m = strncmp(match, entry->path,
 725                            (matchlen < pathlen) ? matchlen : pathlen);
 726                if (m < 0)
 727                        return 0;
 728
 729                /*
 730                 * If we come here even once, that means there is at
 731                 * least one pathspec that would sort equal to or
 732                 * later than the path we are currently looking at.
 733                 * In other words, if we have never reached this point
 734                 * after iterating all pathspecs, it means all
 735                 * pathspecs are either outside of base, or inside the
 736                 * base but sorts strictly earlier than the current
 737                 * one.  In either case, they will never match the
 738                 * subsequent entries.  In such a case, we initialized
 739                 * the variable to -1 and that is what will be
 740                 * returned, allowing the caller to terminate early.
 741                 */
 742                *never_interesting = entry_not_interesting;
 743        }
 744
 745        if (pathlen > matchlen)
 746                return 0;
 747
 748        if (matchlen > pathlen) {
 749                if (match[pathlen] != '/')
 750                        return 0;
 751                if (!S_ISDIR(entry->mode) && !S_ISGITLINK(entry->mode))
 752                        return 0;
 753        }
 754
 755        if (m == -1)
 756                /*
 757                 * we cheated and did not do strncmp(), so we do
 758                 * that here.
 759                 */
 760                m = ps_strncmp(item, match, entry->path, pathlen);
 761
 762        /*
 763         * If common part matched earlier then it is a hit,
 764         * because we rejected the case where path is not a
 765         * leading directory and is shorter than match.
 766         */
 767        if (!m)
 768                /*
 769                 * match_entry does not check if the prefix part is
 770                 * matched case-sensitively. If the entry is a
 771                 * directory and part of prefix, it'll be rematched
 772                 * eventually by basecmp with special treatment for
 773                 * the prefix.
 774                 */
 775                return 1;
 776
 777        return 0;
 778}
 779
 780/* :(icase)-aware string compare */
 781static int basecmp(const struct pathspec_item *item,
 782                   const char *base, const char *match, int len)
 783{
 784        if (item->magic & PATHSPEC_ICASE) {
 785                int ret, n = len > item->prefix ? item->prefix : len;
 786                ret = strncmp(base, match, n);
 787                if (ret)
 788                        return ret;
 789                base += n;
 790                match += n;
 791                len -= n;
 792        }
 793        return ps_strncmp(item, base, match, len);
 794}
 795
 796static int match_dir_prefix(const struct pathspec_item *item,
 797                            const char *base,
 798                            const char *match, int matchlen)
 799{
 800        if (basecmp(item, base, match, matchlen))
 801                return 0;
 802
 803        /*
 804         * If the base is a subdirectory of a path which
 805         * was specified, all of them are interesting.
 806         */
 807        if (!matchlen ||
 808            base[matchlen] == '/' ||
 809            match[matchlen - 1] == '/')
 810                return 1;
 811
 812        /* Just a random prefix match */
 813        return 0;
 814}
 815
 816/*
 817 * Perform matching on the leading non-wildcard part of
 818 * pathspec. item->nowildcard_len must be greater than zero. Return
 819 * non-zero if base is matched.
 820 */
 821static int match_wildcard_base(const struct pathspec_item *item,
 822                               const char *base, int baselen,
 823                               int *matched)
 824{
 825        const char *match = item->match;
 826        /* the wildcard part is not considered in this function */
 827        int matchlen = item->nowildcard_len;
 828
 829        if (baselen) {
 830                int dirlen;
 831                /*
 832                 * Return early if base is longer than the
 833                 * non-wildcard part but it does not match.
 834                 */
 835                if (baselen >= matchlen) {
 836                        *matched = matchlen;
 837                        return !basecmp(item, base, match, matchlen);
 838                }
 839
 840                dirlen = matchlen;
 841                while (dirlen && match[dirlen - 1] != '/')
 842                        dirlen--;
 843
 844                /*
 845                 * Return early if base is shorter than the
 846                 * non-wildcard part but it does not match. Note that
 847                 * base ends with '/' so we are sure it really matches
 848                 * directory
 849                 */
 850                if (basecmp(item, base, match, baselen))
 851                        return 0;
 852                *matched = baselen;
 853        } else
 854                *matched = 0;
 855        /*
 856         * we could have checked entry against the non-wildcard part
 857         * that is not in base and does similar never_interesting
 858         * optimization as in match_entry. For now just be happy with
 859         * base comparison.
 860         */
 861        return entry_interesting;
 862}
 863
 864/*
 865 * Is a tree entry interesting given the pathspec we have?
 866 *
 867 * Pre-condition: either baselen == base_offset (i.e. empty path)
 868 * or base[baselen-1] == '/' (i.e. with trailing slash).
 869 */
 870static enum interesting do_match(const struct name_entry *entry,
 871                                 struct strbuf *base, int base_offset,
 872                                 const struct pathspec *ps,
 873                                 int exclude)
 874{
 875        int i;
 876        int pathlen, baselen = base->len - base_offset;
 877        enum interesting never_interesting = ps->has_wildcard ?
 878                entry_not_interesting : all_entries_not_interesting;
 879
 880        GUARD_PATHSPEC(ps,
 881                       PATHSPEC_FROMTOP |
 882                       PATHSPEC_MAXDEPTH |
 883                       PATHSPEC_LITERAL |
 884                       PATHSPEC_GLOB |
 885                       PATHSPEC_ICASE |
 886                       PATHSPEC_EXCLUDE);
 887
 888        if (!ps->nr) {
 889                if (!ps->recursive ||
 890                    !(ps->magic & PATHSPEC_MAXDEPTH) ||
 891                    ps->max_depth == -1)
 892                        return all_entries_interesting;
 893                return within_depth(base->buf + base_offset, baselen,
 894                                    !!S_ISDIR(entry->mode),
 895                                    ps->max_depth) ?
 896                        entry_interesting : entry_not_interesting;
 897        }
 898
 899        pathlen = tree_entry_len(entry);
 900
 901        for (i = ps->nr - 1; i >= 0; i--) {
 902                const struct pathspec_item *item = ps->items+i;
 903                const char *match = item->match;
 904                const char *base_str = base->buf + base_offset;
 905                int matchlen = item->len, matched = 0;
 906
 907                if ((!exclude &&   item->magic & PATHSPEC_EXCLUDE) ||
 908                    ( exclude && !(item->magic & PATHSPEC_EXCLUDE)))
 909                        continue;
 910
 911                if (baselen >= matchlen) {
 912                        /* If it doesn't match, move along... */
 913                        if (!match_dir_prefix(item, base_str, match, matchlen))
 914                                goto match_wildcards;
 915
 916                        if (!ps->recursive ||
 917                            !(ps->magic & PATHSPEC_MAXDEPTH) ||
 918                            ps->max_depth == -1)
 919                                return all_entries_interesting;
 920
 921                        return within_depth(base_str + matchlen + 1,
 922                                            baselen - matchlen - 1,
 923                                            !!S_ISDIR(entry->mode),
 924                                            ps->max_depth) ?
 925                                entry_interesting : entry_not_interesting;
 926                }
 927
 928                /* Either there must be no base, or the base must match. */
 929                if (baselen == 0 || !basecmp(item, base_str, match, baselen)) {
 930                        if (match_entry(item, entry, pathlen,
 931                                        match + baselen, matchlen - baselen,
 932                                        &never_interesting))
 933                                return entry_interesting;
 934
 935                        if (item->nowildcard_len < item->len) {
 936                                if (!git_fnmatch(item, match + baselen, entry->path,
 937                                                 item->nowildcard_len - baselen))
 938                                        return entry_interesting;
 939
 940                                /*
 941                                 * Match all directories. We'll try to
 942                                 * match files later on.
 943                                 */
 944                                if (ps->recursive && S_ISDIR(entry->mode))
 945                                        return entry_interesting;
 946                        }
 947
 948                        continue;
 949                }
 950
 951match_wildcards:
 952                if (item->nowildcard_len == item->len)
 953                        continue;
 954
 955                if (item->nowildcard_len &&
 956                    !match_wildcard_base(item, base_str, baselen, &matched))
 957                        continue;
 958
 959                /*
 960                 * Concatenate base and entry->path into one and do
 961                 * fnmatch() on it.
 962                 *
 963                 * While we could avoid concatenation in certain cases
 964                 * [1], which saves a memcpy and potentially a
 965                 * realloc, it turns out not worth it. Measurement on
 966                 * linux-2.6 does not show any clear improvements,
 967                 * partly because of the nowildcard_len optimization
 968                 * in git_fnmatch(). Avoid micro-optimizations here.
 969                 *
 970                 * [1] if match_wildcard_base() says the base
 971                 * directory is already matched, we only need to match
 972                 * the rest, which is shorter so _in theory_ faster.
 973                 */
 974
 975                strbuf_add(base, entry->path, pathlen);
 976
 977                if (!git_fnmatch(item, match, base->buf + base_offset,
 978                                 item->nowildcard_len)) {
 979                        strbuf_setlen(base, base_offset + baselen);
 980                        return entry_interesting;
 981                }
 982                strbuf_setlen(base, base_offset + baselen);
 983
 984                /*
 985                 * Match all directories. We'll try to match files
 986                 * later on.
 987                 * max_depth is ignored but we may consider support it
 988                 * in future, see
 989                 * http://thread.gmane.org/gmane.comp.version-control.git/163757/focus=163840
 990                 */
 991                if (ps->recursive && S_ISDIR(entry->mode))
 992                        return entry_interesting;
 993        }
 994        return never_interesting; /* No matches */
 995}
 996
 997/*
 998 * Is a tree entry interesting given the pathspec we have?
 999 *
1000 * Pre-condition: either baselen == base_offset (i.e. empty path)
1001 * or base[baselen-1] == '/' (i.e. with trailing slash).
1002 */
1003enum interesting tree_entry_interesting(const struct name_entry *entry,
1004                                        struct strbuf *base, int base_offset,
1005                                        const struct pathspec *ps)
1006{
1007        enum interesting positive, negative;
1008        positive = do_match(entry, base, base_offset, ps, 0);
1009
1010        /*
1011         * case | entry | positive | negative | result
1012         * -----+-------+----------+----------+-------
1013         *   1  |  file |   -1     |  -1..2   |  -1
1014         *   2  |  file |    0     |  -1..2   |   0
1015         *   3  |  file |    1     |   -1     |   1
1016         *   4  |  file |    1     |    0     |   1
1017         *   5  |  file |    1     |    1     |   0
1018         *   6  |  file |    1     |    2     |   0
1019         *   7  |  file |    2     |   -1     |   2
1020         *   8  |  file |    2     |    0     |   2
1021         *   9  |  file |    2     |    1     |   0
1022         *  10  |  file |    2     |    2     |  -1
1023         * -----+-------+----------+----------+-------
1024         *  11  |  dir  |   -1     |  -1..2   |  -1
1025         *  12  |  dir  |    0     |  -1..2   |   0
1026         *  13  |  dir  |    1     |   -1     |   1
1027         *  14  |  dir  |    1     |    0     |   1
1028         *  15  |  dir  |    1     |    1     |   1 (*)
1029         *  16  |  dir  |    1     |    2     |   0
1030         *  17  |  dir  |    2     |   -1     |   2
1031         *  18  |  dir  |    2     |    0     |   2
1032         *  19  |  dir  |    2     |    1     |   1 (*)
1033         *  20  |  dir  |    2     |    2     |  -1
1034         *
1035         * (*) An exclude pattern interested in a directory does not
1036         * necessarily mean it will exclude all of the directory. In
1037         * wildcard case, it can't decide until looking at individual
1038         * files inside. So don't write such directories off yet.
1039         */
1040
1041        if (!(ps->magic & PATHSPEC_EXCLUDE) ||
1042            positive <= entry_not_interesting) /* #1, #2, #11, #12 */
1043                return positive;
1044
1045        negative = do_match(entry, base, base_offset, ps, 1);
1046
1047        /* #3, #4, #7, #8, #13, #14, #17, #18 */
1048        if (negative <= entry_not_interesting)
1049                return positive;
1050
1051        /* #15, #19 */
1052        if (S_ISDIR(entry->mode) &&
1053            positive >= entry_interesting &&
1054            negative == entry_interesting)
1055                return entry_interesting;
1056
1057        if ((positive == entry_interesting &&
1058             negative >= entry_interesting) || /* #5, #6, #16 */
1059            (positive == all_entries_interesting &&
1060             negative == entry_interesting)) /* #9 */
1061                return entry_not_interesting;
1062
1063        return all_entries_not_interesting; /* #10, #20 */
1064}