]> git.ipfire.org Git - thirdparty/git.git/blame - dir.c
t7064: use update-ref -d to remove upstream branch
[thirdparty/git.git] / dir.c
CommitLineData
453ec4bd
LT
1/*
2 * This handles recursive filename detection with exclude
3 * files, index knowledge etc..
4 *
5 * Copyright (C) Linus Torvalds, 2005-2006
6 * Junio Hamano, 2005-2006
7 */
453ec4bd 8#include "cache.h"
b2141fc1 9#include "config.h"
453ec4bd 10#include "dir.h"
cbd53a21 11#include "object-store.h"
b0db7046 12#include "attr.h"
09595258 13#include "refs.h"
237ec6e4 14#include "wildmatch.h"
64acde94 15#include "pathspec.h"
dde843e7 16#include "utf8.h"
83c094ad
NTND
17#include "varint.h"
18#include "ewah/ewok.h"
883e248b 19#include "fsmonitor.h"
da62f786 20#include "submodule-config.h"
453ec4bd 21
defd7c7b
KB
22/*
23 * Tells read_directory_recursive how a file or directory should be treated.
24 * Values are ordered by significance, e.g. if a directory contains both
25 * excluded and untracked files, it is listed as untracked because
26 * path_untracked > path_excluded.
27 */
28enum path_treatment {
29 path_none = 0,
30 path_recurse,
31 path_excluded,
32 path_untracked
33};
34
cf7c6148
NTND
35/*
36 * Support data structure for our opendir/readdir/closedir wrappers
37 */
38struct cached_dir {
39 DIR *fdir;
40 struct untracked_cache_dir *untracked;
91a2288b
NTND
41 int nr_files;
42 int nr_dirs;
43
ad6f2157
JK
44 const char *d_name;
45 int d_type;
91a2288b
NTND
46 const char *file;
47 struct untracked_cache_dir *ucd;
cf7c6148
NTND
48};
49
defd7c7b 50static enum path_treatment read_directory_recursive(struct dir_struct *dir,
0ef8e169
BW
51 struct index_state *istate, const char *path, int len,
52 struct untracked_cache_dir *untracked,
5aaa7fd3 53 int check_only, int stop_at_first_file, const struct pathspec *pathspec);
ad6f2157
JK
54static int resolve_dtype(int dtype, struct index_state *istate,
55 const char *path, int len);
906fc557 56struct dirent *readdir_skip_dot_and_dotdot(DIR *dirp)
b548f0f1
EN
57{
58 struct dirent *e;
59
60 while ((e = readdir(dirp)) != NULL) {
61 if (!is_dot_or_dotdot(e->d_name))
62 break;
63 }
64 return e;
65}
66
e0556a92
PC
67int count_slashes(const char *s)
68{
69 int cnt = 0;
70 while (*s)
71 if (*s++ == '/')
72 cnt++;
73 return cnt;
74}
75
ba0897e6 76int fspathcmp(const char *a, const char *b)
8cf2a84e
JJ
77{
78 return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
79}
80
ba0897e6 81int fspathncmp(const char *a, const char *b, size_t count)
8cf2a84e
JJ
82{
83 return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
84}
85
1f26ce61
CB
86int git_fnmatch(const struct pathspec_item *item,
87 const char *pattern, const char *string,
88 int prefix)
5d74762d 89{
5d74762d 90 if (prefix > 0) {
93d93537 91 if (ps_strncmp(item, pattern, string, prefix))
eb07894f 92 return WM_NOMATCH;
5d74762d
NTND
93 pattern += prefix;
94 string += prefix;
95 }
bd30c2e4 96 if (item->flags & PATHSPEC_ONESTAR) {
8c6abbcd
NTND
97 int pattern_len = strlen(++pattern);
98 int string_len = strlen(string);
99 return string_len < pattern_len ||
93d93537
NTND
100 ps_strcmp(item, pattern,
101 string + string_len - pattern_len);
8c6abbcd 102 }
bd30c2e4 103 if (item->magic & PATHSPEC_GLOB)
93d93537
NTND
104 return wildmatch(pattern, string,
105 WM_PATHNAME |
55d34269 106 (item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0));
bd30c2e4
NTND
107 else
108 /* wildmatch has not learned no FNM_PATHNAME mode yet */
eb07894f 109 return wildmatch(pattern, string,
55d34269 110 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0);
5d74762d
NTND
111}
112
0b6e56df
JH
113static int fnmatch_icase_mem(const char *pattern, int patternlen,
114 const char *string, int stringlen,
115 int flags)
116{
117 int match_status;
118 struct strbuf pat_buf = STRBUF_INIT;
119 struct strbuf str_buf = STRBUF_INIT;
120 const char *use_pat = pattern;
121 const char *use_str = string;
122
123 if (pattern[patternlen]) {
124 strbuf_add(&pat_buf, pattern, patternlen);
125 use_pat = pat_buf.buf;
126 }
127 if (string[stringlen]) {
128 strbuf_add(&str_buf, string, stringlen);
129 use_str = str_buf.buf;
130 }
131
f30366b2
JH
132 if (ignore_case)
133 flags |= WM_CASEFOLD;
55d34269 134 match_status = wildmatch(use_pat, use_str, flags);
0b6e56df
JH
135
136 strbuf_release(&pat_buf);
137 strbuf_release(&str_buf);
138
139 return match_status;
140}
141
827f4d6c 142static size_t common_prefix_len(const struct pathspec *pathspec)
3c6a370b 143{
827f4d6c 144 int n;
4a085b16 145 size_t max = 0;
3c6a370b 146
93d93537
NTND
147 /*
148 * ":(icase)path" is treated as a pathspec full of
149 * wildcard. In other words, only prefix is considered common
150 * prefix. If the pathspec is abc/foo abc/bar, running in
bbbb6b0b 151 * subdir xyz, the common prefix is still xyz, not xyz/abc as
93d93537
NTND
152 * in non-:(icase).
153 */
5c6933d2
NTND
154 GUARD_PATHSPEC(pathspec,
155 PATHSPEC_FROMTOP |
156 PATHSPEC_MAXDEPTH |
bd30c2e4 157 PATHSPEC_LITERAL |
93d93537 158 PATHSPEC_GLOB |
ef79b1f8 159 PATHSPEC_ICASE |
b0db7046
BW
160 PATHSPEC_EXCLUDE |
161 PATHSPEC_ATTR);
4a085b16 162
827f4d6c 163 for (n = 0; n < pathspec->nr; n++) {
93d93537 164 size_t i = 0, len = 0, item_len;
ef79b1f8
NTND
165 if (pathspec->items[n].magic & PATHSPEC_EXCLUDE)
166 continue;
93d93537
NTND
167 if (pathspec->items[n].magic & PATHSPEC_ICASE)
168 item_len = pathspec->items[n].prefix;
169 else
170 item_len = pathspec->items[n].nowildcard_len;
171 while (i < item_len && (n == 0 || i < max)) {
827f4d6c
NTND
172 char c = pathspec->items[n].match[i];
173 if (c != pathspec->items[0].match[i])
4a085b16
JH
174 break;
175 if (c == '/')
176 len = i + 1;
827f4d6c 177 i++;
4a085b16 178 }
827f4d6c 179 if (n == 0 || len < max) {
4a085b16
JH
180 max = len;
181 if (!max)
182 break;
183 }
3c6a370b 184 }
4a085b16 185 return max;
3c6a370b
LT
186}
187
f950eb95
CB
188/*
189 * Returns a copy of the longest leading path common among all
190 * pathspecs.
191 */
827f4d6c 192char *common_prefix(const struct pathspec *pathspec)
f950eb95
CB
193{
194 unsigned long len = common_prefix_len(pathspec);
195
827f4d6c 196 return len ? xmemdupz(pathspec->items[0].match, len) : NULL;
f950eb95
CB
197}
198
0d32c183
BW
199int fill_directory(struct dir_struct *dir,
200 struct index_state *istate,
201 const struct pathspec *pathspec)
1d8842d9 202{
bec5ab89 203 const char *prefix;
966de302 204 size_t prefix_len;
1d8842d9 205
351ea1c3
EN
206 unsigned exclusive_flags = DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO;
207 if ((dir->flags & exclusive_flags) == exclusive_flags)
208 BUG("DIR_SHOW_IGNORED and DIR_SHOW_IGNORED_TOO are exclusive");
209
1d8842d9
LT
210 /*
211 * Calculate common prefix for the pathspec, and
212 * use that to optimize the directory walk
213 */
bec5ab89
RS
214 prefix_len = common_prefix_len(pathspec);
215 prefix = prefix_len ? pathspec->items[0].match : "";
1d8842d9
LT
216
217 /* Read the directory and prune it */
0d32c183 218 read_directory(dir, istate, prefix, prefix_len, pathspec);
966de302 219
966de302 220 return prefix_len;
1d8842d9
LT
221}
222
bc96cc87
NTND
223int within_depth(const char *name, int namelen,
224 int depth, int max_depth)
225{
226 const char *cp = name, *cpe = name + namelen;
227
228 while (cp < cpe) {
229 if (*cp++ != '/')
230 continue;
231 depth++;
232 if (depth > max_depth)
233 return 0;
234 }
235 return 1;
236}
237
578d81d0
JH
238/*
239 * Read the contents of the blob with the given OID into a buffer.
240 * Append a trailing LF to the end if the last line doesn't have one.
241 *
242 * Returns:
243 * -1 when the OID is invalid or unknown or does not refer to a blob.
244 * 0 when the blob is empty.
245 * 1 along with { data, size } of the (possibly augmented) buffer
246 * when successful.
247 *
4b33e602 248 * Optionally updates the given oid_stat with the given OID (when valid).
578d81d0 249 */
4b33e602
PO
250static int do_read_blob(const struct object_id *oid, struct oid_stat *oid_stat,
251 size_t *size_out, char **data_out)
578d81d0
JH
252{
253 enum object_type type;
254 unsigned long sz;
255 char *data;
256
257 *size_out = 0;
258 *data_out = NULL;
259
b4f5aca4 260 data = read_object_file(oid, &type, &sz);
578d81d0
JH
261 if (!data || type != OBJ_BLOB) {
262 free(data);
263 return -1;
264 }
265
4b33e602
PO
266 if (oid_stat) {
267 memset(&oid_stat->stat, 0, sizeof(oid_stat->stat));
268 oidcpy(&oid_stat->oid, oid);
578d81d0
JH
269 }
270
271 if (sz == 0) {
272 free(data);
273 return 0;
274 }
275
276 if (data[sz - 1] != '\n') {
277 data = xrealloc(data, st_add(sz, 1));
278 data[sz++] = '\n';
279 }
280
281 *size_out = xsize_t(sz);
282 *data_out = data;
283
284 return 1;
285}
286
75a6315f
BW
287#define DO_MATCH_EXCLUDE (1<<0)
288#define DO_MATCH_DIRECTORY (1<<1)
a3d89d8f 289#define DO_MATCH_LEADING_PATHSPEC (1<<2)
42b0874a 290
61cf2820 291/*
29b577b9 292 * Does the given pathspec match the given name? A match is found if
61cf2820 293 *
29b577b9
EN
294 * (1) the pathspec string is leading directory of 'name' ("RECURSIVELY"), or
295 * (2) the pathspec string has a leading part matching 'name' ("LEADING"), or
296 * (3) the pathspec string is a wildcard and matches 'name' ("WILDCARD"), or
297 * (4) the pathspec string is exactly the same as 'name' ("EXACT").
61cf2820 298 *
29b577b9 299 * Return value tells which case it was (1-4), or 0 when there is no match.
61cf2820 300 *
29b577b9
EN
301 * It may be instructive to look at a small table of concrete examples
302 * to understand the differences between 1, 2, and 4:
303 *
304 * Pathspecs
305 * | a/b | a/b/ | a/b/c
306 * ------+-----------+-----------+------------
307 * a/b | EXACT | EXACT[1] | LEADING[2]
308 * Names a/b/ | RECURSIVE | EXACT | LEADING[2]
309 * a/b/c | RECURSIVE | RECURSIVE | EXACT
310 *
311 * [1] Only if DO_MATCH_DIRECTORY is passed; otherwise, this is NOT a match.
312 * [2] Only if DO_MATCH_LEADING_PATHSPEC is passed; otherwise, not a match.
61cf2820 313 */
847a9e5d 314static int match_pathspec_item(struct index_state *istate,
6d2df284 315 const struct pathspec_item *item, int prefix,
42b0874a 316 const char *name, int namelen, unsigned flags)
61cf2820
NTND
317{
318 /* name/namelen has prefix cut off by caller */
319 const char *match = item->match + prefix;
320 int matchlen = item->len - prefix;
321
93d93537
NTND
322 /*
323 * The normal call pattern is:
324 * 1. prefix = common_prefix_len(ps);
325 * 2. prune something, or fill_directory
854b0959 326 * 3. match_pathspec()
93d93537
NTND
327 *
328 * 'prefix' at #1 may be shorter than the command's prefix and
329 * it's ok for #2 to match extra files. Those extras will be
330 * trimmed at #3.
331 *
332 * Suppose the pathspec is 'foo' and '../bar' running from
333 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
334 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
335 * user does not want XYZ/foo, only the "foo" part should be
336 * case-insensitive. We need to filter out XYZ/foo here. In
337 * other words, we do not trust the caller on comparing the
338 * prefix part when :(icase) is involved. We do exact
339 * comparison ourselves.
340 *
341 * Normally the caller (common_prefix_len() in fact) does
342 * _exact_ matching on name[-prefix+1..-1] and we do not need
343 * to check that part. Be defensive and check it anyway, in
344 * case common_prefix_len is changed, or a new caller is
345 * introduced that does not use common_prefix_len.
346 *
347 * If the penalty turns out too high when prefix is really
348 * long, maybe change it to
349 * strncmp(match, name, item->prefix - prefix)
350 */
351 if (item->prefix && (item->magic & PATHSPEC_ICASE) &&
352 strncmp(item->match, name - prefix, item->prefix))
353 return 0;
354
22af33be
NTND
355 if (item->attr_match_nr &&
356 !match_pathspec_attrs(istate, name, namelen, item))
b0db7046
BW
357 return 0;
358
61cf2820
NTND
359 /* If the match was just the prefix, we matched */
360 if (!*match)
361 return MATCHED_RECURSIVELY;
362
93d93537 363 if (matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) {
61cf2820
NTND
364 if (matchlen == namelen)
365 return MATCHED_EXACTLY;
366
367 if (match[matchlen-1] == '/' || name[matchlen] == '/')
368 return MATCHED_RECURSIVELY;
68690fdd
NTND
369 } else if ((flags & DO_MATCH_DIRECTORY) &&
370 match[matchlen - 1] == '/' &&
371 namelen == matchlen - 1 &&
372 !ps_strncmp(item, match, name, namelen))
373 return MATCHED_EXACTLY;
61cf2820 374
5d74762d 375 if (item->nowildcard_len < item->len &&
bd30c2e4 376 !git_fnmatch(item, match, name,
8c6abbcd 377 item->nowildcard_len - prefix))
61cf2820
NTND
378 return MATCHED_FNMATCH;
379
29b577b9 380 /* Perform checks to see if "name" is a leading string of the pathspec */
f1f061e1
EN
381 if ( (flags & DO_MATCH_LEADING_PATHSPEC) &&
382 !(flags & DO_MATCH_EXCLUDE)) {
75a6315f 383 /* name is a literal prefix of the pathspec */
a5e916c7 384 int offset = name[namelen-1] == '/' ? 1 : 0;
75a6315f 385 if ((namelen < matchlen) &&
a5e916c7 386 (match[namelen-offset] == '/') &&
75a6315f 387 !ps_strncmp(item, match, name, namelen))
89a1f4aa 388 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
75a6315f 389
2f5d3847 390 /* name doesn't match up to the first wild character */
75a6315f
BW
391 if (item->nowildcard_len < item->len &&
392 ps_strncmp(item, match, name,
393 item->nowildcard_len - prefix))
394 return 0;
395
072a2310
EN
396 /*
397 * name has no wildcard, and it didn't match as a leading
398 * pathspec so return.
399 */
400 if (item->nowildcard_len == item->len)
401 return 0;
402
75a6315f
BW
403 /*
404 * Here is where we would perform a wildmatch to check if
405 * "name" can be matched as a directory (or a prefix) against
406 * the pathspec. Since wildmatch doesn't have this capability
407 * at the present we have to punt and say that it is a match,
408 * potentially returning a false positive
409 * The submodules themselves will be able to perform more
410 * accurate matching to determine if the pathspec matches.
411 */
89a1f4aa 412 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
75a6315f
BW
413 }
414
61cf2820
NTND
415 return 0;
416}
417
418/*
f1f061e1
EN
419 * do_match_pathspec() is meant to ONLY be called by
420 * match_pathspec_with_flags(); calling it directly risks pathspecs
421 * like ':!unwanted_path' being ignored.
422 *
52ed1894
AS
423 * Given a name and a list of pathspecs, returns the nature of the
424 * closest (i.e. most specific) match of the name to any of the
425 * pathspecs.
426 *
427 * The caller typically calls this multiple times with the same
428 * pathspec and seen[] array but with different name/namelen
429 * (e.g. entries from the index) and is interested in seeing if and
430 * how each pathspec matches all the names it calls this function
431 * with. A mark is left in the seen[] array for each pathspec element
432 * indicating the closest type of match that element achieved, so if
433 * seen[n] remains zero after multiple invocations, that means the nth
434 * pathspec did not match any names, which could indicate that the
435 * user mistyped the nth pathspec.
61cf2820 436 */
847a9e5d 437static int do_match_pathspec(struct index_state *istate,
6d2df284 438 const struct pathspec *ps,
854b0959
NTND
439 const char *name, int namelen,
440 int prefix, char *seen,
42b0874a 441 unsigned flags)
61cf2820 442{
42b0874a 443 int i, retval = 0, exclude = flags & DO_MATCH_EXCLUDE;
61cf2820 444
5c6933d2
NTND
445 GUARD_PATHSPEC(ps,
446 PATHSPEC_FROMTOP |
447 PATHSPEC_MAXDEPTH |
bd30c2e4 448 PATHSPEC_LITERAL |
93d93537 449 PATHSPEC_GLOB |
ef79b1f8 450 PATHSPEC_ICASE |
b0db7046
BW
451 PATHSPEC_EXCLUDE |
452 PATHSPEC_ATTR);
8f4f8f45 453
61cf2820 454 if (!ps->nr) {
6330a171
NTND
455 if (!ps->recursive ||
456 !(ps->magic & PATHSPEC_MAXDEPTH) ||
457 ps->max_depth == -1)
61cf2820
NTND
458 return MATCHED_RECURSIVELY;
459
460 if (within_depth(name, namelen, 0, ps->max_depth))
461 return MATCHED_EXACTLY;
462 else
463 return 0;
464 }
465
466 name += prefix;
467 namelen -= prefix;
468
469 for (i = ps->nr - 1; i >= 0; i--) {
470 int how;
ef79b1f8
NTND
471
472 if ((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) ||
473 ( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE)))
474 continue;
475
61cf2820
NTND
476 if (seen && seen[i] == MATCHED_EXACTLY)
477 continue;
ef79b1f8
NTND
478 /*
479 * Make exclude patterns optional and never report
480 * "pathspec ':(exclude)foo' matches no files"
481 */
482 if (seen && ps->items[i].magic & PATHSPEC_EXCLUDE)
483 seen[i] = MATCHED_FNMATCH;
6d2df284 484 how = match_pathspec_item(istate, ps->items+i, prefix, name,
42b0874a 485 namelen, flags);
6330a171
NTND
486 if (ps->recursive &&
487 (ps->magic & PATHSPEC_MAXDEPTH) &&
488 ps->max_depth != -1 &&
61cf2820
NTND
489 how && how != MATCHED_FNMATCH) {
490 int len = ps->items[i].len;
491 if (name[len] == '/')
492 len++;
493 if (within_depth(name+len, namelen-len, 0, ps->max_depth))
494 how = MATCHED_EXACTLY;
495 else
496 how = 0;
497 }
498 if (how) {
499 if (retval < how)
500 retval = how;
501 if (seen && seen[i] < how)
502 seen[i] = how;
503 }
504 }
505 return retval;
506}
507
847a9e5d 508static int match_pathspec_with_flags(struct index_state *istate,
f1f061e1
EN
509 const struct pathspec *ps,
510 const char *name, int namelen,
511 int prefix, char *seen, unsigned flags)
ef79b1f8
NTND
512{
513 int positive, negative;
6d2df284 514 positive = do_match_pathspec(istate, ps, name, namelen,
42b0874a 515 prefix, seen, flags);
ef79b1f8
NTND
516 if (!(ps->magic & PATHSPEC_EXCLUDE) || !positive)
517 return positive;
6d2df284 518 negative = do_match_pathspec(istate, ps, name, namelen,
42b0874a
NTND
519 prefix, seen,
520 flags | DO_MATCH_EXCLUDE);
ef79b1f8
NTND
521 return negative ? 0 : positive;
522}
523
847a9e5d 524int match_pathspec(struct index_state *istate,
f1f061e1
EN
525 const struct pathspec *ps,
526 const char *name, int namelen,
527 int prefix, char *seen, int is_dir)
528{
529 unsigned flags = is_dir ? DO_MATCH_DIRECTORY : 0;
530 return match_pathspec_with_flags(istate, ps, name, namelen,
531 prefix, seen, flags);
532}
533
75a6315f
BW
534/**
535 * Check if a submodule is a superset of the pathspec
536 */
847a9e5d 537int submodule_path_match(struct index_state *istate,
6d2df284 538 const struct pathspec *ps,
75a6315f
BW
539 const char *submodule_name,
540 char *seen)
541{
f1f061e1
EN
542 int matched = match_pathspec_with_flags(istate, ps, submodule_name,
543 strlen(submodule_name),
544 0, seen,
545 DO_MATCH_DIRECTORY |
546 DO_MATCH_LEADING_PATHSPEC);
75a6315f
BW
547 return matched;
548}
549
777c55a6 550int report_path_error(const char *ps_matched,
c5c33504 551 const struct pathspec *pathspec)
777c55a6
JH
552{
553 /*
554 * Make sure all pathspec matched; otherwise it is an error.
555 */
777c55a6
JH
556 int num, errors = 0;
557 for (num = 0; num < pathspec->nr; num++) {
558 int other, found_dup;
559
560 if (ps_matched[num])
561 continue;
562 /*
563 * The caller might have fed identical pathspec
564 * twice. Do not barf on such a mistake.
565 * FIXME: parse_pathspec should have eliminated
566 * duplicate pathspec.
567 */
568 for (found_dup = other = 0;
569 !found_dup && other < pathspec->nr;
570 other++) {
571 if (other == num || !ps_matched[other])
572 continue;
573 if (!strcmp(pathspec->items[other].original,
574 pathspec->items[num].original))
575 /*
576 * Ok, we have a match already.
577 */
578 found_dup = 1;
579 }
580 if (found_dup)
581 continue;
582
a80897c1 583 error(_("pathspec '%s' did not match any file(s) known to git"),
777c55a6
JH
584 pathspec->items[num].original);
585 errors++;
586 }
777c55a6
JH
587 return errors;
588}
589
fcd631ed
NTND
590/*
591 * Return the length of the "simple" part of a path match limiter.
592 */
87323bda 593int simple_length(const char *match)
fcd631ed
NTND
594{
595 int len = -1;
596
597 for (;;) {
598 unsigned char c = *match++;
599 len++;
600 if (c == '\0' || is_glob_special(c))
601 return len;
602 }
603}
604
87323bda 605int no_wildcard(const char *string)
68492fc7 606{
fcd631ed 607 return string[simple_length(string)] == '\0';
68492fc7
LK
608}
609
65edd96a 610void parse_path_pattern(const char **pattern,
82dce998 611 int *patternlen,
f8708998 612 unsigned *flags,
82dce998 613 int *nowildcardlen)
84460eec
NTND
614{
615 const char *p = *pattern;
616 size_t i, len;
617
618 *flags = 0;
619 if (*p == '!') {
4ff89ee5 620 *flags |= PATTERN_FLAG_NEGATIVE;
84460eec
NTND
621 p++;
622 }
623 len = strlen(p);
624 if (len && p[len - 1] == '/') {
625 len--;
4ff89ee5 626 *flags |= PATTERN_FLAG_MUSTBEDIR;
84460eec
NTND
627 }
628 for (i = 0; i < len; i++) {
629 if (p[i] == '/')
630 break;
631 }
632 if (i == len)
4ff89ee5 633 *flags |= PATTERN_FLAG_NODIR;
84460eec
NTND
634 *nowildcardlen = simple_length(p);
635 /*
636 * we should have excluded the trailing slash from 'p' too,
637 * but that's one more allocation. Instead just make sure
638 * nowildcardlen does not exceed real patternlen
639 */
640 if (*nowildcardlen > len)
641 *nowildcardlen = len;
642 if (*p == '*' && no_wildcard(p + 1))
4ff89ee5 643 *flags |= PATTERN_FLAG_ENDSWITH;
84460eec
NTND
644 *pattern = p;
645 *patternlen = len;
646}
647
af09ce24
DS
648int pl_hashmap_cmp(const void *unused_cmp_data,
649 const struct hashmap_entry *a,
650 const struct hashmap_entry *b,
651 const void *key)
96cc8ab5
DS
652{
653 const struct pattern_entry *ee1 =
654 container_of(a, struct pattern_entry, ent);
655 const struct pattern_entry *ee2 =
656 container_of(b, struct pattern_entry, ent);
657
658 size_t min_len = ee1->patternlen <= ee2->patternlen
659 ? ee1->patternlen
660 : ee2->patternlen;
661
190a65f9
DS
662 if (ignore_case)
663 return strncasecmp(ee1->pattern, ee2->pattern, min_len);
96cc8ab5
DS
664 return strncmp(ee1->pattern, ee2->pattern, min_len);
665}
666
4f52c2ce
DS
667static char *dup_and_filter_pattern(const char *pattern)
668{
669 char *set, *read;
670 size_t count = 0;
671 char *result = xstrdup(pattern);
672
673 set = result;
674 read = result;
675
676 while (*read) {
677 /* skip escape characters (once) */
678 if (*read == '\\')
679 read++;
680
681 *set = *read;
682
683 set++;
684 read++;
685 count++;
686 }
687 *set = 0;
688
689 if (count > 2 &&
690 *(set - 1) == '*' &&
691 *(set - 2) == '/')
692 *(set - 2) = 0;
693
694 return result;
695}
696
96cc8ab5
DS
697static void add_pattern_to_hashsets(struct pattern_list *pl, struct path_pattern *given)
698{
699 struct pattern_entry *translated;
700 char *truncated;
701 char *data = NULL;
9abc60f8 702 const char *prev, *cur, *next;
96cc8ab5
DS
703
704 if (!pl->use_cone_patterns)
705 return;
706
707 if (given->flags & PATTERN_FLAG_NEGATIVE &&
708 given->flags & PATTERN_FLAG_MUSTBEDIR &&
709 !strcmp(given->pattern, "/*")) {
710 pl->full_cone = 0;
711 return;
712 }
713
714 if (!given->flags && !strcmp(given->pattern, "/*")) {
715 pl->full_cone = 1;
716 return;
717 }
718
6c11c6a1 719 if (given->patternlen < 2 ||
9abc60f8 720 *given->pattern == '*' ||
9e6d3e64 721 strstr(given->pattern, "**")) {
41de0c6f
DS
722 /* Not a cone pattern. */
723 warning(_("unrecognized pattern: '%s'"), given->pattern);
724 goto clear_hashmaps;
725 }
726
9abc60f8
DS
727 prev = given->pattern;
728 cur = given->pattern + 1;
729 next = given->pattern + 2;
730
731 while (*cur) {
732 /* Watch for glob characters '*', '\', '[', '?' */
733 if (!is_glob_special(*cur))
734 goto increment;
735
736 /* But only if *prev != '\\' */
737 if (*prev == '\\')
738 goto increment;
739
740 /* But allow the initial '\' */
741 if (*cur == '\\' &&
742 is_glob_special(*next))
743 goto increment;
744
745 /* But a trailing '/' then '*' is fine */
746 if (*prev == '/' &&
747 *cur == '*' &&
748 *next == 0)
749 goto increment;
750
751 /* Not a cone pattern. */
752 warning(_("unrecognized pattern: '%s'"), given->pattern);
753 goto clear_hashmaps;
754
755 increment:
756 prev++;
757 cur++;
758 next++;
759 }
760
96cc8ab5
DS
761 if (given->patternlen > 2 &&
762 !strcmp(given->pattern + given->patternlen - 2, "/*")) {
763 if (!(given->flags & PATTERN_FLAG_NEGATIVE)) {
764 /* Not a cone pattern. */
96cc8ab5
DS
765 warning(_("unrecognized pattern: '%s'"), given->pattern);
766 goto clear_hashmaps;
767 }
768
4f52c2ce 769 truncated = dup_and_filter_pattern(given->pattern);
96cc8ab5
DS
770
771 translated = xmalloc(sizeof(struct pattern_entry));
772 translated->pattern = truncated;
773 translated->patternlen = given->patternlen - 2;
774 hashmap_entry_init(&translated->ent,
190a65f9
DS
775 ignore_case ?
776 strihash(translated->pattern) :
777 strhash(translated->pattern));
96cc8ab5
DS
778
779 if (!hashmap_get_entry(&pl->recursive_hashmap,
780 translated, ent, NULL)) {
781 /* We did not see the "parent" included */
782 warning(_("unrecognized negative pattern: '%s'"),
783 given->pattern);
784 free(truncated);
785 free(translated);
786 goto clear_hashmaps;
787 }
788
789 hashmap_add(&pl->parent_hashmap, &translated->ent);
790 hashmap_remove(&pl->recursive_hashmap, &translated->ent, &data);
791 free(data);
792 return;
793 }
794
795 if (given->flags & PATTERN_FLAG_NEGATIVE) {
796 warning(_("unrecognized negative pattern: '%s'"),
797 given->pattern);
798 goto clear_hashmaps;
799 }
800
801 translated = xmalloc(sizeof(struct pattern_entry));
802
4f52c2ce 803 translated->pattern = dup_and_filter_pattern(given->pattern);
96cc8ab5
DS
804 translated->patternlen = given->patternlen;
805 hashmap_entry_init(&translated->ent,
190a65f9
DS
806 ignore_case ?
807 strihash(translated->pattern) :
808 strhash(translated->pattern));
96cc8ab5
DS
809
810 hashmap_add(&pl->recursive_hashmap, &translated->ent);
811
812 if (hashmap_get_entry(&pl->parent_hashmap, translated, ent, NULL)) {
813 /* we already included this at the parent level */
814 warning(_("your sparse-checkout file may have issues: pattern '%s' is repeated"),
815 given->pattern);
816 hashmap_remove(&pl->parent_hashmap, &translated->ent, &data);
817 free(data);
818 free(translated);
819 }
820
821 return;
822
823clear_hashmaps:
824 warning(_("disabling cone pattern matching"));
6da1a258
EN
825 hashmap_clear_and_free(&pl->parent_hashmap, struct pattern_entry, ent);
826 hashmap_clear_and_free(&pl->recursive_hashmap, struct pattern_entry, ent);
96cc8ab5
DS
827 pl->use_cone_patterns = 0;
828}
829
830static int hashmap_contains_path(struct hashmap *map,
831 struct strbuf *pattern)
832{
833 struct pattern_entry p;
834
835 /* Check straight mapping */
836 p.pattern = pattern->buf;
837 p.patternlen = pattern->len;
190a65f9
DS
838 hashmap_entry_init(&p.ent,
839 ignore_case ?
840 strihash(p.pattern) :
841 strhash(p.pattern));
96cc8ab5
DS
842 return !!hashmap_get_entry(map, &p, ent, NULL);
843}
844
845int hashmap_contains_parent(struct hashmap *map,
846 const char *path,
847 struct strbuf *buffer)
848{
849 char *slash_pos;
850
851 strbuf_setlen(buffer, 0);
852
853 if (path[0] != '/')
854 strbuf_addch(buffer, '/');
855
856 strbuf_addstr(buffer, path);
857
858 slash_pos = strrchr(buffer->buf, '/');
859
860 while (slash_pos > buffer->buf) {
861 strbuf_setlen(buffer, slash_pos - buffer->buf);
862
863 if (hashmap_contains_path(map, buffer))
864 return 1;
865
866 slash_pos = strrchr(buffer->buf, '/');
867 }
868
869 return 0;
870}
871
65edd96a 872void add_pattern(const char *string, const char *base,
caa3d554 873 int baselen, struct pattern_list *pl, int srcpos)
453ec4bd 874{
ab8db613 875 struct path_pattern *pattern;
84460eec 876 int patternlen;
f8708998 877 unsigned flags;
84460eec 878 int nowildcardlen;
453ec4bd 879
65edd96a 880 parse_path_pattern(&string, &patternlen, &flags, &nowildcardlen);
4ff89ee5 881 if (flags & PATTERN_FLAG_MUSTBEDIR) {
ab8db613 882 FLEXPTR_ALLOC_MEM(pattern, pattern, string, patternlen);
d6b8fc30 883 } else {
ab8db613
DS
884 pattern = xmalloc(sizeof(*pattern));
885 pattern->pattern = string;
d6b8fc30 886 }
ab8db613
DS
887 pattern->patternlen = patternlen;
888 pattern->nowildcardlen = nowildcardlen;
889 pattern->base = base;
890 pattern->baselen = baselen;
891 pattern->flags = flags;
892 pattern->srcpos = srcpos;
caa3d554
DS
893 ALLOC_GROW(pl->patterns, pl->nr + 1, pl->alloc);
894 pl->patterns[pl->nr++] = pattern;
895 pattern->pl = pl;
96cc8ab5
DS
896
897 add_pattern_to_hashsets(pl, pattern);
453ec4bd
LT
898}
899
847a9e5d 900static int read_skip_worktree_file_from_index(struct index_state *istate,
578d81d0 901 const char *path,
4b33e602
PO
902 size_t *size_out, char **data_out,
903 struct oid_stat *oid_stat)
c28b3d6e
NTND
904{
905 int pos, len;
c28b3d6e
NTND
906
907 len = strlen(path);
6f52b741 908 pos = index_name_pos(istate, path, len);
c28b3d6e 909 if (pos < 0)
578d81d0 910 return -1;
6f52b741 911 if (!ce_skip_worktree(istate->cache[pos]))
578d81d0
JH
912 return -1;
913
4b33e602 914 return do_read_blob(&istate->cache[pos]->oid, oid_stat, size_out, data_out);
c28b3d6e
NTND
915}
916
f6198812 917/*
caa3d554
DS
918 * Frees memory within pl which was allocated for exclude patterns and
919 * the file buffer. Does not free pl itself.
f6198812 920 */
65edd96a 921void clear_pattern_list(struct pattern_list *pl)
0fd0e241
NTND
922{
923 int i;
924
caa3d554
DS
925 for (i = 0; i < pl->nr; i++)
926 free(pl->patterns[i]);
927 free(pl->patterns);
928 free(pl->filebuf);
6da1a258
EN
929 hashmap_clear_and_free(&pl->recursive_hashmap, struct pattern_entry, ent);
930 hashmap_clear_and_free(&pl->parent_hashmap, struct pattern_entry, ent);
0fd0e241 931
caa3d554 932 memset(pl, 0, sizeof(*pl));
0fd0e241
NTND
933}
934
7e2e4b37 935static void trim_trailing_spaces(char *buf)
16402b99 936{
e61a6c1d
PB
937 char *p, *last_space = NULL;
938
939 for (p = buf; *p; p++)
940 switch (*p) {
941 case ' ':
942 if (!last_space)
943 last_space = p;
944 break;
945 case '\\':
946 p++;
947 if (!*p)
948 return;
949 /* fallthrough */
950 default:
951 last_space = NULL;
952 }
953
954 if (last_space)
955 *last_space = '\0';
16402b99
NTND
956}
957
0dcb8d7f
NTND
958/*
959 * Given a subdirectory name and "dir" of the current directory,
960 * search the subdir in "dir" and return it, or create a new one if it
961 * does not exist in "dir".
962 *
963 * If "name" has the trailing slash, it'll be excluded in the search.
964 */
965static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc,
966 struct untracked_cache_dir *dir,
967 const char *name, int len)
968{
969 int first, last;
970 struct untracked_cache_dir *d;
971 if (!dir)
972 return NULL;
973 if (len && name[len - 1] == '/')
974 len--;
975 first = 0;
976 last = dir->dirs_nr;
977 while (last > first) {
568a05c5 978 int cmp, next = first + ((last - first) >> 1);
0dcb8d7f
NTND
979 d = dir->dirs[next];
980 cmp = strncmp(name, d->name, len);
981 if (!cmp && strlen(d->name) > len)
982 cmp = -1;
983 if (!cmp)
984 return d;
985 if (cmp < 0) {
986 last = next;
987 continue;
988 }
989 first = next+1;
990 }
991
992 uc->dir_created++;
96ffc06f 993 FLEX_ALLOC_MEM(d, name, name, len);
0dcb8d7f
NTND
994
995 ALLOC_GROW(dir->dirs, dir->dirs_nr + 1, dir->dirs_alloc);
f919ffeb
SG
996 MOVE_ARRAY(dir->dirs + first + 1, dir->dirs + first,
997 dir->dirs_nr - first);
0dcb8d7f
NTND
998 dir->dirs_nr++;
999 dir->dirs[first] = d;
1000 return d;
1001}
1002
ccad261f
NTND
1003static void do_invalidate_gitignore(struct untracked_cache_dir *dir)
1004{
1005 int i;
1006 dir->valid = 0;
1007 dir->untracked_nr = 0;
1008 for (i = 0; i < dir->dirs_nr; i++)
1009 do_invalidate_gitignore(dir->dirs[i]);
1010}
1011
1012static void invalidate_gitignore(struct untracked_cache *uc,
1013 struct untracked_cache_dir *dir)
1014{
1015 uc->gitignore_invalidated++;
1016 do_invalidate_gitignore(dir);
1017}
1018
91a2288b
NTND
1019static void invalidate_directory(struct untracked_cache *uc,
1020 struct untracked_cache_dir *dir)
1021{
26cb0182 1022 int i;
b6403131
NTND
1023
1024 /*
1025 * Invalidation increment here is just roughly correct. If
1026 * untracked_nr or any of dirs[].recurse is non-zero, we
1027 * should increment dir_invalidated too. But that's more
1028 * expensive to do.
1029 */
1030 if (dir->valid)
1031 uc->dir_invalidated++;
1032
91a2288b
NTND
1033 dir->valid = 0;
1034 dir->untracked_nr = 0;
26cb0182
NTND
1035 for (i = 0; i < dir->dirs_nr; i++)
1036 dir->dirs[i]->recurse = 0;
91a2288b
NTND
1037}
1038
65edd96a 1039static int add_patterns_from_buffer(char *buf, size_t size,
578d81d0 1040 const char *base, int baselen,
caa3d554 1041 struct pattern_list *pl);
578d81d0 1042
feb9b779
JK
1043/* Flags for add_patterns() */
1044#define PATTERN_NOFOLLOW (1<<0)
1045
55fe6f51
NTND
1046/*
1047 * Given a file with name "fname", read it (either from disk, or from
473e3930 1048 * an index if 'istate' is non-null), parse it and store the
caa3d554 1049 * exclude rules in "pl".
55fe6f51 1050 *
e5cf6d3d 1051 * If "oid_stat" is not NULL, compute oid of the exclude file and fill
65edd96a 1052 * stat data from disk (only valid if add_patterns returns zero). If
e5cf6d3d 1053 * oid_stat.valid is non-zero, "oid_stat" must contain good value as input.
55fe6f51 1054 */
65edd96a 1055static int add_patterns(const char *fname, const char *base, int baselen,
caa3d554 1056 struct pattern_list *pl, struct index_state *istate,
1679d60b 1057 unsigned flags, struct oid_stat *oid_stat)
453ec4bd 1058{
c470701a 1059 struct stat st;
578d81d0
JH
1060 int r;
1061 int fd;
9d14017a 1062 size_t size = 0;
578d81d0 1063 char *buf;
453ec4bd 1064
feb9b779
JK
1065 if (flags & PATTERN_NOFOLLOW)
1066 fd = open_nofollow(fname, O_RDONLY);
1067 else
1068 fd = open(fname, O_RDONLY);
1069
c28b3d6e 1070 if (fd < 0 || fstat(fd, &st) < 0) {
11dc1fcb
NTND
1071 if (fd < 0)
1072 warn_on_fopen_errors(fname);
1073 else
c28b3d6e 1074 close(fd);
578d81d0 1075 if (!istate)
c28b3d6e 1076 return -1;
578d81d0
JH
1077 r = read_skip_worktree_file_from_index(istate, fname,
1078 &size, &buf,
4b33e602 1079 oid_stat);
578d81d0
JH
1080 if (r != 1)
1081 return r;
d961baa8 1082 } else {
c28b3d6e
NTND
1083 size = xsize_t(st.st_size);
1084 if (size == 0) {
4b33e602
PO
1085 if (oid_stat) {
1086 fill_stat_data(&oid_stat->stat, &st);
ba2df751 1087 oidcpy(&oid_stat->oid, the_hash_algo->empty_blob);
4b33e602 1088 oid_stat->valid = 1;
55fe6f51 1089 }
c28b3d6e
NTND
1090 close(fd);
1091 return 0;
1092 }
3733e694 1093 buf = xmallocz(size);
c28b3d6e 1094 if (read_in_full(fd, buf, size) != size) {
45d76f17 1095 free(buf);
c28b3d6e
NTND
1096 close(fd);
1097 return -1;
1098 }
45d76f17 1099 buf[size++] = '\n';
c28b3d6e 1100 close(fd);
4b33e602 1101 if (oid_stat) {
55fe6f51 1102 int pos;
4b33e602
PO
1103 if (oid_stat->valid &&
1104 !match_stat_data_racy(istate, &oid_stat->stat, &st))
e5cf6d3d 1105 ; /* no content change, oid_stat->oid still good */
473e3930
BW
1106 else if (istate &&
1107 (pos = index_name_pos(istate, fname, strlen(fname))) >= 0 &&
1108 !ce_stage(istate->cache[pos]) &&
1109 ce_uptodate(istate->cache[pos]) &&
82b474e0 1110 !would_convert_to_git(istate, fname))
4b33e602
PO
1111 oidcpy(&oid_stat->oid,
1112 &istate->cache[pos]->oid);
55fe6f51 1113 else
2dcde20e
MT
1114 hash_object_file(the_hash_algo, buf, size,
1115 "blob", &oid_stat->oid);
4b33e602
PO
1116 fill_stat_data(&oid_stat->stat, &st);
1117 oid_stat->valid = 1;
55fe6f51 1118 }
6ba78238 1119 }
453ec4bd 1120
65edd96a 1121 add_patterns_from_buffer(buf, size, base, baselen, pl);
578d81d0
JH
1122 return 0;
1123}
1124
65edd96a 1125static int add_patterns_from_buffer(char *buf, size_t size,
578d81d0 1126 const char *base, int baselen,
caa3d554 1127 struct pattern_list *pl)
578d81d0
JH
1128{
1129 int i, lineno = 1;
1130 char *entry;
1131
96cc8ab5
DS
1132 hashmap_init(&pl->recursive_hashmap, pl_hashmap_cmp, NULL, 0);
1133 hashmap_init(&pl->parent_hashmap, pl_hashmap_cmp, NULL, 0);
1134
caa3d554 1135 pl->filebuf = buf;
245e1c19 1136
dde843e7 1137 if (skip_utf8_bom(&buf, size))
caa3d554 1138 size -= buf - pl->filebuf;
dde843e7 1139
453ec4bd 1140 entry = buf;
245e1c19 1141
45d76f17
NTND
1142 for (i = 0; i < size; i++) {
1143 if (buf[i] == '\n') {
453ec4bd
LT
1144 if (entry != buf + i && entry[0] != '#') {
1145 buf[i - (i && buf[i-1] == '\r')] = 0;
7e2e4b37 1146 trim_trailing_spaces(entry);
65edd96a 1147 add_pattern(entry, base, baselen, pl, lineno);
453ec4bd 1148 }
c04318e4 1149 lineno++;
453ec4bd
LT
1150 entry = buf + i + 1;
1151 }
1152 }
1153 return 0;
453ec4bd
LT
1154}
1155
65edd96a 1156int add_patterns_from_file_to_list(const char *fname, const char *base,
caa3d554 1157 int baselen, struct pattern_list *pl,
1679d60b
JK
1158 struct index_state *istate,
1159 unsigned flags)
55fe6f51 1160{
1679d60b 1161 return add_patterns(fname, base, baselen, pl, istate, flags, NULL);
55fe6f51
NTND
1162}
1163
65edd96a 1164int add_patterns_from_blob_to_list(
578d81d0
JH
1165 struct object_id *oid,
1166 const char *base, int baselen,
caa3d554 1167 struct pattern_list *pl)
578d81d0
JH
1168{
1169 char *buf;
1170 size_t size;
1171 int r;
1172
1173 r = do_read_blob(oid, NULL, &size, &buf);
1174 if (r != 1)
1175 return r;
1176
65edd96a 1177 add_patterns_from_buffer(buf, size, base, baselen, pl);
578d81d0
JH
1178 return 0;
1179}
1180
65edd96a 1181struct pattern_list *add_pattern_list(struct dir_struct *dir,
c04318e4 1182 int group_type, const char *src)
c082df24 1183{
caa3d554 1184 struct pattern_list *pl;
c082df24
AS
1185 struct exclude_list_group *group;
1186
1187 group = &dir->exclude_list_group[group_type];
caa3d554
DS
1188 ALLOC_GROW(group->pl, group->nr + 1, group->alloc);
1189 pl = &group->pl[group->nr++];
1190 memset(pl, 0, sizeof(*pl));
1191 pl->src = src;
1192 return pl;
c082df24
AS
1193}
1194
1195/*
1196 * Used to set up core.excludesfile and .git/info/exclude lists.
1197 */
65edd96a 1198static void add_patterns_from_file_1(struct dir_struct *dir, const char *fname,
4b33e602 1199 struct oid_stat *oid_stat)
453ec4bd 1200{
caa3d554 1201 struct pattern_list *pl;
ccad261f
NTND
1202 /*
1203 * catch setup_standard_excludes() that's called before
1204 * dir->untracked is assigned. That function behaves
1205 * differently when dir->untracked is non-NULL.
1206 */
1207 if (!dir->untracked)
1208 dir->unmanaged_exclude_files++;
65edd96a 1209 pl = add_pattern_list(dir, EXC_FILE, fname);
1679d60b 1210 if (add_patterns(fname, "", 0, pl, NULL, 0, oid_stat) < 0)
a80897c1 1211 die(_("cannot use %s as an exclude file"), fname);
453ec4bd
LT
1212}
1213
65edd96a 1214void add_patterns_from_file(struct dir_struct *dir, const char *fname)
0dcb8d7f 1215{
ccad261f 1216 dir->unmanaged_exclude_files++; /* see validate_untracked_cache() */
65edd96a 1217 add_patterns_from_file_1(dir, fname, NULL);
0dcb8d7f
NTND
1218}
1219
82dce998
NTND
1220int match_basename(const char *basename, int basenamelen,
1221 const char *pattern, int prefix, int patternlen,
f8708998 1222 unsigned flags)
593cb880
NTND
1223{
1224 if (prefix == patternlen) {
0b6e56df 1225 if (patternlen == basenamelen &&
ba0897e6 1226 !fspathncmp(pattern, basename, basenamelen))
593cb880 1227 return 1;
4ff89ee5 1228 } else if (flags & PATTERN_FLAG_ENDSWITH) {
0b6e56df 1229 /* "*literal" matching against "fooliteral" */
593cb880 1230 if (patternlen - 1 <= basenamelen &&
ba0897e6 1231 !fspathncmp(pattern + 1,
0b6e56df
JH
1232 basename + basenamelen - (patternlen - 1),
1233 patternlen - 1))
593cb880
NTND
1234 return 1;
1235 } else {
0b6e56df
JH
1236 if (fnmatch_icase_mem(pattern, patternlen,
1237 basename, basenamelen,
1238 0) == 0)
593cb880
NTND
1239 return 1;
1240 }
1241 return 0;
1242}
1243
82dce998
NTND
1244int match_pathname(const char *pathname, int pathlen,
1245 const char *base, int baselen,
1246 const char *pattern, int prefix, int patternlen,
f8708998 1247 unsigned flags)
b5592632
NTND
1248{
1249 const char *name;
1250 int namelen;
1251
1252 /*
1253 * match with FNM_PATHNAME; the pattern has base implicitly
1254 * in front of it.
1255 */
1256 if (*pattern == '/') {
1257 pattern++;
982ac873 1258 patternlen--;
b5592632
NTND
1259 prefix--;
1260 }
1261
1262 /*
1263 * baselen does not count the trailing slash. base[] may or
1264 * may not end with a trailing slash though.
1265 */
1266 if (pathlen < baselen + 1 ||
1267 (baselen && pathname[baselen] != '/') ||
ba0897e6 1268 fspathncmp(pathname, base, baselen))
b5592632
NTND
1269 return 0;
1270
1271 namelen = baselen ? pathlen - baselen - 1 : pathlen;
1272 name = pathname + pathlen - namelen;
1273
1274 if (prefix) {
1275 /*
1276 * if the non-wildcard part is longer than the
1277 * remaining pathname, surely it cannot match.
1278 */
1279 if (prefix > namelen)
1280 return 0;
1281
ba0897e6 1282 if (fspathncmp(pattern, name, prefix))
b5592632
NTND
1283 return 0;
1284 pattern += prefix;
ab3aebc1 1285 patternlen -= prefix;
b5592632
NTND
1286 name += prefix;
1287 namelen -= prefix;
ab3aebc1
JK
1288
1289 /*
1290 * If the whole pattern did not have a wildcard,
1291 * then our prefix match is all we need; we
1292 * do not need to call fnmatch at all.
1293 */
5cee3493 1294 if (!patternlen && !namelen)
ab3aebc1 1295 return 1;
b5592632
NTND
1296 }
1297
ab3aebc1
JK
1298 return fnmatch_icase_mem(pattern, patternlen,
1299 name, namelen,
f30366b2 1300 WM_PATHNAME) == 0;
b5592632
NTND
1301}
1302
578cd7c3
AS
1303/*
1304 * Scan the given exclude list in reverse to see whether pathname
1305 * should be ignored. The first match (i.e. the last on the list), if
1306 * any, determines the fate. Returns the exclude_list element which
1307 * matched, or NULL for undecided.
453ec4bd 1308 */
65edd96a 1309static struct path_pattern *last_matching_pattern_from_list(const char *pathname,
578cd7c3
AS
1310 int pathlen,
1311 const char *basename,
1312 int *dtype,
caa3d554 1313 struct pattern_list *pl,
2b70e88d 1314 struct index_state *istate)
453ec4bd 1315{
ab8db613 1316 struct path_pattern *res = NULL; /* undecided */
5cee3493 1317 int i;
453ec4bd 1318
caa3d554 1319 if (!pl->nr)
578cd7c3 1320 return NULL; /* undefined */
d6b8fc30 1321
caa3d554
DS
1322 for (i = pl->nr - 1; 0 <= i; i--) {
1323 struct path_pattern *pattern = pl->patterns[i];
ab8db613
DS
1324 const char *exclude = pattern->pattern;
1325 int prefix = pattern->nowildcardlen;
35a94d44 1326
4ff89ee5 1327 if (pattern->flags & PATTERN_FLAG_MUSTBEDIR) {
ad6f2157 1328 *dtype = resolve_dtype(*dtype, istate, pathname, pathlen);
35a94d44
NTND
1329 if (*dtype != DT_DIR)
1330 continue;
1331 }
d6b8fc30 1332
4ff89ee5 1333 if (pattern->flags & PATTERN_FLAG_NODIR) {
593cb880
NTND
1334 if (match_basename(basename,
1335 pathlen - (basename - pathname),
ab8db613
DS
1336 exclude, prefix, pattern->patternlen,
1337 pattern->flags)) {
1338 res = pattern;
e6efecc4
NTND
1339 break;
1340 }
35a94d44
NTND
1341 continue;
1342 }
1343
ab8db613
DS
1344 assert(pattern->baselen == 0 ||
1345 pattern->base[pattern->baselen - 1] == '/');
b5592632 1346 if (match_pathname(pathname, pathlen,
ab8db613
DS
1347 pattern->base,
1348 pattern->baselen ? pattern->baselen - 1 : 0,
1349 exclude, prefix, pattern->patternlen,
1350 pattern->flags)) {
1351 res = pattern;
e6efecc4
NTND
1352 break;
1353 }
453ec4bd 1354 }
ab8db613 1355 return res;
578cd7c3
AS
1356}
1357
1358/*
468ce99b
DS
1359 * Scan the list of patterns to determine if the ordered list
1360 * of patterns matches on 'pathname'.
1361 *
1362 * Return 1 for a match, 0 for not matched and -1 for undecided.
578cd7c3 1363 */
468ce99b
DS
1364enum pattern_match_result path_matches_pattern_list(
1365 const char *pathname, int pathlen,
1366 const char *basename, int *dtype,
1367 struct pattern_list *pl,
1368 struct index_state *istate)
578cd7c3 1369{
ab8db613 1370 struct path_pattern *pattern;
96cc8ab5
DS
1371 struct strbuf parent_pathname = STRBUF_INIT;
1372 int result = NOT_MATCHED;
1373 const char *slash_pos;
1374
1375 if (!pl->use_cone_patterns) {
1376 pattern = last_matching_pattern_from_list(pathname, pathlen, basename,
1377 dtype, pl, istate);
1378 if (pattern) {
1379 if (pattern->flags & PATTERN_FLAG_NEGATIVE)
1380 return NOT_MATCHED;
1381 else
1382 return MATCHED;
1383 }
1384
1385 return UNDECIDED;
1386 }
1387
1388 if (pl->full_cone)
1389 return MATCHED;
1390
1391 strbuf_addch(&parent_pathname, '/');
1392 strbuf_add(&parent_pathname, pathname, pathlen);
1393
1394 if (hashmap_contains_path(&pl->recursive_hashmap,
1395 &parent_pathname)) {
eb42feca 1396 result = MATCHED_RECURSIVE;
96cc8ab5 1397 goto done;
468ce99b
DS
1398 }
1399
96cc8ab5
DS
1400 slash_pos = strrchr(parent_pathname.buf, '/');
1401
1402 if (slash_pos == parent_pathname.buf) {
1403 /* include every file in root */
1404 result = MATCHED;
1405 goto done;
1406 }
1407
1408 strbuf_setlen(&parent_pathname, slash_pos - parent_pathname.buf);
1409
1410 if (hashmap_contains_path(&pl->parent_hashmap, &parent_pathname)) {
1411 result = MATCHED;
1412 goto done;
1413 }
1414
1415 if (hashmap_contains_parent(&pl->recursive_hashmap,
1416 pathname,
1417 &parent_pathname))
eb42feca 1418 result = MATCHED_RECURSIVE;
96cc8ab5
DS
1419
1420done:
1421 strbuf_release(&parent_pathname);
1422 return result;
453ec4bd
LT
1423}
1424
65edd96a 1425static struct path_pattern *last_matching_pattern_from_lists(
ab8db613
DS
1426 struct dir_struct *dir, struct index_state *istate,
1427 const char *pathname, int pathlen,
1428 const char *basename, int *dtype_p)
46aa2f95
KB
1429{
1430 int i, j;
1431 struct exclude_list_group *group;
ab8db613 1432 struct path_pattern *pattern;
46aa2f95
KB
1433 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
1434 group = &dir->exclude_list_group[i];
1435 for (j = group->nr - 1; j >= 0; j--) {
65edd96a 1436 pattern = last_matching_pattern_from_list(
46aa2f95 1437 pathname, pathlen, basename, dtype_p,
caa3d554 1438 &group->pl[j], istate);
ab8db613
DS
1439 if (pattern)
1440 return pattern;
46aa2f95
KB
1441 }
1442 }
1443 return NULL;
1444}
1445
6cd5c582
KB
1446/*
1447 * Loads the per-directory exclude list for the substring of base
1448 * which has a char length of baselen.
1449 */
e799ed40
BW
1450static void prep_exclude(struct dir_struct *dir,
1451 struct index_state *istate,
1452 const char *base, int baselen)
6cd5c582
KB
1453{
1454 struct exclude_list_group *group;
caa3d554 1455 struct pattern_list *pl;
6cd5c582 1456 struct exclude_stack *stk = NULL;
0dcb8d7f 1457 struct untracked_cache_dir *untracked;
6cd5c582
KB
1458 int current;
1459
6cd5c582
KB
1460 group = &dir->exclude_list_group[EXC_DIRS];
1461
d961baa8
NTND
1462 /*
1463 * Pop the exclude lists from the EXCL_DIRS exclude_list_group
6cd5c582 1464 * which originate from directories not in the prefix of the
d961baa8
NTND
1465 * path being checked.
1466 */
6cd5c582
KB
1467 while ((stk = dir->exclude_stack) != NULL) {
1468 if (stk->baselen <= baselen &&
aceb9429 1469 !strncmp(dir->basebuf.buf, base, stk->baselen))
6cd5c582 1470 break;
caa3d554 1471 pl = &group->pl[dir->exclude_stack->exclude_ix];
6cd5c582 1472 dir->exclude_stack = stk->prev;
ab8db613 1473 dir->pattern = NULL;
caa3d554 1474 free((char *)pl->src); /* see strbuf_detach() below */
65edd96a 1475 clear_pattern_list(pl);
6cd5c582
KB
1476 free(stk);
1477 group->nr--;
1478 }
1479
95c6f271 1480 /* Skip traversing into sub directories if the parent is excluded */
ab8db613 1481 if (dir->pattern)
95c6f271
KB
1482 return;
1483
aceb9429
NTND
1484 /*
1485 * Lazy initialization. All call sites currently just
1486 * memset(dir, 0, sizeof(*dir)) before use. Changing all of
1487 * them seems lots of work for little benefit.
1488 */
1489 if (!dir->basebuf.buf)
1490 strbuf_init(&dir->basebuf, PATH_MAX);
1491
6cd5c582
KB
1492 /* Read from the parent directories and push them down. */
1493 current = stk ? stk->baselen : -1;
aceb9429 1494 strbuf_setlen(&dir->basebuf, current < 0 ? 0 : current);
0dcb8d7f
NTND
1495 if (dir->untracked)
1496 untracked = stk ? stk->ucd : dir->untracked->root;
1497 else
1498 untracked = NULL;
1499
6cd5c582 1500 while (current < baselen) {
6cd5c582 1501 const char *cp;
4b33e602 1502 struct oid_stat oid_stat;
6cd5c582 1503
ca56dadb 1504 CALLOC_ARRAY(stk, 1);
6cd5c582
KB
1505 if (current < 0) {
1506 cp = base;
1507 current = 0;
d961baa8 1508 } else {
6cd5c582
KB
1509 cp = strchr(base + current + 1, '/');
1510 if (!cp)
1511 die("oops in prep_exclude");
1512 cp++;
0dcb8d7f
NTND
1513 untracked =
1514 lookup_untracked(dir->untracked, untracked,
1515 base + current,
1516 cp - base - current);
6cd5c582
KB
1517 }
1518 stk->prev = dir->exclude_stack;
1519 stk->baselen = cp - base;
95c6f271 1520 stk->exclude_ix = group->nr;
0dcb8d7f 1521 stk->ucd = untracked;
65edd96a 1522 pl = add_pattern_list(dir, EXC_DIRS, NULL);
aceb9429
NTND
1523 strbuf_add(&dir->basebuf, base + current, stk->baselen - current);
1524 assert(stk->baselen == dir->basebuf.len);
95c6f271
KB
1525
1526 /* Abort if the directory is excluded */
1527 if (stk->baselen) {
1528 int dt = DT_DIR;
aceb9429 1529 dir->basebuf.buf[stk->baselen - 1] = 0;
65edd96a 1530 dir->pattern = last_matching_pattern_from_lists(dir,
e799ed40 1531 istate,
aceb9429
NTND
1532 dir->basebuf.buf, stk->baselen - 1,
1533 dir->basebuf.buf + current, &dt);
1534 dir->basebuf.buf[stk->baselen - 1] = '/';
ab8db613 1535 if (dir->pattern &&
4ff89ee5 1536 dir->pattern->flags & PATTERN_FLAG_NEGATIVE)
ab8db613
DS
1537 dir->pattern = NULL;
1538 if (dir->pattern) {
95c6f271
KB
1539 dir->exclude_stack = stk;
1540 return;
1541 }
1542 }
1543
aceb9429 1544 /* Try to read per-directory file */
4b33e602
PO
1545 oidclr(&oid_stat.oid);
1546 oid_stat.valid = 0;
27b099ae
NTND
1547 if (dir->exclude_per_dir &&
1548 /*
1549 * If we know that no files have been added in
1550 * this directory (i.e. valid_cached_dir() has
1551 * been executed and set untracked->valid) ..
1552 */
1553 (!untracked || !untracked->valid ||
1554 /*
1555 * .. and .gitignore does not exist before
70c369cd 1556 * (i.e. null exclude_oid). Then we can skip
7687252f
DT
1557 * loading .gitignore, which would result in
1558 * ENOENT anyway.
27b099ae 1559 */
70c369cd 1560 !is_null_oid(&untracked->exclude_oid))) {
95c6f271
KB
1561 /*
1562 * dir->basebuf gets reused by the traversal, but we
1563 * need fname to remain unchanged to ensure the src
ab8db613 1564 * member of each struct path_pattern correctly
95c6f271 1565 * back-references its source file. Other invocations
65edd96a 1566 * of add_pattern_list provide stable strings, so we
aceb9429 1567 * strbuf_detach() and free() here in the caller.
95c6f271 1568 */
aceb9429
NTND
1569 struct strbuf sb = STRBUF_INIT;
1570 strbuf_addbuf(&sb, &dir->basebuf);
1571 strbuf_addstr(&sb, dir->exclude_per_dir);
caa3d554 1572 pl->src = strbuf_detach(&sb, NULL);
65edd96a 1573 add_patterns(pl->src, pl->src, stk->baselen, pl, istate,
feb9b779 1574 PATTERN_NOFOLLOW,
4b33e602 1575 untracked ? &oid_stat : NULL);
0dcb8d7f 1576 }
5ebf79ad
NTND
1577 /*
1578 * NEEDSWORK: when untracked cache is enabled, prep_exclude()
1579 * will first be called in valid_cached_dir() then maybe many
65edd96a
DS
1580 * times more in last_matching_pattern(). When the cache is
1581 * used, last_matching_pattern() will not be called and
5ebf79ad
NTND
1582 * reading .gitignore content will be a waste.
1583 *
1584 * So when it's called by valid_cached_dir() and we can get
1585 * .gitignore SHA-1 from the index (i.e. .gitignore is not
1586 * modified on work tree), we could delay reading the
1587 * .gitignore content until we absolutely need it in
65edd96a 1588 * last_matching_pattern(). Be careful about ignore rule
5ebf79ad
NTND
1589 * order, though, if you do that.
1590 */
1591 if (untracked &&
9001dc2a 1592 !oideq(&oid_stat.oid, &untracked->exclude_oid)) {
5ebf79ad 1593 invalidate_gitignore(dir->untracked, untracked);
70c369cd 1594 oidcpy(&untracked->exclude_oid, &oid_stat.oid);
95c6f271 1595 }
6cd5c582
KB
1596 dir->exclude_stack = stk;
1597 current = stk->baselen;
1598 }
aceb9429 1599 strbuf_setlen(&dir->basebuf, baselen);
6cd5c582
KB
1600}
1601
f4cd69a6
AS
1602/*
1603 * Loads the exclude lists for the directory containing pathname, then
1604 * scans all exclude lists to determine whether pathname is excluded.
1605 * Returns the exclude_list element which matched, or NULL for
1606 * undecided.
1607 */
65edd96a 1608struct path_pattern *last_matching_pattern(struct dir_struct *dir,
a0bba65b
BW
1609 struct index_state *istate,
1610 const char *pathname,
1611 int *dtype_p)
453ec4bd
LT
1612{
1613 int pathlen = strlen(pathname);
68492fc7
LK
1614 const char *basename = strrchr(pathname, '/');
1615 basename = (basename) ? basename+1 : pathname;
453ec4bd 1616
a0bba65b 1617 prep_exclude(dir, istate, pathname, basename-pathname);
c082df24 1618
ab8db613
DS
1619 if (dir->pattern)
1620 return dir->pattern;
95c6f271 1621
65edd96a 1622 return last_matching_pattern_from_lists(dir, istate, pathname, pathlen,
46aa2f95 1623 basename, dtype_p);
f4cd69a6
AS
1624}
1625
1626/*
1627 * Loads the exclude lists for the directory containing pathname, then
1628 * scans all exclude lists to determine whether pathname is excluded.
1629 * Returns 1 if true, otherwise 0.
1630 */
a0bba65b
BW
1631int is_excluded(struct dir_struct *dir, struct index_state *istate,
1632 const char *pathname, int *dtype_p)
f4cd69a6 1633{
ab8db613 1634 struct path_pattern *pattern =
65edd96a 1635 last_matching_pattern(dir, istate, pathname, dtype_p);
ab8db613 1636 if (pattern)
4ff89ee5 1637 return pattern->flags & PATTERN_FLAG_NEGATIVE ? 0 : 1;
453ec4bd
LT
1638 return 0;
1639}
1640
f3fa1838
JH
1641static struct dir_entry *dir_entry_new(const char *pathname, int len)
1642{
453ec4bd
LT
1643 struct dir_entry *ent;
1644
96ffc06f 1645 FLEX_ALLOC_MEM(ent, name, pathname, len);
453ec4bd 1646 ent->len = len;
4d06f8ac 1647 return ent;
453ec4bd
LT
1648}
1649
9e58beca
BW
1650static struct dir_entry *dir_add_name(struct dir_struct *dir,
1651 struct index_state *istate,
1652 const char *pathname, int len)
6815e569 1653{
9e58beca 1654 if (index_file_exists(istate, pathname, len, ignore_case))
6815e569
JK
1655 return NULL;
1656
25fd2f7a 1657 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
6815e569
JK
1658 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
1659}
1660
9e58beca
BW
1661struct dir_entry *dir_add_ignored(struct dir_struct *dir,
1662 struct index_state *istate,
1663 const char *pathname, int len)
2abd31b0 1664{
9e58beca 1665 if (!index_name_is_other(istate, pathname, len))
2abd31b0
JK
1666 return NULL;
1667
25fd2f7a 1668 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
2abd31b0
JK
1669 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
1670}
1671
09595258
LT
1672enum exist_status {
1673 index_nonexistent = 0,
1674 index_directory,
4b05548f 1675 index_gitdir
09595258
LT
1676};
1677
5102c617 1678/*
71261027 1679 * Do not use the alphabetically sorted index to look up
5102c617 1680 * the directory name; instead, use the case insensitive
ebbd7439 1681 * directory hash.
5102c617 1682 */
ae520e36
BW
1683static enum exist_status directory_exists_in_index_icase(struct index_state *istate,
1684 const char *dirname, int len)
5102c617 1685{
41284eb0 1686 struct cache_entry *ce;
5102c617 1687
ae520e36 1688 if (index_dir_exists(istate, dirname, len))
5102c617
JJ
1689 return index_directory;
1690
ae520e36 1691 ce = index_file_exists(istate, dirname, len, ignore_case);
41284eb0 1692 if (ce && S_ISGITLINK(ce->ce_mode))
5102c617
JJ
1693 return index_gitdir;
1694
5102c617
JJ
1695 return index_nonexistent;
1696}
1697
09595258
LT
1698/*
1699 * The index sorts alphabetically by entry name, which
1700 * means that a gitlink sorts as '\0' at the end, while
1701 * a directory (which is defined not as an entry, but as
1702 * the files it contains) will sort with the '/' at the
1703 * end.
1704 */
ae520e36
BW
1705static enum exist_status directory_exists_in_index(struct index_state *istate,
1706 const char *dirname, int len)
453ec4bd 1707{
5102c617
JJ
1708 int pos;
1709
1710 if (ignore_case)
ae520e36 1711 return directory_exists_in_index_icase(istate, dirname, len);
5102c617 1712
ae520e36 1713 pos = index_name_pos(istate, dirname, len);
09595258
LT
1714 if (pos < 0)
1715 pos = -pos-1;
ae520e36
BW
1716 while (pos < istate->cache_nr) {
1717 const struct cache_entry *ce = istate->cache[pos++];
09595258
LT
1718 unsigned char endchar;
1719
1720 if (strncmp(ce->name, dirname, len))
1721 break;
1722 endchar = ce->name[len];
1723 if (endchar > '/')
1724 break;
1725 if (endchar == '/')
1726 return index_directory;
7a51ed66 1727 if (!endchar && S_ISGITLINK(ce->ce_mode))
09595258
LT
1728 return index_gitdir;
1729 }
1730 return index_nonexistent;
1731}
1732
1733/*
1734 * When we find a directory when traversing the filesystem, we
1735 * have three distinct cases:
1736 *
1737 * - ignore it
1738 * - see it as a directory
1739 * - recurse into it
1740 *
1741 * and which one we choose depends on a combination of existing
1742 * git index contents and the flags passed into the directory
1743 * traversal routine.
1744 *
1745 * Case 1: If we *already* have entries in the index under that
5bd8e2d8
KB
1746 * directory name, we always recurse into the directory to see
1747 * all the files.
09595258
LT
1748 *
1749 * Case 2: If we *already* have that directory name as a gitlink,
1750 * we always continue to see it as a gitlink, regardless of whether
1751 * there is an actual git directory there or not (it might not
1752 * be checked out as a subproject!)
1753 *
1754 * Case 3: if we didn't have it in the index previously, we
1755 * have a few sub-cases:
1756 *
4e689d81
DS
1757 * (a) if DIR_SHOW_OTHER_DIRECTORIES flag is set, we show it as
1758 * just a directory, unless DIR_HIDE_EMPTY_DIRECTORIES is
defd7c7b
KB
1759 * also true, in which case we need to check if it contains any
1760 * untracked and / or ignored files.
4e689d81
DS
1761 * (b) if it looks like a git directory and we don't have the
1762 * DIR_NO_GITLINKS flag, then we treat it as a gitlink, and
1763 * show it as a directory.
09595258
LT
1764 * (c) otherwise, we recurse into it.
1765 */
defd7c7b 1766static enum path_treatment treat_directory(struct dir_struct *dir,
0ef8e169 1767 struct index_state *istate,
0dcb8d7f 1768 struct untracked_cache_dir *untracked,
2df179d3 1769 const char *dirname, int len, int baselen, int excluded,
e1b8c7bd 1770 const struct pathspec *pathspec)
09595258 1771{
8d92fb29
EN
1772 /*
1773 * WARNING: From this function, you can return path_recurse or you
1774 * can call read_directory_recursive() (or neither), but
1775 * you CAN'T DO BOTH.
1776 */
1777 enum path_treatment state;
7f45ab2d 1778 int matches_how = 0;
16846444
EN
1779 int nested_repo = 0, check_only, stop_early;
1780 int old_ignored_nr, old_untracked_nr;
09595258 1781 /* The "len-1" is to strip the final '/' */
0bbd0e8b 1782 enum exist_status status = directory_exists_in_index(istate, dirname, len-1);
09595258 1783
0bbd0e8b
DS
1784 if (status == index_directory)
1785 return path_recurse;
1786 if (status == index_gitdir)
26c986e1 1787 return path_none;
0bbd0e8b
DS
1788 if (status != index_nonexistent)
1789 BUG("Unhandled value for directory_exists_in_index: %d\n", status);
09595258 1790
7f45ab2d
EN
1791 /*
1792 * We don't want to descend into paths that don't match the necessary
1793 * patterns. Clearly, if we don't have a pathspec, then we can't check
1794 * for matching patterns. Also, if (excluded) then we know we matched
1795 * the exclusion patterns so as an optimization we can skip checking
1796 * for matching patterns.
1797 */
1798 if (pathspec && !excluded) {
f1f061e1
EN
1799 matches_how = match_pathspec_with_flags(istate, pathspec,
1800 dirname, len,
1801 0 /* prefix */,
1802 NULL /* seen */,
1803 DO_MATCH_LEADING_PATHSPEC);
7f45ab2d
EN
1804 if (!matches_how)
1805 return path_none;
1806 }
09487f2c 1807
7f45ab2d 1808
0bbd0e8b
DS
1809 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
1810 !(dir->flags & DIR_NO_GITLINKS)) {
1811 struct strbuf sb = STRBUF_INIT;
1812 strbuf_addstr(&sb, dirname);
1813 nested_repo = is_nonbare_repository_dir(&sb);
1814 strbuf_release(&sb);
1815 }
ab282aa5
EN
1816 if (nested_repo) {
1817 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
1818 (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC))
1819 return path_none;
1820 return excluded ? path_excluded : path_untracked;
1821 }
09595258 1822
0bbd0e8b 1823 if (!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)) {
2df179d3
EN
1824 if (excluded &&
1825 (dir->flags & DIR_SHOW_IGNORED_TOO) &&
1826 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING)) {
eec0f7f2
JM
1827
1828 /*
1829 * This is an excluded directory and we are
1830 * showing ignored paths that match an exclude
1831 * pattern. (e.g. show directory as ignored
1832 * only if it matches an exclude pattern).
1833 * This path will either be 'path_excluded`
1834 * (if we are showing empty directories or if
1835 * the directory is not empty), or will be
1836 * 'path_none' (empty directory, and we are
1837 * not showing empty directories).
1838 */
1839 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1840 return path_excluded;
1841
1842 if (read_directory_recursive(dir, istate, dirname, len,
1843 untracked, 1, 1, pathspec) == path_excluded)
1844 return path_excluded;
1845
1846 return path_none;
1847 }
defd7c7b 1848 return path_recurse;
09595258
LT
1849 }
1850
aa6e1b21 1851 assert(dir->flags & DIR_SHOW_OTHER_DIRECTORIES);
721ac4ed 1852
8d92fb29
EN
1853 /*
1854 * If we have a pathspec which could match something _below_ this
1855 * directory (e.g. when checking 'subdir/' having a pathspec like
1856 * 'subdir/some/deep/path/file' or 'subdir/widget-*.c'), then we
1857 * need to recurse.
1858 */
7f45ab2d
EN
1859 if (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC)
1860 return path_recurse;
8d92fb29 1861
aa6e1b21
EN
1862 /* Special cases for where this directory is excluded/ignored */
1863 if (excluded) {
1864 /*
4e689d81 1865 * If DIR_SHOW_OTHER_DIRECTORIES is set and we're not
aa6e1b21
EN
1866 * hiding empty directories, there is no need to
1867 * recurse into an ignored directory.
1868 */
1869 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1870 return path_excluded;
1871
1872 /*
1873 * Even if we are hiding empty directories, we can still avoid
1874 * recursing into ignored directories for DIR_SHOW_IGNORED_TOO
1875 * if DIR_SHOW_IGNORED_TOO_MODE_MATCHING is also set.
1876 */
1877 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
1878 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING))
1879 return path_excluded;
1880 }
1881
8d92fb29 1882 /*
aa6e1b21 1883 * Other than the path_recurse case above, we only need to
dd55fc0d 1884 * recurse into untracked directories if any of the following
aa6e1b21 1885 * bits is set:
dd55fc0d
EN
1886 * - DIR_SHOW_IGNORED (because then we need to determine if
1887 * there are ignored entries below)
1888 * - DIR_SHOW_IGNORED_TOO (same as above)
8d92fb29
EN
1889 * - DIR_HIDE_EMPTY_DIRECTORIES (because we have to determine if
1890 * the directory is empty)
1891 */
aa6e1b21 1892 if (!excluded &&
dd55fc0d
EN
1893 !(dir->flags & (DIR_SHOW_IGNORED |
1894 DIR_SHOW_IGNORED_TOO |
aa6e1b21
EN
1895 DIR_HIDE_EMPTY_DIRECTORIES))) {
1896 return path_untracked;
1897 }
8d92fb29
EN
1898
1899 /*
e6c0be92
EN
1900 * Even if we don't want to know all the paths under an untracked or
1901 * ignored directory, we may still need to go into the directory to
1902 * determine if it is empty (because with DIR_HIDE_EMPTY_DIRECTORIES,
1903 * an empty directory should be path_none instead of path_excluded or
1904 * path_untracked).
8d92fb29
EN
1905 */
1906 check_only = ((dir->flags & DIR_HIDE_EMPTY_DIRECTORIES) &&
1907 !(dir->flags & DIR_SHOW_IGNORED_TOO));
1908
1909 /*
1910 * However, there's another optimization possible as a subset of
1911 * check_only, based on the cases we have to consider:
1912 * A) Directory matches no exclude patterns:
1913 * * Directory is empty => path_none
1914 * * Directory has an untracked file under it => path_untracked
1915 * * Directory has only ignored files under it => path_excluded
1916 * B) Directory matches an exclude pattern:
1917 * * Directory is empty => path_none
1918 * * Directory has an untracked file under it => path_excluded
1919 * * Directory has only ignored files under it => path_excluded
1920 * In case A, we can exit as soon as we've found an untracked
1921 * file but otherwise have to walk all files. In case B, though,
1922 * we can stop at the first file we find under the directory.
1923 */
1924 stop_early = check_only && excluded;
1925
1926 /*
1927 * If /every/ file within an untracked directory is ignored, then
1928 * we want to treat the directory as ignored (for e.g. status
1929 * --porcelain), without listing the individual ignored files
1930 * underneath. To do so, we'll save the current ignored_nr, and
1931 * pop all the ones added after it if it turns out the entire
16846444
EN
1932 * directory is ignored. Also, when DIR_SHOW_IGNORED_TOO and
1933 * !DIR_KEEP_UNTRACKED_CONTENTS then we don't want to show
1934 * untracked paths so will need to pop all those off the last
1935 * after we traverse.
8d92fb29
EN
1936 */
1937 old_ignored_nr = dir->ignored_nr;
16846444 1938 old_untracked_nr = dir->nr;
8d92fb29
EN
1939
1940 /* Actually recurse into dirname now, we'll fixup the state later. */
2e5910f2
DT
1941 untracked = lookup_untracked(dir->untracked, untracked,
1942 dirname + baselen, len - baselen);
8d92fb29
EN
1943 state = read_directory_recursive(dir, istate, dirname, len, untracked,
1944 check_only, stop_early, pathspec);
1945
1946 /* There are a variety of reasons we may need to fixup the state... */
1947 if (state == path_excluded) {
1948 /* state == path_excluded implies all paths under
1949 * dirname were ignored...
1950 *
1951 * if running e.g. `git status --porcelain --ignored=matching`,
1952 * then we want to see the subpaths that are ignored.
1953 *
1954 * if running e.g. just `git status --porcelain`, then
1955 * we just want the directory itself to be listed as ignored
1956 * and not the individual paths underneath.
1957 */
1958 int want_ignored_subpaths =
1959 ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
1960 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING));
1961
1962 if (want_ignored_subpaths) {
1963 /*
1964 * with --ignored=matching, we want the subpaths
1965 * INSTEAD of the directory itself.
1966 */
1967 state = path_none;
1968 } else {
1969 int i;
1970 for (i = old_ignored_nr + 1; i<dir->ignored_nr; ++i)
1971 FREE_AND_NULL(dir->ignored[i]);
1972 dir->ignored_nr = old_ignored_nr;
1973 }
1974 }
5aaa7fd3
JM
1975
1976 /*
16846444
EN
1977 * We may need to ignore some of the untracked paths we found while
1978 * traversing subdirectories.
5aaa7fd3 1979 */
16846444
EN
1980 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
1981 !(dir->flags & DIR_KEEP_UNTRACKED_CONTENTS)) {
1982 int i;
1983 for (i = old_untracked_nr + 1; i<dir->nr; ++i)
1984 FREE_AND_NULL(dir->entries[i]);
1985 dir->nr = old_untracked_nr;
1986 }
1987
5aaa7fd3 1988 /*
8d92fb29
EN
1989 * If there is nothing under the current directory and we are not
1990 * hiding empty directories, then we need to report on the
1991 * untracked or ignored status of the directory itself.
5aaa7fd3 1992 */
8d92fb29
EN
1993 if (state == path_none && !(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1994 state = excluded ? path_excluded : path_untracked;
1995
8d92fb29 1996 return state;
453ec4bd
LT
1997}
1998
9fc42d60
LT
1999/*
2000 * This is an inexact early pruning of any recursive directory
2001 * reading - if the path cannot possibly be in the pathspec,
2002 * return true, and we'll skip it early.
2003 */
e1b8c7bd
BW
2004static int simplify_away(const char *path, int pathlen,
2005 const struct pathspec *pathspec)
9fc42d60 2006{
e1b8c7bd 2007 int i;
9fc42d60 2008
e1b8c7bd
BW
2009 if (!pathspec || !pathspec->nr)
2010 return 0;
2011
2012 GUARD_PATHSPEC(pathspec,
2013 PATHSPEC_FROMTOP |
2014 PATHSPEC_MAXDEPTH |
2015 PATHSPEC_LITERAL |
2016 PATHSPEC_GLOB |
2017 PATHSPEC_ICASE |
b0db7046
BW
2018 PATHSPEC_EXCLUDE |
2019 PATHSPEC_ATTR);
e1b8c7bd
BW
2020
2021 for (i = 0; i < pathspec->nr; i++) {
2022 const struct pathspec_item *item = &pathspec->items[i];
2023 int len = item->nowildcard_len;
2024
2025 if (len > pathlen)
2026 len = pathlen;
2027 if (!ps_strncmp(item, item->match, path, len))
2028 return 0;
9fc42d60 2029 }
e1b8c7bd
BW
2030
2031 return 1;
9fc42d60
LT
2032}
2033
29209cbe
JK
2034/*
2035 * This function tells us whether an excluded path matches a
2036 * list of "interesting" pathspecs. That is, whether a path matched
2037 * by any of the pathspecs could possibly be ignored by excluding
2038 * the specified path. This can happen if:
2039 *
2040 * 1. the path is mentioned explicitly in the pathspec
2041 *
2042 * 2. the path is a directory prefix of some element in the
2043 * pathspec
2044 */
e1b8c7bd
BW
2045static int exclude_matches_pathspec(const char *path, int pathlen,
2046 const struct pathspec *pathspec)
2047{
2048 int i;
2049
2050 if (!pathspec || !pathspec->nr)
2051 return 0;
2052
2053 GUARD_PATHSPEC(pathspec,
2054 PATHSPEC_FROMTOP |
2055 PATHSPEC_MAXDEPTH |
2056 PATHSPEC_LITERAL |
2057 PATHSPEC_GLOB |
2058 PATHSPEC_ICASE |
2059 PATHSPEC_EXCLUDE);
2060
2061 for (i = 0; i < pathspec->nr; i++) {
2062 const struct pathspec_item *item = &pathspec->items[i];
2063 int len = item->nowildcard_len;
2064
2065 if (len == pathlen &&
2066 !ps_strncmp(item, item->match, path, pathlen))
2067 return 1;
2068 if (len > pathlen &&
2069 item->match[pathlen] == '/' &&
2070 !ps_strncmp(item, item->match, path, pathlen))
2071 return 1;
e96980ef
JK
2072 }
2073 return 0;
2074}
2075
98f2a687
BW
2076static int get_index_dtype(struct index_state *istate,
2077 const char *path, int len)
443e061a
LT
2078{
2079 int pos;
9c5e6c80 2080 const struct cache_entry *ce;
443e061a 2081
98f2a687 2082 ce = index_file_exists(istate, path, len, 0);
443e061a
LT
2083 if (ce) {
2084 if (!ce_uptodate(ce))
2085 return DT_UNKNOWN;
2086 if (S_ISGITLINK(ce->ce_mode))
2087 return DT_DIR;
2088 /*
2089 * Nobody actually cares about the
2090 * difference between DT_LNK and DT_REG
2091 */
2092 return DT_REG;
2093 }
2094
2095 /* Try to look it up as a directory */
98f2a687 2096 pos = index_name_pos(istate, path, len);
443e061a
LT
2097 if (pos >= 0)
2098 return DT_UNKNOWN;
2099 pos = -pos-1;
98f2a687
BW
2100 while (pos < istate->cache_nr) {
2101 ce = istate->cache[pos++];
443e061a
LT
2102 if (strncmp(ce->name, path, len))
2103 break;
2104 if (ce->name[len] > '/')
2105 break;
2106 if (ce->name[len] < '/')
2107 continue;
2108 if (!ce_uptodate(ce))
2109 break; /* continue? */
2110 return DT_DIR;
2111 }
2112 return DT_UNKNOWN;
2113}
2114
ad6f2157
JK
2115static int resolve_dtype(int dtype, struct index_state *istate,
2116 const char *path, int len)
07134421 2117{
07134421
LT
2118 struct stat st;
2119
2120 if (dtype != DT_UNKNOWN)
2121 return dtype;
98f2a687 2122 dtype = get_index_dtype(istate, path, len);
443e061a
LT
2123 if (dtype != DT_UNKNOWN)
2124 return dtype;
2125 if (lstat(path, &st))
07134421
LT
2126 return dtype;
2127 if (S_ISREG(st.st_mode))
2128 return DT_REG;
2129 if (S_ISDIR(st.st_mode))
2130 return DT_DIR;
2131 if (S_ISLNK(st.st_mode))
2132 return DT_LNK;
2133 return dtype;
2134}
2135
91a2288b 2136static enum path_treatment treat_path_fast(struct dir_struct *dir,
91a2288b 2137 struct cached_dir *cdir,
0ef8e169 2138 struct index_state *istate,
91a2288b
NTND
2139 struct strbuf *path,
2140 int baselen,
e1b8c7bd 2141 const struct pathspec *pathspec)
91a2288b 2142{
8d92fb29
EN
2143 /*
2144 * WARNING: From this function, you can return path_recurse or you
2145 * can call read_directory_recursive() (or neither), but
2146 * you CAN'T DO BOTH.
2147 */
91a2288b
NTND
2148 strbuf_setlen(path, baselen);
2149 if (!cdir->ucd) {
2150 strbuf_addstr(path, cdir->file);
2151 return path_untracked;
2152 }
2153 strbuf_addstr(path, cdir->ucd->name);
2154 /* treat_one_path() does this before it calls treat_directory() */
00b6c178 2155 strbuf_complete(path, '/');
91a2288b
NTND
2156 if (cdir->ucd->check_only)
2157 /*
2158 * check_only is set as a result of treat_directory() getting
2159 * to its bottom. Verify again the same set of directories
2160 * with check_only set.
2161 */
0ef8e169 2162 return read_directory_recursive(dir, istate, path->buf, path->len,
5aaa7fd3 2163 cdir->ucd, 1, 0, pathspec);
91a2288b
NTND
2164 /*
2165 * We get path_recurse in the first run when
2166 * directory_exists_in_index() returns index_nonexistent. We
2167 * are sure that new changes in the index does not impact the
2168 * outcome. Return now.
2169 */
2170 return path_recurse;
2171}
2172
16e2cfa9 2173static enum path_treatment treat_path(struct dir_struct *dir,
0dcb8d7f 2174 struct untracked_cache_dir *untracked,
cf7c6148 2175 struct cached_dir *cdir,
0ef8e169 2176 struct index_state *istate,
49dc2cc2 2177 struct strbuf *path,
16e2cfa9 2178 int baselen,
e1b8c7bd 2179 const struct pathspec *pathspec)
16e2cfa9 2180{
2df179d3 2181 int has_path_in_index, dtype, excluded;
2eac2a4c 2182
ad6f2157 2183 if (!cdir->d_name)
842385b8 2184 return treat_path_fast(dir, cdir, istate, path,
e1b8c7bd 2185 baselen, pathspec);
ad6f2157 2186 if (is_dot_or_dotdot(cdir->d_name) || !fspathcmp(cdir->d_name, ".git"))
defd7c7b 2187 return path_none;
49dc2cc2 2188 strbuf_setlen(path, baselen);
ad6f2157 2189 strbuf_addstr(path, cdir->d_name);
e1b8c7bd 2190 if (simplify_away(path->buf, path->len, pathspec))
defd7c7b 2191 return path_none;
16e2cfa9 2192
cd129eed 2193 dtype = resolve_dtype(cdir->d_type, istate, path->buf, path->len);
8aaf8d77
KB
2194
2195 /* Always exclude indexed files */
cd129eed
EN
2196 has_path_in_index = !!index_file_exists(istate, path->buf, path->len,
2197 ignore_case);
2eac2a4c 2198 if (dtype != DT_DIR && has_path_in_index)
defd7c7b 2199 return path_none;
8aaf8d77 2200
2eac2a4c
JH
2201 /*
2202 * When we are looking at a directory P in the working tree,
2203 * there are three cases:
2204 *
2205 * (1) P exists in the index. Everything inside the directory P in
2206 * the working tree needs to go when P is checked out from the
2207 * index.
2208 *
2209 * (2) P does not exist in the index, but there is P/Q in the index.
2210 * We know P will stay a directory when we check out the contents
2211 * of the index, but we do not know yet if there is a directory
2212 * P/Q in the working tree to be killed, so we need to recurse.
2213 *
2214 * (3) P does not exist in the index, and there is no P/Q in the index
2215 * to require P to be a directory, either. Only in this case, we
2216 * know that everything inside P will not be killed without
2217 * recursing.
2218 */
2219 if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
2220 (dtype == DT_DIR) &&
de372b1b 2221 !has_path_in_index &&
0ef8e169 2222 (directory_exists_in_index(istate, path->buf, path->len) == index_nonexistent))
de372b1b 2223 return path_none;
8aaf8d77 2224
2df179d3 2225 excluded = is_excluded(dir, istate, path->buf, &dtype);
53cc5356
JH
2226
2227 /*
2228 * Excluded? If we don't explicitly want to show
2229 * ignored files, ignore it
2230 */
2df179d3 2231 if (excluded && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
defd7c7b 2232 return path_excluded;
53cc5356 2233
53cc5356
JH
2234 switch (dtype) {
2235 default:
defd7c7b 2236 return path_none;
53cc5356 2237 case DT_DIR:
07966ed1 2238 /*
8d92fb29
EN
2239 * WARNING: Do not ignore/amend the return value from
2240 * treat_directory(), and especially do not change it to return
2241 * path_recurse as that can cause exponential slowdown.
2242 * Instead, modify treat_directory() to return the right value.
07966ed1 2243 */
8d92fb29
EN
2244 strbuf_addch(path, '/');
2245 return treat_directory(dir, istate, untracked,
2246 path->buf, path->len,
2247 baselen, excluded, pathspec);
53cc5356
JH
2248 case DT_REG:
2249 case DT_LNK:
95c11ecc 2250 if (pathspec &&
f1f061e1
EN
2251 !match_pathspec(istate, pathspec, path->buf, path->len,
2252 0 /* prefix */, NULL /* seen */,
2253 0 /* is_dir */))
95c11ecc 2254 return path_none;
cada7308
2255 if (excluded)
2256 return path_excluded;
95c11ecc 2257 return path_untracked;
53cc5356 2258 }
0dcb8d7f
NTND
2259}
2260
2261static void add_untracked(struct untracked_cache_dir *dir, const char *name)
2262{
2263 if (!dir)
2264 return;
2265 ALLOC_GROW(dir->untracked, dir->untracked_nr + 1,
2266 dir->untracked_alloc);
2267 dir->untracked[dir->untracked_nr++] = xstrdup(name);
16e2cfa9
JH
2268}
2269
91a2288b
NTND
2270static int valid_cached_dir(struct dir_struct *dir,
2271 struct untracked_cache_dir *untracked,
207a06ce 2272 struct index_state *istate,
91a2288b
NTND
2273 struct strbuf *path,
2274 int check_only)
2275{
2276 struct stat st;
2277
2278 if (!untracked)
2279 return 0;
2280
883e248b
BP
2281 /*
2282 * With fsmonitor, we can trust the untracked cache's valid field.
2283 */
2284 refresh_fsmonitor(istate);
2285 if (!(dir->untracked->use_fsmonitor && untracked->valid)) {
2523c4be 2286 if (lstat(path->len ? path->buf : ".", &st)) {
883e248b
BP
2287 memset(&untracked->stat_data, 0, sizeof(untracked->stat_data));
2288 return 0;
2289 }
2290 if (!untracked->valid ||
2291 match_stat_data_racy(istate, &untracked->stat_data, &st)) {
883e248b
BP
2292 fill_stat_data(&untracked->stat_data, &st);
2293 return 0;
2294 }
91a2288b
NTND
2295 }
2296
b6403131 2297 if (untracked->check_only != !!check_only)
91a2288b 2298 return 0;
91a2288b
NTND
2299
2300 /*
2301 * prep_exclude will be called eventually on this directory,
65edd96a 2302 * but it's called much later in last_matching_pattern(). We
91a2288b
NTND
2303 * need it now to determine the validity of the cache for this
2304 * path. The next calls will be nearly no-op, the way
2305 * prep_exclude() is designed.
2306 */
2307 if (path->len && path->buf[path->len - 1] != '/') {
2308 strbuf_addch(path, '/');
207a06ce 2309 prep_exclude(dir, istate, path->buf, path->len);
91a2288b
NTND
2310 strbuf_setlen(path, path->len - 1);
2311 } else
207a06ce 2312 prep_exclude(dir, istate, path->buf, path->len);
91a2288b
NTND
2313
2314 /* hopefully prep_exclude() haven't invalidated this entry... */
2315 return untracked->valid;
2316}
2317
cf7c6148
NTND
2318static int open_cached_dir(struct cached_dir *cdir,
2319 struct dir_struct *dir,
2320 struct untracked_cache_dir *untracked,
207a06ce 2321 struct index_state *istate,
cf7c6148
NTND
2322 struct strbuf *path,
2323 int check_only)
2324{
b6731550
NTND
2325 const char *c_path;
2326
cf7c6148
NTND
2327 memset(cdir, 0, sizeof(*cdir));
2328 cdir->untracked = untracked;
207a06ce 2329 if (valid_cached_dir(dir, untracked, istate, path, check_only))
91a2288b 2330 return 0;
b6731550
NTND
2331 c_path = path->len ? path->buf : ".";
2332 cdir->fdir = opendir(c_path);
2333 if (!cdir->fdir)
2334 warning_errno(_("could not open directory '%s'"), c_path);
b6403131
NTND
2335 if (dir->untracked) {
2336 invalidate_directory(dir->untracked, untracked);
91a2288b 2337 dir->untracked->dir_opened++;
b6403131 2338 }
cf7c6148
NTND
2339 if (!cdir->fdir)
2340 return -1;
2341 return 0;
2342}
2343
2344static int read_cached_dir(struct cached_dir *cdir)
2345{
ad6f2157
JK
2346 struct dirent *de;
2347
cf7c6148 2348 if (cdir->fdir) {
b548f0f1 2349 de = readdir_skip_dot_and_dotdot(cdir->fdir);
ad6f2157
JK
2350 if (!de) {
2351 cdir->d_name = NULL;
2352 cdir->d_type = DT_UNKNOWN;
cf7c6148 2353 return -1;
ad6f2157
JK
2354 }
2355 cdir->d_name = de->d_name;
2356 cdir->d_type = DTYPE(de);
cf7c6148
NTND
2357 return 0;
2358 }
91a2288b
NTND
2359 while (cdir->nr_dirs < cdir->untracked->dirs_nr) {
2360 struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];
26cb0182
NTND
2361 if (!d->recurse) {
2362 cdir->nr_dirs++;
2363 continue;
2364 }
91a2288b
NTND
2365 cdir->ucd = d;
2366 cdir->nr_dirs++;
2367 return 0;
2368 }
2369 cdir->ucd = NULL;
2370 if (cdir->nr_files < cdir->untracked->untracked_nr) {
2371 struct untracked_cache_dir *d = cdir->untracked;
2372 cdir->file = d->untracked[cdir->nr_files++];
2373 return 0;
2374 }
cf7c6148
NTND
2375 return -1;
2376}
2377
2378static void close_cached_dir(struct cached_dir *cdir)
2379{
2380 if (cdir->fdir)
2381 closedir(cdir->fdir);
91a2288b
NTND
2382 /*
2383 * We have gone through this directory and found no untracked
2384 * entries. Mark it valid.
2385 */
26cb0182 2386 if (cdir->untracked) {
91a2288b 2387 cdir->untracked->valid = 1;
26cb0182
NTND
2388 cdir->untracked->recurse = 1;
2389 }
16e2cfa9
JH
2390}
2391
c5c4eddd
EN
2392static void add_path_to_appropriate_result_list(struct dir_struct *dir,
2393 struct untracked_cache_dir *untracked,
2394 struct cached_dir *cdir,
2395 struct index_state *istate,
2396 struct strbuf *path,
2397 int baselen,
2398 const struct pathspec *pathspec,
2399 enum path_treatment state)
2400{
2401 /* add the path to the appropriate result list */
2402 switch (state) {
2403 case path_excluded:
2404 if (dir->flags & DIR_SHOW_IGNORED)
2405 dir_add_name(dir, istate, path->buf, path->len);
2406 else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
2407 ((dir->flags & DIR_COLLECT_IGNORED) &&
2408 exclude_matches_pathspec(path->buf, path->len,
2409 pathspec)))
2410 dir_add_ignored(dir, istate, path->buf, path->len);
2411 break;
2412
2413 case path_untracked:
2414 if (dir->flags & DIR_SHOW_IGNORED)
2415 break;
2416 dir_add_name(dir, istate, path->buf, path->len);
2417 if (cdir->fdir)
2418 add_untracked(untracked, path->buf + baselen);
2419 break;
2420
2421 default:
2422 break;
2423 }
2424}
2425
453ec4bd
LT
2426/*
2427 * Read a directory tree. We currently ignore anything but
2428 * directories, regular files and symlinks. That's because git
2429 * doesn't handle them at all yet. Maybe that will change some
2430 * day.
2431 *
2432 * Also, we ignore the name ".git" (even if it is not a directory).
2433 * That likely will not change.
defd7c7b 2434 *
5aaa7fd3
JM
2435 * If 'stop_at_first_file' is specified, 'path_excluded' is returned
2436 * to signal that a file was found. This is the least significant value that
2437 * indicates that a file was encountered that does not depend on the order of
446f46d8 2438 * whether an untracked or excluded path was encountered first.
5aaa7fd3 2439 *
defd7c7b 2440 * Returns the most significant path_treatment value encountered in the scan.
5aaa7fd3
JM
2441 * If 'stop_at_first_file' is specified, `path_excluded` is the most
2442 * significant path_treatment value that will be returned.
453ec4bd 2443 */
5aaa7fd3 2444
defd7c7b 2445static enum path_treatment read_directory_recursive(struct dir_struct *dir,
0ef8e169
BW
2446 struct index_state *istate, const char *base, int baselen,
2447 struct untracked_cache_dir *untracked, int check_only,
5aaa7fd3 2448 int stop_at_first_file, const struct pathspec *pathspec)
453ec4bd 2449{
777b4203 2450 /*
8d92fb29
EN
2451 * WARNING: Do NOT recurse unless path_recurse is returned from
2452 * treat_path(). Recursing on any other return value
2453 * can result in exponential slowdown.
777b4203 2454 */
cf7c6148 2455 struct cached_dir cdir;
defd7c7b 2456 enum path_treatment state, subdir_state, dir_state = path_none;
bef36921 2457 struct strbuf path = STRBUF_INIT;
453ec4bd 2458
bef36921 2459 strbuf_add(&path, base, baselen);
02cb6753 2460
0ef8e169 2461 if (open_cached_dir(&cdir, dir, untracked, istate, &path, check_only))
1528d247 2462 goto out;
7fe1ffda 2463 dir->visited_directories++;
1528d247 2464
0dcb8d7f
NTND
2465 if (untracked)
2466 untracked->check_only = !!check_only;
2467
cf7c6148 2468 while (!read_cached_dir(&cdir)) {
defd7c7b 2469 /* check how the file or directory should be treated */
0ef8e169 2470 state = treat_path(dir, untracked, &cdir, istate, &path,
e1b8c7bd 2471 baselen, pathspec);
7fe1ffda 2472 dir->visited_paths++;
0dcb8d7f 2473
defd7c7b
KB
2474 if (state > dir_state)
2475 dir_state = state;
2476
2477 /* recurse into subdir if instructed by treat_path */
8d92fb29 2478 if (state == path_recurse) {
0dcb8d7f
NTND
2479 struct untracked_cache_dir *ud;
2480 ud = lookup_untracked(dir->untracked, untracked,
2481 path.buf + baselen,
2482 path.len - baselen);
2483 subdir_state =
0ef8e169 2484 read_directory_recursive(dir, istate, path.buf,
e1b8c7bd 2485 path.len, ud,
5aaa7fd3 2486 check_only, stop_at_first_file, pathspec);
defd7c7b
KB
2487 if (subdir_state > dir_state)
2488 dir_state = subdir_state;
404ebced 2489
69f272b9
EN
2490 if (pathspec &&
2491 !match_pathspec(istate, pathspec, path.buf, path.len,
404ebced
EN
2492 0 /* prefix */, NULL,
2493 0 /* do NOT special case dirs */))
2494 state = path_none;
defd7c7b
KB
2495 }
2496
2497 if (check_only) {
5aaa7fd3
JM
2498 if (stop_at_first_file) {
2499 /*
2500 * If stopping at first file, then
2501 * signal that a file was found by
2502 * returning `path_excluded`. This is
2503 * to return a consistent value
2504 * regardless of whether an ignored or
2505 * excluded file happened to be
2506 * encountered 1st.
2507 *
2508 * In current usage, the
2509 * `stop_at_first_file` is passed when
2510 * an ancestor directory has matched
2511 * an exclude pattern, so any found
2512 * files will be excluded.
2513 */
2514 if (dir_state >= path_excluded) {
2515 dir_state = path_excluded;
2516 break;
2517 }
2518 }
2519
defd7c7b 2520 /* abort early if maximum state has been reached */
0dcb8d7f 2521 if (dir_state == path_untracked) {
91a2288b 2522 if (cdir.fdir)
0dcb8d7f 2523 add_untracked(untracked, path.buf + baselen);
defd7c7b 2524 break;
0dcb8d7f 2525 }
0126d141 2526 /* skip the add_path_to_appropriate_result_list() */
02cb6753 2527 continue;
453ec4bd 2528 }
defd7c7b 2529
c5c4eddd
EN
2530 add_path_to_appropriate_result_list(dir, untracked, &cdir,
2531 istate, &path, baselen,
2532 pathspec, state);
453ec4bd 2533 }
cf7c6148 2534 close_cached_dir(&cdir);
1528d247 2535 out:
bef36921 2536 strbuf_release(&path);
453ec4bd 2537
defd7c7b 2538 return dir_state;
453ec4bd
LT
2539}
2540
bbf504a9 2541int cmp_dir_entry(const void *p1, const void *p2)
453ec4bd
LT
2542{
2543 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
2544 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
2545
ccdd4a0f 2546 return name_compare(e1->name, e1->len, e2->name, e2->len);
453ec4bd
LT
2547}
2548
fb898888 2549/* check if *out lexically strictly contains *in */
bbf504a9 2550int check_dir_entry_contains(const struct dir_entry *out, const struct dir_entry *in)
fb898888
SL
2551{
2552 return (out->len < in->len) &&
2553 (out->name[out->len - 1] == '/') &&
2554 !memcmp(out->name, in->name, out->len);
2555}
2556
48ffef96 2557static int treat_leading_path(struct dir_struct *dir,
0ef8e169 2558 struct index_state *istate,
48ffef96 2559 const char *path, int len,
e1b8c7bd 2560 const struct pathspec *pathspec)
48ffef96 2561{
49dc2cc2 2562 struct strbuf sb = STRBUF_INIT;
ad6f2157 2563 struct strbuf subdir = STRBUF_INIT;
b9670c1f 2564 int prevlen, baselen;
48ffef96 2565 const char *cp;
b9670c1f 2566 struct cached_dir cdir;
b9670c1f
EN
2567 enum path_treatment state = path_none;
2568
2569 /*
2570 * For each directory component of path, we are going to check whether
2571 * that path is relevant given the pathspec. For example, if path is
2572 * foo/bar/baz/
2573 * then we will ask treat_path() whether we should go into foo, then
2574 * whether we should go into bar, then whether baz is relevant.
2575 * Checking each is important because e.g. if path is
2576 * .git/info/
2577 * then we need to check .git to know we shouldn't traverse it.
2578 * If the return from treat_path() is:
2579 * * path_none, for any path, we return false.
2580 * * path_recurse, for all path components, we return true
2581 * * <anything else> for some intermediate component, we make sure
2582 * to add that path to the relevant list but return false
2583 * signifying that we shouldn't recurse into it.
2584 */
48ffef96
JH
2585
2586 while (len && path[len - 1] == '/')
2587 len--;
2588 if (!len)
2589 return 1;
b9670c1f 2590
b9670c1f 2591 memset(&cdir, 0, sizeof(cdir));
ad6f2157 2592 cdir.d_type = DT_DIR;
48ffef96 2593 baselen = 0;
b9670c1f 2594 prevlen = 0;
48ffef96 2595 while (1) {
b9670c1f
EN
2596 prevlen = baselen + !!baselen;
2597 cp = path + prevlen;
48ffef96
JH
2598 cp = memchr(cp, '/', path + len - cp);
2599 if (!cp)
2600 baselen = len;
2601 else
2602 baselen = cp - path;
b9670c1f 2603 strbuf_reset(&sb);
49dc2cc2
RS
2604 strbuf_add(&sb, path, baselen);
2605 if (!is_directory(sb.buf))
2606 break;
b9670c1f
EN
2607 strbuf_reset(&sb);
2608 strbuf_add(&sb, path, prevlen);
ad6f2157
JK
2609 strbuf_reset(&subdir);
2610 strbuf_add(&subdir, path+prevlen, baselen-prevlen);
2611 cdir.d_name = subdir.buf;
8d92fb29 2612 state = treat_path(dir, NULL, &cdir, istate, &sb, prevlen, pathspec);
777b4203 2613
b9670c1f 2614 if (state != path_recurse)
49dc2cc2 2615 break; /* do not recurse into it */
b9670c1f 2616 if (len <= baselen)
49dc2cc2 2617 break; /* finished checking */
48ffef96 2618 }
b9670c1f
EN
2619 add_path_to_appropriate_result_list(dir, NULL, &cdir, istate,
2620 &sb, baselen, pathspec,
2621 state);
2622
ad6f2157 2623 strbuf_release(&subdir);
49dc2cc2 2624 strbuf_release(&sb);
b9670c1f 2625 return state == path_recurse;
48ffef96
JH
2626}
2627
1e8fef60
NTND
2628static const char *get_ident_string(void)
2629{
2630 static struct strbuf sb = STRBUF_INIT;
2631 struct utsname uts;
2632
2633 if (sb.len)
2634 return sb.buf;
100e4337 2635 if (uname(&uts) < 0)
1e8fef60 2636 die_errno(_("failed to get kernel name and information"));
0e0f7618
CC
2637 strbuf_addf(&sb, "Location %s, system %s", get_git_work_tree(),
2638 uts.sysname);
1e8fef60
NTND
2639 return sb.buf;
2640}
2641
2642static int ident_in_untracked(const struct untracked_cache *uc)
2643{
0e0f7618
CC
2644 /*
2645 * Previous git versions may have saved many NUL separated
2646 * strings in the "ident" field, but it is insane to manage
2647 * many locations, so just take care of the first one.
2648 */
1e8fef60 2649
0e0f7618 2650 return !strcmp(uc->ident.buf, get_ident_string());
1e8fef60
NTND
2651}
2652
0e0f7618 2653static void set_untracked_ident(struct untracked_cache *uc)
1e8fef60 2654{
0e0f7618 2655 strbuf_reset(&uc->ident);
1e8fef60 2656 strbuf_addstr(&uc->ident, get_ident_string());
0e0f7618
CC
2657
2658 /*
2659 * This strbuf used to contain a list of NUL separated
2660 * strings, so save NUL too for backward compatibility.
2661 */
1e8fef60
NTND
2662 strbuf_addch(&uc->ident, 0);
2663}
2664
4a4ca479
CC
2665static void new_untracked_cache(struct index_state *istate)
2666{
2667 struct untracked_cache *uc = xcalloc(1, sizeof(*uc));
2668 strbuf_init(&uc->ident, 100);
2669 uc->exclude_per_dir = ".gitignore";
2670 /* should be the same flags used by git-status */
2671 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;
0e0f7618 2672 set_untracked_ident(uc);
4a4ca479 2673 istate->untracked = uc;
0e0f7618 2674 istate->cache_changed |= UNTRACKED_CHANGED;
4a4ca479
CC
2675}
2676
2677void add_untracked_cache(struct index_state *istate)
2678{
2679 if (!istate->untracked) {
2680 new_untracked_cache(istate);
0e0f7618
CC
2681 } else {
2682 if (!ident_in_untracked(istate->untracked)) {
2683 free_untracked_cache(istate->untracked);
2684 new_untracked_cache(istate);
2685 }
2686 }
4a4ca479
CC
2687}
2688
07b29bfd
CC
2689void remove_untracked_cache(struct index_state *istate)
2690{
2691 if (istate->untracked) {
2692 free_untracked_cache(istate->untracked);
2693 istate->untracked = NULL;
2694 istate->cache_changed |= UNTRACKED_CHANGED;
2695 }
2696}
2697
ccad261f
NTND
2698static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,
2699 int base_len,
2700 const struct pathspec *pathspec)
2701{
2702 struct untracked_cache_dir *root;
026336cb 2703 static int untracked_cache_disabled = -1;
ccad261f 2704
026336cb
JH
2705 if (!dir->untracked)
2706 return NULL;
2707 if (untracked_cache_disabled < 0)
2708 untracked_cache_disabled = git_env_bool("GIT_DISABLE_UNTRACKED_CACHE", 0);
2709 if (untracked_cache_disabled)
ccad261f
NTND
2710 return NULL;
2711
2712 /*
2713 * We only support $GIT_DIR/info/exclude and core.excludesfile
2714 * as the global ignore rule files. Any other additions
2715 * (e.g. from command line) invalidate the cache. This
2716 * condition also catches running setup_standard_excludes()
2717 * before setting dir->untracked!
2718 */
2719 if (dir->unmanaged_exclude_files)
2720 return NULL;
2721
2722 /*
2723 * Optimize for the main use case only: whole-tree git
2724 * status. More work involved in treat_leading_path() if we
2725 * use cache on just a subset of the worktree. pathspec
2726 * support could make the matter even worse.
2727 */
2728 if (base_len || (pathspec && pathspec->nr))
2729 return NULL;
2730
2731 /* Different set of flags may produce different results */
2732 if (dir->flags != dir->untracked->dir_flags ||
2733 /*
2734 * See treat_directory(), case index_nonexistent. Without
2735 * this flag, we may need to also cache .git file content
2736 * for the resolve_gitlink_ref() call, which we don't.
2737 */
2738 !(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||
2739 /* We don't support collecting ignore files */
2740 (dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |
2741 DIR_COLLECT_IGNORED)))
2742 return NULL;
2743
2744 /*
2745 * If we use .gitignore in the cache and now you change it to
2746 * .gitexclude, everything will go wrong.
2747 */
2748 if (dir->exclude_per_dir != dir->untracked->exclude_per_dir &&
2749 strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))
2750 return NULL;
2751
2752 /*
2753 * EXC_CMDL is not considered in the cache. If people set it,
2754 * skip the cache.
2755 */
2756 if (dir->exclude_list_group[EXC_CMDL].nr)
2757 return NULL;
2758
1e8fef60 2759 if (!ident_in_untracked(dir->untracked)) {
1a07e59c 2760 warning(_("untracked cache is disabled on this system or location"));
1e8fef60
NTND
2761 return NULL;
2762 }
2763
6347d649
JH
2764 if (!dir->untracked->root)
2765 FLEX_ALLOC_STR(dir->untracked->root, name, "");
ccad261f
NTND
2766
2767 /* Validate $GIT_DIR/info/exclude and core.excludesfile */
2768 root = dir->untracked->root;
9001dc2a 2769 if (!oideq(&dir->ss_info_exclude.oid,
4b33e602 2770 &dir->untracked->ss_info_exclude.oid)) {
ccad261f
NTND
2771 invalidate_gitignore(dir->untracked, root);
2772 dir->untracked->ss_info_exclude = dir->ss_info_exclude;
2773 }
9001dc2a 2774 if (!oideq(&dir->ss_excludes_file.oid,
4b33e602 2775 &dir->untracked->ss_excludes_file.oid)) {
ccad261f
NTND
2776 invalidate_gitignore(dir->untracked, root);
2777 dir->untracked->ss_excludes_file = dir->ss_excludes_file;
2778 }
26cb0182
NTND
2779
2780 /* Make sure this directory is not dropped out at saving phase */
2781 root->recurse = 1;
ccad261f
NTND
2782 return root;
2783}
2784
7f9dd879
EN
2785static void emit_traversal_statistics(struct dir_struct *dir,
2786 struct repository *repo,
2787 const char *path,
2788 int path_len)
2789{
2790 if (!trace2_is_enabled())
2791 return;
2792
2793 if (!path_len) {
2794 trace2_data_string("read_directory", repo, "path", "");
2795 } else {
2796 struct strbuf tmp = STRBUF_INIT;
2797 strbuf_add(&tmp, path, path_len);
2798 trace2_data_string("read_directory", repo, "path", tmp.buf);
2799 strbuf_release(&tmp);
2800 }
2801
7fe1ffda
EN
2802 trace2_data_intmax("read_directory", repo,
2803 "directories-visited", dir->visited_directories);
2804 trace2_data_intmax("read_directory", repo,
2805 "paths-visited", dir->visited_paths);
2806
7f9dd879
EN
2807 if (!dir->untracked)
2808 return;
2809 trace2_data_intmax("read_directory", repo,
2810 "node-creation", dir->untracked->dir_created);
2811 trace2_data_intmax("read_directory", repo,
2812 "gitignore-invalidation",
2813 dir->untracked->gitignore_invalidated);
2814 trace2_data_intmax("read_directory", repo,
2815 "directory-invalidation",
2816 dir->untracked->dir_invalidated);
2817 trace2_data_intmax("read_directory", repo,
2818 "opendir", dir->untracked->dir_opened);
2819}
2820
2c1eb104
BW
2821int read_directory(struct dir_struct *dir, struct index_state *istate,
2822 const char *path, int len, const struct pathspec *pathspec)
9fc42d60 2823{
ccad261f 2824 struct untracked_cache_dir *untracked;
b4189aa8 2825
7f9dd879 2826 trace2_region_enter("dir", "read_directory", istate->repo);
7fe1ffda
EN
2827 dir->visited_paths = 0;
2828 dir->visited_directories = 0;
c46c406a
NTND
2829
2830 if (has_symlink_leading_path(path, len)) {
7f9dd879 2831 trace2_region_leave("dir", "read_directory", istate->repo);
725b0605 2832 return dir->nr;
c46c406a 2833 }
725b0605 2834
ccad261f
NTND
2835 untracked = validate_untracked_cache(dir, len, pathspec);
2836 if (!untracked)
2837 /*
2838 * make sure untracked cache code path is disabled,
2839 * e.g. prep_exclude()
2840 */
2841 dir->untracked = NULL;
2c1eb104 2842 if (!len || treat_leading_path(dir, istate, path, len, pathspec))
5aaa7fd3 2843 read_directory_recursive(dir, istate, path, len, untracked, 0, 0, pathspec);
bbf504a9
SL
2844 QSORT(dir->entries, dir->nr, cmp_dir_entry);
2845 QSORT(dir->ignored, dir->ignored_nr, cmp_dir_entry);
fb898888 2846
7f9dd879
EN
2847 emit_traversal_statistics(dir, istate->repo, path, len);
2848
2849 trace2_region_leave("dir", "read_directory", istate->repo);
c9ccb5d3 2850 if (dir->untracked) {
026336cb 2851 static int force_untracked_cache = -1;
026336cb
JH
2852
2853 if (force_untracked_cache < 0)
2854 force_untracked_cache =
2855 git_env_bool("GIT_FORCE_UNTRACKED_CACHE", 0);
026336cb 2856 if (force_untracked_cache &&
fc9ecbeb 2857 dir->untracked == istate->untracked &&
1bbb3dba
NTND
2858 (dir->untracked->dir_opened ||
2859 dir->untracked->gitignore_invalidated ||
2860 dir->untracked->dir_invalidated))
2c1eb104
BW
2861 istate->cache_changed |= UNTRACKED_CHANGED;
2862 if (dir->untracked != istate->untracked) {
6a83d902 2863 FREE_AND_NULL(dir->untracked);
1bbb3dba 2864 }
c9ccb5d3 2865 }
7f9dd879 2866
453ec4bd
LT
2867 return dir->nr;
2868}
c91f0d92 2869
686a4a06 2870int file_exists(const char *f)
c91f0d92 2871{
686a4a06 2872 struct stat sb;
a50f9fc5 2873 return lstat(f, &sb) == 0;
c91f0d92 2874}
e6636747 2875
0488481e
NTND
2876int repo_file_exists(struct repository *repo, const char *path)
2877{
2878 if (repo != the_repository)
2879 BUG("do not know how to check file existence in arbitrary repo");
2880
2881 return file_exists(path);
2882}
2883
63ec5e1f
JS
2884static int cmp_icase(char a, char b)
2885{
2886 if (a == b)
2887 return 0;
2888 if (ignore_case)
2889 return toupper(a) - toupper(b);
2890 return a - b;
2891}
2892
e6636747 2893/*
9b125da4
NTND
2894 * Given two normalized paths (a trailing slash is ok), if subdir is
2895 * outside dir, return -1. Otherwise return the offset in subdir that
2896 * can be used as relative path to dir.
e6636747 2897 */
9b125da4 2898int dir_inside_of(const char *subdir, const char *dir)
e6636747 2899{
9b125da4 2900 int offset = 0;
e6636747 2901
9b125da4 2902 assert(dir && subdir && *dir && *subdir);
e6636747 2903
63ec5e1f 2904 while (*dir && *subdir && !cmp_icase(*dir, *subdir)) {
e6636747 2905 dir++;
9b125da4
NTND
2906 subdir++;
2907 offset++;
490544b1 2908 }
9b125da4
NTND
2909
2910 /* hel[p]/me vs hel[l]/yeah */
2911 if (*dir && *subdir)
2912 return -1;
2913
2914 if (!*subdir)
2915 return !*dir ? offset : -1; /* same dir */
2916
2917 /* foo/[b]ar vs foo/[] */
2918 if (is_dir_sep(dir[-1]))
2919 return is_dir_sep(subdir[-1]) ? offset : -1;
2920
2921 /* foo[/]bar vs foo[] */
2922 return is_dir_sep(*subdir) ? offset + 1 : -1;
e6636747
JS
2923}
2924
2925int is_inside_dir(const char *dir)
2926{
56b9f6e7
RS
2927 char *cwd;
2928 int rc;
2929
b892913d
NTND
2930 if (!dir)
2931 return 0;
56b9f6e7
RS
2932
2933 cwd = xgetcwd();
2934 rc = (dir_inside_of(cwd, dir) >= 0);
2935 free(cwd);
2936 return rc;
e6636747 2937}
7155b727 2938
55892d23
AP
2939int is_empty_dir(const char *path)
2940{
2941 DIR *dir = opendir(path);
2942 struct dirent *e;
2943 int ret = 1;
2944
2945 if (!dir)
2946 return 0;
2947
b548f0f1
EN
2948 e = readdir_skip_dot_and_dotdot(dir);
2949 if (e)
2950 ret = 0;
55892d23
AP
2951
2952 closedir(dir);
2953 return ret;
2954}
2955
ae2f203e 2956static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
7155b727 2957{
a0f4afbe 2958 DIR *dir;
7155b727 2959 struct dirent *e;
ae2f203e 2960 int ret = 0, original_len = path->len, len, kept_down = 0;
a0f4afbe 2961 int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
c844a803 2962 int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
1053fe82 2963 struct object_id submodule_head;
7155b727 2964
a0f4afbe 2965 if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
a98e6101 2966 !resolve_gitlink_ref(path->buf, "HEAD", &submodule_head)) {
a0f4afbe 2967 /* Do not descend and nuke a nested git work tree. */
ae2f203e
JH
2968 if (kept_up)
2969 *kept_up = 1;
a0f4afbe 2970 return 0;
ae2f203e 2971 }
a0f4afbe 2972
ae2f203e 2973 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
a0f4afbe 2974 dir = opendir(path->buf);
c844a803 2975 if (!dir) {
863808cd
MH
2976 if (errno == ENOENT)
2977 return keep_toplevel ? -1 : 0;
2978 else if (errno == EACCES && !keep_toplevel)
ecb2c282
MH
2979 /*
2980 * An empty dir could be removable even if it
2981 * is unreadable:
2982 */
c844a803
JH
2983 return rmdir(path->buf);
2984 else
2985 return -1;
2986 }
00b6c178 2987 strbuf_complete(path, '/');
7155b727
JS
2988
2989 len = path->len;
b548f0f1 2990 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
7155b727 2991 struct stat st;
7155b727
JS
2992
2993 strbuf_setlen(path, len);
2994 strbuf_addstr(path, e->d_name);
863808cd
MH
2995 if (lstat(path->buf, &st)) {
2996 if (errno == ENOENT)
2997 /*
2998 * file disappeared, which is what we
2999 * wanted anyway
3000 */
3001 continue;
15beaaa3 3002 /* fall through */
863808cd 3003 } else if (S_ISDIR(st.st_mode)) {
ae2f203e 3004 if (!remove_dir_recurse(path, flag, &kept_down))
7155b727 3005 continue; /* happy */
863808cd
MH
3006 } else if (!only_empty &&
3007 (!unlink(path->buf) || errno == ENOENT)) {
7155b727 3008 continue; /* happy, too */
863808cd 3009 }
7155b727
JS
3010
3011 /* path too long, stat fails, or non-directory still exists */
3012 ret = -1;
3013 break;
3014 }
3015 closedir(dir);
3016
3017 strbuf_setlen(path, original_len);
ae2f203e 3018 if (!ret && !keep_toplevel && !kept_down)
863808cd 3019 ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1;
ae2f203e
JH
3020 else if (kept_up)
3021 /*
3022 * report the uplevel that it is not an error that we
3023 * did not rmdir() our directory.
3024 */
3025 *kept_up = !ret;
7155b727
JS
3026 return ret;
3027}
039bc64e 3028
ae2f203e
JH
3029int remove_dir_recursively(struct strbuf *path, int flag)
3030{
3031 return remove_dir_recurse(path, flag, NULL);
3032}
3033
f932729c
JK
3034static GIT_PATH_FUNC(git_path_info_exclude, "info/exclude")
3035
039bc64e
JH
3036void setup_standard_excludes(struct dir_struct *dir)
3037{
039bc64e 3038 dir->exclude_per_dir = ".gitignore";
099d2d86 3039
51d18631 3040 /* core.excludesfile defaulting to $XDG_CONFIG_HOME/git/ignore */
2845ce7f
PT
3041 if (!excludes_file)
3042 excludes_file = xdg_config_home("ignore");
4698c8fe 3043 if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
65edd96a 3044 add_patterns_from_file_1(dir, excludes_file,
38ccaf93 3045 dir->untracked ? &dir->ss_excludes_file : NULL);
099d2d86
JH
3046
3047 /* per repository user preference */
f0056f64
JK
3048 if (startup_info->have_repository) {
3049 const char *path = git_path_info_exclude();
3050 if (!access_or_warn(path, R_OK, 0))
65edd96a 3051 add_patterns_from_file_1(dir, path,
f0056f64
JK
3052 dir->untracked ? &dir->ss_info_exclude : NULL);
3053 }
039bc64e 3054}
4a92d1bf 3055
dd23022a
DS
3056char *get_sparse_checkout_filename(void)
3057{
3058 return git_pathdup("info/sparse-checkout");
3059}
3060
3061int get_sparse_checkout_patterns(struct pattern_list *pl)
3062{
3063 int res;
3064 char *sparse_filename = get_sparse_checkout_filename();
3065
3066 pl->use_cone_patterns = core_sparse_checkout_cone;
1679d60b 3067 res = add_patterns_from_file_to_list(sparse_filename, "", 0, pl, NULL, 0);
dd23022a
DS
3068
3069 free(sparse_filename);
3070 return res;
3071}
3072
4a92d1bf
AR
3073int remove_path(const char *name)
3074{
3075 char *slash;
3076
c7054209 3077 if (unlink(name) && !is_missing_file_error(errno))
4a92d1bf
AR
3078 return -1;
3079
3080 slash = strrchr(name, '/');
3081 if (slash) {
3082 char *dirs = xstrdup(name);
3083 slash = dirs + (slash - name);
3084 do {
3085 *slash = '\0';
3fc0d131 3086 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
4a92d1bf
AR
3087 free(dirs);
3088 }
3089 return 0;
3090}
3091
270be816 3092/*
dad4f23c
EN
3093 * Frees memory within dir which was allocated, and resets fields for further
3094 * use. Does not free dir itself.
270be816 3095 */
eceba532 3096void dir_clear(struct dir_struct *dir)
270be816
AS
3097{
3098 int i, j;
3099 struct exclude_list_group *group;
caa3d554 3100 struct pattern_list *pl;
270be816 3101 struct exclude_stack *stk;
ce93a4c6 3102 struct dir_struct new = DIR_INIT;
270be816
AS
3103
3104 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
3105 group = &dir->exclude_list_group[i];
3106 for (j = 0; j < group->nr; j++) {
caa3d554 3107 pl = &group->pl[j];
270be816 3108 if (i == EXC_DIRS)
caa3d554 3109 free((char *)pl->src);
65edd96a 3110 clear_pattern_list(pl);
270be816 3111 }
caa3d554 3112 free(group->pl);
270be816
AS
3113 }
3114
dad4f23c
EN
3115 for (i = 0; i < dir->ignored_nr; i++)
3116 free(dir->ignored[i]);
3117 for (i = 0; i < dir->nr; i++)
3118 free(dir->entries[i]);
3119 free(dir->ignored);
3120 free(dir->entries);
3121
270be816
AS
3122 stk = dir->exclude_stack;
3123 while (stk) {
3124 struct exclude_stack *prev = stk->prev;
3125 free(stk);
3126 stk = prev;
3127 }
aceb9429 3128 strbuf_release(&dir->basebuf);
dad4f23c 3129
ce93a4c6 3130 memcpy(dir, &new, sizeof(*dir));
270be816 3131}
83c094ad
NTND
3132
3133struct ondisk_untracked_cache {
3134 struct stat_data info_exclude_stat;
3135 struct stat_data excludes_file_stat;
3136 uint32_t dir_flags;
83c094ad
NTND
3137};
3138
268ba201 3139#define ouc_offset(x) offsetof(struct ondisk_untracked_cache, x)
83c094ad
NTND
3140
3141struct write_data {
3142 int index; /* number of written untracked_cache_dir */
3143 struct ewah_bitmap *check_only; /* from untracked_cache_dir */
3144 struct ewah_bitmap *valid; /* from untracked_cache_dir */
3145 struct ewah_bitmap *sha1_valid; /* set if exclude_sha1 is not null */
3146 struct strbuf out;
3147 struct strbuf sb_stat;
3148 struct strbuf sb_sha1;
3149};
3150
3151static void stat_data_to_disk(struct stat_data *to, const struct stat_data *from)
3152{
3153 to->sd_ctime.sec = htonl(from->sd_ctime.sec);
3154 to->sd_ctime.nsec = htonl(from->sd_ctime.nsec);
3155 to->sd_mtime.sec = htonl(from->sd_mtime.sec);
3156 to->sd_mtime.nsec = htonl(from->sd_mtime.nsec);
3157 to->sd_dev = htonl(from->sd_dev);
3158 to->sd_ino = htonl(from->sd_ino);
3159 to->sd_uid = htonl(from->sd_uid);
3160 to->sd_gid = htonl(from->sd_gid);
3161 to->sd_size = htonl(from->sd_size);
3162}
3163
3164static void write_one_dir(struct untracked_cache_dir *untracked,
3165 struct write_data *wd)
3166{
3167 struct stat_data stat_data;
3168 struct strbuf *out = &wd->out;
3169 unsigned char intbuf[16];
3170 unsigned int intlen, value;
3171 int i = wd->index++;
3172
3173 /*
3174 * untracked_nr should be reset whenever valid is clear, but
3175 * for safety..
3176 */
3177 if (!untracked->valid) {
3178 untracked->untracked_nr = 0;
3179 untracked->check_only = 0;
3180 }
3181
3182 if (untracked->check_only)
3183 ewah_set(wd->check_only, i);
3184 if (untracked->valid) {
3185 ewah_set(wd->valid, i);
3186 stat_data_to_disk(&stat_data, &untracked->stat_data);
3187 strbuf_add(&wd->sb_stat, &stat_data, sizeof(stat_data));
3188 }
70c369cd 3189 if (!is_null_oid(&untracked->exclude_oid)) {
83c094ad 3190 ewah_set(wd->sha1_valid, i);
70c369cd 3191 strbuf_add(&wd->sb_sha1, untracked->exclude_oid.hash,
3192 the_hash_algo->rawsz);
83c094ad
NTND
3193 }
3194
3195 intlen = encode_varint(untracked->untracked_nr, intbuf);
3196 strbuf_add(out, intbuf, intlen);
3197
3198 /* skip non-recurse directories */
3199 for (i = 0, value = 0; i < untracked->dirs_nr; i++)
3200 if (untracked->dirs[i]->recurse)
3201 value++;
3202 intlen = encode_varint(value, intbuf);
3203 strbuf_add(out, intbuf, intlen);
3204
3205 strbuf_add(out, untracked->name, strlen(untracked->name) + 1);
3206
3207 for (i = 0; i < untracked->untracked_nr; i++)
3208 strbuf_add(out, untracked->untracked[i],
3209 strlen(untracked->untracked[i]) + 1);
3210
3211 for (i = 0; i < untracked->dirs_nr; i++)
3212 if (untracked->dirs[i]->recurse)
3213 write_one_dir(untracked->dirs[i], wd);
3214}
3215
3216void write_untracked_extension(struct strbuf *out, struct untracked_cache *untracked)
3217{
3218 struct ondisk_untracked_cache *ouc;
3219 struct write_data wd;
3220 unsigned char varbuf[16];
e0b83735 3221 int varint_len;
3899b88b 3222 const unsigned hashsz = the_hash_algo->rawsz;
e0b83735 3223
ca56dadb 3224 CALLOC_ARRAY(ouc, 1);
83c094ad
NTND
3225 stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);
3226 stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);
83c094ad 3227 ouc->dir_flags = htonl(untracked->dir_flags);
1e8fef60
NTND
3228
3229 varint_len = encode_varint(untracked->ident.len, varbuf);
3230 strbuf_add(out, varbuf, varint_len);
8109984d 3231 strbuf_addbuf(out, &untracked->ident);
1e8fef60 3232
3899b88b 3233 strbuf_add(out, ouc, sizeof(*ouc));
3234 strbuf_add(out, untracked->ss_info_exclude.oid.hash, hashsz);
3235 strbuf_add(out, untracked->ss_excludes_file.oid.hash, hashsz);
3236 strbuf_add(out, untracked->exclude_per_dir, strlen(untracked->exclude_per_dir) + 1);
6a83d902 3237 FREE_AND_NULL(ouc);
83c094ad
NTND
3238
3239 if (!untracked->root) {
3240 varint_len = encode_varint(0, varbuf);
3241 strbuf_add(out, varbuf, varint_len);
3242 return;
3243 }
3244
3245 wd.index = 0;
3246 wd.check_only = ewah_new();
3247 wd.valid = ewah_new();
3248 wd.sha1_valid = ewah_new();
3249 strbuf_init(&wd.out, 1024);
3250 strbuf_init(&wd.sb_stat, 1024);
3251 strbuf_init(&wd.sb_sha1, 1024);
3252 write_one_dir(untracked->root, &wd);
3253
3254 varint_len = encode_varint(wd.index, varbuf);
3255 strbuf_add(out, varbuf, varint_len);
3256 strbuf_addbuf(out, &wd.out);
3257 ewah_serialize_strbuf(wd.valid, out);
3258 ewah_serialize_strbuf(wd.check_only, out);
3259 ewah_serialize_strbuf(wd.sha1_valid, out);
3260 strbuf_addbuf(out, &wd.sb_stat);
3261 strbuf_addbuf(out, &wd.sb_sha1);
3262 strbuf_addch(out, '\0'); /* safe guard for string lists */
3263
3264 ewah_free(wd.valid);
3265 ewah_free(wd.check_only);
3266 ewah_free(wd.sha1_valid);
3267 strbuf_release(&wd.out);
3268 strbuf_release(&wd.sb_stat);
3269 strbuf_release(&wd.sb_sha1);
3270}
f9e6c649
NTND
3271
3272static void free_untracked(struct untracked_cache_dir *ucd)
3273{
3274 int i;
3275 if (!ucd)
3276 return;
3277 for (i = 0; i < ucd->dirs_nr; i++)
3278 free_untracked(ucd->dirs[i]);
3279 for (i = 0; i < ucd->untracked_nr; i++)
3280 free(ucd->untracked[i]);
3281 free(ucd->untracked);
3282 free(ucd->dirs);
3283 free(ucd);
3284}
3285
3286void free_untracked_cache(struct untracked_cache *uc)
3287{
3288 if (uc)
3289 free_untracked(uc->root);
3290 free(uc);
3291}
3292
3293struct read_data {
3294 int index;
3295 struct untracked_cache_dir **ucd;
3296 struct ewah_bitmap *check_only;
3297 struct ewah_bitmap *valid;
3298 struct ewah_bitmap *sha1_valid;
3299 const unsigned char *data;
3300 const unsigned char *end;
3301};
3302
268ba201 3303static void stat_data_from_disk(struct stat_data *to, const unsigned char *data)
f9e6c649 3304{
268ba201
RS
3305 memcpy(to, data, sizeof(*to));
3306 to->sd_ctime.sec = ntohl(to->sd_ctime.sec);
3307 to->sd_ctime.nsec = ntohl(to->sd_ctime.nsec);
3308 to->sd_mtime.sec = ntohl(to->sd_mtime.sec);
3309 to->sd_mtime.nsec = ntohl(to->sd_mtime.nsec);
3310 to->sd_dev = ntohl(to->sd_dev);
3311 to->sd_ino = ntohl(to->sd_ino);
3312 to->sd_uid = ntohl(to->sd_uid);
3313 to->sd_gid = ntohl(to->sd_gid);
3314 to->sd_size = ntohl(to->sd_size);
f9e6c649
NTND
3315}
3316
3317static int read_one_dir(struct untracked_cache_dir **untracked_,
3318 struct read_data *rd)
3319{
3320 struct untracked_cache_dir ud, *untracked;
b511d6d5 3321 const unsigned char *data = rd->data, *end = rd->end;
c6909f99 3322 const unsigned char *eos;
f9e6c649 3323 unsigned int value;
08bf354d 3324 int i;
f9e6c649
NTND
3325
3326 memset(&ud, 0, sizeof(ud));
3327
b511d6d5
JK
3328 value = decode_varint(&data);
3329 if (data > end)
f9e6c649
NTND
3330 return -1;
3331 ud.recurse = 1;
3332 ud.untracked_alloc = value;
3333 ud.untracked_nr = value;
3334 if (ud.untracked_nr)
b32fa95f 3335 ALLOC_ARRAY(ud.untracked, ud.untracked_nr);
f9e6c649 3336
b511d6d5
JK
3337 ud.dirs_alloc = ud.dirs_nr = decode_varint(&data);
3338 if (data > end)
f9e6c649 3339 return -1;
b32fa95f 3340 ALLOC_ARRAY(ud.dirs, ud.dirs_nr);
f9e6c649 3341
c6909f99
JK
3342 eos = memchr(data, '\0', end - data);
3343 if (!eos || eos == end)
f9e6c649 3344 return -1;
c6909f99 3345
08bf354d 3346 *untracked_ = untracked = xmalloc(st_add3(sizeof(*untracked), eos - data, 1));
f9e6c649 3347 memcpy(untracked, &ud, sizeof(ud));
08bf354d 3348 memcpy(untracked->name, data, eos - data + 1);
b511d6d5 3349 data = eos + 1;
f9e6c649
NTND
3350
3351 for (i = 0; i < untracked->untracked_nr; i++) {
c6909f99
JK
3352 eos = memchr(data, '\0', end - data);
3353 if (!eos || eos == end)
f9e6c649 3354 return -1;
08bf354d 3355 untracked->untracked[i] = xmemdupz(data, eos - data);
b511d6d5 3356 data = eos + 1;
f9e6c649
NTND
3357 }
3358
3359 rd->ucd[rd->index++] = untracked;
3360 rd->data = data;
3361
3362 for (i = 0; i < untracked->dirs_nr; i++) {
08bf354d 3363 if (read_one_dir(untracked->dirs + i, rd) < 0)
f9e6c649
NTND
3364 return -1;
3365 }
3366 return 0;
3367}
3368
3369static void set_check_only(size_t pos, void *cb)
3370{
3371 struct read_data *rd = cb;
3372 struct untracked_cache_dir *ud = rd->ucd[pos];
3373 ud->check_only = 1;
3374}
3375
3376static void read_stat(size_t pos, void *cb)
3377{
3378 struct read_data *rd = cb;
3379 struct untracked_cache_dir *ud = rd->ucd[pos];
3380 if (rd->data + sizeof(struct stat_data) > rd->end) {
3381 rd->data = rd->end + 1;
3382 return;
3383 }
268ba201 3384 stat_data_from_disk(&ud->stat_data, rd->data);
f9e6c649
NTND
3385 rd->data += sizeof(struct stat_data);
3386 ud->valid = 1;
3387}
3388
70c369cd 3389static void read_oid(size_t pos, void *cb)
f9e6c649
NTND
3390{
3391 struct read_data *rd = cb;
3392 struct untracked_cache_dir *ud = rd->ucd[pos];
70c369cd 3393 if (rd->data + the_hash_algo->rawsz > rd->end) {
f9e6c649
NTND
3394 rd->data = rd->end + 1;
3395 return;
3396 }
92e2cab9 3397 oidread(&ud->exclude_oid, rd->data);
70c369cd 3398 rd->data += the_hash_algo->rawsz;
f9e6c649
NTND
3399}
3400
4b33e602
PO
3401static void load_oid_stat(struct oid_stat *oid_stat, const unsigned char *data,
3402 const unsigned char *sha1)
f9e6c649 3403{
4b33e602 3404 stat_data_from_disk(&oid_stat->stat, data);
92e2cab9 3405 oidread(&oid_stat->oid, sha1);
4b33e602 3406 oid_stat->valid = 1;
f9e6c649
NTND
3407}
3408
3409struct untracked_cache *read_untracked_extension(const void *data, unsigned long sz)
3410{
f9e6c649
NTND
3411 struct untracked_cache *uc;
3412 struct read_data rd;
3413 const unsigned char *next = data, *end = (const unsigned char *)data + sz;
1e8fef60 3414 const char *ident;
1140bf01
JK
3415 int ident_len;
3416 ssize_t len;
268ba201 3417 const char *exclude_per_dir;
3899b88b 3418 const unsigned hashsz = the_hash_algo->rawsz;
3419 const unsigned offset = sizeof(struct ondisk_untracked_cache);
3420 const unsigned exclude_per_dir_offset = offset + 2 * hashsz;
f9e6c649
NTND
3421
3422 if (sz <= 1 || end[-1] != '\0')
3423 return NULL;
3424 end--;
3425
1e8fef60
NTND
3426 ident_len = decode_varint(&next);
3427 if (next + ident_len > end)
3428 return NULL;
3429 ident = (const char *)next;
3430 next += ident_len;
3431
3899b88b 3432 if (next + exclude_per_dir_offset + 1 > end)
f9e6c649
NTND
3433 return NULL;
3434
ca56dadb 3435 CALLOC_ARRAY(uc, 1);
1e8fef60
NTND
3436 strbuf_init(&uc->ident, ident_len);
3437 strbuf_add(&uc->ident, ident, ident_len);
4b33e602
PO
3438 load_oid_stat(&uc->ss_info_exclude,
3439 next + ouc_offset(info_exclude_stat),
3899b88b 3440 next + offset);
4b33e602
PO
3441 load_oid_stat(&uc->ss_excludes_file,
3442 next + ouc_offset(excludes_file_stat),
3899b88b 3443 next + offset + hashsz);
268ba201 3444 uc->dir_flags = get_be32(next + ouc_offset(dir_flags));
3899b88b 3445 exclude_per_dir = (const char *)next + exclude_per_dir_offset;
268ba201 3446 uc->exclude_per_dir = xstrdup(exclude_per_dir);
f9e6c649 3447 /* NUL after exclude_per_dir is covered by sizeof(*ouc) */
3899b88b 3448 next += exclude_per_dir_offset + strlen(exclude_per_dir) + 1;
f9e6c649
NTND
3449 if (next >= end)
3450 goto done2;
3451
3452 len = decode_varint(&next);
3453 if (next > end || len == 0)
3454 goto done2;
3455
3456 rd.valid = ewah_new();
3457 rd.check_only = ewah_new();
3458 rd.sha1_valid = ewah_new();
3459 rd.data = next;
3460 rd.end = end;
3461 rd.index = 0;
b32fa95f 3462 ALLOC_ARRAY(rd.ucd, len);
f9e6c649
NTND
3463
3464 if (read_one_dir(&uc->root, &rd) || rd.index != len)
3465 goto done;
3466
3467 next = rd.data;
3468 len = ewah_read_mmap(rd.valid, next, end - next);
3469 if (len < 0)
3470 goto done;
3471
3472 next += len;
3473 len = ewah_read_mmap(rd.check_only, next, end - next);
3474 if (len < 0)
3475 goto done;
3476
3477 next += len;
3478 len = ewah_read_mmap(rd.sha1_valid, next, end - next);
3479 if (len < 0)
3480 goto done;
3481
3482 ewah_each_bit(rd.check_only, set_check_only, &rd);
3483 rd.data = next + len;
3484 ewah_each_bit(rd.valid, read_stat, &rd);
70c369cd 3485 ewah_each_bit(rd.sha1_valid, read_oid, &rd);
f9e6c649
NTND
3486 next = rd.data;
3487
3488done:
3489 free(rd.ucd);
3490 ewah_free(rd.valid);
3491 ewah_free(rd.check_only);
3492 ewah_free(rd.sha1_valid);
3493done2:
3494 if (next != end) {
3495 free_untracked_cache(uc);
3496 uc = NULL;
3497 }
3498 return uc;
3499}
e931371a 3500
73f9145f
NTND
3501static void invalidate_one_directory(struct untracked_cache *uc,
3502 struct untracked_cache_dir *ucd)
3503{
3504 uc->dir_invalidated++;
3505 ucd->valid = 0;
3506 ucd->untracked_nr = 0;
3507}
3508
3509/*
3510 * Normally when an entry is added or removed from a directory,
3511 * invalidating that directory is enough. No need to touch its
3512 * ancestors. When a directory is shown as "foo/bar/" in git-status
3513 * however, deleting or adding an entry may have cascading effect.
3514 *
3515 * Say the "foo/bar/file" has become untracked, we need to tell the
3516 * untracked_cache_dir of "foo" that "bar/" is not an untracked
3517 * directory any more (because "bar" is managed by foo as an untracked
3518 * "file").
3519 *
3520 * Similarly, if "foo/bar/file" moves from untracked to tracked and it
3521 * was the last untracked entry in the entire "foo", we should show
3522 * "foo/" instead. Which means we have to invalidate past "bar" up to
3523 * "foo".
3524 *
3525 * This function traverses all directories from root to leaf. If there
3526 * is a chance of one of the above cases happening, we invalidate back
3527 * to root. Otherwise we just invalidate the leaf. There may be a more
3528 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to
3529 * detect these cases and avoid unnecessary invalidation, for example,
3530 * checking for the untracked entry named "bar/" in "foo", but for now
3531 * stick to something safe and simple.
3532 */
3533static int invalidate_one_component(struct untracked_cache *uc,
3534 struct untracked_cache_dir *dir,
3535 const char *path, int len)
3536{
3537 const char *rest = strchr(path, '/');
3538
3539 if (rest) {
3540 int component_len = rest - path;
3541 struct untracked_cache_dir *d =
3542 lookup_untracked(uc, dir, path, component_len);
3543 int ret =
3544 invalidate_one_component(uc, d, rest + 1,
3545 len - (component_len + 1));
3546 if (ret)
3547 invalidate_one_directory(uc, dir);
3548 return ret;
3549 }
3550
3551 invalidate_one_directory(uc, dir);
3552 return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;
3553}
3554
e931371a 3555void untracked_cache_invalidate_path(struct index_state *istate,
0cacebf0 3556 const char *path, int safe_path)
e931371a 3557{
e931371a
NTND
3558 if (!istate->untracked || !istate->untracked->root)
3559 return;
68f95b26 3560 if (!safe_path && !verify_path(path, 0))
0cacebf0 3561 return;
73f9145f
NTND
3562 invalidate_one_component(istate->untracked, istate->untracked->root,
3563 path, strlen(path));
e931371a
NTND
3564}
3565
3566void untracked_cache_remove_from_index(struct index_state *istate,
3567 const char *path)
3568{
0cacebf0 3569 untracked_cache_invalidate_path(istate, path, 1);
e931371a
NTND
3570}
3571
3572void untracked_cache_add_to_index(struct index_state *istate,
3573 const char *path)
3574{
0cacebf0 3575 untracked_cache_invalidate_path(istate, path, 1);
e931371a 3576}
47e83eb3 3577
da62f786
SB
3578static void connect_wt_gitdir_in_nested(const char *sub_worktree,
3579 const char *sub_gitdir)
3580{
3581 int i;
3582 struct repository subrepo;
3583 struct strbuf sub_wt = STRBUF_INIT;
3584 struct strbuf sub_gd = STRBUF_INIT;
3585
3586 const struct submodule *sub;
3587
3588 /* If the submodule has no working tree, we can ignore it. */
3589 if (repo_init(&subrepo, sub_gitdir, sub_worktree))
3590 return;
3591
3592 if (repo_read_index(&subrepo) < 0)
a80897c1 3593 die(_("index file corrupt in repo %s"), subrepo.gitdir);
da62f786 3594
d425f651
DS
3595 /* TODO: audit for interaction with sparse-index. */
3596 ensure_full_index(subrepo.index);
da62f786
SB
3597 for (i = 0; i < subrepo.index->cache_nr; i++) {
3598 const struct cache_entry *ce = subrepo.index->cache[i];
3599
3600 if (!S_ISGITLINK(ce->ce_mode))
3601 continue;
3602
3603 while (i + 1 < subrepo.index->cache_nr &&
3604 !strcmp(ce->name, subrepo.index->cache[i + 1]->name))
3605 /*
3606 * Skip entries with the same name in different stages
3607 * to make sure an entry is returned only once.
3608 */
3609 i++;
3610
14228447 3611 sub = submodule_from_path(&subrepo, null_oid(), ce->name);
da62f786
SB
3612 if (!sub || !is_submodule_active(&subrepo, ce->name))
3613 /* .gitmodules broken or inactive sub */
3614 continue;
3615
3616 strbuf_reset(&sub_wt);
3617 strbuf_reset(&sub_gd);
3618 strbuf_addf(&sub_wt, "%s/%s", sub_worktree, sub->path);
3619 strbuf_addf(&sub_gd, "%s/modules/%s", sub_gitdir, sub->name);
3620
3621 connect_work_tree_and_git_dir(sub_wt.buf, sub_gd.buf, 1);
3622 }
3623 strbuf_release(&sub_wt);
3624 strbuf_release(&sub_gd);
3625 repo_clear(&subrepo);
3626}
3627
3628void connect_work_tree_and_git_dir(const char *work_tree_,
3629 const char *git_dir_,
3630 int recurse_into_nested)
47e83eb3 3631{
365444a6
SB
3632 struct strbuf gitfile_sb = STRBUF_INIT;
3633 struct strbuf cfg_sb = STRBUF_INIT;
47e83eb3 3634 struct strbuf rel_path = STRBUF_INIT;
365444a6 3635 char *git_dir, *work_tree;
47e83eb3 3636
365444a6
SB
3637 /* Prepare .git file */
3638 strbuf_addf(&gitfile_sb, "%s/.git", work_tree_);
3639 if (safe_create_leading_directories_const(gitfile_sb.buf))
3640 die(_("could not create directories for %s"), gitfile_sb.buf);
3641
3642 /* Prepare config file */
3643 strbuf_addf(&cfg_sb, "%s/config", git_dir_);
3644 if (safe_create_leading_directories_const(cfg_sb.buf))
3645 die(_("could not create directories for %s"), cfg_sb.buf);
47e83eb3 3646
e394fa01
JH
3647 git_dir = real_pathdup(git_dir_, 1);
3648 work_tree = real_pathdup(work_tree_, 1);
365444a6
SB
3649
3650 /* Write .git file */
3651 write_file(gitfile_sb.buf, "gitdir: %s",
3652 relative_path(git_dir, work_tree, &rel_path));
47e83eb3 3653 /* Update core.worktree setting */
365444a6 3654 git_config_set_in_file(cfg_sb.buf, "core.worktree",
47e83eb3
SB
3655 relative_path(work_tree, git_dir, &rel_path));
3656
365444a6
SB
3657 strbuf_release(&gitfile_sb);
3658 strbuf_release(&cfg_sb);
47e83eb3 3659 strbuf_release(&rel_path);
da62f786
SB
3660
3661 if (recurse_into_nested)
3662 connect_wt_gitdir_in_nested(work_tree, git_dir);
3663
47e83eb3
SB
3664 free(work_tree);
3665 free(git_dir);
3666}
f6f85861
SB
3667
3668/*
3669 * Migrate the git directory of the given path from old_git_dir to new_git_dir.
3670 */
3671void relocate_gitdir(const char *path, const char *old_git_dir, const char *new_git_dir)
3672{
3673 if (rename(old_git_dir, new_git_dir) < 0)
3674 die_errno(_("could not migrate git directory from '%s' to '%s'"),
3675 old_git_dir, new_git_dir);
3676
da62f786 3677 connect_work_tree_and_git_dir(path, new_git_dir, 0);
f6f85861 3678}