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