dir.con commit Merge branch 'bg/xcalloc-nmemb-then-size' (a634a6d)
   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        char *buf, *entry;
 542
 543        fd = open(fname, O_RDONLY);
 544        if (fd < 0 || fstat(fd, &st) < 0) {
 545                if (errno != ENOENT)
 546                        warn_on_inaccessible(fname);
 547                if (0 <= fd)
 548                        close(fd);
 549                if (!check_index ||
 550                    (buf = read_skip_worktree_file_from_index(fname, &size)) == NULL)
 551                        return -1;
 552                if (size == 0) {
 553                        free(buf);
 554                        return 0;
 555                }
 556                if (buf[size-1] != '\n') {
 557                        buf = xrealloc(buf, size+1);
 558                        buf[size++] = '\n';
 559                }
 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        entry = buf;
 579        for (i = 0; i < size; i++) {
 580                if (buf[i] == '\n') {
 581                        if (entry != buf + i && entry[0] != '#') {
 582                                buf[i - (i && buf[i-1] == '\r')] = 0;
 583                                trim_trailing_spaces(entry);
 584                                add_exclude(entry, base, baselen, el, lineno);
 585                        }
 586                        lineno++;
 587                        entry = buf + i + 1;
 588                }
 589        }
 590        return 0;
 591}
 592
 593struct exclude_list *add_exclude_list(struct dir_struct *dir,
 594                                      int group_type, const char *src)
 595{
 596        struct exclude_list *el;
 597        struct exclude_list_group *group;
 598
 599        group = &dir->exclude_list_group[group_type];
 600        ALLOC_GROW(group->el, group->nr + 1, group->alloc);
 601        el = &group->el[group->nr++];
 602        memset(el, 0, sizeof(*el));
 603        el->src = src;
 604        return el;
 605}
 606
 607/*
 608 * Used to set up core.excludesfile and .git/info/exclude lists.
 609 */
 610void add_excludes_from_file(struct dir_struct *dir, const char *fname)
 611{
 612        struct exclude_list *el;
 613        el = add_exclude_list(dir, EXC_FILE, fname);
 614        if (add_excludes_from_file_to_list(fname, "", 0, el, 0) < 0)
 615                die("cannot use %s as an exclude file", fname);
 616}
 617
 618int match_basename(const char *basename, int basenamelen,
 619                   const char *pattern, int prefix, int patternlen,
 620                   int flags)
 621{
 622        if (prefix == patternlen) {
 623                if (patternlen == basenamelen &&
 624                    !strncmp_icase(pattern, basename, basenamelen))
 625                        return 1;
 626        } else if (flags & EXC_FLAG_ENDSWITH) {
 627                /* "*literal" matching against "fooliteral" */
 628                if (patternlen - 1 <= basenamelen &&
 629                    !strncmp_icase(pattern + 1,
 630                                   basename + basenamelen - (patternlen - 1),
 631                                   patternlen - 1))
 632                        return 1;
 633        } else {
 634                if (fnmatch_icase_mem(pattern, patternlen,
 635                                      basename, basenamelen,
 636                                      0) == 0)
 637                        return 1;
 638        }
 639        return 0;
 640}
 641
 642int match_pathname(const char *pathname, int pathlen,
 643                   const char *base, int baselen,
 644                   const char *pattern, int prefix, int patternlen,
 645                   int flags)
 646{
 647        const char *name;
 648        int namelen;
 649
 650        /*
 651         * match with FNM_PATHNAME; the pattern has base implicitly
 652         * in front of it.
 653         */
 654        if (*pattern == '/') {
 655                pattern++;
 656                patternlen--;
 657                prefix--;
 658        }
 659
 660        /*
 661         * baselen does not count the trailing slash. base[] may or
 662         * may not end with a trailing slash though.
 663         */
 664        if (pathlen < baselen + 1 ||
 665            (baselen && pathname[baselen] != '/') ||
 666            strncmp_icase(pathname, base, baselen))
 667                return 0;
 668
 669        namelen = baselen ? pathlen - baselen - 1 : pathlen;
 670        name = pathname + pathlen - namelen;
 671
 672        if (prefix) {
 673                /*
 674                 * if the non-wildcard part is longer than the
 675                 * remaining pathname, surely it cannot match.
 676                 */
 677                if (prefix > namelen)
 678                        return 0;
 679
 680                if (strncmp_icase(pattern, name, prefix))
 681                        return 0;
 682                pattern += prefix;
 683                patternlen -= prefix;
 684                name    += prefix;
 685                namelen -= prefix;
 686
 687                /*
 688                 * If the whole pattern did not have a wildcard,
 689                 * then our prefix match is all we need; we
 690                 * do not need to call fnmatch at all.
 691                 */
 692                if (!patternlen && !namelen)
 693                        return 1;
 694        }
 695
 696        return fnmatch_icase_mem(pattern, patternlen,
 697                                 name, namelen,
 698                                 WM_PATHNAME) == 0;
 699}
 700
 701/*
 702 * Scan the given exclude list in reverse to see whether pathname
 703 * should be ignored.  The first match (i.e. the last on the list), if
 704 * any, determines the fate.  Returns the exclude_list element which
 705 * matched, or NULL for undecided.
 706 */
 707static struct exclude *last_exclude_matching_from_list(const char *pathname,
 708                                                       int pathlen,
 709                                                       const char *basename,
 710                                                       int *dtype,
 711                                                       struct exclude_list *el)
 712{
 713        int i;
 714
 715        if (!el->nr)
 716                return NULL;    /* undefined */
 717
 718        for (i = el->nr - 1; 0 <= i; i--) {
 719                struct exclude *x = el->excludes[i];
 720                const char *exclude = x->pattern;
 721                int prefix = x->nowildcardlen;
 722
 723                if (x->flags & EXC_FLAG_MUSTBEDIR) {
 724                        if (*dtype == DT_UNKNOWN)
 725                                *dtype = get_dtype(NULL, pathname, pathlen);
 726                        if (*dtype != DT_DIR)
 727                                continue;
 728                }
 729
 730                if (x->flags & EXC_FLAG_NODIR) {
 731                        if (match_basename(basename,
 732                                           pathlen - (basename - pathname),
 733                                           exclude, prefix, x->patternlen,
 734                                           x->flags))
 735                                return x;
 736                        continue;
 737                }
 738
 739                assert(x->baselen == 0 || x->base[x->baselen - 1] == '/');
 740                if (match_pathname(pathname, pathlen,
 741                                   x->base, x->baselen ? x->baselen - 1 : 0,
 742                                   exclude, prefix, x->patternlen, x->flags))
 743                        return x;
 744        }
 745        return NULL; /* undecided */
 746}
 747
 748/*
 749 * Scan the list and let the last match determine the fate.
 750 * Return 1 for exclude, 0 for include and -1 for undecided.
 751 */
 752int is_excluded_from_list(const char *pathname,
 753                          int pathlen, const char *basename, int *dtype,
 754                          struct exclude_list *el)
 755{
 756        struct exclude *exclude;
 757        exclude = last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el);
 758        if (exclude)
 759                return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
 760        return -1; /* undecided */
 761}
 762
 763static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir,
 764                const char *pathname, int pathlen, const char *basename,
 765                int *dtype_p)
 766{
 767        int i, j;
 768        struct exclude_list_group *group;
 769        struct exclude *exclude;
 770        for (i = EXC_CMDL; i <= EXC_FILE; i++) {
 771                group = &dir->exclude_list_group[i];
 772                for (j = group->nr - 1; j >= 0; j--) {
 773                        exclude = last_exclude_matching_from_list(
 774                                pathname, pathlen, basename, dtype_p,
 775                                &group->el[j]);
 776                        if (exclude)
 777                                return exclude;
 778                }
 779        }
 780        return NULL;
 781}
 782
 783/*
 784 * Loads the per-directory exclude list for the substring of base
 785 * which has a char length of baselen.
 786 */
 787static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
 788{
 789        struct exclude_list_group *group;
 790        struct exclude_list *el;
 791        struct exclude_stack *stk = NULL;
 792        int current;
 793
 794        group = &dir->exclude_list_group[EXC_DIRS];
 795
 796        /* Pop the exclude lists from the EXCL_DIRS exclude_list_group
 797         * which originate from directories not in the prefix of the
 798         * path being checked. */
 799        while ((stk = dir->exclude_stack) != NULL) {
 800                if (stk->baselen <= baselen &&
 801                    !strncmp(dir->basebuf, base, stk->baselen))
 802                        break;
 803                el = &group->el[dir->exclude_stack->exclude_ix];
 804                dir->exclude_stack = stk->prev;
 805                dir->exclude = NULL;
 806                free((char *)el->src); /* see strdup() below */
 807                clear_exclude_list(el);
 808                free(stk);
 809                group->nr--;
 810        }
 811
 812        /* Skip traversing into sub directories if the parent is excluded */
 813        if (dir->exclude)
 814                return;
 815
 816        /* Read from the parent directories and push them down. */
 817        current = stk ? stk->baselen : -1;
 818        while (current < baselen) {
 819                struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
 820                const char *cp;
 821
 822                if (current < 0) {
 823                        cp = base;
 824                        current = 0;
 825                }
 826                else {
 827                        cp = strchr(base + current + 1, '/');
 828                        if (!cp)
 829                                die("oops in prep_exclude");
 830                        cp++;
 831                }
 832                stk->prev = dir->exclude_stack;
 833                stk->baselen = cp - base;
 834                stk->exclude_ix = group->nr;
 835                el = add_exclude_list(dir, EXC_DIRS, NULL);
 836                memcpy(dir->basebuf + current, base + current,
 837                       stk->baselen - current);
 838
 839                /* Abort if the directory is excluded */
 840                if (stk->baselen) {
 841                        int dt = DT_DIR;
 842                        dir->basebuf[stk->baselen - 1] = 0;
 843                        dir->exclude = last_exclude_matching_from_lists(dir,
 844                                dir->basebuf, stk->baselen - 1,
 845                                dir->basebuf + current, &dt);
 846                        dir->basebuf[stk->baselen - 1] = '/';
 847                        if (dir->exclude &&
 848                            dir->exclude->flags & EXC_FLAG_NEGATIVE)
 849                                dir->exclude = NULL;
 850                        if (dir->exclude) {
 851                                dir->basebuf[stk->baselen] = 0;
 852                                dir->exclude_stack = stk;
 853                                return;
 854                        }
 855                }
 856
 857                /* Try to read per-directory file unless path is too long */
 858                if (dir->exclude_per_dir &&
 859                    stk->baselen + strlen(dir->exclude_per_dir) < PATH_MAX) {
 860                        strcpy(dir->basebuf + stk->baselen,
 861                                        dir->exclude_per_dir);
 862                        /*
 863                         * dir->basebuf gets reused by the traversal, but we
 864                         * need fname to remain unchanged to ensure the src
 865                         * member of each struct exclude correctly
 866                         * back-references its source file.  Other invocations
 867                         * of add_exclude_list provide stable strings, so we
 868                         * strdup() and free() here in the caller.
 869                         */
 870                        el->src = strdup(dir->basebuf);
 871                        add_excludes_from_file_to_list(dir->basebuf,
 872                                        dir->basebuf, stk->baselen, el, 1);
 873                }
 874                dir->exclude_stack = stk;
 875                current = stk->baselen;
 876        }
 877        dir->basebuf[baselen] = '\0';
 878}
 879
 880/*
 881 * Loads the exclude lists for the directory containing pathname, then
 882 * scans all exclude lists to determine whether pathname is excluded.
 883 * Returns the exclude_list element which matched, or NULL for
 884 * undecided.
 885 */
 886struct exclude *last_exclude_matching(struct dir_struct *dir,
 887                                             const char *pathname,
 888                                             int *dtype_p)
 889{
 890        int pathlen = strlen(pathname);
 891        const char *basename = strrchr(pathname, '/');
 892        basename = (basename) ? basename+1 : pathname;
 893
 894        prep_exclude(dir, pathname, basename-pathname);
 895
 896        if (dir->exclude)
 897                return dir->exclude;
 898
 899        return last_exclude_matching_from_lists(dir, pathname, pathlen,
 900                        basename, dtype_p);
 901}
 902
 903/*
 904 * Loads the exclude lists for the directory containing pathname, then
 905 * scans all exclude lists to determine whether pathname is excluded.
 906 * Returns 1 if true, otherwise 0.
 907 */
 908int is_excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
 909{
 910        struct exclude *exclude =
 911                last_exclude_matching(dir, pathname, dtype_p);
 912        if (exclude)
 913                return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
 914        return 0;
 915}
 916
 917static struct dir_entry *dir_entry_new(const char *pathname, int len)
 918{
 919        struct dir_entry *ent;
 920
 921        ent = xmalloc(sizeof(*ent) + len + 1);
 922        ent->len = len;
 923        memcpy(ent->name, pathname, len);
 924        ent->name[len] = 0;
 925        return ent;
 926}
 927
 928static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
 929{
 930        if (cache_file_exists(pathname, len, ignore_case))
 931                return NULL;
 932
 933        ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
 934        return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
 935}
 936
 937struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
 938{
 939        if (!cache_name_is_other(pathname, len))
 940                return NULL;
 941
 942        ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
 943        return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
 944}
 945
 946enum exist_status {
 947        index_nonexistent = 0,
 948        index_directory,
 949        index_gitdir
 950};
 951
 952/*
 953 * Do not use the alphabetically sorted index to look up
 954 * the directory name; instead, use the case insensitive
 955 * directory hash.
 956 */
 957static enum exist_status directory_exists_in_index_icase(const char *dirname, int len)
 958{
 959        const struct cache_entry *ce = cache_dir_exists(dirname, len);
 960        unsigned char endchar;
 961
 962        if (!ce)
 963                return index_nonexistent;
 964        endchar = ce->name[len];
 965
 966        /*
 967         * The cache_entry structure returned will contain this dirname
 968         * and possibly additional path components.
 969         */
 970        if (endchar == '/')
 971                return index_directory;
 972
 973        /*
 974         * If there are no additional path components, then this cache_entry
 975         * represents a submodule.  Submodules, despite being directories,
 976         * are stored in the cache without a closing slash.
 977         */
 978        if (!endchar && S_ISGITLINK(ce->ce_mode))
 979                return index_gitdir;
 980
 981        /* This should never be hit, but it exists just in case. */
 982        return index_nonexistent;
 983}
 984
 985/*
 986 * The index sorts alphabetically by entry name, which
 987 * means that a gitlink sorts as '\0' at the end, while
 988 * a directory (which is defined not as an entry, but as
 989 * the files it contains) will sort with the '/' at the
 990 * end.
 991 */
 992static enum exist_status directory_exists_in_index(const char *dirname, int len)
 993{
 994        int pos;
 995
 996        if (ignore_case)
 997                return directory_exists_in_index_icase(dirname, len);
 998
 999        pos = cache_name_pos(dirname, len);
1000        if (pos < 0)
1001                pos = -pos-1;
1002        while (pos < active_nr) {
1003                const struct cache_entry *ce = active_cache[pos++];
1004                unsigned char endchar;
1005
1006                if (strncmp(ce->name, dirname, len))
1007                        break;
1008                endchar = ce->name[len];
1009                if (endchar > '/')
1010                        break;
1011                if (endchar == '/')
1012                        return index_directory;
1013                if (!endchar && S_ISGITLINK(ce->ce_mode))
1014                        return index_gitdir;
1015        }
1016        return index_nonexistent;
1017}
1018
1019/*
1020 * When we find a directory when traversing the filesystem, we
1021 * have three distinct cases:
1022 *
1023 *  - ignore it
1024 *  - see it as a directory
1025 *  - recurse into it
1026 *
1027 * and which one we choose depends on a combination of existing
1028 * git index contents and the flags passed into the directory
1029 * traversal routine.
1030 *
1031 * Case 1: If we *already* have entries in the index under that
1032 * directory name, we always recurse into the directory to see
1033 * all the files.
1034 *
1035 * Case 2: If we *already* have that directory name as a gitlink,
1036 * we always continue to see it as a gitlink, regardless of whether
1037 * there is an actual git directory there or not (it might not
1038 * be checked out as a subproject!)
1039 *
1040 * Case 3: if we didn't have it in the index previously, we
1041 * have a few sub-cases:
1042 *
1043 *  (a) if "show_other_directories" is true, we show it as
1044 *      just a directory, unless "hide_empty_directories" is
1045 *      also true, in which case we need to check if it contains any
1046 *      untracked and / or ignored files.
1047 *  (b) if it looks like a git directory, and we don't have
1048 *      'no_gitlinks' set we treat it as a gitlink, and show it
1049 *      as a directory.
1050 *  (c) otherwise, we recurse into it.
1051 */
1052static enum path_treatment treat_directory(struct dir_struct *dir,
1053        const char *dirname, int len, int exclude,
1054        const struct path_simplify *simplify)
1055{
1056        /* The "len-1" is to strip the final '/' */
1057        switch (directory_exists_in_index(dirname, len-1)) {
1058        case index_directory:
1059                return path_recurse;
1060
1061        case index_gitdir:
1062                return path_none;
1063
1064        case index_nonexistent:
1065                if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
1066                        break;
1067                if (!(dir->flags & DIR_NO_GITLINKS)) {
1068                        unsigned char sha1[20];
1069                        if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
1070                                return path_untracked;
1071                }
1072                return path_recurse;
1073        }
1074
1075        /* This is the "show_other_directories" case */
1076
1077        if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1078                return exclude ? path_excluded : path_untracked;
1079
1080        return read_directory_recursive(dir, dirname, len, 1, simplify);
1081}
1082
1083/*
1084 * This is an inexact early pruning of any recursive directory
1085 * reading - if the path cannot possibly be in the pathspec,
1086 * return true, and we'll skip it early.
1087 */
1088static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
1089{
1090        if (simplify) {
1091                for (;;) {
1092                        const char *match = simplify->path;
1093                        int len = simplify->len;
1094
1095                        if (!match)
1096                                break;
1097                        if (len > pathlen)
1098                                len = pathlen;
1099                        if (!memcmp(path, match, len))
1100                                return 0;
1101                        simplify++;
1102                }
1103                return 1;
1104        }
1105        return 0;
1106}
1107
1108/*
1109 * This function tells us whether an excluded path matches a
1110 * list of "interesting" pathspecs. That is, whether a path matched
1111 * by any of the pathspecs could possibly be ignored by excluding
1112 * the specified path. This can happen if:
1113 *
1114 *   1. the path is mentioned explicitly in the pathspec
1115 *
1116 *   2. the path is a directory prefix of some element in the
1117 *      pathspec
1118 */
1119static int exclude_matches_pathspec(const char *path, int len,
1120                const struct path_simplify *simplify)
1121{
1122        if (simplify) {
1123                for (; simplify->path; simplify++) {
1124                        if (len == simplify->len
1125                            && !memcmp(path, simplify->path, len))
1126                                return 1;
1127                        if (len < simplify->len
1128                            && simplify->path[len] == '/'
1129                            && !memcmp(path, simplify->path, len))
1130                                return 1;
1131                }
1132        }
1133        return 0;
1134}
1135
1136static int get_index_dtype(const char *path, int len)
1137{
1138        int pos;
1139        const struct cache_entry *ce;
1140
1141        ce = cache_file_exists(path, len, 0);
1142        if (ce) {
1143                if (!ce_uptodate(ce))
1144                        return DT_UNKNOWN;
1145                if (S_ISGITLINK(ce->ce_mode))
1146                        return DT_DIR;
1147                /*
1148                 * Nobody actually cares about the
1149                 * difference between DT_LNK and DT_REG
1150                 */
1151                return DT_REG;
1152        }
1153
1154        /* Try to look it up as a directory */
1155        pos = cache_name_pos(path, len);
1156        if (pos >= 0)
1157                return DT_UNKNOWN;
1158        pos = -pos-1;
1159        while (pos < active_nr) {
1160                ce = active_cache[pos++];
1161                if (strncmp(ce->name, path, len))
1162                        break;
1163                if (ce->name[len] > '/')
1164                        break;
1165                if (ce->name[len] < '/')
1166                        continue;
1167                if (!ce_uptodate(ce))
1168                        break;  /* continue? */
1169                return DT_DIR;
1170        }
1171        return DT_UNKNOWN;
1172}
1173
1174static int get_dtype(struct dirent *de, const char *path, int len)
1175{
1176        int dtype = de ? DTYPE(de) : DT_UNKNOWN;
1177        struct stat st;
1178
1179        if (dtype != DT_UNKNOWN)
1180                return dtype;
1181        dtype = get_index_dtype(path, len);
1182        if (dtype != DT_UNKNOWN)
1183                return dtype;
1184        if (lstat(path, &st))
1185                return dtype;
1186        if (S_ISREG(st.st_mode))
1187                return DT_REG;
1188        if (S_ISDIR(st.st_mode))
1189                return DT_DIR;
1190        if (S_ISLNK(st.st_mode))
1191                return DT_LNK;
1192        return dtype;
1193}
1194
1195static enum path_treatment treat_one_path(struct dir_struct *dir,
1196                                          struct strbuf *path,
1197                                          const struct path_simplify *simplify,
1198                                          int dtype, struct dirent *de)
1199{
1200        int exclude;
1201        int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);
1202
1203        if (dtype == DT_UNKNOWN)
1204                dtype = get_dtype(de, path->buf, path->len);
1205
1206        /* Always exclude indexed files */
1207        if (dtype != DT_DIR && has_path_in_index)
1208                return path_none;
1209
1210        /*
1211         * When we are looking at a directory P in the working tree,
1212         * there are three cases:
1213         *
1214         * (1) P exists in the index.  Everything inside the directory P in
1215         * the working tree needs to go when P is checked out from the
1216         * index.
1217         *
1218         * (2) P does not exist in the index, but there is P/Q in the index.
1219         * We know P will stay a directory when we check out the contents
1220         * of the index, but we do not know yet if there is a directory
1221         * P/Q in the working tree to be killed, so we need to recurse.
1222         *
1223         * (3) P does not exist in the index, and there is no P/Q in the index
1224         * to require P to be a directory, either.  Only in this case, we
1225         * know that everything inside P will not be killed without
1226         * recursing.
1227         */
1228        if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
1229            (dtype == DT_DIR) &&
1230            !has_path_in_index &&
1231            (directory_exists_in_index(path->buf, path->len) == index_nonexistent))
1232                return path_none;
1233
1234        exclude = is_excluded(dir, path->buf, &dtype);
1235
1236        /*
1237         * Excluded? If we don't explicitly want to show
1238         * ignored files, ignore it
1239         */
1240        if (exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
1241                return path_excluded;
1242
1243        switch (dtype) {
1244        default:
1245                return path_none;
1246        case DT_DIR:
1247                strbuf_addch(path, '/');
1248                return treat_directory(dir, path->buf, path->len, exclude,
1249                        simplify);
1250        case DT_REG:
1251        case DT_LNK:
1252                return exclude ? path_excluded : path_untracked;
1253        }
1254}
1255
1256static enum path_treatment treat_path(struct dir_struct *dir,
1257                                      struct dirent *de,
1258                                      struct strbuf *path,
1259                                      int baselen,
1260                                      const struct path_simplify *simplify)
1261{
1262        int dtype;
1263
1264        if (is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name, ".git"))
1265                return path_none;
1266        strbuf_setlen(path, baselen);
1267        strbuf_addstr(path, de->d_name);
1268        if (simplify_away(path->buf, path->len, simplify))
1269                return path_none;
1270
1271        dtype = DTYPE(de);
1272        return treat_one_path(dir, path, simplify, dtype, de);
1273}
1274
1275/*
1276 * Read a directory tree. We currently ignore anything but
1277 * directories, regular files and symlinks. That's because git
1278 * doesn't handle them at all yet. Maybe that will change some
1279 * day.
1280 *
1281 * Also, we ignore the name ".git" (even if it is not a directory).
1282 * That likely will not change.
1283 *
1284 * Returns the most significant path_treatment value encountered in the scan.
1285 */
1286static enum path_treatment read_directory_recursive(struct dir_struct *dir,
1287                                    const char *base, int baselen,
1288                                    int check_only,
1289                                    const struct path_simplify *simplify)
1290{
1291        DIR *fdir;
1292        enum path_treatment state, subdir_state, dir_state = path_none;
1293        struct dirent *de;
1294        struct strbuf path = STRBUF_INIT;
1295
1296        strbuf_add(&path, base, baselen);
1297
1298        fdir = opendir(path.len ? path.buf : ".");
1299        if (!fdir)
1300                goto out;
1301
1302        while ((de = readdir(fdir)) != NULL) {
1303                /* check how the file or directory should be treated */
1304                state = treat_path(dir, de, &path, baselen, simplify);
1305                if (state > dir_state)
1306                        dir_state = state;
1307
1308                /* recurse into subdir if instructed by treat_path */
1309                if (state == path_recurse) {
1310                        subdir_state = read_directory_recursive(dir, path.buf,
1311                                path.len, check_only, simplify);
1312                        if (subdir_state > dir_state)
1313                                dir_state = subdir_state;
1314                }
1315
1316                if (check_only) {
1317                        /* abort early if maximum state has been reached */
1318                        if (dir_state == path_untracked)
1319                                break;
1320                        /* skip the dir_add_* part */
1321                        continue;
1322                }
1323
1324                /* add the path to the appropriate result list */
1325                switch (state) {
1326                case path_excluded:
1327                        if (dir->flags & DIR_SHOW_IGNORED)
1328                                dir_add_name(dir, path.buf, path.len);
1329                        else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
1330                                ((dir->flags & DIR_COLLECT_IGNORED) &&
1331                                exclude_matches_pathspec(path.buf, path.len,
1332                                        simplify)))
1333                                dir_add_ignored(dir, path.buf, path.len);
1334                        break;
1335
1336                case path_untracked:
1337                        if (!(dir->flags & DIR_SHOW_IGNORED))
1338                                dir_add_name(dir, path.buf, path.len);
1339                        break;
1340
1341                default:
1342                        break;
1343                }
1344        }
1345        closedir(fdir);
1346 out:
1347        strbuf_release(&path);
1348
1349        return dir_state;
1350}
1351
1352static int cmp_name(const void *p1, const void *p2)
1353{
1354        const struct dir_entry *e1 = *(const struct dir_entry **)p1;
1355        const struct dir_entry *e2 = *(const struct dir_entry **)p2;
1356
1357        return cache_name_compare(e1->name, e1->len,
1358                                  e2->name, e2->len);
1359}
1360
1361static struct path_simplify *create_simplify(const char **pathspec)
1362{
1363        int nr, alloc = 0;
1364        struct path_simplify *simplify = NULL;
1365
1366        if (!pathspec)
1367                return NULL;
1368
1369        for (nr = 0 ; ; nr++) {
1370                const char *match;
1371                ALLOC_GROW(simplify, nr + 1, alloc);
1372                match = *pathspec++;
1373                if (!match)
1374                        break;
1375                simplify[nr].path = match;
1376                simplify[nr].len = simple_length(match);
1377        }
1378        simplify[nr].path = NULL;
1379        simplify[nr].len = 0;
1380        return simplify;
1381}
1382
1383static void free_simplify(struct path_simplify *simplify)
1384{
1385        free(simplify);
1386}
1387
1388static int treat_leading_path(struct dir_struct *dir,
1389                              const char *path, int len,
1390                              const struct path_simplify *simplify)
1391{
1392        struct strbuf sb = STRBUF_INIT;
1393        int baselen, rc = 0;
1394        const char *cp;
1395        int old_flags = dir->flags;
1396
1397        while (len && path[len - 1] == '/')
1398                len--;
1399        if (!len)
1400                return 1;
1401        baselen = 0;
1402        dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;
1403        while (1) {
1404                cp = path + baselen + !!baselen;
1405                cp = memchr(cp, '/', path + len - cp);
1406                if (!cp)
1407                        baselen = len;
1408                else
1409                        baselen = cp - path;
1410                strbuf_setlen(&sb, 0);
1411                strbuf_add(&sb, path, baselen);
1412                if (!is_directory(sb.buf))
1413                        break;
1414                if (simplify_away(sb.buf, sb.len, simplify))
1415                        break;
1416                if (treat_one_path(dir, &sb, simplify,
1417                                   DT_DIR, NULL) == path_none)
1418                        break; /* do not recurse into it */
1419                if (len <= baselen) {
1420                        rc = 1;
1421                        break; /* finished checking */
1422                }
1423        }
1424        strbuf_release(&sb);
1425        dir->flags = old_flags;
1426        return rc;
1427}
1428
1429int read_directory(struct dir_struct *dir, const char *path, int len, const struct pathspec *pathspec)
1430{
1431        struct path_simplify *simplify;
1432
1433        /*
1434         * Check out create_simplify()
1435         */
1436        if (pathspec)
1437                GUARD_PATHSPEC(pathspec,
1438                               PATHSPEC_FROMTOP |
1439                               PATHSPEC_MAXDEPTH |
1440                               PATHSPEC_LITERAL |
1441                               PATHSPEC_GLOB |
1442                               PATHSPEC_ICASE |
1443                               PATHSPEC_EXCLUDE);
1444
1445        if (has_symlink_leading_path(path, len))
1446                return dir->nr;
1447
1448        /*
1449         * exclude patterns are treated like positive ones in
1450         * create_simplify. Usually exclude patterns should be a
1451         * subset of positive ones, which has no impacts on
1452         * create_simplify().
1453         */
1454        simplify = create_simplify(pathspec ? pathspec->_raw : NULL);
1455        if (!len || treat_leading_path(dir, path, len, simplify))
1456                read_directory_recursive(dir, path, len, 0, simplify);
1457        free_simplify(simplify);
1458        qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
1459        qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
1460        return dir->nr;
1461}
1462
1463int file_exists(const char *f)
1464{
1465        struct stat sb;
1466        return lstat(f, &sb) == 0;
1467}
1468
1469/*
1470 * Given two normalized paths (a trailing slash is ok), if subdir is
1471 * outside dir, return -1.  Otherwise return the offset in subdir that
1472 * can be used as relative path to dir.
1473 */
1474int dir_inside_of(const char *subdir, const char *dir)
1475{
1476        int offset = 0;
1477
1478        assert(dir && subdir && *dir && *subdir);
1479
1480        while (*dir && *subdir && *dir == *subdir) {
1481                dir++;
1482                subdir++;
1483                offset++;
1484        }
1485
1486        /* hel[p]/me vs hel[l]/yeah */
1487        if (*dir && *subdir)
1488                return -1;
1489
1490        if (!*subdir)
1491                return !*dir ? offset : -1; /* same dir */
1492
1493        /* foo/[b]ar vs foo/[] */
1494        if (is_dir_sep(dir[-1]))
1495                return is_dir_sep(subdir[-1]) ? offset : -1;
1496
1497        /* foo[/]bar vs foo[] */
1498        return is_dir_sep(*subdir) ? offset + 1 : -1;
1499}
1500
1501int is_inside_dir(const char *dir)
1502{
1503        char cwd[PATH_MAX];
1504        if (!dir)
1505                return 0;
1506        if (!getcwd(cwd, sizeof(cwd)))
1507                die_errno("can't find the current directory");
1508        return dir_inside_of(cwd, dir) >= 0;
1509}
1510
1511int is_empty_dir(const char *path)
1512{
1513        DIR *dir = opendir(path);
1514        struct dirent *e;
1515        int ret = 1;
1516
1517        if (!dir)
1518                return 0;
1519
1520        while ((e = readdir(dir)) != NULL)
1521                if (!is_dot_or_dotdot(e->d_name)) {
1522                        ret = 0;
1523                        break;
1524                }
1525
1526        closedir(dir);
1527        return ret;
1528}
1529
1530static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
1531{
1532        DIR *dir;
1533        struct dirent *e;
1534        int ret = 0, original_len = path->len, len, kept_down = 0;
1535        int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
1536        int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
1537        unsigned char submodule_head[20];
1538
1539        if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
1540            !resolve_gitlink_ref(path->buf, "HEAD", submodule_head)) {
1541                /* Do not descend and nuke a nested git work tree. */
1542                if (kept_up)
1543                        *kept_up = 1;
1544                return 0;
1545        }
1546
1547        flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
1548        dir = opendir(path->buf);
1549        if (!dir) {
1550                if (errno == ENOENT)
1551                        return keep_toplevel ? -1 : 0;
1552                else if (errno == EACCES && !keep_toplevel)
1553                        /*
1554                         * An empty dir could be removable even if it
1555                         * is unreadable:
1556                         */
1557                        return rmdir(path->buf);
1558                else
1559                        return -1;
1560        }
1561        if (path->buf[original_len - 1] != '/')
1562                strbuf_addch(path, '/');
1563
1564        len = path->len;
1565        while ((e = readdir(dir)) != NULL) {
1566                struct stat st;
1567                if (is_dot_or_dotdot(e->d_name))
1568                        continue;
1569
1570                strbuf_setlen(path, len);
1571                strbuf_addstr(path, e->d_name);
1572                if (lstat(path->buf, &st)) {
1573                        if (errno == ENOENT)
1574                                /*
1575                                 * file disappeared, which is what we
1576                                 * wanted anyway
1577                                 */
1578                                continue;
1579                        /* fall thru */
1580                } else if (S_ISDIR(st.st_mode)) {
1581                        if (!remove_dir_recurse(path, flag, &kept_down))
1582                                continue; /* happy */
1583                } else if (!only_empty &&
1584                           (!unlink(path->buf) || errno == ENOENT)) {
1585                        continue; /* happy, too */
1586                }
1587
1588                /* path too long, stat fails, or non-directory still exists */
1589                ret = -1;
1590                break;
1591        }
1592        closedir(dir);
1593
1594        strbuf_setlen(path, original_len);
1595        if (!ret && !keep_toplevel && !kept_down)
1596                ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1;
1597        else if (kept_up)
1598                /*
1599                 * report the uplevel that it is not an error that we
1600                 * did not rmdir() our directory.
1601                 */
1602                *kept_up = !ret;
1603        return ret;
1604}
1605
1606int remove_dir_recursively(struct strbuf *path, int flag)
1607{
1608        return remove_dir_recurse(path, flag, NULL);
1609}
1610
1611void setup_standard_excludes(struct dir_struct *dir)
1612{
1613        const char *path;
1614        char *xdg_path;
1615
1616        dir->exclude_per_dir = ".gitignore";
1617        path = git_path("info/exclude");
1618        if (!excludes_file) {
1619                home_config_paths(NULL, &xdg_path, "ignore");
1620                excludes_file = xdg_path;
1621        }
1622        if (!access_or_warn(path, R_OK, 0))
1623                add_excludes_from_file(dir, path);
1624        if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
1625                add_excludes_from_file(dir, excludes_file);
1626}
1627
1628int remove_path(const char *name)
1629{
1630        char *slash;
1631
1632        if (unlink(name) && errno != ENOENT && errno != ENOTDIR)
1633                return -1;
1634
1635        slash = strrchr(name, '/');
1636        if (slash) {
1637                char *dirs = xstrdup(name);
1638                slash = dirs + (slash - name);
1639                do {
1640                        *slash = '\0';
1641                } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
1642                free(dirs);
1643        }
1644        return 0;
1645}
1646
1647/*
1648 * Frees memory within dir which was allocated for exclude lists and
1649 * the exclude_stack.  Does not free dir itself.
1650 */
1651void clear_directory(struct dir_struct *dir)
1652{
1653        int i, j;
1654        struct exclude_list_group *group;
1655        struct exclude_list *el;
1656        struct exclude_stack *stk;
1657
1658        for (i = EXC_CMDL; i <= EXC_FILE; i++) {
1659                group = &dir->exclude_list_group[i];
1660                for (j = 0; j < group->nr; j++) {
1661                        el = &group->el[j];
1662                        if (i == EXC_DIRS)
1663                                free((char *)el->src);
1664                        clear_exclude_list(el);
1665                }
1666                free(group->el);
1667        }
1668
1669        stk = dir->exclude_stack;
1670        while (stk) {
1671                struct exclude_stack *prev = stk->prev;
1672                free(stk);
1673                stk = prev;
1674        }
1675}