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