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