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