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