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