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