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