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