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