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