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