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