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