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