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