Merge branch 'jc/varargs-attributes'
[git.git] / dir.c
blob45be4ad2615a4dff0439c9df77f63a70c34ba7b5
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"
33 #include "hex.h"
36 * The maximum size of a pattern/exclude file. If the file exceeds this size
37 * we will ignore it.
39 #define PATTERN_MAX_FILE_SIZE (100 * 1024 * 1024)
42 * Tells read_directory_recursive how a file or directory should be treated.
43 * Values are ordered by significance, e.g. if a directory contains both
44 * excluded and untracked files, it is listed as untracked because
45 * path_untracked > path_excluded.
47 enum path_treatment {
48 path_none = 0,
49 path_recurse,
50 path_excluded,
51 path_untracked
55 * Support data structure for our opendir/readdir/closedir wrappers
57 struct cached_dir {
58 DIR *fdir;
59 struct untracked_cache_dir *untracked;
60 int nr_files;
61 int nr_dirs;
63 const char *d_name;
64 int d_type;
65 const char *file;
66 struct untracked_cache_dir *ucd;
69 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
70 struct index_state *istate, const char *path, int len,
71 struct untracked_cache_dir *untracked,
72 int check_only, int stop_at_first_file, const struct pathspec *pathspec);
73 static int resolve_dtype(int dtype, struct index_state *istate,
74 const char *path, int len);
75 struct dirent *readdir_skip_dot_and_dotdot(DIR *dirp)
77 struct dirent *e;
79 while ((e = readdir(dirp)) != NULL) {
80 if (!is_dot_or_dotdot(e->d_name))
81 break;
83 return e;
86 int count_slashes(const char *s)
88 int cnt = 0;
89 while (*s)
90 if (*s++ == '/')
91 cnt++;
92 return cnt;
95 int fspathcmp(const char *a, const char *b)
97 return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
100 int fspatheq(const char *a, const char *b)
102 return !fspathcmp(a, b);
105 int fspathncmp(const char *a, const char *b, size_t count)
107 return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
110 int paths_collide(const char *a, const char *b)
112 size_t len_a = strlen(a), len_b = strlen(b);
114 if (len_a == len_b)
115 return fspatheq(a, b);
117 if (len_a < len_b)
118 return is_dir_sep(b[len_a]) && !fspathncmp(a, b, len_a);
119 return is_dir_sep(a[len_b]) && !fspathncmp(a, b, len_b);
122 unsigned int fspathhash(const char *str)
124 return ignore_case ? strihash(str) : strhash(str);
127 int git_fnmatch(const struct pathspec_item *item,
128 const char *pattern, const char *string,
129 int prefix)
131 if (prefix > 0) {
132 if (ps_strncmp(item, pattern, string, prefix))
133 return WM_NOMATCH;
134 pattern += prefix;
135 string += prefix;
137 if (item->flags & PATHSPEC_ONESTAR) {
138 int pattern_len = strlen(++pattern);
139 int string_len = strlen(string);
140 return string_len < pattern_len ||
141 ps_strcmp(item, pattern,
142 string + string_len - pattern_len);
144 if (item->magic & PATHSPEC_GLOB)
145 return wildmatch(pattern, string,
146 WM_PATHNAME |
147 (item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0));
148 else
149 /* wildmatch has not learned no FNM_PATHNAME mode yet */
150 return wildmatch(pattern, string,
151 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0);
154 static int fnmatch_icase_mem(const char *pattern, int patternlen,
155 const char *string, int stringlen,
156 int flags)
158 int match_status;
159 struct strbuf pat_buf = STRBUF_INIT;
160 struct strbuf str_buf = STRBUF_INIT;
161 const char *use_pat = pattern;
162 const char *use_str = string;
164 if (pattern[patternlen]) {
165 strbuf_add(&pat_buf, pattern, patternlen);
166 use_pat = pat_buf.buf;
168 if (string[stringlen]) {
169 strbuf_add(&str_buf, string, stringlen);
170 use_str = str_buf.buf;
173 if (ignore_case)
174 flags |= WM_CASEFOLD;
175 match_status = wildmatch(use_pat, use_str, flags);
177 strbuf_release(&pat_buf);
178 strbuf_release(&str_buf);
180 return match_status;
183 static size_t common_prefix_len(const struct pathspec *pathspec)
185 int n;
186 size_t max = 0;
189 * ":(icase)path" is treated as a pathspec full of
190 * wildcard. In other words, only prefix is considered common
191 * prefix. If the pathspec is abc/foo abc/bar, running in
192 * subdir xyz, the common prefix is still xyz, not xyz/abc as
193 * in non-:(icase).
195 GUARD_PATHSPEC(pathspec,
196 PATHSPEC_FROMTOP |
197 PATHSPEC_MAXDEPTH |
198 PATHSPEC_LITERAL |
199 PATHSPEC_GLOB |
200 PATHSPEC_ICASE |
201 PATHSPEC_EXCLUDE |
202 PATHSPEC_ATTR);
204 for (n = 0; n < pathspec->nr; n++) {
205 size_t i = 0, len = 0, item_len;
206 if (pathspec->items[n].magic & PATHSPEC_EXCLUDE)
207 continue;
208 if (pathspec->items[n].magic & PATHSPEC_ICASE)
209 item_len = pathspec->items[n].prefix;
210 else
211 item_len = pathspec->items[n].nowildcard_len;
212 while (i < item_len && (n == 0 || i < max)) {
213 char c = pathspec->items[n].match[i];
214 if (c != pathspec->items[0].match[i])
215 break;
216 if (c == '/')
217 len = i + 1;
218 i++;
220 if (n == 0 || len < max) {
221 max = len;
222 if (!max)
223 break;
226 return max;
230 * Returns a copy of the longest leading path common among all
231 * pathspecs.
233 char *common_prefix(const struct pathspec *pathspec)
235 unsigned long len = common_prefix_len(pathspec);
237 return len ? xmemdupz(pathspec->items[0].match, len) : NULL;
240 int fill_directory(struct dir_struct *dir,
241 struct index_state *istate,
242 const struct pathspec *pathspec)
244 const char *prefix;
245 size_t prefix_len;
247 unsigned exclusive_flags = DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO;
248 if ((dir->flags & exclusive_flags) == exclusive_flags)
249 BUG("DIR_SHOW_IGNORED and DIR_SHOW_IGNORED_TOO are exclusive");
252 * Calculate common prefix for the pathspec, and
253 * use that to optimize the directory walk
255 prefix_len = common_prefix_len(pathspec);
256 prefix = prefix_len ? pathspec->items[0].match : "";
258 /* Read the directory and prune it */
259 read_directory(dir, istate, prefix, prefix_len, pathspec);
261 return prefix_len;
264 int within_depth(const char *name, int namelen,
265 int depth, int max_depth)
267 const char *cp = name, *cpe = name + namelen;
269 while (cp < cpe) {
270 if (*cp++ != '/')
271 continue;
272 depth++;
273 if (depth > max_depth)
274 return 0;
276 return 1;
280 * Read the contents of the blob with the given OID into a buffer.
281 * Append a trailing LF to the end if the last line doesn't have one.
283 * Returns:
284 * -1 when the OID is invalid or unknown or does not refer to a blob.
285 * 0 when the blob is empty.
286 * 1 along with { data, size } of the (possibly augmented) buffer
287 * when successful.
289 * Optionally updates the given oid_stat with the given OID (when valid).
291 static int do_read_blob(const struct object_id *oid, struct oid_stat *oid_stat,
292 size_t *size_out, char **data_out)
294 enum object_type type;
295 unsigned long sz;
296 char *data;
298 *size_out = 0;
299 *data_out = NULL;
301 data = repo_read_object_file(the_repository, oid, &type, &sz);
302 if (!data || type != OBJ_BLOB) {
303 free(data);
304 return -1;
307 if (oid_stat) {
308 memset(&oid_stat->stat, 0, sizeof(oid_stat->stat));
309 oidcpy(&oid_stat->oid, oid);
312 if (sz == 0) {
313 free(data);
314 return 0;
317 if (data[sz - 1] != '\n') {
318 data = xrealloc(data, st_add(sz, 1));
319 data[sz++] = '\n';
322 *size_out = xsize_t(sz);
323 *data_out = data;
325 return 1;
328 #define DO_MATCH_EXCLUDE (1<<0)
329 #define DO_MATCH_DIRECTORY (1<<1)
330 #define DO_MATCH_LEADING_PATHSPEC (1<<2)
333 * Does the given pathspec match the given name? A match is found if
335 * (1) the pathspec string is leading directory of 'name' ("RECURSIVELY"), or
336 * (2) the pathspec string has a leading part matching 'name' ("LEADING"), or
337 * (3) the pathspec string is a wildcard and matches 'name' ("WILDCARD"), or
338 * (4) the pathspec string is exactly the same as 'name' ("EXACT").
340 * Return value tells which case it was (1-4), or 0 when there is no match.
342 * It may be instructive to look at a small table of concrete examples
343 * to understand the differences between 1, 2, and 4:
345 * Pathspecs
346 * | a/b | a/b/ | a/b/c
347 * ------+-----------+-----------+------------
348 * a/b | EXACT | EXACT[1] | LEADING[2]
349 * Names a/b/ | RECURSIVE | EXACT | LEADING[2]
350 * a/b/c | RECURSIVE | RECURSIVE | EXACT
352 * [1] Only if DO_MATCH_DIRECTORY is passed; otherwise, this is NOT a match.
353 * [2] Only if DO_MATCH_LEADING_PATHSPEC is passed; otherwise, not a match.
355 static int match_pathspec_item(struct index_state *istate,
356 const struct pathspec_item *item, int prefix,
357 const char *name, int namelen, unsigned flags)
359 /* name/namelen has prefix cut off by caller */
360 const char *match = item->match + prefix;
361 int matchlen = item->len - prefix;
364 * The normal call pattern is:
365 * 1. prefix = common_prefix_len(ps);
366 * 2. prune something, or fill_directory
367 * 3. match_pathspec()
369 * 'prefix' at #1 may be shorter than the command's prefix and
370 * it's ok for #2 to match extra files. Those extras will be
371 * trimmed at #3.
373 * Suppose the pathspec is 'foo' and '../bar' running from
374 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
375 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
376 * user does not want XYZ/foo, only the "foo" part should be
377 * case-insensitive. We need to filter out XYZ/foo here. In
378 * other words, we do not trust the caller on comparing the
379 * prefix part when :(icase) is involved. We do exact
380 * comparison ourselves.
382 * Normally the caller (common_prefix_len() in fact) does
383 * _exact_ matching on name[-prefix+1..-1] and we do not need
384 * to check that part. Be defensive and check it anyway, in
385 * case common_prefix_len is changed, or a new caller is
386 * introduced that does not use common_prefix_len.
388 * If the penalty turns out too high when prefix is really
389 * long, maybe change it to
390 * strncmp(match, name, item->prefix - prefix)
392 if (item->prefix && (item->magic & PATHSPEC_ICASE) &&
393 strncmp(item->match, name - prefix, item->prefix))
394 return 0;
396 if (item->attr_match_nr &&
397 !match_pathspec_attrs(istate, name - prefix, namelen + prefix, item))
398 return 0;
400 /* If the match was just the prefix, we matched */
401 if (!*match)
402 return MATCHED_RECURSIVELY;
404 if (matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) {
405 if (matchlen == namelen)
406 return MATCHED_EXACTLY;
408 if (match[matchlen-1] == '/' || name[matchlen] == '/')
409 return MATCHED_RECURSIVELY;
410 } else if ((flags & DO_MATCH_DIRECTORY) &&
411 match[matchlen - 1] == '/' &&
412 namelen == matchlen - 1 &&
413 !ps_strncmp(item, match, name, namelen))
414 return MATCHED_EXACTLY;
416 if (item->nowildcard_len < item->len &&
417 !git_fnmatch(item, match, name,
418 item->nowildcard_len - prefix))
419 return MATCHED_FNMATCH;
421 /* Perform checks to see if "name" is a leading string of the pathspec */
422 if ( (flags & DO_MATCH_LEADING_PATHSPEC) &&
423 !(flags & DO_MATCH_EXCLUDE)) {
424 /* name is a literal prefix of the pathspec */
425 int offset = name[namelen-1] == '/' ? 1 : 0;
426 if ((namelen < matchlen) &&
427 (match[namelen-offset] == '/') &&
428 !ps_strncmp(item, match, name, namelen))
429 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
431 /* name doesn't match up to the first wild character */
432 if (item->nowildcard_len < item->len &&
433 ps_strncmp(item, match, name,
434 item->nowildcard_len - prefix))
435 return 0;
438 * name has no wildcard, and it didn't match as a leading
439 * pathspec so return.
441 if (item->nowildcard_len == item->len)
442 return 0;
445 * Here is where we would perform a wildmatch to check if
446 * "name" can be matched as a directory (or a prefix) against
447 * the pathspec. Since wildmatch doesn't have this capability
448 * at the present we have to punt and say that it is a match,
449 * potentially returning a false positive
450 * The submodules themselves will be able to perform more
451 * accurate matching to determine if the pathspec matches.
453 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
456 return 0;
460 * do_match_pathspec() is meant to ONLY be called by
461 * match_pathspec_with_flags(); calling it directly risks pathspecs
462 * like ':!unwanted_path' being ignored.
464 * Given a name and a list of pathspecs, returns the nature of the
465 * closest (i.e. most specific) match of the name to any of the
466 * pathspecs.
468 * The caller typically calls this multiple times with the same
469 * pathspec and seen[] array but with different name/namelen
470 * (e.g. entries from the index) and is interested in seeing if and
471 * how each pathspec matches all the names it calls this function
472 * with. A mark is left in the seen[] array for each pathspec element
473 * indicating the closest type of match that element achieved, so if
474 * seen[n] remains zero after multiple invocations, that means the nth
475 * pathspec did not match any names, which could indicate that the
476 * user mistyped the nth pathspec.
478 static int do_match_pathspec(struct index_state *istate,
479 const struct pathspec *ps,
480 const char *name, int namelen,
481 int prefix, char *seen,
482 unsigned flags)
484 int i, retval = 0, exclude = flags & DO_MATCH_EXCLUDE;
486 GUARD_PATHSPEC(ps,
487 PATHSPEC_FROMTOP |
488 PATHSPEC_MAXDEPTH |
489 PATHSPEC_LITERAL |
490 PATHSPEC_GLOB |
491 PATHSPEC_ICASE |
492 PATHSPEC_EXCLUDE |
493 PATHSPEC_ATTR);
495 if (!ps->nr) {
496 if (!ps->recursive ||
497 !(ps->magic & PATHSPEC_MAXDEPTH) ||
498 ps->max_depth == -1)
499 return MATCHED_RECURSIVELY;
501 if (within_depth(name, namelen, 0, ps->max_depth))
502 return MATCHED_EXACTLY;
503 else
504 return 0;
507 name += prefix;
508 namelen -= prefix;
510 for (i = ps->nr - 1; i >= 0; i--) {
511 int how;
513 if ((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) ||
514 ( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE)))
515 continue;
517 if (seen && seen[i] == MATCHED_EXACTLY)
518 continue;
520 * Make exclude patterns optional and never report
521 * "pathspec ':(exclude)foo' matches no files"
523 if (seen && ps->items[i].magic & PATHSPEC_EXCLUDE)
524 seen[i] = MATCHED_FNMATCH;
525 how = match_pathspec_item(istate, ps->items+i, prefix, name,
526 namelen, flags);
527 if (ps->recursive &&
528 (ps->magic & PATHSPEC_MAXDEPTH) &&
529 ps->max_depth != -1 &&
530 how && how != MATCHED_FNMATCH) {
531 int len = ps->items[i].len;
532 if (name[len] == '/')
533 len++;
534 if (within_depth(name+len, namelen-len, 0, ps->max_depth))
535 how = MATCHED_EXACTLY;
536 else
537 how = 0;
539 if (how) {
540 if (retval < how)
541 retval = how;
542 if (seen && seen[i] < how)
543 seen[i] = how;
546 return retval;
549 static int match_pathspec_with_flags(struct index_state *istate,
550 const struct pathspec *ps,
551 const char *name, int namelen,
552 int prefix, char *seen, unsigned flags)
554 int positive, negative;
555 positive = do_match_pathspec(istate, ps, name, namelen,
556 prefix, seen, flags);
557 if (!(ps->magic & PATHSPEC_EXCLUDE) || !positive)
558 return positive;
559 negative = do_match_pathspec(istate, ps, name, namelen,
560 prefix, seen,
561 flags | DO_MATCH_EXCLUDE);
562 return negative ? 0 : positive;
565 int match_pathspec(struct index_state *istate,
566 const struct pathspec *ps,
567 const char *name, int namelen,
568 int prefix, char *seen, int is_dir)
570 unsigned flags = is_dir ? DO_MATCH_DIRECTORY : 0;
571 return match_pathspec_with_flags(istate, ps, name, namelen,
572 prefix, seen, flags);
576 * Check if a submodule is a superset of the pathspec
578 int submodule_path_match(struct index_state *istate,
579 const struct pathspec *ps,
580 const char *submodule_name,
581 char *seen)
583 int matched = match_pathspec_with_flags(istate, ps, submodule_name,
584 strlen(submodule_name),
585 0, seen,
586 DO_MATCH_DIRECTORY |
587 DO_MATCH_LEADING_PATHSPEC);
588 return matched;
591 int report_path_error(const char *ps_matched,
592 const struct pathspec *pathspec)
595 * Make sure all pathspec matched; otherwise it is an error.
597 int num, errors = 0;
598 for (num = 0; num < pathspec->nr; num++) {
599 int other, found_dup;
601 if (ps_matched[num])
602 continue;
604 * The caller might have fed identical pathspec
605 * twice. Do not barf on such a mistake.
606 * FIXME: parse_pathspec should have eliminated
607 * duplicate pathspec.
609 for (found_dup = other = 0;
610 !found_dup && other < pathspec->nr;
611 other++) {
612 if (other == num || !ps_matched[other])
613 continue;
614 if (!strcmp(pathspec->items[other].original,
615 pathspec->items[num].original))
617 * Ok, we have a match already.
619 found_dup = 1;
621 if (found_dup)
622 continue;
624 error(_("pathspec '%s' did not match any file(s) known to git"),
625 pathspec->items[num].original);
626 errors++;
628 return errors;
632 * Return the length of the "simple" part of a path match limiter.
634 int simple_length(const char *match)
636 int len = -1;
638 for (;;) {
639 unsigned char c = *match++;
640 len++;
641 if (c == '\0' || is_glob_special(c))
642 return len;
646 int no_wildcard(const char *string)
648 return string[simple_length(string)] == '\0';
651 void parse_path_pattern(const char **pattern,
652 int *patternlen,
653 unsigned *flags,
654 int *nowildcardlen)
656 const char *p = *pattern;
657 size_t i, len;
659 *flags = 0;
660 if (*p == '!') {
661 *flags |= PATTERN_FLAG_NEGATIVE;
662 p++;
664 len = strlen(p);
665 if (len && p[len - 1] == '/') {
666 len--;
667 *flags |= PATTERN_FLAG_MUSTBEDIR;
669 for (i = 0; i < len; i++) {
670 if (p[i] == '/')
671 break;
673 if (i == len)
674 *flags |= PATTERN_FLAG_NODIR;
675 *nowildcardlen = simple_length(p);
677 * we should have excluded the trailing slash from 'p' too,
678 * but that's one more allocation. Instead just make sure
679 * nowildcardlen does not exceed real patternlen
681 if (*nowildcardlen > len)
682 *nowildcardlen = len;
683 if (*p == '*' && no_wildcard(p + 1))
684 *flags |= PATTERN_FLAG_ENDSWITH;
685 *pattern = p;
686 *patternlen = len;
689 int pl_hashmap_cmp(const void *cmp_data UNUSED,
690 const struct hashmap_entry *a,
691 const struct hashmap_entry *b,
692 const void *key UNUSED)
694 const struct pattern_entry *ee1 =
695 container_of(a, struct pattern_entry, ent);
696 const struct pattern_entry *ee2 =
697 container_of(b, struct pattern_entry, ent);
699 size_t min_len = ee1->patternlen <= ee2->patternlen
700 ? ee1->patternlen
701 : ee2->patternlen;
703 return fspathncmp(ee1->pattern, ee2->pattern, min_len);
706 static char *dup_and_filter_pattern(const char *pattern)
708 char *set, *read;
709 size_t count = 0;
710 char *result = xstrdup(pattern);
712 set = result;
713 read = result;
715 while (*read) {
716 /* skip escape characters (once) */
717 if (*read == '\\')
718 read++;
720 *set = *read;
722 set++;
723 read++;
724 count++;
726 *set = 0;
728 if (count > 2 &&
729 *(set - 1) == '*' &&
730 *(set - 2) == '/')
731 *(set - 2) = 0;
733 return result;
736 static void clear_pattern_entry_hashmap(struct hashmap *map)
738 struct hashmap_iter iter;
739 struct pattern_entry *entry;
741 hashmap_for_each_entry(map, &iter, entry, ent) {
742 free(entry->pattern);
744 hashmap_clear_and_free(map, struct pattern_entry, ent);
747 static void add_pattern_to_hashsets(struct pattern_list *pl, struct path_pattern *given)
749 struct pattern_entry *translated;
750 char *truncated;
751 char *data = NULL;
752 const char *prev, *cur, *next;
754 if (!pl->use_cone_patterns)
755 return;
757 if (given->flags & PATTERN_FLAG_NEGATIVE &&
758 given->flags & PATTERN_FLAG_MUSTBEDIR &&
759 !strcmp(given->pattern, "/*")) {
760 pl->full_cone = 0;
761 return;
764 if (!given->flags && !strcmp(given->pattern, "/*")) {
765 pl->full_cone = 1;
766 return;
769 if (given->patternlen < 2 ||
770 *given->pattern != '/' ||
771 strstr(given->pattern, "**")) {
772 /* Not a cone pattern. */
773 warning(_("unrecognized pattern: '%s'"), given->pattern);
774 goto clear_hashmaps;
777 if (!(given->flags & PATTERN_FLAG_MUSTBEDIR) &&
778 strcmp(given->pattern, "/*")) {
779 /* Not a cone pattern. */
780 warning(_("unrecognized pattern: '%s'"), given->pattern);
781 goto clear_hashmaps;
784 prev = given->pattern;
785 cur = given->pattern + 1;
786 next = given->pattern + 2;
788 while (*cur) {
789 /* Watch for glob characters '*', '\', '[', '?' */
790 if (!is_glob_special(*cur))
791 goto increment;
793 /* But only if *prev != '\\' */
794 if (*prev == '\\')
795 goto increment;
797 /* But allow the initial '\' */
798 if (*cur == '\\' &&
799 is_glob_special(*next))
800 goto increment;
802 /* But a trailing '/' then '*' is fine */
803 if (*prev == '/' &&
804 *cur == '*' &&
805 *next == 0)
806 goto increment;
808 /* Not a cone pattern. */
809 warning(_("unrecognized pattern: '%s'"), given->pattern);
810 goto clear_hashmaps;
812 increment:
813 prev++;
814 cur++;
815 next++;
818 if (given->patternlen > 2 &&
819 !strcmp(given->pattern + given->patternlen - 2, "/*")) {
820 struct pattern_entry *old;
822 if (!(given->flags & PATTERN_FLAG_NEGATIVE)) {
823 /* Not a cone pattern. */
824 warning(_("unrecognized pattern: '%s'"), given->pattern);
825 goto clear_hashmaps;
828 truncated = dup_and_filter_pattern(given->pattern);
830 translated = xmalloc(sizeof(struct pattern_entry));
831 translated->pattern = truncated;
832 translated->patternlen = given->patternlen - 2;
833 hashmap_entry_init(&translated->ent,
834 fspathhash(translated->pattern));
836 if (!hashmap_get_entry(&pl->recursive_hashmap,
837 translated, ent, NULL)) {
838 /* We did not see the "parent" included */
839 warning(_("unrecognized negative pattern: '%s'"),
840 given->pattern);
841 free(truncated);
842 free(translated);
843 goto clear_hashmaps;
846 hashmap_add(&pl->parent_hashmap, &translated->ent);
847 old = hashmap_remove_entry(&pl->recursive_hashmap, translated, ent, &data);
848 if (old) {
849 free(old->pattern);
850 free(old);
852 free(data);
853 return;
856 if (given->flags & PATTERN_FLAG_NEGATIVE) {
857 warning(_("unrecognized negative pattern: '%s'"),
858 given->pattern);
859 goto clear_hashmaps;
862 translated = xmalloc(sizeof(struct pattern_entry));
864 translated->pattern = dup_and_filter_pattern(given->pattern);
865 translated->patternlen = given->patternlen;
866 hashmap_entry_init(&translated->ent,
867 fspathhash(translated->pattern));
869 hashmap_add(&pl->recursive_hashmap, &translated->ent);
871 if (hashmap_get_entry(&pl->parent_hashmap, translated, ent, NULL)) {
872 /* we already included this at the parent level */
873 warning(_("your sparse-checkout file may have issues: pattern '%s' is repeated"),
874 given->pattern);
875 goto clear_hashmaps;
878 return;
880 clear_hashmaps:
881 warning(_("disabling cone pattern matching"));
882 clear_pattern_entry_hashmap(&pl->recursive_hashmap);
883 clear_pattern_entry_hashmap(&pl->parent_hashmap);
884 pl->use_cone_patterns = 0;
887 static int hashmap_contains_path(struct hashmap *map,
888 struct strbuf *pattern)
890 struct pattern_entry p;
892 /* Check straight mapping */
893 p.pattern = pattern->buf;
894 p.patternlen = pattern->len;
895 hashmap_entry_init(&p.ent, fspathhash(p.pattern));
896 return !!hashmap_get_entry(map, &p, ent, NULL);
899 int hashmap_contains_parent(struct hashmap *map,
900 const char *path,
901 struct strbuf *buffer)
903 char *slash_pos;
905 strbuf_setlen(buffer, 0);
907 if (path[0] != '/')
908 strbuf_addch(buffer, '/');
910 strbuf_addstr(buffer, path);
912 slash_pos = strrchr(buffer->buf, '/');
914 while (slash_pos > buffer->buf) {
915 strbuf_setlen(buffer, slash_pos - buffer->buf);
917 if (hashmap_contains_path(map, buffer))
918 return 1;
920 slash_pos = strrchr(buffer->buf, '/');
923 return 0;
926 void add_pattern(const char *string, const char *base,
927 int baselen, struct pattern_list *pl, int srcpos)
929 struct path_pattern *pattern;
930 int patternlen;
931 unsigned flags;
932 int nowildcardlen;
934 parse_path_pattern(&string, &patternlen, &flags, &nowildcardlen);
935 FLEX_ALLOC_MEM(pattern, pattern, string, patternlen);
936 pattern->patternlen = patternlen;
937 pattern->nowildcardlen = nowildcardlen;
938 pattern->base = base;
939 pattern->baselen = baselen;
940 pattern->flags = flags;
941 pattern->srcpos = srcpos;
942 ALLOC_GROW(pl->patterns, pl->nr + 1, pl->alloc);
943 pl->patterns[pl->nr++] = pattern;
944 pattern->pl = pl;
946 add_pattern_to_hashsets(pl, pattern);
949 static int read_skip_worktree_file_from_index(struct index_state *istate,
950 const char *path,
951 size_t *size_out, char **data_out,
952 struct oid_stat *oid_stat)
954 int pos, len;
956 len = strlen(path);
957 pos = index_name_pos(istate, path, len);
958 if (pos < 0)
959 return -1;
960 if (!ce_skip_worktree(istate->cache[pos]))
961 return -1;
963 return do_read_blob(&istate->cache[pos]->oid, oid_stat, size_out, data_out);
967 * Frees memory within pl which was allocated for exclude patterns and
968 * the file buffer. Does not free pl itself.
970 void clear_pattern_list(struct pattern_list *pl)
972 int i;
974 for (i = 0; i < pl->nr; i++)
975 free(pl->patterns[i]);
976 free(pl->patterns);
977 clear_pattern_entry_hashmap(&pl->recursive_hashmap);
978 clear_pattern_entry_hashmap(&pl->parent_hashmap);
980 memset(pl, 0, sizeof(*pl));
983 static void trim_trailing_spaces(char *buf)
985 char *p, *last_space = NULL;
987 for (p = buf; *p; p++)
988 switch (*p) {
989 case ' ':
990 if (!last_space)
991 last_space = p;
992 break;
993 case '\\':
994 p++;
995 if (!*p)
996 return;
997 /* fallthrough */
998 default:
999 last_space = NULL;
1002 if (last_space)
1003 *last_space = '\0';
1007 * Given a subdirectory name and "dir" of the current directory,
1008 * search the subdir in "dir" and return it, or create a new one if it
1009 * does not exist in "dir".
1011 * If "name" has the trailing slash, it'll be excluded in the search.
1013 static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc,
1014 struct untracked_cache_dir *dir,
1015 const char *name, int len)
1017 int first, last;
1018 struct untracked_cache_dir *d;
1019 if (!dir)
1020 return NULL;
1021 if (len && name[len - 1] == '/')
1022 len--;
1023 first = 0;
1024 last = dir->dirs_nr;
1025 while (last > first) {
1026 int cmp, next = first + ((last - first) >> 1);
1027 d = dir->dirs[next];
1028 cmp = strncmp(name, d->name, len);
1029 if (!cmp && strlen(d->name) > len)
1030 cmp = -1;
1031 if (!cmp)
1032 return d;
1033 if (cmp < 0) {
1034 last = next;
1035 continue;
1037 first = next+1;
1040 uc->dir_created++;
1041 FLEX_ALLOC_MEM(d, name, name, len);
1043 ALLOC_GROW(dir->dirs, dir->dirs_nr + 1, dir->dirs_alloc);
1044 MOVE_ARRAY(dir->dirs + first + 1, dir->dirs + first,
1045 dir->dirs_nr - first);
1046 dir->dirs_nr++;
1047 dir->dirs[first] = d;
1048 return d;
1051 static void do_invalidate_gitignore(struct untracked_cache_dir *dir)
1053 int i;
1054 dir->valid = 0;
1055 dir->untracked_nr = 0;
1056 for (i = 0; i < dir->dirs_nr; i++)
1057 do_invalidate_gitignore(dir->dirs[i]);
1060 static void invalidate_gitignore(struct untracked_cache *uc,
1061 struct untracked_cache_dir *dir)
1063 uc->gitignore_invalidated++;
1064 do_invalidate_gitignore(dir);
1067 static void invalidate_directory(struct untracked_cache *uc,
1068 struct untracked_cache_dir *dir)
1070 int i;
1073 * Invalidation increment here is just roughly correct. If
1074 * untracked_nr or any of dirs[].recurse is non-zero, we
1075 * should increment dir_invalidated too. But that's more
1076 * expensive to do.
1078 if (dir->valid)
1079 uc->dir_invalidated++;
1081 dir->valid = 0;
1082 dir->untracked_nr = 0;
1083 for (i = 0; i < dir->dirs_nr; i++)
1084 dir->dirs[i]->recurse = 0;
1087 static int add_patterns_from_buffer(char *buf, size_t size,
1088 const char *base, int baselen,
1089 struct pattern_list *pl);
1091 /* Flags for add_patterns() */
1092 #define PATTERN_NOFOLLOW (1<<0)
1095 * Given a file with name "fname", read it (either from disk, or from
1096 * an index if 'istate' is non-null), parse it and store the
1097 * exclude rules in "pl".
1099 * If "oid_stat" is not NULL, compute oid of the exclude file and fill
1100 * stat data from disk (only valid if add_patterns returns zero). If
1101 * oid_stat.valid is non-zero, "oid_stat" must contain good value as input.
1103 static int add_patterns(const char *fname, const char *base, int baselen,
1104 struct pattern_list *pl, struct index_state *istate,
1105 unsigned flags, struct oid_stat *oid_stat)
1107 struct stat st;
1108 int r;
1109 int fd;
1110 size_t size = 0;
1111 char *buf;
1113 if (flags & PATTERN_NOFOLLOW)
1114 fd = open_nofollow(fname, O_RDONLY);
1115 else
1116 fd = open(fname, O_RDONLY);
1118 if (fd < 0 || fstat(fd, &st) < 0) {
1119 if (fd < 0)
1120 warn_on_fopen_errors(fname);
1121 else
1122 close(fd);
1123 if (!istate)
1124 return -1;
1125 r = read_skip_worktree_file_from_index(istate, fname,
1126 &size, &buf,
1127 oid_stat);
1128 if (r != 1)
1129 return r;
1130 } else {
1131 size = xsize_t(st.st_size);
1132 if (size == 0) {
1133 if (oid_stat) {
1134 fill_stat_data(&oid_stat->stat, &st);
1135 oidcpy(&oid_stat->oid, the_hash_algo->empty_blob);
1136 oid_stat->valid = 1;
1138 close(fd);
1139 return 0;
1141 buf = xmallocz(size);
1142 if (read_in_full(fd, buf, size) != size) {
1143 free(buf);
1144 close(fd);
1145 return -1;
1147 buf[size++] = '\n';
1148 close(fd);
1149 if (oid_stat) {
1150 int pos;
1151 if (oid_stat->valid &&
1152 !match_stat_data_racy(istate, &oid_stat->stat, &st))
1153 ; /* no content change, oid_stat->oid still good */
1154 else if (istate &&
1155 (pos = index_name_pos(istate, fname, strlen(fname))) >= 0 &&
1156 !ce_stage(istate->cache[pos]) &&
1157 ce_uptodate(istate->cache[pos]) &&
1158 !would_convert_to_git(istate, fname))
1159 oidcpy(&oid_stat->oid,
1160 &istate->cache[pos]->oid);
1161 else
1162 hash_object_file(the_hash_algo, buf, size,
1163 OBJ_BLOB, &oid_stat->oid);
1164 fill_stat_data(&oid_stat->stat, &st);
1165 oid_stat->valid = 1;
1169 if (size > PATTERN_MAX_FILE_SIZE) {
1170 warning("ignoring excessively large pattern file: %s", fname);
1171 free(buf);
1172 return -1;
1175 add_patterns_from_buffer(buf, size, base, baselen, pl);
1176 free(buf);
1177 return 0;
1180 static int add_patterns_from_buffer(char *buf, size_t size,
1181 const char *base, int baselen,
1182 struct pattern_list *pl)
1184 char *orig = buf;
1185 int i, lineno = 1;
1186 char *entry;
1188 hashmap_init(&pl->recursive_hashmap, pl_hashmap_cmp, NULL, 0);
1189 hashmap_init(&pl->parent_hashmap, pl_hashmap_cmp, NULL, 0);
1191 if (skip_utf8_bom(&buf, size))
1192 size -= buf - orig;
1194 entry = buf;
1196 for (i = 0; i < size; i++) {
1197 if (buf[i] == '\n') {
1198 if (entry != buf + i && entry[0] != '#') {
1199 buf[i - (i && buf[i-1] == '\r')] = 0;
1200 trim_trailing_spaces(entry);
1201 add_pattern(entry, base, baselen, pl, lineno);
1203 lineno++;
1204 entry = buf + i + 1;
1207 return 0;
1210 int add_patterns_from_file_to_list(const char *fname, const char *base,
1211 int baselen, struct pattern_list *pl,
1212 struct index_state *istate,
1213 unsigned flags)
1215 return add_patterns(fname, base, baselen, pl, istate, flags, NULL);
1218 int add_patterns_from_blob_to_list(
1219 struct object_id *oid,
1220 const char *base, int baselen,
1221 struct pattern_list *pl)
1223 char *buf;
1224 size_t size;
1225 int r;
1227 r = do_read_blob(oid, NULL, &size, &buf);
1228 if (r != 1)
1229 return r;
1231 if (size > PATTERN_MAX_FILE_SIZE) {
1232 warning("ignoring excessively large pattern blob: %s",
1233 oid_to_hex(oid));
1234 free(buf);
1235 return -1;
1238 add_patterns_from_buffer(buf, size, base, baselen, pl);
1239 free(buf);
1240 return 0;
1243 struct pattern_list *add_pattern_list(struct dir_struct *dir,
1244 int group_type, const char *src)
1246 struct pattern_list *pl;
1247 struct exclude_list_group *group;
1249 group = &dir->internal.exclude_list_group[group_type];
1250 ALLOC_GROW(group->pl, group->nr + 1, group->alloc);
1251 pl = &group->pl[group->nr++];
1252 memset(pl, 0, sizeof(*pl));
1253 pl->src = src;
1254 return pl;
1258 * Used to set up core.excludesfile and .git/info/exclude lists.
1260 static void add_patterns_from_file_1(struct dir_struct *dir, const char *fname,
1261 struct oid_stat *oid_stat)
1263 struct pattern_list *pl;
1265 * catch setup_standard_excludes() that's called before
1266 * dir->untracked is assigned. That function behaves
1267 * differently when dir->untracked is non-NULL.
1269 if (!dir->untracked)
1270 dir->internal.unmanaged_exclude_files++;
1271 pl = add_pattern_list(dir, EXC_FILE, fname);
1272 if (add_patterns(fname, "", 0, pl, NULL, 0, oid_stat) < 0)
1273 die(_("cannot use %s as an exclude file"), fname);
1276 void add_patterns_from_file(struct dir_struct *dir, const char *fname)
1278 dir->internal.unmanaged_exclude_files++; /* see validate_untracked_cache() */
1279 add_patterns_from_file_1(dir, fname, NULL);
1282 int match_basename(const char *basename, int basenamelen,
1283 const char *pattern, int prefix, int patternlen,
1284 unsigned flags)
1286 if (prefix == patternlen) {
1287 if (patternlen == basenamelen &&
1288 !fspathncmp(pattern, basename, basenamelen))
1289 return 1;
1290 } else if (flags & PATTERN_FLAG_ENDSWITH) {
1291 /* "*literal" matching against "fooliteral" */
1292 if (patternlen - 1 <= basenamelen &&
1293 !fspathncmp(pattern + 1,
1294 basename + basenamelen - (patternlen - 1),
1295 patternlen - 1))
1296 return 1;
1297 } else {
1298 if (fnmatch_icase_mem(pattern, patternlen,
1299 basename, basenamelen,
1300 0) == 0)
1301 return 1;
1303 return 0;
1306 int match_pathname(const char *pathname, int pathlen,
1307 const char *base, int baselen,
1308 const char *pattern, int prefix, int patternlen)
1310 const char *name;
1311 int namelen;
1314 * match with FNM_PATHNAME; the pattern has base implicitly
1315 * in front of it.
1317 if (*pattern == '/') {
1318 pattern++;
1319 patternlen--;
1320 prefix--;
1324 * baselen does not count the trailing slash. base[] may or
1325 * may not end with a trailing slash though.
1327 if (pathlen < baselen + 1 ||
1328 (baselen && pathname[baselen] != '/') ||
1329 fspathncmp(pathname, base, baselen))
1330 return 0;
1332 namelen = baselen ? pathlen - baselen - 1 : pathlen;
1333 name = pathname + pathlen - namelen;
1335 if (prefix) {
1337 * if the non-wildcard part is longer than the
1338 * remaining pathname, surely it cannot match.
1340 if (prefix > namelen)
1341 return 0;
1343 if (fspathncmp(pattern, name, prefix))
1344 return 0;
1345 pattern += prefix;
1346 patternlen -= prefix;
1347 name += prefix;
1348 namelen -= prefix;
1351 * If the whole pattern did not have a wildcard,
1352 * then our prefix match is all we need; we
1353 * do not need to call fnmatch at all.
1355 if (!patternlen && !namelen)
1356 return 1;
1359 return fnmatch_icase_mem(pattern, patternlen,
1360 name, namelen,
1361 WM_PATHNAME) == 0;
1365 * Scan the given exclude list in reverse to see whether pathname
1366 * should be ignored. The first match (i.e. the last on the list), if
1367 * any, determines the fate. Returns the exclude_list element which
1368 * matched, or NULL for undecided.
1370 static struct path_pattern *last_matching_pattern_from_list(const char *pathname,
1371 int pathlen,
1372 const char *basename,
1373 int *dtype,
1374 struct pattern_list *pl,
1375 struct index_state *istate)
1377 struct path_pattern *res = NULL; /* undecided */
1378 int i;
1380 if (!pl->nr)
1381 return NULL; /* undefined */
1383 for (i = pl->nr - 1; 0 <= i; i--) {
1384 struct path_pattern *pattern = pl->patterns[i];
1385 const char *exclude = pattern->pattern;
1386 int prefix = pattern->nowildcardlen;
1388 if (pattern->flags & PATTERN_FLAG_MUSTBEDIR) {
1389 *dtype = resolve_dtype(*dtype, istate, pathname, pathlen);
1390 if (*dtype != DT_DIR)
1391 continue;
1394 if (pattern->flags & PATTERN_FLAG_NODIR) {
1395 if (match_basename(basename,
1396 pathlen - (basename - pathname),
1397 exclude, prefix, pattern->patternlen,
1398 pattern->flags)) {
1399 res = pattern;
1400 break;
1402 continue;
1405 assert(pattern->baselen == 0 ||
1406 pattern->base[pattern->baselen - 1] == '/');
1407 if (match_pathname(pathname, pathlen,
1408 pattern->base,
1409 pattern->baselen ? pattern->baselen - 1 : 0,
1410 exclude, prefix, pattern->patternlen)) {
1411 res = pattern;
1412 break;
1415 return res;
1419 * Scan the list of patterns to determine if the ordered list
1420 * of patterns matches on 'pathname'.
1422 * Return 1 for a match, 0 for not matched and -1 for undecided.
1424 enum pattern_match_result path_matches_pattern_list(
1425 const char *pathname, int pathlen,
1426 const char *basename, int *dtype,
1427 struct pattern_list *pl,
1428 struct index_state *istate)
1430 struct path_pattern *pattern;
1431 struct strbuf parent_pathname = STRBUF_INIT;
1432 int result = NOT_MATCHED;
1433 size_t slash_pos;
1435 if (!pl->use_cone_patterns) {
1436 pattern = last_matching_pattern_from_list(pathname, pathlen, basename,
1437 dtype, pl, istate);
1438 if (pattern) {
1439 if (pattern->flags & PATTERN_FLAG_NEGATIVE)
1440 return NOT_MATCHED;
1441 else
1442 return MATCHED;
1445 return UNDECIDED;
1448 if (pl->full_cone)
1449 return MATCHED;
1451 strbuf_addch(&parent_pathname, '/');
1452 strbuf_add(&parent_pathname, pathname, pathlen);
1455 * Directory entries are matched if and only if a file
1456 * contained immediately within them is matched. For the
1457 * case of a directory entry, modify the path to create
1458 * a fake filename within this directory, allowing us to
1459 * use the file-base matching logic in an equivalent way.
1461 if (parent_pathname.len > 0 &&
1462 parent_pathname.buf[parent_pathname.len - 1] == '/') {
1463 slash_pos = parent_pathname.len - 1;
1464 strbuf_add(&parent_pathname, "-", 1);
1465 } else {
1466 const char *slash_ptr = strrchr(parent_pathname.buf, '/');
1467 slash_pos = slash_ptr ? slash_ptr - parent_pathname.buf : 0;
1470 if (hashmap_contains_path(&pl->recursive_hashmap,
1471 &parent_pathname)) {
1472 result = MATCHED_RECURSIVE;
1473 goto done;
1476 if (!slash_pos) {
1477 /* include every file in root */
1478 result = MATCHED;
1479 goto done;
1482 strbuf_setlen(&parent_pathname, slash_pos);
1484 if (hashmap_contains_path(&pl->parent_hashmap, &parent_pathname)) {
1485 result = MATCHED;
1486 goto done;
1489 if (hashmap_contains_parent(&pl->recursive_hashmap,
1490 pathname,
1491 &parent_pathname))
1492 result = MATCHED_RECURSIVE;
1494 done:
1495 strbuf_release(&parent_pathname);
1496 return result;
1499 int init_sparse_checkout_patterns(struct index_state *istate)
1501 if (!core_apply_sparse_checkout)
1502 return 1;
1503 if (istate->sparse_checkout_patterns)
1504 return 0;
1506 CALLOC_ARRAY(istate->sparse_checkout_patterns, 1);
1508 if (get_sparse_checkout_patterns(istate->sparse_checkout_patterns) < 0) {
1509 FREE_AND_NULL(istate->sparse_checkout_patterns);
1510 return -1;
1513 return 0;
1516 static int path_in_sparse_checkout_1(const char *path,
1517 struct index_state *istate,
1518 int require_cone_mode)
1520 int dtype = DT_REG;
1521 enum pattern_match_result match = UNDECIDED;
1522 const char *end, *slash;
1525 * We default to accepting a path if the path is empty, there are no
1526 * patterns, or the patterns are of the wrong type.
1528 if (!*path ||
1529 init_sparse_checkout_patterns(istate) ||
1530 (require_cone_mode &&
1531 !istate->sparse_checkout_patterns->use_cone_patterns))
1532 return 1;
1535 * If UNDECIDED, use the match from the parent dir (recursively), or
1536 * fall back to NOT_MATCHED at the topmost level. Note that cone mode
1537 * never returns UNDECIDED, so we will execute only one iteration in
1538 * this case.
1540 for (end = path + strlen(path);
1541 end > path && match == UNDECIDED;
1542 end = slash) {
1544 for (slash = end - 1; slash > path && *slash != '/'; slash--)
1545 ; /* do nothing */
1547 match = path_matches_pattern_list(path, end - path,
1548 slash > path ? slash + 1 : path, &dtype,
1549 istate->sparse_checkout_patterns, istate);
1551 /* We are going to match the parent dir now */
1552 dtype = DT_DIR;
1554 return match > 0;
1557 int path_in_sparse_checkout(const char *path,
1558 struct index_state *istate)
1560 return path_in_sparse_checkout_1(path, istate, 0);
1563 int path_in_cone_mode_sparse_checkout(const char *path,
1564 struct index_state *istate)
1566 return path_in_sparse_checkout_1(path, istate, 1);
1569 static struct path_pattern *last_matching_pattern_from_lists(
1570 struct dir_struct *dir, struct index_state *istate,
1571 const char *pathname, int pathlen,
1572 const char *basename, int *dtype_p)
1574 int i, j;
1575 struct exclude_list_group *group;
1576 struct path_pattern *pattern;
1577 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
1578 group = &dir->internal.exclude_list_group[i];
1579 for (j = group->nr - 1; j >= 0; j--) {
1580 pattern = last_matching_pattern_from_list(
1581 pathname, pathlen, basename, dtype_p,
1582 &group->pl[j], istate);
1583 if (pattern)
1584 return pattern;
1587 return NULL;
1591 * Loads the per-directory exclude list for the substring of base
1592 * which has a char length of baselen.
1594 static void prep_exclude(struct dir_struct *dir,
1595 struct index_state *istate,
1596 const char *base, int baselen)
1598 struct exclude_list_group *group;
1599 struct pattern_list *pl;
1600 struct exclude_stack *stk = NULL;
1601 struct untracked_cache_dir *untracked;
1602 int current;
1604 group = &dir->internal.exclude_list_group[EXC_DIRS];
1607 * Pop the exclude lists from the EXCL_DIRS exclude_list_group
1608 * which originate from directories not in the prefix of the
1609 * path being checked.
1611 while ((stk = dir->internal.exclude_stack) != NULL) {
1612 if (stk->baselen <= baselen &&
1613 !strncmp(dir->internal.basebuf.buf, base, stk->baselen))
1614 break;
1615 pl = &group->pl[dir->internal.exclude_stack->exclude_ix];
1616 dir->internal.exclude_stack = stk->prev;
1617 dir->internal.pattern = NULL;
1618 free((char *)pl->src); /* see strbuf_detach() below */
1619 clear_pattern_list(pl);
1620 free(stk);
1621 group->nr--;
1624 /* Skip traversing into sub directories if the parent is excluded */
1625 if (dir->internal.pattern)
1626 return;
1629 * Lazy initialization. All call sites currently just
1630 * memset(dir, 0, sizeof(*dir)) before use. Changing all of
1631 * them seems lots of work for little benefit.
1633 if (!dir->internal.basebuf.buf)
1634 strbuf_init(&dir->internal.basebuf, PATH_MAX);
1636 /* Read from the parent directories and push them down. */
1637 current = stk ? stk->baselen : -1;
1638 strbuf_setlen(&dir->internal.basebuf, current < 0 ? 0 : current);
1639 if (dir->untracked)
1640 untracked = stk ? stk->ucd : dir->untracked->root;
1641 else
1642 untracked = NULL;
1644 while (current < baselen) {
1645 const char *cp;
1646 struct oid_stat oid_stat;
1648 CALLOC_ARRAY(stk, 1);
1649 if (current < 0) {
1650 cp = base;
1651 current = 0;
1652 } else {
1653 cp = strchr(base + current + 1, '/');
1654 if (!cp)
1655 die("oops in prep_exclude");
1656 cp++;
1657 untracked =
1658 lookup_untracked(dir->untracked,
1659 untracked,
1660 base + current,
1661 cp - base - current);
1663 stk->prev = dir->internal.exclude_stack;
1664 stk->baselen = cp - base;
1665 stk->exclude_ix = group->nr;
1666 stk->ucd = untracked;
1667 pl = add_pattern_list(dir, EXC_DIRS, NULL);
1668 strbuf_add(&dir->internal.basebuf, base + current, stk->baselen - current);
1669 assert(stk->baselen == dir->internal.basebuf.len);
1671 /* Abort if the directory is excluded */
1672 if (stk->baselen) {
1673 int dt = DT_DIR;
1674 dir->internal.basebuf.buf[stk->baselen - 1] = 0;
1675 dir->internal.pattern = last_matching_pattern_from_lists(dir,
1676 istate,
1677 dir->internal.basebuf.buf, stk->baselen - 1,
1678 dir->internal.basebuf.buf + current, &dt);
1679 dir->internal.basebuf.buf[stk->baselen - 1] = '/';
1680 if (dir->internal.pattern &&
1681 dir->internal.pattern->flags & PATTERN_FLAG_NEGATIVE)
1682 dir->internal.pattern = NULL;
1683 if (dir->internal.pattern) {
1684 dir->internal.exclude_stack = stk;
1685 return;
1689 /* Try to read per-directory file */
1690 oidclr(&oid_stat.oid);
1691 oid_stat.valid = 0;
1692 if (dir->exclude_per_dir &&
1694 * If we know that no files have been added in
1695 * this directory (i.e. valid_cached_dir() has
1696 * been executed and set untracked->valid) ..
1698 (!untracked || !untracked->valid ||
1700 * .. and .gitignore does not exist before
1701 * (i.e. null exclude_oid). Then we can skip
1702 * loading .gitignore, which would result in
1703 * ENOENT anyway.
1705 !is_null_oid(&untracked->exclude_oid))) {
1707 * dir->internal.basebuf gets reused by the traversal,
1708 * but we need fname to remain unchanged to ensure the
1709 * src member of each struct path_pattern correctly
1710 * back-references its source file. Other invocations
1711 * of add_pattern_list provide stable strings, so we
1712 * strbuf_detach() and free() here in the caller.
1714 struct strbuf sb = STRBUF_INIT;
1715 strbuf_addbuf(&sb, &dir->internal.basebuf);
1716 strbuf_addstr(&sb, dir->exclude_per_dir);
1717 pl->src = strbuf_detach(&sb, NULL);
1718 add_patterns(pl->src, pl->src, stk->baselen, pl, istate,
1719 PATTERN_NOFOLLOW,
1720 untracked ? &oid_stat : NULL);
1723 * NEEDSWORK: when untracked cache is enabled, prep_exclude()
1724 * will first be called in valid_cached_dir() then maybe many
1725 * times more in last_matching_pattern(). When the cache is
1726 * used, last_matching_pattern() will not be called and
1727 * reading .gitignore content will be a waste.
1729 * So when it's called by valid_cached_dir() and we can get
1730 * .gitignore SHA-1 from the index (i.e. .gitignore is not
1731 * modified on work tree), we could delay reading the
1732 * .gitignore content until we absolutely need it in
1733 * last_matching_pattern(). Be careful about ignore rule
1734 * order, though, if you do that.
1736 if (untracked &&
1737 !oideq(&oid_stat.oid, &untracked->exclude_oid)) {
1738 invalidate_gitignore(dir->untracked, untracked);
1739 oidcpy(&untracked->exclude_oid, &oid_stat.oid);
1741 dir->internal.exclude_stack = stk;
1742 current = stk->baselen;
1744 strbuf_setlen(&dir->internal.basebuf, baselen);
1748 * Loads the exclude lists for the directory containing pathname, then
1749 * scans all exclude lists to determine whether pathname is excluded.
1750 * Returns the exclude_list element which matched, or NULL for
1751 * undecided.
1753 struct path_pattern *last_matching_pattern(struct dir_struct *dir,
1754 struct index_state *istate,
1755 const char *pathname,
1756 int *dtype_p)
1758 int pathlen = strlen(pathname);
1759 const char *basename = strrchr(pathname, '/');
1760 basename = (basename) ? basename+1 : pathname;
1762 prep_exclude(dir, istate, pathname, basename-pathname);
1764 if (dir->internal.pattern)
1765 return dir->internal.pattern;
1767 return last_matching_pattern_from_lists(dir, istate, pathname, pathlen,
1768 basename, dtype_p);
1772 * Loads the exclude lists for the directory containing pathname, then
1773 * scans all exclude lists to determine whether pathname is excluded.
1774 * Returns 1 if true, otherwise 0.
1776 int is_excluded(struct dir_struct *dir, struct index_state *istate,
1777 const char *pathname, int *dtype_p)
1779 struct path_pattern *pattern =
1780 last_matching_pattern(dir, istate, pathname, dtype_p);
1781 if (pattern)
1782 return pattern->flags & PATTERN_FLAG_NEGATIVE ? 0 : 1;
1783 return 0;
1786 static struct dir_entry *dir_entry_new(const char *pathname, int len)
1788 struct dir_entry *ent;
1790 FLEX_ALLOC_MEM(ent, name, pathname, len);
1791 ent->len = len;
1792 return ent;
1795 static struct dir_entry *dir_add_name(struct dir_struct *dir,
1796 struct index_state *istate,
1797 const char *pathname, int len)
1799 if (index_file_exists(istate, pathname, len, ignore_case))
1800 return NULL;
1802 ALLOC_GROW(dir->entries, dir->nr+1, dir->internal.alloc);
1803 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
1806 struct dir_entry *dir_add_ignored(struct dir_struct *dir,
1807 struct index_state *istate,
1808 const char *pathname, int len)
1810 if (!index_name_is_other(istate, pathname, len))
1811 return NULL;
1813 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->internal.ignored_alloc);
1814 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
1817 enum exist_status {
1818 index_nonexistent = 0,
1819 index_directory,
1820 index_gitdir
1824 * Do not use the alphabetically sorted index to look up
1825 * the directory name; instead, use the case insensitive
1826 * directory hash.
1828 static enum exist_status directory_exists_in_index_icase(struct index_state *istate,
1829 const char *dirname, int len)
1831 struct cache_entry *ce;
1833 if (index_dir_exists(istate, dirname, len))
1834 return index_directory;
1836 ce = index_file_exists(istate, dirname, len, ignore_case);
1837 if (ce && S_ISGITLINK(ce->ce_mode))
1838 return index_gitdir;
1840 return index_nonexistent;
1844 * The index sorts alphabetically by entry name, which
1845 * means that a gitlink sorts as '\0' at the end, while
1846 * a directory (which is defined not as an entry, but as
1847 * the files it contains) will sort with the '/' at the
1848 * end.
1850 static enum exist_status directory_exists_in_index(struct index_state *istate,
1851 const char *dirname, int len)
1853 int pos;
1855 if (ignore_case)
1856 return directory_exists_in_index_icase(istate, dirname, len);
1858 pos = index_name_pos(istate, dirname, len);
1859 if (pos < 0)
1860 pos = -pos-1;
1861 while (pos < istate->cache_nr) {
1862 const struct cache_entry *ce = istate->cache[pos++];
1863 unsigned char endchar;
1865 if (strncmp(ce->name, dirname, len))
1866 break;
1867 endchar = ce->name[len];
1868 if (endchar > '/')
1869 break;
1870 if (endchar == '/')
1871 return index_directory;
1872 if (!endchar && S_ISGITLINK(ce->ce_mode))
1873 return index_gitdir;
1875 return index_nonexistent;
1879 * When we find a directory when traversing the filesystem, we
1880 * have three distinct cases:
1882 * - ignore it
1883 * - see it as a directory
1884 * - recurse into it
1886 * and which one we choose depends on a combination of existing
1887 * git index contents and the flags passed into the directory
1888 * traversal routine.
1890 * Case 1: If we *already* have entries in the index under that
1891 * directory name, we always recurse into the directory to see
1892 * all the files.
1894 * Case 2: If we *already* have that directory name as a gitlink,
1895 * we always continue to see it as a gitlink, regardless of whether
1896 * there is an actual git directory there or not (it might not
1897 * be checked out as a subproject!)
1899 * Case 3: if we didn't have it in the index previously, we
1900 * have a few sub-cases:
1902 * (a) if DIR_SHOW_OTHER_DIRECTORIES flag is set, we show it as
1903 * just a directory, unless DIR_HIDE_EMPTY_DIRECTORIES is
1904 * also true, in which case we need to check if it contains any
1905 * untracked and / or ignored files.
1906 * (b) if it looks like a git directory and we don't have the
1907 * DIR_NO_GITLINKS flag, then we treat it as a gitlink, and
1908 * show it as a directory.
1909 * (c) otherwise, we recurse into it.
1911 static enum path_treatment treat_directory(struct dir_struct *dir,
1912 struct index_state *istate,
1913 struct untracked_cache_dir *untracked,
1914 const char *dirname, int len, int baselen, int excluded,
1915 const struct pathspec *pathspec)
1918 * WARNING: From this function, you can return path_recurse or you
1919 * can call read_directory_recursive() (or neither), but
1920 * you CAN'T DO BOTH.
1922 enum path_treatment state;
1923 int matches_how = 0;
1924 int check_only, stop_early;
1925 int old_ignored_nr, old_untracked_nr;
1926 /* The "len-1" is to strip the final '/' */
1927 enum exist_status status = directory_exists_in_index(istate, dirname, len-1);
1929 if (status == index_directory)
1930 return path_recurse;
1931 if (status == index_gitdir)
1932 return path_none;
1933 if (status != index_nonexistent)
1934 BUG("Unhandled value for directory_exists_in_index: %d\n", status);
1937 * We don't want to descend into paths that don't match the necessary
1938 * patterns. Clearly, if we don't have a pathspec, then we can't check
1939 * for matching patterns. Also, if (excluded) then we know we matched
1940 * the exclusion patterns so as an optimization we can skip checking
1941 * for matching patterns.
1943 if (pathspec && !excluded) {
1944 matches_how = match_pathspec_with_flags(istate, pathspec,
1945 dirname, len,
1946 0 /* prefix */,
1947 NULL /* seen */,
1948 DO_MATCH_LEADING_PATHSPEC);
1949 if (!matches_how)
1950 return path_none;
1954 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
1955 !(dir->flags & DIR_NO_GITLINKS)) {
1957 * Determine if `dirname` is a nested repo by confirming that:
1958 * 1) we are in a nonbare repository, and
1959 * 2) `dirname` is not an immediate parent of `the_repository->gitdir`,
1960 * which could occur if the git_dir or worktree location was
1961 * manually configured by the user; see t2205 testcases 1-3 for
1962 * examples where this matters
1964 int nested_repo;
1965 struct strbuf sb = STRBUF_INIT;
1966 strbuf_addstr(&sb, dirname);
1967 nested_repo = is_nonbare_repository_dir(&sb);
1969 if (nested_repo) {
1970 char *real_dirname, *real_gitdir;
1971 strbuf_addstr(&sb, ".git");
1972 real_dirname = real_pathdup(sb.buf, 1);
1973 real_gitdir = real_pathdup(the_repository->gitdir, 1);
1975 nested_repo = !!strcmp(real_dirname, real_gitdir);
1976 free(real_gitdir);
1977 free(real_dirname);
1979 strbuf_release(&sb);
1981 if (nested_repo) {
1982 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
1983 (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC))
1984 return path_none;
1985 return excluded ? path_excluded : path_untracked;
1989 if (!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)) {
1990 if (excluded &&
1991 (dir->flags & DIR_SHOW_IGNORED_TOO) &&
1992 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING)) {
1995 * This is an excluded directory and we are
1996 * showing ignored paths that match an exclude
1997 * pattern. (e.g. show directory as ignored
1998 * only if it matches an exclude pattern).
1999 * This path will either be 'path_excluded`
2000 * (if we are showing empty directories or if
2001 * the directory is not empty), or will be
2002 * 'path_none' (empty directory, and we are
2003 * not showing empty directories).
2005 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
2006 return path_excluded;
2008 if (read_directory_recursive(dir, istate, dirname, len,
2009 untracked, 1, 1, pathspec) == path_excluded)
2010 return path_excluded;
2012 return path_none;
2014 return path_recurse;
2017 assert(dir->flags & DIR_SHOW_OTHER_DIRECTORIES);
2020 * If we have a pathspec which could match something _below_ this
2021 * directory (e.g. when checking 'subdir/' having a pathspec like
2022 * 'subdir/some/deep/path/file' or 'subdir/widget-*.c'), then we
2023 * need to recurse.
2025 if (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC)
2026 return path_recurse;
2028 /* Special cases for where this directory is excluded/ignored */
2029 if (excluded) {
2031 * If DIR_SHOW_OTHER_DIRECTORIES is set and we're not
2032 * hiding empty directories, there is no need to
2033 * recurse into an ignored directory.
2035 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
2036 return path_excluded;
2039 * Even if we are hiding empty directories, we can still avoid
2040 * recursing into ignored directories for DIR_SHOW_IGNORED_TOO
2041 * if DIR_SHOW_IGNORED_TOO_MODE_MATCHING is also set.
2043 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
2044 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING))
2045 return path_excluded;
2049 * Other than the path_recurse case above, we only need to
2050 * recurse into untracked directories if any of the following
2051 * bits is set:
2052 * - DIR_SHOW_IGNORED (because then we need to determine if
2053 * there are ignored entries below)
2054 * - DIR_SHOW_IGNORED_TOO (same as above)
2055 * - DIR_HIDE_EMPTY_DIRECTORIES (because we have to determine if
2056 * the directory is empty)
2058 if (!excluded &&
2059 !(dir->flags & (DIR_SHOW_IGNORED |
2060 DIR_SHOW_IGNORED_TOO |
2061 DIR_HIDE_EMPTY_DIRECTORIES))) {
2062 return path_untracked;
2066 * Even if we don't want to know all the paths under an untracked or
2067 * ignored directory, we may still need to go into the directory to
2068 * determine if it is empty (because with DIR_HIDE_EMPTY_DIRECTORIES,
2069 * an empty directory should be path_none instead of path_excluded or
2070 * path_untracked).
2072 check_only = ((dir->flags & DIR_HIDE_EMPTY_DIRECTORIES) &&
2073 !(dir->flags & DIR_SHOW_IGNORED_TOO));
2076 * However, there's another optimization possible as a subset of
2077 * check_only, based on the cases we have to consider:
2078 * A) Directory matches no exclude patterns:
2079 * * Directory is empty => path_none
2080 * * Directory has an untracked file under it => path_untracked
2081 * * Directory has only ignored files under it => path_excluded
2082 * B) Directory matches an exclude pattern:
2083 * * Directory is empty => path_none
2084 * * Directory has an untracked file under it => path_excluded
2085 * * Directory has only ignored files under it => path_excluded
2086 * In case A, we can exit as soon as we've found an untracked
2087 * file but otherwise have to walk all files. In case B, though,
2088 * we can stop at the first file we find under the directory.
2090 stop_early = check_only && excluded;
2093 * If /every/ file within an untracked directory is ignored, then
2094 * we want to treat the directory as ignored (for e.g. status
2095 * --porcelain), without listing the individual ignored files
2096 * underneath. To do so, we'll save the current ignored_nr, and
2097 * pop all the ones added after it if it turns out the entire
2098 * directory is ignored. Also, when DIR_SHOW_IGNORED_TOO and
2099 * !DIR_KEEP_UNTRACKED_CONTENTS then we don't want to show
2100 * untracked paths so will need to pop all those off the last
2101 * after we traverse.
2103 old_ignored_nr = dir->ignored_nr;
2104 old_untracked_nr = dir->nr;
2106 /* Actually recurse into dirname now, we'll fixup the state later. */
2107 untracked = lookup_untracked(dir->untracked, untracked,
2108 dirname + baselen, len - baselen);
2109 state = read_directory_recursive(dir, istate, dirname, len, untracked,
2110 check_only, stop_early, pathspec);
2112 /* There are a variety of reasons we may need to fixup the state... */
2113 if (state == path_excluded) {
2114 /* state == path_excluded implies all paths under
2115 * dirname were ignored...
2117 * if running e.g. `git status --porcelain --ignored=matching`,
2118 * then we want to see the subpaths that are ignored.
2120 * if running e.g. just `git status --porcelain`, then
2121 * we just want the directory itself to be listed as ignored
2122 * and not the individual paths underneath.
2124 int want_ignored_subpaths =
2125 ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
2126 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING));
2128 if (want_ignored_subpaths) {
2130 * with --ignored=matching, we want the subpaths
2131 * INSTEAD of the directory itself.
2133 state = path_none;
2134 } else {
2135 int i;
2136 for (i = old_ignored_nr + 1; i<dir->ignored_nr; ++i)
2137 FREE_AND_NULL(dir->ignored[i]);
2138 dir->ignored_nr = old_ignored_nr;
2143 * We may need to ignore some of the untracked paths we found while
2144 * traversing subdirectories.
2146 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
2147 !(dir->flags & DIR_KEEP_UNTRACKED_CONTENTS)) {
2148 int i;
2149 for (i = old_untracked_nr + 1; i<dir->nr; ++i)
2150 FREE_AND_NULL(dir->entries[i]);
2151 dir->nr = old_untracked_nr;
2155 * If there is nothing under the current directory and we are not
2156 * hiding empty directories, then we need to report on the
2157 * untracked or ignored status of the directory itself.
2159 if (state == path_none && !(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
2160 state = excluded ? path_excluded : path_untracked;
2162 return state;
2166 * This is an inexact early pruning of any recursive directory
2167 * reading - if the path cannot possibly be in the pathspec,
2168 * return true, and we'll skip it early.
2170 static int simplify_away(const char *path, int pathlen,
2171 const struct pathspec *pathspec)
2173 int i;
2175 if (!pathspec || !pathspec->nr)
2176 return 0;
2178 GUARD_PATHSPEC(pathspec,
2179 PATHSPEC_FROMTOP |
2180 PATHSPEC_MAXDEPTH |
2181 PATHSPEC_LITERAL |
2182 PATHSPEC_GLOB |
2183 PATHSPEC_ICASE |
2184 PATHSPEC_EXCLUDE |
2185 PATHSPEC_ATTR);
2187 for (i = 0; i < pathspec->nr; i++) {
2188 const struct pathspec_item *item = &pathspec->items[i];
2189 int len = item->nowildcard_len;
2191 if (len > pathlen)
2192 len = pathlen;
2193 if (!ps_strncmp(item, item->match, path, len))
2194 return 0;
2197 return 1;
2201 * This function tells us whether an excluded path matches a
2202 * list of "interesting" pathspecs. That is, whether a path matched
2203 * by any of the pathspecs could possibly be ignored by excluding
2204 * the specified path. This can happen if:
2206 * 1. the path is mentioned explicitly in the pathspec
2208 * 2. the path is a directory prefix of some element in the
2209 * pathspec
2211 static int exclude_matches_pathspec(const char *path, int pathlen,
2212 const struct pathspec *pathspec)
2214 int i;
2216 if (!pathspec || !pathspec->nr)
2217 return 0;
2219 GUARD_PATHSPEC(pathspec,
2220 PATHSPEC_FROMTOP |
2221 PATHSPEC_MAXDEPTH |
2222 PATHSPEC_LITERAL |
2223 PATHSPEC_GLOB |
2224 PATHSPEC_ICASE |
2225 PATHSPEC_EXCLUDE |
2226 PATHSPEC_ATTR);
2228 for (i = 0; i < pathspec->nr; i++) {
2229 const struct pathspec_item *item = &pathspec->items[i];
2230 int len = item->nowildcard_len;
2232 if (len == pathlen &&
2233 !ps_strncmp(item, item->match, path, pathlen))
2234 return 1;
2235 if (len > pathlen &&
2236 item->match[pathlen] == '/' &&
2237 !ps_strncmp(item, item->match, path, pathlen))
2238 return 1;
2240 return 0;
2243 static int get_index_dtype(struct index_state *istate,
2244 const char *path, int len)
2246 int pos;
2247 const struct cache_entry *ce;
2249 ce = index_file_exists(istate, path, len, 0);
2250 if (ce) {
2251 if (!ce_uptodate(ce))
2252 return DT_UNKNOWN;
2253 if (S_ISGITLINK(ce->ce_mode))
2254 return DT_DIR;
2256 * Nobody actually cares about the
2257 * difference between DT_LNK and DT_REG
2259 return DT_REG;
2262 /* Try to look it up as a directory */
2263 pos = index_name_pos(istate, path, len);
2264 if (pos >= 0)
2265 return DT_UNKNOWN;
2266 pos = -pos-1;
2267 while (pos < istate->cache_nr) {
2268 ce = istate->cache[pos++];
2269 if (strncmp(ce->name, path, len))
2270 break;
2271 if (ce->name[len] > '/')
2272 break;
2273 if (ce->name[len] < '/')
2274 continue;
2275 if (!ce_uptodate(ce))
2276 break; /* continue? */
2277 return DT_DIR;
2279 return DT_UNKNOWN;
2282 unsigned char get_dtype(struct dirent *e, struct strbuf *path,
2283 int follow_symlink)
2285 struct stat st;
2286 unsigned char dtype = DTYPE(e);
2287 size_t base_path_len;
2289 if (dtype != DT_UNKNOWN && !(follow_symlink && dtype == DT_LNK))
2290 return dtype;
2293 * d_type unknown or unfollowed symlink, try to fall back on [l]stat
2294 * results. If [l]stat fails, explicitly set DT_UNKNOWN.
2296 base_path_len = path->len;
2297 strbuf_addstr(path, e->d_name);
2298 if ((follow_symlink && stat(path->buf, &st)) ||
2299 (!follow_symlink && lstat(path->buf, &st)))
2300 goto cleanup;
2302 /* determine d_type from st_mode */
2303 if (S_ISREG(st.st_mode))
2304 dtype = DT_REG;
2305 else if (S_ISDIR(st.st_mode))
2306 dtype = DT_DIR;
2307 else if (S_ISLNK(st.st_mode))
2308 dtype = DT_LNK;
2310 cleanup:
2311 strbuf_setlen(path, base_path_len);
2312 return dtype;
2315 static int resolve_dtype(int dtype, struct index_state *istate,
2316 const char *path, int len)
2318 struct stat st;
2320 if (dtype != DT_UNKNOWN)
2321 return dtype;
2322 dtype = get_index_dtype(istate, path, len);
2323 if (dtype != DT_UNKNOWN)
2324 return dtype;
2325 if (lstat(path, &st))
2326 return dtype;
2327 if (S_ISREG(st.st_mode))
2328 return DT_REG;
2329 if (S_ISDIR(st.st_mode))
2330 return DT_DIR;
2331 if (S_ISLNK(st.st_mode))
2332 return DT_LNK;
2333 return dtype;
2336 static enum path_treatment treat_path_fast(struct dir_struct *dir,
2337 struct cached_dir *cdir,
2338 struct index_state *istate,
2339 struct strbuf *path,
2340 int baselen,
2341 const struct pathspec *pathspec)
2344 * WARNING: From this function, you can return path_recurse or you
2345 * can call read_directory_recursive() (or neither), but
2346 * you CAN'T DO BOTH.
2348 strbuf_setlen(path, baselen);
2349 if (!cdir->ucd) {
2350 strbuf_addstr(path, cdir->file);
2351 return path_untracked;
2353 strbuf_addstr(path, cdir->ucd->name);
2354 /* treat_one_path() does this before it calls treat_directory() */
2355 strbuf_complete(path, '/');
2356 if (cdir->ucd->check_only)
2358 * check_only is set as a result of treat_directory() getting
2359 * to its bottom. Verify again the same set of directories
2360 * with check_only set.
2362 return read_directory_recursive(dir, istate, path->buf, path->len,
2363 cdir->ucd, 1, 0, pathspec);
2365 * We get path_recurse in the first run when
2366 * directory_exists_in_index() returns index_nonexistent. We
2367 * are sure that new changes in the index does not impact the
2368 * outcome. Return now.
2370 return path_recurse;
2373 static enum path_treatment treat_path(struct dir_struct *dir,
2374 struct untracked_cache_dir *untracked,
2375 struct cached_dir *cdir,
2376 struct index_state *istate,
2377 struct strbuf *path,
2378 int baselen,
2379 const struct pathspec *pathspec)
2381 int has_path_in_index, dtype, excluded;
2383 if (!cdir->d_name)
2384 return treat_path_fast(dir, cdir, istate, path,
2385 baselen, pathspec);
2386 if (is_dot_or_dotdot(cdir->d_name) || !fspathcmp(cdir->d_name, ".git"))
2387 return path_none;
2388 strbuf_setlen(path, baselen);
2389 strbuf_addstr(path, cdir->d_name);
2390 if (simplify_away(path->buf, path->len, pathspec))
2391 return path_none;
2393 dtype = resolve_dtype(cdir->d_type, istate, path->buf, path->len);
2395 /* Always exclude indexed files */
2396 has_path_in_index = !!index_file_exists(istate, path->buf, path->len,
2397 ignore_case);
2398 if (dtype != DT_DIR && has_path_in_index)
2399 return path_none;
2402 * When we are looking at a directory P in the working tree,
2403 * there are three cases:
2405 * (1) P exists in the index. Everything inside the directory P in
2406 * the working tree needs to go when P is checked out from the
2407 * index.
2409 * (2) P does not exist in the index, but there is P/Q in the index.
2410 * We know P will stay a directory when we check out the contents
2411 * of the index, but we do not know yet if there is a directory
2412 * P/Q in the working tree to be killed, so we need to recurse.
2414 * (3) P does not exist in the index, and there is no P/Q in the index
2415 * to require P to be a directory, either. Only in this case, we
2416 * know that everything inside P will not be killed without
2417 * recursing.
2419 if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
2420 (dtype == DT_DIR) &&
2421 !has_path_in_index &&
2422 (directory_exists_in_index(istate, path->buf, path->len) == index_nonexistent))
2423 return path_none;
2425 excluded = is_excluded(dir, istate, path->buf, &dtype);
2428 * Excluded? If we don't explicitly want to show
2429 * ignored files, ignore it
2431 if (excluded && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
2432 return path_excluded;
2434 switch (dtype) {
2435 default:
2436 return path_none;
2437 case DT_DIR:
2439 * WARNING: Do not ignore/amend the return value from
2440 * treat_directory(), and especially do not change it to return
2441 * path_recurse as that can cause exponential slowdown.
2442 * Instead, modify treat_directory() to return the right value.
2444 strbuf_addch(path, '/');
2445 return treat_directory(dir, istate, untracked,
2446 path->buf, path->len,
2447 baselen, excluded, pathspec);
2448 case DT_REG:
2449 case DT_LNK:
2450 if (pathspec &&
2451 !match_pathspec(istate, pathspec, path->buf, path->len,
2452 0 /* prefix */, NULL /* seen */,
2453 0 /* is_dir */))
2454 return path_none;
2455 if (excluded)
2456 return path_excluded;
2457 return path_untracked;
2461 static void add_untracked(struct untracked_cache_dir *dir, const char *name)
2463 if (!dir)
2464 return;
2465 ALLOC_GROW(dir->untracked, dir->untracked_nr + 1,
2466 dir->untracked_alloc);
2467 dir->untracked[dir->untracked_nr++] = xstrdup(name);
2470 static int valid_cached_dir(struct dir_struct *dir,
2471 struct untracked_cache_dir *untracked,
2472 struct index_state *istate,
2473 struct strbuf *path,
2474 int check_only)
2476 struct stat st;
2478 if (!untracked)
2479 return 0;
2482 * With fsmonitor, we can trust the untracked cache's valid field.
2484 refresh_fsmonitor(istate);
2485 if (!(dir->untracked->use_fsmonitor && untracked->valid)) {
2486 if (lstat(path->len ? path->buf : ".", &st)) {
2487 memset(&untracked->stat_data, 0, sizeof(untracked->stat_data));
2488 return 0;
2490 if (!untracked->valid ||
2491 match_stat_data_racy(istate, &untracked->stat_data, &st)) {
2492 fill_stat_data(&untracked->stat_data, &st);
2493 return 0;
2497 if (untracked->check_only != !!check_only)
2498 return 0;
2501 * prep_exclude will be called eventually on this directory,
2502 * but it's called much later in last_matching_pattern(). We
2503 * need it now to determine the validity of the cache for this
2504 * path. The next calls will be nearly no-op, the way
2505 * prep_exclude() is designed.
2507 if (path->len && path->buf[path->len - 1] != '/') {
2508 strbuf_addch(path, '/');
2509 prep_exclude(dir, istate, path->buf, path->len);
2510 strbuf_setlen(path, path->len - 1);
2511 } else
2512 prep_exclude(dir, istate, path->buf, path->len);
2514 /* hopefully prep_exclude() haven't invalidated this entry... */
2515 return untracked->valid;
2518 static int open_cached_dir(struct cached_dir *cdir,
2519 struct dir_struct *dir,
2520 struct untracked_cache_dir *untracked,
2521 struct index_state *istate,
2522 struct strbuf *path,
2523 int check_only)
2525 const char *c_path;
2527 memset(cdir, 0, sizeof(*cdir));
2528 cdir->untracked = untracked;
2529 if (valid_cached_dir(dir, untracked, istate, path, check_only))
2530 return 0;
2531 c_path = path->len ? path->buf : ".";
2532 cdir->fdir = opendir(c_path);
2533 if (!cdir->fdir)
2534 warning_errno(_("could not open directory '%s'"), c_path);
2535 if (dir->untracked) {
2536 invalidate_directory(dir->untracked, untracked);
2537 dir->untracked->dir_opened++;
2539 if (!cdir->fdir)
2540 return -1;
2541 return 0;
2544 static int read_cached_dir(struct cached_dir *cdir)
2546 struct dirent *de;
2548 if (cdir->fdir) {
2549 de = readdir_skip_dot_and_dotdot(cdir->fdir);
2550 if (!de) {
2551 cdir->d_name = NULL;
2552 cdir->d_type = DT_UNKNOWN;
2553 return -1;
2555 cdir->d_name = de->d_name;
2556 cdir->d_type = DTYPE(de);
2557 return 0;
2559 while (cdir->nr_dirs < cdir->untracked->dirs_nr) {
2560 struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];
2561 if (!d->recurse) {
2562 cdir->nr_dirs++;
2563 continue;
2565 cdir->ucd = d;
2566 cdir->nr_dirs++;
2567 return 0;
2569 cdir->ucd = NULL;
2570 if (cdir->nr_files < cdir->untracked->untracked_nr) {
2571 struct untracked_cache_dir *d = cdir->untracked;
2572 cdir->file = d->untracked[cdir->nr_files++];
2573 return 0;
2575 return -1;
2578 static void close_cached_dir(struct cached_dir *cdir)
2580 if (cdir->fdir)
2581 closedir(cdir->fdir);
2583 * We have gone through this directory and found no untracked
2584 * entries. Mark it valid.
2586 if (cdir->untracked) {
2587 cdir->untracked->valid = 1;
2588 cdir->untracked->recurse = 1;
2592 static void add_path_to_appropriate_result_list(struct dir_struct *dir,
2593 struct untracked_cache_dir *untracked,
2594 struct cached_dir *cdir,
2595 struct index_state *istate,
2596 struct strbuf *path,
2597 int baselen,
2598 const struct pathspec *pathspec,
2599 enum path_treatment state)
2601 /* add the path to the appropriate result list */
2602 switch (state) {
2603 case path_excluded:
2604 if (dir->flags & DIR_SHOW_IGNORED)
2605 dir_add_name(dir, istate, path->buf, path->len);
2606 else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
2607 ((dir->flags & DIR_COLLECT_IGNORED) &&
2608 exclude_matches_pathspec(path->buf, path->len,
2609 pathspec)))
2610 dir_add_ignored(dir, istate, path->buf, path->len);
2611 break;
2613 case path_untracked:
2614 if (dir->flags & DIR_SHOW_IGNORED)
2615 break;
2616 dir_add_name(dir, istate, path->buf, path->len);
2617 if (cdir->fdir)
2618 add_untracked(untracked, path->buf + baselen);
2619 break;
2621 default:
2622 break;
2627 * Read a directory tree. We currently ignore anything but
2628 * directories, regular files and symlinks. That's because git
2629 * doesn't handle them at all yet. Maybe that will change some
2630 * day.
2632 * Also, we ignore the name ".git" (even if it is not a directory).
2633 * That likely will not change.
2635 * If 'stop_at_first_file' is specified, 'path_excluded' is returned
2636 * to signal that a file was found. This is the least significant value that
2637 * indicates that a file was encountered that does not depend on the order of
2638 * whether an untracked or excluded path was encountered first.
2640 * Returns the most significant path_treatment value encountered in the scan.
2641 * If 'stop_at_first_file' is specified, `path_excluded` is the most
2642 * significant path_treatment value that will be returned.
2645 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
2646 struct index_state *istate, const char *base, int baselen,
2647 struct untracked_cache_dir *untracked, int check_only,
2648 int stop_at_first_file, const struct pathspec *pathspec)
2651 * WARNING: Do NOT recurse unless path_recurse is returned from
2652 * treat_path(). Recursing on any other return value
2653 * can result in exponential slowdown.
2655 struct cached_dir cdir;
2656 enum path_treatment state, subdir_state, dir_state = path_none;
2657 struct strbuf path = STRBUF_INIT;
2659 strbuf_add(&path, base, baselen);
2661 if (open_cached_dir(&cdir, dir, untracked, istate, &path, check_only))
2662 goto out;
2663 dir->internal.visited_directories++;
2665 if (untracked)
2666 untracked->check_only = !!check_only;
2668 while (!read_cached_dir(&cdir)) {
2669 /* check how the file or directory should be treated */
2670 state = treat_path(dir, untracked, &cdir, istate, &path,
2671 baselen, pathspec);
2672 dir->internal.visited_paths++;
2674 if (state > dir_state)
2675 dir_state = state;
2677 /* recurse into subdir if instructed by treat_path */
2678 if (state == path_recurse) {
2679 struct untracked_cache_dir *ud;
2680 ud = lookup_untracked(dir->untracked,
2681 untracked,
2682 path.buf + baselen,
2683 path.len - baselen);
2684 subdir_state =
2685 read_directory_recursive(dir, istate, path.buf,
2686 path.len, ud,
2687 check_only, stop_at_first_file, pathspec);
2688 if (subdir_state > dir_state)
2689 dir_state = subdir_state;
2691 if (pathspec &&
2692 !match_pathspec(istate, pathspec, path.buf, path.len,
2693 0 /* prefix */, NULL,
2694 0 /* do NOT special case dirs */))
2695 state = path_none;
2698 if (check_only) {
2699 if (stop_at_first_file) {
2701 * If stopping at first file, then
2702 * signal that a file was found by
2703 * returning `path_excluded`. This is
2704 * to return a consistent value
2705 * regardless of whether an ignored or
2706 * excluded file happened to be
2707 * encountered 1st.
2709 * In current usage, the
2710 * `stop_at_first_file` is passed when
2711 * an ancestor directory has matched
2712 * an exclude pattern, so any found
2713 * files will be excluded.
2715 if (dir_state >= path_excluded) {
2716 dir_state = path_excluded;
2717 break;
2721 /* abort early if maximum state has been reached */
2722 if (dir_state == path_untracked) {
2723 if (cdir.fdir)
2724 add_untracked(untracked, path.buf + baselen);
2725 break;
2727 /* skip the add_path_to_appropriate_result_list() */
2728 continue;
2731 add_path_to_appropriate_result_list(dir, untracked, &cdir,
2732 istate, &path, baselen,
2733 pathspec, state);
2735 close_cached_dir(&cdir);
2736 out:
2737 strbuf_release(&path);
2739 return dir_state;
2742 int cmp_dir_entry(const void *p1, const void *p2)
2744 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
2745 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
2747 return name_compare(e1->name, e1->len, e2->name, e2->len);
2750 /* check if *out lexically strictly contains *in */
2751 int check_dir_entry_contains(const struct dir_entry *out, const struct dir_entry *in)
2753 return (out->len < in->len) &&
2754 (out->name[out->len - 1] == '/') &&
2755 !memcmp(out->name, in->name, out->len);
2758 static int treat_leading_path(struct dir_struct *dir,
2759 struct index_state *istate,
2760 const char *path, int len,
2761 const struct pathspec *pathspec)
2763 struct strbuf sb = STRBUF_INIT;
2764 struct strbuf subdir = STRBUF_INIT;
2765 int prevlen, baselen;
2766 const char *cp;
2767 struct cached_dir cdir;
2768 enum path_treatment state = path_none;
2771 * For each directory component of path, we are going to check whether
2772 * that path is relevant given the pathspec. For example, if path is
2773 * foo/bar/baz/
2774 * then we will ask treat_path() whether we should go into foo, then
2775 * whether we should go into bar, then whether baz is relevant.
2776 * Checking each is important because e.g. if path is
2777 * .git/info/
2778 * then we need to check .git to know we shouldn't traverse it.
2779 * If the return from treat_path() is:
2780 * * path_none, for any path, we return false.
2781 * * path_recurse, for all path components, we return true
2782 * * <anything else> for some intermediate component, we make sure
2783 * to add that path to the relevant list but return false
2784 * signifying that we shouldn't recurse into it.
2787 while (len && path[len - 1] == '/')
2788 len--;
2789 if (!len)
2790 return 1;
2792 memset(&cdir, 0, sizeof(cdir));
2793 cdir.d_type = DT_DIR;
2794 baselen = 0;
2795 prevlen = 0;
2796 while (1) {
2797 prevlen = baselen + !!baselen;
2798 cp = path + prevlen;
2799 cp = memchr(cp, '/', path + len - cp);
2800 if (!cp)
2801 baselen = len;
2802 else
2803 baselen = cp - path;
2804 strbuf_reset(&sb);
2805 strbuf_add(&sb, path, baselen);
2806 if (!is_directory(sb.buf))
2807 break;
2808 strbuf_reset(&sb);
2809 strbuf_add(&sb, path, prevlen);
2810 strbuf_reset(&subdir);
2811 strbuf_add(&subdir, path+prevlen, baselen-prevlen);
2812 cdir.d_name = subdir.buf;
2813 state = treat_path(dir, NULL, &cdir, istate, &sb, prevlen, pathspec);
2815 if (state != path_recurse)
2816 break; /* do not recurse into it */
2817 if (len <= baselen)
2818 break; /* finished checking */
2820 add_path_to_appropriate_result_list(dir, NULL, &cdir, istate,
2821 &sb, baselen, pathspec,
2822 state);
2824 strbuf_release(&subdir);
2825 strbuf_release(&sb);
2826 return state == path_recurse;
2829 static const char *get_ident_string(void)
2831 static struct strbuf sb = STRBUF_INIT;
2832 struct utsname uts;
2834 if (sb.len)
2835 return sb.buf;
2836 if (uname(&uts) < 0)
2837 die_errno(_("failed to get kernel name and information"));
2838 strbuf_addf(&sb, "Location %s, system %s", get_git_work_tree(),
2839 uts.sysname);
2840 return sb.buf;
2843 static int ident_in_untracked(const struct untracked_cache *uc)
2846 * Previous git versions may have saved many NUL separated
2847 * strings in the "ident" field, but it is insane to manage
2848 * many locations, so just take care of the first one.
2851 return !strcmp(uc->ident.buf, get_ident_string());
2854 static void set_untracked_ident(struct untracked_cache *uc)
2856 strbuf_reset(&uc->ident);
2857 strbuf_addstr(&uc->ident, get_ident_string());
2860 * This strbuf used to contain a list of NUL separated
2861 * strings, so save NUL too for backward compatibility.
2863 strbuf_addch(&uc->ident, 0);
2866 static unsigned new_untracked_cache_flags(struct index_state *istate)
2868 struct repository *repo = istate->repo;
2869 char *val;
2872 * This logic is coordinated with the setting of these flags in
2873 * wt-status.c#wt_status_collect_untracked(), and the evaluation
2874 * of the config setting in commit.c#git_status_config()
2876 if (!repo_config_get_string(repo, "status.showuntrackedfiles", &val) &&
2877 !strcmp(val, "all"))
2878 return 0;
2881 * The default, if "all" is not set, is "normal" - leading us here.
2882 * If the value is "none" then it really doesn't matter.
2884 return DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;
2887 static void new_untracked_cache(struct index_state *istate, int flags)
2889 struct untracked_cache *uc = xcalloc(1, sizeof(*uc));
2890 strbuf_init(&uc->ident, 100);
2891 uc->exclude_per_dir = ".gitignore";
2892 uc->dir_flags = flags >= 0 ? flags : new_untracked_cache_flags(istate);
2893 set_untracked_ident(uc);
2894 istate->untracked = uc;
2895 istate->cache_changed |= UNTRACKED_CHANGED;
2898 void add_untracked_cache(struct index_state *istate)
2900 if (!istate->untracked) {
2901 new_untracked_cache(istate, -1);
2902 } else {
2903 if (!ident_in_untracked(istate->untracked)) {
2904 free_untracked_cache(istate->untracked);
2905 new_untracked_cache(istate, -1);
2910 void remove_untracked_cache(struct index_state *istate)
2912 if (istate->untracked) {
2913 free_untracked_cache(istate->untracked);
2914 istate->untracked = NULL;
2915 istate->cache_changed |= UNTRACKED_CHANGED;
2919 static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,
2920 int base_len,
2921 const struct pathspec *pathspec,
2922 struct index_state *istate)
2924 struct untracked_cache_dir *root;
2925 static int untracked_cache_disabled = -1;
2927 if (!dir->untracked)
2928 return NULL;
2929 if (untracked_cache_disabled < 0)
2930 untracked_cache_disabled = git_env_bool("GIT_DISABLE_UNTRACKED_CACHE", 0);
2931 if (untracked_cache_disabled)
2932 return NULL;
2935 * We only support $GIT_DIR/info/exclude and core.excludesfile
2936 * as the global ignore rule files. Any other additions
2937 * (e.g. from command line) invalidate the cache. This
2938 * condition also catches running setup_standard_excludes()
2939 * before setting dir->untracked!
2941 if (dir->internal.unmanaged_exclude_files)
2942 return NULL;
2945 * Optimize for the main use case only: whole-tree git
2946 * status. More work involved in treat_leading_path() if we
2947 * use cache on just a subset of the worktree. pathspec
2948 * support could make the matter even worse.
2950 if (base_len || (pathspec && pathspec->nr))
2951 return NULL;
2953 /* We don't support collecting ignore files */
2954 if (dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |
2955 DIR_COLLECT_IGNORED))
2956 return NULL;
2959 * If we use .gitignore in the cache and now you change it to
2960 * .gitexclude, everything will go wrong.
2962 if (dir->exclude_per_dir != dir->untracked->exclude_per_dir &&
2963 strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))
2964 return NULL;
2967 * EXC_CMDL is not considered in the cache. If people set it,
2968 * skip the cache.
2970 if (dir->internal.exclude_list_group[EXC_CMDL].nr)
2971 return NULL;
2973 if (!ident_in_untracked(dir->untracked)) {
2974 warning(_("untracked cache is disabled on this system or location"));
2975 return NULL;
2979 * If the untracked structure we received does not have the same flags
2980 * as requested in this run, we're going to need to either discard the
2981 * existing structure (and potentially later recreate), or bypass the
2982 * untracked cache mechanism for this run.
2984 if (dir->flags != dir->untracked->dir_flags) {
2986 * If the untracked structure we received does not have the same flags
2987 * as configured, then we need to reset / create a new "untracked"
2988 * structure to match the new config.
2990 * Keeping the saved and used untracked cache consistent with the
2991 * configuration provides an opportunity for frequent users of
2992 * "git status -uall" to leverage the untracked cache by aligning their
2993 * configuration - setting "status.showuntrackedfiles" to "all" or
2994 * "normal" as appropriate.
2996 * Previously using -uall (or setting "status.showuntrackedfiles" to
2997 * "all") was incompatible with untracked cache and *consistently*
2998 * caused surprisingly bad performance (with fscache and fsmonitor
2999 * enabled) on Windows.
3001 * IMPROVEMENT OPPORTUNITY: If we reworked the untracked cache storage
3002 * to not be as bound up with the desired output in a given run,
3003 * and instead iterated through and stored enough information to
3004 * correctly serve both "modes", then users could get peak performance
3005 * with or without '-uall' regardless of their
3006 * "status.showuntrackedfiles" config.
3008 if (dir->untracked->dir_flags != new_untracked_cache_flags(istate)) {
3009 free_untracked_cache(istate->untracked);
3010 new_untracked_cache(istate, dir->flags);
3011 dir->untracked = istate->untracked;
3013 else {
3015 * Current untracked cache data is consistent with config, but not
3016 * usable in this request/run; just bypass untracked cache.
3018 return NULL;
3022 if (!dir->untracked->root) {
3023 /* Untracked cache existed but is not initialized; fix that */
3024 FLEX_ALLOC_STR(dir->untracked->root, name, "");
3025 istate->cache_changed |= UNTRACKED_CHANGED;
3028 /* Validate $GIT_DIR/info/exclude and core.excludesfile */
3029 root = dir->untracked->root;
3030 if (!oideq(&dir->internal.ss_info_exclude.oid,
3031 &dir->untracked->ss_info_exclude.oid)) {
3032 invalidate_gitignore(dir->untracked, root);
3033 dir->untracked->ss_info_exclude = dir->internal.ss_info_exclude;
3035 if (!oideq(&dir->internal.ss_excludes_file.oid,
3036 &dir->untracked->ss_excludes_file.oid)) {
3037 invalidate_gitignore(dir->untracked, root);
3038 dir->untracked->ss_excludes_file = dir->internal.ss_excludes_file;
3041 /* Make sure this directory is not dropped out at saving phase */
3042 root->recurse = 1;
3043 return root;
3046 static void emit_traversal_statistics(struct dir_struct *dir,
3047 struct repository *repo,
3048 const char *path,
3049 int path_len)
3051 if (!trace2_is_enabled())
3052 return;
3054 if (!path_len) {
3055 trace2_data_string("read_directory", repo, "path", "");
3056 } else {
3057 struct strbuf tmp = STRBUF_INIT;
3058 strbuf_add(&tmp, path, path_len);
3059 trace2_data_string("read_directory", repo, "path", tmp.buf);
3060 strbuf_release(&tmp);
3063 trace2_data_intmax("read_directory", repo,
3064 "directories-visited", dir->internal.visited_directories);
3065 trace2_data_intmax("read_directory", repo,
3066 "paths-visited", dir->internal.visited_paths);
3068 if (!dir->untracked)
3069 return;
3070 trace2_data_intmax("read_directory", repo,
3071 "node-creation", dir->untracked->dir_created);
3072 trace2_data_intmax("read_directory", repo,
3073 "gitignore-invalidation",
3074 dir->untracked->gitignore_invalidated);
3075 trace2_data_intmax("read_directory", repo,
3076 "directory-invalidation",
3077 dir->untracked->dir_invalidated);
3078 trace2_data_intmax("read_directory", repo,
3079 "opendir", dir->untracked->dir_opened);
3082 int read_directory(struct dir_struct *dir, struct index_state *istate,
3083 const char *path, int len, const struct pathspec *pathspec)
3085 struct untracked_cache_dir *untracked;
3087 trace2_region_enter("dir", "read_directory", istate->repo);
3088 dir->internal.visited_paths = 0;
3089 dir->internal.visited_directories = 0;
3091 if (has_symlink_leading_path(path, len)) {
3092 trace2_region_leave("dir", "read_directory", istate->repo);
3093 return dir->nr;
3096 untracked = validate_untracked_cache(dir, len, pathspec, istate);
3097 if (!untracked)
3099 * make sure untracked cache code path is disabled,
3100 * e.g. prep_exclude()
3102 dir->untracked = NULL;
3103 if (!len || treat_leading_path(dir, istate, path, len, pathspec))
3104 read_directory_recursive(dir, istate, path, len, untracked, 0, 0, pathspec);
3105 QSORT(dir->entries, dir->nr, cmp_dir_entry);
3106 QSORT(dir->ignored, dir->ignored_nr, cmp_dir_entry);
3108 emit_traversal_statistics(dir, istate->repo, path, len);
3110 trace2_region_leave("dir", "read_directory", istate->repo);
3111 if (dir->untracked) {
3112 static int force_untracked_cache = -1;
3114 if (force_untracked_cache < 0)
3115 force_untracked_cache =
3116 git_env_bool("GIT_FORCE_UNTRACKED_CACHE", -1);
3117 if (force_untracked_cache < 0)
3118 force_untracked_cache = (istate->repo->settings.core_untracked_cache == UNTRACKED_CACHE_WRITE);
3119 if (force_untracked_cache &&
3120 dir->untracked == istate->untracked &&
3121 (dir->untracked->dir_opened ||
3122 dir->untracked->gitignore_invalidated ||
3123 dir->untracked->dir_invalidated))
3124 istate->cache_changed |= UNTRACKED_CHANGED;
3125 if (dir->untracked != istate->untracked) {
3126 FREE_AND_NULL(dir->untracked);
3130 return dir->nr;
3133 int file_exists(const char *f)
3135 struct stat sb;
3136 return lstat(f, &sb) == 0;
3139 int repo_file_exists(struct repository *repo, const char *path)
3141 if (repo != the_repository)
3142 BUG("do not know how to check file existence in arbitrary repo");
3144 return file_exists(path);
3147 static int cmp_icase(char a, char b)
3149 if (a == b)
3150 return 0;
3151 if (ignore_case)
3152 return toupper(a) - toupper(b);
3153 return a - b;
3157 * Given two normalized paths (a trailing slash is ok), if subdir is
3158 * outside dir, return -1. Otherwise return the offset in subdir that
3159 * can be used as relative path to dir.
3161 int dir_inside_of(const char *subdir, const char *dir)
3163 int offset = 0;
3165 assert(dir && subdir && *dir && *subdir);
3167 while (*dir && *subdir && !cmp_icase(*dir, *subdir)) {
3168 dir++;
3169 subdir++;
3170 offset++;
3173 /* hel[p]/me vs hel[l]/yeah */
3174 if (*dir && *subdir)
3175 return -1;
3177 if (!*subdir)
3178 return !*dir ? offset : -1; /* same dir */
3180 /* foo/[b]ar vs foo/[] */
3181 if (is_dir_sep(dir[-1]))
3182 return is_dir_sep(subdir[-1]) ? offset : -1;
3184 /* foo[/]bar vs foo[] */
3185 return is_dir_sep(*subdir) ? offset + 1 : -1;
3188 int is_inside_dir(const char *dir)
3190 char *cwd;
3191 int rc;
3193 if (!dir)
3194 return 0;
3196 cwd = xgetcwd();
3197 rc = (dir_inside_of(cwd, dir) >= 0);
3198 free(cwd);
3199 return rc;
3202 int is_empty_dir(const char *path)
3204 DIR *dir = opendir(path);
3205 struct dirent *e;
3206 int ret = 1;
3208 if (!dir)
3209 return 0;
3211 e = readdir_skip_dot_and_dotdot(dir);
3212 if (e)
3213 ret = 0;
3215 closedir(dir);
3216 return ret;
3219 char *git_url_basename(const char *repo, int is_bundle, int is_bare)
3221 const char *end = repo + strlen(repo), *start, *ptr;
3222 size_t len;
3223 char *dir;
3226 * Skip scheme.
3228 start = strstr(repo, "://");
3229 if (!start)
3230 start = repo;
3231 else
3232 start += 3;
3235 * Skip authentication data. The stripping does happen
3236 * greedily, such that we strip up to the last '@' inside
3237 * the host part.
3239 for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
3240 if (*ptr == '@')
3241 start = ptr + 1;
3245 * Strip trailing spaces, slashes and /.git
3247 while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
3248 end--;
3249 if (end - start > 5 && is_dir_sep(end[-5]) &&
3250 !strncmp(end - 4, ".git", 4)) {
3251 end -= 5;
3252 while (start < end && is_dir_sep(end[-1]))
3253 end--;
3257 * It should not be possible to overflow `ptrdiff_t` by passing in an
3258 * insanely long URL, but GCC does not know that and will complain
3259 * without this check.
3261 if (end - start < 0)
3262 die(_("No directory name could be guessed.\n"
3263 "Please specify a directory on the command line"));
3266 * Strip trailing port number if we've got only a
3267 * hostname (that is, there is no dir separator but a
3268 * colon). This check is required such that we do not
3269 * strip URI's like '/foo/bar:2222.git', which should
3270 * result in a dir '2222' being guessed due to backwards
3271 * compatibility.
3273 if (memchr(start, '/', end - start) == NULL
3274 && memchr(start, ':', end - start) != NULL) {
3275 ptr = end;
3276 while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
3277 ptr--;
3278 if (start < ptr && ptr[-1] == ':')
3279 end = ptr - 1;
3283 * Find last component. To remain backwards compatible we
3284 * also regard colons as path separators, such that
3285 * cloning a repository 'foo:bar.git' would result in a
3286 * directory 'bar' being guessed.
3288 ptr = end;
3289 while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
3290 ptr--;
3291 start = ptr;
3294 * Strip .{bundle,git}.
3296 len = end - start;
3297 strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
3299 if (!len || (len == 1 && *start == '/'))
3300 die(_("No directory name could be guessed.\n"
3301 "Please specify a directory on the command line"));
3303 if (is_bare)
3304 dir = xstrfmt("%.*s.git", (int)len, start);
3305 else
3306 dir = xstrndup(start, len);
3308 * Replace sequences of 'control' characters and whitespace
3309 * with one ascii space, remove leading and trailing spaces.
3311 if (*dir) {
3312 char *out = dir;
3313 int prev_space = 1 /* strip leading whitespace */;
3314 for (end = dir; *end; ++end) {
3315 char ch = *end;
3316 if ((unsigned char)ch < '\x20')
3317 ch = '\x20';
3318 if (isspace(ch)) {
3319 if (prev_space)
3320 continue;
3321 prev_space = 1;
3322 } else
3323 prev_space = 0;
3324 *out++ = ch;
3326 *out = '\0';
3327 if (out > dir && prev_space)
3328 out[-1] = '\0';
3330 return dir;
3333 void strip_dir_trailing_slashes(char *dir)
3335 char *end = dir + strlen(dir);
3337 while (dir < end - 1 && is_dir_sep(end[-1]))
3338 end--;
3339 *end = '\0';
3342 static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
3344 DIR *dir;
3345 struct dirent *e;
3346 int ret = 0, original_len = path->len, len, kept_down = 0;
3347 int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
3348 int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
3349 int purge_original_cwd = (flag & REMOVE_DIR_PURGE_ORIGINAL_CWD);
3350 struct object_id submodule_head;
3352 if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
3353 !repo_resolve_gitlink_ref(the_repository, path->buf,
3354 "HEAD", &submodule_head)) {
3355 /* Do not descend and nuke a nested git work tree. */
3356 if (kept_up)
3357 *kept_up = 1;
3358 return 0;
3361 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
3362 dir = opendir(path->buf);
3363 if (!dir) {
3364 if (errno == ENOENT)
3365 return keep_toplevel ? -1 : 0;
3366 else if (errno == EACCES && !keep_toplevel)
3368 * An empty dir could be removable even if it
3369 * is unreadable:
3371 return rmdir(path->buf);
3372 else
3373 return -1;
3375 strbuf_complete(path, '/');
3377 len = path->len;
3378 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
3379 struct stat st;
3381 strbuf_setlen(path, len);
3382 strbuf_addstr(path, e->d_name);
3383 if (lstat(path->buf, &st)) {
3384 if (errno == ENOENT)
3386 * file disappeared, which is what we
3387 * wanted anyway
3389 continue;
3390 /* fall through */
3391 } else if (S_ISDIR(st.st_mode)) {
3392 if (!remove_dir_recurse(path, flag, &kept_down))
3393 continue; /* happy */
3394 } else if (!only_empty &&
3395 (!unlink(path->buf) || errno == ENOENT)) {
3396 continue; /* happy, too */
3399 /* path too long, stat fails, or non-directory still exists */
3400 ret = -1;
3401 break;
3403 closedir(dir);
3405 strbuf_setlen(path, original_len);
3406 if (!ret && !keep_toplevel && !kept_down) {
3407 if (!purge_original_cwd &&
3408 startup_info->original_cwd &&
3409 !strcmp(startup_info->original_cwd, path->buf))
3410 ret = -1; /* Do not remove current working directory */
3411 else
3412 ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1;
3413 } else if (kept_up)
3415 * report the uplevel that it is not an error that we
3416 * did not rmdir() our directory.
3418 *kept_up = !ret;
3419 return ret;
3422 int remove_dir_recursively(struct strbuf *path, int flag)
3424 return remove_dir_recurse(path, flag, NULL);
3427 static GIT_PATH_FUNC(git_path_info_exclude, "info/exclude")
3429 void setup_standard_excludes(struct dir_struct *dir)
3431 dir->exclude_per_dir = ".gitignore";
3433 /* core.excludesfile defaulting to $XDG_CONFIG_HOME/git/ignore */
3434 if (!excludes_file)
3435 excludes_file = xdg_config_home("ignore");
3436 if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
3437 add_patterns_from_file_1(dir, excludes_file,
3438 dir->untracked ? &dir->internal.ss_excludes_file : NULL);
3440 /* per repository user preference */
3441 if (startup_info->have_repository) {
3442 const char *path = git_path_info_exclude();
3443 if (!access_or_warn(path, R_OK, 0))
3444 add_patterns_from_file_1(dir, path,
3445 dir->untracked ? &dir->internal.ss_info_exclude : NULL);
3449 char *get_sparse_checkout_filename(void)
3451 return git_pathdup("info/sparse-checkout");
3454 int get_sparse_checkout_patterns(struct pattern_list *pl)
3456 int res;
3457 char *sparse_filename = get_sparse_checkout_filename();
3459 pl->use_cone_patterns = core_sparse_checkout_cone;
3460 res = add_patterns_from_file_to_list(sparse_filename, "", 0, pl, NULL, 0);
3462 free(sparse_filename);
3463 return res;
3466 int remove_path(const char *name)
3468 char *slash;
3470 if (unlink(name) && !is_missing_file_error(errno))
3471 return -1;
3473 slash = strrchr(name, '/');
3474 if (slash) {
3475 char *dirs = xstrdup(name);
3476 slash = dirs + (slash - name);
3477 do {
3478 *slash = '\0';
3479 if (startup_info->original_cwd &&
3480 !strcmp(startup_info->original_cwd, dirs))
3481 break;
3482 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
3483 free(dirs);
3485 return 0;
3489 * Frees memory within dir which was allocated, and resets fields for further
3490 * use. Does not free dir itself.
3492 void dir_clear(struct dir_struct *dir)
3494 int i, j;
3495 struct exclude_list_group *group;
3496 struct pattern_list *pl;
3497 struct exclude_stack *stk;
3498 struct dir_struct new = DIR_INIT;
3500 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
3501 group = &dir->internal.exclude_list_group[i];
3502 for (j = 0; j < group->nr; j++) {
3503 pl = &group->pl[j];
3504 if (i == EXC_DIRS)
3505 free((char *)pl->src);
3506 clear_pattern_list(pl);
3508 free(group->pl);
3511 for (i = 0; i < dir->ignored_nr; i++)
3512 free(dir->ignored[i]);
3513 for (i = 0; i < dir->nr; i++)
3514 free(dir->entries[i]);
3515 free(dir->ignored);
3516 free(dir->entries);
3518 stk = dir->internal.exclude_stack;
3519 while (stk) {
3520 struct exclude_stack *prev = stk->prev;
3521 free(stk);
3522 stk = prev;
3524 strbuf_release(&dir->internal.basebuf);
3526 memcpy(dir, &new, sizeof(*dir));
3529 struct ondisk_untracked_cache {
3530 struct stat_data info_exclude_stat;
3531 struct stat_data excludes_file_stat;
3532 uint32_t dir_flags;
3535 #define ouc_offset(x) offsetof(struct ondisk_untracked_cache, x)
3537 struct write_data {
3538 int index; /* number of written untracked_cache_dir */
3539 struct ewah_bitmap *check_only; /* from untracked_cache_dir */
3540 struct ewah_bitmap *valid; /* from untracked_cache_dir */
3541 struct ewah_bitmap *sha1_valid; /* set if exclude_sha1 is not null */
3542 struct strbuf out;
3543 struct strbuf sb_stat;
3544 struct strbuf sb_sha1;
3547 static void stat_data_to_disk(struct stat_data *to, const struct stat_data *from)
3549 to->sd_ctime.sec = htonl(from->sd_ctime.sec);
3550 to->sd_ctime.nsec = htonl(from->sd_ctime.nsec);
3551 to->sd_mtime.sec = htonl(from->sd_mtime.sec);
3552 to->sd_mtime.nsec = htonl(from->sd_mtime.nsec);
3553 to->sd_dev = htonl(from->sd_dev);
3554 to->sd_ino = htonl(from->sd_ino);
3555 to->sd_uid = htonl(from->sd_uid);
3556 to->sd_gid = htonl(from->sd_gid);
3557 to->sd_size = htonl(from->sd_size);
3560 static void write_one_dir(struct untracked_cache_dir *untracked,
3561 struct write_data *wd)
3563 struct stat_data stat_data;
3564 struct strbuf *out = &wd->out;
3565 unsigned char intbuf[16];
3566 unsigned int intlen, value;
3567 int i = wd->index++;
3570 * untracked_nr should be reset whenever valid is clear, but
3571 * for safety..
3573 if (!untracked->valid) {
3574 untracked->untracked_nr = 0;
3575 untracked->check_only = 0;
3578 if (untracked->check_only)
3579 ewah_set(wd->check_only, i);
3580 if (untracked->valid) {
3581 ewah_set(wd->valid, i);
3582 stat_data_to_disk(&stat_data, &untracked->stat_data);
3583 strbuf_add(&wd->sb_stat, &stat_data, sizeof(stat_data));
3585 if (!is_null_oid(&untracked->exclude_oid)) {
3586 ewah_set(wd->sha1_valid, i);
3587 strbuf_add(&wd->sb_sha1, untracked->exclude_oid.hash,
3588 the_hash_algo->rawsz);
3591 intlen = encode_varint(untracked->untracked_nr, intbuf);
3592 strbuf_add(out, intbuf, intlen);
3594 /* skip non-recurse directories */
3595 for (i = 0, value = 0; i < untracked->dirs_nr; i++)
3596 if (untracked->dirs[i]->recurse)
3597 value++;
3598 intlen = encode_varint(value, intbuf);
3599 strbuf_add(out, intbuf, intlen);
3601 strbuf_add(out, untracked->name, strlen(untracked->name) + 1);
3603 for (i = 0; i < untracked->untracked_nr; i++)
3604 strbuf_add(out, untracked->untracked[i],
3605 strlen(untracked->untracked[i]) + 1);
3607 for (i = 0; i < untracked->dirs_nr; i++)
3608 if (untracked->dirs[i]->recurse)
3609 write_one_dir(untracked->dirs[i], wd);
3612 void write_untracked_extension(struct strbuf *out, struct untracked_cache *untracked)
3614 struct ondisk_untracked_cache *ouc;
3615 struct write_data wd;
3616 unsigned char varbuf[16];
3617 int varint_len;
3618 const unsigned hashsz = the_hash_algo->rawsz;
3620 CALLOC_ARRAY(ouc, 1);
3621 stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);
3622 stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);
3623 ouc->dir_flags = htonl(untracked->dir_flags);
3625 varint_len = encode_varint(untracked->ident.len, varbuf);
3626 strbuf_add(out, varbuf, varint_len);
3627 strbuf_addbuf(out, &untracked->ident);
3629 strbuf_add(out, ouc, sizeof(*ouc));
3630 strbuf_add(out, untracked->ss_info_exclude.oid.hash, hashsz);
3631 strbuf_add(out, untracked->ss_excludes_file.oid.hash, hashsz);
3632 strbuf_add(out, untracked->exclude_per_dir, strlen(untracked->exclude_per_dir) + 1);
3633 FREE_AND_NULL(ouc);
3635 if (!untracked->root) {
3636 varint_len = encode_varint(0, varbuf);
3637 strbuf_add(out, varbuf, varint_len);
3638 return;
3641 wd.index = 0;
3642 wd.check_only = ewah_new();
3643 wd.valid = ewah_new();
3644 wd.sha1_valid = ewah_new();
3645 strbuf_init(&wd.out, 1024);
3646 strbuf_init(&wd.sb_stat, 1024);
3647 strbuf_init(&wd.sb_sha1, 1024);
3648 write_one_dir(untracked->root, &wd);
3650 varint_len = encode_varint(wd.index, varbuf);
3651 strbuf_add(out, varbuf, varint_len);
3652 strbuf_addbuf(out, &wd.out);
3653 ewah_serialize_strbuf(wd.valid, out);
3654 ewah_serialize_strbuf(wd.check_only, out);
3655 ewah_serialize_strbuf(wd.sha1_valid, out);
3656 strbuf_addbuf(out, &wd.sb_stat);
3657 strbuf_addbuf(out, &wd.sb_sha1);
3658 strbuf_addch(out, '\0'); /* safe guard for string lists */
3660 ewah_free(wd.valid);
3661 ewah_free(wd.check_only);
3662 ewah_free(wd.sha1_valid);
3663 strbuf_release(&wd.out);
3664 strbuf_release(&wd.sb_stat);
3665 strbuf_release(&wd.sb_sha1);
3668 static void free_untracked(struct untracked_cache_dir *ucd)
3670 int i;
3671 if (!ucd)
3672 return;
3673 for (i = 0; i < ucd->dirs_nr; i++)
3674 free_untracked(ucd->dirs[i]);
3675 for (i = 0; i < ucd->untracked_nr; i++)
3676 free(ucd->untracked[i]);
3677 free(ucd->untracked);
3678 free(ucd->dirs);
3679 free(ucd);
3682 void free_untracked_cache(struct untracked_cache *uc)
3684 if (!uc)
3685 return;
3687 free(uc->exclude_per_dir_to_free);
3688 strbuf_release(&uc->ident);
3689 free_untracked(uc->root);
3690 free(uc);
3693 struct read_data {
3694 int index;
3695 struct untracked_cache_dir **ucd;
3696 struct ewah_bitmap *check_only;
3697 struct ewah_bitmap *valid;
3698 struct ewah_bitmap *sha1_valid;
3699 const unsigned char *data;
3700 const unsigned char *end;
3703 static void stat_data_from_disk(struct stat_data *to, const unsigned char *data)
3705 memcpy(to, data, sizeof(*to));
3706 to->sd_ctime.sec = ntohl(to->sd_ctime.sec);
3707 to->sd_ctime.nsec = ntohl(to->sd_ctime.nsec);
3708 to->sd_mtime.sec = ntohl(to->sd_mtime.sec);
3709 to->sd_mtime.nsec = ntohl(to->sd_mtime.nsec);
3710 to->sd_dev = ntohl(to->sd_dev);
3711 to->sd_ino = ntohl(to->sd_ino);
3712 to->sd_uid = ntohl(to->sd_uid);
3713 to->sd_gid = ntohl(to->sd_gid);
3714 to->sd_size = ntohl(to->sd_size);
3717 static int read_one_dir(struct untracked_cache_dir **untracked_,
3718 struct read_data *rd)
3720 struct untracked_cache_dir ud, *untracked;
3721 const unsigned char *data = rd->data, *end = rd->end;
3722 const unsigned char *eos;
3723 unsigned int value;
3724 int i;
3726 memset(&ud, 0, sizeof(ud));
3728 value = decode_varint(&data);
3729 if (data > end)
3730 return -1;
3731 ud.recurse = 1;
3732 ud.untracked_alloc = value;
3733 ud.untracked_nr = value;
3734 if (ud.untracked_nr)
3735 ALLOC_ARRAY(ud.untracked, ud.untracked_nr);
3737 ud.dirs_alloc = ud.dirs_nr = decode_varint(&data);
3738 if (data > end)
3739 return -1;
3740 ALLOC_ARRAY(ud.dirs, ud.dirs_nr);
3742 eos = memchr(data, '\0', end - data);
3743 if (!eos || eos == end)
3744 return -1;
3746 *untracked_ = untracked = xmalloc(st_add3(sizeof(*untracked), eos - data, 1));
3747 memcpy(untracked, &ud, sizeof(ud));
3748 memcpy(untracked->name, data, eos - data + 1);
3749 data = eos + 1;
3751 for (i = 0; i < untracked->untracked_nr; i++) {
3752 eos = memchr(data, '\0', end - data);
3753 if (!eos || eos == end)
3754 return -1;
3755 untracked->untracked[i] = xmemdupz(data, eos - data);
3756 data = eos + 1;
3759 rd->ucd[rd->index++] = untracked;
3760 rd->data = data;
3762 for (i = 0; i < untracked->dirs_nr; i++) {
3763 if (read_one_dir(untracked->dirs + i, rd) < 0)
3764 return -1;
3766 return 0;
3769 static void set_check_only(size_t pos, void *cb)
3771 struct read_data *rd = cb;
3772 struct untracked_cache_dir *ud = rd->ucd[pos];
3773 ud->check_only = 1;
3776 static void read_stat(size_t pos, void *cb)
3778 struct read_data *rd = cb;
3779 struct untracked_cache_dir *ud = rd->ucd[pos];
3780 if (rd->data + sizeof(struct stat_data) > rd->end) {
3781 rd->data = rd->end + 1;
3782 return;
3784 stat_data_from_disk(&ud->stat_data, rd->data);
3785 rd->data += sizeof(struct stat_data);
3786 ud->valid = 1;
3789 static void read_oid(size_t pos, void *cb)
3791 struct read_data *rd = cb;
3792 struct untracked_cache_dir *ud = rd->ucd[pos];
3793 if (rd->data + the_hash_algo->rawsz > rd->end) {
3794 rd->data = rd->end + 1;
3795 return;
3797 oidread(&ud->exclude_oid, rd->data);
3798 rd->data += the_hash_algo->rawsz;
3801 static void load_oid_stat(struct oid_stat *oid_stat, const unsigned char *data,
3802 const unsigned char *sha1)
3804 stat_data_from_disk(&oid_stat->stat, data);
3805 oidread(&oid_stat->oid, sha1);
3806 oid_stat->valid = 1;
3809 struct untracked_cache *read_untracked_extension(const void *data, unsigned long sz)
3811 struct untracked_cache *uc;
3812 struct read_data rd;
3813 const unsigned char *next = data, *end = (const unsigned char *)data + sz;
3814 const char *ident;
3815 int ident_len;
3816 ssize_t len;
3817 const char *exclude_per_dir;
3818 const unsigned hashsz = the_hash_algo->rawsz;
3819 const unsigned offset = sizeof(struct ondisk_untracked_cache);
3820 const unsigned exclude_per_dir_offset = offset + 2 * hashsz;
3822 if (sz <= 1 || end[-1] != '\0')
3823 return NULL;
3824 end--;
3826 ident_len = decode_varint(&next);
3827 if (next + ident_len > end)
3828 return NULL;
3829 ident = (const char *)next;
3830 next += ident_len;
3832 if (next + exclude_per_dir_offset + 1 > end)
3833 return NULL;
3835 CALLOC_ARRAY(uc, 1);
3836 strbuf_init(&uc->ident, ident_len);
3837 strbuf_add(&uc->ident, ident, ident_len);
3838 load_oid_stat(&uc->ss_info_exclude,
3839 next + ouc_offset(info_exclude_stat),
3840 next + offset);
3841 load_oid_stat(&uc->ss_excludes_file,
3842 next + ouc_offset(excludes_file_stat),
3843 next + offset + hashsz);
3844 uc->dir_flags = get_be32(next + ouc_offset(dir_flags));
3845 exclude_per_dir = (const char *)next + exclude_per_dir_offset;
3846 uc->exclude_per_dir = uc->exclude_per_dir_to_free = xstrdup(exclude_per_dir);
3847 /* NUL after exclude_per_dir is covered by sizeof(*ouc) */
3848 next += exclude_per_dir_offset + strlen(exclude_per_dir) + 1;
3849 if (next >= end)
3850 goto done2;
3852 len = decode_varint(&next);
3853 if (next > end || len == 0)
3854 goto done2;
3856 rd.valid = ewah_new();
3857 rd.check_only = ewah_new();
3858 rd.sha1_valid = ewah_new();
3859 rd.data = next;
3860 rd.end = end;
3861 rd.index = 0;
3862 ALLOC_ARRAY(rd.ucd, len);
3864 if (read_one_dir(&uc->root, &rd) || rd.index != len)
3865 goto done;
3867 next = rd.data;
3868 len = ewah_read_mmap(rd.valid, next, end - next);
3869 if (len < 0)
3870 goto done;
3872 next += len;
3873 len = ewah_read_mmap(rd.check_only, next, end - next);
3874 if (len < 0)
3875 goto done;
3877 next += len;
3878 len = ewah_read_mmap(rd.sha1_valid, next, end - next);
3879 if (len < 0)
3880 goto done;
3882 ewah_each_bit(rd.check_only, set_check_only, &rd);
3883 rd.data = next + len;
3884 ewah_each_bit(rd.valid, read_stat, &rd);
3885 ewah_each_bit(rd.sha1_valid, read_oid, &rd);
3886 next = rd.data;
3888 done:
3889 free(rd.ucd);
3890 ewah_free(rd.valid);
3891 ewah_free(rd.check_only);
3892 ewah_free(rd.sha1_valid);
3893 done2:
3894 if (next != end) {
3895 free_untracked_cache(uc);
3896 uc = NULL;
3898 return uc;
3901 static void invalidate_one_directory(struct untracked_cache *uc,
3902 struct untracked_cache_dir *ucd)
3904 uc->dir_invalidated++;
3905 ucd->valid = 0;
3906 ucd->untracked_nr = 0;
3910 * Normally when an entry is added or removed from a directory,
3911 * invalidating that directory is enough. No need to touch its
3912 * ancestors. When a directory is shown as "foo/bar/" in git-status
3913 * however, deleting or adding an entry may have cascading effect.
3915 * Say the "foo/bar/file" has become untracked, we need to tell the
3916 * untracked_cache_dir of "foo" that "bar/" is not an untracked
3917 * directory any more (because "bar" is managed by foo as an untracked
3918 * "file").
3920 * Similarly, if "foo/bar/file" moves from untracked to tracked and it
3921 * was the last untracked entry in the entire "foo", we should show
3922 * "foo/" instead. Which means we have to invalidate past "bar" up to
3923 * "foo".
3925 * This function traverses all directories from root to leaf. If there
3926 * is a chance of one of the above cases happening, we invalidate back
3927 * to root. Otherwise we just invalidate the leaf. There may be a more
3928 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to
3929 * detect these cases and avoid unnecessary invalidation, for example,
3930 * checking for the untracked entry named "bar/" in "foo", but for now
3931 * stick to something safe and simple.
3933 static int invalidate_one_component(struct untracked_cache *uc,
3934 struct untracked_cache_dir *dir,
3935 const char *path, int len)
3937 const char *rest = strchr(path, '/');
3939 if (rest) {
3940 int component_len = rest - path;
3941 struct untracked_cache_dir *d =
3942 lookup_untracked(uc, dir, path, component_len);
3943 int ret =
3944 invalidate_one_component(uc, d, rest + 1,
3945 len - (component_len + 1));
3946 if (ret)
3947 invalidate_one_directory(uc, dir);
3948 return ret;
3951 invalidate_one_directory(uc, dir);
3952 return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;
3955 void untracked_cache_invalidate_path(struct index_state *istate,
3956 const char *path, int safe_path)
3958 if (!istate->untracked || !istate->untracked->root)
3959 return;
3960 if (!safe_path && !verify_path(path, 0))
3961 return;
3962 invalidate_one_component(istate->untracked, istate->untracked->root,
3963 path, strlen(path));
3966 void untracked_cache_invalidate_trimmed_path(struct index_state *istate,
3967 const char *path,
3968 int safe_path)
3970 size_t len = strlen(path);
3972 if (!len)
3973 BUG("untracked_cache_invalidate_trimmed_path given zero length path");
3975 if (path[len - 1] != '/') {
3976 untracked_cache_invalidate_path(istate, path, safe_path);
3977 } else {
3978 struct strbuf tmp = STRBUF_INIT;
3980 strbuf_add(&tmp, path, len - 1);
3981 untracked_cache_invalidate_path(istate, tmp.buf, safe_path);
3982 strbuf_release(&tmp);
3986 void untracked_cache_remove_from_index(struct index_state *istate,
3987 const char *path)
3989 untracked_cache_invalidate_path(istate, path, 1);
3992 void untracked_cache_add_to_index(struct index_state *istate,
3993 const char *path)
3995 untracked_cache_invalidate_path(istate, path, 1);
3998 static void connect_wt_gitdir_in_nested(const char *sub_worktree,
3999 const char *sub_gitdir)
4001 int i;
4002 struct repository subrepo;
4003 struct strbuf sub_wt = STRBUF_INIT;
4004 struct strbuf sub_gd = STRBUF_INIT;
4006 const struct submodule *sub;
4008 /* If the submodule has no working tree, we can ignore it. */
4009 if (repo_init(&subrepo, sub_gitdir, sub_worktree))
4010 return;
4012 if (repo_read_index(&subrepo) < 0)
4013 die(_("index file corrupt in repo %s"), subrepo.gitdir);
4015 /* TODO: audit for interaction with sparse-index. */
4016 ensure_full_index(subrepo.index);
4017 for (i = 0; i < subrepo.index->cache_nr; i++) {
4018 const struct cache_entry *ce = subrepo.index->cache[i];
4020 if (!S_ISGITLINK(ce->ce_mode))
4021 continue;
4023 while (i + 1 < subrepo.index->cache_nr &&
4024 !strcmp(ce->name, subrepo.index->cache[i + 1]->name))
4026 * Skip entries with the same name in different stages
4027 * to make sure an entry is returned only once.
4029 i++;
4031 sub = submodule_from_path(&subrepo, null_oid(), ce->name);
4032 if (!sub || !is_submodule_active(&subrepo, ce->name))
4033 /* .gitmodules broken or inactive sub */
4034 continue;
4036 strbuf_reset(&sub_wt);
4037 strbuf_reset(&sub_gd);
4038 strbuf_addf(&sub_wt, "%s/%s", sub_worktree, sub->path);
4039 submodule_name_to_gitdir(&sub_gd, &subrepo, sub->name);
4041 connect_work_tree_and_git_dir(sub_wt.buf, sub_gd.buf, 1);
4043 strbuf_release(&sub_wt);
4044 strbuf_release(&sub_gd);
4045 repo_clear(&subrepo);
4048 void connect_work_tree_and_git_dir(const char *work_tree_,
4049 const char *git_dir_,
4050 int recurse_into_nested)
4052 struct strbuf gitfile_sb = STRBUF_INIT;
4053 struct strbuf cfg_sb = STRBUF_INIT;
4054 struct strbuf rel_path = STRBUF_INIT;
4055 char *git_dir, *work_tree;
4057 /* Prepare .git file */
4058 strbuf_addf(&gitfile_sb, "%s/.git", work_tree_);
4059 if (safe_create_leading_directories_const(gitfile_sb.buf))
4060 die(_("could not create directories for %s"), gitfile_sb.buf);
4062 /* Prepare config file */
4063 strbuf_addf(&cfg_sb, "%s/config", git_dir_);
4064 if (safe_create_leading_directories_const(cfg_sb.buf))
4065 die(_("could not create directories for %s"), cfg_sb.buf);
4067 git_dir = real_pathdup(git_dir_, 1);
4068 work_tree = real_pathdup(work_tree_, 1);
4070 /* Write .git file */
4071 write_file(gitfile_sb.buf, "gitdir: %s",
4072 relative_path(git_dir, work_tree, &rel_path));
4073 /* Update core.worktree setting */
4074 git_config_set_in_file(cfg_sb.buf, "core.worktree",
4075 relative_path(work_tree, git_dir, &rel_path));
4077 strbuf_release(&gitfile_sb);
4078 strbuf_release(&cfg_sb);
4079 strbuf_release(&rel_path);
4081 if (recurse_into_nested)
4082 connect_wt_gitdir_in_nested(work_tree, git_dir);
4084 free(work_tree);
4085 free(git_dir);
4089 * Migrate the git directory of the given path from old_git_dir to new_git_dir.
4091 void relocate_gitdir(const char *path, const char *old_git_dir, const char *new_git_dir)
4093 if (rename(old_git_dir, new_git_dir) < 0)
4094 die_errno(_("could not migrate git directory from '%s' to '%s'"),
4095 old_git_dir, new_git_dir);
4097 connect_work_tree_and_git_dir(path, new_git_dir, 0);
4100 int path_match_flags(const char *const str, const enum path_match_flags flags)
4102 const char *p = str;
4104 if (flags & PATH_MATCH_NATIVE &&
4105 flags & PATH_MATCH_XPLATFORM)
4106 BUG("path_match_flags() must get one match kind, not multiple!");
4107 else if (!(flags & PATH_MATCH_KINDS_MASK))
4108 BUG("path_match_flags() must get at least one match kind!");
4110 if (flags & PATH_MATCH_STARTS_WITH_DOT_SLASH &&
4111 flags & PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH)
4112 BUG("path_match_flags() must get one platform kind, not multiple!");
4113 else if (!(flags & PATH_MATCH_PLATFORM_MASK))
4114 BUG("path_match_flags() must get at least one platform kind!");
4116 if (*p++ != '.')
4117 return 0;
4118 if (flags & PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH &&
4119 *p++ != '.')
4120 return 0;
4122 if (flags & PATH_MATCH_NATIVE)
4123 return is_dir_sep(*p);
4124 else if (flags & PATH_MATCH_XPLATFORM)
4125 return is_xplatform_dir_sep(*p);
4126 BUG("unreachable");