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