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