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