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