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