The sixth batch
[alt-git.git] / dir.c
blob2d83f3311a75131a98a22a1d278b433c32ada560
1 /*
2 * This handles recursive filename detection with exclude
3 * files, index knowledge etc..
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 "config.h"
11 #include "convert.h"
12 #include "dir.h"
13 #include "environment.h"
14 #include "gettext.h"
15 #include "name-hash.h"
16 #include "object-file.h"
17 #include "object-store-ll.h"
18 #include "path.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-ll.h"
26 #include "read-cache-ll.h"
27 #include "setup.h"
28 #include "sparse-index.h"
29 #include "submodule-config.h"
30 #include "symlinks.h"
31 #include "trace2.h"
32 #include "tree.h"
35 * Tells read_directory_recursive how a file or directory should be treated.
36 * Values are ordered by significance, e.g. if a directory contains both
37 * excluded and untracked files, it is listed as untracked because
38 * path_untracked > path_excluded.
40 enum path_treatment {
41 path_none = 0,
42 path_recurse,
43 path_excluded,
44 path_untracked
48 * Support data structure for our opendir/readdir/closedir wrappers
50 struct cached_dir {
51 DIR *fdir;
52 struct untracked_cache_dir *untracked;
53 int nr_files;
54 int nr_dirs;
56 const char *d_name;
57 int d_type;
58 const char *file;
59 struct untracked_cache_dir *ucd;
62 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
63 struct index_state *istate, const char *path, int len,
64 struct untracked_cache_dir *untracked,
65 int check_only, int stop_at_first_file, const struct pathspec *pathspec);
66 static int resolve_dtype(int dtype, struct index_state *istate,
67 const char *path, int len);
68 struct dirent *readdir_skip_dot_and_dotdot(DIR *dirp)
70 struct dirent *e;
72 while ((e = readdir(dirp)) != NULL) {
73 if (!is_dot_or_dotdot(e->d_name))
74 break;
76 return e;
79 int count_slashes(const char *s)
81 int cnt = 0;
82 while (*s)
83 if (*s++ == '/')
84 cnt++;
85 return cnt;
88 int fspathcmp(const char *a, const char *b)
90 return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
93 int fspatheq(const char *a, const char *b)
95 return !fspathcmp(a, b);
98 int fspathncmp(const char *a, const char *b, size_t count)
100 return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
103 int paths_collide(const char *a, const char *b)
105 size_t len_a = strlen(a), len_b = strlen(b);
107 if (len_a == len_b)
108 return fspatheq(a, b);
110 if (len_a < len_b)
111 return is_dir_sep(b[len_a]) && !fspathncmp(a, b, len_a);
112 return is_dir_sep(a[len_b]) && !fspathncmp(a, b, len_b);
115 unsigned int fspathhash(const char *str)
117 return ignore_case ? strihash(str) : strhash(str);
120 int git_fnmatch(const struct pathspec_item *item,
121 const char *pattern, const char *string,
122 int prefix)
124 if (prefix > 0) {
125 if (ps_strncmp(item, pattern, string, prefix))
126 return WM_NOMATCH;
127 pattern += prefix;
128 string += prefix;
130 if (item->flags & PATHSPEC_ONESTAR) {
131 int pattern_len = strlen(++pattern);
132 int string_len = strlen(string);
133 return string_len < pattern_len ||
134 ps_strcmp(item, pattern,
135 string + string_len - pattern_len);
137 if (item->magic & PATHSPEC_GLOB)
138 return wildmatch(pattern, string,
139 WM_PATHNAME |
140 (item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0));
141 else
142 /* wildmatch has not learned no FNM_PATHNAME mode yet */
143 return wildmatch(pattern, string,
144 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0);
147 static int fnmatch_icase_mem(const char *pattern, int patternlen,
148 const char *string, int stringlen,
149 int flags)
151 int match_status;
152 struct strbuf pat_buf = STRBUF_INIT;
153 struct strbuf str_buf = STRBUF_INIT;
154 const char *use_pat = pattern;
155 const char *use_str = string;
157 if (pattern[patternlen]) {
158 strbuf_add(&pat_buf, pattern, patternlen);
159 use_pat = pat_buf.buf;
161 if (string[stringlen]) {
162 strbuf_add(&str_buf, string, stringlen);
163 use_str = str_buf.buf;
166 if (ignore_case)
167 flags |= WM_CASEFOLD;
168 match_status = wildmatch(use_pat, use_str, flags);
170 strbuf_release(&pat_buf);
171 strbuf_release(&str_buf);
173 return match_status;
176 static size_t common_prefix_len(const struct pathspec *pathspec)
178 int n;
179 size_t max = 0;
182 * ":(icase)path" is treated as a pathspec full of
183 * wildcard. In other words, only prefix is considered common
184 * prefix. If the pathspec is abc/foo abc/bar, running in
185 * subdir xyz, the common prefix is still xyz, not xyz/abc as
186 * in non-:(icase).
188 GUARD_PATHSPEC(pathspec,
189 PATHSPEC_FROMTOP |
190 PATHSPEC_MAXDEPTH |
191 PATHSPEC_LITERAL |
192 PATHSPEC_GLOB |
193 PATHSPEC_ICASE |
194 PATHSPEC_EXCLUDE |
195 PATHSPEC_ATTR);
197 for (n = 0; n < pathspec->nr; n++) {
198 size_t i = 0, len = 0, item_len;
199 if (pathspec->items[n].magic & PATHSPEC_EXCLUDE)
200 continue;
201 if (pathspec->items[n].magic & PATHSPEC_ICASE)
202 item_len = pathspec->items[n].prefix;
203 else
204 item_len = pathspec->items[n].nowildcard_len;
205 while (i < item_len && (n == 0 || i < max)) {
206 char c = pathspec->items[n].match[i];
207 if (c != pathspec->items[0].match[i])
208 break;
209 if (c == '/')
210 len = i + 1;
211 i++;
213 if (n == 0 || len < max) {
214 max = len;
215 if (!max)
216 break;
219 return max;
223 * Returns a copy of the longest leading path common among all
224 * pathspecs.
226 char *common_prefix(const struct pathspec *pathspec)
228 unsigned long len = common_prefix_len(pathspec);
230 return len ? xmemdupz(pathspec->items[0].match, len) : NULL;
233 int fill_directory(struct dir_struct *dir,
234 struct index_state *istate,
235 const struct pathspec *pathspec)
237 const char *prefix;
238 size_t prefix_len;
240 unsigned exclusive_flags = DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO;
241 if ((dir->flags & exclusive_flags) == exclusive_flags)
242 BUG("DIR_SHOW_IGNORED and DIR_SHOW_IGNORED_TOO are exclusive");
245 * Calculate common prefix for the pathspec, and
246 * use that to optimize the directory walk
248 prefix_len = common_prefix_len(pathspec);
249 prefix = prefix_len ? pathspec->items[0].match : "";
251 /* Read the directory and prune it */
252 read_directory(dir, istate, prefix, prefix_len, pathspec);
254 return prefix_len;
257 int within_depth(const char *name, int namelen,
258 int depth, int max_depth)
260 const char *cp = name, *cpe = name + namelen;
262 while (cp < cpe) {
263 if (*cp++ != '/')
264 continue;
265 depth++;
266 if (depth > max_depth)
267 return 0;
269 return 1;
273 * Read the contents of the blob with the given OID into a buffer.
274 * Append a trailing LF to the end if the last line doesn't have one.
276 * Returns:
277 * -1 when the OID is invalid or unknown or does not refer to a blob.
278 * 0 when the blob is empty.
279 * 1 along with { data, size } of the (possibly augmented) buffer
280 * when successful.
282 * Optionally updates the given oid_stat with the given OID (when valid).
284 static int do_read_blob(const struct object_id *oid, struct oid_stat *oid_stat,
285 size_t *size_out, char **data_out)
287 enum object_type type;
288 unsigned long sz;
289 char *data;
291 *size_out = 0;
292 *data_out = NULL;
294 data = repo_read_object_file(the_repository, oid, &type, &sz);
295 if (!data || type != OBJ_BLOB) {
296 free(data);
297 return -1;
300 if (oid_stat) {
301 memset(&oid_stat->stat, 0, sizeof(oid_stat->stat));
302 oidcpy(&oid_stat->oid, oid);
305 if (sz == 0) {
306 free(data);
307 return 0;
310 if (data[sz - 1] != '\n') {
311 data = xrealloc(data, st_add(sz, 1));
312 data[sz++] = '\n';
315 *size_out = xsize_t(sz);
316 *data_out = data;
318 return 1;
321 #define DO_MATCH_EXCLUDE (1<<0)
322 #define DO_MATCH_DIRECTORY (1<<1)
323 #define DO_MATCH_LEADING_PATHSPEC (1<<2)
326 * Does the given pathspec match the given name? A match is found if
328 * (1) the pathspec string is leading directory of 'name' ("RECURSIVELY"), or
329 * (2) the pathspec string has a leading part matching 'name' ("LEADING"), or
330 * (3) the pathspec string is a wildcard and matches 'name' ("WILDCARD"), or
331 * (4) the pathspec string is exactly the same as 'name' ("EXACT").
333 * Return value tells which case it was (1-4), or 0 when there is no match.
335 * It may be instructive to look at a small table of concrete examples
336 * to understand the differences between 1, 2, and 4:
338 * Pathspecs
339 * | a/b | a/b/ | a/b/c
340 * ------+-----------+-----------+------------
341 * a/b | EXACT | EXACT[1] | LEADING[2]
342 * Names a/b/ | RECURSIVE | EXACT | LEADING[2]
343 * a/b/c | RECURSIVE | RECURSIVE | EXACT
345 * [1] Only if DO_MATCH_DIRECTORY is passed; otherwise, this is NOT a match.
346 * [2] Only if DO_MATCH_LEADING_PATHSPEC is passed; otherwise, not a match.
348 static int match_pathspec_item(struct index_state *istate,
349 const struct pathspec_item *item, int prefix,
350 const char *name, int namelen, unsigned flags)
352 /* name/namelen has prefix cut off by caller */
353 const char *match = item->match + prefix;
354 int matchlen = item->len - prefix;
357 * The normal call pattern is:
358 * 1. prefix = common_prefix_len(ps);
359 * 2. prune something, or fill_directory
360 * 3. match_pathspec()
362 * 'prefix' at #1 may be shorter than the command's prefix and
363 * it's ok for #2 to match extra files. Those extras will be
364 * trimmed at #3.
366 * Suppose the pathspec is 'foo' and '../bar' running from
367 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
368 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
369 * user does not want XYZ/foo, only the "foo" part should be
370 * case-insensitive. We need to filter out XYZ/foo here. In
371 * other words, we do not trust the caller on comparing the
372 * prefix part when :(icase) is involved. We do exact
373 * comparison ourselves.
375 * Normally the caller (common_prefix_len() in fact) does
376 * _exact_ matching on name[-prefix+1..-1] and we do not need
377 * to check that part. Be defensive and check it anyway, in
378 * case common_prefix_len is changed, or a new caller is
379 * introduced that does not use common_prefix_len.
381 * If the penalty turns out too high when prefix is really
382 * long, maybe change it to
383 * strncmp(match, name, item->prefix - prefix)
385 if (item->prefix && (item->magic & PATHSPEC_ICASE) &&
386 strncmp(item->match, name - prefix, item->prefix))
387 return 0;
389 if (item->attr_match_nr &&
390 !match_pathspec_attrs(istate, name - prefix, namelen + prefix, item))
391 return 0;
393 /* If the match was just the prefix, we matched */
394 if (!*match)
395 return MATCHED_RECURSIVELY;
397 if (matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) {
398 if (matchlen == namelen)
399 return MATCHED_EXACTLY;
401 if (match[matchlen-1] == '/' || name[matchlen] == '/')
402 return MATCHED_RECURSIVELY;
403 } else if ((flags & DO_MATCH_DIRECTORY) &&
404 match[matchlen - 1] == '/' &&
405 namelen == matchlen - 1 &&
406 !ps_strncmp(item, match, name, namelen))
407 return MATCHED_EXACTLY;
409 if (item->nowildcard_len < item->len &&
410 !git_fnmatch(item, match, name,
411 item->nowildcard_len - prefix))
412 return MATCHED_FNMATCH;
414 /* Perform checks to see if "name" is a leading string of the pathspec */
415 if ( (flags & DO_MATCH_LEADING_PATHSPEC) &&
416 !(flags & DO_MATCH_EXCLUDE)) {
417 /* name is a literal prefix of the pathspec */
418 int offset = name[namelen-1] == '/' ? 1 : 0;
419 if ((namelen < matchlen) &&
420 (match[namelen-offset] == '/') &&
421 !ps_strncmp(item, match, name, namelen))
422 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
424 /* name doesn't match up to the first wild character */
425 if (item->nowildcard_len < item->len &&
426 ps_strncmp(item, match, name,
427 item->nowildcard_len - prefix))
428 return 0;
431 * name has no wildcard, and it didn't match as a leading
432 * pathspec so return.
434 if (item->nowildcard_len == item->len)
435 return 0;
438 * Here is where we would perform a wildmatch to check if
439 * "name" can be matched as a directory (or a prefix) against
440 * the pathspec. Since wildmatch doesn't have this capability
441 * at the present we have to punt and say that it is a match,
442 * potentially returning a false positive
443 * The submodules themselves will be able to perform more
444 * accurate matching to determine if the pathspec matches.
446 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
449 return 0;
453 * do_match_pathspec() is meant to ONLY be called by
454 * match_pathspec_with_flags(); calling it directly risks pathspecs
455 * like ':!unwanted_path' being ignored.
457 * Given a name and a list of pathspecs, returns the nature of the
458 * closest (i.e. most specific) match of the name to any of the
459 * pathspecs.
461 * The caller typically calls this multiple times with the same
462 * pathspec and seen[] array but with different name/namelen
463 * (e.g. entries from the index) and is interested in seeing if and
464 * how each pathspec matches all the names it calls this function
465 * with. A mark is left in the seen[] array for each pathspec element
466 * indicating the closest type of match that element achieved, so if
467 * seen[n] remains zero after multiple invocations, that means the nth
468 * pathspec did not match any names, which could indicate that the
469 * user mistyped the nth pathspec.
471 static int do_match_pathspec(struct index_state *istate,
472 const struct pathspec *ps,
473 const char *name, int namelen,
474 int prefix, char *seen,
475 unsigned flags)
477 int i, retval = 0, exclude = flags & DO_MATCH_EXCLUDE;
479 GUARD_PATHSPEC(ps,
480 PATHSPEC_FROMTOP |
481 PATHSPEC_MAXDEPTH |
482 PATHSPEC_LITERAL |
483 PATHSPEC_GLOB |
484 PATHSPEC_ICASE |
485 PATHSPEC_EXCLUDE |
486 PATHSPEC_ATTR);
488 if (!ps->nr) {
489 if (!ps->recursive ||
490 !(ps->magic & PATHSPEC_MAXDEPTH) ||
491 ps->max_depth == -1)
492 return MATCHED_RECURSIVELY;
494 if (within_depth(name, namelen, 0, ps->max_depth))
495 return MATCHED_EXACTLY;
496 else
497 return 0;
500 name += prefix;
501 namelen -= prefix;
503 for (i = ps->nr - 1; i >= 0; i--) {
504 int how;
506 if ((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) ||
507 ( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE)))
508 continue;
510 if (seen && seen[i] == MATCHED_EXACTLY)
511 continue;
513 * Make exclude patterns optional and never report
514 * "pathspec ':(exclude)foo' matches no files"
516 if (seen && ps->items[i].magic & PATHSPEC_EXCLUDE)
517 seen[i] = MATCHED_FNMATCH;
518 how = match_pathspec_item(istate, ps->items+i, prefix, name,
519 namelen, flags);
520 if (ps->recursive &&
521 (ps->magic & PATHSPEC_MAXDEPTH) &&
522 ps->max_depth != -1 &&
523 how && how != MATCHED_FNMATCH) {
524 int len = ps->items[i].len;
525 if (name[len] == '/')
526 len++;
527 if (within_depth(name+len, namelen-len, 0, ps->max_depth))
528 how = MATCHED_EXACTLY;
529 else
530 how = 0;
532 if (how) {
533 if (retval < how)
534 retval = how;
535 if (seen && seen[i] < how)
536 seen[i] = how;
539 return retval;
542 static int match_pathspec_with_flags(struct index_state *istate,
543 const struct pathspec *ps,
544 const char *name, int namelen,
545 int prefix, char *seen, unsigned flags)
547 int positive, negative;
548 positive = do_match_pathspec(istate, ps, name, namelen,
549 prefix, seen, flags);
550 if (!(ps->magic & PATHSPEC_EXCLUDE) || !positive)
551 return positive;
552 negative = do_match_pathspec(istate, ps, name, namelen,
553 prefix, seen,
554 flags | DO_MATCH_EXCLUDE);
555 return negative ? 0 : positive;
558 int match_pathspec(struct index_state *istate,
559 const struct pathspec *ps,
560 const char *name, int namelen,
561 int prefix, char *seen, int is_dir)
563 unsigned flags = is_dir ? DO_MATCH_DIRECTORY : 0;
564 return match_pathspec_with_flags(istate, ps, name, namelen,
565 prefix, seen, flags);
569 * Check if a submodule is a superset of the pathspec
571 int submodule_path_match(struct index_state *istate,
572 const struct pathspec *ps,
573 const char *submodule_name,
574 char *seen)
576 int matched = match_pathspec_with_flags(istate, ps, submodule_name,
577 strlen(submodule_name),
578 0, seen,
579 DO_MATCH_DIRECTORY |
580 DO_MATCH_LEADING_PATHSPEC);
581 return matched;
584 int report_path_error(const char *ps_matched,
585 const struct pathspec *pathspec)
588 * Make sure all pathspec matched; otherwise it is an error.
590 int num, errors = 0;
591 for (num = 0; num < pathspec->nr; num++) {
592 int other, found_dup;
594 if (ps_matched[num])
595 continue;
597 * The caller might have fed identical pathspec
598 * twice. Do not barf on such a mistake.
599 * FIXME: parse_pathspec should have eliminated
600 * duplicate pathspec.
602 for (found_dup = other = 0;
603 !found_dup && other < pathspec->nr;
604 other++) {
605 if (other == num || !ps_matched[other])
606 continue;
607 if (!strcmp(pathspec->items[other].original,
608 pathspec->items[num].original))
610 * Ok, we have a match already.
612 found_dup = 1;
614 if (found_dup)
615 continue;
617 error(_("pathspec '%s' did not match any file(s) known to git"),
618 pathspec->items[num].original);
619 errors++;
621 return errors;
625 * Return the length of the "simple" part of a path match limiter.
627 int simple_length(const char *match)
629 int len = -1;
631 for (;;) {
632 unsigned char c = *match++;
633 len++;
634 if (c == '\0' || is_glob_special(c))
635 return len;
639 int no_wildcard(const char *string)
641 return string[simple_length(string)] == '\0';
644 void parse_path_pattern(const char **pattern,
645 int *patternlen,
646 unsigned *flags,
647 int *nowildcardlen)
649 const char *p = *pattern;
650 size_t i, len;
652 *flags = 0;
653 if (*p == '!') {
654 *flags |= PATTERN_FLAG_NEGATIVE;
655 p++;
657 len = strlen(p);
658 if (len && p[len - 1] == '/') {
659 len--;
660 *flags |= PATTERN_FLAG_MUSTBEDIR;
662 for (i = 0; i < len; i++) {
663 if (p[i] == '/')
664 break;
666 if (i == len)
667 *flags |= PATTERN_FLAG_NODIR;
668 *nowildcardlen = simple_length(p);
670 * we should have excluded the trailing slash from 'p' too,
671 * but that's one more allocation. Instead just make sure
672 * nowildcardlen does not exceed real patternlen
674 if (*nowildcardlen > len)
675 *nowildcardlen = len;
676 if (*p == '*' && no_wildcard(p + 1))
677 *flags |= PATTERN_FLAG_ENDSWITH;
678 *pattern = p;
679 *patternlen = len;
682 int pl_hashmap_cmp(const void *cmp_data UNUSED,
683 const struct hashmap_entry *a,
684 const struct hashmap_entry *b,
685 const void *key UNUSED)
687 const struct pattern_entry *ee1 =
688 container_of(a, struct pattern_entry, ent);
689 const struct pattern_entry *ee2 =
690 container_of(b, struct pattern_entry, ent);
692 size_t min_len = ee1->patternlen <= ee2->patternlen
693 ? ee1->patternlen
694 : ee2->patternlen;
696 return fspathncmp(ee1->pattern, ee2->pattern, min_len);
699 static char *dup_and_filter_pattern(const char *pattern)
701 char *set, *read;
702 size_t count = 0;
703 char *result = xstrdup(pattern);
705 set = result;
706 read = result;
708 while (*read) {
709 /* skip escape characters (once) */
710 if (*read == '\\')
711 read++;
713 *set = *read;
715 set++;
716 read++;
717 count++;
719 *set = 0;
721 if (count > 2 &&
722 *(set - 1) == '*' &&
723 *(set - 2) == '/')
724 *(set - 2) = 0;
726 return result;
729 static void add_pattern_to_hashsets(struct pattern_list *pl, struct path_pattern *given)
731 struct pattern_entry *translated;
732 char *truncated;
733 char *data = NULL;
734 const char *prev, *cur, *next;
736 if (!pl->use_cone_patterns)
737 return;
739 if (given->flags & PATTERN_FLAG_NEGATIVE &&
740 given->flags & PATTERN_FLAG_MUSTBEDIR &&
741 !strcmp(given->pattern, "/*")) {
742 pl->full_cone = 0;
743 return;
746 if (!given->flags && !strcmp(given->pattern, "/*")) {
747 pl->full_cone = 1;
748 return;
751 if (given->patternlen < 2 ||
752 *given->pattern != '/' ||
753 strstr(given->pattern, "**")) {
754 /* Not a cone pattern. */
755 warning(_("unrecognized pattern: '%s'"), given->pattern);
756 goto clear_hashmaps;
759 if (!(given->flags & PATTERN_FLAG_MUSTBEDIR) &&
760 strcmp(given->pattern, "/*")) {
761 /* Not a cone pattern. */
762 warning(_("unrecognized pattern: '%s'"), given->pattern);
763 goto clear_hashmaps;
766 prev = given->pattern;
767 cur = given->pattern + 1;
768 next = given->pattern + 2;
770 while (*cur) {
771 /* Watch for glob characters '*', '\', '[', '?' */
772 if (!is_glob_special(*cur))
773 goto increment;
775 /* But only if *prev != '\\' */
776 if (*prev == '\\')
777 goto increment;
779 /* But allow the initial '\' */
780 if (*cur == '\\' &&
781 is_glob_special(*next))
782 goto increment;
784 /* But a trailing '/' then '*' is fine */
785 if (*prev == '/' &&
786 *cur == '*' &&
787 *next == 0)
788 goto increment;
790 /* Not a cone pattern. */
791 warning(_("unrecognized pattern: '%s'"), given->pattern);
792 goto clear_hashmaps;
794 increment:
795 prev++;
796 cur++;
797 next++;
800 if (given->patternlen > 2 &&
801 !strcmp(given->pattern + given->patternlen - 2, "/*")) {
802 if (!(given->flags & PATTERN_FLAG_NEGATIVE)) {
803 /* Not a cone pattern. */
804 warning(_("unrecognized pattern: '%s'"), given->pattern);
805 goto clear_hashmaps;
808 truncated = dup_and_filter_pattern(given->pattern);
810 translated = xmalloc(sizeof(struct pattern_entry));
811 translated->pattern = truncated;
812 translated->patternlen = given->patternlen - 2;
813 hashmap_entry_init(&translated->ent,
814 fspathhash(translated->pattern));
816 if (!hashmap_get_entry(&pl->recursive_hashmap,
817 translated, ent, NULL)) {
818 /* We did not see the "parent" included */
819 warning(_("unrecognized negative pattern: '%s'"),
820 given->pattern);
821 free(truncated);
822 free(translated);
823 goto clear_hashmaps;
826 hashmap_add(&pl->parent_hashmap, &translated->ent);
827 hashmap_remove(&pl->recursive_hashmap, &translated->ent, &data);
828 free(data);
829 return;
832 if (given->flags & PATTERN_FLAG_NEGATIVE) {
833 warning(_("unrecognized negative pattern: '%s'"),
834 given->pattern);
835 goto clear_hashmaps;
838 translated = xmalloc(sizeof(struct pattern_entry));
840 translated->pattern = dup_and_filter_pattern(given->pattern);
841 translated->patternlen = given->patternlen;
842 hashmap_entry_init(&translated->ent,
843 fspathhash(translated->pattern));
845 hashmap_add(&pl->recursive_hashmap, &translated->ent);
847 if (hashmap_get_entry(&pl->parent_hashmap, translated, ent, NULL)) {
848 /* we already included this at the parent level */
849 warning(_("your sparse-checkout file may have issues: pattern '%s' is repeated"),
850 given->pattern);
851 goto clear_hashmaps;
854 return;
856 clear_hashmaps:
857 warning(_("disabling cone pattern matching"));
858 hashmap_clear_and_free(&pl->parent_hashmap, struct pattern_entry, ent);
859 hashmap_clear_and_free(&pl->recursive_hashmap, struct pattern_entry, ent);
860 pl->use_cone_patterns = 0;
863 static int hashmap_contains_path(struct hashmap *map,
864 struct strbuf *pattern)
866 struct pattern_entry p;
868 /* Check straight mapping */
869 p.pattern = pattern->buf;
870 p.patternlen = pattern->len;
871 hashmap_entry_init(&p.ent, fspathhash(p.pattern));
872 return !!hashmap_get_entry(map, &p, ent, NULL);
875 int hashmap_contains_parent(struct hashmap *map,
876 const char *path,
877 struct strbuf *buffer)
879 char *slash_pos;
881 strbuf_setlen(buffer, 0);
883 if (path[0] != '/')
884 strbuf_addch(buffer, '/');
886 strbuf_addstr(buffer, path);
888 slash_pos = strrchr(buffer->buf, '/');
890 while (slash_pos > buffer->buf) {
891 strbuf_setlen(buffer, slash_pos - buffer->buf);
893 if (hashmap_contains_path(map, buffer))
894 return 1;
896 slash_pos = strrchr(buffer->buf, '/');
899 return 0;
902 void add_pattern(const char *string, const char *base,
903 int baselen, struct pattern_list *pl, int srcpos)
905 struct path_pattern *pattern;
906 int patternlen;
907 unsigned flags;
908 int nowildcardlen;
910 parse_path_pattern(&string, &patternlen, &flags, &nowildcardlen);
911 if (flags & PATTERN_FLAG_MUSTBEDIR) {
912 FLEXPTR_ALLOC_MEM(pattern, pattern, string, patternlen);
913 } else {
914 pattern = xmalloc(sizeof(*pattern));
915 pattern->pattern = string;
917 pattern->patternlen = patternlen;
918 pattern->nowildcardlen = nowildcardlen;
919 pattern->base = base;
920 pattern->baselen = baselen;
921 pattern->flags = flags;
922 pattern->srcpos = srcpos;
923 ALLOC_GROW(pl->patterns, pl->nr + 1, pl->alloc);
924 pl->patterns[pl->nr++] = pattern;
925 pattern->pl = pl;
927 add_pattern_to_hashsets(pl, pattern);
930 static int read_skip_worktree_file_from_index(struct index_state *istate,
931 const char *path,
932 size_t *size_out, char **data_out,
933 struct oid_stat *oid_stat)
935 int pos, len;
937 len = strlen(path);
938 pos = index_name_pos(istate, path, len);
939 if (pos < 0)
940 return -1;
941 if (!ce_skip_worktree(istate->cache[pos]))
942 return -1;
944 return do_read_blob(&istate->cache[pos]->oid, oid_stat, size_out, data_out);
948 * Frees memory within pl which was allocated for exclude patterns and
949 * the file buffer. Does not free pl itself.
951 void clear_pattern_list(struct pattern_list *pl)
953 int i;
955 for (i = 0; i < pl->nr; i++)
956 free(pl->patterns[i]);
957 free(pl->patterns);
958 free(pl->filebuf);
959 hashmap_clear_and_free(&pl->recursive_hashmap, struct pattern_entry, ent);
960 hashmap_clear_and_free(&pl->parent_hashmap, struct pattern_entry, ent);
962 memset(pl, 0, sizeof(*pl));
965 static void trim_trailing_spaces(char *buf)
967 char *p, *last_space = NULL;
969 for (p = buf; *p; p++)
970 switch (*p) {
971 case ' ':
972 if (!last_space)
973 last_space = p;
974 break;
975 case '\\':
976 p++;
977 if (!*p)
978 return;
979 /* fallthrough */
980 default:
981 last_space = NULL;
984 if (last_space)
985 *last_space = '\0';
989 * Given a subdirectory name and "dir" of the current directory,
990 * search the subdir in "dir" and return it, or create a new one if it
991 * does not exist in "dir".
993 * If "name" has the trailing slash, it'll be excluded in the search.
995 static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc,
996 struct untracked_cache_dir *dir,
997 const char *name, int len)
999 int first, last;
1000 struct untracked_cache_dir *d;
1001 if (!dir)
1002 return NULL;
1003 if (len && name[len - 1] == '/')
1004 len--;
1005 first = 0;
1006 last = dir->dirs_nr;
1007 while (last > first) {
1008 int cmp, next = first + ((last - first) >> 1);
1009 d = dir->dirs[next];
1010 cmp = strncmp(name, d->name, len);
1011 if (!cmp && strlen(d->name) > len)
1012 cmp = -1;
1013 if (!cmp)
1014 return d;
1015 if (cmp < 0) {
1016 last = next;
1017 continue;
1019 first = next+1;
1022 uc->dir_created++;
1023 FLEX_ALLOC_MEM(d, name, name, len);
1025 ALLOC_GROW(dir->dirs, dir->dirs_nr + 1, dir->dirs_alloc);
1026 MOVE_ARRAY(dir->dirs + first + 1, dir->dirs + first,
1027 dir->dirs_nr - first);
1028 dir->dirs_nr++;
1029 dir->dirs[first] = d;
1030 return d;
1033 static void do_invalidate_gitignore(struct untracked_cache_dir *dir)
1035 int i;
1036 dir->valid = 0;
1037 dir->untracked_nr = 0;
1038 for (i = 0; i < dir->dirs_nr; i++)
1039 do_invalidate_gitignore(dir->dirs[i]);
1042 static void invalidate_gitignore(struct untracked_cache *uc,
1043 struct untracked_cache_dir *dir)
1045 uc->gitignore_invalidated++;
1046 do_invalidate_gitignore(dir);
1049 static void invalidate_directory(struct untracked_cache *uc,
1050 struct untracked_cache_dir *dir)
1052 int i;
1055 * Invalidation increment here is just roughly correct. If
1056 * untracked_nr or any of dirs[].recurse is non-zero, we
1057 * should increment dir_invalidated too. But that's more
1058 * expensive to do.
1060 if (dir->valid)
1061 uc->dir_invalidated++;
1063 dir->valid = 0;
1064 dir->untracked_nr = 0;
1065 for (i = 0; i < dir->dirs_nr; i++)
1066 dir->dirs[i]->recurse = 0;
1069 static int add_patterns_from_buffer(char *buf, size_t size,
1070 const char *base, int baselen,
1071 struct pattern_list *pl);
1073 /* Flags for add_patterns() */
1074 #define PATTERN_NOFOLLOW (1<<0)
1077 * Given a file with name "fname", read it (either from disk, or from
1078 * an index if 'istate' is non-null), parse it and store the
1079 * exclude rules in "pl".
1081 * If "oid_stat" is not NULL, compute oid of the exclude file and fill
1082 * stat data from disk (only valid if add_patterns returns zero). If
1083 * oid_stat.valid is non-zero, "oid_stat" must contain good value as input.
1085 static int add_patterns(const char *fname, const char *base, int baselen,
1086 struct pattern_list *pl, struct index_state *istate,
1087 unsigned flags, struct oid_stat *oid_stat)
1089 struct stat st;
1090 int r;
1091 int fd;
1092 size_t size = 0;
1093 char *buf;
1095 if (flags & PATTERN_NOFOLLOW)
1096 fd = open_nofollow(fname, O_RDONLY);
1097 else
1098 fd = open(fname, O_RDONLY);
1100 if (fd < 0 || fstat(fd, &st) < 0) {
1101 if (fd < 0)
1102 warn_on_fopen_errors(fname);
1103 else
1104 close(fd);
1105 if (!istate)
1106 return -1;
1107 r = read_skip_worktree_file_from_index(istate, fname,
1108 &size, &buf,
1109 oid_stat);
1110 if (r != 1)
1111 return r;
1112 } else {
1113 size = xsize_t(st.st_size);
1114 if (size == 0) {
1115 if (oid_stat) {
1116 fill_stat_data(&oid_stat->stat, &st);
1117 oidcpy(&oid_stat->oid, the_hash_algo->empty_blob);
1118 oid_stat->valid = 1;
1120 close(fd);
1121 return 0;
1123 buf = xmallocz(size);
1124 if (read_in_full(fd, buf, size) != size) {
1125 free(buf);
1126 close(fd);
1127 return -1;
1129 buf[size++] = '\n';
1130 close(fd);
1131 if (oid_stat) {
1132 int pos;
1133 if (oid_stat->valid &&
1134 !match_stat_data_racy(istate, &oid_stat->stat, &st))
1135 ; /* no content change, oid_stat->oid still good */
1136 else if (istate &&
1137 (pos = index_name_pos(istate, fname, strlen(fname))) >= 0 &&
1138 !ce_stage(istate->cache[pos]) &&
1139 ce_uptodate(istate->cache[pos]) &&
1140 !would_convert_to_git(istate, fname))
1141 oidcpy(&oid_stat->oid,
1142 &istate->cache[pos]->oid);
1143 else
1144 hash_object_file(the_hash_algo, buf, size,
1145 OBJ_BLOB, &oid_stat->oid);
1146 fill_stat_data(&oid_stat->stat, &st);
1147 oid_stat->valid = 1;
1151 add_patterns_from_buffer(buf, size, base, baselen, pl);
1152 return 0;
1155 static int add_patterns_from_buffer(char *buf, size_t size,
1156 const char *base, int baselen,
1157 struct pattern_list *pl)
1159 int i, lineno = 1;
1160 char *entry;
1162 hashmap_init(&pl->recursive_hashmap, pl_hashmap_cmp, NULL, 0);
1163 hashmap_init(&pl->parent_hashmap, pl_hashmap_cmp, NULL, 0);
1165 pl->filebuf = buf;
1167 if (skip_utf8_bom(&buf, size))
1168 size -= buf - pl->filebuf;
1170 entry = buf;
1172 for (i = 0; i < size; i++) {
1173 if (buf[i] == '\n') {
1174 if (entry != buf + i && entry[0] != '#') {
1175 buf[i - (i && buf[i-1] == '\r')] = 0;
1176 trim_trailing_spaces(entry);
1177 add_pattern(entry, base, baselen, pl, lineno);
1179 lineno++;
1180 entry = buf + i + 1;
1183 return 0;
1186 int add_patterns_from_file_to_list(const char *fname, const char *base,
1187 int baselen, struct pattern_list *pl,
1188 struct index_state *istate,
1189 unsigned flags)
1191 return add_patterns(fname, base, baselen, pl, istate, flags, NULL);
1194 int add_patterns_from_blob_to_list(
1195 struct object_id *oid,
1196 const char *base, int baselen,
1197 struct pattern_list *pl)
1199 char *buf;
1200 size_t size;
1201 int r;
1203 r = do_read_blob(oid, NULL, &size, &buf);
1204 if (r != 1)
1205 return r;
1207 add_patterns_from_buffer(buf, size, base, baselen, pl);
1208 return 0;
1211 struct pattern_list *add_pattern_list(struct dir_struct *dir,
1212 int group_type, const char *src)
1214 struct pattern_list *pl;
1215 struct exclude_list_group *group;
1217 group = &dir->internal.exclude_list_group[group_type];
1218 ALLOC_GROW(group->pl, group->nr + 1, group->alloc);
1219 pl = &group->pl[group->nr++];
1220 memset(pl, 0, sizeof(*pl));
1221 pl->src = src;
1222 return pl;
1226 * Used to set up core.excludesfile and .git/info/exclude lists.
1228 static void add_patterns_from_file_1(struct dir_struct *dir, const char *fname,
1229 struct oid_stat *oid_stat)
1231 struct pattern_list *pl;
1233 * catch setup_standard_excludes() that's called before
1234 * dir->untracked is assigned. That function behaves
1235 * differently when dir->untracked is non-NULL.
1237 if (!dir->untracked)
1238 dir->internal.unmanaged_exclude_files++;
1239 pl = add_pattern_list(dir, EXC_FILE, fname);
1240 if (add_patterns(fname, "", 0, pl, NULL, 0, oid_stat) < 0)
1241 die(_("cannot use %s as an exclude file"), fname);
1244 void add_patterns_from_file(struct dir_struct *dir, const char *fname)
1246 dir->internal.unmanaged_exclude_files++; /* see validate_untracked_cache() */
1247 add_patterns_from_file_1(dir, fname, NULL);
1250 int match_basename(const char *basename, int basenamelen,
1251 const char *pattern, int prefix, int patternlen,
1252 unsigned flags)
1254 if (prefix == patternlen) {
1255 if (patternlen == basenamelen &&
1256 !fspathncmp(pattern, basename, basenamelen))
1257 return 1;
1258 } else if (flags & PATTERN_FLAG_ENDSWITH) {
1259 /* "*literal" matching against "fooliteral" */
1260 if (patternlen - 1 <= basenamelen &&
1261 !fspathncmp(pattern + 1,
1262 basename + basenamelen - (patternlen - 1),
1263 patternlen - 1))
1264 return 1;
1265 } else {
1266 if (fnmatch_icase_mem(pattern, patternlen,
1267 basename, basenamelen,
1268 0) == 0)
1269 return 1;
1271 return 0;
1274 int match_pathname(const char *pathname, int pathlen,
1275 const char *base, int baselen,
1276 const char *pattern, int prefix, int patternlen)
1278 const char *name;
1279 int namelen;
1282 * match with FNM_PATHNAME; the pattern has base implicitly
1283 * in front of it.
1285 if (*pattern == '/') {
1286 pattern++;
1287 patternlen--;
1288 prefix--;
1292 * baselen does not count the trailing slash. base[] may or
1293 * may not end with a trailing slash though.
1295 if (pathlen < baselen + 1 ||
1296 (baselen && pathname[baselen] != '/') ||
1297 fspathncmp(pathname, base, baselen))
1298 return 0;
1300 namelen = baselen ? pathlen - baselen - 1 : pathlen;
1301 name = pathname + pathlen - namelen;
1303 if (prefix) {
1305 * if the non-wildcard part is longer than the
1306 * remaining pathname, surely it cannot match.
1308 if (prefix > namelen)
1309 return 0;
1311 if (fspathncmp(pattern, name, prefix))
1312 return 0;
1313 pattern += prefix;
1314 patternlen -= prefix;
1315 name += prefix;
1316 namelen -= prefix;
1319 * If the whole pattern did not have a wildcard,
1320 * then our prefix match is all we need; we
1321 * do not need to call fnmatch at all.
1323 if (!patternlen && !namelen)
1324 return 1;
1327 return fnmatch_icase_mem(pattern, patternlen,
1328 name, namelen,
1329 WM_PATHNAME) == 0;
1333 * Scan the given exclude list in reverse to see whether pathname
1334 * should be ignored. The first match (i.e. the last on the list), if
1335 * any, determines the fate. Returns the exclude_list element which
1336 * matched, or NULL for undecided.
1338 static struct path_pattern *last_matching_pattern_from_list(const char *pathname,
1339 int pathlen,
1340 const char *basename,
1341 int *dtype,
1342 struct pattern_list *pl,
1343 struct index_state *istate)
1345 struct path_pattern *res = NULL; /* undecided */
1346 int i;
1348 if (!pl->nr)
1349 return NULL; /* undefined */
1351 for (i = pl->nr - 1; 0 <= i; i--) {
1352 struct path_pattern *pattern = pl->patterns[i];
1353 const char *exclude = pattern->pattern;
1354 int prefix = pattern->nowildcardlen;
1356 if (pattern->flags & PATTERN_FLAG_MUSTBEDIR) {
1357 *dtype = resolve_dtype(*dtype, istate, pathname, pathlen);
1358 if (*dtype != DT_DIR)
1359 continue;
1362 if (pattern->flags & PATTERN_FLAG_NODIR) {
1363 if (match_basename(basename,
1364 pathlen - (basename - pathname),
1365 exclude, prefix, pattern->patternlen,
1366 pattern->flags)) {
1367 res = pattern;
1368 break;
1370 continue;
1373 assert(pattern->baselen == 0 ||
1374 pattern->base[pattern->baselen - 1] == '/');
1375 if (match_pathname(pathname, pathlen,
1376 pattern->base,
1377 pattern->baselen ? pattern->baselen - 1 : 0,
1378 exclude, prefix, pattern->patternlen)) {
1379 res = pattern;
1380 break;
1383 return res;
1387 * Scan the list of patterns to determine if the ordered list
1388 * of patterns matches on 'pathname'.
1390 * Return 1 for a match, 0 for not matched and -1 for undecided.
1392 enum pattern_match_result path_matches_pattern_list(
1393 const char *pathname, int pathlen,
1394 const char *basename, int *dtype,
1395 struct pattern_list *pl,
1396 struct index_state *istate)
1398 struct path_pattern *pattern;
1399 struct strbuf parent_pathname = STRBUF_INIT;
1400 int result = NOT_MATCHED;
1401 size_t slash_pos;
1403 if (!pl->use_cone_patterns) {
1404 pattern = last_matching_pattern_from_list(pathname, pathlen, basename,
1405 dtype, pl, istate);
1406 if (pattern) {
1407 if (pattern->flags & PATTERN_FLAG_NEGATIVE)
1408 return NOT_MATCHED;
1409 else
1410 return MATCHED;
1413 return UNDECIDED;
1416 if (pl->full_cone)
1417 return MATCHED;
1419 strbuf_addch(&parent_pathname, '/');
1420 strbuf_add(&parent_pathname, pathname, pathlen);
1423 * Directory entries are matched if and only if a file
1424 * contained immediately within them is matched. For the
1425 * case of a directory entry, modify the path to create
1426 * a fake filename within this directory, allowing us to
1427 * use the file-base matching logic in an equivalent way.
1429 if (parent_pathname.len > 0 &&
1430 parent_pathname.buf[parent_pathname.len - 1] == '/') {
1431 slash_pos = parent_pathname.len - 1;
1432 strbuf_add(&parent_pathname, "-", 1);
1433 } else {
1434 const char *slash_ptr = strrchr(parent_pathname.buf, '/');
1435 slash_pos = slash_ptr ? slash_ptr - parent_pathname.buf : 0;
1438 if (hashmap_contains_path(&pl->recursive_hashmap,
1439 &parent_pathname)) {
1440 result = MATCHED_RECURSIVE;
1441 goto done;
1444 if (!slash_pos) {
1445 /* include every file in root */
1446 result = MATCHED;
1447 goto done;
1450 strbuf_setlen(&parent_pathname, slash_pos);
1452 if (hashmap_contains_path(&pl->parent_hashmap, &parent_pathname)) {
1453 result = MATCHED;
1454 goto done;
1457 if (hashmap_contains_parent(&pl->recursive_hashmap,
1458 pathname,
1459 &parent_pathname))
1460 result = MATCHED_RECURSIVE;
1462 done:
1463 strbuf_release(&parent_pathname);
1464 return result;
1467 int init_sparse_checkout_patterns(struct index_state *istate)
1469 if (!core_apply_sparse_checkout)
1470 return 1;
1471 if (istate->sparse_checkout_patterns)
1472 return 0;
1474 CALLOC_ARRAY(istate->sparse_checkout_patterns, 1);
1476 if (get_sparse_checkout_patterns(istate->sparse_checkout_patterns) < 0) {
1477 FREE_AND_NULL(istate->sparse_checkout_patterns);
1478 return -1;
1481 return 0;
1484 static int path_in_sparse_checkout_1(const char *path,
1485 struct index_state *istate,
1486 int require_cone_mode)
1488 int dtype = DT_REG;
1489 enum pattern_match_result match = UNDECIDED;
1490 const char *end, *slash;
1493 * We default to accepting a path if the path is empty, there are no
1494 * patterns, or the patterns are of the wrong type.
1496 if (!*path ||
1497 init_sparse_checkout_patterns(istate) ||
1498 (require_cone_mode &&
1499 !istate->sparse_checkout_patterns->use_cone_patterns))
1500 return 1;
1503 * If UNDECIDED, use the match from the parent dir (recursively), or
1504 * fall back to NOT_MATCHED at the topmost level. Note that cone mode
1505 * never returns UNDECIDED, so we will execute only one iteration in
1506 * this case.
1508 for (end = path + strlen(path);
1509 end > path && match == UNDECIDED;
1510 end = slash) {
1512 for (slash = end - 1; slash > path && *slash != '/'; slash--)
1513 ; /* do nothing */
1515 match = path_matches_pattern_list(path, end - path,
1516 slash > path ? slash + 1 : path, &dtype,
1517 istate->sparse_checkout_patterns, istate);
1519 /* We are going to match the parent dir now */
1520 dtype = DT_DIR;
1522 return match > 0;
1525 int path_in_sparse_checkout(const char *path,
1526 struct index_state *istate)
1528 return path_in_sparse_checkout_1(path, istate, 0);
1531 int path_in_cone_mode_sparse_checkout(const char *path,
1532 struct index_state *istate)
1534 return path_in_sparse_checkout_1(path, istate, 1);
1537 static struct path_pattern *last_matching_pattern_from_lists(
1538 struct dir_struct *dir, struct index_state *istate,
1539 const char *pathname, int pathlen,
1540 const char *basename, int *dtype_p)
1542 int i, j;
1543 struct exclude_list_group *group;
1544 struct path_pattern *pattern;
1545 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
1546 group = &dir->internal.exclude_list_group[i];
1547 for (j = group->nr - 1; j >= 0; j--) {
1548 pattern = last_matching_pattern_from_list(
1549 pathname, pathlen, basename, dtype_p,
1550 &group->pl[j], istate);
1551 if (pattern)
1552 return pattern;
1555 return NULL;
1559 * Loads the per-directory exclude list for the substring of base
1560 * which has a char length of baselen.
1562 static void prep_exclude(struct dir_struct *dir,
1563 struct index_state *istate,
1564 const char *base, int baselen)
1566 struct exclude_list_group *group;
1567 struct pattern_list *pl;
1568 struct exclude_stack *stk = NULL;
1569 struct untracked_cache_dir *untracked;
1570 int current;
1572 group = &dir->internal.exclude_list_group[EXC_DIRS];
1575 * Pop the exclude lists from the EXCL_DIRS exclude_list_group
1576 * which originate from directories not in the prefix of the
1577 * path being checked.
1579 while ((stk = dir->internal.exclude_stack) != NULL) {
1580 if (stk->baselen <= baselen &&
1581 !strncmp(dir->internal.basebuf.buf, base, stk->baselen))
1582 break;
1583 pl = &group->pl[dir->internal.exclude_stack->exclude_ix];
1584 dir->internal.exclude_stack = stk->prev;
1585 dir->internal.pattern = NULL;
1586 free((char *)pl->src); /* see strbuf_detach() below */
1587 clear_pattern_list(pl);
1588 free(stk);
1589 group->nr--;
1592 /* Skip traversing into sub directories if the parent is excluded */
1593 if (dir->internal.pattern)
1594 return;
1597 * Lazy initialization. All call sites currently just
1598 * memset(dir, 0, sizeof(*dir)) before use. Changing all of
1599 * them seems lots of work for little benefit.
1601 if (!dir->internal.basebuf.buf)
1602 strbuf_init(&dir->internal.basebuf, PATH_MAX);
1604 /* Read from the parent directories and push them down. */
1605 current = stk ? stk->baselen : -1;
1606 strbuf_setlen(&dir->internal.basebuf, current < 0 ? 0 : current);
1607 if (dir->untracked)
1608 untracked = stk ? stk->ucd : dir->untracked->root;
1609 else
1610 untracked = NULL;
1612 while (current < baselen) {
1613 const char *cp;
1614 struct oid_stat oid_stat;
1616 CALLOC_ARRAY(stk, 1);
1617 if (current < 0) {
1618 cp = base;
1619 current = 0;
1620 } else {
1621 cp = strchr(base + current + 1, '/');
1622 if (!cp)
1623 die("oops in prep_exclude");
1624 cp++;
1625 untracked =
1626 lookup_untracked(dir->untracked,
1627 untracked,
1628 base + current,
1629 cp - base - current);
1631 stk->prev = dir->internal.exclude_stack;
1632 stk->baselen = cp - base;
1633 stk->exclude_ix = group->nr;
1634 stk->ucd = untracked;
1635 pl = add_pattern_list(dir, EXC_DIRS, NULL);
1636 strbuf_add(&dir->internal.basebuf, base + current, stk->baselen - current);
1637 assert(stk->baselen == dir->internal.basebuf.len);
1639 /* Abort if the directory is excluded */
1640 if (stk->baselen) {
1641 int dt = DT_DIR;
1642 dir->internal.basebuf.buf[stk->baselen - 1] = 0;
1643 dir->internal.pattern = last_matching_pattern_from_lists(dir,
1644 istate,
1645 dir->internal.basebuf.buf, stk->baselen - 1,
1646 dir->internal.basebuf.buf + current, &dt);
1647 dir->internal.basebuf.buf[stk->baselen - 1] = '/';
1648 if (dir->internal.pattern &&
1649 dir->internal.pattern->flags & PATTERN_FLAG_NEGATIVE)
1650 dir->internal.pattern = NULL;
1651 if (dir->internal.pattern) {
1652 dir->internal.exclude_stack = stk;
1653 return;
1657 /* Try to read per-directory file */
1658 oidclr(&oid_stat.oid);
1659 oid_stat.valid = 0;
1660 if (dir->exclude_per_dir &&
1662 * If we know that no files have been added in
1663 * this directory (i.e. valid_cached_dir() has
1664 * been executed and set untracked->valid) ..
1666 (!untracked || !untracked->valid ||
1668 * .. and .gitignore does not exist before
1669 * (i.e. null exclude_oid). Then we can skip
1670 * loading .gitignore, which would result in
1671 * ENOENT anyway.
1673 !is_null_oid(&untracked->exclude_oid))) {
1675 * dir->internal.basebuf gets reused by the traversal,
1676 * but we need fname to remain unchanged to ensure the
1677 * src member of each struct path_pattern correctly
1678 * back-references its source file. Other invocations
1679 * of add_pattern_list provide stable strings, so we
1680 * strbuf_detach() and free() here in the caller.
1682 struct strbuf sb = STRBUF_INIT;
1683 strbuf_addbuf(&sb, &dir->internal.basebuf);
1684 strbuf_addstr(&sb, dir->exclude_per_dir);
1685 pl->src = strbuf_detach(&sb, NULL);
1686 add_patterns(pl->src, pl->src, stk->baselen, pl, istate,
1687 PATTERN_NOFOLLOW,
1688 untracked ? &oid_stat : NULL);
1691 * NEEDSWORK: when untracked cache is enabled, prep_exclude()
1692 * will first be called in valid_cached_dir() then maybe many
1693 * times more in last_matching_pattern(). When the cache is
1694 * used, last_matching_pattern() will not be called and
1695 * reading .gitignore content will be a waste.
1697 * So when it's called by valid_cached_dir() and we can get
1698 * .gitignore SHA-1 from the index (i.e. .gitignore is not
1699 * modified on work tree), we could delay reading the
1700 * .gitignore content until we absolutely need it in
1701 * last_matching_pattern(). Be careful about ignore rule
1702 * order, though, if you do that.
1704 if (untracked &&
1705 !oideq(&oid_stat.oid, &untracked->exclude_oid)) {
1706 invalidate_gitignore(dir->untracked, untracked);
1707 oidcpy(&untracked->exclude_oid, &oid_stat.oid);
1709 dir->internal.exclude_stack = stk;
1710 current = stk->baselen;
1712 strbuf_setlen(&dir->internal.basebuf, baselen);
1716 * Loads the exclude lists for the directory containing pathname, then
1717 * scans all exclude lists to determine whether pathname is excluded.
1718 * Returns the exclude_list element which matched, or NULL for
1719 * undecided.
1721 struct path_pattern *last_matching_pattern(struct dir_struct *dir,
1722 struct index_state *istate,
1723 const char *pathname,
1724 int *dtype_p)
1726 int pathlen = strlen(pathname);
1727 const char *basename = strrchr(pathname, '/');
1728 basename = (basename) ? basename+1 : pathname;
1730 prep_exclude(dir, istate, pathname, basename-pathname);
1732 if (dir->internal.pattern)
1733 return dir->internal.pattern;
1735 return last_matching_pattern_from_lists(dir, istate, pathname, pathlen,
1736 basename, dtype_p);
1740 * Loads the exclude lists for the directory containing pathname, then
1741 * scans all exclude lists to determine whether pathname is excluded.
1742 * Returns 1 if true, otherwise 0.
1744 int is_excluded(struct dir_struct *dir, struct index_state *istate,
1745 const char *pathname, int *dtype_p)
1747 struct path_pattern *pattern =
1748 last_matching_pattern(dir, istate, pathname, dtype_p);
1749 if (pattern)
1750 return pattern->flags & PATTERN_FLAG_NEGATIVE ? 0 : 1;
1751 return 0;
1754 static struct dir_entry *dir_entry_new(const char *pathname, int len)
1756 struct dir_entry *ent;
1758 FLEX_ALLOC_MEM(ent, name, pathname, len);
1759 ent->len = len;
1760 return ent;
1763 static struct dir_entry *dir_add_name(struct dir_struct *dir,
1764 struct index_state *istate,
1765 const char *pathname, int len)
1767 if (index_file_exists(istate, pathname, len, ignore_case))
1768 return NULL;
1770 ALLOC_GROW(dir->entries, dir->nr+1, dir->internal.alloc);
1771 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
1774 struct dir_entry *dir_add_ignored(struct dir_struct *dir,
1775 struct index_state *istate,
1776 const char *pathname, int len)
1778 if (!index_name_is_other(istate, pathname, len))
1779 return NULL;
1781 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->internal.ignored_alloc);
1782 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
1785 enum exist_status {
1786 index_nonexistent = 0,
1787 index_directory,
1788 index_gitdir
1792 * Do not use the alphabetically sorted index to look up
1793 * the directory name; instead, use the case insensitive
1794 * directory hash.
1796 static enum exist_status directory_exists_in_index_icase(struct index_state *istate,
1797 const char *dirname, int len)
1799 struct cache_entry *ce;
1801 if (index_dir_exists(istate, dirname, len))
1802 return index_directory;
1804 ce = index_file_exists(istate, dirname, len, ignore_case);
1805 if (ce && S_ISGITLINK(ce->ce_mode))
1806 return index_gitdir;
1808 return index_nonexistent;
1812 * The index sorts alphabetically by entry name, which
1813 * means that a gitlink sorts as '\0' at the end, while
1814 * a directory (which is defined not as an entry, but as
1815 * the files it contains) will sort with the '/' at the
1816 * end.
1818 static enum exist_status directory_exists_in_index(struct index_state *istate,
1819 const char *dirname, int len)
1821 int pos;
1823 if (ignore_case)
1824 return directory_exists_in_index_icase(istate, dirname, len);
1826 pos = index_name_pos(istate, dirname, len);
1827 if (pos < 0)
1828 pos = -pos-1;
1829 while (pos < istate->cache_nr) {
1830 const struct cache_entry *ce = istate->cache[pos++];
1831 unsigned char endchar;
1833 if (strncmp(ce->name, dirname, len))
1834 break;
1835 endchar = ce->name[len];
1836 if (endchar > '/')
1837 break;
1838 if (endchar == '/')
1839 return index_directory;
1840 if (!endchar && S_ISGITLINK(ce->ce_mode))
1841 return index_gitdir;
1843 return index_nonexistent;
1847 * When we find a directory when traversing the filesystem, we
1848 * have three distinct cases:
1850 * - ignore it
1851 * - see it as a directory
1852 * - recurse into it
1854 * and which one we choose depends on a combination of existing
1855 * git index contents and the flags passed into the directory
1856 * traversal routine.
1858 * Case 1: If we *already* have entries in the index under that
1859 * directory name, we always recurse into the directory to see
1860 * all the files.
1862 * Case 2: If we *already* have that directory name as a gitlink,
1863 * we always continue to see it as a gitlink, regardless of whether
1864 * there is an actual git directory there or not (it might not
1865 * be checked out as a subproject!)
1867 * Case 3: if we didn't have it in the index previously, we
1868 * have a few sub-cases:
1870 * (a) if DIR_SHOW_OTHER_DIRECTORIES flag is set, we show it as
1871 * just a directory, unless DIR_HIDE_EMPTY_DIRECTORIES is
1872 * also true, in which case we need to check if it contains any
1873 * untracked and / or ignored files.
1874 * (b) if it looks like a git directory and we don't have the
1875 * DIR_NO_GITLINKS flag, then we treat it as a gitlink, and
1876 * show it as a directory.
1877 * (c) otherwise, we recurse into it.
1879 static enum path_treatment treat_directory(struct dir_struct *dir,
1880 struct index_state *istate,
1881 struct untracked_cache_dir *untracked,
1882 const char *dirname, int len, int baselen, int excluded,
1883 const struct pathspec *pathspec)
1886 * WARNING: From this function, you can return path_recurse or you
1887 * can call read_directory_recursive() (or neither), but
1888 * you CAN'T DO BOTH.
1890 enum path_treatment state;
1891 int matches_how = 0;
1892 int check_only, stop_early;
1893 int old_ignored_nr, old_untracked_nr;
1894 /* The "len-1" is to strip the final '/' */
1895 enum exist_status status = directory_exists_in_index(istate, dirname, len-1);
1897 if (status == index_directory)
1898 return path_recurse;
1899 if (status == index_gitdir)
1900 return path_none;
1901 if (status != index_nonexistent)
1902 BUG("Unhandled value for directory_exists_in_index: %d\n", status);
1905 * We don't want to descend into paths that don't match the necessary
1906 * patterns. Clearly, if we don't have a pathspec, then we can't check
1907 * for matching patterns. Also, if (excluded) then we know we matched
1908 * the exclusion patterns so as an optimization we can skip checking
1909 * for matching patterns.
1911 if (pathspec && !excluded) {
1912 matches_how = match_pathspec_with_flags(istate, pathspec,
1913 dirname, len,
1914 0 /* prefix */,
1915 NULL /* seen */,
1916 DO_MATCH_LEADING_PATHSPEC);
1917 if (!matches_how)
1918 return path_none;
1922 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
1923 !(dir->flags & DIR_NO_GITLINKS)) {
1925 * Determine if `dirname` is a nested repo by confirming that:
1926 * 1) we are in a nonbare repository, and
1927 * 2) `dirname` is not an immediate parent of `the_repository->gitdir`,
1928 * which could occur if the git_dir or worktree location was
1929 * manually configured by the user; see t2205 testcases 1-3 for
1930 * examples where this matters
1932 int nested_repo;
1933 struct strbuf sb = STRBUF_INIT;
1934 strbuf_addstr(&sb, dirname);
1935 nested_repo = is_nonbare_repository_dir(&sb);
1937 if (nested_repo) {
1938 char *real_dirname, *real_gitdir;
1939 strbuf_addstr(&sb, ".git");
1940 real_dirname = real_pathdup(sb.buf, 1);
1941 real_gitdir = real_pathdup(the_repository->gitdir, 1);
1943 nested_repo = !!strcmp(real_dirname, real_gitdir);
1944 free(real_gitdir);
1945 free(real_dirname);
1947 strbuf_release(&sb);
1949 if (nested_repo) {
1950 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
1951 (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC))
1952 return path_none;
1953 return excluded ? path_excluded : path_untracked;
1957 if (!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)) {
1958 if (excluded &&
1959 (dir->flags & DIR_SHOW_IGNORED_TOO) &&
1960 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING)) {
1963 * This is an excluded directory and we are
1964 * showing ignored paths that match an exclude
1965 * pattern. (e.g. show directory as ignored
1966 * only if it matches an exclude pattern).
1967 * This path will either be 'path_excluded`
1968 * (if we are showing empty directories or if
1969 * the directory is not empty), or will be
1970 * 'path_none' (empty directory, and we are
1971 * not showing empty directories).
1973 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1974 return path_excluded;
1976 if (read_directory_recursive(dir, istate, dirname, len,
1977 untracked, 1, 1, pathspec) == path_excluded)
1978 return path_excluded;
1980 return path_none;
1982 return path_recurse;
1985 assert(dir->flags & DIR_SHOW_OTHER_DIRECTORIES);
1988 * If we have a pathspec which could match something _below_ this
1989 * directory (e.g. when checking 'subdir/' having a pathspec like
1990 * 'subdir/some/deep/path/file' or 'subdir/widget-*.c'), then we
1991 * need to recurse.
1993 if (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC)
1994 return path_recurse;
1996 /* Special cases for where this directory is excluded/ignored */
1997 if (excluded) {
1999 * If DIR_SHOW_OTHER_DIRECTORIES is set and we're not
2000 * hiding empty directories, there is no need to
2001 * recurse into an ignored directory.
2003 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
2004 return path_excluded;
2007 * Even if we are hiding empty directories, we can still avoid
2008 * recursing into ignored directories for DIR_SHOW_IGNORED_TOO
2009 * if DIR_SHOW_IGNORED_TOO_MODE_MATCHING is also set.
2011 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
2012 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING))
2013 return path_excluded;
2017 * Other than the path_recurse case above, we only need to
2018 * recurse into untracked directories if any of the following
2019 * bits is set:
2020 * - DIR_SHOW_IGNORED (because then we need to determine if
2021 * there are ignored entries below)
2022 * - DIR_SHOW_IGNORED_TOO (same as above)
2023 * - DIR_HIDE_EMPTY_DIRECTORIES (because we have to determine if
2024 * the directory is empty)
2026 if (!excluded &&
2027 !(dir->flags & (DIR_SHOW_IGNORED |
2028 DIR_SHOW_IGNORED_TOO |
2029 DIR_HIDE_EMPTY_DIRECTORIES))) {
2030 return path_untracked;
2034 * Even if we don't want to know all the paths under an untracked or
2035 * ignored directory, we may still need to go into the directory to
2036 * determine if it is empty (because with DIR_HIDE_EMPTY_DIRECTORIES,
2037 * an empty directory should be path_none instead of path_excluded or
2038 * path_untracked).
2040 check_only = ((dir->flags & DIR_HIDE_EMPTY_DIRECTORIES) &&
2041 !(dir->flags & DIR_SHOW_IGNORED_TOO));
2044 * However, there's another optimization possible as a subset of
2045 * check_only, based on the cases we have to consider:
2046 * A) Directory matches no exclude patterns:
2047 * * Directory is empty => path_none
2048 * * Directory has an untracked file under it => path_untracked
2049 * * Directory has only ignored files under it => path_excluded
2050 * B) Directory matches an exclude pattern:
2051 * * Directory is empty => path_none
2052 * * Directory has an untracked file under it => path_excluded
2053 * * Directory has only ignored files under it => path_excluded
2054 * In case A, we can exit as soon as we've found an untracked
2055 * file but otherwise have to walk all files. In case B, though,
2056 * we can stop at the first file we find under the directory.
2058 stop_early = check_only && excluded;
2061 * If /every/ file within an untracked directory is ignored, then
2062 * we want to treat the directory as ignored (for e.g. status
2063 * --porcelain), without listing the individual ignored files
2064 * underneath. To do so, we'll save the current ignored_nr, and
2065 * pop all the ones added after it if it turns out the entire
2066 * directory is ignored. Also, when DIR_SHOW_IGNORED_TOO and
2067 * !DIR_KEEP_UNTRACKED_CONTENTS then we don't want to show
2068 * untracked paths so will need to pop all those off the last
2069 * after we traverse.
2071 old_ignored_nr = dir->ignored_nr;
2072 old_untracked_nr = dir->nr;
2074 /* Actually recurse into dirname now, we'll fixup the state later. */
2075 untracked = lookup_untracked(dir->untracked, untracked,
2076 dirname + baselen, len - baselen);
2077 state = read_directory_recursive(dir, istate, dirname, len, untracked,
2078 check_only, stop_early, pathspec);
2080 /* There are a variety of reasons we may need to fixup the state... */
2081 if (state == path_excluded) {
2082 /* state == path_excluded implies all paths under
2083 * dirname were ignored...
2085 * if running e.g. `git status --porcelain --ignored=matching`,
2086 * then we want to see the subpaths that are ignored.
2088 * if running e.g. just `git status --porcelain`, then
2089 * we just want the directory itself to be listed as ignored
2090 * and not the individual paths underneath.
2092 int want_ignored_subpaths =
2093 ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
2094 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING));
2096 if (want_ignored_subpaths) {
2098 * with --ignored=matching, we want the subpaths
2099 * INSTEAD of the directory itself.
2101 state = path_none;
2102 } else {
2103 int i;
2104 for (i = old_ignored_nr + 1; i<dir->ignored_nr; ++i)
2105 FREE_AND_NULL(dir->ignored[i]);
2106 dir->ignored_nr = old_ignored_nr;
2111 * We may need to ignore some of the untracked paths we found while
2112 * traversing subdirectories.
2114 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
2115 !(dir->flags & DIR_KEEP_UNTRACKED_CONTENTS)) {
2116 int i;
2117 for (i = old_untracked_nr + 1; i<dir->nr; ++i)
2118 FREE_AND_NULL(dir->entries[i]);
2119 dir->nr = old_untracked_nr;
2123 * If there is nothing under the current directory and we are not
2124 * hiding empty directories, then we need to report on the
2125 * untracked or ignored status of the directory itself.
2127 if (state == path_none && !(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
2128 state = excluded ? path_excluded : path_untracked;
2130 return state;
2134 * This is an inexact early pruning of any recursive directory
2135 * reading - if the path cannot possibly be in the pathspec,
2136 * return true, and we'll skip it early.
2138 static int simplify_away(const char *path, int pathlen,
2139 const struct pathspec *pathspec)
2141 int i;
2143 if (!pathspec || !pathspec->nr)
2144 return 0;
2146 GUARD_PATHSPEC(pathspec,
2147 PATHSPEC_FROMTOP |
2148 PATHSPEC_MAXDEPTH |
2149 PATHSPEC_LITERAL |
2150 PATHSPEC_GLOB |
2151 PATHSPEC_ICASE |
2152 PATHSPEC_EXCLUDE |
2153 PATHSPEC_ATTR);
2155 for (i = 0; i < pathspec->nr; i++) {
2156 const struct pathspec_item *item = &pathspec->items[i];
2157 int len = item->nowildcard_len;
2159 if (len > pathlen)
2160 len = pathlen;
2161 if (!ps_strncmp(item, item->match, path, len))
2162 return 0;
2165 return 1;
2169 * This function tells us whether an excluded path matches a
2170 * list of "interesting" pathspecs. That is, whether a path matched
2171 * by any of the pathspecs could possibly be ignored by excluding
2172 * the specified path. This can happen if:
2174 * 1. the path is mentioned explicitly in the pathspec
2176 * 2. the path is a directory prefix of some element in the
2177 * pathspec
2179 static int exclude_matches_pathspec(const char *path, int pathlen,
2180 const struct pathspec *pathspec)
2182 int i;
2184 if (!pathspec || !pathspec->nr)
2185 return 0;
2187 GUARD_PATHSPEC(pathspec,
2188 PATHSPEC_FROMTOP |
2189 PATHSPEC_MAXDEPTH |
2190 PATHSPEC_LITERAL |
2191 PATHSPEC_GLOB |
2192 PATHSPEC_ICASE |
2193 PATHSPEC_EXCLUDE |
2194 PATHSPEC_ATTR);
2196 for (i = 0; i < pathspec->nr; i++) {
2197 const struct pathspec_item *item = &pathspec->items[i];
2198 int len = item->nowildcard_len;
2200 if (len == pathlen &&
2201 !ps_strncmp(item, item->match, path, pathlen))
2202 return 1;
2203 if (len > pathlen &&
2204 item->match[pathlen] == '/' &&
2205 !ps_strncmp(item, item->match, path, pathlen))
2206 return 1;
2208 return 0;
2211 static int get_index_dtype(struct index_state *istate,
2212 const char *path, int len)
2214 int pos;
2215 const struct cache_entry *ce;
2217 ce = index_file_exists(istate, path, len, 0);
2218 if (ce) {
2219 if (!ce_uptodate(ce))
2220 return DT_UNKNOWN;
2221 if (S_ISGITLINK(ce->ce_mode))
2222 return DT_DIR;
2224 * Nobody actually cares about the
2225 * difference between DT_LNK and DT_REG
2227 return DT_REG;
2230 /* Try to look it up as a directory */
2231 pos = index_name_pos(istate, path, len);
2232 if (pos >= 0)
2233 return DT_UNKNOWN;
2234 pos = -pos-1;
2235 while (pos < istate->cache_nr) {
2236 ce = istate->cache[pos++];
2237 if (strncmp(ce->name, path, len))
2238 break;
2239 if (ce->name[len] > '/')
2240 break;
2241 if (ce->name[len] < '/')
2242 continue;
2243 if (!ce_uptodate(ce))
2244 break; /* continue? */
2245 return DT_DIR;
2247 return DT_UNKNOWN;
2250 unsigned char get_dtype(struct dirent *e, struct strbuf *path,
2251 int follow_symlink)
2253 struct stat st;
2254 unsigned char dtype = DTYPE(e);
2255 size_t base_path_len;
2257 if (dtype != DT_UNKNOWN && !(follow_symlink && dtype == DT_LNK))
2258 return dtype;
2261 * d_type unknown or unfollowed symlink, try to fall back on [l]stat
2262 * results. If [l]stat fails, explicitly set DT_UNKNOWN.
2264 base_path_len = path->len;
2265 strbuf_addstr(path, e->d_name);
2266 if ((follow_symlink && stat(path->buf, &st)) ||
2267 (!follow_symlink && lstat(path->buf, &st)))
2268 goto cleanup;
2270 /* determine d_type from st_mode */
2271 if (S_ISREG(st.st_mode))
2272 dtype = DT_REG;
2273 else if (S_ISDIR(st.st_mode))
2274 dtype = DT_DIR;
2275 else if (S_ISLNK(st.st_mode))
2276 dtype = DT_LNK;
2278 cleanup:
2279 strbuf_setlen(path, base_path_len);
2280 return dtype;
2283 static int resolve_dtype(int dtype, struct index_state *istate,
2284 const char *path, int len)
2286 struct stat st;
2288 if (dtype != DT_UNKNOWN)
2289 return dtype;
2290 dtype = get_index_dtype(istate, path, len);
2291 if (dtype != DT_UNKNOWN)
2292 return dtype;
2293 if (lstat(path, &st))
2294 return dtype;
2295 if (S_ISREG(st.st_mode))
2296 return DT_REG;
2297 if (S_ISDIR(st.st_mode))
2298 return DT_DIR;
2299 if (S_ISLNK(st.st_mode))
2300 return DT_LNK;
2301 return dtype;
2304 static enum path_treatment treat_path_fast(struct dir_struct *dir,
2305 struct cached_dir *cdir,
2306 struct index_state *istate,
2307 struct strbuf *path,
2308 int baselen,
2309 const struct pathspec *pathspec)
2312 * WARNING: From this function, you can return path_recurse or you
2313 * can call read_directory_recursive() (or neither), but
2314 * you CAN'T DO BOTH.
2316 strbuf_setlen(path, baselen);
2317 if (!cdir->ucd) {
2318 strbuf_addstr(path, cdir->file);
2319 return path_untracked;
2321 strbuf_addstr(path, cdir->ucd->name);
2322 /* treat_one_path() does this before it calls treat_directory() */
2323 strbuf_complete(path, '/');
2324 if (cdir->ucd->check_only)
2326 * check_only is set as a result of treat_directory() getting
2327 * to its bottom. Verify again the same set of directories
2328 * with check_only set.
2330 return read_directory_recursive(dir, istate, path->buf, path->len,
2331 cdir->ucd, 1, 0, pathspec);
2333 * We get path_recurse in the first run when
2334 * directory_exists_in_index() returns index_nonexistent. We
2335 * are sure that new changes in the index does not impact the
2336 * outcome. Return now.
2338 return path_recurse;
2341 static enum path_treatment treat_path(struct dir_struct *dir,
2342 struct untracked_cache_dir *untracked,
2343 struct cached_dir *cdir,
2344 struct index_state *istate,
2345 struct strbuf *path,
2346 int baselen,
2347 const struct pathspec *pathspec)
2349 int has_path_in_index, dtype, excluded;
2351 if (!cdir->d_name)
2352 return treat_path_fast(dir, cdir, istate, path,
2353 baselen, pathspec);
2354 if (is_dot_or_dotdot(cdir->d_name) || !fspathcmp(cdir->d_name, ".git"))
2355 return path_none;
2356 strbuf_setlen(path, baselen);
2357 strbuf_addstr(path, cdir->d_name);
2358 if (simplify_away(path->buf, path->len, pathspec))
2359 return path_none;
2361 dtype = resolve_dtype(cdir->d_type, istate, path->buf, path->len);
2363 /* Always exclude indexed files */
2364 has_path_in_index = !!index_file_exists(istate, path->buf, path->len,
2365 ignore_case);
2366 if (dtype != DT_DIR && has_path_in_index)
2367 return path_none;
2370 * When we are looking at a directory P in the working tree,
2371 * there are three cases:
2373 * (1) P exists in the index. Everything inside the directory P in
2374 * the working tree needs to go when P is checked out from the
2375 * index.
2377 * (2) P does not exist in the index, but there is P/Q in the index.
2378 * We know P will stay a directory when we check out the contents
2379 * of the index, but we do not know yet if there is a directory
2380 * P/Q in the working tree to be killed, so we need to recurse.
2382 * (3) P does not exist in the index, and there is no P/Q in the index
2383 * to require P to be a directory, either. Only in this case, we
2384 * know that everything inside P will not be killed without
2385 * recursing.
2387 if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
2388 (dtype == DT_DIR) &&
2389 !has_path_in_index &&
2390 (directory_exists_in_index(istate, path->buf, path->len) == index_nonexistent))
2391 return path_none;
2393 excluded = is_excluded(dir, istate, path->buf, &dtype);
2396 * Excluded? If we don't explicitly want to show
2397 * ignored files, ignore it
2399 if (excluded && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
2400 return path_excluded;
2402 switch (dtype) {
2403 default:
2404 return path_none;
2405 case DT_DIR:
2407 * WARNING: Do not ignore/amend the return value from
2408 * treat_directory(), and especially do not change it to return
2409 * path_recurse as that can cause exponential slowdown.
2410 * Instead, modify treat_directory() to return the right value.
2412 strbuf_addch(path, '/');
2413 return treat_directory(dir, istate, untracked,
2414 path->buf, path->len,
2415 baselen, excluded, pathspec);
2416 case DT_REG:
2417 case DT_LNK:
2418 if (pathspec &&
2419 !match_pathspec(istate, pathspec, path->buf, path->len,
2420 0 /* prefix */, NULL /* seen */,
2421 0 /* is_dir */))
2422 return path_none;
2423 if (excluded)
2424 return path_excluded;
2425 return path_untracked;
2429 static void add_untracked(struct untracked_cache_dir *dir, const char *name)
2431 if (!dir)
2432 return;
2433 ALLOC_GROW(dir->untracked, dir->untracked_nr + 1,
2434 dir->untracked_alloc);
2435 dir->untracked[dir->untracked_nr++] = xstrdup(name);
2438 static int valid_cached_dir(struct dir_struct *dir,
2439 struct untracked_cache_dir *untracked,
2440 struct index_state *istate,
2441 struct strbuf *path,
2442 int check_only)
2444 struct stat st;
2446 if (!untracked)
2447 return 0;
2450 * With fsmonitor, we can trust the untracked cache's valid field.
2452 refresh_fsmonitor(istate);
2453 if (!(dir->untracked->use_fsmonitor && untracked->valid)) {
2454 if (lstat(path->len ? path->buf : ".", &st)) {
2455 memset(&untracked->stat_data, 0, sizeof(untracked->stat_data));
2456 return 0;
2458 if (!untracked->valid ||
2459 match_stat_data_racy(istate, &untracked->stat_data, &st)) {
2460 fill_stat_data(&untracked->stat_data, &st);
2461 return 0;
2465 if (untracked->check_only != !!check_only)
2466 return 0;
2469 * prep_exclude will be called eventually on this directory,
2470 * but it's called much later in last_matching_pattern(). We
2471 * need it now to determine the validity of the cache for this
2472 * path. The next calls will be nearly no-op, the way
2473 * prep_exclude() is designed.
2475 if (path->len && path->buf[path->len - 1] != '/') {
2476 strbuf_addch(path, '/');
2477 prep_exclude(dir, istate, path->buf, path->len);
2478 strbuf_setlen(path, path->len - 1);
2479 } else
2480 prep_exclude(dir, istate, path->buf, path->len);
2482 /* hopefully prep_exclude() haven't invalidated this entry... */
2483 return untracked->valid;
2486 static int open_cached_dir(struct cached_dir *cdir,
2487 struct dir_struct *dir,
2488 struct untracked_cache_dir *untracked,
2489 struct index_state *istate,
2490 struct strbuf *path,
2491 int check_only)
2493 const char *c_path;
2495 memset(cdir, 0, sizeof(*cdir));
2496 cdir->untracked = untracked;
2497 if (valid_cached_dir(dir, untracked, istate, path, check_only))
2498 return 0;
2499 c_path = path->len ? path->buf : ".";
2500 cdir->fdir = opendir(c_path);
2501 if (!cdir->fdir)
2502 warning_errno(_("could not open directory '%s'"), c_path);
2503 if (dir->untracked) {
2504 invalidate_directory(dir->untracked, untracked);
2505 dir->untracked->dir_opened++;
2507 if (!cdir->fdir)
2508 return -1;
2509 return 0;
2512 static int read_cached_dir(struct cached_dir *cdir)
2514 struct dirent *de;
2516 if (cdir->fdir) {
2517 de = readdir_skip_dot_and_dotdot(cdir->fdir);
2518 if (!de) {
2519 cdir->d_name = NULL;
2520 cdir->d_type = DT_UNKNOWN;
2521 return -1;
2523 cdir->d_name = de->d_name;
2524 cdir->d_type = DTYPE(de);
2525 return 0;
2527 while (cdir->nr_dirs < cdir->untracked->dirs_nr) {
2528 struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];
2529 if (!d->recurse) {
2530 cdir->nr_dirs++;
2531 continue;
2533 cdir->ucd = d;
2534 cdir->nr_dirs++;
2535 return 0;
2537 cdir->ucd = NULL;
2538 if (cdir->nr_files < cdir->untracked->untracked_nr) {
2539 struct untracked_cache_dir *d = cdir->untracked;
2540 cdir->file = d->untracked[cdir->nr_files++];
2541 return 0;
2543 return -1;
2546 static void close_cached_dir(struct cached_dir *cdir)
2548 if (cdir->fdir)
2549 closedir(cdir->fdir);
2551 * We have gone through this directory and found no untracked
2552 * entries. Mark it valid.
2554 if (cdir->untracked) {
2555 cdir->untracked->valid = 1;
2556 cdir->untracked->recurse = 1;
2560 static void add_path_to_appropriate_result_list(struct dir_struct *dir,
2561 struct untracked_cache_dir *untracked,
2562 struct cached_dir *cdir,
2563 struct index_state *istate,
2564 struct strbuf *path,
2565 int baselen,
2566 const struct pathspec *pathspec,
2567 enum path_treatment state)
2569 /* add the path to the appropriate result list */
2570 switch (state) {
2571 case path_excluded:
2572 if (dir->flags & DIR_SHOW_IGNORED)
2573 dir_add_name(dir, istate, path->buf, path->len);
2574 else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
2575 ((dir->flags & DIR_COLLECT_IGNORED) &&
2576 exclude_matches_pathspec(path->buf, path->len,
2577 pathspec)))
2578 dir_add_ignored(dir, istate, path->buf, path->len);
2579 break;
2581 case path_untracked:
2582 if (dir->flags & DIR_SHOW_IGNORED)
2583 break;
2584 dir_add_name(dir, istate, path->buf, path->len);
2585 if (cdir->fdir)
2586 add_untracked(untracked, path->buf + baselen);
2587 break;
2589 default:
2590 break;
2595 * Read a directory tree. We currently ignore anything but
2596 * directories, regular files and symlinks. That's because git
2597 * doesn't handle them at all yet. Maybe that will change some
2598 * day.
2600 * Also, we ignore the name ".git" (even if it is not a directory).
2601 * That likely will not change.
2603 * If 'stop_at_first_file' is specified, 'path_excluded' is returned
2604 * to signal that a file was found. This is the least significant value that
2605 * indicates that a file was encountered that does not depend on the order of
2606 * whether an untracked or excluded path was encountered first.
2608 * Returns the most significant path_treatment value encountered in the scan.
2609 * If 'stop_at_first_file' is specified, `path_excluded` is the most
2610 * significant path_treatment value that will be returned.
2613 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
2614 struct index_state *istate, const char *base, int baselen,
2615 struct untracked_cache_dir *untracked, int check_only,
2616 int stop_at_first_file, const struct pathspec *pathspec)
2619 * WARNING: Do NOT recurse unless path_recurse is returned from
2620 * treat_path(). Recursing on any other return value
2621 * can result in exponential slowdown.
2623 struct cached_dir cdir;
2624 enum path_treatment state, subdir_state, dir_state = path_none;
2625 struct strbuf path = STRBUF_INIT;
2627 strbuf_add(&path, base, baselen);
2629 if (open_cached_dir(&cdir, dir, untracked, istate, &path, check_only))
2630 goto out;
2631 dir->internal.visited_directories++;
2633 if (untracked)
2634 untracked->check_only = !!check_only;
2636 while (!read_cached_dir(&cdir)) {
2637 /* check how the file or directory should be treated */
2638 state = treat_path(dir, untracked, &cdir, istate, &path,
2639 baselen, pathspec);
2640 dir->internal.visited_paths++;
2642 if (state > dir_state)
2643 dir_state = state;
2645 /* recurse into subdir if instructed by treat_path */
2646 if (state == path_recurse) {
2647 struct untracked_cache_dir *ud;
2648 ud = lookup_untracked(dir->untracked,
2649 untracked,
2650 path.buf + baselen,
2651 path.len - baselen);
2652 subdir_state =
2653 read_directory_recursive(dir, istate, path.buf,
2654 path.len, ud,
2655 check_only, stop_at_first_file, pathspec);
2656 if (subdir_state > dir_state)
2657 dir_state = subdir_state;
2659 if (pathspec &&
2660 !match_pathspec(istate, pathspec, path.buf, path.len,
2661 0 /* prefix */, NULL,
2662 0 /* do NOT special case dirs */))
2663 state = path_none;
2666 if (check_only) {
2667 if (stop_at_first_file) {
2669 * If stopping at first file, then
2670 * signal that a file was found by
2671 * returning `path_excluded`. This is
2672 * to return a consistent value
2673 * regardless of whether an ignored or
2674 * excluded file happened to be
2675 * encountered 1st.
2677 * In current usage, the
2678 * `stop_at_first_file` is passed when
2679 * an ancestor directory has matched
2680 * an exclude pattern, so any found
2681 * files will be excluded.
2683 if (dir_state >= path_excluded) {
2684 dir_state = path_excluded;
2685 break;
2689 /* abort early if maximum state has been reached */
2690 if (dir_state == path_untracked) {
2691 if (cdir.fdir)
2692 add_untracked(untracked, path.buf + baselen);
2693 break;
2695 /* skip the add_path_to_appropriate_result_list() */
2696 continue;
2699 add_path_to_appropriate_result_list(dir, untracked, &cdir,
2700 istate, &path, baselen,
2701 pathspec, state);
2703 close_cached_dir(&cdir);
2704 out:
2705 strbuf_release(&path);
2707 return dir_state;
2710 int cmp_dir_entry(const void *p1, const void *p2)
2712 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
2713 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
2715 return name_compare(e1->name, e1->len, e2->name, e2->len);
2718 /* check if *out lexically strictly contains *in */
2719 int check_dir_entry_contains(const struct dir_entry *out, const struct dir_entry *in)
2721 return (out->len < in->len) &&
2722 (out->name[out->len - 1] == '/') &&
2723 !memcmp(out->name, in->name, out->len);
2726 static int treat_leading_path(struct dir_struct *dir,
2727 struct index_state *istate,
2728 const char *path, int len,
2729 const struct pathspec *pathspec)
2731 struct strbuf sb = STRBUF_INIT;
2732 struct strbuf subdir = STRBUF_INIT;
2733 int prevlen, baselen;
2734 const char *cp;
2735 struct cached_dir cdir;
2736 enum path_treatment state = path_none;
2739 * For each directory component of path, we are going to check whether
2740 * that path is relevant given the pathspec. For example, if path is
2741 * foo/bar/baz/
2742 * then we will ask treat_path() whether we should go into foo, then
2743 * whether we should go into bar, then whether baz is relevant.
2744 * Checking each is important because e.g. if path is
2745 * .git/info/
2746 * then we need to check .git to know we shouldn't traverse it.
2747 * If the return from treat_path() is:
2748 * * path_none, for any path, we return false.
2749 * * path_recurse, for all path components, we return true
2750 * * <anything else> for some intermediate component, we make sure
2751 * to add that path to the relevant list but return false
2752 * signifying that we shouldn't recurse into it.
2755 while (len && path[len - 1] == '/')
2756 len--;
2757 if (!len)
2758 return 1;
2760 memset(&cdir, 0, sizeof(cdir));
2761 cdir.d_type = DT_DIR;
2762 baselen = 0;
2763 prevlen = 0;
2764 while (1) {
2765 prevlen = baselen + !!baselen;
2766 cp = path + prevlen;
2767 cp = memchr(cp, '/', path + len - cp);
2768 if (!cp)
2769 baselen = len;
2770 else
2771 baselen = cp - path;
2772 strbuf_reset(&sb);
2773 strbuf_add(&sb, path, baselen);
2774 if (!is_directory(sb.buf))
2775 break;
2776 strbuf_reset(&sb);
2777 strbuf_add(&sb, path, prevlen);
2778 strbuf_reset(&subdir);
2779 strbuf_add(&subdir, path+prevlen, baselen-prevlen);
2780 cdir.d_name = subdir.buf;
2781 state = treat_path(dir, NULL, &cdir, istate, &sb, prevlen, pathspec);
2783 if (state != path_recurse)
2784 break; /* do not recurse into it */
2785 if (len <= baselen)
2786 break; /* finished checking */
2788 add_path_to_appropriate_result_list(dir, NULL, &cdir, istate,
2789 &sb, baselen, pathspec,
2790 state);
2792 strbuf_release(&subdir);
2793 strbuf_release(&sb);
2794 return state == path_recurse;
2797 static const char *get_ident_string(void)
2799 static struct strbuf sb = STRBUF_INIT;
2800 struct utsname uts;
2802 if (sb.len)
2803 return sb.buf;
2804 if (uname(&uts) < 0)
2805 die_errno(_("failed to get kernel name and information"));
2806 strbuf_addf(&sb, "Location %s, system %s", get_git_work_tree(),
2807 uts.sysname);
2808 return sb.buf;
2811 static int ident_in_untracked(const struct untracked_cache *uc)
2814 * Previous git versions may have saved many NUL separated
2815 * strings in the "ident" field, but it is insane to manage
2816 * many locations, so just take care of the first one.
2819 return !strcmp(uc->ident.buf, get_ident_string());
2822 static void set_untracked_ident(struct untracked_cache *uc)
2824 strbuf_reset(&uc->ident);
2825 strbuf_addstr(&uc->ident, get_ident_string());
2828 * This strbuf used to contain a list of NUL separated
2829 * strings, so save NUL too for backward compatibility.
2831 strbuf_addch(&uc->ident, 0);
2834 static unsigned new_untracked_cache_flags(struct index_state *istate)
2836 struct repository *repo = istate->repo;
2837 char *val;
2840 * This logic is coordinated with the setting of these flags in
2841 * wt-status.c#wt_status_collect_untracked(), and the evaluation
2842 * of the config setting in commit.c#git_status_config()
2844 if (!repo_config_get_string(repo, "status.showuntrackedfiles", &val) &&
2845 !strcmp(val, "all"))
2846 return 0;
2849 * The default, if "all" is not set, is "normal" - leading us here.
2850 * If the value is "none" then it really doesn't matter.
2852 return DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;
2855 static void new_untracked_cache(struct index_state *istate, int flags)
2857 struct untracked_cache *uc = xcalloc(1, sizeof(*uc));
2858 strbuf_init(&uc->ident, 100);
2859 uc->exclude_per_dir = ".gitignore";
2860 uc->dir_flags = flags >= 0 ? flags : new_untracked_cache_flags(istate);
2861 set_untracked_ident(uc);
2862 istate->untracked = uc;
2863 istate->cache_changed |= UNTRACKED_CHANGED;
2866 void add_untracked_cache(struct index_state *istate)
2868 if (!istate->untracked) {
2869 new_untracked_cache(istate, -1);
2870 } else {
2871 if (!ident_in_untracked(istate->untracked)) {
2872 free_untracked_cache(istate->untracked);
2873 new_untracked_cache(istate, -1);
2878 void remove_untracked_cache(struct index_state *istate)
2880 if (istate->untracked) {
2881 free_untracked_cache(istate->untracked);
2882 istate->untracked = NULL;
2883 istate->cache_changed |= UNTRACKED_CHANGED;
2887 static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,
2888 int base_len,
2889 const struct pathspec *pathspec,
2890 struct index_state *istate)
2892 struct untracked_cache_dir *root;
2893 static int untracked_cache_disabled = -1;
2895 if (!dir->untracked)
2896 return NULL;
2897 if (untracked_cache_disabled < 0)
2898 untracked_cache_disabled = git_env_bool("GIT_DISABLE_UNTRACKED_CACHE", 0);
2899 if (untracked_cache_disabled)
2900 return NULL;
2903 * We only support $GIT_DIR/info/exclude and core.excludesfile
2904 * as the global ignore rule files. Any other additions
2905 * (e.g. from command line) invalidate the cache. This
2906 * condition also catches running setup_standard_excludes()
2907 * before setting dir->untracked!
2909 if (dir->internal.unmanaged_exclude_files)
2910 return NULL;
2913 * Optimize for the main use case only: whole-tree git
2914 * status. More work involved in treat_leading_path() if we
2915 * use cache on just a subset of the worktree. pathspec
2916 * support could make the matter even worse.
2918 if (base_len || (pathspec && pathspec->nr))
2919 return NULL;
2921 /* We don't support collecting ignore files */
2922 if (dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |
2923 DIR_COLLECT_IGNORED))
2924 return NULL;
2927 * If we use .gitignore in the cache and now you change it to
2928 * .gitexclude, everything will go wrong.
2930 if (dir->exclude_per_dir != dir->untracked->exclude_per_dir &&
2931 strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))
2932 return NULL;
2935 * EXC_CMDL is not considered in the cache. If people set it,
2936 * skip the cache.
2938 if (dir->internal.exclude_list_group[EXC_CMDL].nr)
2939 return NULL;
2941 if (!ident_in_untracked(dir->untracked)) {
2942 warning(_("untracked cache is disabled on this system or location"));
2943 return NULL;
2947 * If the untracked structure we received does not have the same flags
2948 * as requested in this run, we're going to need to either discard the
2949 * existing structure (and potentially later recreate), or bypass the
2950 * untracked cache mechanism for this run.
2952 if (dir->flags != dir->untracked->dir_flags) {
2954 * If the untracked structure we received does not have the same flags
2955 * as configured, then we need to reset / create a new "untracked"
2956 * structure to match the new config.
2958 * Keeping the saved and used untracked cache consistent with the
2959 * configuration provides an opportunity for frequent users of
2960 * "git status -uall" to leverage the untracked cache by aligning their
2961 * configuration - setting "status.showuntrackedfiles" to "all" or
2962 * "normal" as appropriate.
2964 * Previously using -uall (or setting "status.showuntrackedfiles" to
2965 * "all") was incompatible with untracked cache and *consistently*
2966 * caused surprisingly bad performance (with fscache and fsmonitor
2967 * enabled) on Windows.
2969 * IMPROVEMENT OPPORTUNITY: If we reworked the untracked cache storage
2970 * to not be as bound up with the desired output in a given run,
2971 * and instead iterated through and stored enough information to
2972 * correctly serve both "modes", then users could get peak performance
2973 * with or without '-uall' regardless of their
2974 * "status.showuntrackedfiles" config.
2976 if (dir->untracked->dir_flags != new_untracked_cache_flags(istate)) {
2977 free_untracked_cache(istate->untracked);
2978 new_untracked_cache(istate, dir->flags);
2979 dir->untracked = istate->untracked;
2981 else {
2983 * Current untracked cache data is consistent with config, but not
2984 * usable in this request/run; just bypass untracked cache.
2986 return NULL;
2990 if (!dir->untracked->root) {
2991 /* Untracked cache existed but is not initialized; fix that */
2992 FLEX_ALLOC_STR(dir->untracked->root, name, "");
2993 istate->cache_changed |= UNTRACKED_CHANGED;
2996 /* Validate $GIT_DIR/info/exclude and core.excludesfile */
2997 root = dir->untracked->root;
2998 if (!oideq(&dir->internal.ss_info_exclude.oid,
2999 &dir->untracked->ss_info_exclude.oid)) {
3000 invalidate_gitignore(dir->untracked, root);
3001 dir->untracked->ss_info_exclude = dir->internal.ss_info_exclude;
3003 if (!oideq(&dir->internal.ss_excludes_file.oid,
3004 &dir->untracked->ss_excludes_file.oid)) {
3005 invalidate_gitignore(dir->untracked, root);
3006 dir->untracked->ss_excludes_file = dir->internal.ss_excludes_file;
3009 /* Make sure this directory is not dropped out at saving phase */
3010 root->recurse = 1;
3011 return root;
3014 static void emit_traversal_statistics(struct dir_struct *dir,
3015 struct repository *repo,
3016 const char *path,
3017 int path_len)
3019 if (!trace2_is_enabled())
3020 return;
3022 if (!path_len) {
3023 trace2_data_string("read_directory", repo, "path", "");
3024 } else {
3025 struct strbuf tmp = STRBUF_INIT;
3026 strbuf_add(&tmp, path, path_len);
3027 trace2_data_string("read_directory", repo, "path", tmp.buf);
3028 strbuf_release(&tmp);
3031 trace2_data_intmax("read_directory", repo,
3032 "directories-visited", dir->internal.visited_directories);
3033 trace2_data_intmax("read_directory", repo,
3034 "paths-visited", dir->internal.visited_paths);
3036 if (!dir->untracked)
3037 return;
3038 trace2_data_intmax("read_directory", repo,
3039 "node-creation", dir->untracked->dir_created);
3040 trace2_data_intmax("read_directory", repo,
3041 "gitignore-invalidation",
3042 dir->untracked->gitignore_invalidated);
3043 trace2_data_intmax("read_directory", repo,
3044 "directory-invalidation",
3045 dir->untracked->dir_invalidated);
3046 trace2_data_intmax("read_directory", repo,
3047 "opendir", dir->untracked->dir_opened);
3050 int read_directory(struct dir_struct *dir, struct index_state *istate,
3051 const char *path, int len, const struct pathspec *pathspec)
3053 struct untracked_cache_dir *untracked;
3055 trace2_region_enter("dir", "read_directory", istate->repo);
3056 dir->internal.visited_paths = 0;
3057 dir->internal.visited_directories = 0;
3059 if (has_symlink_leading_path(path, len)) {
3060 trace2_region_leave("dir", "read_directory", istate->repo);
3061 return dir->nr;
3064 untracked = validate_untracked_cache(dir, len, pathspec, istate);
3065 if (!untracked)
3067 * make sure untracked cache code path is disabled,
3068 * e.g. prep_exclude()
3070 dir->untracked = NULL;
3071 if (!len || treat_leading_path(dir, istate, path, len, pathspec))
3072 read_directory_recursive(dir, istate, path, len, untracked, 0, 0, pathspec);
3073 QSORT(dir->entries, dir->nr, cmp_dir_entry);
3074 QSORT(dir->ignored, dir->ignored_nr, cmp_dir_entry);
3076 emit_traversal_statistics(dir, istate->repo, path, len);
3078 trace2_region_leave("dir", "read_directory", istate->repo);
3079 if (dir->untracked) {
3080 static int force_untracked_cache = -1;
3082 if (force_untracked_cache < 0)
3083 force_untracked_cache =
3084 git_env_bool("GIT_FORCE_UNTRACKED_CACHE", -1);
3085 if (force_untracked_cache < 0)
3086 force_untracked_cache = (istate->repo->settings.core_untracked_cache == UNTRACKED_CACHE_WRITE);
3087 if (force_untracked_cache &&
3088 dir->untracked == istate->untracked &&
3089 (dir->untracked->dir_opened ||
3090 dir->untracked->gitignore_invalidated ||
3091 dir->untracked->dir_invalidated))
3092 istate->cache_changed |= UNTRACKED_CHANGED;
3093 if (dir->untracked != istate->untracked) {
3094 FREE_AND_NULL(dir->untracked);
3098 return dir->nr;
3101 int file_exists(const char *f)
3103 struct stat sb;
3104 return lstat(f, &sb) == 0;
3107 int repo_file_exists(struct repository *repo, const char *path)
3109 if (repo != the_repository)
3110 BUG("do not know how to check file existence in arbitrary repo");
3112 return file_exists(path);
3115 static int cmp_icase(char a, char b)
3117 if (a == b)
3118 return 0;
3119 if (ignore_case)
3120 return toupper(a) - toupper(b);
3121 return a - b;
3125 * Given two normalized paths (a trailing slash is ok), if subdir is
3126 * outside dir, return -1. Otherwise return the offset in subdir that
3127 * can be used as relative path to dir.
3129 int dir_inside_of(const char *subdir, const char *dir)
3131 int offset = 0;
3133 assert(dir && subdir && *dir && *subdir);
3135 while (*dir && *subdir && !cmp_icase(*dir, *subdir)) {
3136 dir++;
3137 subdir++;
3138 offset++;
3141 /* hel[p]/me vs hel[l]/yeah */
3142 if (*dir && *subdir)
3143 return -1;
3145 if (!*subdir)
3146 return !*dir ? offset : -1; /* same dir */
3148 /* foo/[b]ar vs foo/[] */
3149 if (is_dir_sep(dir[-1]))
3150 return is_dir_sep(subdir[-1]) ? offset : -1;
3152 /* foo[/]bar vs foo[] */
3153 return is_dir_sep(*subdir) ? offset + 1 : -1;
3156 int is_inside_dir(const char *dir)
3158 char *cwd;
3159 int rc;
3161 if (!dir)
3162 return 0;
3164 cwd = xgetcwd();
3165 rc = (dir_inside_of(cwd, dir) >= 0);
3166 free(cwd);
3167 return rc;
3170 int is_empty_dir(const char *path)
3172 DIR *dir = opendir(path);
3173 struct dirent *e;
3174 int ret = 1;
3176 if (!dir)
3177 return 0;
3179 e = readdir_skip_dot_and_dotdot(dir);
3180 if (e)
3181 ret = 0;
3183 closedir(dir);
3184 return ret;
3187 char *git_url_basename(const char *repo, int is_bundle, int is_bare)
3189 const char *end = repo + strlen(repo), *start, *ptr;
3190 size_t len;
3191 char *dir;
3194 * Skip scheme.
3196 start = strstr(repo, "://");
3197 if (!start)
3198 start = repo;
3199 else
3200 start += 3;
3203 * Skip authentication data. The stripping does happen
3204 * greedily, such that we strip up to the last '@' inside
3205 * the host part.
3207 for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
3208 if (*ptr == '@')
3209 start = ptr + 1;
3213 * Strip trailing spaces, slashes and /.git
3215 while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
3216 end--;
3217 if (end - start > 5 && is_dir_sep(end[-5]) &&
3218 !strncmp(end - 4, ".git", 4)) {
3219 end -= 5;
3220 while (start < end && is_dir_sep(end[-1]))
3221 end--;
3225 * It should not be possible to overflow `ptrdiff_t` by passing in an
3226 * insanely long URL, but GCC does not know that and will complain
3227 * without this check.
3229 if (end - start < 0)
3230 die(_("No directory name could be guessed.\n"
3231 "Please specify a directory on the command line"));
3234 * Strip trailing port number if we've got only a
3235 * hostname (that is, there is no dir separator but a
3236 * colon). This check is required such that we do not
3237 * strip URI's like '/foo/bar:2222.git', which should
3238 * result in a dir '2222' being guessed due to backwards
3239 * compatibility.
3241 if (memchr(start, '/', end - start) == NULL
3242 && memchr(start, ':', end - start) != NULL) {
3243 ptr = end;
3244 while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
3245 ptr--;
3246 if (start < ptr && ptr[-1] == ':')
3247 end = ptr - 1;
3251 * Find last component. To remain backwards compatible we
3252 * also regard colons as path separators, such that
3253 * cloning a repository 'foo:bar.git' would result in a
3254 * directory 'bar' being guessed.
3256 ptr = end;
3257 while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
3258 ptr--;
3259 start = ptr;
3262 * Strip .{bundle,git}.
3264 len = end - start;
3265 strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
3267 if (!len || (len == 1 && *start == '/'))
3268 die(_("No directory name could be guessed.\n"
3269 "Please specify a directory on the command line"));
3271 if (is_bare)
3272 dir = xstrfmt("%.*s.git", (int)len, start);
3273 else
3274 dir = xstrndup(start, len);
3276 * Replace sequences of 'control' characters and whitespace
3277 * with one ascii space, remove leading and trailing spaces.
3279 if (*dir) {
3280 char *out = dir;
3281 int prev_space = 1 /* strip leading whitespace */;
3282 for (end = dir; *end; ++end) {
3283 char ch = *end;
3284 if ((unsigned char)ch < '\x20')
3285 ch = '\x20';
3286 if (isspace(ch)) {
3287 if (prev_space)
3288 continue;
3289 prev_space = 1;
3290 } else
3291 prev_space = 0;
3292 *out++ = ch;
3294 *out = '\0';
3295 if (out > dir && prev_space)
3296 out[-1] = '\0';
3298 return dir;
3301 void strip_dir_trailing_slashes(char *dir)
3303 char *end = dir + strlen(dir);
3305 while (dir < end - 1 && is_dir_sep(end[-1]))
3306 end--;
3307 *end = '\0';
3310 static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
3312 DIR *dir;
3313 struct dirent *e;
3314 int ret = 0, original_len = path->len, len, kept_down = 0;
3315 int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
3316 int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
3317 int purge_original_cwd = (flag & REMOVE_DIR_PURGE_ORIGINAL_CWD);
3318 struct object_id submodule_head;
3320 if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
3321 !resolve_gitlink_ref(path->buf, "HEAD", &submodule_head)) {
3322 /* Do not descend and nuke a nested git work tree. */
3323 if (kept_up)
3324 *kept_up = 1;
3325 return 0;
3328 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
3329 dir = opendir(path->buf);
3330 if (!dir) {
3331 if (errno == ENOENT)
3332 return keep_toplevel ? -1 : 0;
3333 else if (errno == EACCES && !keep_toplevel)
3335 * An empty dir could be removable even if it
3336 * is unreadable:
3338 return rmdir(path->buf);
3339 else
3340 return -1;
3342 strbuf_complete(path, '/');
3344 len = path->len;
3345 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
3346 struct stat st;
3348 strbuf_setlen(path, len);
3349 strbuf_addstr(path, e->d_name);
3350 if (lstat(path->buf, &st)) {
3351 if (errno == ENOENT)
3353 * file disappeared, which is what we
3354 * wanted anyway
3356 continue;
3357 /* fall through */
3358 } else if (S_ISDIR(st.st_mode)) {
3359 if (!remove_dir_recurse(path, flag, &kept_down))
3360 continue; /* happy */
3361 } else if (!only_empty &&
3362 (!unlink(path->buf) || errno == ENOENT)) {
3363 continue; /* happy, too */
3366 /* path too long, stat fails, or non-directory still exists */
3367 ret = -1;
3368 break;
3370 closedir(dir);
3372 strbuf_setlen(path, original_len);
3373 if (!ret && !keep_toplevel && !kept_down) {
3374 if (!purge_original_cwd &&
3375 startup_info->original_cwd &&
3376 !strcmp(startup_info->original_cwd, path->buf))
3377 ret = -1; /* Do not remove current working directory */
3378 else
3379 ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1;
3380 } else if (kept_up)
3382 * report the uplevel that it is not an error that we
3383 * did not rmdir() our directory.
3385 *kept_up = !ret;
3386 return ret;
3389 int remove_dir_recursively(struct strbuf *path, int flag)
3391 return remove_dir_recurse(path, flag, NULL);
3394 static GIT_PATH_FUNC(git_path_info_exclude, "info/exclude")
3396 void setup_standard_excludes(struct dir_struct *dir)
3398 dir->exclude_per_dir = ".gitignore";
3400 /* core.excludesfile defaulting to $XDG_CONFIG_HOME/git/ignore */
3401 if (!excludes_file)
3402 excludes_file = xdg_config_home("ignore");
3403 if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
3404 add_patterns_from_file_1(dir, excludes_file,
3405 dir->untracked ? &dir->internal.ss_excludes_file : NULL);
3407 /* per repository user preference */
3408 if (startup_info->have_repository) {
3409 const char *path = git_path_info_exclude();
3410 if (!access_or_warn(path, R_OK, 0))
3411 add_patterns_from_file_1(dir, path,
3412 dir->untracked ? &dir->internal.ss_info_exclude : NULL);
3416 char *get_sparse_checkout_filename(void)
3418 return git_pathdup("info/sparse-checkout");
3421 int get_sparse_checkout_patterns(struct pattern_list *pl)
3423 int res;
3424 char *sparse_filename = get_sparse_checkout_filename();
3426 pl->use_cone_patterns = core_sparse_checkout_cone;
3427 res = add_patterns_from_file_to_list(sparse_filename, "", 0, pl, NULL, 0);
3429 free(sparse_filename);
3430 return res;
3433 int remove_path(const char *name)
3435 char *slash;
3437 if (unlink(name) && !is_missing_file_error(errno))
3438 return -1;
3440 slash = strrchr(name, '/');
3441 if (slash) {
3442 char *dirs = xstrdup(name);
3443 slash = dirs + (slash - name);
3444 do {
3445 *slash = '\0';
3446 if (startup_info->original_cwd &&
3447 !strcmp(startup_info->original_cwd, dirs))
3448 break;
3449 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
3450 free(dirs);
3452 return 0;
3456 * Frees memory within dir which was allocated, and resets fields for further
3457 * use. Does not free dir itself.
3459 void dir_clear(struct dir_struct *dir)
3461 int i, j;
3462 struct exclude_list_group *group;
3463 struct pattern_list *pl;
3464 struct exclude_stack *stk;
3465 struct dir_struct new = DIR_INIT;
3467 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
3468 group = &dir->internal.exclude_list_group[i];
3469 for (j = 0; j < group->nr; j++) {
3470 pl = &group->pl[j];
3471 if (i == EXC_DIRS)
3472 free((char *)pl->src);
3473 clear_pattern_list(pl);
3475 free(group->pl);
3478 for (i = 0; i < dir->ignored_nr; i++)
3479 free(dir->ignored[i]);
3480 for (i = 0; i < dir->nr; i++)
3481 free(dir->entries[i]);
3482 free(dir->ignored);
3483 free(dir->entries);
3485 stk = dir->internal.exclude_stack;
3486 while (stk) {
3487 struct exclude_stack *prev = stk->prev;
3488 free(stk);
3489 stk = prev;
3491 strbuf_release(&dir->internal.basebuf);
3493 memcpy(dir, &new, sizeof(*dir));
3496 struct ondisk_untracked_cache {
3497 struct stat_data info_exclude_stat;
3498 struct stat_data excludes_file_stat;
3499 uint32_t dir_flags;
3502 #define ouc_offset(x) offsetof(struct ondisk_untracked_cache, x)
3504 struct write_data {
3505 int index; /* number of written untracked_cache_dir */
3506 struct ewah_bitmap *check_only; /* from untracked_cache_dir */
3507 struct ewah_bitmap *valid; /* from untracked_cache_dir */
3508 struct ewah_bitmap *sha1_valid; /* set if exclude_sha1 is not null */
3509 struct strbuf out;
3510 struct strbuf sb_stat;
3511 struct strbuf sb_sha1;
3514 static void stat_data_to_disk(struct stat_data *to, const struct stat_data *from)
3516 to->sd_ctime.sec = htonl(from->sd_ctime.sec);
3517 to->sd_ctime.nsec = htonl(from->sd_ctime.nsec);
3518 to->sd_mtime.sec = htonl(from->sd_mtime.sec);
3519 to->sd_mtime.nsec = htonl(from->sd_mtime.nsec);
3520 to->sd_dev = htonl(from->sd_dev);
3521 to->sd_ino = htonl(from->sd_ino);
3522 to->sd_uid = htonl(from->sd_uid);
3523 to->sd_gid = htonl(from->sd_gid);
3524 to->sd_size = htonl(from->sd_size);
3527 static void write_one_dir(struct untracked_cache_dir *untracked,
3528 struct write_data *wd)
3530 struct stat_data stat_data;
3531 struct strbuf *out = &wd->out;
3532 unsigned char intbuf[16];
3533 unsigned int intlen, value;
3534 int i = wd->index++;
3537 * untracked_nr should be reset whenever valid is clear, but
3538 * for safety..
3540 if (!untracked->valid) {
3541 untracked->untracked_nr = 0;
3542 untracked->check_only = 0;
3545 if (untracked->check_only)
3546 ewah_set(wd->check_only, i);
3547 if (untracked->valid) {
3548 ewah_set(wd->valid, i);
3549 stat_data_to_disk(&stat_data, &untracked->stat_data);
3550 strbuf_add(&wd->sb_stat, &stat_data, sizeof(stat_data));
3552 if (!is_null_oid(&untracked->exclude_oid)) {
3553 ewah_set(wd->sha1_valid, i);
3554 strbuf_add(&wd->sb_sha1, untracked->exclude_oid.hash,
3555 the_hash_algo->rawsz);
3558 intlen = encode_varint(untracked->untracked_nr, intbuf);
3559 strbuf_add(out, intbuf, intlen);
3561 /* skip non-recurse directories */
3562 for (i = 0, value = 0; i < untracked->dirs_nr; i++)
3563 if (untracked->dirs[i]->recurse)
3564 value++;
3565 intlen = encode_varint(value, intbuf);
3566 strbuf_add(out, intbuf, intlen);
3568 strbuf_add(out, untracked->name, strlen(untracked->name) + 1);
3570 for (i = 0; i < untracked->untracked_nr; i++)
3571 strbuf_add(out, untracked->untracked[i],
3572 strlen(untracked->untracked[i]) + 1);
3574 for (i = 0; i < untracked->dirs_nr; i++)
3575 if (untracked->dirs[i]->recurse)
3576 write_one_dir(untracked->dirs[i], wd);
3579 void write_untracked_extension(struct strbuf *out, struct untracked_cache *untracked)
3581 struct ondisk_untracked_cache *ouc;
3582 struct write_data wd;
3583 unsigned char varbuf[16];
3584 int varint_len;
3585 const unsigned hashsz = the_hash_algo->rawsz;
3587 CALLOC_ARRAY(ouc, 1);
3588 stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);
3589 stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);
3590 ouc->dir_flags = htonl(untracked->dir_flags);
3592 varint_len = encode_varint(untracked->ident.len, varbuf);
3593 strbuf_add(out, varbuf, varint_len);
3594 strbuf_addbuf(out, &untracked->ident);
3596 strbuf_add(out, ouc, sizeof(*ouc));
3597 strbuf_add(out, untracked->ss_info_exclude.oid.hash, hashsz);
3598 strbuf_add(out, untracked->ss_excludes_file.oid.hash, hashsz);
3599 strbuf_add(out, untracked->exclude_per_dir, strlen(untracked->exclude_per_dir) + 1);
3600 FREE_AND_NULL(ouc);
3602 if (!untracked->root) {
3603 varint_len = encode_varint(0, varbuf);
3604 strbuf_add(out, varbuf, varint_len);
3605 return;
3608 wd.index = 0;
3609 wd.check_only = ewah_new();
3610 wd.valid = ewah_new();
3611 wd.sha1_valid = ewah_new();
3612 strbuf_init(&wd.out, 1024);
3613 strbuf_init(&wd.sb_stat, 1024);
3614 strbuf_init(&wd.sb_sha1, 1024);
3615 write_one_dir(untracked->root, &wd);
3617 varint_len = encode_varint(wd.index, varbuf);
3618 strbuf_add(out, varbuf, varint_len);
3619 strbuf_addbuf(out, &wd.out);
3620 ewah_serialize_strbuf(wd.valid, out);
3621 ewah_serialize_strbuf(wd.check_only, out);
3622 ewah_serialize_strbuf(wd.sha1_valid, out);
3623 strbuf_addbuf(out, &wd.sb_stat);
3624 strbuf_addbuf(out, &wd.sb_sha1);
3625 strbuf_addch(out, '\0'); /* safe guard for string lists */
3627 ewah_free(wd.valid);
3628 ewah_free(wd.check_only);
3629 ewah_free(wd.sha1_valid);
3630 strbuf_release(&wd.out);
3631 strbuf_release(&wd.sb_stat);
3632 strbuf_release(&wd.sb_sha1);
3635 static void free_untracked(struct untracked_cache_dir *ucd)
3637 int i;
3638 if (!ucd)
3639 return;
3640 for (i = 0; i < ucd->dirs_nr; i++)
3641 free_untracked(ucd->dirs[i]);
3642 for (i = 0; i < ucd->untracked_nr; i++)
3643 free(ucd->untracked[i]);
3644 free(ucd->untracked);
3645 free(ucd->dirs);
3646 free(ucd);
3649 void free_untracked_cache(struct untracked_cache *uc)
3651 if (!uc)
3652 return;
3654 free(uc->exclude_per_dir_to_free);
3655 strbuf_release(&uc->ident);
3656 free_untracked(uc->root);
3657 free(uc);
3660 struct read_data {
3661 int index;
3662 struct untracked_cache_dir **ucd;
3663 struct ewah_bitmap *check_only;
3664 struct ewah_bitmap *valid;
3665 struct ewah_bitmap *sha1_valid;
3666 const unsigned char *data;
3667 const unsigned char *end;
3670 static void stat_data_from_disk(struct stat_data *to, const unsigned char *data)
3672 memcpy(to, data, sizeof(*to));
3673 to->sd_ctime.sec = ntohl(to->sd_ctime.sec);
3674 to->sd_ctime.nsec = ntohl(to->sd_ctime.nsec);
3675 to->sd_mtime.sec = ntohl(to->sd_mtime.sec);
3676 to->sd_mtime.nsec = ntohl(to->sd_mtime.nsec);
3677 to->sd_dev = ntohl(to->sd_dev);
3678 to->sd_ino = ntohl(to->sd_ino);
3679 to->sd_uid = ntohl(to->sd_uid);
3680 to->sd_gid = ntohl(to->sd_gid);
3681 to->sd_size = ntohl(to->sd_size);
3684 static int read_one_dir(struct untracked_cache_dir **untracked_,
3685 struct read_data *rd)
3687 struct untracked_cache_dir ud, *untracked;
3688 const unsigned char *data = rd->data, *end = rd->end;
3689 const unsigned char *eos;
3690 unsigned int value;
3691 int i;
3693 memset(&ud, 0, sizeof(ud));
3695 value = decode_varint(&data);
3696 if (data > end)
3697 return -1;
3698 ud.recurse = 1;
3699 ud.untracked_alloc = value;
3700 ud.untracked_nr = value;
3701 if (ud.untracked_nr)
3702 ALLOC_ARRAY(ud.untracked, ud.untracked_nr);
3704 ud.dirs_alloc = ud.dirs_nr = decode_varint(&data);
3705 if (data > end)
3706 return -1;
3707 ALLOC_ARRAY(ud.dirs, ud.dirs_nr);
3709 eos = memchr(data, '\0', end - data);
3710 if (!eos || eos == end)
3711 return -1;
3713 *untracked_ = untracked = xmalloc(st_add3(sizeof(*untracked), eos - data, 1));
3714 memcpy(untracked, &ud, sizeof(ud));
3715 memcpy(untracked->name, data, eos - data + 1);
3716 data = eos + 1;
3718 for (i = 0; i < untracked->untracked_nr; i++) {
3719 eos = memchr(data, '\0', end - data);
3720 if (!eos || eos == end)
3721 return -1;
3722 untracked->untracked[i] = xmemdupz(data, eos - data);
3723 data = eos + 1;
3726 rd->ucd[rd->index++] = untracked;
3727 rd->data = data;
3729 for (i = 0; i < untracked->dirs_nr; i++) {
3730 if (read_one_dir(untracked->dirs + i, rd) < 0)
3731 return -1;
3733 return 0;
3736 static void set_check_only(size_t pos, void *cb)
3738 struct read_data *rd = cb;
3739 struct untracked_cache_dir *ud = rd->ucd[pos];
3740 ud->check_only = 1;
3743 static void read_stat(size_t pos, void *cb)
3745 struct read_data *rd = cb;
3746 struct untracked_cache_dir *ud = rd->ucd[pos];
3747 if (rd->data + sizeof(struct stat_data) > rd->end) {
3748 rd->data = rd->end + 1;
3749 return;
3751 stat_data_from_disk(&ud->stat_data, rd->data);
3752 rd->data += sizeof(struct stat_data);
3753 ud->valid = 1;
3756 static void read_oid(size_t pos, void *cb)
3758 struct read_data *rd = cb;
3759 struct untracked_cache_dir *ud = rd->ucd[pos];
3760 if (rd->data + the_hash_algo->rawsz > rd->end) {
3761 rd->data = rd->end + 1;
3762 return;
3764 oidread(&ud->exclude_oid, rd->data);
3765 rd->data += the_hash_algo->rawsz;
3768 static void load_oid_stat(struct oid_stat *oid_stat, const unsigned char *data,
3769 const unsigned char *sha1)
3771 stat_data_from_disk(&oid_stat->stat, data);
3772 oidread(&oid_stat->oid, sha1);
3773 oid_stat->valid = 1;
3776 struct untracked_cache *read_untracked_extension(const void *data, unsigned long sz)
3778 struct untracked_cache *uc;
3779 struct read_data rd;
3780 const unsigned char *next = data, *end = (const unsigned char *)data + sz;
3781 const char *ident;
3782 int ident_len;
3783 ssize_t len;
3784 const char *exclude_per_dir;
3785 const unsigned hashsz = the_hash_algo->rawsz;
3786 const unsigned offset = sizeof(struct ondisk_untracked_cache);
3787 const unsigned exclude_per_dir_offset = offset + 2 * hashsz;
3789 if (sz <= 1 || end[-1] != '\0')
3790 return NULL;
3791 end--;
3793 ident_len = decode_varint(&next);
3794 if (next + ident_len > end)
3795 return NULL;
3796 ident = (const char *)next;
3797 next += ident_len;
3799 if (next + exclude_per_dir_offset + 1 > end)
3800 return NULL;
3802 CALLOC_ARRAY(uc, 1);
3803 strbuf_init(&uc->ident, ident_len);
3804 strbuf_add(&uc->ident, ident, ident_len);
3805 load_oid_stat(&uc->ss_info_exclude,
3806 next + ouc_offset(info_exclude_stat),
3807 next + offset);
3808 load_oid_stat(&uc->ss_excludes_file,
3809 next + ouc_offset(excludes_file_stat),
3810 next + offset + hashsz);
3811 uc->dir_flags = get_be32(next + ouc_offset(dir_flags));
3812 exclude_per_dir = (const char *)next + exclude_per_dir_offset;
3813 uc->exclude_per_dir = uc->exclude_per_dir_to_free = xstrdup(exclude_per_dir);
3814 /* NUL after exclude_per_dir is covered by sizeof(*ouc) */
3815 next += exclude_per_dir_offset + strlen(exclude_per_dir) + 1;
3816 if (next >= end)
3817 goto done2;
3819 len = decode_varint(&next);
3820 if (next > end || len == 0)
3821 goto done2;
3823 rd.valid = ewah_new();
3824 rd.check_only = ewah_new();
3825 rd.sha1_valid = ewah_new();
3826 rd.data = next;
3827 rd.end = end;
3828 rd.index = 0;
3829 ALLOC_ARRAY(rd.ucd, len);
3831 if (read_one_dir(&uc->root, &rd) || rd.index != len)
3832 goto done;
3834 next = rd.data;
3835 len = ewah_read_mmap(rd.valid, next, end - next);
3836 if (len < 0)
3837 goto done;
3839 next += len;
3840 len = ewah_read_mmap(rd.check_only, next, end - next);
3841 if (len < 0)
3842 goto done;
3844 next += len;
3845 len = ewah_read_mmap(rd.sha1_valid, next, end - next);
3846 if (len < 0)
3847 goto done;
3849 ewah_each_bit(rd.check_only, set_check_only, &rd);
3850 rd.data = next + len;
3851 ewah_each_bit(rd.valid, read_stat, &rd);
3852 ewah_each_bit(rd.sha1_valid, read_oid, &rd);
3853 next = rd.data;
3855 done:
3856 free(rd.ucd);
3857 ewah_free(rd.valid);
3858 ewah_free(rd.check_only);
3859 ewah_free(rd.sha1_valid);
3860 done2:
3861 if (next != end) {
3862 free_untracked_cache(uc);
3863 uc = NULL;
3865 return uc;
3868 static void invalidate_one_directory(struct untracked_cache *uc,
3869 struct untracked_cache_dir *ucd)
3871 uc->dir_invalidated++;
3872 ucd->valid = 0;
3873 ucd->untracked_nr = 0;
3877 * Normally when an entry is added or removed from a directory,
3878 * invalidating that directory is enough. No need to touch its
3879 * ancestors. When a directory is shown as "foo/bar/" in git-status
3880 * however, deleting or adding an entry may have cascading effect.
3882 * Say the "foo/bar/file" has become untracked, we need to tell the
3883 * untracked_cache_dir of "foo" that "bar/" is not an untracked
3884 * directory any more (because "bar" is managed by foo as an untracked
3885 * "file").
3887 * Similarly, if "foo/bar/file" moves from untracked to tracked and it
3888 * was the last untracked entry in the entire "foo", we should show
3889 * "foo/" instead. Which means we have to invalidate past "bar" up to
3890 * "foo".
3892 * This function traverses all directories from root to leaf. If there
3893 * is a chance of one of the above cases happening, we invalidate back
3894 * to root. Otherwise we just invalidate the leaf. There may be a more
3895 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to
3896 * detect these cases and avoid unnecessary invalidation, for example,
3897 * checking for the untracked entry named "bar/" in "foo", but for now
3898 * stick to something safe and simple.
3900 static int invalidate_one_component(struct untracked_cache *uc,
3901 struct untracked_cache_dir *dir,
3902 const char *path, int len)
3904 const char *rest = strchr(path, '/');
3906 if (rest) {
3907 int component_len = rest - path;
3908 struct untracked_cache_dir *d =
3909 lookup_untracked(uc, dir, path, component_len);
3910 int ret =
3911 invalidate_one_component(uc, d, rest + 1,
3912 len - (component_len + 1));
3913 if (ret)
3914 invalidate_one_directory(uc, dir);
3915 return ret;
3918 invalidate_one_directory(uc, dir);
3919 return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;
3922 void untracked_cache_invalidate_path(struct index_state *istate,
3923 const char *path, int safe_path)
3925 if (!istate->untracked || !istate->untracked->root)
3926 return;
3927 if (!safe_path && !verify_path(path, 0))
3928 return;
3929 invalidate_one_component(istate->untracked, istate->untracked->root,
3930 path, strlen(path));
3933 void untracked_cache_invalidate_trimmed_path(struct index_state *istate,
3934 const char *path,
3935 int safe_path)
3937 size_t len = strlen(path);
3939 if (!len)
3940 BUG("untracked_cache_invalidate_trimmed_path given zero length path");
3942 if (path[len - 1] != '/') {
3943 untracked_cache_invalidate_path(istate, path, safe_path);
3944 } else {
3945 struct strbuf tmp = STRBUF_INIT;
3947 strbuf_add(&tmp, path, len - 1);
3948 untracked_cache_invalidate_path(istate, tmp.buf, safe_path);
3949 strbuf_release(&tmp);
3953 void untracked_cache_remove_from_index(struct index_state *istate,
3954 const char *path)
3956 untracked_cache_invalidate_path(istate, path, 1);
3959 void untracked_cache_add_to_index(struct index_state *istate,
3960 const char *path)
3962 untracked_cache_invalidate_path(istate, path, 1);
3965 static void connect_wt_gitdir_in_nested(const char *sub_worktree,
3966 const char *sub_gitdir)
3968 int i;
3969 struct repository subrepo;
3970 struct strbuf sub_wt = STRBUF_INIT;
3971 struct strbuf sub_gd = STRBUF_INIT;
3973 const struct submodule *sub;
3975 /* If the submodule has no working tree, we can ignore it. */
3976 if (repo_init(&subrepo, sub_gitdir, sub_worktree))
3977 return;
3979 if (repo_read_index(&subrepo) < 0)
3980 die(_("index file corrupt in repo %s"), subrepo.gitdir);
3982 /* TODO: audit for interaction with sparse-index. */
3983 ensure_full_index(subrepo.index);
3984 for (i = 0; i < subrepo.index->cache_nr; i++) {
3985 const struct cache_entry *ce = subrepo.index->cache[i];
3987 if (!S_ISGITLINK(ce->ce_mode))
3988 continue;
3990 while (i + 1 < subrepo.index->cache_nr &&
3991 !strcmp(ce->name, subrepo.index->cache[i + 1]->name))
3993 * Skip entries with the same name in different stages
3994 * to make sure an entry is returned only once.
3996 i++;
3998 sub = submodule_from_path(&subrepo, null_oid(), ce->name);
3999 if (!sub || !is_submodule_active(&subrepo, ce->name))
4000 /* .gitmodules broken or inactive sub */
4001 continue;
4003 strbuf_reset(&sub_wt);
4004 strbuf_reset(&sub_gd);
4005 strbuf_addf(&sub_wt, "%s/%s", sub_worktree, sub->path);
4006 submodule_name_to_gitdir(&sub_gd, &subrepo, sub->name);
4008 connect_work_tree_and_git_dir(sub_wt.buf, sub_gd.buf, 1);
4010 strbuf_release(&sub_wt);
4011 strbuf_release(&sub_gd);
4012 repo_clear(&subrepo);
4015 void connect_work_tree_and_git_dir(const char *work_tree_,
4016 const char *git_dir_,
4017 int recurse_into_nested)
4019 struct strbuf gitfile_sb = STRBUF_INIT;
4020 struct strbuf cfg_sb = STRBUF_INIT;
4021 struct strbuf rel_path = STRBUF_INIT;
4022 char *git_dir, *work_tree;
4024 /* Prepare .git file */
4025 strbuf_addf(&gitfile_sb, "%s/.git", work_tree_);
4026 if (safe_create_leading_directories_const(gitfile_sb.buf))
4027 die(_("could not create directories for %s"), gitfile_sb.buf);
4029 /* Prepare config file */
4030 strbuf_addf(&cfg_sb, "%s/config", git_dir_);
4031 if (safe_create_leading_directories_const(cfg_sb.buf))
4032 die(_("could not create directories for %s"), cfg_sb.buf);
4034 git_dir = real_pathdup(git_dir_, 1);
4035 work_tree = real_pathdup(work_tree_, 1);
4037 /* Write .git file */
4038 write_file(gitfile_sb.buf, "gitdir: %s",
4039 relative_path(git_dir, work_tree, &rel_path));
4040 /* Update core.worktree setting */
4041 git_config_set_in_file(cfg_sb.buf, "core.worktree",
4042 relative_path(work_tree, git_dir, &rel_path));
4044 strbuf_release(&gitfile_sb);
4045 strbuf_release(&cfg_sb);
4046 strbuf_release(&rel_path);
4048 if (recurse_into_nested)
4049 connect_wt_gitdir_in_nested(work_tree, git_dir);
4051 free(work_tree);
4052 free(git_dir);
4056 * Migrate the git directory of the given path from old_git_dir to new_git_dir.
4058 void relocate_gitdir(const char *path, const char *old_git_dir, const char *new_git_dir)
4060 if (rename(old_git_dir, new_git_dir) < 0)
4061 die_errno(_("could not migrate git directory from '%s' to '%s'"),
4062 old_git_dir, new_git_dir);
4064 connect_work_tree_and_git_dir(path, new_git_dir, 0);
4067 int path_match_flags(const char *const str, const enum path_match_flags flags)
4069 const char *p = str;
4071 if (flags & PATH_MATCH_NATIVE &&
4072 flags & PATH_MATCH_XPLATFORM)
4073 BUG("path_match_flags() must get one match kind, not multiple!");
4074 else if (!(flags & PATH_MATCH_KINDS_MASK))
4075 BUG("path_match_flags() must get at least one match kind!");
4077 if (flags & PATH_MATCH_STARTS_WITH_DOT_SLASH &&
4078 flags & PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH)
4079 BUG("path_match_flags() must get one platform kind, not multiple!");
4080 else if (!(flags & PATH_MATCH_PLATFORM_MASK))
4081 BUG("path_match_flags() must get at least one platform kind!");
4083 if (*p++ != '.')
4084 return 0;
4085 if (flags & PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH &&
4086 *p++ != '.')
4087 return 0;
4089 if (flags & PATH_MATCH_NATIVE)
4090 return is_dir_sep(*p);
4091 else if (flags & PATH_MATCH_XPLATFORM)
4092 return is_xplatform_dir_sep(*p);
4093 BUG("unreachable");