dir.con commit tmp-objdir: put quarantine information in the environment (e34c2e0)
   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#include "utf8.h"
  16#include "varint.h"
  17#include "ewah/ewok.h"
  18
  19struct path_simplify {
  20        int len;
  21        const char *path;
  22};
  23
  24/*
  25 * Tells read_directory_recursive how a file or directory should be treated.
  26 * Values are ordered by significance, e.g. if a directory contains both
  27 * excluded and untracked files, it is listed as untracked because
  28 * path_untracked > path_excluded.
  29 */
  30enum path_treatment {
  31        path_none = 0,
  32        path_recurse,
  33        path_excluded,
  34        path_untracked
  35};
  36
  37/*
  38 * Support data structure for our opendir/readdir/closedir wrappers
  39 */
  40struct cached_dir {
  41        DIR *fdir;
  42        struct untracked_cache_dir *untracked;
  43        int nr_files;
  44        int nr_dirs;
  45
  46        struct dirent *de;
  47        const char *file;
  48        struct untracked_cache_dir *ucd;
  49};
  50
  51static enum path_treatment read_directory_recursive(struct dir_struct *dir,
  52        const char *path, int len, struct untracked_cache_dir *untracked,
  53        int check_only, const struct path_simplify *simplify);
  54static int get_dtype(struct dirent *de, const char *path, int len);
  55
  56int fspathcmp(const char *a, const char *b)
  57{
  58        return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
  59}
  60
  61int fspathncmp(const char *a, const char *b, size_t count)
  62{
  63        return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
  64}
  65
  66int git_fnmatch(const struct pathspec_item *item,
  67                const char *pattern, const char *string,
  68                int prefix)
  69{
  70        if (prefix > 0) {
  71                if (ps_strncmp(item, pattern, string, prefix))
  72                        return WM_NOMATCH;
  73                pattern += prefix;
  74                string += prefix;
  75        }
  76        if (item->flags & PATHSPEC_ONESTAR) {
  77                int pattern_len = strlen(++pattern);
  78                int string_len = strlen(string);
  79                return string_len < pattern_len ||
  80                        ps_strcmp(item, pattern,
  81                                  string + string_len - pattern_len);
  82        }
  83        if (item->magic & PATHSPEC_GLOB)
  84                return wildmatch(pattern, string,
  85                                 WM_PATHNAME |
  86                                 (item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0),
  87                                 NULL);
  88        else
  89                /* wildmatch has not learned no FNM_PATHNAME mode yet */
  90                return wildmatch(pattern, string,
  91                                 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0,
  92                                 NULL);
  93}
  94
  95static int fnmatch_icase_mem(const char *pattern, int patternlen,
  96                             const char *string, int stringlen,
  97                             int flags)
  98{
  99        int match_status;
 100        struct strbuf pat_buf = STRBUF_INIT;
 101        struct strbuf str_buf = STRBUF_INIT;
 102        const char *use_pat = pattern;
 103        const char *use_str = string;
 104
 105        if (pattern[patternlen]) {
 106                strbuf_add(&pat_buf, pattern, patternlen);
 107                use_pat = pat_buf.buf;
 108        }
 109        if (string[stringlen]) {
 110                strbuf_add(&str_buf, string, stringlen);
 111                use_str = str_buf.buf;
 112        }
 113
 114        if (ignore_case)
 115                flags |= WM_CASEFOLD;
 116        match_status = wildmatch(use_pat, use_str, flags, NULL);
 117
 118        strbuf_release(&pat_buf);
 119        strbuf_release(&str_buf);
 120
 121        return match_status;
 122}
 123
 124static size_t common_prefix_len(const struct pathspec *pathspec)
 125{
 126        int n;
 127        size_t max = 0;
 128
 129        /*
 130         * ":(icase)path" is treated as a pathspec full of
 131         * wildcard. In other words, only prefix is considered common
 132         * prefix. If the pathspec is abc/foo abc/bar, running in
 133         * subdir xyz, the common prefix is still xyz, not xuz/abc as
 134         * in non-:(icase).
 135         */
 136        GUARD_PATHSPEC(pathspec,
 137                       PATHSPEC_FROMTOP |
 138                       PATHSPEC_MAXDEPTH |
 139                       PATHSPEC_LITERAL |
 140                       PATHSPEC_GLOB |
 141                       PATHSPEC_ICASE |
 142                       PATHSPEC_EXCLUDE);
 143
 144        for (n = 0; n < pathspec->nr; n++) {
 145                size_t i = 0, len = 0, item_len;
 146                if (pathspec->items[n].magic & PATHSPEC_EXCLUDE)
 147                        continue;
 148                if (pathspec->items[n].magic & PATHSPEC_ICASE)
 149                        item_len = pathspec->items[n].prefix;
 150                else
 151                        item_len = pathspec->items[n].nowildcard_len;
 152                while (i < item_len && (n == 0 || i < max)) {
 153                        char c = pathspec->items[n].match[i];
 154                        if (c != pathspec->items[0].match[i])
 155                                break;
 156                        if (c == '/')
 157                                len = i + 1;
 158                        i++;
 159                }
 160                if (n == 0 || len < max) {
 161                        max = len;
 162                        if (!max)
 163                                break;
 164                }
 165        }
 166        return max;
 167}
 168
 169/*
 170 * Returns a copy of the longest leading path common among all
 171 * pathspecs.
 172 */
 173char *common_prefix(const struct pathspec *pathspec)
 174{
 175        unsigned long len = common_prefix_len(pathspec);
 176
 177        return len ? xmemdupz(pathspec->items[0].match, len) : NULL;
 178}
 179
 180int fill_directory(struct dir_struct *dir, const struct pathspec *pathspec)
 181{
 182        size_t len;
 183
 184        /*
 185         * Calculate common prefix for the pathspec, and
 186         * use that to optimize the directory walk
 187         */
 188        len = common_prefix_len(pathspec);
 189
 190        /* Read the directory and prune it */
 191        read_directory(dir, pathspec->nr ? pathspec->_raw[0] : "", len, pathspec);
 192        return len;
 193}
 194
 195int within_depth(const char *name, int namelen,
 196                        int depth, int max_depth)
 197{
 198        const char *cp = name, *cpe = name + namelen;
 199
 200        while (cp < cpe) {
 201                if (*cp++ != '/')
 202                        continue;
 203                depth++;
 204                if (depth > max_depth)
 205                        return 0;
 206        }
 207        return 1;
 208}
 209
 210#define DO_MATCH_EXCLUDE   1
 211#define DO_MATCH_DIRECTORY 2
 212
 213/*
 214 * Does 'match' match the given name?
 215 * A match is found if
 216 *
 217 * (1) the 'match' string is leading directory of 'name', or
 218 * (2) the 'match' string is a wildcard and matches 'name', or
 219 * (3) the 'match' string is exactly the same as 'name'.
 220 *
 221 * and the return value tells which case it was.
 222 *
 223 * It returns 0 when there is no match.
 224 */
 225static int match_pathspec_item(const struct pathspec_item *item, int prefix,
 226                               const char *name, int namelen, unsigned flags)
 227{
 228        /* name/namelen has prefix cut off by caller */
 229        const char *match = item->match + prefix;
 230        int matchlen = item->len - prefix;
 231
 232        /*
 233         * The normal call pattern is:
 234         * 1. prefix = common_prefix_len(ps);
 235         * 2. prune something, or fill_directory
 236         * 3. match_pathspec()
 237         *
 238         * 'prefix' at #1 may be shorter than the command's prefix and
 239         * it's ok for #2 to match extra files. Those extras will be
 240         * trimmed at #3.
 241         *
 242         * Suppose the pathspec is 'foo' and '../bar' running from
 243         * subdir 'xyz'. The common prefix at #1 will be empty, thanks
 244         * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
 245         * user does not want XYZ/foo, only the "foo" part should be
 246         * case-insensitive. We need to filter out XYZ/foo here. In
 247         * other words, we do not trust the caller on comparing the
 248         * prefix part when :(icase) is involved. We do exact
 249         * comparison ourselves.
 250         *
 251         * Normally the caller (common_prefix_len() in fact) does
 252         * _exact_ matching on name[-prefix+1..-1] and we do not need
 253         * to check that part. Be defensive and check it anyway, in
 254         * case common_prefix_len is changed, or a new caller is
 255         * introduced that does not use common_prefix_len.
 256         *
 257         * If the penalty turns out too high when prefix is really
 258         * long, maybe change it to
 259         * strncmp(match, name, item->prefix - prefix)
 260         */
 261        if (item->prefix && (item->magic & PATHSPEC_ICASE) &&
 262            strncmp(item->match, name - prefix, item->prefix))
 263                return 0;
 264
 265        /* If the match was just the prefix, we matched */
 266        if (!*match)
 267                return MATCHED_RECURSIVELY;
 268
 269        if (matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) {
 270                if (matchlen == namelen)
 271                        return MATCHED_EXACTLY;
 272
 273                if (match[matchlen-1] == '/' || name[matchlen] == '/')
 274                        return MATCHED_RECURSIVELY;
 275        } else if ((flags & DO_MATCH_DIRECTORY) &&
 276                   match[matchlen - 1] == '/' &&
 277                   namelen == matchlen - 1 &&
 278                   !ps_strncmp(item, match, name, namelen))
 279                return MATCHED_EXACTLY;
 280
 281        if (item->nowildcard_len < item->len &&
 282            !git_fnmatch(item, match, name,
 283                         item->nowildcard_len - prefix))
 284                return MATCHED_FNMATCH;
 285
 286        return 0;
 287}
 288
 289/*
 290 * Given a name and a list of pathspecs, returns the nature of the
 291 * closest (i.e. most specific) match of the name to any of the
 292 * pathspecs.
 293 *
 294 * The caller typically calls this multiple times with the same
 295 * pathspec and seen[] array but with different name/namelen
 296 * (e.g. entries from the index) and is interested in seeing if and
 297 * how each pathspec matches all the names it calls this function
 298 * with.  A mark is left in the seen[] array for each pathspec element
 299 * indicating the closest type of match that element achieved, so if
 300 * seen[n] remains zero after multiple invocations, that means the nth
 301 * pathspec did not match any names, which could indicate that the
 302 * user mistyped the nth pathspec.
 303 */
 304static int do_match_pathspec(const struct pathspec *ps,
 305                             const char *name, int namelen,
 306                             int prefix, char *seen,
 307                             unsigned flags)
 308{
 309        int i, retval = 0, exclude = flags & DO_MATCH_EXCLUDE;
 310
 311        GUARD_PATHSPEC(ps,
 312                       PATHSPEC_FROMTOP |
 313                       PATHSPEC_MAXDEPTH |
 314                       PATHSPEC_LITERAL |
 315                       PATHSPEC_GLOB |
 316                       PATHSPEC_ICASE |
 317                       PATHSPEC_EXCLUDE);
 318
 319        if (!ps->nr) {
 320                if (!ps->recursive ||
 321                    !(ps->magic & PATHSPEC_MAXDEPTH) ||
 322                    ps->max_depth == -1)
 323                        return MATCHED_RECURSIVELY;
 324
 325                if (within_depth(name, namelen, 0, ps->max_depth))
 326                        return MATCHED_EXACTLY;
 327                else
 328                        return 0;
 329        }
 330
 331        name += prefix;
 332        namelen -= prefix;
 333
 334        for (i = ps->nr - 1; i >= 0; i--) {
 335                int how;
 336
 337                if ((!exclude &&   ps->items[i].magic & PATHSPEC_EXCLUDE) ||
 338                    ( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE)))
 339                        continue;
 340
 341                if (seen && seen[i] == MATCHED_EXACTLY)
 342                        continue;
 343                /*
 344                 * Make exclude patterns optional and never report
 345                 * "pathspec ':(exclude)foo' matches no files"
 346                 */
 347                if (seen && ps->items[i].magic & PATHSPEC_EXCLUDE)
 348                        seen[i] = MATCHED_FNMATCH;
 349                how = match_pathspec_item(ps->items+i, prefix, name,
 350                                          namelen, flags);
 351                if (ps->recursive &&
 352                    (ps->magic & PATHSPEC_MAXDEPTH) &&
 353                    ps->max_depth != -1 &&
 354                    how && how != MATCHED_FNMATCH) {
 355                        int len = ps->items[i].len;
 356                        if (name[len] == '/')
 357                                len++;
 358                        if (within_depth(name+len, namelen-len, 0, ps->max_depth))
 359                                how = MATCHED_EXACTLY;
 360                        else
 361                                how = 0;
 362                }
 363                if (how) {
 364                        if (retval < how)
 365                                retval = how;
 366                        if (seen && seen[i] < how)
 367                                seen[i] = how;
 368                }
 369        }
 370        return retval;
 371}
 372
 373int match_pathspec(const struct pathspec *ps,
 374                   const char *name, int namelen,
 375                   int prefix, char *seen, int is_dir)
 376{
 377        int positive, negative;
 378        unsigned flags = is_dir ? DO_MATCH_DIRECTORY : 0;
 379        positive = do_match_pathspec(ps, name, namelen,
 380                                     prefix, seen, flags);
 381        if (!(ps->magic & PATHSPEC_EXCLUDE) || !positive)
 382                return positive;
 383        negative = do_match_pathspec(ps, name, namelen,
 384                                     prefix, seen,
 385                                     flags | DO_MATCH_EXCLUDE);
 386        return negative ? 0 : positive;
 387}
 388
 389int report_path_error(const char *ps_matched,
 390                      const struct pathspec *pathspec,
 391                      const char *prefix)
 392{
 393        /*
 394         * Make sure all pathspec matched; otherwise it is an error.
 395         */
 396        int num, errors = 0;
 397        for (num = 0; num < pathspec->nr; num++) {
 398                int other, found_dup;
 399
 400                if (ps_matched[num])
 401                        continue;
 402                /*
 403                 * The caller might have fed identical pathspec
 404                 * twice.  Do not barf on such a mistake.
 405                 * FIXME: parse_pathspec should have eliminated
 406                 * duplicate pathspec.
 407                 */
 408                for (found_dup = other = 0;
 409                     !found_dup && other < pathspec->nr;
 410                     other++) {
 411                        if (other == num || !ps_matched[other])
 412                                continue;
 413                        if (!strcmp(pathspec->items[other].original,
 414                                    pathspec->items[num].original))
 415                                /*
 416                                 * Ok, we have a match already.
 417                                 */
 418                                found_dup = 1;
 419                }
 420                if (found_dup)
 421                        continue;
 422
 423                error("pathspec '%s' did not match any file(s) known to git.",
 424                      pathspec->items[num].original);
 425                errors++;
 426        }
 427        return errors;
 428}
 429
 430/*
 431 * Return the length of the "simple" part of a path match limiter.
 432 */
 433int simple_length(const char *match)
 434{
 435        int len = -1;
 436
 437        for (;;) {
 438                unsigned char c = *match++;
 439                len++;
 440                if (c == '\0' || is_glob_special(c))
 441                        return len;
 442        }
 443}
 444
 445int no_wildcard(const char *string)
 446{
 447        return string[simple_length(string)] == '\0';
 448}
 449
 450void parse_exclude_pattern(const char **pattern,
 451                           int *patternlen,
 452                           unsigned *flags,
 453                           int *nowildcardlen)
 454{
 455        const char *p = *pattern;
 456        size_t i, len;
 457
 458        *flags = 0;
 459        if (*p == '!') {
 460                *flags |= EXC_FLAG_NEGATIVE;
 461                p++;
 462        }
 463        len = strlen(p);
 464        if (len && p[len - 1] == '/') {
 465                len--;
 466                *flags |= EXC_FLAG_MUSTBEDIR;
 467        }
 468        for (i = 0; i < len; i++) {
 469                if (p[i] == '/')
 470                        break;
 471        }
 472        if (i == len)
 473                *flags |= EXC_FLAG_NODIR;
 474        *nowildcardlen = simple_length(p);
 475        /*
 476         * we should have excluded the trailing slash from 'p' too,
 477         * but that's one more allocation. Instead just make sure
 478         * nowildcardlen does not exceed real patternlen
 479         */
 480        if (*nowildcardlen > len)
 481                *nowildcardlen = len;
 482        if (*p == '*' && no_wildcard(p + 1))
 483                *flags |= EXC_FLAG_ENDSWITH;
 484        *pattern = p;
 485        *patternlen = len;
 486}
 487
 488void add_exclude(const char *string, const char *base,
 489                 int baselen, struct exclude_list *el, int srcpos)
 490{
 491        struct exclude *x;
 492        int patternlen;
 493        unsigned flags;
 494        int nowildcardlen;
 495
 496        parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen);
 497        if (flags & EXC_FLAG_MUSTBEDIR) {
 498                FLEXPTR_ALLOC_MEM(x, pattern, string, patternlen);
 499        } else {
 500                x = xmalloc(sizeof(*x));
 501                x->pattern = string;
 502        }
 503        x->patternlen = patternlen;
 504        x->nowildcardlen = nowildcardlen;
 505        x->base = base;
 506        x->baselen = baselen;
 507        x->flags = flags;
 508        x->srcpos = srcpos;
 509        ALLOC_GROW(el->excludes, el->nr + 1, el->alloc);
 510        el->excludes[el->nr++] = x;
 511        x->el = el;
 512}
 513
 514static void *read_skip_worktree_file_from_index(const char *path, size_t *size,
 515                                                struct sha1_stat *sha1_stat)
 516{
 517        int pos, len;
 518        unsigned long sz;
 519        enum object_type type;
 520        void *data;
 521
 522        len = strlen(path);
 523        pos = cache_name_pos(path, len);
 524        if (pos < 0)
 525                return NULL;
 526        if (!ce_skip_worktree(active_cache[pos]))
 527                return NULL;
 528        data = read_sha1_file(active_cache[pos]->oid.hash, &type, &sz);
 529        if (!data || type != OBJ_BLOB) {
 530                free(data);
 531                return NULL;
 532        }
 533        *size = xsize_t(sz);
 534        if (sha1_stat) {
 535                memset(&sha1_stat->stat, 0, sizeof(sha1_stat->stat));
 536                hashcpy(sha1_stat->sha1, active_cache[pos]->oid.hash);
 537        }
 538        return data;
 539}
 540
 541/*
 542 * Frees memory within el which was allocated for exclude patterns and
 543 * the file buffer.  Does not free el itself.
 544 */
 545void clear_exclude_list(struct exclude_list *el)
 546{
 547        int i;
 548
 549        for (i = 0; i < el->nr; i++)
 550                free(el->excludes[i]);
 551        free(el->excludes);
 552        free(el->filebuf);
 553
 554        memset(el, 0, sizeof(*el));
 555}
 556
 557static void trim_trailing_spaces(char *buf)
 558{
 559        char *p, *last_space = NULL;
 560
 561        for (p = buf; *p; p++)
 562                switch (*p) {
 563                case ' ':
 564                        if (!last_space)
 565                                last_space = p;
 566                        break;
 567                case '\\':
 568                        p++;
 569                        if (!*p)
 570                                return;
 571                        /* fallthrough */
 572                default:
 573                        last_space = NULL;
 574                }
 575
 576        if (last_space)
 577                *last_space = '\0';
 578}
 579
 580/*
 581 * Given a subdirectory name and "dir" of the current directory,
 582 * search the subdir in "dir" and return it, or create a new one if it
 583 * does not exist in "dir".
 584 *
 585 * If "name" has the trailing slash, it'll be excluded in the search.
 586 */
 587static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc,
 588                                                    struct untracked_cache_dir *dir,
 589                                                    const char *name, int len)
 590{
 591        int first, last;
 592        struct untracked_cache_dir *d;
 593        if (!dir)
 594                return NULL;
 595        if (len && name[len - 1] == '/')
 596                len--;
 597        first = 0;
 598        last = dir->dirs_nr;
 599        while (last > first) {
 600                int cmp, next = (last + first) >> 1;
 601                d = dir->dirs[next];
 602                cmp = strncmp(name, d->name, len);
 603                if (!cmp && strlen(d->name) > len)
 604                        cmp = -1;
 605                if (!cmp)
 606                        return d;
 607                if (cmp < 0) {
 608                        last = next;
 609                        continue;
 610                }
 611                first = next+1;
 612        }
 613
 614        uc->dir_created++;
 615        FLEX_ALLOC_MEM(d, name, name, len);
 616
 617        ALLOC_GROW(dir->dirs, dir->dirs_nr + 1, dir->dirs_alloc);
 618        memmove(dir->dirs + first + 1, dir->dirs + first,
 619                (dir->dirs_nr - first) * sizeof(*dir->dirs));
 620        dir->dirs_nr++;
 621        dir->dirs[first] = d;
 622        return d;
 623}
 624
 625static void do_invalidate_gitignore(struct untracked_cache_dir *dir)
 626{
 627        int i;
 628        dir->valid = 0;
 629        dir->untracked_nr = 0;
 630        for (i = 0; i < dir->dirs_nr; i++)
 631                do_invalidate_gitignore(dir->dirs[i]);
 632}
 633
 634static void invalidate_gitignore(struct untracked_cache *uc,
 635                                 struct untracked_cache_dir *dir)
 636{
 637        uc->gitignore_invalidated++;
 638        do_invalidate_gitignore(dir);
 639}
 640
 641static void invalidate_directory(struct untracked_cache *uc,
 642                                 struct untracked_cache_dir *dir)
 643{
 644        int i;
 645        uc->dir_invalidated++;
 646        dir->valid = 0;
 647        dir->untracked_nr = 0;
 648        for (i = 0; i < dir->dirs_nr; i++)
 649                dir->dirs[i]->recurse = 0;
 650}
 651
 652/*
 653 * Given a file with name "fname", read it (either from disk, or from
 654 * the index if "check_index" is non-zero), parse it and store the
 655 * exclude rules in "el".
 656 *
 657 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill
 658 * stat data from disk (only valid if add_excludes returns zero). If
 659 * ss_valid is non-zero, "ss" must contain good value as input.
 660 */
 661static int add_excludes(const char *fname, const char *base, int baselen,
 662                        struct exclude_list *el, int check_index,
 663                        struct sha1_stat *sha1_stat)
 664{
 665        struct stat st;
 666        int fd, i, lineno = 1;
 667        size_t size = 0;
 668        char *buf, *entry;
 669
 670        fd = open(fname, O_RDONLY);
 671        if (fd < 0 || fstat(fd, &st) < 0) {
 672                if (errno != ENOENT)
 673                        warn_on_inaccessible(fname);
 674                if (0 <= fd)
 675                        close(fd);
 676                if (!check_index ||
 677                    (buf = read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL)
 678                        return -1;
 679                if (size == 0) {
 680                        free(buf);
 681                        return 0;
 682                }
 683                if (buf[size-1] != '\n') {
 684                        buf = xrealloc(buf, st_add(size, 1));
 685                        buf[size++] = '\n';
 686                }
 687        } else {
 688                size = xsize_t(st.st_size);
 689                if (size == 0) {
 690                        if (sha1_stat) {
 691                                fill_stat_data(&sha1_stat->stat, &st);
 692                                hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN);
 693                                sha1_stat->valid = 1;
 694                        }
 695                        close(fd);
 696                        return 0;
 697                }
 698                buf = xmallocz(size);
 699                if (read_in_full(fd, buf, size) != size) {
 700                        free(buf);
 701                        close(fd);
 702                        return -1;
 703                }
 704                buf[size++] = '\n';
 705                close(fd);
 706                if (sha1_stat) {
 707                        int pos;
 708                        if (sha1_stat->valid &&
 709                            !match_stat_data_racy(&the_index, &sha1_stat->stat, &st))
 710                                ; /* no content change, ss->sha1 still good */
 711                        else if (check_index &&
 712                                 (pos = cache_name_pos(fname, strlen(fname))) >= 0 &&
 713                                 !ce_stage(active_cache[pos]) &&
 714                                 ce_uptodate(active_cache[pos]) &&
 715                                 !would_convert_to_git(fname))
 716                                hashcpy(sha1_stat->sha1,
 717                                        active_cache[pos]->oid.hash);
 718                        else
 719                                hash_sha1_file(buf, size, "blob", sha1_stat->sha1);
 720                        fill_stat_data(&sha1_stat->stat, &st);
 721                        sha1_stat->valid = 1;
 722                }
 723        }
 724
 725        el->filebuf = buf;
 726
 727        if (skip_utf8_bom(&buf, size))
 728                size -= buf - el->filebuf;
 729
 730        entry = buf;
 731
 732        for (i = 0; i < size; i++) {
 733                if (buf[i] == '\n') {
 734                        if (entry != buf + i && entry[0] != '#') {
 735                                buf[i - (i && buf[i-1] == '\r')] = 0;
 736                                trim_trailing_spaces(entry);
 737                                add_exclude(entry, base, baselen, el, lineno);
 738                        }
 739                        lineno++;
 740                        entry = buf + i + 1;
 741                }
 742        }
 743        return 0;
 744}
 745
 746int add_excludes_from_file_to_list(const char *fname, const char *base,
 747                                   int baselen, struct exclude_list *el,
 748                                   int check_index)
 749{
 750        return add_excludes(fname, base, baselen, el, check_index, NULL);
 751}
 752
 753struct exclude_list *add_exclude_list(struct dir_struct *dir,
 754                                      int group_type, const char *src)
 755{
 756        struct exclude_list *el;
 757        struct exclude_list_group *group;
 758
 759        group = &dir->exclude_list_group[group_type];
 760        ALLOC_GROW(group->el, group->nr + 1, group->alloc);
 761        el = &group->el[group->nr++];
 762        memset(el, 0, sizeof(*el));
 763        el->src = src;
 764        return el;
 765}
 766
 767/*
 768 * Used to set up core.excludesfile and .git/info/exclude lists.
 769 */
 770static void add_excludes_from_file_1(struct dir_struct *dir, const char *fname,
 771                                     struct sha1_stat *sha1_stat)
 772{
 773        struct exclude_list *el;
 774        /*
 775         * catch setup_standard_excludes() that's called before
 776         * dir->untracked is assigned. That function behaves
 777         * differently when dir->untracked is non-NULL.
 778         */
 779        if (!dir->untracked)
 780                dir->unmanaged_exclude_files++;
 781        el = add_exclude_list(dir, EXC_FILE, fname);
 782        if (add_excludes(fname, "", 0, el, 0, sha1_stat) < 0)
 783                die("cannot use %s as an exclude file", fname);
 784}
 785
 786void add_excludes_from_file(struct dir_struct *dir, const char *fname)
 787{
 788        dir->unmanaged_exclude_files++; /* see validate_untracked_cache() */
 789        add_excludes_from_file_1(dir, fname, NULL);
 790}
 791
 792int match_basename(const char *basename, int basenamelen,
 793                   const char *pattern, int prefix, int patternlen,
 794                   unsigned flags)
 795{
 796        if (prefix == patternlen) {
 797                if (patternlen == basenamelen &&
 798                    !fspathncmp(pattern, basename, basenamelen))
 799                        return 1;
 800        } else if (flags & EXC_FLAG_ENDSWITH) {
 801                /* "*literal" matching against "fooliteral" */
 802                if (patternlen - 1 <= basenamelen &&
 803                    !fspathncmp(pattern + 1,
 804                                   basename + basenamelen - (patternlen - 1),
 805                                   patternlen - 1))
 806                        return 1;
 807        } else {
 808                if (fnmatch_icase_mem(pattern, patternlen,
 809                                      basename, basenamelen,
 810                                      0) == 0)
 811                        return 1;
 812        }
 813        return 0;
 814}
 815
 816int match_pathname(const char *pathname, int pathlen,
 817                   const char *base, int baselen,
 818                   const char *pattern, int prefix, int patternlen,
 819                   unsigned flags)
 820{
 821        const char *name;
 822        int namelen;
 823
 824        /*
 825         * match with FNM_PATHNAME; the pattern has base implicitly
 826         * in front of it.
 827         */
 828        if (*pattern == '/') {
 829                pattern++;
 830                patternlen--;
 831                prefix--;
 832        }
 833
 834        /*
 835         * baselen does not count the trailing slash. base[] may or
 836         * may not end with a trailing slash though.
 837         */
 838        if (pathlen < baselen + 1 ||
 839            (baselen && pathname[baselen] != '/') ||
 840            fspathncmp(pathname, base, baselen))
 841                return 0;
 842
 843        namelen = baselen ? pathlen - baselen - 1 : pathlen;
 844        name = pathname + pathlen - namelen;
 845
 846        if (prefix) {
 847                /*
 848                 * if the non-wildcard part is longer than the
 849                 * remaining pathname, surely it cannot match.
 850                 */
 851                if (prefix > namelen)
 852                        return 0;
 853
 854                if (fspathncmp(pattern, name, prefix))
 855                        return 0;
 856                pattern += prefix;
 857                patternlen -= prefix;
 858                name    += prefix;
 859                namelen -= prefix;
 860
 861                /*
 862                 * If the whole pattern did not have a wildcard,
 863                 * then our prefix match is all we need; we
 864                 * do not need to call fnmatch at all.
 865                 */
 866                if (!patternlen && !namelen)
 867                        return 1;
 868        }
 869
 870        return fnmatch_icase_mem(pattern, patternlen,
 871                                 name, namelen,
 872                                 WM_PATHNAME) == 0;
 873}
 874
 875/*
 876 * Scan the given exclude list in reverse to see whether pathname
 877 * should be ignored.  The first match (i.e. the last on the list), if
 878 * any, determines the fate.  Returns the exclude_list element which
 879 * matched, or NULL for undecided.
 880 */
 881static struct exclude *last_exclude_matching_from_list(const char *pathname,
 882                                                       int pathlen,
 883                                                       const char *basename,
 884                                                       int *dtype,
 885                                                       struct exclude_list *el)
 886{
 887        struct exclude *exc = NULL; /* undecided */
 888        int i;
 889
 890        if (!el->nr)
 891                return NULL;    /* undefined */
 892
 893        for (i = el->nr - 1; 0 <= i; i--) {
 894                struct exclude *x = el->excludes[i];
 895                const char *exclude = x->pattern;
 896                int prefix = x->nowildcardlen;
 897
 898                if (x->flags & EXC_FLAG_MUSTBEDIR) {
 899                        if (*dtype == DT_UNKNOWN)
 900                                *dtype = get_dtype(NULL, pathname, pathlen);
 901                        if (*dtype != DT_DIR)
 902                                continue;
 903                }
 904
 905                if (x->flags & EXC_FLAG_NODIR) {
 906                        if (match_basename(basename,
 907                                           pathlen - (basename - pathname),
 908                                           exclude, prefix, x->patternlen,
 909                                           x->flags)) {
 910                                exc = x;
 911                                break;
 912                        }
 913                        continue;
 914                }
 915
 916                assert(x->baselen == 0 || x->base[x->baselen - 1] == '/');
 917                if (match_pathname(pathname, pathlen,
 918                                   x->base, x->baselen ? x->baselen - 1 : 0,
 919                                   exclude, prefix, x->patternlen, x->flags)) {
 920                        exc = x;
 921                        break;
 922                }
 923        }
 924        return exc;
 925}
 926
 927/*
 928 * Scan the list and let the last match determine the fate.
 929 * Return 1 for exclude, 0 for include and -1 for undecided.
 930 */
 931int is_excluded_from_list(const char *pathname,
 932                          int pathlen, const char *basename, int *dtype,
 933                          struct exclude_list *el)
 934{
 935        struct exclude *exclude;
 936        exclude = last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el);
 937        if (exclude)
 938                return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
 939        return -1; /* undecided */
 940}
 941
 942static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir,
 943                const char *pathname, int pathlen, const char *basename,
 944                int *dtype_p)
 945{
 946        int i, j;
 947        struct exclude_list_group *group;
 948        struct exclude *exclude;
 949        for (i = EXC_CMDL; i <= EXC_FILE; i++) {
 950                group = &dir->exclude_list_group[i];
 951                for (j = group->nr - 1; j >= 0; j--) {
 952                        exclude = last_exclude_matching_from_list(
 953                                pathname, pathlen, basename, dtype_p,
 954                                &group->el[j]);
 955                        if (exclude)
 956                                return exclude;
 957                }
 958        }
 959        return NULL;
 960}
 961
 962/*
 963 * Loads the per-directory exclude list for the substring of base
 964 * which has a char length of baselen.
 965 */
 966static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
 967{
 968        struct exclude_list_group *group;
 969        struct exclude_list *el;
 970        struct exclude_stack *stk = NULL;
 971        struct untracked_cache_dir *untracked;
 972        int current;
 973
 974        group = &dir->exclude_list_group[EXC_DIRS];
 975
 976        /*
 977         * Pop the exclude lists from the EXCL_DIRS exclude_list_group
 978         * which originate from directories not in the prefix of the
 979         * path being checked.
 980         */
 981        while ((stk = dir->exclude_stack) != NULL) {
 982                if (stk->baselen <= baselen &&
 983                    !strncmp(dir->basebuf.buf, base, stk->baselen))
 984                        break;
 985                el = &group->el[dir->exclude_stack->exclude_ix];
 986                dir->exclude_stack = stk->prev;
 987                dir->exclude = NULL;
 988                free((char *)el->src); /* see strbuf_detach() below */
 989                clear_exclude_list(el);
 990                free(stk);
 991                group->nr--;
 992        }
 993
 994        /* Skip traversing into sub directories if the parent is excluded */
 995        if (dir->exclude)
 996                return;
 997
 998        /*
 999         * Lazy initialization. All call sites currently just
1000         * memset(dir, 0, sizeof(*dir)) before use. Changing all of
1001         * them seems lots of work for little benefit.
1002         */
1003        if (!dir->basebuf.buf)
1004                strbuf_init(&dir->basebuf, PATH_MAX);
1005
1006        /* Read from the parent directories and push them down. */
1007        current = stk ? stk->baselen : -1;
1008        strbuf_setlen(&dir->basebuf, current < 0 ? 0 : current);
1009        if (dir->untracked)
1010                untracked = stk ? stk->ucd : dir->untracked->root;
1011        else
1012                untracked = NULL;
1013
1014        while (current < baselen) {
1015                const char *cp;
1016                struct sha1_stat sha1_stat;
1017
1018                stk = xcalloc(1, sizeof(*stk));
1019                if (current < 0) {
1020                        cp = base;
1021                        current = 0;
1022                } else {
1023                        cp = strchr(base + current + 1, '/');
1024                        if (!cp)
1025                                die("oops in prep_exclude");
1026                        cp++;
1027                        untracked =
1028                                lookup_untracked(dir->untracked, untracked,
1029                                                 base + current,
1030                                                 cp - base - current);
1031                }
1032                stk->prev = dir->exclude_stack;
1033                stk->baselen = cp - base;
1034                stk->exclude_ix = group->nr;
1035                stk->ucd = untracked;
1036                el = add_exclude_list(dir, EXC_DIRS, NULL);
1037                strbuf_add(&dir->basebuf, base + current, stk->baselen - current);
1038                assert(stk->baselen == dir->basebuf.len);
1039
1040                /* Abort if the directory is excluded */
1041                if (stk->baselen) {
1042                        int dt = DT_DIR;
1043                        dir->basebuf.buf[stk->baselen - 1] = 0;
1044                        dir->exclude = last_exclude_matching_from_lists(dir,
1045                                dir->basebuf.buf, stk->baselen - 1,
1046                                dir->basebuf.buf + current, &dt);
1047                        dir->basebuf.buf[stk->baselen - 1] = '/';
1048                        if (dir->exclude &&
1049                            dir->exclude->flags & EXC_FLAG_NEGATIVE)
1050                                dir->exclude = NULL;
1051                        if (dir->exclude) {
1052                                dir->exclude_stack = stk;
1053                                return;
1054                        }
1055                }
1056
1057                /* Try to read per-directory file */
1058                hashclr(sha1_stat.sha1);
1059                sha1_stat.valid = 0;
1060                if (dir->exclude_per_dir &&
1061                    /*
1062                     * If we know that no files have been added in
1063                     * this directory (i.e. valid_cached_dir() has
1064                     * been executed and set untracked->valid) ..
1065                     */
1066                    (!untracked || !untracked->valid ||
1067                     /*
1068                      * .. and .gitignore does not exist before
1069                      * (i.e. null exclude_sha1). Then we can skip
1070                      * loading .gitignore, which would result in
1071                      * ENOENT anyway.
1072                      */
1073                     !is_null_sha1(untracked->exclude_sha1))) {
1074                        /*
1075                         * dir->basebuf gets reused by the traversal, but we
1076                         * need fname to remain unchanged to ensure the src
1077                         * member of each struct exclude correctly
1078                         * back-references its source file.  Other invocations
1079                         * of add_exclude_list provide stable strings, so we
1080                         * strbuf_detach() and free() here in the caller.
1081                         */
1082                        struct strbuf sb = STRBUF_INIT;
1083                        strbuf_addbuf(&sb, &dir->basebuf);
1084                        strbuf_addstr(&sb, dir->exclude_per_dir);
1085                        el->src = strbuf_detach(&sb, NULL);
1086                        add_excludes(el->src, el->src, stk->baselen, el, 1,
1087                                     untracked ? &sha1_stat : NULL);
1088                }
1089                /*
1090                 * NEEDSWORK: when untracked cache is enabled, prep_exclude()
1091                 * will first be called in valid_cached_dir() then maybe many
1092                 * times more in last_exclude_matching(). When the cache is
1093                 * used, last_exclude_matching() will not be called and
1094                 * reading .gitignore content will be a waste.
1095                 *
1096                 * So when it's called by valid_cached_dir() and we can get
1097                 * .gitignore SHA-1 from the index (i.e. .gitignore is not
1098                 * modified on work tree), we could delay reading the
1099                 * .gitignore content until we absolutely need it in
1100                 * last_exclude_matching(). Be careful about ignore rule
1101                 * order, though, if you do that.
1102                 */
1103                if (untracked &&
1104                    hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {
1105                        invalidate_gitignore(dir->untracked, untracked);
1106                        hashcpy(untracked->exclude_sha1, sha1_stat.sha1);
1107                }
1108                dir->exclude_stack = stk;
1109                current = stk->baselen;
1110        }
1111        strbuf_setlen(&dir->basebuf, baselen);
1112}
1113
1114/*
1115 * Loads the exclude lists for the directory containing pathname, then
1116 * scans all exclude lists to determine whether pathname is excluded.
1117 * Returns the exclude_list element which matched, or NULL for
1118 * undecided.
1119 */
1120struct exclude *last_exclude_matching(struct dir_struct *dir,
1121                                             const char *pathname,
1122                                             int *dtype_p)
1123{
1124        int pathlen = strlen(pathname);
1125        const char *basename = strrchr(pathname, '/');
1126        basename = (basename) ? basename+1 : pathname;
1127
1128        prep_exclude(dir, pathname, basename-pathname);
1129
1130        if (dir->exclude)
1131                return dir->exclude;
1132
1133        return last_exclude_matching_from_lists(dir, pathname, pathlen,
1134                        basename, dtype_p);
1135}
1136
1137/*
1138 * Loads the exclude lists for the directory containing pathname, then
1139 * scans all exclude lists to determine whether pathname is excluded.
1140 * Returns 1 if true, otherwise 0.
1141 */
1142int is_excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
1143{
1144        struct exclude *exclude =
1145                last_exclude_matching(dir, pathname, dtype_p);
1146        if (exclude)
1147                return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
1148        return 0;
1149}
1150
1151static struct dir_entry *dir_entry_new(const char *pathname, int len)
1152{
1153        struct dir_entry *ent;
1154
1155        FLEX_ALLOC_MEM(ent, name, pathname, len);
1156        ent->len = len;
1157        return ent;
1158}
1159
1160static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
1161{
1162        if (cache_file_exists(pathname, len, ignore_case))
1163                return NULL;
1164
1165        ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
1166        return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
1167}
1168
1169struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
1170{
1171        if (!cache_name_is_other(pathname, len))
1172                return NULL;
1173
1174        ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
1175        return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
1176}
1177
1178enum exist_status {
1179        index_nonexistent = 0,
1180        index_directory,
1181        index_gitdir
1182};
1183
1184/*
1185 * Do not use the alphabetically sorted index to look up
1186 * the directory name; instead, use the case insensitive
1187 * directory hash.
1188 */
1189static enum exist_status directory_exists_in_index_icase(const char *dirname, int len)
1190{
1191        struct cache_entry *ce;
1192
1193        if (cache_dir_exists(dirname, len))
1194                return index_directory;
1195
1196        ce = cache_file_exists(dirname, len, ignore_case);
1197        if (ce && S_ISGITLINK(ce->ce_mode))
1198                return index_gitdir;
1199
1200        return index_nonexistent;
1201}
1202
1203/*
1204 * The index sorts alphabetically by entry name, which
1205 * means that a gitlink sorts as '\0' at the end, while
1206 * a directory (which is defined not as an entry, but as
1207 * the files it contains) will sort with the '/' at the
1208 * end.
1209 */
1210static enum exist_status directory_exists_in_index(const char *dirname, int len)
1211{
1212        int pos;
1213
1214        if (ignore_case)
1215                return directory_exists_in_index_icase(dirname, len);
1216
1217        pos = cache_name_pos(dirname, len);
1218        if (pos < 0)
1219                pos = -pos-1;
1220        while (pos < active_nr) {
1221                const struct cache_entry *ce = active_cache[pos++];
1222                unsigned char endchar;
1223
1224                if (strncmp(ce->name, dirname, len))
1225                        break;
1226                endchar = ce->name[len];
1227                if (endchar > '/')
1228                        break;
1229                if (endchar == '/')
1230                        return index_directory;
1231                if (!endchar && S_ISGITLINK(ce->ce_mode))
1232                        return index_gitdir;
1233        }
1234        return index_nonexistent;
1235}
1236
1237/*
1238 * When we find a directory when traversing the filesystem, we
1239 * have three distinct cases:
1240 *
1241 *  - ignore it
1242 *  - see it as a directory
1243 *  - recurse into it
1244 *
1245 * and which one we choose depends on a combination of existing
1246 * git index contents and the flags passed into the directory
1247 * traversal routine.
1248 *
1249 * Case 1: If we *already* have entries in the index under that
1250 * directory name, we always recurse into the directory to see
1251 * all the files.
1252 *
1253 * Case 2: If we *already* have that directory name as a gitlink,
1254 * we always continue to see it as a gitlink, regardless of whether
1255 * there is an actual git directory there or not (it might not
1256 * be checked out as a subproject!)
1257 *
1258 * Case 3: if we didn't have it in the index previously, we
1259 * have a few sub-cases:
1260 *
1261 *  (a) if "show_other_directories" is true, we show it as
1262 *      just a directory, unless "hide_empty_directories" is
1263 *      also true, in which case we need to check if it contains any
1264 *      untracked and / or ignored files.
1265 *  (b) if it looks like a git directory, and we don't have
1266 *      'no_gitlinks' set we treat it as a gitlink, and show it
1267 *      as a directory.
1268 *  (c) otherwise, we recurse into it.
1269 */
1270static enum path_treatment treat_directory(struct dir_struct *dir,
1271        struct untracked_cache_dir *untracked,
1272        const char *dirname, int len, int baselen, int exclude,
1273        const struct path_simplify *simplify)
1274{
1275        /* The "len-1" is to strip the final '/' */
1276        switch (directory_exists_in_index(dirname, len-1)) {
1277        case index_directory:
1278                return path_recurse;
1279
1280        case index_gitdir:
1281                return path_none;
1282
1283        case index_nonexistent:
1284                if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
1285                        break;
1286                if (!(dir->flags & DIR_NO_GITLINKS)) {
1287                        unsigned char sha1[20];
1288                        if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
1289                                return path_untracked;
1290                }
1291                return path_recurse;
1292        }
1293
1294        /* This is the "show_other_directories" case */
1295
1296        if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1297                return exclude ? path_excluded : path_untracked;
1298
1299        untracked = lookup_untracked(dir->untracked, untracked,
1300                                     dirname + baselen, len - baselen);
1301        return read_directory_recursive(dir, dirname, len,
1302                                        untracked, 1, simplify);
1303}
1304
1305/*
1306 * This is an inexact early pruning of any recursive directory
1307 * reading - if the path cannot possibly be in the pathspec,
1308 * return true, and we'll skip it early.
1309 */
1310static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
1311{
1312        if (simplify) {
1313                for (;;) {
1314                        const char *match = simplify->path;
1315                        int len = simplify->len;
1316
1317                        if (!match)
1318                                break;
1319                        if (len > pathlen)
1320                                len = pathlen;
1321                        if (!memcmp(path, match, len))
1322                                return 0;
1323                        simplify++;
1324                }
1325                return 1;
1326        }
1327        return 0;
1328}
1329
1330/*
1331 * This function tells us whether an excluded path matches a
1332 * list of "interesting" pathspecs. That is, whether a path matched
1333 * by any of the pathspecs could possibly be ignored by excluding
1334 * the specified path. This can happen if:
1335 *
1336 *   1. the path is mentioned explicitly in the pathspec
1337 *
1338 *   2. the path is a directory prefix of some element in the
1339 *      pathspec
1340 */
1341static int exclude_matches_pathspec(const char *path, int len,
1342                const struct path_simplify *simplify)
1343{
1344        if (simplify) {
1345                for (; simplify->path; simplify++) {
1346                        if (len == simplify->len
1347                            && !memcmp(path, simplify->path, len))
1348                                return 1;
1349                        if (len < simplify->len
1350                            && simplify->path[len] == '/'
1351                            && !memcmp(path, simplify->path, len))
1352                                return 1;
1353                }
1354        }
1355        return 0;
1356}
1357
1358static int get_index_dtype(const char *path, int len)
1359{
1360        int pos;
1361        const struct cache_entry *ce;
1362
1363        ce = cache_file_exists(path, len, 0);
1364        if (ce) {
1365                if (!ce_uptodate(ce))
1366                        return DT_UNKNOWN;
1367                if (S_ISGITLINK(ce->ce_mode))
1368                        return DT_DIR;
1369                /*
1370                 * Nobody actually cares about the
1371                 * difference between DT_LNK and DT_REG
1372                 */
1373                return DT_REG;
1374        }
1375
1376        /* Try to look it up as a directory */
1377        pos = cache_name_pos(path, len);
1378        if (pos >= 0)
1379                return DT_UNKNOWN;
1380        pos = -pos-1;
1381        while (pos < active_nr) {
1382                ce = active_cache[pos++];
1383                if (strncmp(ce->name, path, len))
1384                        break;
1385                if (ce->name[len] > '/')
1386                        break;
1387                if (ce->name[len] < '/')
1388                        continue;
1389                if (!ce_uptodate(ce))
1390                        break;  /* continue? */
1391                return DT_DIR;
1392        }
1393        return DT_UNKNOWN;
1394}
1395
1396static int get_dtype(struct dirent *de, const char *path, int len)
1397{
1398        int dtype = de ? DTYPE(de) : DT_UNKNOWN;
1399        struct stat st;
1400
1401        if (dtype != DT_UNKNOWN)
1402                return dtype;
1403        dtype = get_index_dtype(path, len);
1404        if (dtype != DT_UNKNOWN)
1405                return dtype;
1406        if (lstat(path, &st))
1407                return dtype;
1408        if (S_ISREG(st.st_mode))
1409                return DT_REG;
1410        if (S_ISDIR(st.st_mode))
1411                return DT_DIR;
1412        if (S_ISLNK(st.st_mode))
1413                return DT_LNK;
1414        return dtype;
1415}
1416
1417static enum path_treatment treat_one_path(struct dir_struct *dir,
1418                                          struct untracked_cache_dir *untracked,
1419                                          struct strbuf *path,
1420                                          int baselen,
1421                                          const struct path_simplify *simplify,
1422                                          int dtype, struct dirent *de)
1423{
1424        int exclude;
1425        int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);
1426
1427        if (dtype == DT_UNKNOWN)
1428                dtype = get_dtype(de, path->buf, path->len);
1429
1430        /* Always exclude indexed files */
1431        if (dtype != DT_DIR && has_path_in_index)
1432                return path_none;
1433
1434        /*
1435         * When we are looking at a directory P in the working tree,
1436         * there are three cases:
1437         *
1438         * (1) P exists in the index.  Everything inside the directory P in
1439         * the working tree needs to go when P is checked out from the
1440         * index.
1441         *
1442         * (2) P does not exist in the index, but there is P/Q in the index.
1443         * We know P will stay a directory when we check out the contents
1444         * of the index, but we do not know yet if there is a directory
1445         * P/Q in the working tree to be killed, so we need to recurse.
1446         *
1447         * (3) P does not exist in the index, and there is no P/Q in the index
1448         * to require P to be a directory, either.  Only in this case, we
1449         * know that everything inside P will not be killed without
1450         * recursing.
1451         */
1452        if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
1453            (dtype == DT_DIR) &&
1454            !has_path_in_index &&
1455            (directory_exists_in_index(path->buf, path->len) == index_nonexistent))
1456                return path_none;
1457
1458        exclude = is_excluded(dir, path->buf, &dtype);
1459
1460        /*
1461         * Excluded? If we don't explicitly want to show
1462         * ignored files, ignore it
1463         */
1464        if (exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
1465                return path_excluded;
1466
1467        switch (dtype) {
1468        default:
1469                return path_none;
1470        case DT_DIR:
1471                strbuf_addch(path, '/');
1472                return treat_directory(dir, untracked, path->buf, path->len,
1473                                       baselen, exclude, simplify);
1474        case DT_REG:
1475        case DT_LNK:
1476                return exclude ? path_excluded : path_untracked;
1477        }
1478}
1479
1480static enum path_treatment treat_path_fast(struct dir_struct *dir,
1481                                           struct untracked_cache_dir *untracked,
1482                                           struct cached_dir *cdir,
1483                                           struct strbuf *path,
1484                                           int baselen,
1485                                           const struct path_simplify *simplify)
1486{
1487        strbuf_setlen(path, baselen);
1488        if (!cdir->ucd) {
1489                strbuf_addstr(path, cdir->file);
1490                return path_untracked;
1491        }
1492        strbuf_addstr(path, cdir->ucd->name);
1493        /* treat_one_path() does this before it calls treat_directory() */
1494        strbuf_complete(path, '/');
1495        if (cdir->ucd->check_only)
1496                /*
1497                 * check_only is set as a result of treat_directory() getting
1498                 * to its bottom. Verify again the same set of directories
1499                 * with check_only set.
1500                 */
1501                return read_directory_recursive(dir, path->buf, path->len,
1502                                                cdir->ucd, 1, simplify);
1503        /*
1504         * We get path_recurse in the first run when
1505         * directory_exists_in_index() returns index_nonexistent. We
1506         * are sure that new changes in the index does not impact the
1507         * outcome. Return now.
1508         */
1509        return path_recurse;
1510}
1511
1512static enum path_treatment treat_path(struct dir_struct *dir,
1513                                      struct untracked_cache_dir *untracked,
1514                                      struct cached_dir *cdir,
1515                                      struct strbuf *path,
1516                                      int baselen,
1517                                      const struct path_simplify *simplify)
1518{
1519        int dtype;
1520        struct dirent *de = cdir->de;
1521
1522        if (!de)
1523                return treat_path_fast(dir, untracked, cdir, path,
1524                                       baselen, simplify);
1525        if (is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name, ".git"))
1526                return path_none;
1527        strbuf_setlen(path, baselen);
1528        strbuf_addstr(path, de->d_name);
1529        if (simplify_away(path->buf, path->len, simplify))
1530                return path_none;
1531
1532        dtype = DTYPE(de);
1533        return treat_one_path(dir, untracked, path, baselen, simplify, dtype, de);
1534}
1535
1536static void add_untracked(struct untracked_cache_dir *dir, const char *name)
1537{
1538        if (!dir)
1539                return;
1540        ALLOC_GROW(dir->untracked, dir->untracked_nr + 1,
1541                   dir->untracked_alloc);
1542        dir->untracked[dir->untracked_nr++] = xstrdup(name);
1543}
1544
1545static int valid_cached_dir(struct dir_struct *dir,
1546                            struct untracked_cache_dir *untracked,
1547                            struct strbuf *path,
1548                            int check_only)
1549{
1550        struct stat st;
1551
1552        if (!untracked)
1553                return 0;
1554
1555        if (stat(path->len ? path->buf : ".", &st)) {
1556                invalidate_directory(dir->untracked, untracked);
1557                memset(&untracked->stat_data, 0, sizeof(untracked->stat_data));
1558                return 0;
1559        }
1560        if (!untracked->valid ||
1561            match_stat_data_racy(&the_index, &untracked->stat_data, &st)) {
1562                if (untracked->valid)
1563                        invalidate_directory(dir->untracked, untracked);
1564                fill_stat_data(&untracked->stat_data, &st);
1565                return 0;
1566        }
1567
1568        if (untracked->check_only != !!check_only) {
1569                invalidate_directory(dir->untracked, untracked);
1570                return 0;
1571        }
1572
1573        /*
1574         * prep_exclude will be called eventually on this directory,
1575         * but it's called much later in last_exclude_matching(). We
1576         * need it now to determine the validity of the cache for this
1577         * path. The next calls will be nearly no-op, the way
1578         * prep_exclude() is designed.
1579         */
1580        if (path->len && path->buf[path->len - 1] != '/') {
1581                strbuf_addch(path, '/');
1582                prep_exclude(dir, path->buf, path->len);
1583                strbuf_setlen(path, path->len - 1);
1584        } else
1585                prep_exclude(dir, path->buf, path->len);
1586
1587        /* hopefully prep_exclude() haven't invalidated this entry... */
1588        return untracked->valid;
1589}
1590
1591static int open_cached_dir(struct cached_dir *cdir,
1592                           struct dir_struct *dir,
1593                           struct untracked_cache_dir *untracked,
1594                           struct strbuf *path,
1595                           int check_only)
1596{
1597        memset(cdir, 0, sizeof(*cdir));
1598        cdir->untracked = untracked;
1599        if (valid_cached_dir(dir, untracked, path, check_only))
1600                return 0;
1601        cdir->fdir = opendir(path->len ? path->buf : ".");
1602        if (dir->untracked)
1603                dir->untracked->dir_opened++;
1604        if (!cdir->fdir)
1605                return -1;
1606        return 0;
1607}
1608
1609static int read_cached_dir(struct cached_dir *cdir)
1610{
1611        if (cdir->fdir) {
1612                cdir->de = readdir(cdir->fdir);
1613                if (!cdir->de)
1614                        return -1;
1615                return 0;
1616        }
1617        while (cdir->nr_dirs < cdir->untracked->dirs_nr) {
1618                struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];
1619                if (!d->recurse) {
1620                        cdir->nr_dirs++;
1621                        continue;
1622                }
1623                cdir->ucd = d;
1624                cdir->nr_dirs++;
1625                return 0;
1626        }
1627        cdir->ucd = NULL;
1628        if (cdir->nr_files < cdir->untracked->untracked_nr) {
1629                struct untracked_cache_dir *d = cdir->untracked;
1630                cdir->file = d->untracked[cdir->nr_files++];
1631                return 0;
1632        }
1633        return -1;
1634}
1635
1636static void close_cached_dir(struct cached_dir *cdir)
1637{
1638        if (cdir->fdir)
1639                closedir(cdir->fdir);
1640        /*
1641         * We have gone through this directory and found no untracked
1642         * entries. Mark it valid.
1643         */
1644        if (cdir->untracked) {
1645                cdir->untracked->valid = 1;
1646                cdir->untracked->recurse = 1;
1647        }
1648}
1649
1650/*
1651 * Read a directory tree. We currently ignore anything but
1652 * directories, regular files and symlinks. That's because git
1653 * doesn't handle them at all yet. Maybe that will change some
1654 * day.
1655 *
1656 * Also, we ignore the name ".git" (even if it is not a directory).
1657 * That likely will not change.
1658 *
1659 * Returns the most significant path_treatment value encountered in the scan.
1660 */
1661static enum path_treatment read_directory_recursive(struct dir_struct *dir,
1662                                    const char *base, int baselen,
1663                                    struct untracked_cache_dir *untracked, int check_only,
1664                                    const struct path_simplify *simplify)
1665{
1666        struct cached_dir cdir;
1667        enum path_treatment state, subdir_state, dir_state = path_none;
1668        struct strbuf path = STRBUF_INIT;
1669
1670        strbuf_add(&path, base, baselen);
1671
1672        if (open_cached_dir(&cdir, dir, untracked, &path, check_only))
1673                goto out;
1674
1675        if (untracked)
1676                untracked->check_only = !!check_only;
1677
1678        while (!read_cached_dir(&cdir)) {
1679                /* check how the file or directory should be treated */
1680                state = treat_path(dir, untracked, &cdir, &path, baselen, simplify);
1681
1682                if (state > dir_state)
1683                        dir_state = state;
1684
1685                /* recurse into subdir if instructed by treat_path */
1686                if (state == path_recurse) {
1687                        struct untracked_cache_dir *ud;
1688                        ud = lookup_untracked(dir->untracked, untracked,
1689                                              path.buf + baselen,
1690                                              path.len - baselen);
1691                        subdir_state =
1692                                read_directory_recursive(dir, path.buf, path.len,
1693                                                         ud, check_only, simplify);
1694                        if (subdir_state > dir_state)
1695                                dir_state = subdir_state;
1696                }
1697
1698                if (check_only) {
1699                        /* abort early if maximum state has been reached */
1700                        if (dir_state == path_untracked) {
1701                                if (cdir.fdir)
1702                                        add_untracked(untracked, path.buf + baselen);
1703                                break;
1704                        }
1705                        /* skip the dir_add_* part */
1706                        continue;
1707                }
1708
1709                /* add the path to the appropriate result list */
1710                switch (state) {
1711                case path_excluded:
1712                        if (dir->flags & DIR_SHOW_IGNORED)
1713                                dir_add_name(dir, path.buf, path.len);
1714                        else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
1715                                ((dir->flags & DIR_COLLECT_IGNORED) &&
1716                                exclude_matches_pathspec(path.buf, path.len,
1717                                        simplify)))
1718                                dir_add_ignored(dir, path.buf, path.len);
1719                        break;
1720
1721                case path_untracked:
1722                        if (dir->flags & DIR_SHOW_IGNORED)
1723                                break;
1724                        dir_add_name(dir, path.buf, path.len);
1725                        if (cdir.fdir)
1726                                add_untracked(untracked, path.buf + baselen);
1727                        break;
1728
1729                default:
1730                        break;
1731                }
1732        }
1733        close_cached_dir(&cdir);
1734 out:
1735        strbuf_release(&path);
1736
1737        return dir_state;
1738}
1739
1740static int cmp_name(const void *p1, const void *p2)
1741{
1742        const struct dir_entry *e1 = *(const struct dir_entry **)p1;
1743        const struct dir_entry *e2 = *(const struct dir_entry **)p2;
1744
1745        return name_compare(e1->name, e1->len, e2->name, e2->len);
1746}
1747
1748static struct path_simplify *create_simplify(const char **pathspec)
1749{
1750        int nr, alloc = 0;
1751        struct path_simplify *simplify = NULL;
1752
1753        if (!pathspec)
1754                return NULL;
1755
1756        for (nr = 0 ; ; nr++) {
1757                const char *match;
1758                ALLOC_GROW(simplify, nr + 1, alloc);
1759                match = *pathspec++;
1760                if (!match)
1761                        break;
1762                simplify[nr].path = match;
1763                simplify[nr].len = simple_length(match);
1764        }
1765        simplify[nr].path = NULL;
1766        simplify[nr].len = 0;
1767        return simplify;
1768}
1769
1770static void free_simplify(struct path_simplify *simplify)
1771{
1772        free(simplify);
1773}
1774
1775static int treat_leading_path(struct dir_struct *dir,
1776                              const char *path, int len,
1777                              const struct path_simplify *simplify)
1778{
1779        struct strbuf sb = STRBUF_INIT;
1780        int baselen, rc = 0;
1781        const char *cp;
1782        int old_flags = dir->flags;
1783
1784        while (len && path[len - 1] == '/')
1785                len--;
1786        if (!len)
1787                return 1;
1788        baselen = 0;
1789        dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;
1790        while (1) {
1791                cp = path + baselen + !!baselen;
1792                cp = memchr(cp, '/', path + len - cp);
1793                if (!cp)
1794                        baselen = len;
1795                else
1796                        baselen = cp - path;
1797                strbuf_setlen(&sb, 0);
1798                strbuf_add(&sb, path, baselen);
1799                if (!is_directory(sb.buf))
1800                        break;
1801                if (simplify_away(sb.buf, sb.len, simplify))
1802                        break;
1803                if (treat_one_path(dir, NULL, &sb, baselen, simplify,
1804                                   DT_DIR, NULL) == path_none)
1805                        break; /* do not recurse into it */
1806                if (len <= baselen) {
1807                        rc = 1;
1808                        break; /* finished checking */
1809                }
1810        }
1811        strbuf_release(&sb);
1812        dir->flags = old_flags;
1813        return rc;
1814}
1815
1816static const char *get_ident_string(void)
1817{
1818        static struct strbuf sb = STRBUF_INIT;
1819        struct utsname uts;
1820
1821        if (sb.len)
1822                return sb.buf;
1823        if (uname(&uts) < 0)
1824                die_errno(_("failed to get kernel name and information"));
1825        strbuf_addf(&sb, "Location %s, system %s", get_git_work_tree(),
1826                    uts.sysname);
1827        return sb.buf;
1828}
1829
1830static int ident_in_untracked(const struct untracked_cache *uc)
1831{
1832        /*
1833         * Previous git versions may have saved many NUL separated
1834         * strings in the "ident" field, but it is insane to manage
1835         * many locations, so just take care of the first one.
1836         */
1837
1838        return !strcmp(uc->ident.buf, get_ident_string());
1839}
1840
1841static void set_untracked_ident(struct untracked_cache *uc)
1842{
1843        strbuf_reset(&uc->ident);
1844        strbuf_addstr(&uc->ident, get_ident_string());
1845
1846        /*
1847         * This strbuf used to contain a list of NUL separated
1848         * strings, so save NUL too for backward compatibility.
1849         */
1850        strbuf_addch(&uc->ident, 0);
1851}
1852
1853static void new_untracked_cache(struct index_state *istate)
1854{
1855        struct untracked_cache *uc = xcalloc(1, sizeof(*uc));
1856        strbuf_init(&uc->ident, 100);
1857        uc->exclude_per_dir = ".gitignore";
1858        /* should be the same flags used by git-status */
1859        uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;
1860        set_untracked_ident(uc);
1861        istate->untracked = uc;
1862        istate->cache_changed |= UNTRACKED_CHANGED;
1863}
1864
1865void add_untracked_cache(struct index_state *istate)
1866{
1867        if (!istate->untracked) {
1868                new_untracked_cache(istate);
1869        } else {
1870                if (!ident_in_untracked(istate->untracked)) {
1871                        free_untracked_cache(istate->untracked);
1872                        new_untracked_cache(istate);
1873                }
1874        }
1875}
1876
1877void remove_untracked_cache(struct index_state *istate)
1878{
1879        if (istate->untracked) {
1880                free_untracked_cache(istate->untracked);
1881                istate->untracked = NULL;
1882                istate->cache_changed |= UNTRACKED_CHANGED;
1883        }
1884}
1885
1886static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,
1887                                                      int base_len,
1888                                                      const struct pathspec *pathspec)
1889{
1890        struct untracked_cache_dir *root;
1891
1892        if (!dir->untracked || getenv("GIT_DISABLE_UNTRACKED_CACHE"))
1893                return NULL;
1894
1895        /*
1896         * We only support $GIT_DIR/info/exclude and core.excludesfile
1897         * as the global ignore rule files. Any other additions
1898         * (e.g. from command line) invalidate the cache. This
1899         * condition also catches running setup_standard_excludes()
1900         * before setting dir->untracked!
1901         */
1902        if (dir->unmanaged_exclude_files)
1903                return NULL;
1904
1905        /*
1906         * Optimize for the main use case only: whole-tree git
1907         * status. More work involved in treat_leading_path() if we
1908         * use cache on just a subset of the worktree. pathspec
1909         * support could make the matter even worse.
1910         */
1911        if (base_len || (pathspec && pathspec->nr))
1912                return NULL;
1913
1914        /* Different set of flags may produce different results */
1915        if (dir->flags != dir->untracked->dir_flags ||
1916            /*
1917             * See treat_directory(), case index_nonexistent. Without
1918             * this flag, we may need to also cache .git file content
1919             * for the resolve_gitlink_ref() call, which we don't.
1920             */
1921            !(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||
1922            /* We don't support collecting ignore files */
1923            (dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |
1924                           DIR_COLLECT_IGNORED)))
1925                return NULL;
1926
1927        /*
1928         * If we use .gitignore in the cache and now you change it to
1929         * .gitexclude, everything will go wrong.
1930         */
1931        if (dir->exclude_per_dir != dir->untracked->exclude_per_dir &&
1932            strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))
1933                return NULL;
1934
1935        /*
1936         * EXC_CMDL is not considered in the cache. If people set it,
1937         * skip the cache.
1938         */
1939        if (dir->exclude_list_group[EXC_CMDL].nr)
1940                return NULL;
1941
1942        if (!ident_in_untracked(dir->untracked)) {
1943                warning(_("Untracked cache is disabled on this system or location."));
1944                return NULL;
1945        }
1946
1947        if (!dir->untracked->root) {
1948                const int len = sizeof(*dir->untracked->root);
1949                dir->untracked->root = xmalloc(len);
1950                memset(dir->untracked->root, 0, len);
1951        }
1952
1953        /* Validate $GIT_DIR/info/exclude and core.excludesfile */
1954        root = dir->untracked->root;
1955        if (hashcmp(dir->ss_info_exclude.sha1,
1956                    dir->untracked->ss_info_exclude.sha1)) {
1957                invalidate_gitignore(dir->untracked, root);
1958                dir->untracked->ss_info_exclude = dir->ss_info_exclude;
1959        }
1960        if (hashcmp(dir->ss_excludes_file.sha1,
1961                    dir->untracked->ss_excludes_file.sha1)) {
1962                invalidate_gitignore(dir->untracked, root);
1963                dir->untracked->ss_excludes_file = dir->ss_excludes_file;
1964        }
1965
1966        /* Make sure this directory is not dropped out at saving phase */
1967        root->recurse = 1;
1968        return root;
1969}
1970
1971int read_directory(struct dir_struct *dir, const char *path, int len, const struct pathspec *pathspec)
1972{
1973        struct path_simplify *simplify;
1974        struct untracked_cache_dir *untracked;
1975
1976        /*
1977         * Check out create_simplify()
1978         */
1979        if (pathspec)
1980                GUARD_PATHSPEC(pathspec,
1981                               PATHSPEC_FROMTOP |
1982                               PATHSPEC_MAXDEPTH |
1983                               PATHSPEC_LITERAL |
1984                               PATHSPEC_GLOB |
1985                               PATHSPEC_ICASE |
1986                               PATHSPEC_EXCLUDE);
1987
1988        if (has_symlink_leading_path(path, len))
1989                return dir->nr;
1990
1991        /*
1992         * exclude patterns are treated like positive ones in
1993         * create_simplify. Usually exclude patterns should be a
1994         * subset of positive ones, which has no impacts on
1995         * create_simplify().
1996         */
1997        simplify = create_simplify(pathspec ? pathspec->_raw : NULL);
1998        untracked = validate_untracked_cache(dir, len, pathspec);
1999        if (!untracked)
2000                /*
2001                 * make sure untracked cache code path is disabled,
2002                 * e.g. prep_exclude()
2003                 */
2004                dir->untracked = NULL;
2005        if (!len || treat_leading_path(dir, path, len, simplify))
2006                read_directory_recursive(dir, path, len, untracked, 0, simplify);
2007        free_simplify(simplify);
2008        qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
2009        qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
2010        if (dir->untracked) {
2011                static struct trace_key trace_untracked_stats = TRACE_KEY_INIT(UNTRACKED_STATS);
2012                trace_printf_key(&trace_untracked_stats,
2013                                 "node creation: %u\n"
2014                                 "gitignore invalidation: %u\n"
2015                                 "directory invalidation: %u\n"
2016                                 "opendir: %u\n",
2017                                 dir->untracked->dir_created,
2018                                 dir->untracked->gitignore_invalidated,
2019                                 dir->untracked->dir_invalidated,
2020                                 dir->untracked->dir_opened);
2021                if (dir->untracked == the_index.untracked &&
2022                    (dir->untracked->dir_opened ||
2023                     dir->untracked->gitignore_invalidated ||
2024                     dir->untracked->dir_invalidated))
2025                        the_index.cache_changed |= UNTRACKED_CHANGED;
2026                if (dir->untracked != the_index.untracked) {
2027                        free(dir->untracked);
2028                        dir->untracked = NULL;
2029                }
2030        }
2031        return dir->nr;
2032}
2033
2034int file_exists(const char *f)
2035{
2036        struct stat sb;
2037        return lstat(f, &sb) == 0;
2038}
2039
2040static int cmp_icase(char a, char b)
2041{
2042        if (a == b)
2043                return 0;
2044        if (ignore_case)
2045                return toupper(a) - toupper(b);
2046        return a - b;
2047}
2048
2049/*
2050 * Given two normalized paths (a trailing slash is ok), if subdir is
2051 * outside dir, return -1.  Otherwise return the offset in subdir that
2052 * can be used as relative path to dir.
2053 */
2054int dir_inside_of(const char *subdir, const char *dir)
2055{
2056        int offset = 0;
2057
2058        assert(dir && subdir && *dir && *subdir);
2059
2060        while (*dir && *subdir && !cmp_icase(*dir, *subdir)) {
2061                dir++;
2062                subdir++;
2063                offset++;
2064        }
2065
2066        /* hel[p]/me vs hel[l]/yeah */
2067        if (*dir && *subdir)
2068                return -1;
2069
2070        if (!*subdir)
2071                return !*dir ? offset : -1; /* same dir */
2072
2073        /* foo/[b]ar vs foo/[] */
2074        if (is_dir_sep(dir[-1]))
2075                return is_dir_sep(subdir[-1]) ? offset : -1;
2076
2077        /* foo[/]bar vs foo[] */
2078        return is_dir_sep(*subdir) ? offset + 1 : -1;
2079}
2080
2081int is_inside_dir(const char *dir)
2082{
2083        char *cwd;
2084        int rc;
2085
2086        if (!dir)
2087                return 0;
2088
2089        cwd = xgetcwd();
2090        rc = (dir_inside_of(cwd, dir) >= 0);
2091        free(cwd);
2092        return rc;
2093}
2094
2095int is_empty_dir(const char *path)
2096{
2097        DIR *dir = opendir(path);
2098        struct dirent *e;
2099        int ret = 1;
2100
2101        if (!dir)
2102                return 0;
2103
2104        while ((e = readdir(dir)) != NULL)
2105                if (!is_dot_or_dotdot(e->d_name)) {
2106                        ret = 0;
2107                        break;
2108                }
2109
2110        closedir(dir);
2111        return ret;
2112}
2113
2114static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
2115{
2116        DIR *dir;
2117        struct dirent *e;
2118        int ret = 0, original_len = path->len, len, kept_down = 0;
2119        int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
2120        int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
2121        unsigned char submodule_head[20];
2122
2123        if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
2124            !resolve_gitlink_ref(path->buf, "HEAD", submodule_head)) {
2125                /* Do not descend and nuke a nested git work tree. */
2126                if (kept_up)
2127                        *kept_up = 1;
2128                return 0;
2129        }
2130
2131        flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
2132        dir = opendir(path->buf);
2133        if (!dir) {
2134                if (errno == ENOENT)
2135                        return keep_toplevel ? -1 : 0;
2136                else if (errno == EACCES && !keep_toplevel)
2137                        /*
2138                         * An empty dir could be removable even if it
2139                         * is unreadable:
2140                         */
2141                        return rmdir(path->buf);
2142                else
2143                        return -1;
2144        }
2145        strbuf_complete(path, '/');
2146
2147        len = path->len;
2148        while ((e = readdir(dir)) != NULL) {
2149                struct stat st;
2150                if (is_dot_or_dotdot(e->d_name))
2151                        continue;
2152
2153                strbuf_setlen(path, len);
2154                strbuf_addstr(path, e->d_name);
2155                if (lstat(path->buf, &st)) {
2156                        if (errno == ENOENT)
2157                                /*
2158                                 * file disappeared, which is what we
2159                                 * wanted anyway
2160                                 */
2161                                continue;
2162                        /* fall thru */
2163                } else if (S_ISDIR(st.st_mode)) {
2164                        if (!remove_dir_recurse(path, flag, &kept_down))
2165                                continue; /* happy */
2166                } else if (!only_empty &&
2167                           (!unlink(path->buf) || errno == ENOENT)) {
2168                        continue; /* happy, too */
2169                }
2170
2171                /* path too long, stat fails, or non-directory still exists */
2172                ret = -1;
2173                break;
2174        }
2175        closedir(dir);
2176
2177        strbuf_setlen(path, original_len);
2178        if (!ret && !keep_toplevel && !kept_down)
2179                ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1;
2180        else if (kept_up)
2181                /*
2182                 * report the uplevel that it is not an error that we
2183                 * did not rmdir() our directory.
2184                 */
2185                *kept_up = !ret;
2186        return ret;
2187}
2188
2189int remove_dir_recursively(struct strbuf *path, int flag)
2190{
2191        return remove_dir_recurse(path, flag, NULL);
2192}
2193
2194static GIT_PATH_FUNC(git_path_info_exclude, "info/exclude")
2195
2196void setup_standard_excludes(struct dir_struct *dir)
2197{
2198        const char *path;
2199
2200        dir->exclude_per_dir = ".gitignore";
2201
2202        /* core.excludefile defaulting to $XDG_HOME/git/ignore */
2203        if (!excludes_file)
2204                excludes_file = xdg_config_home("ignore");
2205        if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
2206                add_excludes_from_file_1(dir, excludes_file,
2207                                         dir->untracked ? &dir->ss_excludes_file : NULL);
2208
2209        /* per repository user preference */
2210        path = git_path_info_exclude();
2211        if (!access_or_warn(path, R_OK, 0))
2212                add_excludes_from_file_1(dir, path,
2213                                         dir->untracked ? &dir->ss_info_exclude : NULL);
2214}
2215
2216int remove_path(const char *name)
2217{
2218        char *slash;
2219
2220        if (unlink(name) && errno != ENOENT && errno != ENOTDIR)
2221                return -1;
2222
2223        slash = strrchr(name, '/');
2224        if (slash) {
2225                char *dirs = xstrdup(name);
2226                slash = dirs + (slash - name);
2227                do {
2228                        *slash = '\0';
2229                } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
2230                free(dirs);
2231        }
2232        return 0;
2233}
2234
2235/*
2236 * Frees memory within dir which was allocated for exclude lists and
2237 * the exclude_stack.  Does not free dir itself.
2238 */
2239void clear_directory(struct dir_struct *dir)
2240{
2241        int i, j;
2242        struct exclude_list_group *group;
2243        struct exclude_list *el;
2244        struct exclude_stack *stk;
2245
2246        for (i = EXC_CMDL; i <= EXC_FILE; i++) {
2247                group = &dir->exclude_list_group[i];
2248                for (j = 0; j < group->nr; j++) {
2249                        el = &group->el[j];
2250                        if (i == EXC_DIRS)
2251                                free((char *)el->src);
2252                        clear_exclude_list(el);
2253                }
2254                free(group->el);
2255        }
2256
2257        stk = dir->exclude_stack;
2258        while (stk) {
2259                struct exclude_stack *prev = stk->prev;
2260                free(stk);
2261                stk = prev;
2262        }
2263        strbuf_release(&dir->basebuf);
2264}
2265
2266struct ondisk_untracked_cache {
2267        struct stat_data info_exclude_stat;
2268        struct stat_data excludes_file_stat;
2269        uint32_t dir_flags;
2270        unsigned char info_exclude_sha1[20];
2271        unsigned char excludes_file_sha1[20];
2272        char exclude_per_dir[FLEX_ARRAY];
2273};
2274
2275#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)
2276
2277struct write_data {
2278        int index;         /* number of written untracked_cache_dir */
2279        struct ewah_bitmap *check_only; /* from untracked_cache_dir */
2280        struct ewah_bitmap *valid;      /* from untracked_cache_dir */
2281        struct ewah_bitmap *sha1_valid; /* set if exclude_sha1 is not null */
2282        struct strbuf out;
2283        struct strbuf sb_stat;
2284        struct strbuf sb_sha1;
2285};
2286
2287static void stat_data_to_disk(struct stat_data *to, const struct stat_data *from)
2288{
2289        to->sd_ctime.sec  = htonl(from->sd_ctime.sec);
2290        to->sd_ctime.nsec = htonl(from->sd_ctime.nsec);
2291        to->sd_mtime.sec  = htonl(from->sd_mtime.sec);
2292        to->sd_mtime.nsec = htonl(from->sd_mtime.nsec);
2293        to->sd_dev        = htonl(from->sd_dev);
2294        to->sd_ino        = htonl(from->sd_ino);
2295        to->sd_uid        = htonl(from->sd_uid);
2296        to->sd_gid        = htonl(from->sd_gid);
2297        to->sd_size       = htonl(from->sd_size);
2298}
2299
2300static void write_one_dir(struct untracked_cache_dir *untracked,
2301                          struct write_data *wd)
2302{
2303        struct stat_data stat_data;
2304        struct strbuf *out = &wd->out;
2305        unsigned char intbuf[16];
2306        unsigned int intlen, value;
2307        int i = wd->index++;
2308
2309        /*
2310         * untracked_nr should be reset whenever valid is clear, but
2311         * for safety..
2312         */
2313        if (!untracked->valid) {
2314                untracked->untracked_nr = 0;
2315                untracked->check_only = 0;
2316        }
2317
2318        if (untracked->check_only)
2319                ewah_set(wd->check_only, i);
2320        if (untracked->valid) {
2321                ewah_set(wd->valid, i);
2322                stat_data_to_disk(&stat_data, &untracked->stat_data);
2323                strbuf_add(&wd->sb_stat, &stat_data, sizeof(stat_data));
2324        }
2325        if (!is_null_sha1(untracked->exclude_sha1)) {
2326                ewah_set(wd->sha1_valid, i);
2327                strbuf_add(&wd->sb_sha1, untracked->exclude_sha1, 20);
2328        }
2329
2330        intlen = encode_varint(untracked->untracked_nr, intbuf);
2331        strbuf_add(out, intbuf, intlen);
2332
2333        /* skip non-recurse directories */
2334        for (i = 0, value = 0; i < untracked->dirs_nr; i++)
2335                if (untracked->dirs[i]->recurse)
2336                        value++;
2337        intlen = encode_varint(value, intbuf);
2338        strbuf_add(out, intbuf, intlen);
2339
2340        strbuf_add(out, untracked->name, strlen(untracked->name) + 1);
2341
2342        for (i = 0; i < untracked->untracked_nr; i++)
2343                strbuf_add(out, untracked->untracked[i],
2344                           strlen(untracked->untracked[i]) + 1);
2345
2346        for (i = 0; i < untracked->dirs_nr; i++)
2347                if (untracked->dirs[i]->recurse)
2348                        write_one_dir(untracked->dirs[i], wd);
2349}
2350
2351void write_untracked_extension(struct strbuf *out, struct untracked_cache *untracked)
2352{
2353        struct ondisk_untracked_cache *ouc;
2354        struct write_data wd;
2355        unsigned char varbuf[16];
2356        int varint_len;
2357        size_t len = strlen(untracked->exclude_per_dir);
2358
2359        FLEX_ALLOC_MEM(ouc, exclude_per_dir, untracked->exclude_per_dir, len);
2360        stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);
2361        stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);
2362        hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);
2363        hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);
2364        ouc->dir_flags = htonl(untracked->dir_flags);
2365
2366        varint_len = encode_varint(untracked->ident.len, varbuf);
2367        strbuf_add(out, varbuf, varint_len);
2368        strbuf_addbuf(out, &untracked->ident);
2369
2370        strbuf_add(out, ouc, ouc_size(len));
2371        free(ouc);
2372        ouc = NULL;
2373
2374        if (!untracked->root) {
2375                varint_len = encode_varint(0, varbuf);
2376                strbuf_add(out, varbuf, varint_len);
2377                return;
2378        }
2379
2380        wd.index      = 0;
2381        wd.check_only = ewah_new();
2382        wd.valid      = ewah_new();
2383        wd.sha1_valid = ewah_new();
2384        strbuf_init(&wd.out, 1024);
2385        strbuf_init(&wd.sb_stat, 1024);
2386        strbuf_init(&wd.sb_sha1, 1024);
2387        write_one_dir(untracked->root, &wd);
2388
2389        varint_len = encode_varint(wd.index, varbuf);
2390        strbuf_add(out, varbuf, varint_len);
2391        strbuf_addbuf(out, &wd.out);
2392        ewah_serialize_strbuf(wd.valid, out);
2393        ewah_serialize_strbuf(wd.check_only, out);
2394        ewah_serialize_strbuf(wd.sha1_valid, out);
2395        strbuf_addbuf(out, &wd.sb_stat);
2396        strbuf_addbuf(out, &wd.sb_sha1);
2397        strbuf_addch(out, '\0'); /* safe guard for string lists */
2398
2399        ewah_free(wd.valid);
2400        ewah_free(wd.check_only);
2401        ewah_free(wd.sha1_valid);
2402        strbuf_release(&wd.out);
2403        strbuf_release(&wd.sb_stat);
2404        strbuf_release(&wd.sb_sha1);
2405}
2406
2407static void free_untracked(struct untracked_cache_dir *ucd)
2408{
2409        int i;
2410        if (!ucd)
2411                return;
2412        for (i = 0; i < ucd->dirs_nr; i++)
2413                free_untracked(ucd->dirs[i]);
2414        for (i = 0; i < ucd->untracked_nr; i++)
2415                free(ucd->untracked[i]);
2416        free(ucd->untracked);
2417        free(ucd->dirs);
2418        free(ucd);
2419}
2420
2421void free_untracked_cache(struct untracked_cache *uc)
2422{
2423        if (uc)
2424                free_untracked(uc->root);
2425        free(uc);
2426}
2427
2428struct read_data {
2429        int index;
2430        struct untracked_cache_dir **ucd;
2431        struct ewah_bitmap *check_only;
2432        struct ewah_bitmap *valid;
2433        struct ewah_bitmap *sha1_valid;
2434        const unsigned char *data;
2435        const unsigned char *end;
2436};
2437
2438static void stat_data_from_disk(struct stat_data *to, const struct stat_data *from)
2439{
2440        to->sd_ctime.sec  = get_be32(&from->sd_ctime.sec);
2441        to->sd_ctime.nsec = get_be32(&from->sd_ctime.nsec);
2442        to->sd_mtime.sec  = get_be32(&from->sd_mtime.sec);
2443        to->sd_mtime.nsec = get_be32(&from->sd_mtime.nsec);
2444        to->sd_dev        = get_be32(&from->sd_dev);
2445        to->sd_ino        = get_be32(&from->sd_ino);
2446        to->sd_uid        = get_be32(&from->sd_uid);
2447        to->sd_gid        = get_be32(&from->sd_gid);
2448        to->sd_size       = get_be32(&from->sd_size);
2449}
2450
2451static int read_one_dir(struct untracked_cache_dir **untracked_,
2452                        struct read_data *rd)
2453{
2454        struct untracked_cache_dir ud, *untracked;
2455        const unsigned char *next, *data = rd->data, *end = rd->end;
2456        unsigned int value;
2457        int i, len;
2458
2459        memset(&ud, 0, sizeof(ud));
2460
2461        next = data;
2462        value = decode_varint(&next);
2463        if (next > end)
2464                return -1;
2465        ud.recurse         = 1;
2466        ud.untracked_alloc = value;
2467        ud.untracked_nr    = value;
2468        if (ud.untracked_nr)
2469                ALLOC_ARRAY(ud.untracked, ud.untracked_nr);
2470        data = next;
2471
2472        next = data;
2473        ud.dirs_alloc = ud.dirs_nr = decode_varint(&next);
2474        if (next > end)
2475                return -1;
2476        ALLOC_ARRAY(ud.dirs, ud.dirs_nr);
2477        data = next;
2478
2479        len = strlen((const char *)data);
2480        next = data + len + 1;
2481        if (next > rd->end)
2482                return -1;
2483        *untracked_ = untracked = xmalloc(st_add(sizeof(*untracked), len));
2484        memcpy(untracked, &ud, sizeof(ud));
2485        memcpy(untracked->name, data, len + 1);
2486        data = next;
2487
2488        for (i = 0; i < untracked->untracked_nr; i++) {
2489                len = strlen((const char *)data);
2490                next = data + len + 1;
2491                if (next > rd->end)
2492                        return -1;
2493                untracked->untracked[i] = xstrdup((const char*)data);
2494                data = next;
2495        }
2496
2497        rd->ucd[rd->index++] = untracked;
2498        rd->data = data;
2499
2500        for (i = 0; i < untracked->dirs_nr; i++) {
2501                len = read_one_dir(untracked->dirs + i, rd);
2502                if (len < 0)
2503                        return -1;
2504        }
2505        return 0;
2506}
2507
2508static void set_check_only(size_t pos, void *cb)
2509{
2510        struct read_data *rd = cb;
2511        struct untracked_cache_dir *ud = rd->ucd[pos];
2512        ud->check_only = 1;
2513}
2514
2515static void read_stat(size_t pos, void *cb)
2516{
2517        struct read_data *rd = cb;
2518        struct untracked_cache_dir *ud = rd->ucd[pos];
2519        if (rd->data + sizeof(struct stat_data) > rd->end) {
2520                rd->data = rd->end + 1;
2521                return;
2522        }
2523        stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);
2524        rd->data += sizeof(struct stat_data);
2525        ud->valid = 1;
2526}
2527
2528static void read_sha1(size_t pos, void *cb)
2529{
2530        struct read_data *rd = cb;
2531        struct untracked_cache_dir *ud = rd->ucd[pos];
2532        if (rd->data + 20 > rd->end) {
2533                rd->data = rd->end + 1;
2534                return;
2535        }
2536        hashcpy(ud->exclude_sha1, rd->data);
2537        rd->data += 20;
2538}
2539
2540static void load_sha1_stat(struct sha1_stat *sha1_stat,
2541                           const struct stat_data *stat,
2542                           const unsigned char *sha1)
2543{
2544        stat_data_from_disk(&sha1_stat->stat, stat);
2545        hashcpy(sha1_stat->sha1, sha1);
2546        sha1_stat->valid = 1;
2547}
2548
2549struct untracked_cache *read_untracked_extension(const void *data, unsigned long sz)
2550{
2551        const struct ondisk_untracked_cache *ouc;
2552        struct untracked_cache *uc;
2553        struct read_data rd;
2554        const unsigned char *next = data, *end = (const unsigned char *)data + sz;
2555        const char *ident;
2556        int ident_len, len;
2557
2558        if (sz <= 1 || end[-1] != '\0')
2559                return NULL;
2560        end--;
2561
2562        ident_len = decode_varint(&next);
2563        if (next + ident_len > end)
2564                return NULL;
2565        ident = (const char *)next;
2566        next += ident_len;
2567
2568        ouc = (const struct ondisk_untracked_cache *)next;
2569        if (next + ouc_size(0) > end)
2570                return NULL;
2571
2572        uc = xcalloc(1, sizeof(*uc));
2573        strbuf_init(&uc->ident, ident_len);
2574        strbuf_add(&uc->ident, ident, ident_len);
2575        load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,
2576                       ouc->info_exclude_sha1);
2577        load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,
2578                       ouc->excludes_file_sha1);
2579        uc->dir_flags = get_be32(&ouc->dir_flags);
2580        uc->exclude_per_dir = xstrdup(ouc->exclude_per_dir);
2581        /* NUL after exclude_per_dir is covered by sizeof(*ouc) */
2582        next += ouc_size(strlen(ouc->exclude_per_dir));
2583        if (next >= end)
2584                goto done2;
2585
2586        len = decode_varint(&next);
2587        if (next > end || len == 0)
2588                goto done2;
2589
2590        rd.valid      = ewah_new();
2591        rd.check_only = ewah_new();
2592        rd.sha1_valid = ewah_new();
2593        rd.data       = next;
2594        rd.end        = end;
2595        rd.index      = 0;
2596        ALLOC_ARRAY(rd.ucd, len);
2597
2598        if (read_one_dir(&uc->root, &rd) || rd.index != len)
2599                goto done;
2600
2601        next = rd.data;
2602        len = ewah_read_mmap(rd.valid, next, end - next);
2603        if (len < 0)
2604                goto done;
2605
2606        next += len;
2607        len = ewah_read_mmap(rd.check_only, next, end - next);
2608        if (len < 0)
2609                goto done;
2610
2611        next += len;
2612        len = ewah_read_mmap(rd.sha1_valid, next, end - next);
2613        if (len < 0)
2614                goto done;
2615
2616        ewah_each_bit(rd.check_only, set_check_only, &rd);
2617        rd.data = next + len;
2618        ewah_each_bit(rd.valid, read_stat, &rd);
2619        ewah_each_bit(rd.sha1_valid, read_sha1, &rd);
2620        next = rd.data;
2621
2622done:
2623        free(rd.ucd);
2624        ewah_free(rd.valid);
2625        ewah_free(rd.check_only);
2626        ewah_free(rd.sha1_valid);
2627done2:
2628        if (next != end) {
2629                free_untracked_cache(uc);
2630                uc = NULL;
2631        }
2632        return uc;
2633}
2634
2635static void invalidate_one_directory(struct untracked_cache *uc,
2636                                     struct untracked_cache_dir *ucd)
2637{
2638        uc->dir_invalidated++;
2639        ucd->valid = 0;
2640        ucd->untracked_nr = 0;
2641}
2642
2643/*
2644 * Normally when an entry is added or removed from a directory,
2645 * invalidating that directory is enough. No need to touch its
2646 * ancestors. When a directory is shown as "foo/bar/" in git-status
2647 * however, deleting or adding an entry may have cascading effect.
2648 *
2649 * Say the "foo/bar/file" has become untracked, we need to tell the
2650 * untracked_cache_dir of "foo" that "bar/" is not an untracked
2651 * directory any more (because "bar" is managed by foo as an untracked
2652 * "file").
2653 *
2654 * Similarly, if "foo/bar/file" moves from untracked to tracked and it
2655 * was the last untracked entry in the entire "foo", we should show
2656 * "foo/" instead. Which means we have to invalidate past "bar" up to
2657 * "foo".
2658 *
2659 * This function traverses all directories from root to leaf. If there
2660 * is a chance of one of the above cases happening, we invalidate back
2661 * to root. Otherwise we just invalidate the leaf. There may be a more
2662 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to
2663 * detect these cases and avoid unnecessary invalidation, for example,
2664 * checking for the untracked entry named "bar/" in "foo", but for now
2665 * stick to something safe and simple.
2666 */
2667static int invalidate_one_component(struct untracked_cache *uc,
2668                                    struct untracked_cache_dir *dir,
2669                                    const char *path, int len)
2670{
2671        const char *rest = strchr(path, '/');
2672
2673        if (rest) {
2674                int component_len = rest - path;
2675                struct untracked_cache_dir *d =
2676                        lookup_untracked(uc, dir, path, component_len);
2677                int ret =
2678                        invalidate_one_component(uc, d, rest + 1,
2679                                                 len - (component_len + 1));
2680                if (ret)
2681                        invalidate_one_directory(uc, dir);
2682                return ret;
2683        }
2684
2685        invalidate_one_directory(uc, dir);
2686        return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;
2687}
2688
2689void untracked_cache_invalidate_path(struct index_state *istate,
2690                                     const char *path)
2691{
2692        if (!istate->untracked || !istate->untracked->root)
2693                return;
2694        invalidate_one_component(istate->untracked, istate->untracked->root,
2695                                 path, strlen(path));
2696}
2697
2698void untracked_cache_remove_from_index(struct index_state *istate,
2699                                       const char *path)
2700{
2701        untracked_cache_invalidate_path(istate, path);
2702}
2703
2704void untracked_cache_add_to_index(struct index_state *istate,
2705                                  const char *path)
2706{
2707        untracked_cache_invalidate_path(istate, path);
2708}