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