f81e1d291758a462f434f555cd77f471faeecc5b
   1/*
   2 * This handles recursive filename detection with exclude
   3 * files, index knowledge etc..
   4 *
   5 * Copyright (C) Linus Torvalds, 2005-2006
   6 *               Junio Hamano, 2005-2006
   7 */
   8#include "cache.h"
   9#include "dir.h"
  10#include "refs.h"
  11
  12struct path_simplify {
  13        int len;
  14        const char *path;
  15};
  16
  17static int read_directory_recursive(struct dir_struct *dir, const char *path, int len,
  18        int check_only, const struct path_simplify *simplify);
  19static int get_dtype(struct dirent *de, const char *path, int len);
  20
  21/* helper string functions with support for the ignore_case flag */
  22int strcmp_icase(const char *a, const char *b)
  23{
  24        return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
  25}
  26
  27int strncmp_icase(const char *a, const char *b, size_t count)
  28{
  29        return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
  30}
  31
  32int fnmatch_icase(const char *pattern, const char *string, int flags)
  33{
  34        return fnmatch(pattern, string, flags | (ignore_case ? FNM_CASEFOLD : 0));
  35}
  36
  37inline int git_fnmatch(const char *pattern, const char *string,
  38                       int flags, int prefix)
  39{
  40        int fnm_flags = 0;
  41        if (flags & GFNM_PATHNAME)
  42                fnm_flags |= FNM_PATHNAME;
  43        if (prefix > 0) {
  44                if (strncmp(pattern, string, prefix))
  45                        return FNM_NOMATCH;
  46                pattern += prefix;
  47                string += prefix;
  48        }
  49        return fnmatch(pattern, string, fnm_flags);
  50}
  51
  52static size_t common_prefix_len(const char **pathspec)
  53{
  54        const char *n, *first;
  55        size_t max = 0;
  56
  57        if (!pathspec)
  58                return max;
  59
  60        first = *pathspec;
  61        while ((n = *pathspec++)) {
  62                size_t i, len = 0;
  63                for (i = 0; first == n || i < max; i++) {
  64                        char c = n[i];
  65                        if (!c || c != first[i] || is_glob_special(c))
  66                                break;
  67                        if (c == '/')
  68                                len = i + 1;
  69                }
  70                if (first == n || len < max) {
  71                        max = len;
  72                        if (!max)
  73                                break;
  74                }
  75        }
  76        return max;
  77}
  78
  79/*
  80 * Returns a copy of the longest leading path common among all
  81 * pathspecs.
  82 */
  83char *common_prefix(const char **pathspec)
  84{
  85        unsigned long len = common_prefix_len(pathspec);
  86
  87        return len ? xmemdupz(*pathspec, len) : NULL;
  88}
  89
  90int fill_directory(struct dir_struct *dir, const char **pathspec)
  91{
  92        size_t len;
  93
  94        /*
  95         * Calculate common prefix for the pathspec, and
  96         * use that to optimize the directory walk
  97         */
  98        len = common_prefix_len(pathspec);
  99
 100        /* Read the directory and prune it */
 101        read_directory(dir, pathspec ? *pathspec : "", len, pathspec);
 102        return len;
 103}
 104
 105int within_depth(const char *name, int namelen,
 106                        int depth, int max_depth)
 107{
 108        const char *cp = name, *cpe = name + namelen;
 109
 110        while (cp < cpe) {
 111                if (*cp++ != '/')
 112                        continue;
 113                depth++;
 114                if (depth > max_depth)
 115                        return 0;
 116        }
 117        return 1;
 118}
 119
 120/*
 121 * Does 'match' match the given name?
 122 * A match is found if
 123 *
 124 * (1) the 'match' string is leading directory of 'name', or
 125 * (2) the 'match' string is a wildcard and matches 'name', or
 126 * (3) the 'match' string is exactly the same as 'name'.
 127 *
 128 * and the return value tells which case it was.
 129 *
 130 * It returns 0 when there is no match.
 131 */
 132static int match_one(const char *match, const char *name, int namelen)
 133{
 134        int matchlen;
 135
 136        /* If the match was just the prefix, we matched */
 137        if (!*match)
 138                return MATCHED_RECURSIVELY;
 139
 140        if (ignore_case) {
 141                for (;;) {
 142                        unsigned char c1 = tolower(*match);
 143                        unsigned char c2 = tolower(*name);
 144                        if (c1 == '\0' || is_glob_special(c1))
 145                                break;
 146                        if (c1 != c2)
 147                                return 0;
 148                        match++;
 149                        name++;
 150                        namelen--;
 151                }
 152        } else {
 153                for (;;) {
 154                        unsigned char c1 = *match;
 155                        unsigned char c2 = *name;
 156                        if (c1 == '\0' || is_glob_special(c1))
 157                                break;
 158                        if (c1 != c2)
 159                                return 0;
 160                        match++;
 161                        name++;
 162                        namelen--;
 163                }
 164        }
 165
 166
 167        /*
 168         * If we don't match the matchstring exactly,
 169         * we need to match by fnmatch
 170         */
 171        matchlen = strlen(match);
 172        if (strncmp_icase(match, name, matchlen))
 173                return !fnmatch_icase(match, name, 0) ? MATCHED_FNMATCH : 0;
 174
 175        if (namelen == matchlen)
 176                return MATCHED_EXACTLY;
 177        if (match[matchlen-1] == '/' || name[matchlen] == '/')
 178                return MATCHED_RECURSIVELY;
 179        return 0;
 180}
 181
 182/*
 183 * Given a name and a list of pathspecs, see if the name matches
 184 * any of the pathspecs.  The caller is also interested in seeing
 185 * all pathspec matches some names it calls this function with
 186 * (otherwise the user could have mistyped the unmatched pathspec),
 187 * and a mark is left in seen[] array for pathspec element that
 188 * actually matched anything.
 189 */
 190int match_pathspec(const char **pathspec, const char *name, int namelen,
 191                int prefix, char *seen)
 192{
 193        int i, retval = 0;
 194
 195        if (!pathspec)
 196                return 1;
 197
 198        name += prefix;
 199        namelen -= prefix;
 200
 201        for (i = 0; pathspec[i] != NULL; i++) {
 202                int how;
 203                const char *match = pathspec[i] + prefix;
 204                if (seen && seen[i] == MATCHED_EXACTLY)
 205                        continue;
 206                how = match_one(match, name, namelen);
 207                if (how) {
 208                        if (retval < how)
 209                                retval = how;
 210                        if (seen && seen[i] < how)
 211                                seen[i] = how;
 212                }
 213        }
 214        return retval;
 215}
 216
 217/*
 218 * Does 'match' match the given name?
 219 * A match is found if
 220 *
 221 * (1) the 'match' string is leading directory of 'name', or
 222 * (2) the 'match' string is a wildcard and matches 'name', or
 223 * (3) the 'match' string is exactly the same as 'name'.
 224 *
 225 * and the return value tells which case it was.
 226 *
 227 * It returns 0 when there is no match.
 228 */
 229static int match_pathspec_item(const struct pathspec_item *item, int prefix,
 230                               const char *name, int namelen)
 231{
 232        /* name/namelen has prefix cut off by caller */
 233        const char *match = item->match + prefix;
 234        int matchlen = item->len - prefix;
 235
 236        /* If the match was just the prefix, we matched */
 237        if (!*match)
 238                return MATCHED_RECURSIVELY;
 239
 240        if (matchlen <= namelen && !strncmp(match, name, matchlen)) {
 241                if (matchlen == namelen)
 242                        return MATCHED_EXACTLY;
 243
 244                if (match[matchlen-1] == '/' || name[matchlen] == '/')
 245                        return MATCHED_RECURSIVELY;
 246        }
 247
 248        if (item->nowildcard_len < item->len &&
 249            !git_fnmatch(match, name, 0, item->nowildcard_len - prefix))
 250                return MATCHED_FNMATCH;
 251
 252        return 0;
 253}
 254
 255/*
 256 * Given a name and a list of pathspecs, see if the name matches
 257 * any of the pathspecs.  The caller is also interested in seeing
 258 * all pathspec matches some names it calls this function with
 259 * (otherwise the user could have mistyped the unmatched pathspec),
 260 * and a mark is left in seen[] array for pathspec element that
 261 * actually matched anything.
 262 */
 263int match_pathspec_depth(const struct pathspec *ps,
 264                         const char *name, int namelen,
 265                         int prefix, char *seen)
 266{
 267        int i, retval = 0;
 268
 269        if (!ps->nr) {
 270                if (!ps->recursive || ps->max_depth == -1)
 271                        return MATCHED_RECURSIVELY;
 272
 273                if (within_depth(name, namelen, 0, ps->max_depth))
 274                        return MATCHED_EXACTLY;
 275                else
 276                        return 0;
 277        }
 278
 279        name += prefix;
 280        namelen -= prefix;
 281
 282        for (i = ps->nr - 1; i >= 0; i--) {
 283                int how;
 284                if (seen && seen[i] == MATCHED_EXACTLY)
 285                        continue;
 286                how = match_pathspec_item(ps->items+i, prefix, name, namelen);
 287                if (ps->recursive && ps->max_depth != -1 &&
 288                    how && how != MATCHED_FNMATCH) {
 289                        int len = ps->items[i].len;
 290                        if (name[len] == '/')
 291                                len++;
 292                        if (within_depth(name+len, namelen-len, 0, ps->max_depth))
 293                                how = MATCHED_EXACTLY;
 294                        else
 295                                how = 0;
 296                }
 297                if (how) {
 298                        if (retval < how)
 299                                retval = how;
 300                        if (seen && seen[i] < how)
 301                                seen[i] = how;
 302                }
 303        }
 304        return retval;
 305}
 306
 307/*
 308 * Return the length of the "simple" part of a path match limiter.
 309 */
 310static int simple_length(const char *match)
 311{
 312        int len = -1;
 313
 314        for (;;) {
 315                unsigned char c = *match++;
 316                len++;
 317                if (c == '\0' || is_glob_special(c))
 318                        return len;
 319        }
 320}
 321
 322static int no_wildcard(const char *string)
 323{
 324        return string[simple_length(string)] == '\0';
 325}
 326
 327void parse_exclude_pattern(const char **pattern,
 328                           int *patternlen,
 329                           int *flags,
 330                           int *nowildcardlen)
 331{
 332        const char *p = *pattern;
 333        size_t i, len;
 334
 335        *flags = 0;
 336        if (*p == '!') {
 337                *flags |= EXC_FLAG_NEGATIVE;
 338                p++;
 339        }
 340        len = strlen(p);
 341        if (len && p[len - 1] == '/') {
 342                len--;
 343                *flags |= EXC_FLAG_MUSTBEDIR;
 344        }
 345        for (i = 0; i < len; i++) {
 346                if (p[i] == '/')
 347                        break;
 348        }
 349        if (i == len)
 350                *flags |= EXC_FLAG_NODIR;
 351        *nowildcardlen = simple_length(p);
 352        /*
 353         * we should have excluded the trailing slash from 'p' too,
 354         * but that's one more allocation. Instead just make sure
 355         * nowildcardlen does not exceed real patternlen
 356         */
 357        if (*nowildcardlen > len)
 358                *nowildcardlen = len;
 359        if (*p == '*' && no_wildcard(p + 1))
 360                *flags |= EXC_FLAG_ENDSWITH;
 361        *pattern = p;
 362        *patternlen = len;
 363}
 364
 365void add_exclude(const char *string, const char *base,
 366                 int baselen, struct exclude_list *which)
 367{
 368        struct exclude *x;
 369        int patternlen;
 370        int flags;
 371        int nowildcardlen;
 372
 373        parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen);
 374        if (flags & EXC_FLAG_MUSTBEDIR) {
 375                char *s;
 376                x = xmalloc(sizeof(*x) + patternlen + 1);
 377                s = (char *)(x+1);
 378                memcpy(s, string, patternlen);
 379                s[patternlen] = '\0';
 380                x->pattern = s;
 381        } else {
 382                x = xmalloc(sizeof(*x));
 383                x->pattern = string;
 384        }
 385        x->patternlen = patternlen;
 386        x->nowildcardlen = nowildcardlen;
 387        x->base = base;
 388        x->baselen = baselen;
 389        x->flags = flags;
 390        ALLOC_GROW(which->excludes, which->nr + 1, which->alloc);
 391        which->excludes[which->nr++] = x;
 392}
 393
 394static void *read_skip_worktree_file_from_index(const char *path, size_t *size)
 395{
 396        int pos, len;
 397        unsigned long sz;
 398        enum object_type type;
 399        void *data;
 400        struct index_state *istate = &the_index;
 401
 402        len = strlen(path);
 403        pos = index_name_pos(istate, path, len);
 404        if (pos < 0)
 405                return NULL;
 406        if (!ce_skip_worktree(istate->cache[pos]))
 407                return NULL;
 408        data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
 409        if (!data || type != OBJ_BLOB) {
 410                free(data);
 411                return NULL;
 412        }
 413        *size = xsize_t(sz);
 414        return data;
 415}
 416
 417void free_excludes(struct exclude_list *el)
 418{
 419        int i;
 420
 421        for (i = 0; i < el->nr; i++)
 422                free(el->excludes[i]);
 423        free(el->excludes);
 424
 425        el->nr = 0;
 426        el->excludes = NULL;
 427}
 428
 429int add_excludes_from_file_to_list(const char *fname,
 430                                   const char *base,
 431                                   int baselen,
 432                                   char **buf_p,
 433                                   struct exclude_list *which,
 434                                   int check_index)
 435{
 436        struct stat st;
 437        int fd, i;
 438        size_t size = 0;
 439        char *buf, *entry;
 440
 441        fd = open(fname, O_RDONLY);
 442        if (fd < 0 || fstat(fd, &st) < 0) {
 443                if (errno != ENOENT)
 444                        warn_on_inaccessible(fname);
 445                if (0 <= fd)
 446                        close(fd);
 447                if (!check_index ||
 448                    (buf = read_skip_worktree_file_from_index(fname, &size)) == NULL)
 449                        return -1;
 450                if (size == 0) {
 451                        free(buf);
 452                        return 0;
 453                }
 454                if (buf[size-1] != '\n') {
 455                        buf = xrealloc(buf, size+1);
 456                        buf[size++] = '\n';
 457                }
 458        }
 459        else {
 460                size = xsize_t(st.st_size);
 461                if (size == 0) {
 462                        close(fd);
 463                        return 0;
 464                }
 465                buf = xmalloc(size+1);
 466                if (read_in_full(fd, buf, size) != size) {
 467                        free(buf);
 468                        close(fd);
 469                        return -1;
 470                }
 471                buf[size++] = '\n';
 472                close(fd);
 473        }
 474
 475        if (buf_p)
 476                *buf_p = buf;
 477        entry = buf;
 478        for (i = 0; i < size; i++) {
 479                if (buf[i] == '\n') {
 480                        if (entry != buf + i && entry[0] != '#') {
 481                                buf[i - (i && buf[i-1] == '\r')] = 0;
 482                                add_exclude(entry, base, baselen, which);
 483                        }
 484                        entry = buf + i + 1;
 485                }
 486        }
 487        return 0;
 488}
 489
 490void add_excludes_from_file(struct dir_struct *dir, const char *fname)
 491{
 492        if (add_excludes_from_file_to_list(fname, "", 0, NULL,
 493                                           &dir->exclude_list[EXC_FILE], 0) < 0)
 494                die("cannot use %s as an exclude file", fname);
 495}
 496
 497static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
 498{
 499        struct exclude_list *el;
 500        struct exclude_stack *stk = NULL;
 501        int current;
 502
 503        if ((!dir->exclude_per_dir) ||
 504            (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
 505                return; /* too long a path -- ignore */
 506
 507        /* Pop the ones that are not the prefix of the path being checked. */
 508        el = &dir->exclude_list[EXC_DIRS];
 509        while ((stk = dir->exclude_stack) != NULL) {
 510                if (stk->baselen <= baselen &&
 511                    !strncmp(dir->basebuf, base, stk->baselen))
 512                        break;
 513                dir->exclude_stack = stk->prev;
 514                while (stk->exclude_ix < el->nr)
 515                        free(el->excludes[--el->nr]);
 516                free(stk->filebuf);
 517                free(stk);
 518        }
 519
 520        /* Read from the parent directories and push them down. */
 521        current = stk ? stk->baselen : -1;
 522        while (current < baselen) {
 523                struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
 524                const char *cp;
 525
 526                if (current < 0) {
 527                        cp = base;
 528                        current = 0;
 529                }
 530                else {
 531                        cp = strchr(base + current + 1, '/');
 532                        if (!cp)
 533                                die("oops in prep_exclude");
 534                        cp++;
 535                }
 536                stk->prev = dir->exclude_stack;
 537                stk->baselen = cp - base;
 538                stk->exclude_ix = el->nr;
 539                memcpy(dir->basebuf + current, base + current,
 540                       stk->baselen - current);
 541                strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
 542                add_excludes_from_file_to_list(dir->basebuf,
 543                                               dir->basebuf, stk->baselen,
 544                                               &stk->filebuf, el, 1);
 545                dir->exclude_stack = stk;
 546                current = stk->baselen;
 547        }
 548        dir->basebuf[baselen] = '\0';
 549}
 550
 551int match_basename(const char *basename, int basenamelen,
 552                   const char *pattern, int prefix, int patternlen,
 553                   int flags)
 554{
 555        if (prefix == patternlen) {
 556                if (!strcmp_icase(pattern, basename))
 557                        return 1;
 558        } else if (flags & EXC_FLAG_ENDSWITH) {
 559                if (patternlen - 1 <= basenamelen &&
 560                    !strcmp_icase(pattern + 1,
 561                                  basename + basenamelen - patternlen + 1))
 562                        return 1;
 563        } else {
 564                if (fnmatch_icase(pattern, basename, 0) == 0)
 565                        return 1;
 566        }
 567        return 0;
 568}
 569
 570int match_pathname(const char *pathname, int pathlen,
 571                   const char *base, int baselen,
 572                   const char *pattern, int prefix, int patternlen,
 573                   int flags)
 574{
 575        const char *name;
 576        int namelen;
 577
 578        /*
 579         * match with FNM_PATHNAME; the pattern has base implicitly
 580         * in front of it.
 581         */
 582        if (*pattern == '/') {
 583                pattern++;
 584                prefix--;
 585        }
 586
 587        /*
 588         * baselen does not count the trailing slash. base[] may or
 589         * may not end with a trailing slash though.
 590         */
 591        if (pathlen < baselen + 1 ||
 592            (baselen && pathname[baselen] != '/') ||
 593            strncmp_icase(pathname, base, baselen))
 594                return 0;
 595
 596        namelen = baselen ? pathlen - baselen - 1 : pathlen;
 597        name = pathname + pathlen - namelen;
 598
 599        if (prefix) {
 600                /*
 601                 * if the non-wildcard part is longer than the
 602                 * remaining pathname, surely it cannot match.
 603                 */
 604                if (prefix > namelen)
 605                        return 0;
 606
 607                if (strncmp_icase(pattern, name, prefix))
 608                        return 0;
 609                pattern += prefix;
 610                name    += prefix;
 611                namelen -= prefix;
 612        }
 613
 614        return fnmatch_icase(pattern, name, FNM_PATHNAME) == 0;
 615}
 616
 617/* Scan the list and let the last match determine the fate.
 618 * Return 1 for exclude, 0 for include and -1 for undecided.
 619 */
 620int excluded_from_list(const char *pathname,
 621                       int pathlen, const char *basename, int *dtype,
 622                       struct exclude_list *el)
 623{
 624        int i;
 625
 626        if (!el->nr)
 627                return -1;      /* undefined */
 628
 629        for (i = el->nr - 1; 0 <= i; i--) {
 630                struct exclude *x = el->excludes[i];
 631                const char *exclude = x->pattern;
 632                int to_exclude = x->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
 633                int prefix = x->nowildcardlen;
 634
 635                if (x->flags & EXC_FLAG_MUSTBEDIR) {
 636                        if (*dtype == DT_UNKNOWN)
 637                                *dtype = get_dtype(NULL, pathname, pathlen);
 638                        if (*dtype != DT_DIR)
 639                                continue;
 640                }
 641
 642                if (x->flags & EXC_FLAG_NODIR) {
 643                        if (match_basename(basename,
 644                                           pathlen - (basename - pathname),
 645                                           exclude, prefix, x->patternlen,
 646                                           x->flags))
 647                                return to_exclude;
 648                        continue;
 649                }
 650
 651                assert(x->baselen == 0 || x->base[x->baselen - 1] == '/');
 652                if (match_pathname(pathname, pathlen,
 653                                   x->base, x->baselen ? x->baselen - 1 : 0,
 654                                   exclude, prefix, x->patternlen, x->flags))
 655                        return to_exclude;
 656        }
 657        return -1; /* undecided */
 658}
 659
 660static int excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
 661{
 662        int pathlen = strlen(pathname);
 663        int st;
 664        const char *basename = strrchr(pathname, '/');
 665        basename = (basename) ? basename+1 : pathname;
 666
 667        prep_exclude(dir, pathname, basename-pathname);
 668        for (st = EXC_CMDL; st <= EXC_FILE; st++) {
 669                switch (excluded_from_list(pathname, pathlen, basename,
 670                                           dtype_p, &dir->exclude_list[st])) {
 671                case 0:
 672                        return 0;
 673                case 1:
 674                        return 1;
 675                }
 676        }
 677        return 0;
 678}
 679
 680void path_exclude_check_init(struct path_exclude_check *check,
 681                             struct dir_struct *dir)
 682{
 683        check->dir = dir;
 684        strbuf_init(&check->path, 256);
 685}
 686
 687void path_exclude_check_clear(struct path_exclude_check *check)
 688{
 689        strbuf_release(&check->path);
 690}
 691
 692/*
 693 * Is this name excluded?  This is for a caller like show_files() that
 694 * do not honor directory hierarchy and iterate through paths that are
 695 * possibly in an ignored directory.
 696 *
 697 * A path to a directory known to be excluded is left in check->path to
 698 * optimize for repeated checks for files in the same excluded directory.
 699 */
 700int path_excluded(struct path_exclude_check *check,
 701                  const char *name, int namelen, int *dtype)
 702{
 703        int i;
 704        struct strbuf *path = &check->path;
 705
 706        /*
 707         * we allow the caller to pass namelen as an optimization; it
 708         * must match the length of the name, as we eventually call
 709         * excluded() on the whole name string.
 710         */
 711        if (namelen < 0)
 712                namelen = strlen(name);
 713
 714        if (path->len &&
 715            path->len <= namelen &&
 716            !memcmp(name, path->buf, path->len) &&
 717            (!name[path->len] || name[path->len] == '/'))
 718                return 1;
 719
 720        strbuf_setlen(path, 0);
 721        for (i = 0; name[i]; i++) {
 722                int ch = name[i];
 723
 724                if (ch == '/') {
 725                        int dt = DT_DIR;
 726                        if (excluded(check->dir, path->buf, &dt))
 727                                return 1;
 728                }
 729                strbuf_addch(path, ch);
 730        }
 731
 732        /* An entry in the index; cannot be a directory with subentries */
 733        strbuf_setlen(path, 0);
 734
 735        return excluded(check->dir, name, dtype);
 736}
 737
 738static struct dir_entry *dir_entry_new(const char *pathname, int len)
 739{
 740        struct dir_entry *ent;
 741
 742        ent = xmalloc(sizeof(*ent) + len + 1);
 743        ent->len = len;
 744        memcpy(ent->name, pathname, len);
 745        ent->name[len] = 0;
 746        return ent;
 747}
 748
 749static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
 750{
 751        if (cache_name_exists(pathname, len, ignore_case))
 752                return NULL;
 753
 754        ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
 755        return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
 756}
 757
 758struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
 759{
 760        if (!cache_name_is_other(pathname, len))
 761                return NULL;
 762
 763        ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
 764        return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
 765}
 766
 767enum exist_status {
 768        index_nonexistent = 0,
 769        index_directory,
 770        index_gitdir
 771};
 772
 773/*
 774 * Do not use the alphabetically stored index to look up
 775 * the directory name; instead, use the case insensitive
 776 * name hash.
 777 */
 778static enum exist_status directory_exists_in_index_icase(const char *dirname, int len)
 779{
 780        struct cache_entry *ce = index_name_exists(&the_index, dirname, len + 1, ignore_case);
 781        unsigned char endchar;
 782
 783        if (!ce)
 784                return index_nonexistent;
 785        endchar = ce->name[len];
 786
 787        /*
 788         * The cache_entry structure returned will contain this dirname
 789         * and possibly additional path components.
 790         */
 791        if (endchar == '/')
 792                return index_directory;
 793
 794        /*
 795         * If there are no additional path components, then this cache_entry
 796         * represents a submodule.  Submodules, despite being directories,
 797         * are stored in the cache without a closing slash.
 798         */
 799        if (!endchar && S_ISGITLINK(ce->ce_mode))
 800                return index_gitdir;
 801
 802        /* This should never be hit, but it exists just in case. */
 803        return index_nonexistent;
 804}
 805
 806/*
 807 * The index sorts alphabetically by entry name, which
 808 * means that a gitlink sorts as '\0' at the end, while
 809 * a directory (which is defined not as an entry, but as
 810 * the files it contains) will sort with the '/' at the
 811 * end.
 812 */
 813static enum exist_status directory_exists_in_index(const char *dirname, int len)
 814{
 815        int pos;
 816
 817        if (ignore_case)
 818                return directory_exists_in_index_icase(dirname, len);
 819
 820        pos = cache_name_pos(dirname, len);
 821        if (pos < 0)
 822                pos = -pos-1;
 823        while (pos < active_nr) {
 824                struct cache_entry *ce = active_cache[pos++];
 825                unsigned char endchar;
 826
 827                if (strncmp(ce->name, dirname, len))
 828                        break;
 829                endchar = ce->name[len];
 830                if (endchar > '/')
 831                        break;
 832                if (endchar == '/')
 833                        return index_directory;
 834                if (!endchar && S_ISGITLINK(ce->ce_mode))
 835                        return index_gitdir;
 836        }
 837        return index_nonexistent;
 838}
 839
 840/*
 841 * When we find a directory when traversing the filesystem, we
 842 * have three distinct cases:
 843 *
 844 *  - ignore it
 845 *  - see it as a directory
 846 *  - recurse into it
 847 *
 848 * and which one we choose depends on a combination of existing
 849 * git index contents and the flags passed into the directory
 850 * traversal routine.
 851 *
 852 * Case 1: If we *already* have entries in the index under that
 853 * directory name, we always recurse into the directory to see
 854 * all the files.
 855 *
 856 * Case 2: If we *already* have that directory name as a gitlink,
 857 * we always continue to see it as a gitlink, regardless of whether
 858 * there is an actual git directory there or not (it might not
 859 * be checked out as a subproject!)
 860 *
 861 * Case 3: if we didn't have it in the index previously, we
 862 * have a few sub-cases:
 863 *
 864 *  (a) if "show_other_directories" is true, we show it as
 865 *      just a directory, unless "hide_empty_directories" is
 866 *      also true and the directory is empty, in which case
 867 *      we just ignore it entirely.
 868 *  (b) if it looks like a git directory, and we don't have
 869 *      'no_gitlinks' set we treat it as a gitlink, and show it
 870 *      as a directory.
 871 *  (c) otherwise, we recurse into it.
 872 */
 873enum directory_treatment {
 874        show_directory,
 875        ignore_directory,
 876        recurse_into_directory
 877};
 878
 879static enum directory_treatment treat_directory(struct dir_struct *dir,
 880        const char *dirname, int len,
 881        const struct path_simplify *simplify)
 882{
 883        /* The "len-1" is to strip the final '/' */
 884        switch (directory_exists_in_index(dirname, len-1)) {
 885        case index_directory:
 886                return recurse_into_directory;
 887
 888        case index_gitdir:
 889                if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
 890                        return ignore_directory;
 891                return show_directory;
 892
 893        case index_nonexistent:
 894                if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
 895                        break;
 896                if (!(dir->flags & DIR_NO_GITLINKS)) {
 897                        unsigned char sha1[20];
 898                        if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
 899                                return show_directory;
 900                }
 901                return recurse_into_directory;
 902        }
 903
 904        /* This is the "show_other_directories" case */
 905        if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
 906                return show_directory;
 907        if (!read_directory_recursive(dir, dirname, len, 1, simplify))
 908                return ignore_directory;
 909        return show_directory;
 910}
 911
 912/*
 913 * This is an inexact early pruning of any recursive directory
 914 * reading - if the path cannot possibly be in the pathspec,
 915 * return true, and we'll skip it early.
 916 */
 917static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
 918{
 919        if (simplify) {
 920                for (;;) {
 921                        const char *match = simplify->path;
 922                        int len = simplify->len;
 923
 924                        if (!match)
 925                                break;
 926                        if (len > pathlen)
 927                                len = pathlen;
 928                        if (!memcmp(path, match, len))
 929                                return 0;
 930                        simplify++;
 931                }
 932                return 1;
 933        }
 934        return 0;
 935}
 936
 937/*
 938 * This function tells us whether an excluded path matches a
 939 * list of "interesting" pathspecs. That is, whether a path matched
 940 * by any of the pathspecs could possibly be ignored by excluding
 941 * the specified path. This can happen if:
 942 *
 943 *   1. the path is mentioned explicitly in the pathspec
 944 *
 945 *   2. the path is a directory prefix of some element in the
 946 *      pathspec
 947 */
 948static int exclude_matches_pathspec(const char *path, int len,
 949                const struct path_simplify *simplify)
 950{
 951        if (simplify) {
 952                for (; simplify->path; simplify++) {
 953                        if (len == simplify->len
 954                            && !memcmp(path, simplify->path, len))
 955                                return 1;
 956                        if (len < simplify->len
 957                            && simplify->path[len] == '/'
 958                            && !memcmp(path, simplify->path, len))
 959                                return 1;
 960                }
 961        }
 962        return 0;
 963}
 964
 965static int get_index_dtype(const char *path, int len)
 966{
 967        int pos;
 968        struct cache_entry *ce;
 969
 970        ce = cache_name_exists(path, len, 0);
 971        if (ce) {
 972                if (!ce_uptodate(ce))
 973                        return DT_UNKNOWN;
 974                if (S_ISGITLINK(ce->ce_mode))
 975                        return DT_DIR;
 976                /*
 977                 * Nobody actually cares about the
 978                 * difference between DT_LNK and DT_REG
 979                 */
 980                return DT_REG;
 981        }
 982
 983        /* Try to look it up as a directory */
 984        pos = cache_name_pos(path, len);
 985        if (pos >= 0)
 986                return DT_UNKNOWN;
 987        pos = -pos-1;
 988        while (pos < active_nr) {
 989                ce = active_cache[pos++];
 990                if (strncmp(ce->name, path, len))
 991                        break;
 992                if (ce->name[len] > '/')
 993                        break;
 994                if (ce->name[len] < '/')
 995                        continue;
 996                if (!ce_uptodate(ce))
 997                        break;  /* continue? */
 998                return DT_DIR;
 999        }
1000        return DT_UNKNOWN;
1001}
1002
1003static int get_dtype(struct dirent *de, const char *path, int len)
1004{
1005        int dtype = de ? DTYPE(de) : DT_UNKNOWN;
1006        struct stat st;
1007
1008        if (dtype != DT_UNKNOWN)
1009                return dtype;
1010        dtype = get_index_dtype(path, len);
1011        if (dtype != DT_UNKNOWN)
1012                return dtype;
1013        if (lstat(path, &st))
1014                return dtype;
1015        if (S_ISREG(st.st_mode))
1016                return DT_REG;
1017        if (S_ISDIR(st.st_mode))
1018                return DT_DIR;
1019        if (S_ISLNK(st.st_mode))
1020                return DT_LNK;
1021        return dtype;
1022}
1023
1024enum path_treatment {
1025        path_ignored,
1026        path_handled,
1027        path_recurse
1028};
1029
1030static enum path_treatment treat_one_path(struct dir_struct *dir,
1031                                          struct strbuf *path,
1032                                          const struct path_simplify *simplify,
1033                                          int dtype, struct dirent *de)
1034{
1035        int exclude = excluded(dir, path->buf, &dtype);
1036        if (exclude && (dir->flags & DIR_COLLECT_IGNORED)
1037            && exclude_matches_pathspec(path->buf, path->len, simplify))
1038                dir_add_ignored(dir, path->buf, path->len);
1039
1040        /*
1041         * Excluded? If we don't explicitly want to show
1042         * ignored files, ignore it
1043         */
1044        if (exclude && !(dir->flags & DIR_SHOW_IGNORED))
1045                return path_ignored;
1046
1047        if (dtype == DT_UNKNOWN)
1048                dtype = get_dtype(de, path->buf, path->len);
1049
1050        /*
1051         * Do we want to see just the ignored files?
1052         * We still need to recurse into directories,
1053         * even if we don't ignore them, since the
1054         * directory may contain files that we do..
1055         */
1056        if (!exclude && (dir->flags & DIR_SHOW_IGNORED)) {
1057                if (dtype != DT_DIR)
1058                        return path_ignored;
1059        }
1060
1061        switch (dtype) {
1062        default:
1063                return path_ignored;
1064        case DT_DIR:
1065                strbuf_addch(path, '/');
1066                switch (treat_directory(dir, path->buf, path->len, simplify)) {
1067                case show_directory:
1068                        if (exclude != !!(dir->flags
1069                                          & DIR_SHOW_IGNORED))
1070                                return path_ignored;
1071                        break;
1072                case recurse_into_directory:
1073                        return path_recurse;
1074                case ignore_directory:
1075                        return path_ignored;
1076                }
1077                break;
1078        case DT_REG:
1079        case DT_LNK:
1080                break;
1081        }
1082        return path_handled;
1083}
1084
1085static enum path_treatment treat_path(struct dir_struct *dir,
1086                                      struct dirent *de,
1087                                      struct strbuf *path,
1088                                      int baselen,
1089                                      const struct path_simplify *simplify)
1090{
1091        int dtype;
1092
1093        if (is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name, ".git"))
1094                return path_ignored;
1095        strbuf_setlen(path, baselen);
1096        strbuf_addstr(path, de->d_name);
1097        if (simplify_away(path->buf, path->len, simplify))
1098                return path_ignored;
1099
1100        dtype = DTYPE(de);
1101        return treat_one_path(dir, path, simplify, dtype, de);
1102}
1103
1104/*
1105 * Read a directory tree. We currently ignore anything but
1106 * directories, regular files and symlinks. That's because git
1107 * doesn't handle them at all yet. Maybe that will change some
1108 * day.
1109 *
1110 * Also, we ignore the name ".git" (even if it is not a directory).
1111 * That likely will not change.
1112 */
1113static int read_directory_recursive(struct dir_struct *dir,
1114                                    const char *base, int baselen,
1115                                    int check_only,
1116                                    const struct path_simplify *simplify)
1117{
1118        DIR *fdir;
1119        int contents = 0;
1120        struct dirent *de;
1121        struct strbuf path = STRBUF_INIT;
1122
1123        strbuf_add(&path, base, baselen);
1124
1125        fdir = opendir(path.len ? path.buf : ".");
1126        if (!fdir)
1127                goto out;
1128
1129        while ((de = readdir(fdir)) != NULL) {
1130                switch (treat_path(dir, de, &path, baselen, simplify)) {
1131                case path_recurse:
1132                        contents += read_directory_recursive(dir, path.buf,
1133                                                             path.len, 0,
1134                                                             simplify);
1135                        continue;
1136                case path_ignored:
1137                        continue;
1138                case path_handled:
1139                        break;
1140                }
1141                contents++;
1142                if (check_only)
1143                        break;
1144                dir_add_name(dir, path.buf, path.len);
1145        }
1146        closedir(fdir);
1147 out:
1148        strbuf_release(&path);
1149
1150        return contents;
1151}
1152
1153static int cmp_name(const void *p1, const void *p2)
1154{
1155        const struct dir_entry *e1 = *(const struct dir_entry **)p1;
1156        const struct dir_entry *e2 = *(const struct dir_entry **)p2;
1157
1158        return cache_name_compare(e1->name, e1->len,
1159                                  e2->name, e2->len);
1160}
1161
1162static struct path_simplify *create_simplify(const char **pathspec)
1163{
1164        int nr, alloc = 0;
1165        struct path_simplify *simplify = NULL;
1166
1167        if (!pathspec)
1168                return NULL;
1169
1170        for (nr = 0 ; ; nr++) {
1171                const char *match;
1172                if (nr >= alloc) {
1173                        alloc = alloc_nr(alloc);
1174                        simplify = xrealloc(simplify, alloc * sizeof(*simplify));
1175                }
1176                match = *pathspec++;
1177                if (!match)
1178                        break;
1179                simplify[nr].path = match;
1180                simplify[nr].len = simple_length(match);
1181        }
1182        simplify[nr].path = NULL;
1183        simplify[nr].len = 0;
1184        return simplify;
1185}
1186
1187static void free_simplify(struct path_simplify *simplify)
1188{
1189        free(simplify);
1190}
1191
1192static int treat_leading_path(struct dir_struct *dir,
1193                              const char *path, int len,
1194                              const struct path_simplify *simplify)
1195{
1196        struct strbuf sb = STRBUF_INIT;
1197        int baselen, rc = 0;
1198        const char *cp;
1199
1200        while (len && path[len - 1] == '/')
1201                len--;
1202        if (!len)
1203                return 1;
1204        baselen = 0;
1205        while (1) {
1206                cp = path + baselen + !!baselen;
1207                cp = memchr(cp, '/', path + len - cp);
1208                if (!cp)
1209                        baselen = len;
1210                else
1211                        baselen = cp - path;
1212                strbuf_setlen(&sb, 0);
1213                strbuf_add(&sb, path, baselen);
1214                if (!is_directory(sb.buf))
1215                        break;
1216                if (simplify_away(sb.buf, sb.len, simplify))
1217                        break;
1218                if (treat_one_path(dir, &sb, simplify,
1219                                   DT_DIR, NULL) == path_ignored)
1220                        break; /* do not recurse into it */
1221                if (len <= baselen) {
1222                        rc = 1;
1223                        break; /* finished checking */
1224                }
1225        }
1226        strbuf_release(&sb);
1227        return rc;
1228}
1229
1230int read_directory(struct dir_struct *dir, const char *path, int len, const char **pathspec)
1231{
1232        struct path_simplify *simplify;
1233
1234        if (has_symlink_leading_path(path, len))
1235                return dir->nr;
1236
1237        simplify = create_simplify(pathspec);
1238        if (!len || treat_leading_path(dir, path, len, simplify))
1239                read_directory_recursive(dir, path, len, 0, simplify);
1240        free_simplify(simplify);
1241        qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
1242        qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
1243        return dir->nr;
1244}
1245
1246int file_exists(const char *f)
1247{
1248        struct stat sb;
1249        return lstat(f, &sb) == 0;
1250}
1251
1252/*
1253 * Given two normalized paths (a trailing slash is ok), if subdir is
1254 * outside dir, return -1.  Otherwise return the offset in subdir that
1255 * can be used as relative path to dir.
1256 */
1257int dir_inside_of(const char *subdir, const char *dir)
1258{
1259        int offset = 0;
1260
1261        assert(dir && subdir && *dir && *subdir);
1262
1263        while (*dir && *subdir && *dir == *subdir) {
1264                dir++;
1265                subdir++;
1266                offset++;
1267        }
1268
1269        /* hel[p]/me vs hel[l]/yeah */
1270        if (*dir && *subdir)
1271                return -1;
1272
1273        if (!*subdir)
1274                return !*dir ? offset : -1; /* same dir */
1275
1276        /* foo/[b]ar vs foo/[] */
1277        if (is_dir_sep(dir[-1]))
1278                return is_dir_sep(subdir[-1]) ? offset : -1;
1279
1280        /* foo[/]bar vs foo[] */
1281        return is_dir_sep(*subdir) ? offset + 1 : -1;
1282}
1283
1284int is_inside_dir(const char *dir)
1285{
1286        char cwd[PATH_MAX];
1287        if (!dir)
1288                return 0;
1289        if (!getcwd(cwd, sizeof(cwd)))
1290                die_errno("can't find the current directory");
1291        return dir_inside_of(cwd, dir) >= 0;
1292}
1293
1294int is_empty_dir(const char *path)
1295{
1296        DIR *dir = opendir(path);
1297        struct dirent *e;
1298        int ret = 1;
1299
1300        if (!dir)
1301                return 0;
1302
1303        while ((e = readdir(dir)) != NULL)
1304                if (!is_dot_or_dotdot(e->d_name)) {
1305                        ret = 0;
1306                        break;
1307                }
1308
1309        closedir(dir);
1310        return ret;
1311}
1312
1313static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
1314{
1315        DIR *dir;
1316        struct dirent *e;
1317        int ret = 0, original_len = path->len, len, kept_down = 0;
1318        int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
1319        int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
1320        unsigned char submodule_head[20];
1321
1322        if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
1323            !resolve_gitlink_ref(path->buf, "HEAD", submodule_head)) {
1324                /* Do not descend and nuke a nested git work tree. */
1325                if (kept_up)
1326                        *kept_up = 1;
1327                return 0;
1328        }
1329
1330        flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
1331        dir = opendir(path->buf);
1332        if (!dir) {
1333                /* an empty dir could be removed even if it is unreadble */
1334                if (!keep_toplevel)
1335                        return rmdir(path->buf);
1336                else
1337                        return -1;
1338        }
1339        if (path->buf[original_len - 1] != '/')
1340                strbuf_addch(path, '/');
1341
1342        len = path->len;
1343        while ((e = readdir(dir)) != NULL) {
1344                struct stat st;
1345                if (is_dot_or_dotdot(e->d_name))
1346                        continue;
1347
1348                strbuf_setlen(path, len);
1349                strbuf_addstr(path, e->d_name);
1350                if (lstat(path->buf, &st))
1351                        ; /* fall thru */
1352                else if (S_ISDIR(st.st_mode)) {
1353                        if (!remove_dir_recurse(path, flag, &kept_down))
1354                                continue; /* happy */
1355                } else if (!only_empty && !unlink(path->buf))
1356                        continue; /* happy, too */
1357
1358                /* path too long, stat fails, or non-directory still exists */
1359                ret = -1;
1360                break;
1361        }
1362        closedir(dir);
1363
1364        strbuf_setlen(path, original_len);
1365        if (!ret && !keep_toplevel && !kept_down)
1366                ret = rmdir(path->buf);
1367        else if (kept_up)
1368                /*
1369                 * report the uplevel that it is not an error that we
1370                 * did not rmdir() our directory.
1371                 */
1372                *kept_up = !ret;
1373        return ret;
1374}
1375
1376int remove_dir_recursively(struct strbuf *path, int flag)
1377{
1378        return remove_dir_recurse(path, flag, NULL);
1379}
1380
1381void setup_standard_excludes(struct dir_struct *dir)
1382{
1383        const char *path;
1384        char *xdg_path;
1385
1386        dir->exclude_per_dir = ".gitignore";
1387        path = git_path("info/exclude");
1388        if (!excludes_file) {
1389                home_config_paths(NULL, &xdg_path, "ignore");
1390                excludes_file = xdg_path;
1391        }
1392        if (!access_or_warn(path, R_OK))
1393                add_excludes_from_file(dir, path);
1394        if (excludes_file && !access_or_warn(excludes_file, R_OK))
1395                add_excludes_from_file(dir, excludes_file);
1396}
1397
1398int remove_path(const char *name)
1399{
1400        char *slash;
1401
1402        if (unlink(name) && errno != ENOENT)
1403                return -1;
1404
1405        slash = strrchr(name, '/');
1406        if (slash) {
1407                char *dirs = xstrdup(name);
1408                slash = dirs + (slash - name);
1409                do {
1410                        *slash = '\0';
1411                } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
1412                free(dirs);
1413        }
1414        return 0;
1415}
1416
1417static int pathspec_item_cmp(const void *a_, const void *b_)
1418{
1419        struct pathspec_item *a, *b;
1420
1421        a = (struct pathspec_item *)a_;
1422        b = (struct pathspec_item *)b_;
1423        return strcmp(a->match, b->match);
1424}
1425
1426int init_pathspec(struct pathspec *pathspec, const char **paths)
1427{
1428        const char **p = paths;
1429        int i;
1430
1431        memset(pathspec, 0, sizeof(*pathspec));
1432        if (!p)
1433                return 0;
1434        while (*p)
1435                p++;
1436        pathspec->raw = paths;
1437        pathspec->nr = p - paths;
1438        if (!pathspec->nr)
1439                return 0;
1440
1441        pathspec->items = xmalloc(sizeof(struct pathspec_item)*pathspec->nr);
1442        for (i = 0; i < pathspec->nr; i++) {
1443                struct pathspec_item *item = pathspec->items+i;
1444                const char *path = paths[i];
1445
1446                item->match = path;
1447                item->len = strlen(path);
1448                item->nowildcard_len = simple_length(path);
1449                if (item->nowildcard_len < item->len)
1450                        pathspec->has_wildcard = 1;
1451        }
1452
1453        qsort(pathspec->items, pathspec->nr,
1454              sizeof(struct pathspec_item), pathspec_item_cmp);
1455
1456        return 0;
1457}
1458
1459void free_pathspec(struct pathspec *pathspec)
1460{
1461        free(pathspec->items);
1462        pathspec->items = NULL;
1463}