cache.h: remove expand_user_path()
[git/debian.git] / dir.c
blobc72481c60ee3a552d46644443b3e1c66dc980d09
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 "alloc.h"
11 #include "config.h"
12 #include "dir.h"
13 #include "gettext.h"
14 #include "object-store.h"
15 #include "attr.h"
16 #include "refs.h"
17 #include "wildmatch.h"
18 #include "pathspec.h"
19 #include "utf8.h"
20 #include "varint.h"
21 #include "ewah/ewok.h"
22 #include "fsmonitor.h"
23 #include "submodule-config.h"
26 * Tells read_directory_recursive how a file or directory should be treated.
27 * Values are ordered by significance, e.g. if a directory contains both
28 * excluded and untracked files, it is listed as untracked because
29 * path_untracked > path_excluded.
31 enum path_treatment {
32 path_none = 0,
33 path_recurse,
34 path_excluded,
35 path_untracked
39 * Support data structure for our opendir/readdir/closedir wrappers
41 struct cached_dir {
42 DIR *fdir;
43 struct untracked_cache_dir *untracked;
44 int nr_files;
45 int nr_dirs;
47 const char *d_name;
48 int d_type;
49 const char *file;
50 struct untracked_cache_dir *ucd;
53 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
54 struct index_state *istate, const char *path, int len,
55 struct untracked_cache_dir *untracked,
56 int check_only, int stop_at_first_file, const struct pathspec *pathspec);
57 static int resolve_dtype(int dtype, struct index_state *istate,
58 const char *path, int len);
59 struct dirent *readdir_skip_dot_and_dotdot(DIR *dirp)
61 struct dirent *e;
63 while ((e = readdir(dirp)) != NULL) {
64 if (!is_dot_or_dotdot(e->d_name))
65 break;
67 return e;
70 int count_slashes(const char *s)
72 int cnt = 0;
73 while (*s)
74 if (*s++ == '/')
75 cnt++;
76 return cnt;
79 int fspathcmp(const char *a, const char *b)
81 return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
84 int fspatheq(const char *a, const char *b)
86 return !fspathcmp(a, b);
89 int fspathncmp(const char *a, const char *b, size_t count)
91 return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
94 unsigned int fspathhash(const char *str)
96 return ignore_case ? strihash(str) : strhash(str);
99 int git_fnmatch(const struct pathspec_item *item,
100 const char *pattern, const char *string,
101 int prefix)
103 if (prefix > 0) {
104 if (ps_strncmp(item, pattern, string, prefix))
105 return WM_NOMATCH;
106 pattern += prefix;
107 string += prefix;
109 if (item->flags & PATHSPEC_ONESTAR) {
110 int pattern_len = strlen(++pattern);
111 int string_len = strlen(string);
112 return string_len < pattern_len ||
113 ps_strcmp(item, pattern,
114 string + string_len - pattern_len);
116 if (item->magic & PATHSPEC_GLOB)
117 return wildmatch(pattern, string,
118 WM_PATHNAME |
119 (item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0));
120 else
121 /* wildmatch has not learned no FNM_PATHNAME mode yet */
122 return wildmatch(pattern, string,
123 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0);
126 static int fnmatch_icase_mem(const char *pattern, int patternlen,
127 const char *string, int stringlen,
128 int flags)
130 int match_status;
131 struct strbuf pat_buf = STRBUF_INIT;
132 struct strbuf str_buf = STRBUF_INIT;
133 const char *use_pat = pattern;
134 const char *use_str = string;
136 if (pattern[patternlen]) {
137 strbuf_add(&pat_buf, pattern, patternlen);
138 use_pat = pat_buf.buf;
140 if (string[stringlen]) {
141 strbuf_add(&str_buf, string, stringlen);
142 use_str = str_buf.buf;
145 if (ignore_case)
146 flags |= WM_CASEFOLD;
147 match_status = wildmatch(use_pat, use_str, flags);
149 strbuf_release(&pat_buf);
150 strbuf_release(&str_buf);
152 return match_status;
155 static size_t common_prefix_len(const struct pathspec *pathspec)
157 int n;
158 size_t max = 0;
161 * ":(icase)path" is treated as a pathspec full of
162 * wildcard. In other words, only prefix is considered common
163 * prefix. If the pathspec is abc/foo abc/bar, running in
164 * subdir xyz, the common prefix is still xyz, not xyz/abc as
165 * in non-:(icase).
167 GUARD_PATHSPEC(pathspec,
168 PATHSPEC_FROMTOP |
169 PATHSPEC_MAXDEPTH |
170 PATHSPEC_LITERAL |
171 PATHSPEC_GLOB |
172 PATHSPEC_ICASE |
173 PATHSPEC_EXCLUDE |
174 PATHSPEC_ATTR);
176 for (n = 0; n < pathspec->nr; n++) {
177 size_t i = 0, len = 0, item_len;
178 if (pathspec->items[n].magic & PATHSPEC_EXCLUDE)
179 continue;
180 if (pathspec->items[n].magic & PATHSPEC_ICASE)
181 item_len = pathspec->items[n].prefix;
182 else
183 item_len = pathspec->items[n].nowildcard_len;
184 while (i < item_len && (n == 0 || i < max)) {
185 char c = pathspec->items[n].match[i];
186 if (c != pathspec->items[0].match[i])
187 break;
188 if (c == '/')
189 len = i + 1;
190 i++;
192 if (n == 0 || len < max) {
193 max = len;
194 if (!max)
195 break;
198 return max;
202 * Returns a copy of the longest leading path common among all
203 * pathspecs.
205 char *common_prefix(const struct pathspec *pathspec)
207 unsigned long len = common_prefix_len(pathspec);
209 return len ? xmemdupz(pathspec->items[0].match, len) : NULL;
212 int fill_directory(struct dir_struct *dir,
213 struct index_state *istate,
214 const struct pathspec *pathspec)
216 const char *prefix;
217 size_t prefix_len;
219 unsigned exclusive_flags = DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO;
220 if ((dir->flags & exclusive_flags) == exclusive_flags)
221 BUG("DIR_SHOW_IGNORED and DIR_SHOW_IGNORED_TOO are exclusive");
224 * Calculate common prefix for the pathspec, and
225 * use that to optimize the directory walk
227 prefix_len = common_prefix_len(pathspec);
228 prefix = prefix_len ? pathspec->items[0].match : "";
230 /* Read the directory and prune it */
231 read_directory(dir, istate, prefix, prefix_len, pathspec);
233 return prefix_len;
236 int within_depth(const char *name, int namelen,
237 int depth, int max_depth)
239 const char *cp = name, *cpe = name + namelen;
241 while (cp < cpe) {
242 if (*cp++ != '/')
243 continue;
244 depth++;
245 if (depth > max_depth)
246 return 0;
248 return 1;
252 * Read the contents of the blob with the given OID into a buffer.
253 * Append a trailing LF to the end if the last line doesn't have one.
255 * Returns:
256 * -1 when the OID is invalid or unknown or does not refer to a blob.
257 * 0 when the blob is empty.
258 * 1 along with { data, size } of the (possibly augmented) buffer
259 * when successful.
261 * Optionally updates the given oid_stat with the given OID (when valid).
263 static int do_read_blob(const struct object_id *oid, struct oid_stat *oid_stat,
264 size_t *size_out, char **data_out)
266 enum object_type type;
267 unsigned long sz;
268 char *data;
270 *size_out = 0;
271 *data_out = NULL;
273 data = read_object_file(oid, &type, &sz);
274 if (!data || type != OBJ_BLOB) {
275 free(data);
276 return -1;
279 if (oid_stat) {
280 memset(&oid_stat->stat, 0, sizeof(oid_stat->stat));
281 oidcpy(&oid_stat->oid, oid);
284 if (sz == 0) {
285 free(data);
286 return 0;
289 if (data[sz - 1] != '\n') {
290 data = xrealloc(data, st_add(sz, 1));
291 data[sz++] = '\n';
294 *size_out = xsize_t(sz);
295 *data_out = data;
297 return 1;
300 #define DO_MATCH_EXCLUDE (1<<0)
301 #define DO_MATCH_DIRECTORY (1<<1)
302 #define DO_MATCH_LEADING_PATHSPEC (1<<2)
305 * Does the given pathspec match the given name? A match is found if
307 * (1) the pathspec string is leading directory of 'name' ("RECURSIVELY"), or
308 * (2) the pathspec string has a leading part matching 'name' ("LEADING"), or
309 * (3) the pathspec string is a wildcard and matches 'name' ("WILDCARD"), or
310 * (4) the pathspec string is exactly the same as 'name' ("EXACT").
312 * Return value tells which case it was (1-4), or 0 when there is no match.
314 * It may be instructive to look at a small table of concrete examples
315 * to understand the differences between 1, 2, and 4:
317 * Pathspecs
318 * | a/b | a/b/ | a/b/c
319 * ------+-----------+-----------+------------
320 * a/b | EXACT | EXACT[1] | LEADING[2]
321 * Names a/b/ | RECURSIVE | EXACT | LEADING[2]
322 * a/b/c | RECURSIVE | RECURSIVE | EXACT
324 * [1] Only if DO_MATCH_DIRECTORY is passed; otherwise, this is NOT a match.
325 * [2] Only if DO_MATCH_LEADING_PATHSPEC is passed; otherwise, not a match.
327 static int match_pathspec_item(struct index_state *istate,
328 const struct pathspec_item *item, int prefix,
329 const char *name, int namelen, unsigned flags)
331 /* name/namelen has prefix cut off by caller */
332 const char *match = item->match + prefix;
333 int matchlen = item->len - prefix;
336 * The normal call pattern is:
337 * 1. prefix = common_prefix_len(ps);
338 * 2. prune something, or fill_directory
339 * 3. match_pathspec()
341 * 'prefix' at #1 may be shorter than the command's prefix and
342 * it's ok for #2 to match extra files. Those extras will be
343 * trimmed at #3.
345 * Suppose the pathspec is 'foo' and '../bar' running from
346 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
347 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
348 * user does not want XYZ/foo, only the "foo" part should be
349 * case-insensitive. We need to filter out XYZ/foo here. In
350 * other words, we do not trust the caller on comparing the
351 * prefix part when :(icase) is involved. We do exact
352 * comparison ourselves.
354 * Normally the caller (common_prefix_len() in fact) does
355 * _exact_ matching on name[-prefix+1..-1] and we do not need
356 * to check that part. Be defensive and check it anyway, in
357 * case common_prefix_len is changed, or a new caller is
358 * introduced that does not use common_prefix_len.
360 * If the penalty turns out too high when prefix is really
361 * long, maybe change it to
362 * strncmp(match, name, item->prefix - prefix)
364 if (item->prefix && (item->magic & PATHSPEC_ICASE) &&
365 strncmp(item->match, name - prefix, item->prefix))
366 return 0;
368 if (item->attr_match_nr &&
369 !match_pathspec_attrs(istate, name, namelen, item))
370 return 0;
372 /* If the match was just the prefix, we matched */
373 if (!*match)
374 return MATCHED_RECURSIVELY;
376 if (matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) {
377 if (matchlen == namelen)
378 return MATCHED_EXACTLY;
380 if (match[matchlen-1] == '/' || name[matchlen] == '/')
381 return MATCHED_RECURSIVELY;
382 } else if ((flags & DO_MATCH_DIRECTORY) &&
383 match[matchlen - 1] == '/' &&
384 namelen == matchlen - 1 &&
385 !ps_strncmp(item, match, name, namelen))
386 return MATCHED_EXACTLY;
388 if (item->nowildcard_len < item->len &&
389 !git_fnmatch(item, match, name,
390 item->nowildcard_len - prefix))
391 return MATCHED_FNMATCH;
393 /* Perform checks to see if "name" is a leading string of the pathspec */
394 if ( (flags & DO_MATCH_LEADING_PATHSPEC) &&
395 !(flags & DO_MATCH_EXCLUDE)) {
396 /* name is a literal prefix of the pathspec */
397 int offset = name[namelen-1] == '/' ? 1 : 0;
398 if ((namelen < matchlen) &&
399 (match[namelen-offset] == '/') &&
400 !ps_strncmp(item, match, name, namelen))
401 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
403 /* name doesn't match up to the first wild character */
404 if (item->nowildcard_len < item->len &&
405 ps_strncmp(item, match, name,
406 item->nowildcard_len - prefix))
407 return 0;
410 * name has no wildcard, and it didn't match as a leading
411 * pathspec so return.
413 if (item->nowildcard_len == item->len)
414 return 0;
417 * Here is where we would perform a wildmatch to check if
418 * "name" can be matched as a directory (or a prefix) against
419 * the pathspec. Since wildmatch doesn't have this capability
420 * at the present we have to punt and say that it is a match,
421 * potentially returning a false positive
422 * The submodules themselves will be able to perform more
423 * accurate matching to determine if the pathspec matches.
425 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
428 return 0;
432 * do_match_pathspec() is meant to ONLY be called by
433 * match_pathspec_with_flags(); calling it directly risks pathspecs
434 * like ':!unwanted_path' being ignored.
436 * Given a name and a list of pathspecs, returns the nature of the
437 * closest (i.e. most specific) match of the name to any of the
438 * pathspecs.
440 * The caller typically calls this multiple times with the same
441 * pathspec and seen[] array but with different name/namelen
442 * (e.g. entries from the index) and is interested in seeing if and
443 * how each pathspec matches all the names it calls this function
444 * with. A mark is left in the seen[] array for each pathspec element
445 * indicating the closest type of match that element achieved, so if
446 * seen[n] remains zero after multiple invocations, that means the nth
447 * pathspec did not match any names, which could indicate that the
448 * user mistyped the nth pathspec.
450 static int do_match_pathspec(struct index_state *istate,
451 const struct pathspec *ps,
452 const char *name, int namelen,
453 int prefix, char *seen,
454 unsigned flags)
456 int i, retval = 0, exclude = flags & DO_MATCH_EXCLUDE;
458 GUARD_PATHSPEC(ps,
459 PATHSPEC_FROMTOP |
460 PATHSPEC_MAXDEPTH |
461 PATHSPEC_LITERAL |
462 PATHSPEC_GLOB |
463 PATHSPEC_ICASE |
464 PATHSPEC_EXCLUDE |
465 PATHSPEC_ATTR);
467 if (!ps->nr) {
468 if (!ps->recursive ||
469 !(ps->magic & PATHSPEC_MAXDEPTH) ||
470 ps->max_depth == -1)
471 return MATCHED_RECURSIVELY;
473 if (within_depth(name, namelen, 0, ps->max_depth))
474 return MATCHED_EXACTLY;
475 else
476 return 0;
479 name += prefix;
480 namelen -= prefix;
482 for (i = ps->nr - 1; i >= 0; i--) {
483 int how;
485 if ((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) ||
486 ( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE)))
487 continue;
489 if (seen && seen[i] == MATCHED_EXACTLY)
490 continue;
492 * Make exclude patterns optional and never report
493 * "pathspec ':(exclude)foo' matches no files"
495 if (seen && ps->items[i].magic & PATHSPEC_EXCLUDE)
496 seen[i] = MATCHED_FNMATCH;
497 how = match_pathspec_item(istate, ps->items+i, prefix, name,
498 namelen, flags);
499 if (ps->recursive &&
500 (ps->magic & PATHSPEC_MAXDEPTH) &&
501 ps->max_depth != -1 &&
502 how && how != MATCHED_FNMATCH) {
503 int len = ps->items[i].len;
504 if (name[len] == '/')
505 len++;
506 if (within_depth(name+len, namelen-len, 0, ps->max_depth))
507 how = MATCHED_EXACTLY;
508 else
509 how = 0;
511 if (how) {
512 if (retval < how)
513 retval = how;
514 if (seen && seen[i] < how)
515 seen[i] = how;
518 return retval;
521 static int match_pathspec_with_flags(struct index_state *istate,
522 const struct pathspec *ps,
523 const char *name, int namelen,
524 int prefix, char *seen, unsigned flags)
526 int positive, negative;
527 positive = do_match_pathspec(istate, ps, name, namelen,
528 prefix, seen, flags);
529 if (!(ps->magic & PATHSPEC_EXCLUDE) || !positive)
530 return positive;
531 negative = do_match_pathspec(istate, ps, name, namelen,
532 prefix, seen,
533 flags | DO_MATCH_EXCLUDE);
534 return negative ? 0 : positive;
537 int match_pathspec(struct index_state *istate,
538 const struct pathspec *ps,
539 const char *name, int namelen,
540 int prefix, char *seen, int is_dir)
542 unsigned flags = is_dir ? DO_MATCH_DIRECTORY : 0;
543 return match_pathspec_with_flags(istate, ps, name, namelen,
544 prefix, seen, flags);
548 * Check if a submodule is a superset of the pathspec
550 int submodule_path_match(struct index_state *istate,
551 const struct pathspec *ps,
552 const char *submodule_name,
553 char *seen)
555 int matched = match_pathspec_with_flags(istate, ps, submodule_name,
556 strlen(submodule_name),
557 0, seen,
558 DO_MATCH_DIRECTORY |
559 DO_MATCH_LEADING_PATHSPEC);
560 return matched;
563 int report_path_error(const char *ps_matched,
564 const struct pathspec *pathspec)
567 * Make sure all pathspec matched; otherwise it is an error.
569 int num, errors = 0;
570 for (num = 0; num < pathspec->nr; num++) {
571 int other, found_dup;
573 if (ps_matched[num])
574 continue;
576 * The caller might have fed identical pathspec
577 * twice. Do not barf on such a mistake.
578 * FIXME: parse_pathspec should have eliminated
579 * duplicate pathspec.
581 for (found_dup = other = 0;
582 !found_dup && other < pathspec->nr;
583 other++) {
584 if (other == num || !ps_matched[other])
585 continue;
586 if (!strcmp(pathspec->items[other].original,
587 pathspec->items[num].original))
589 * Ok, we have a match already.
591 found_dup = 1;
593 if (found_dup)
594 continue;
596 error(_("pathspec '%s' did not match any file(s) known to git"),
597 pathspec->items[num].original);
598 errors++;
600 return errors;
604 * Return the length of the "simple" part of a path match limiter.
606 int simple_length(const char *match)
608 int len = -1;
610 for (;;) {
611 unsigned char c = *match++;
612 len++;
613 if (c == '\0' || is_glob_special(c))
614 return len;
618 int no_wildcard(const char *string)
620 return string[simple_length(string)] == '\0';
623 void parse_path_pattern(const char **pattern,
624 int *patternlen,
625 unsigned *flags,
626 int *nowildcardlen)
628 const char *p = *pattern;
629 size_t i, len;
631 *flags = 0;
632 if (*p == '!') {
633 *flags |= PATTERN_FLAG_NEGATIVE;
634 p++;
636 len = strlen(p);
637 if (len && p[len - 1] == '/') {
638 len--;
639 *flags |= PATTERN_FLAG_MUSTBEDIR;
641 for (i = 0; i < len; i++) {
642 if (p[i] == '/')
643 break;
645 if (i == len)
646 *flags |= PATTERN_FLAG_NODIR;
647 *nowildcardlen = simple_length(p);
649 * we should have excluded the trailing slash from 'p' too,
650 * but that's one more allocation. Instead just make sure
651 * nowildcardlen does not exceed real patternlen
653 if (*nowildcardlen > len)
654 *nowildcardlen = len;
655 if (*p == '*' && no_wildcard(p + 1))
656 *flags |= PATTERN_FLAG_ENDSWITH;
657 *pattern = p;
658 *patternlen = len;
661 int pl_hashmap_cmp(const void *cmp_data UNUSED,
662 const struct hashmap_entry *a,
663 const struct hashmap_entry *b,
664 const void *key UNUSED)
666 const struct pattern_entry *ee1 =
667 container_of(a, struct pattern_entry, ent);
668 const struct pattern_entry *ee2 =
669 container_of(b, struct pattern_entry, ent);
671 size_t min_len = ee1->patternlen <= ee2->patternlen
672 ? ee1->patternlen
673 : ee2->patternlen;
675 return fspathncmp(ee1->pattern, ee2->pattern, min_len);
678 static char *dup_and_filter_pattern(const char *pattern)
680 char *set, *read;
681 size_t count = 0;
682 char *result = xstrdup(pattern);
684 set = result;
685 read = result;
687 while (*read) {
688 /* skip escape characters (once) */
689 if (*read == '\\')
690 read++;
692 *set = *read;
694 set++;
695 read++;
696 count++;
698 *set = 0;
700 if (count > 2 &&
701 *(set - 1) == '*' &&
702 *(set - 2) == '/')
703 *(set - 2) = 0;
705 return result;
708 static void add_pattern_to_hashsets(struct pattern_list *pl, struct path_pattern *given)
710 struct pattern_entry *translated;
711 char *truncated;
712 char *data = NULL;
713 const char *prev, *cur, *next;
715 if (!pl->use_cone_patterns)
716 return;
718 if (given->flags & PATTERN_FLAG_NEGATIVE &&
719 given->flags & PATTERN_FLAG_MUSTBEDIR &&
720 !strcmp(given->pattern, "/*")) {
721 pl->full_cone = 0;
722 return;
725 if (!given->flags && !strcmp(given->pattern, "/*")) {
726 pl->full_cone = 1;
727 return;
730 if (given->patternlen < 2 ||
731 *given->pattern != '/' ||
732 strstr(given->pattern, "**")) {
733 /* Not a cone pattern. */
734 warning(_("unrecognized pattern: '%s'"), given->pattern);
735 goto clear_hashmaps;
738 if (!(given->flags & PATTERN_FLAG_MUSTBEDIR) &&
739 strcmp(given->pattern, "/*")) {
740 /* Not a cone pattern. */
741 warning(_("unrecognized pattern: '%s'"), given->pattern);
742 goto clear_hashmaps;
745 prev = given->pattern;
746 cur = given->pattern + 1;
747 next = given->pattern + 2;
749 while (*cur) {
750 /* Watch for glob characters '*', '\', '[', '?' */
751 if (!is_glob_special(*cur))
752 goto increment;
754 /* But only if *prev != '\\' */
755 if (*prev == '\\')
756 goto increment;
758 /* But allow the initial '\' */
759 if (*cur == '\\' &&
760 is_glob_special(*next))
761 goto increment;
763 /* But a trailing '/' then '*' is fine */
764 if (*prev == '/' &&
765 *cur == '*' &&
766 *next == 0)
767 goto increment;
769 /* Not a cone pattern. */
770 warning(_("unrecognized pattern: '%s'"), given->pattern);
771 goto clear_hashmaps;
773 increment:
774 prev++;
775 cur++;
776 next++;
779 if (given->patternlen > 2 &&
780 !strcmp(given->pattern + given->patternlen - 2, "/*")) {
781 if (!(given->flags & PATTERN_FLAG_NEGATIVE)) {
782 /* Not a cone pattern. */
783 warning(_("unrecognized pattern: '%s'"), given->pattern);
784 goto clear_hashmaps;
787 truncated = dup_and_filter_pattern(given->pattern);
789 translated = xmalloc(sizeof(struct pattern_entry));
790 translated->pattern = truncated;
791 translated->patternlen = given->patternlen - 2;
792 hashmap_entry_init(&translated->ent,
793 fspathhash(translated->pattern));
795 if (!hashmap_get_entry(&pl->recursive_hashmap,
796 translated, ent, NULL)) {
797 /* We did not see the "parent" included */
798 warning(_("unrecognized negative pattern: '%s'"),
799 given->pattern);
800 free(truncated);
801 free(translated);
802 goto clear_hashmaps;
805 hashmap_add(&pl->parent_hashmap, &translated->ent);
806 hashmap_remove(&pl->recursive_hashmap, &translated->ent, &data);
807 free(data);
808 return;
811 if (given->flags & PATTERN_FLAG_NEGATIVE) {
812 warning(_("unrecognized negative pattern: '%s'"),
813 given->pattern);
814 goto clear_hashmaps;
817 translated = xmalloc(sizeof(struct pattern_entry));
819 translated->pattern = dup_and_filter_pattern(given->pattern);
820 translated->patternlen = given->patternlen;
821 hashmap_entry_init(&translated->ent,
822 fspathhash(translated->pattern));
824 hashmap_add(&pl->recursive_hashmap, &translated->ent);
826 if (hashmap_get_entry(&pl->parent_hashmap, translated, ent, NULL)) {
827 /* we already included this at the parent level */
828 warning(_("your sparse-checkout file may have issues: pattern '%s' is repeated"),
829 given->pattern);
830 goto clear_hashmaps;
833 return;
835 clear_hashmaps:
836 warning(_("disabling cone pattern matching"));
837 hashmap_clear_and_free(&pl->parent_hashmap, struct pattern_entry, ent);
838 hashmap_clear_and_free(&pl->recursive_hashmap, struct pattern_entry, ent);
839 pl->use_cone_patterns = 0;
842 static int hashmap_contains_path(struct hashmap *map,
843 struct strbuf *pattern)
845 struct pattern_entry p;
847 /* Check straight mapping */
848 p.pattern = pattern->buf;
849 p.patternlen = pattern->len;
850 hashmap_entry_init(&p.ent, fspathhash(p.pattern));
851 return !!hashmap_get_entry(map, &p, ent, NULL);
854 int hashmap_contains_parent(struct hashmap *map,
855 const char *path,
856 struct strbuf *buffer)
858 char *slash_pos;
860 strbuf_setlen(buffer, 0);
862 if (path[0] != '/')
863 strbuf_addch(buffer, '/');
865 strbuf_addstr(buffer, path);
867 slash_pos = strrchr(buffer->buf, '/');
869 while (slash_pos > buffer->buf) {
870 strbuf_setlen(buffer, slash_pos - buffer->buf);
872 if (hashmap_contains_path(map, buffer))
873 return 1;
875 slash_pos = strrchr(buffer->buf, '/');
878 return 0;
881 void add_pattern(const char *string, const char *base,
882 int baselen, struct pattern_list *pl, int srcpos)
884 struct path_pattern *pattern;
885 int patternlen;
886 unsigned flags;
887 int nowildcardlen;
889 parse_path_pattern(&string, &patternlen, &flags, &nowildcardlen);
890 if (flags & PATTERN_FLAG_MUSTBEDIR) {
891 FLEXPTR_ALLOC_MEM(pattern, pattern, string, patternlen);
892 } else {
893 pattern = xmalloc(sizeof(*pattern));
894 pattern->pattern = string;
896 pattern->patternlen = patternlen;
897 pattern->nowildcardlen = nowildcardlen;
898 pattern->base = base;
899 pattern->baselen = baselen;
900 pattern->flags = flags;
901 pattern->srcpos = srcpos;
902 ALLOC_GROW(pl->patterns, pl->nr + 1, pl->alloc);
903 pl->patterns[pl->nr++] = pattern;
904 pattern->pl = pl;
906 add_pattern_to_hashsets(pl, pattern);
909 static int read_skip_worktree_file_from_index(struct index_state *istate,
910 const char *path,
911 size_t *size_out, char **data_out,
912 struct oid_stat *oid_stat)
914 int pos, len;
916 len = strlen(path);
917 pos = index_name_pos(istate, path, len);
918 if (pos < 0)
919 return -1;
920 if (!ce_skip_worktree(istate->cache[pos]))
921 return -1;
923 return do_read_blob(&istate->cache[pos]->oid, oid_stat, size_out, data_out);
927 * Frees memory within pl which was allocated for exclude patterns and
928 * the file buffer. Does not free pl itself.
930 void clear_pattern_list(struct pattern_list *pl)
932 int i;
934 for (i = 0; i < pl->nr; i++)
935 free(pl->patterns[i]);
936 free(pl->patterns);
937 free(pl->filebuf);
938 hashmap_clear_and_free(&pl->recursive_hashmap, struct pattern_entry, ent);
939 hashmap_clear_and_free(&pl->parent_hashmap, struct pattern_entry, ent);
941 memset(pl, 0, sizeof(*pl));
944 static void trim_trailing_spaces(char *buf)
946 char *p, *last_space = NULL;
948 for (p = buf; *p; p++)
949 switch (*p) {
950 case ' ':
951 if (!last_space)
952 last_space = p;
953 break;
954 case '\\':
955 p++;
956 if (!*p)
957 return;
958 /* fallthrough */
959 default:
960 last_space = NULL;
963 if (last_space)
964 *last_space = '\0';
968 * Given a subdirectory name and "dir" of the current directory,
969 * search the subdir in "dir" and return it, or create a new one if it
970 * does not exist in "dir".
972 * If "name" has the trailing slash, it'll be excluded in the search.
974 static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc,
975 struct untracked_cache_dir *dir,
976 const char *name, int len)
978 int first, last;
979 struct untracked_cache_dir *d;
980 if (!dir)
981 return NULL;
982 if (len && name[len - 1] == '/')
983 len--;
984 first = 0;
985 last = dir->dirs_nr;
986 while (last > first) {
987 int cmp, next = first + ((last - first) >> 1);
988 d = dir->dirs[next];
989 cmp = strncmp(name, d->name, len);
990 if (!cmp && strlen(d->name) > len)
991 cmp = -1;
992 if (!cmp)
993 return d;
994 if (cmp < 0) {
995 last = next;
996 continue;
998 first = next+1;
1001 uc->dir_created++;
1002 FLEX_ALLOC_MEM(d, name, name, len);
1004 ALLOC_GROW(dir->dirs, dir->dirs_nr + 1, dir->dirs_alloc);
1005 MOVE_ARRAY(dir->dirs + first + 1, dir->dirs + first,
1006 dir->dirs_nr - first);
1007 dir->dirs_nr++;
1008 dir->dirs[first] = d;
1009 return d;
1012 static void do_invalidate_gitignore(struct untracked_cache_dir *dir)
1014 int i;
1015 dir->valid = 0;
1016 dir->untracked_nr = 0;
1017 for (i = 0; i < dir->dirs_nr; i++)
1018 do_invalidate_gitignore(dir->dirs[i]);
1021 static void invalidate_gitignore(struct untracked_cache *uc,
1022 struct untracked_cache_dir *dir)
1024 uc->gitignore_invalidated++;
1025 do_invalidate_gitignore(dir);
1028 static void invalidate_directory(struct untracked_cache *uc,
1029 struct untracked_cache_dir *dir)
1031 int i;
1034 * Invalidation increment here is just roughly correct. If
1035 * untracked_nr or any of dirs[].recurse is non-zero, we
1036 * should increment dir_invalidated too. But that's more
1037 * expensive to do.
1039 if (dir->valid)
1040 uc->dir_invalidated++;
1042 dir->valid = 0;
1043 dir->untracked_nr = 0;
1044 for (i = 0; i < dir->dirs_nr; i++)
1045 dir->dirs[i]->recurse = 0;
1048 static int add_patterns_from_buffer(char *buf, size_t size,
1049 const char *base, int baselen,
1050 struct pattern_list *pl);
1052 /* Flags for add_patterns() */
1053 #define PATTERN_NOFOLLOW (1<<0)
1056 * Given a file with name "fname", read it (either from disk, or from
1057 * an index if 'istate' is non-null), parse it and store the
1058 * exclude rules in "pl".
1060 * If "oid_stat" is not NULL, compute oid of the exclude file and fill
1061 * stat data from disk (only valid if add_patterns returns zero). If
1062 * oid_stat.valid is non-zero, "oid_stat" must contain good value as input.
1064 static int add_patterns(const char *fname, const char *base, int baselen,
1065 struct pattern_list *pl, struct index_state *istate,
1066 unsigned flags, struct oid_stat *oid_stat)
1068 struct stat st;
1069 int r;
1070 int fd;
1071 size_t size = 0;
1072 char *buf;
1074 if (flags & PATTERN_NOFOLLOW)
1075 fd = open_nofollow(fname, O_RDONLY);
1076 else
1077 fd = open(fname, O_RDONLY);
1079 if (fd < 0 || fstat(fd, &st) < 0) {
1080 if (fd < 0)
1081 warn_on_fopen_errors(fname);
1082 else
1083 close(fd);
1084 if (!istate)
1085 return -1;
1086 r = read_skip_worktree_file_from_index(istate, fname,
1087 &size, &buf,
1088 oid_stat);
1089 if (r != 1)
1090 return r;
1091 } else {
1092 size = xsize_t(st.st_size);
1093 if (size == 0) {
1094 if (oid_stat) {
1095 fill_stat_data(&oid_stat->stat, &st);
1096 oidcpy(&oid_stat->oid, the_hash_algo->empty_blob);
1097 oid_stat->valid = 1;
1099 close(fd);
1100 return 0;
1102 buf = xmallocz(size);
1103 if (read_in_full(fd, buf, size) != size) {
1104 free(buf);
1105 close(fd);
1106 return -1;
1108 buf[size++] = '\n';
1109 close(fd);
1110 if (oid_stat) {
1111 int pos;
1112 if (oid_stat->valid &&
1113 !match_stat_data_racy(istate, &oid_stat->stat, &st))
1114 ; /* no content change, oid_stat->oid still good */
1115 else if (istate &&
1116 (pos = index_name_pos(istate, fname, strlen(fname))) >= 0 &&
1117 !ce_stage(istate->cache[pos]) &&
1118 ce_uptodate(istate->cache[pos]) &&
1119 !would_convert_to_git(istate, fname))
1120 oidcpy(&oid_stat->oid,
1121 &istate->cache[pos]->oid);
1122 else
1123 hash_object_file(the_hash_algo, buf, size,
1124 OBJ_BLOB, &oid_stat->oid);
1125 fill_stat_data(&oid_stat->stat, &st);
1126 oid_stat->valid = 1;
1130 add_patterns_from_buffer(buf, size, base, baselen, pl);
1131 return 0;
1134 static int add_patterns_from_buffer(char *buf, size_t size,
1135 const char *base, int baselen,
1136 struct pattern_list *pl)
1138 int i, lineno = 1;
1139 char *entry;
1141 hashmap_init(&pl->recursive_hashmap, pl_hashmap_cmp, NULL, 0);
1142 hashmap_init(&pl->parent_hashmap, pl_hashmap_cmp, NULL, 0);
1144 pl->filebuf = buf;
1146 if (skip_utf8_bom(&buf, size))
1147 size -= buf - pl->filebuf;
1149 entry = buf;
1151 for (i = 0; i < size; i++) {
1152 if (buf[i] == '\n') {
1153 if (entry != buf + i && entry[0] != '#') {
1154 buf[i - (i && buf[i-1] == '\r')] = 0;
1155 trim_trailing_spaces(entry);
1156 add_pattern(entry, base, baselen, pl, lineno);
1158 lineno++;
1159 entry = buf + i + 1;
1162 return 0;
1165 int add_patterns_from_file_to_list(const char *fname, const char *base,
1166 int baselen, struct pattern_list *pl,
1167 struct index_state *istate,
1168 unsigned flags)
1170 return add_patterns(fname, base, baselen, pl, istate, flags, NULL);
1173 int add_patterns_from_blob_to_list(
1174 struct object_id *oid,
1175 const char *base, int baselen,
1176 struct pattern_list *pl)
1178 char *buf;
1179 size_t size;
1180 int r;
1182 r = do_read_blob(oid, NULL, &size, &buf);
1183 if (r != 1)
1184 return r;
1186 add_patterns_from_buffer(buf, size, base, baselen, pl);
1187 return 0;
1190 struct pattern_list *add_pattern_list(struct dir_struct *dir,
1191 int group_type, const char *src)
1193 struct pattern_list *pl;
1194 struct exclude_list_group *group;
1196 group = &dir->internal.exclude_list_group[group_type];
1197 ALLOC_GROW(group->pl, group->nr + 1, group->alloc);
1198 pl = &group->pl[group->nr++];
1199 memset(pl, 0, sizeof(*pl));
1200 pl->src = src;
1201 return pl;
1205 * Used to set up core.excludesfile and .git/info/exclude lists.
1207 static void add_patterns_from_file_1(struct dir_struct *dir, const char *fname,
1208 struct oid_stat *oid_stat)
1210 struct pattern_list *pl;
1212 * catch setup_standard_excludes() that's called before
1213 * dir->untracked is assigned. That function behaves
1214 * differently when dir->untracked is non-NULL.
1216 if (!dir->untracked)
1217 dir->internal.unmanaged_exclude_files++;
1218 pl = add_pattern_list(dir, EXC_FILE, fname);
1219 if (add_patterns(fname, "", 0, pl, NULL, 0, oid_stat) < 0)
1220 die(_("cannot use %s as an exclude file"), fname);
1223 void add_patterns_from_file(struct dir_struct *dir, const char *fname)
1225 dir->internal.unmanaged_exclude_files++; /* see validate_untracked_cache() */
1226 add_patterns_from_file_1(dir, fname, NULL);
1229 int match_basename(const char *basename, int basenamelen,
1230 const char *pattern, int prefix, int patternlen,
1231 unsigned flags)
1233 if (prefix == patternlen) {
1234 if (patternlen == basenamelen &&
1235 !fspathncmp(pattern, basename, basenamelen))
1236 return 1;
1237 } else if (flags & PATTERN_FLAG_ENDSWITH) {
1238 /* "*literal" matching against "fooliteral" */
1239 if (patternlen - 1 <= basenamelen &&
1240 !fspathncmp(pattern + 1,
1241 basename + basenamelen - (patternlen - 1),
1242 patternlen - 1))
1243 return 1;
1244 } else {
1245 if (fnmatch_icase_mem(pattern, patternlen,
1246 basename, basenamelen,
1247 0) == 0)
1248 return 1;
1250 return 0;
1253 int match_pathname(const char *pathname, int pathlen,
1254 const char *base, int baselen,
1255 const char *pattern, int prefix, int patternlen)
1257 const char *name;
1258 int namelen;
1261 * match with FNM_PATHNAME; the pattern has base implicitly
1262 * in front of it.
1264 if (*pattern == '/') {
1265 pattern++;
1266 patternlen--;
1267 prefix--;
1271 * baselen does not count the trailing slash. base[] may or
1272 * may not end with a trailing slash though.
1274 if (pathlen < baselen + 1 ||
1275 (baselen && pathname[baselen] != '/') ||
1276 fspathncmp(pathname, base, baselen))
1277 return 0;
1279 namelen = baselen ? pathlen - baselen - 1 : pathlen;
1280 name = pathname + pathlen - namelen;
1282 if (prefix) {
1284 * if the non-wildcard part is longer than the
1285 * remaining pathname, surely it cannot match.
1287 if (prefix > namelen)
1288 return 0;
1290 if (fspathncmp(pattern, name, prefix))
1291 return 0;
1292 pattern += prefix;
1293 patternlen -= prefix;
1294 name += prefix;
1295 namelen -= prefix;
1298 * If the whole pattern did not have a wildcard,
1299 * then our prefix match is all we need; we
1300 * do not need to call fnmatch at all.
1302 if (!patternlen && !namelen)
1303 return 1;
1306 return fnmatch_icase_mem(pattern, patternlen,
1307 name, namelen,
1308 WM_PATHNAME) == 0;
1312 * Scan the given exclude list in reverse to see whether pathname
1313 * should be ignored. The first match (i.e. the last on the list), if
1314 * any, determines the fate. Returns the exclude_list element which
1315 * matched, or NULL for undecided.
1317 static struct path_pattern *last_matching_pattern_from_list(const char *pathname,
1318 int pathlen,
1319 const char *basename,
1320 int *dtype,
1321 struct pattern_list *pl,
1322 struct index_state *istate)
1324 struct path_pattern *res = NULL; /* undecided */
1325 int i;
1327 if (!pl->nr)
1328 return NULL; /* undefined */
1330 for (i = pl->nr - 1; 0 <= i; i--) {
1331 struct path_pattern *pattern = pl->patterns[i];
1332 const char *exclude = pattern->pattern;
1333 int prefix = pattern->nowildcardlen;
1335 if (pattern->flags & PATTERN_FLAG_MUSTBEDIR) {
1336 *dtype = resolve_dtype(*dtype, istate, pathname, pathlen);
1337 if (*dtype != DT_DIR)
1338 continue;
1341 if (pattern->flags & PATTERN_FLAG_NODIR) {
1342 if (match_basename(basename,
1343 pathlen - (basename - pathname),
1344 exclude, prefix, pattern->patternlen,
1345 pattern->flags)) {
1346 res = pattern;
1347 break;
1349 continue;
1352 assert(pattern->baselen == 0 ||
1353 pattern->base[pattern->baselen - 1] == '/');
1354 if (match_pathname(pathname, pathlen,
1355 pattern->base,
1356 pattern->baselen ? pattern->baselen - 1 : 0,
1357 exclude, prefix, pattern->patternlen)) {
1358 res = pattern;
1359 break;
1362 return res;
1366 * Scan the list of patterns to determine if the ordered list
1367 * of patterns matches on 'pathname'.
1369 * Return 1 for a match, 0 for not matched and -1 for undecided.
1371 enum pattern_match_result path_matches_pattern_list(
1372 const char *pathname, int pathlen,
1373 const char *basename, int *dtype,
1374 struct pattern_list *pl,
1375 struct index_state *istate)
1377 struct path_pattern *pattern;
1378 struct strbuf parent_pathname = STRBUF_INIT;
1379 int result = NOT_MATCHED;
1380 size_t slash_pos;
1382 if (!pl->use_cone_patterns) {
1383 pattern = last_matching_pattern_from_list(pathname, pathlen, basename,
1384 dtype, pl, istate);
1385 if (pattern) {
1386 if (pattern->flags & PATTERN_FLAG_NEGATIVE)
1387 return NOT_MATCHED;
1388 else
1389 return MATCHED;
1392 return UNDECIDED;
1395 if (pl->full_cone)
1396 return MATCHED;
1398 strbuf_addch(&parent_pathname, '/');
1399 strbuf_add(&parent_pathname, pathname, pathlen);
1402 * Directory entries are matched if and only if a file
1403 * contained immediately within them is matched. For the
1404 * case of a directory entry, modify the path to create
1405 * a fake filename within this directory, allowing us to
1406 * use the file-base matching logic in an equivalent way.
1408 if (parent_pathname.len > 0 &&
1409 parent_pathname.buf[parent_pathname.len - 1] == '/') {
1410 slash_pos = parent_pathname.len - 1;
1411 strbuf_add(&parent_pathname, "-", 1);
1412 } else {
1413 const char *slash_ptr = strrchr(parent_pathname.buf, '/');
1414 slash_pos = slash_ptr ? slash_ptr - parent_pathname.buf : 0;
1417 if (hashmap_contains_path(&pl->recursive_hashmap,
1418 &parent_pathname)) {
1419 result = MATCHED_RECURSIVE;
1420 goto done;
1423 if (!slash_pos) {
1424 /* include every file in root */
1425 result = MATCHED;
1426 goto done;
1429 strbuf_setlen(&parent_pathname, slash_pos);
1431 if (hashmap_contains_path(&pl->parent_hashmap, &parent_pathname)) {
1432 result = MATCHED;
1433 goto done;
1436 if (hashmap_contains_parent(&pl->recursive_hashmap,
1437 pathname,
1438 &parent_pathname))
1439 result = MATCHED_RECURSIVE;
1441 done:
1442 strbuf_release(&parent_pathname);
1443 return result;
1446 int init_sparse_checkout_patterns(struct index_state *istate)
1448 if (!core_apply_sparse_checkout)
1449 return 1;
1450 if (istate->sparse_checkout_patterns)
1451 return 0;
1453 CALLOC_ARRAY(istate->sparse_checkout_patterns, 1);
1455 if (get_sparse_checkout_patterns(istate->sparse_checkout_patterns) < 0) {
1456 FREE_AND_NULL(istate->sparse_checkout_patterns);
1457 return -1;
1460 return 0;
1463 static int path_in_sparse_checkout_1(const char *path,
1464 struct index_state *istate,
1465 int require_cone_mode)
1467 int dtype = DT_REG;
1468 enum pattern_match_result match = UNDECIDED;
1469 const char *end, *slash;
1472 * We default to accepting a path if the path is empty, there are no
1473 * patterns, or the patterns are of the wrong type.
1475 if (!*path ||
1476 init_sparse_checkout_patterns(istate) ||
1477 (require_cone_mode &&
1478 !istate->sparse_checkout_patterns->use_cone_patterns))
1479 return 1;
1482 * If UNDECIDED, use the match from the parent dir (recursively), or
1483 * fall back to NOT_MATCHED at the topmost level. Note that cone mode
1484 * never returns UNDECIDED, so we will execute only one iteration in
1485 * this case.
1487 for (end = path + strlen(path);
1488 end > path && match == UNDECIDED;
1489 end = slash) {
1491 for (slash = end - 1; slash > path && *slash != '/'; slash--)
1492 ; /* do nothing */
1494 match = path_matches_pattern_list(path, end - path,
1495 slash > path ? slash + 1 : path, &dtype,
1496 istate->sparse_checkout_patterns, istate);
1498 /* We are going to match the parent dir now */
1499 dtype = DT_DIR;
1501 return match > 0;
1504 int path_in_sparse_checkout(const char *path,
1505 struct index_state *istate)
1507 return path_in_sparse_checkout_1(path, istate, 0);
1510 int path_in_cone_mode_sparse_checkout(const char *path,
1511 struct index_state *istate)
1513 return path_in_sparse_checkout_1(path, istate, 1);
1516 static struct path_pattern *last_matching_pattern_from_lists(
1517 struct dir_struct *dir, struct index_state *istate,
1518 const char *pathname, int pathlen,
1519 const char *basename, int *dtype_p)
1521 int i, j;
1522 struct exclude_list_group *group;
1523 struct path_pattern *pattern;
1524 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
1525 group = &dir->internal.exclude_list_group[i];
1526 for (j = group->nr - 1; j >= 0; j--) {
1527 pattern = last_matching_pattern_from_list(
1528 pathname, pathlen, basename, dtype_p,
1529 &group->pl[j], istate);
1530 if (pattern)
1531 return pattern;
1534 return NULL;
1538 * Loads the per-directory exclude list for the substring of base
1539 * which has a char length of baselen.
1541 static void prep_exclude(struct dir_struct *dir,
1542 struct index_state *istate,
1543 const char *base, int baselen)
1545 struct exclude_list_group *group;
1546 struct pattern_list *pl;
1547 struct exclude_stack *stk = NULL;
1548 struct untracked_cache_dir *untracked;
1549 int current;
1551 group = &dir->internal.exclude_list_group[EXC_DIRS];
1554 * Pop the exclude lists from the EXCL_DIRS exclude_list_group
1555 * which originate from directories not in the prefix of the
1556 * path being checked.
1558 while ((stk = dir->internal.exclude_stack) != NULL) {
1559 if (stk->baselen <= baselen &&
1560 !strncmp(dir->internal.basebuf.buf, base, stk->baselen))
1561 break;
1562 pl = &group->pl[dir->internal.exclude_stack->exclude_ix];
1563 dir->internal.exclude_stack = stk->prev;
1564 dir->internal.pattern = NULL;
1565 free((char *)pl->src); /* see strbuf_detach() below */
1566 clear_pattern_list(pl);
1567 free(stk);
1568 group->nr--;
1571 /* Skip traversing into sub directories if the parent is excluded */
1572 if (dir->internal.pattern)
1573 return;
1576 * Lazy initialization. All call sites currently just
1577 * memset(dir, 0, sizeof(*dir)) before use. Changing all of
1578 * them seems lots of work for little benefit.
1580 if (!dir->internal.basebuf.buf)
1581 strbuf_init(&dir->internal.basebuf, PATH_MAX);
1583 /* Read from the parent directories and push them down. */
1584 current = stk ? stk->baselen : -1;
1585 strbuf_setlen(&dir->internal.basebuf, current < 0 ? 0 : current);
1586 if (dir->untracked)
1587 untracked = stk ? stk->ucd : dir->untracked->root;
1588 else
1589 untracked = NULL;
1591 while (current < baselen) {
1592 const char *cp;
1593 struct oid_stat oid_stat;
1595 CALLOC_ARRAY(stk, 1);
1596 if (current < 0) {
1597 cp = base;
1598 current = 0;
1599 } else {
1600 cp = strchr(base + current + 1, '/');
1601 if (!cp)
1602 die("oops in prep_exclude");
1603 cp++;
1604 untracked =
1605 lookup_untracked(dir->untracked,
1606 untracked,
1607 base + current,
1608 cp - base - current);
1610 stk->prev = dir->internal.exclude_stack;
1611 stk->baselen = cp - base;
1612 stk->exclude_ix = group->nr;
1613 stk->ucd = untracked;
1614 pl = add_pattern_list(dir, EXC_DIRS, NULL);
1615 strbuf_add(&dir->internal.basebuf, base + current, stk->baselen - current);
1616 assert(stk->baselen == dir->internal.basebuf.len);
1618 /* Abort if the directory is excluded */
1619 if (stk->baselen) {
1620 int dt = DT_DIR;
1621 dir->internal.basebuf.buf[stk->baselen - 1] = 0;
1622 dir->internal.pattern = last_matching_pattern_from_lists(dir,
1623 istate,
1624 dir->internal.basebuf.buf, stk->baselen - 1,
1625 dir->internal.basebuf.buf + current, &dt);
1626 dir->internal.basebuf.buf[stk->baselen - 1] = '/';
1627 if (dir->internal.pattern &&
1628 dir->internal.pattern->flags & PATTERN_FLAG_NEGATIVE)
1629 dir->internal.pattern = NULL;
1630 if (dir->internal.pattern) {
1631 dir->internal.exclude_stack = stk;
1632 return;
1636 /* Try to read per-directory file */
1637 oidclr(&oid_stat.oid);
1638 oid_stat.valid = 0;
1639 if (dir->exclude_per_dir &&
1641 * If we know that no files have been added in
1642 * this directory (i.e. valid_cached_dir() has
1643 * been executed and set untracked->valid) ..
1645 (!untracked || !untracked->valid ||
1647 * .. and .gitignore does not exist before
1648 * (i.e. null exclude_oid). Then we can skip
1649 * loading .gitignore, which would result in
1650 * ENOENT anyway.
1652 !is_null_oid(&untracked->exclude_oid))) {
1654 * dir->internal.basebuf gets reused by the traversal,
1655 * but we need fname to remain unchanged to ensure the
1656 * src member of each struct path_pattern correctly
1657 * back-references its source file. Other invocations
1658 * of add_pattern_list provide stable strings, so we
1659 * strbuf_detach() and free() here in the caller.
1661 struct strbuf sb = STRBUF_INIT;
1662 strbuf_addbuf(&sb, &dir->internal.basebuf);
1663 strbuf_addstr(&sb, dir->exclude_per_dir);
1664 pl->src = strbuf_detach(&sb, NULL);
1665 add_patterns(pl->src, pl->src, stk->baselen, pl, istate,
1666 PATTERN_NOFOLLOW,
1667 untracked ? &oid_stat : NULL);
1670 * NEEDSWORK: when untracked cache is enabled, prep_exclude()
1671 * will first be called in valid_cached_dir() then maybe many
1672 * times more in last_matching_pattern(). When the cache is
1673 * used, last_matching_pattern() will not be called and
1674 * reading .gitignore content will be a waste.
1676 * So when it's called by valid_cached_dir() and we can get
1677 * .gitignore SHA-1 from the index (i.e. .gitignore is not
1678 * modified on work tree), we could delay reading the
1679 * .gitignore content until we absolutely need it in
1680 * last_matching_pattern(). Be careful about ignore rule
1681 * order, though, if you do that.
1683 if (untracked &&
1684 !oideq(&oid_stat.oid, &untracked->exclude_oid)) {
1685 invalidate_gitignore(dir->untracked, untracked);
1686 oidcpy(&untracked->exclude_oid, &oid_stat.oid);
1688 dir->internal.exclude_stack = stk;
1689 current = stk->baselen;
1691 strbuf_setlen(&dir->internal.basebuf, baselen);
1695 * Loads the exclude lists for the directory containing pathname, then
1696 * scans all exclude lists to determine whether pathname is excluded.
1697 * Returns the exclude_list element which matched, or NULL for
1698 * undecided.
1700 struct path_pattern *last_matching_pattern(struct dir_struct *dir,
1701 struct index_state *istate,
1702 const char *pathname,
1703 int *dtype_p)
1705 int pathlen = strlen(pathname);
1706 const char *basename = strrchr(pathname, '/');
1707 basename = (basename) ? basename+1 : pathname;
1709 prep_exclude(dir, istate, pathname, basename-pathname);
1711 if (dir->internal.pattern)
1712 return dir->internal.pattern;
1714 return last_matching_pattern_from_lists(dir, istate, pathname, pathlen,
1715 basename, dtype_p);
1719 * Loads the exclude lists for the directory containing pathname, then
1720 * scans all exclude lists to determine whether pathname is excluded.
1721 * Returns 1 if true, otherwise 0.
1723 int is_excluded(struct dir_struct *dir, struct index_state *istate,
1724 const char *pathname, int *dtype_p)
1726 struct path_pattern *pattern =
1727 last_matching_pattern(dir, istate, pathname, dtype_p);
1728 if (pattern)
1729 return pattern->flags & PATTERN_FLAG_NEGATIVE ? 0 : 1;
1730 return 0;
1733 static struct dir_entry *dir_entry_new(const char *pathname, int len)
1735 struct dir_entry *ent;
1737 FLEX_ALLOC_MEM(ent, name, pathname, len);
1738 ent->len = len;
1739 return ent;
1742 static struct dir_entry *dir_add_name(struct dir_struct *dir,
1743 struct index_state *istate,
1744 const char *pathname, int len)
1746 if (index_file_exists(istate, pathname, len, ignore_case))
1747 return NULL;
1749 ALLOC_GROW(dir->entries, dir->nr+1, dir->internal.alloc);
1750 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
1753 struct dir_entry *dir_add_ignored(struct dir_struct *dir,
1754 struct index_state *istate,
1755 const char *pathname, int len)
1757 if (!index_name_is_other(istate, pathname, len))
1758 return NULL;
1760 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->internal.ignored_alloc);
1761 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
1764 enum exist_status {
1765 index_nonexistent = 0,
1766 index_directory,
1767 index_gitdir
1771 * Do not use the alphabetically sorted index to look up
1772 * the directory name; instead, use the case insensitive
1773 * directory hash.
1775 static enum exist_status directory_exists_in_index_icase(struct index_state *istate,
1776 const char *dirname, int len)
1778 struct cache_entry *ce;
1780 if (index_dir_exists(istate, dirname, len))
1781 return index_directory;
1783 ce = index_file_exists(istate, dirname, len, ignore_case);
1784 if (ce && S_ISGITLINK(ce->ce_mode))
1785 return index_gitdir;
1787 return index_nonexistent;
1791 * The index sorts alphabetically by entry name, which
1792 * means that a gitlink sorts as '\0' at the end, while
1793 * a directory (which is defined not as an entry, but as
1794 * the files it contains) will sort with the '/' at the
1795 * end.
1797 static enum exist_status directory_exists_in_index(struct index_state *istate,
1798 const char *dirname, int len)
1800 int pos;
1802 if (ignore_case)
1803 return directory_exists_in_index_icase(istate, dirname, len);
1805 pos = index_name_pos(istate, dirname, len);
1806 if (pos < 0)
1807 pos = -pos-1;
1808 while (pos < istate->cache_nr) {
1809 const struct cache_entry *ce = istate->cache[pos++];
1810 unsigned char endchar;
1812 if (strncmp(ce->name, dirname, len))
1813 break;
1814 endchar = ce->name[len];
1815 if (endchar > '/')
1816 break;
1817 if (endchar == '/')
1818 return index_directory;
1819 if (!endchar && S_ISGITLINK(ce->ce_mode))
1820 return index_gitdir;
1822 return index_nonexistent;
1826 * When we find a directory when traversing the filesystem, we
1827 * have three distinct cases:
1829 * - ignore it
1830 * - see it as a directory
1831 * - recurse into it
1833 * and which one we choose depends on a combination of existing
1834 * git index contents and the flags passed into the directory
1835 * traversal routine.
1837 * Case 1: If we *already* have entries in the index under that
1838 * directory name, we always recurse into the directory to see
1839 * all the files.
1841 * Case 2: If we *already* have that directory name as a gitlink,
1842 * we always continue to see it as a gitlink, regardless of whether
1843 * there is an actual git directory there or not (it might not
1844 * be checked out as a subproject!)
1846 * Case 3: if we didn't have it in the index previously, we
1847 * have a few sub-cases:
1849 * (a) if DIR_SHOW_OTHER_DIRECTORIES flag is set, we show it as
1850 * just a directory, unless DIR_HIDE_EMPTY_DIRECTORIES is
1851 * also true, in which case we need to check if it contains any
1852 * untracked and / or ignored files.
1853 * (b) if it looks like a git directory and we don't have the
1854 * DIR_NO_GITLINKS flag, then we treat it as a gitlink, and
1855 * show it as a directory.
1856 * (c) otherwise, we recurse into it.
1858 static enum path_treatment treat_directory(struct dir_struct *dir,
1859 struct index_state *istate,
1860 struct untracked_cache_dir *untracked,
1861 const char *dirname, int len, int baselen, int excluded,
1862 const struct pathspec *pathspec)
1865 * WARNING: From this function, you can return path_recurse or you
1866 * can call read_directory_recursive() (or neither), but
1867 * you CAN'T DO BOTH.
1869 enum path_treatment state;
1870 int matches_how = 0;
1871 int check_only, stop_early;
1872 int old_ignored_nr, old_untracked_nr;
1873 /* The "len-1" is to strip the final '/' */
1874 enum exist_status status = directory_exists_in_index(istate, dirname, len-1);
1876 if (status == index_directory)
1877 return path_recurse;
1878 if (status == index_gitdir)
1879 return path_none;
1880 if (status != index_nonexistent)
1881 BUG("Unhandled value for directory_exists_in_index: %d\n", status);
1884 * We don't want to descend into paths that don't match the necessary
1885 * patterns. Clearly, if we don't have a pathspec, then we can't check
1886 * for matching patterns. Also, if (excluded) then we know we matched
1887 * the exclusion patterns so as an optimization we can skip checking
1888 * for matching patterns.
1890 if (pathspec && !excluded) {
1891 matches_how = match_pathspec_with_flags(istate, pathspec,
1892 dirname, len,
1893 0 /* prefix */,
1894 NULL /* seen */,
1895 DO_MATCH_LEADING_PATHSPEC);
1896 if (!matches_how)
1897 return path_none;
1901 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
1902 !(dir->flags & DIR_NO_GITLINKS)) {
1904 * Determine if `dirname` is a nested repo by confirming that:
1905 * 1) we are in a nonbare repository, and
1906 * 2) `dirname` is not an immediate parent of `the_repository->gitdir`,
1907 * which could occur if the git_dir or worktree location was
1908 * manually configured by the user; see t2205 testcases 1-3 for
1909 * examples where this matters
1911 int nested_repo;
1912 struct strbuf sb = STRBUF_INIT;
1913 strbuf_addstr(&sb, dirname);
1914 nested_repo = is_nonbare_repository_dir(&sb);
1916 if (nested_repo) {
1917 char *real_dirname, *real_gitdir;
1918 strbuf_addstr(&sb, ".git");
1919 real_dirname = real_pathdup(sb.buf, 1);
1920 real_gitdir = real_pathdup(the_repository->gitdir, 1);
1922 nested_repo = !!strcmp(real_dirname, real_gitdir);
1923 free(real_gitdir);
1924 free(real_dirname);
1926 strbuf_release(&sb);
1928 if (nested_repo) {
1929 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
1930 (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC))
1931 return path_none;
1932 return excluded ? path_excluded : path_untracked;
1936 if (!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)) {
1937 if (excluded &&
1938 (dir->flags & DIR_SHOW_IGNORED_TOO) &&
1939 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING)) {
1942 * This is an excluded directory and we are
1943 * showing ignored paths that match an exclude
1944 * pattern. (e.g. show directory as ignored
1945 * only if it matches an exclude pattern).
1946 * This path will either be 'path_excluded`
1947 * (if we are showing empty directories or if
1948 * the directory is not empty), or will be
1949 * 'path_none' (empty directory, and we are
1950 * not showing empty directories).
1952 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1953 return path_excluded;
1955 if (read_directory_recursive(dir, istate, dirname, len,
1956 untracked, 1, 1, pathspec) == path_excluded)
1957 return path_excluded;
1959 return path_none;
1961 return path_recurse;
1964 assert(dir->flags & DIR_SHOW_OTHER_DIRECTORIES);
1967 * If we have a pathspec which could match something _below_ this
1968 * directory (e.g. when checking 'subdir/' having a pathspec like
1969 * 'subdir/some/deep/path/file' or 'subdir/widget-*.c'), then we
1970 * need to recurse.
1972 if (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC)
1973 return path_recurse;
1975 /* Special cases for where this directory is excluded/ignored */
1976 if (excluded) {
1978 * If DIR_SHOW_OTHER_DIRECTORIES is set and we're not
1979 * hiding empty directories, there is no need to
1980 * recurse into an ignored directory.
1982 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1983 return path_excluded;
1986 * Even if we are hiding empty directories, we can still avoid
1987 * recursing into ignored directories for DIR_SHOW_IGNORED_TOO
1988 * if DIR_SHOW_IGNORED_TOO_MODE_MATCHING is also set.
1990 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
1991 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING))
1992 return path_excluded;
1996 * Other than the path_recurse case above, we only need to
1997 * recurse into untracked directories if any of the following
1998 * bits is set:
1999 * - DIR_SHOW_IGNORED (because then we need to determine if
2000 * there are ignored entries below)
2001 * - DIR_SHOW_IGNORED_TOO (same as above)
2002 * - DIR_HIDE_EMPTY_DIRECTORIES (because we have to determine if
2003 * the directory is empty)
2005 if (!excluded &&
2006 !(dir->flags & (DIR_SHOW_IGNORED |
2007 DIR_SHOW_IGNORED_TOO |
2008 DIR_HIDE_EMPTY_DIRECTORIES))) {
2009 return path_untracked;
2013 * Even if we don't want to know all the paths under an untracked or
2014 * ignored directory, we may still need to go into the directory to
2015 * determine if it is empty (because with DIR_HIDE_EMPTY_DIRECTORIES,
2016 * an empty directory should be path_none instead of path_excluded or
2017 * path_untracked).
2019 check_only = ((dir->flags & DIR_HIDE_EMPTY_DIRECTORIES) &&
2020 !(dir->flags & DIR_SHOW_IGNORED_TOO));
2023 * However, there's another optimization possible as a subset of
2024 * check_only, based on the cases we have to consider:
2025 * A) Directory matches no exclude patterns:
2026 * * Directory is empty => path_none
2027 * * Directory has an untracked file under it => path_untracked
2028 * * Directory has only ignored files under it => path_excluded
2029 * B) Directory matches an exclude pattern:
2030 * * Directory is empty => path_none
2031 * * Directory has an untracked file under it => path_excluded
2032 * * Directory has only ignored files under it => path_excluded
2033 * In case A, we can exit as soon as we've found an untracked
2034 * file but otherwise have to walk all files. In case B, though,
2035 * we can stop at the first file we find under the directory.
2037 stop_early = check_only && excluded;
2040 * If /every/ file within an untracked directory is ignored, then
2041 * we want to treat the directory as ignored (for e.g. status
2042 * --porcelain), without listing the individual ignored files
2043 * underneath. To do so, we'll save the current ignored_nr, and
2044 * pop all the ones added after it if it turns out the entire
2045 * directory is ignored. Also, when DIR_SHOW_IGNORED_TOO and
2046 * !DIR_KEEP_UNTRACKED_CONTENTS then we don't want to show
2047 * untracked paths so will need to pop all those off the last
2048 * after we traverse.
2050 old_ignored_nr = dir->ignored_nr;
2051 old_untracked_nr = dir->nr;
2053 /* Actually recurse into dirname now, we'll fixup the state later. */
2054 untracked = lookup_untracked(dir->untracked, untracked,
2055 dirname + baselen, len - baselen);
2056 state = read_directory_recursive(dir, istate, dirname, len, untracked,
2057 check_only, stop_early, pathspec);
2059 /* There are a variety of reasons we may need to fixup the state... */
2060 if (state == path_excluded) {
2061 /* state == path_excluded implies all paths under
2062 * dirname were ignored...
2064 * if running e.g. `git status --porcelain --ignored=matching`,
2065 * then we want to see the subpaths that are ignored.
2067 * if running e.g. just `git status --porcelain`, then
2068 * we just want the directory itself to be listed as ignored
2069 * and not the individual paths underneath.
2071 int want_ignored_subpaths =
2072 ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
2073 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING));
2075 if (want_ignored_subpaths) {
2077 * with --ignored=matching, we want the subpaths
2078 * INSTEAD of the directory itself.
2080 state = path_none;
2081 } else {
2082 int i;
2083 for (i = old_ignored_nr + 1; i<dir->ignored_nr; ++i)
2084 FREE_AND_NULL(dir->ignored[i]);
2085 dir->ignored_nr = old_ignored_nr;
2090 * We may need to ignore some of the untracked paths we found while
2091 * traversing subdirectories.
2093 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
2094 !(dir->flags & DIR_KEEP_UNTRACKED_CONTENTS)) {
2095 int i;
2096 for (i = old_untracked_nr + 1; i<dir->nr; ++i)
2097 FREE_AND_NULL(dir->entries[i]);
2098 dir->nr = old_untracked_nr;
2102 * If there is nothing under the current directory and we are not
2103 * hiding empty directories, then we need to report on the
2104 * untracked or ignored status of the directory itself.
2106 if (state == path_none && !(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
2107 state = excluded ? path_excluded : path_untracked;
2109 return state;
2113 * This is an inexact early pruning of any recursive directory
2114 * reading - if the path cannot possibly be in the pathspec,
2115 * return true, and we'll skip it early.
2117 static int simplify_away(const char *path, int pathlen,
2118 const struct pathspec *pathspec)
2120 int i;
2122 if (!pathspec || !pathspec->nr)
2123 return 0;
2125 GUARD_PATHSPEC(pathspec,
2126 PATHSPEC_FROMTOP |
2127 PATHSPEC_MAXDEPTH |
2128 PATHSPEC_LITERAL |
2129 PATHSPEC_GLOB |
2130 PATHSPEC_ICASE |
2131 PATHSPEC_EXCLUDE |
2132 PATHSPEC_ATTR);
2134 for (i = 0; i < pathspec->nr; i++) {
2135 const struct pathspec_item *item = &pathspec->items[i];
2136 int len = item->nowildcard_len;
2138 if (len > pathlen)
2139 len = pathlen;
2140 if (!ps_strncmp(item, item->match, path, len))
2141 return 0;
2144 return 1;
2148 * This function tells us whether an excluded path matches a
2149 * list of "interesting" pathspecs. That is, whether a path matched
2150 * by any of the pathspecs could possibly be ignored by excluding
2151 * the specified path. This can happen if:
2153 * 1. the path is mentioned explicitly in the pathspec
2155 * 2. the path is a directory prefix of some element in the
2156 * pathspec
2158 static int exclude_matches_pathspec(const char *path, int pathlen,
2159 const struct pathspec *pathspec)
2161 int i;
2163 if (!pathspec || !pathspec->nr)
2164 return 0;
2166 GUARD_PATHSPEC(pathspec,
2167 PATHSPEC_FROMTOP |
2168 PATHSPEC_MAXDEPTH |
2169 PATHSPEC_LITERAL |
2170 PATHSPEC_GLOB |
2171 PATHSPEC_ICASE |
2172 PATHSPEC_EXCLUDE);
2174 for (i = 0; i < pathspec->nr; i++) {
2175 const struct pathspec_item *item = &pathspec->items[i];
2176 int len = item->nowildcard_len;
2178 if (len == pathlen &&
2179 !ps_strncmp(item, item->match, path, pathlen))
2180 return 1;
2181 if (len > pathlen &&
2182 item->match[pathlen] == '/' &&
2183 !ps_strncmp(item, item->match, path, pathlen))
2184 return 1;
2186 return 0;
2189 static int get_index_dtype(struct index_state *istate,
2190 const char *path, int len)
2192 int pos;
2193 const struct cache_entry *ce;
2195 ce = index_file_exists(istate, path, len, 0);
2196 if (ce) {
2197 if (!ce_uptodate(ce))
2198 return DT_UNKNOWN;
2199 if (S_ISGITLINK(ce->ce_mode))
2200 return DT_DIR;
2202 * Nobody actually cares about the
2203 * difference between DT_LNK and DT_REG
2205 return DT_REG;
2208 /* Try to look it up as a directory */
2209 pos = index_name_pos(istate, path, len);
2210 if (pos >= 0)
2211 return DT_UNKNOWN;
2212 pos = -pos-1;
2213 while (pos < istate->cache_nr) {
2214 ce = istate->cache[pos++];
2215 if (strncmp(ce->name, path, len))
2216 break;
2217 if (ce->name[len] > '/')
2218 break;
2219 if (ce->name[len] < '/')
2220 continue;
2221 if (!ce_uptodate(ce))
2222 break; /* continue? */
2223 return DT_DIR;
2225 return DT_UNKNOWN;
2228 static int resolve_dtype(int dtype, struct index_state *istate,
2229 const char *path, int len)
2231 struct stat st;
2233 if (dtype != DT_UNKNOWN)
2234 return dtype;
2235 dtype = get_index_dtype(istate, path, len);
2236 if (dtype != DT_UNKNOWN)
2237 return dtype;
2238 if (lstat(path, &st))
2239 return dtype;
2240 if (S_ISREG(st.st_mode))
2241 return DT_REG;
2242 if (S_ISDIR(st.st_mode))
2243 return DT_DIR;
2244 if (S_ISLNK(st.st_mode))
2245 return DT_LNK;
2246 return dtype;
2249 static enum path_treatment treat_path_fast(struct dir_struct *dir,
2250 struct cached_dir *cdir,
2251 struct index_state *istate,
2252 struct strbuf *path,
2253 int baselen,
2254 const struct pathspec *pathspec)
2257 * WARNING: From this function, you can return path_recurse or you
2258 * can call read_directory_recursive() (or neither), but
2259 * you CAN'T DO BOTH.
2261 strbuf_setlen(path, baselen);
2262 if (!cdir->ucd) {
2263 strbuf_addstr(path, cdir->file);
2264 return path_untracked;
2266 strbuf_addstr(path, cdir->ucd->name);
2267 /* treat_one_path() does this before it calls treat_directory() */
2268 strbuf_complete(path, '/');
2269 if (cdir->ucd->check_only)
2271 * check_only is set as a result of treat_directory() getting
2272 * to its bottom. Verify again the same set of directories
2273 * with check_only set.
2275 return read_directory_recursive(dir, istate, path->buf, path->len,
2276 cdir->ucd, 1, 0, pathspec);
2278 * We get path_recurse in the first run when
2279 * directory_exists_in_index() returns index_nonexistent. We
2280 * are sure that new changes in the index does not impact the
2281 * outcome. Return now.
2283 return path_recurse;
2286 static enum path_treatment treat_path(struct dir_struct *dir,
2287 struct untracked_cache_dir *untracked,
2288 struct cached_dir *cdir,
2289 struct index_state *istate,
2290 struct strbuf *path,
2291 int baselen,
2292 const struct pathspec *pathspec)
2294 int has_path_in_index, dtype, excluded;
2296 if (!cdir->d_name)
2297 return treat_path_fast(dir, cdir, istate, path,
2298 baselen, pathspec);
2299 if (is_dot_or_dotdot(cdir->d_name) || !fspathcmp(cdir->d_name, ".git"))
2300 return path_none;
2301 strbuf_setlen(path, baselen);
2302 strbuf_addstr(path, cdir->d_name);
2303 if (simplify_away(path->buf, path->len, pathspec))
2304 return path_none;
2306 dtype = resolve_dtype(cdir->d_type, istate, path->buf, path->len);
2308 /* Always exclude indexed files */
2309 has_path_in_index = !!index_file_exists(istate, path->buf, path->len,
2310 ignore_case);
2311 if (dtype != DT_DIR && has_path_in_index)
2312 return path_none;
2315 * When we are looking at a directory P in the working tree,
2316 * there are three cases:
2318 * (1) P exists in the index. Everything inside the directory P in
2319 * the working tree needs to go when P is checked out from the
2320 * index.
2322 * (2) P does not exist in the index, but there is P/Q in the index.
2323 * We know P will stay a directory when we check out the contents
2324 * of the index, but we do not know yet if there is a directory
2325 * P/Q in the working tree to be killed, so we need to recurse.
2327 * (3) P does not exist in the index, and there is no P/Q in the index
2328 * to require P to be a directory, either. Only in this case, we
2329 * know that everything inside P will not be killed without
2330 * recursing.
2332 if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
2333 (dtype == DT_DIR) &&
2334 !has_path_in_index &&
2335 (directory_exists_in_index(istate, path->buf, path->len) == index_nonexistent))
2336 return path_none;
2338 excluded = is_excluded(dir, istate, path->buf, &dtype);
2341 * Excluded? If we don't explicitly want to show
2342 * ignored files, ignore it
2344 if (excluded && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
2345 return path_excluded;
2347 switch (dtype) {
2348 default:
2349 return path_none;
2350 case DT_DIR:
2352 * WARNING: Do not ignore/amend the return value from
2353 * treat_directory(), and especially do not change it to return
2354 * path_recurse as that can cause exponential slowdown.
2355 * Instead, modify treat_directory() to return the right value.
2357 strbuf_addch(path, '/');
2358 return treat_directory(dir, istate, untracked,
2359 path->buf, path->len,
2360 baselen, excluded, pathspec);
2361 case DT_REG:
2362 case DT_LNK:
2363 if (pathspec &&
2364 !match_pathspec(istate, pathspec, path->buf, path->len,
2365 0 /* prefix */, NULL /* seen */,
2366 0 /* is_dir */))
2367 return path_none;
2368 if (excluded)
2369 return path_excluded;
2370 return path_untracked;
2374 static void add_untracked(struct untracked_cache_dir *dir, const char *name)
2376 if (!dir)
2377 return;
2378 ALLOC_GROW(dir->untracked, dir->untracked_nr + 1,
2379 dir->untracked_alloc);
2380 dir->untracked[dir->untracked_nr++] = xstrdup(name);
2383 static int valid_cached_dir(struct dir_struct *dir,
2384 struct untracked_cache_dir *untracked,
2385 struct index_state *istate,
2386 struct strbuf *path,
2387 int check_only)
2389 struct stat st;
2391 if (!untracked)
2392 return 0;
2395 * With fsmonitor, we can trust the untracked cache's valid field.
2397 refresh_fsmonitor(istate);
2398 if (!(dir->untracked->use_fsmonitor && untracked->valid)) {
2399 if (lstat(path->len ? path->buf : ".", &st)) {
2400 memset(&untracked->stat_data, 0, sizeof(untracked->stat_data));
2401 return 0;
2403 if (!untracked->valid ||
2404 match_stat_data_racy(istate, &untracked->stat_data, &st)) {
2405 fill_stat_data(&untracked->stat_data, &st);
2406 return 0;
2410 if (untracked->check_only != !!check_only)
2411 return 0;
2414 * prep_exclude will be called eventually on this directory,
2415 * but it's called much later in last_matching_pattern(). We
2416 * need it now to determine the validity of the cache for this
2417 * path. The next calls will be nearly no-op, the way
2418 * prep_exclude() is designed.
2420 if (path->len && path->buf[path->len - 1] != '/') {
2421 strbuf_addch(path, '/');
2422 prep_exclude(dir, istate, path->buf, path->len);
2423 strbuf_setlen(path, path->len - 1);
2424 } else
2425 prep_exclude(dir, istate, path->buf, path->len);
2427 /* hopefully prep_exclude() haven't invalidated this entry... */
2428 return untracked->valid;
2431 static int open_cached_dir(struct cached_dir *cdir,
2432 struct dir_struct *dir,
2433 struct untracked_cache_dir *untracked,
2434 struct index_state *istate,
2435 struct strbuf *path,
2436 int check_only)
2438 const char *c_path;
2440 memset(cdir, 0, sizeof(*cdir));
2441 cdir->untracked = untracked;
2442 if (valid_cached_dir(dir, untracked, istate, path, check_only))
2443 return 0;
2444 c_path = path->len ? path->buf : ".";
2445 cdir->fdir = opendir(c_path);
2446 if (!cdir->fdir)
2447 warning_errno(_("could not open directory '%s'"), c_path);
2448 if (dir->untracked) {
2449 invalidate_directory(dir->untracked, untracked);
2450 dir->untracked->dir_opened++;
2452 if (!cdir->fdir)
2453 return -1;
2454 return 0;
2457 static int read_cached_dir(struct cached_dir *cdir)
2459 struct dirent *de;
2461 if (cdir->fdir) {
2462 de = readdir_skip_dot_and_dotdot(cdir->fdir);
2463 if (!de) {
2464 cdir->d_name = NULL;
2465 cdir->d_type = DT_UNKNOWN;
2466 return -1;
2468 cdir->d_name = de->d_name;
2469 cdir->d_type = DTYPE(de);
2470 return 0;
2472 while (cdir->nr_dirs < cdir->untracked->dirs_nr) {
2473 struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];
2474 if (!d->recurse) {
2475 cdir->nr_dirs++;
2476 continue;
2478 cdir->ucd = d;
2479 cdir->nr_dirs++;
2480 return 0;
2482 cdir->ucd = NULL;
2483 if (cdir->nr_files < cdir->untracked->untracked_nr) {
2484 struct untracked_cache_dir *d = cdir->untracked;
2485 cdir->file = d->untracked[cdir->nr_files++];
2486 return 0;
2488 return -1;
2491 static void close_cached_dir(struct cached_dir *cdir)
2493 if (cdir->fdir)
2494 closedir(cdir->fdir);
2496 * We have gone through this directory and found no untracked
2497 * entries. Mark it valid.
2499 if (cdir->untracked) {
2500 cdir->untracked->valid = 1;
2501 cdir->untracked->recurse = 1;
2505 static void add_path_to_appropriate_result_list(struct dir_struct *dir,
2506 struct untracked_cache_dir *untracked,
2507 struct cached_dir *cdir,
2508 struct index_state *istate,
2509 struct strbuf *path,
2510 int baselen,
2511 const struct pathspec *pathspec,
2512 enum path_treatment state)
2514 /* add the path to the appropriate result list */
2515 switch (state) {
2516 case path_excluded:
2517 if (dir->flags & DIR_SHOW_IGNORED)
2518 dir_add_name(dir, istate, path->buf, path->len);
2519 else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
2520 ((dir->flags & DIR_COLLECT_IGNORED) &&
2521 exclude_matches_pathspec(path->buf, path->len,
2522 pathspec)))
2523 dir_add_ignored(dir, istate, path->buf, path->len);
2524 break;
2526 case path_untracked:
2527 if (dir->flags & DIR_SHOW_IGNORED)
2528 break;
2529 dir_add_name(dir, istate, path->buf, path->len);
2530 if (cdir->fdir)
2531 add_untracked(untracked, path->buf + baselen);
2532 break;
2534 default:
2535 break;
2540 * Read a directory tree. We currently ignore anything but
2541 * directories, regular files and symlinks. That's because git
2542 * doesn't handle them at all yet. Maybe that will change some
2543 * day.
2545 * Also, we ignore the name ".git" (even if it is not a directory).
2546 * That likely will not change.
2548 * If 'stop_at_first_file' is specified, 'path_excluded' is returned
2549 * to signal that a file was found. This is the least significant value that
2550 * indicates that a file was encountered that does not depend on the order of
2551 * whether an untracked or excluded path was encountered first.
2553 * Returns the most significant path_treatment value encountered in the scan.
2554 * If 'stop_at_first_file' is specified, `path_excluded` is the most
2555 * significant path_treatment value that will be returned.
2558 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
2559 struct index_state *istate, const char *base, int baselen,
2560 struct untracked_cache_dir *untracked, int check_only,
2561 int stop_at_first_file, const struct pathspec *pathspec)
2564 * WARNING: Do NOT recurse unless path_recurse is returned from
2565 * treat_path(). Recursing on any other return value
2566 * can result in exponential slowdown.
2568 struct cached_dir cdir;
2569 enum path_treatment state, subdir_state, dir_state = path_none;
2570 struct strbuf path = STRBUF_INIT;
2572 strbuf_add(&path, base, baselen);
2574 if (open_cached_dir(&cdir, dir, untracked, istate, &path, check_only))
2575 goto out;
2576 dir->internal.visited_directories++;
2578 if (untracked)
2579 untracked->check_only = !!check_only;
2581 while (!read_cached_dir(&cdir)) {
2582 /* check how the file or directory should be treated */
2583 state = treat_path(dir, untracked, &cdir, istate, &path,
2584 baselen, pathspec);
2585 dir->internal.visited_paths++;
2587 if (state > dir_state)
2588 dir_state = state;
2590 /* recurse into subdir if instructed by treat_path */
2591 if (state == path_recurse) {
2592 struct untracked_cache_dir *ud;
2593 ud = lookup_untracked(dir->untracked,
2594 untracked,
2595 path.buf + baselen,
2596 path.len - baselen);
2597 subdir_state =
2598 read_directory_recursive(dir, istate, path.buf,
2599 path.len, ud,
2600 check_only, stop_at_first_file, pathspec);
2601 if (subdir_state > dir_state)
2602 dir_state = subdir_state;
2604 if (pathspec &&
2605 !match_pathspec(istate, pathspec, path.buf, path.len,
2606 0 /* prefix */, NULL,
2607 0 /* do NOT special case dirs */))
2608 state = path_none;
2611 if (check_only) {
2612 if (stop_at_first_file) {
2614 * If stopping at first file, then
2615 * signal that a file was found by
2616 * returning `path_excluded`. This is
2617 * to return a consistent value
2618 * regardless of whether an ignored or
2619 * excluded file happened to be
2620 * encountered 1st.
2622 * In current usage, the
2623 * `stop_at_first_file` is passed when
2624 * an ancestor directory has matched
2625 * an exclude pattern, so any found
2626 * files will be excluded.
2628 if (dir_state >= path_excluded) {
2629 dir_state = path_excluded;
2630 break;
2634 /* abort early if maximum state has been reached */
2635 if (dir_state == path_untracked) {
2636 if (cdir.fdir)
2637 add_untracked(untracked, path.buf + baselen);
2638 break;
2640 /* skip the add_path_to_appropriate_result_list() */
2641 continue;
2644 add_path_to_appropriate_result_list(dir, untracked, &cdir,
2645 istate, &path, baselen,
2646 pathspec, state);
2648 close_cached_dir(&cdir);
2649 out:
2650 strbuf_release(&path);
2652 return dir_state;
2655 int cmp_dir_entry(const void *p1, const void *p2)
2657 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
2658 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
2660 return name_compare(e1->name, e1->len, e2->name, e2->len);
2663 /* check if *out lexically strictly contains *in */
2664 int check_dir_entry_contains(const struct dir_entry *out, const struct dir_entry *in)
2666 return (out->len < in->len) &&
2667 (out->name[out->len - 1] == '/') &&
2668 !memcmp(out->name, in->name, out->len);
2671 static int treat_leading_path(struct dir_struct *dir,
2672 struct index_state *istate,
2673 const char *path, int len,
2674 const struct pathspec *pathspec)
2676 struct strbuf sb = STRBUF_INIT;
2677 struct strbuf subdir = STRBUF_INIT;
2678 int prevlen, baselen;
2679 const char *cp;
2680 struct cached_dir cdir;
2681 enum path_treatment state = path_none;
2684 * For each directory component of path, we are going to check whether
2685 * that path is relevant given the pathspec. For example, if path is
2686 * foo/bar/baz/
2687 * then we will ask treat_path() whether we should go into foo, then
2688 * whether we should go into bar, then whether baz is relevant.
2689 * Checking each is important because e.g. if path is
2690 * .git/info/
2691 * then we need to check .git to know we shouldn't traverse it.
2692 * If the return from treat_path() is:
2693 * * path_none, for any path, we return false.
2694 * * path_recurse, for all path components, we return true
2695 * * <anything else> for some intermediate component, we make sure
2696 * to add that path to the relevant list but return false
2697 * signifying that we shouldn't recurse into it.
2700 while (len && path[len - 1] == '/')
2701 len--;
2702 if (!len)
2703 return 1;
2705 memset(&cdir, 0, sizeof(cdir));
2706 cdir.d_type = DT_DIR;
2707 baselen = 0;
2708 prevlen = 0;
2709 while (1) {
2710 prevlen = baselen + !!baselen;
2711 cp = path + prevlen;
2712 cp = memchr(cp, '/', path + len - cp);
2713 if (!cp)
2714 baselen = len;
2715 else
2716 baselen = cp - path;
2717 strbuf_reset(&sb);
2718 strbuf_add(&sb, path, baselen);
2719 if (!is_directory(sb.buf))
2720 break;
2721 strbuf_reset(&sb);
2722 strbuf_add(&sb, path, prevlen);
2723 strbuf_reset(&subdir);
2724 strbuf_add(&subdir, path+prevlen, baselen-prevlen);
2725 cdir.d_name = subdir.buf;
2726 state = treat_path(dir, NULL, &cdir, istate, &sb, prevlen, pathspec);
2728 if (state != path_recurse)
2729 break; /* do not recurse into it */
2730 if (len <= baselen)
2731 break; /* finished checking */
2733 add_path_to_appropriate_result_list(dir, NULL, &cdir, istate,
2734 &sb, baselen, pathspec,
2735 state);
2737 strbuf_release(&subdir);
2738 strbuf_release(&sb);
2739 return state == path_recurse;
2742 static const char *get_ident_string(void)
2744 static struct strbuf sb = STRBUF_INIT;
2745 struct utsname uts;
2747 if (sb.len)
2748 return sb.buf;
2749 if (uname(&uts) < 0)
2750 die_errno(_("failed to get kernel name and information"));
2751 strbuf_addf(&sb, "Location %s, system %s", get_git_work_tree(),
2752 uts.sysname);
2753 return sb.buf;
2756 static int ident_in_untracked(const struct untracked_cache *uc)
2759 * Previous git versions may have saved many NUL separated
2760 * strings in the "ident" field, but it is insane to manage
2761 * many locations, so just take care of the first one.
2764 return !strcmp(uc->ident.buf, get_ident_string());
2767 static void set_untracked_ident(struct untracked_cache *uc)
2769 strbuf_reset(&uc->ident);
2770 strbuf_addstr(&uc->ident, get_ident_string());
2773 * This strbuf used to contain a list of NUL separated
2774 * strings, so save NUL too for backward compatibility.
2776 strbuf_addch(&uc->ident, 0);
2779 static unsigned new_untracked_cache_flags(struct index_state *istate)
2781 struct repository *repo = istate->repo;
2782 char *val;
2785 * This logic is coordinated with the setting of these flags in
2786 * wt-status.c#wt_status_collect_untracked(), and the evaluation
2787 * of the config setting in commit.c#git_status_config()
2789 if (!repo_config_get_string(repo, "status.showuntrackedfiles", &val) &&
2790 !strcmp(val, "all"))
2791 return 0;
2794 * The default, if "all" is not set, is "normal" - leading us here.
2795 * If the value is "none" then it really doesn't matter.
2797 return DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;
2800 static void new_untracked_cache(struct index_state *istate, int flags)
2802 struct untracked_cache *uc = xcalloc(1, sizeof(*uc));
2803 strbuf_init(&uc->ident, 100);
2804 uc->exclude_per_dir = ".gitignore";
2805 uc->dir_flags = flags >= 0 ? flags : new_untracked_cache_flags(istate);
2806 set_untracked_ident(uc);
2807 istate->untracked = uc;
2808 istate->cache_changed |= UNTRACKED_CHANGED;
2811 void add_untracked_cache(struct index_state *istate)
2813 if (!istate->untracked) {
2814 new_untracked_cache(istate, -1);
2815 } else {
2816 if (!ident_in_untracked(istate->untracked)) {
2817 free_untracked_cache(istate->untracked);
2818 new_untracked_cache(istate, -1);
2823 void remove_untracked_cache(struct index_state *istate)
2825 if (istate->untracked) {
2826 free_untracked_cache(istate->untracked);
2827 istate->untracked = NULL;
2828 istate->cache_changed |= UNTRACKED_CHANGED;
2832 static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,
2833 int base_len,
2834 const struct pathspec *pathspec,
2835 struct index_state *istate)
2837 struct untracked_cache_dir *root;
2838 static int untracked_cache_disabled = -1;
2840 if (!dir->untracked)
2841 return NULL;
2842 if (untracked_cache_disabled < 0)
2843 untracked_cache_disabled = git_env_bool("GIT_DISABLE_UNTRACKED_CACHE", 0);
2844 if (untracked_cache_disabled)
2845 return NULL;
2848 * We only support $GIT_DIR/info/exclude and core.excludesfile
2849 * as the global ignore rule files. Any other additions
2850 * (e.g. from command line) invalidate the cache. This
2851 * condition also catches running setup_standard_excludes()
2852 * before setting dir->untracked!
2854 if (dir->internal.unmanaged_exclude_files)
2855 return NULL;
2858 * Optimize for the main use case only: whole-tree git
2859 * status. More work involved in treat_leading_path() if we
2860 * use cache on just a subset of the worktree. pathspec
2861 * support could make the matter even worse.
2863 if (base_len || (pathspec && pathspec->nr))
2864 return NULL;
2866 /* We don't support collecting ignore files */
2867 if (dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |
2868 DIR_COLLECT_IGNORED))
2869 return NULL;
2872 * If we use .gitignore in the cache and now you change it to
2873 * .gitexclude, everything will go wrong.
2875 if (dir->exclude_per_dir != dir->untracked->exclude_per_dir &&
2876 strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))
2877 return NULL;
2880 * EXC_CMDL is not considered in the cache. If people set it,
2881 * skip the cache.
2883 if (dir->internal.exclude_list_group[EXC_CMDL].nr)
2884 return NULL;
2886 if (!ident_in_untracked(dir->untracked)) {
2887 warning(_("untracked cache is disabled on this system or location"));
2888 return NULL;
2892 * If the untracked structure we received does not have the same flags
2893 * as requested in this run, we're going to need to either discard the
2894 * existing structure (and potentially later recreate), or bypass the
2895 * untracked cache mechanism for this run.
2897 if (dir->flags != dir->untracked->dir_flags) {
2899 * If the untracked structure we received does not have the same flags
2900 * as configured, then we need to reset / create a new "untracked"
2901 * structure to match the new config.
2903 * Keeping the saved and used untracked cache consistent with the
2904 * configuration provides an opportunity for frequent users of
2905 * "git status -uall" to leverage the untracked cache by aligning their
2906 * configuration - setting "status.showuntrackedfiles" to "all" or
2907 * "normal" as appropriate.
2909 * Previously using -uall (or setting "status.showuntrackedfiles" to
2910 * "all") was incompatible with untracked cache and *consistently*
2911 * caused surprisingly bad performance (with fscache and fsmonitor
2912 * enabled) on Windows.
2914 * IMPROVEMENT OPPORTUNITY: If we reworked the untracked cache storage
2915 * to not be as bound up with the desired output in a given run,
2916 * and instead iterated through and stored enough information to
2917 * correctly serve both "modes", then users could get peak performance
2918 * with or without '-uall' regardless of their
2919 * "status.showuntrackedfiles" config.
2921 if (dir->untracked->dir_flags != new_untracked_cache_flags(istate)) {
2922 free_untracked_cache(istate->untracked);
2923 new_untracked_cache(istate, dir->flags);
2924 dir->untracked = istate->untracked;
2926 else {
2928 * Current untracked cache data is consistent with config, but not
2929 * usable in this request/run; just bypass untracked cache.
2931 return NULL;
2935 if (!dir->untracked->root) {
2936 /* Untracked cache existed but is not initialized; fix that */
2937 FLEX_ALLOC_STR(dir->untracked->root, name, "");
2938 istate->cache_changed |= UNTRACKED_CHANGED;
2941 /* Validate $GIT_DIR/info/exclude and core.excludesfile */
2942 root = dir->untracked->root;
2943 if (!oideq(&dir->internal.ss_info_exclude.oid,
2944 &dir->untracked->ss_info_exclude.oid)) {
2945 invalidate_gitignore(dir->untracked, root);
2946 dir->untracked->ss_info_exclude = dir->internal.ss_info_exclude;
2948 if (!oideq(&dir->internal.ss_excludes_file.oid,
2949 &dir->untracked->ss_excludes_file.oid)) {
2950 invalidate_gitignore(dir->untracked, root);
2951 dir->untracked->ss_excludes_file = dir->internal.ss_excludes_file;
2954 /* Make sure this directory is not dropped out at saving phase */
2955 root->recurse = 1;
2956 return root;
2959 static void emit_traversal_statistics(struct dir_struct *dir,
2960 struct repository *repo,
2961 const char *path,
2962 int path_len)
2964 if (!trace2_is_enabled())
2965 return;
2967 if (!path_len) {
2968 trace2_data_string("read_directory", repo, "path", "");
2969 } else {
2970 struct strbuf tmp = STRBUF_INIT;
2971 strbuf_add(&tmp, path, path_len);
2972 trace2_data_string("read_directory", repo, "path", tmp.buf);
2973 strbuf_release(&tmp);
2976 trace2_data_intmax("read_directory", repo,
2977 "directories-visited", dir->internal.visited_directories);
2978 trace2_data_intmax("read_directory", repo,
2979 "paths-visited", dir->internal.visited_paths);
2981 if (!dir->untracked)
2982 return;
2983 trace2_data_intmax("read_directory", repo,
2984 "node-creation", dir->untracked->dir_created);
2985 trace2_data_intmax("read_directory", repo,
2986 "gitignore-invalidation",
2987 dir->untracked->gitignore_invalidated);
2988 trace2_data_intmax("read_directory", repo,
2989 "directory-invalidation",
2990 dir->untracked->dir_invalidated);
2991 trace2_data_intmax("read_directory", repo,
2992 "opendir", dir->untracked->dir_opened);
2995 int read_directory(struct dir_struct *dir, struct index_state *istate,
2996 const char *path, int len, const struct pathspec *pathspec)
2998 struct untracked_cache_dir *untracked;
3000 trace2_region_enter("dir", "read_directory", istate->repo);
3001 dir->internal.visited_paths = 0;
3002 dir->internal.visited_directories = 0;
3004 if (has_symlink_leading_path(path, len)) {
3005 trace2_region_leave("dir", "read_directory", istate->repo);
3006 return dir->nr;
3009 untracked = validate_untracked_cache(dir, len, pathspec, istate);
3010 if (!untracked)
3012 * make sure untracked cache code path is disabled,
3013 * e.g. prep_exclude()
3015 dir->untracked = NULL;
3016 if (!len || treat_leading_path(dir, istate, path, len, pathspec))
3017 read_directory_recursive(dir, istate, path, len, untracked, 0, 0, pathspec);
3018 QSORT(dir->entries, dir->nr, cmp_dir_entry);
3019 QSORT(dir->ignored, dir->ignored_nr, cmp_dir_entry);
3021 emit_traversal_statistics(dir, istate->repo, path, len);
3023 trace2_region_leave("dir", "read_directory", istate->repo);
3024 if (dir->untracked) {
3025 static int force_untracked_cache = -1;
3027 if (force_untracked_cache < 0)
3028 force_untracked_cache =
3029 git_env_bool("GIT_FORCE_UNTRACKED_CACHE", -1);
3030 if (force_untracked_cache < 0)
3031 force_untracked_cache = (istate->repo->settings.core_untracked_cache == UNTRACKED_CACHE_WRITE);
3032 if (force_untracked_cache &&
3033 dir->untracked == istate->untracked &&
3034 (dir->untracked->dir_opened ||
3035 dir->untracked->gitignore_invalidated ||
3036 dir->untracked->dir_invalidated))
3037 istate->cache_changed |= UNTRACKED_CHANGED;
3038 if (dir->untracked != istate->untracked) {
3039 FREE_AND_NULL(dir->untracked);
3043 return dir->nr;
3046 int file_exists(const char *f)
3048 struct stat sb;
3049 return lstat(f, &sb) == 0;
3052 int repo_file_exists(struct repository *repo, const char *path)
3054 if (repo != the_repository)
3055 BUG("do not know how to check file existence in arbitrary repo");
3057 return file_exists(path);
3060 static int cmp_icase(char a, char b)
3062 if (a == b)
3063 return 0;
3064 if (ignore_case)
3065 return toupper(a) - toupper(b);
3066 return a - b;
3070 * Given two normalized paths (a trailing slash is ok), if subdir is
3071 * outside dir, return -1. Otherwise return the offset in subdir that
3072 * can be used as relative path to dir.
3074 int dir_inside_of(const char *subdir, const char *dir)
3076 int offset = 0;
3078 assert(dir && subdir && *dir && *subdir);
3080 while (*dir && *subdir && !cmp_icase(*dir, *subdir)) {
3081 dir++;
3082 subdir++;
3083 offset++;
3086 /* hel[p]/me vs hel[l]/yeah */
3087 if (*dir && *subdir)
3088 return -1;
3090 if (!*subdir)
3091 return !*dir ? offset : -1; /* same dir */
3093 /* foo/[b]ar vs foo/[] */
3094 if (is_dir_sep(dir[-1]))
3095 return is_dir_sep(subdir[-1]) ? offset : -1;
3097 /* foo[/]bar vs foo[] */
3098 return is_dir_sep(*subdir) ? offset + 1 : -1;
3101 int is_inside_dir(const char *dir)
3103 char *cwd;
3104 int rc;
3106 if (!dir)
3107 return 0;
3109 cwd = xgetcwd();
3110 rc = (dir_inside_of(cwd, dir) >= 0);
3111 free(cwd);
3112 return rc;
3115 int is_empty_dir(const char *path)
3117 DIR *dir = opendir(path);
3118 struct dirent *e;
3119 int ret = 1;
3121 if (!dir)
3122 return 0;
3124 e = readdir_skip_dot_and_dotdot(dir);
3125 if (e)
3126 ret = 0;
3128 closedir(dir);
3129 return ret;
3132 char *git_url_basename(const char *repo, int is_bundle, int is_bare)
3134 const char *end = repo + strlen(repo), *start, *ptr;
3135 size_t len;
3136 char *dir;
3139 * Skip scheme.
3141 start = strstr(repo, "://");
3142 if (!start)
3143 start = repo;
3144 else
3145 start += 3;
3148 * Skip authentication data. The stripping does happen
3149 * greedily, such that we strip up to the last '@' inside
3150 * the host part.
3152 for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
3153 if (*ptr == '@')
3154 start = ptr + 1;
3158 * Strip trailing spaces, slashes and /.git
3160 while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
3161 end--;
3162 if (end - start > 5 && is_dir_sep(end[-5]) &&
3163 !strncmp(end - 4, ".git", 4)) {
3164 end -= 5;
3165 while (start < end && is_dir_sep(end[-1]))
3166 end--;
3170 * It should not be possible to overflow `ptrdiff_t` by passing in an
3171 * insanely long URL, but GCC does not know that and will complain
3172 * without this check.
3174 if (end - start < 0)
3175 die(_("No directory name could be guessed.\n"
3176 "Please specify a directory on the command line"));
3179 * Strip trailing port number if we've got only a
3180 * hostname (that is, there is no dir separator but a
3181 * colon). This check is required such that we do not
3182 * strip URI's like '/foo/bar:2222.git', which should
3183 * result in a dir '2222' being guessed due to backwards
3184 * compatibility.
3186 if (memchr(start, '/', end - start) == NULL
3187 && memchr(start, ':', end - start) != NULL) {
3188 ptr = end;
3189 while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
3190 ptr--;
3191 if (start < ptr && ptr[-1] == ':')
3192 end = ptr - 1;
3196 * Find last component. To remain backwards compatible we
3197 * also regard colons as path separators, such that
3198 * cloning a repository 'foo:bar.git' would result in a
3199 * directory 'bar' being guessed.
3201 ptr = end;
3202 while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
3203 ptr--;
3204 start = ptr;
3207 * Strip .{bundle,git}.
3209 len = end - start;
3210 strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
3212 if (!len || (len == 1 && *start == '/'))
3213 die(_("No directory name could be guessed.\n"
3214 "Please specify a directory on the command line"));
3216 if (is_bare)
3217 dir = xstrfmt("%.*s.git", (int)len, start);
3218 else
3219 dir = xstrndup(start, len);
3221 * Replace sequences of 'control' characters and whitespace
3222 * with one ascii space, remove leading and trailing spaces.
3224 if (*dir) {
3225 char *out = dir;
3226 int prev_space = 1 /* strip leading whitespace */;
3227 for (end = dir; *end; ++end) {
3228 char ch = *end;
3229 if ((unsigned char)ch < '\x20')
3230 ch = '\x20';
3231 if (isspace(ch)) {
3232 if (prev_space)
3233 continue;
3234 prev_space = 1;
3235 } else
3236 prev_space = 0;
3237 *out++ = ch;
3239 *out = '\0';
3240 if (out > dir && prev_space)
3241 out[-1] = '\0';
3243 return dir;
3246 void strip_dir_trailing_slashes(char *dir)
3248 char *end = dir + strlen(dir);
3250 while (dir < end - 1 && is_dir_sep(end[-1]))
3251 end--;
3252 *end = '\0';
3255 static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
3257 DIR *dir;
3258 struct dirent *e;
3259 int ret = 0, original_len = path->len, len, kept_down = 0;
3260 int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
3261 int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
3262 int purge_original_cwd = (flag & REMOVE_DIR_PURGE_ORIGINAL_CWD);
3263 struct object_id submodule_head;
3265 if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
3266 !resolve_gitlink_ref(path->buf, "HEAD", &submodule_head)) {
3267 /* Do not descend and nuke a nested git work tree. */
3268 if (kept_up)
3269 *kept_up = 1;
3270 return 0;
3273 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
3274 dir = opendir(path->buf);
3275 if (!dir) {
3276 if (errno == ENOENT)
3277 return keep_toplevel ? -1 : 0;
3278 else if (errno == EACCES && !keep_toplevel)
3280 * An empty dir could be removable even if it
3281 * is unreadable:
3283 return rmdir(path->buf);
3284 else
3285 return -1;
3287 strbuf_complete(path, '/');
3289 len = path->len;
3290 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
3291 struct stat st;
3293 strbuf_setlen(path, len);
3294 strbuf_addstr(path, e->d_name);
3295 if (lstat(path->buf, &st)) {
3296 if (errno == ENOENT)
3298 * file disappeared, which is what we
3299 * wanted anyway
3301 continue;
3302 /* fall through */
3303 } else if (S_ISDIR(st.st_mode)) {
3304 if (!remove_dir_recurse(path, flag, &kept_down))
3305 continue; /* happy */
3306 } else if (!only_empty &&
3307 (!unlink(path->buf) || errno == ENOENT)) {
3308 continue; /* happy, too */
3311 /* path too long, stat fails, or non-directory still exists */
3312 ret = -1;
3313 break;
3315 closedir(dir);
3317 strbuf_setlen(path, original_len);
3318 if (!ret && !keep_toplevel && !kept_down) {
3319 if (!purge_original_cwd &&
3320 startup_info->original_cwd &&
3321 !strcmp(startup_info->original_cwd, path->buf))
3322 ret = -1; /* Do not remove current working directory */
3323 else
3324 ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1;
3325 } else if (kept_up)
3327 * report the uplevel that it is not an error that we
3328 * did not rmdir() our directory.
3330 *kept_up = !ret;
3331 return ret;
3334 int remove_dir_recursively(struct strbuf *path, int flag)
3336 return remove_dir_recurse(path, flag, NULL);
3339 static GIT_PATH_FUNC(git_path_info_exclude, "info/exclude")
3341 void setup_standard_excludes(struct dir_struct *dir)
3343 dir->exclude_per_dir = ".gitignore";
3345 /* core.excludesfile defaulting to $XDG_CONFIG_HOME/git/ignore */
3346 if (!excludes_file)
3347 excludes_file = xdg_config_home("ignore");
3348 if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
3349 add_patterns_from_file_1(dir, excludes_file,
3350 dir->untracked ? &dir->internal.ss_excludes_file : NULL);
3352 /* per repository user preference */
3353 if (startup_info->have_repository) {
3354 const char *path = git_path_info_exclude();
3355 if (!access_or_warn(path, R_OK, 0))
3356 add_patterns_from_file_1(dir, path,
3357 dir->untracked ? &dir->internal.ss_info_exclude : NULL);
3361 char *get_sparse_checkout_filename(void)
3363 return git_pathdup("info/sparse-checkout");
3366 int get_sparse_checkout_patterns(struct pattern_list *pl)
3368 int res;
3369 char *sparse_filename = get_sparse_checkout_filename();
3371 pl->use_cone_patterns = core_sparse_checkout_cone;
3372 res = add_patterns_from_file_to_list(sparse_filename, "", 0, pl, NULL, 0);
3374 free(sparse_filename);
3375 return res;
3378 int remove_path(const char *name)
3380 char *slash;
3382 if (unlink(name) && !is_missing_file_error(errno))
3383 return -1;
3385 slash = strrchr(name, '/');
3386 if (slash) {
3387 char *dirs = xstrdup(name);
3388 slash = dirs + (slash - name);
3389 do {
3390 *slash = '\0';
3391 if (startup_info->original_cwd &&
3392 !strcmp(startup_info->original_cwd, dirs))
3393 break;
3394 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
3395 free(dirs);
3397 return 0;
3401 * Frees memory within dir which was allocated, and resets fields for further
3402 * use. Does not free dir itself.
3404 void dir_clear(struct dir_struct *dir)
3406 int i, j;
3407 struct exclude_list_group *group;
3408 struct pattern_list *pl;
3409 struct exclude_stack *stk;
3410 struct dir_struct new = DIR_INIT;
3412 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
3413 group = &dir->internal.exclude_list_group[i];
3414 for (j = 0; j < group->nr; j++) {
3415 pl = &group->pl[j];
3416 if (i == EXC_DIRS)
3417 free((char *)pl->src);
3418 clear_pattern_list(pl);
3420 free(group->pl);
3423 for (i = 0; i < dir->ignored_nr; i++)
3424 free(dir->ignored[i]);
3425 for (i = 0; i < dir->nr; i++)
3426 free(dir->entries[i]);
3427 free(dir->ignored);
3428 free(dir->entries);
3430 stk = dir->internal.exclude_stack;
3431 while (stk) {
3432 struct exclude_stack *prev = stk->prev;
3433 free(stk);
3434 stk = prev;
3436 strbuf_release(&dir->internal.basebuf);
3438 memcpy(dir, &new, sizeof(*dir));
3441 struct ondisk_untracked_cache {
3442 struct stat_data info_exclude_stat;
3443 struct stat_data excludes_file_stat;
3444 uint32_t dir_flags;
3447 #define ouc_offset(x) offsetof(struct ondisk_untracked_cache, x)
3449 struct write_data {
3450 int index; /* number of written untracked_cache_dir */
3451 struct ewah_bitmap *check_only; /* from untracked_cache_dir */
3452 struct ewah_bitmap *valid; /* from untracked_cache_dir */
3453 struct ewah_bitmap *sha1_valid; /* set if exclude_sha1 is not null */
3454 struct strbuf out;
3455 struct strbuf sb_stat;
3456 struct strbuf sb_sha1;
3459 static void stat_data_to_disk(struct stat_data *to, const struct stat_data *from)
3461 to->sd_ctime.sec = htonl(from->sd_ctime.sec);
3462 to->sd_ctime.nsec = htonl(from->sd_ctime.nsec);
3463 to->sd_mtime.sec = htonl(from->sd_mtime.sec);
3464 to->sd_mtime.nsec = htonl(from->sd_mtime.nsec);
3465 to->sd_dev = htonl(from->sd_dev);
3466 to->sd_ino = htonl(from->sd_ino);
3467 to->sd_uid = htonl(from->sd_uid);
3468 to->sd_gid = htonl(from->sd_gid);
3469 to->sd_size = htonl(from->sd_size);
3472 static void write_one_dir(struct untracked_cache_dir *untracked,
3473 struct write_data *wd)
3475 struct stat_data stat_data;
3476 struct strbuf *out = &wd->out;
3477 unsigned char intbuf[16];
3478 unsigned int intlen, value;
3479 int i = wd->index++;
3482 * untracked_nr should be reset whenever valid is clear, but
3483 * for safety..
3485 if (!untracked->valid) {
3486 untracked->untracked_nr = 0;
3487 untracked->check_only = 0;
3490 if (untracked->check_only)
3491 ewah_set(wd->check_only, i);
3492 if (untracked->valid) {
3493 ewah_set(wd->valid, i);
3494 stat_data_to_disk(&stat_data, &untracked->stat_data);
3495 strbuf_add(&wd->sb_stat, &stat_data, sizeof(stat_data));
3497 if (!is_null_oid(&untracked->exclude_oid)) {
3498 ewah_set(wd->sha1_valid, i);
3499 strbuf_add(&wd->sb_sha1, untracked->exclude_oid.hash,
3500 the_hash_algo->rawsz);
3503 intlen = encode_varint(untracked->untracked_nr, intbuf);
3504 strbuf_add(out, intbuf, intlen);
3506 /* skip non-recurse directories */
3507 for (i = 0, value = 0; i < untracked->dirs_nr; i++)
3508 if (untracked->dirs[i]->recurse)
3509 value++;
3510 intlen = encode_varint(value, intbuf);
3511 strbuf_add(out, intbuf, intlen);
3513 strbuf_add(out, untracked->name, strlen(untracked->name) + 1);
3515 for (i = 0; i < untracked->untracked_nr; i++)
3516 strbuf_add(out, untracked->untracked[i],
3517 strlen(untracked->untracked[i]) + 1);
3519 for (i = 0; i < untracked->dirs_nr; i++)
3520 if (untracked->dirs[i]->recurse)
3521 write_one_dir(untracked->dirs[i], wd);
3524 void write_untracked_extension(struct strbuf *out, struct untracked_cache *untracked)
3526 struct ondisk_untracked_cache *ouc;
3527 struct write_data wd;
3528 unsigned char varbuf[16];
3529 int varint_len;
3530 const unsigned hashsz = the_hash_algo->rawsz;
3532 CALLOC_ARRAY(ouc, 1);
3533 stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);
3534 stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);
3535 ouc->dir_flags = htonl(untracked->dir_flags);
3537 varint_len = encode_varint(untracked->ident.len, varbuf);
3538 strbuf_add(out, varbuf, varint_len);
3539 strbuf_addbuf(out, &untracked->ident);
3541 strbuf_add(out, ouc, sizeof(*ouc));
3542 strbuf_add(out, untracked->ss_info_exclude.oid.hash, hashsz);
3543 strbuf_add(out, untracked->ss_excludes_file.oid.hash, hashsz);
3544 strbuf_add(out, untracked->exclude_per_dir, strlen(untracked->exclude_per_dir) + 1);
3545 FREE_AND_NULL(ouc);
3547 if (!untracked->root) {
3548 varint_len = encode_varint(0, varbuf);
3549 strbuf_add(out, varbuf, varint_len);
3550 return;
3553 wd.index = 0;
3554 wd.check_only = ewah_new();
3555 wd.valid = ewah_new();
3556 wd.sha1_valid = ewah_new();
3557 strbuf_init(&wd.out, 1024);
3558 strbuf_init(&wd.sb_stat, 1024);
3559 strbuf_init(&wd.sb_sha1, 1024);
3560 write_one_dir(untracked->root, &wd);
3562 varint_len = encode_varint(wd.index, varbuf);
3563 strbuf_add(out, varbuf, varint_len);
3564 strbuf_addbuf(out, &wd.out);
3565 ewah_serialize_strbuf(wd.valid, out);
3566 ewah_serialize_strbuf(wd.check_only, out);
3567 ewah_serialize_strbuf(wd.sha1_valid, out);
3568 strbuf_addbuf(out, &wd.sb_stat);
3569 strbuf_addbuf(out, &wd.sb_sha1);
3570 strbuf_addch(out, '\0'); /* safe guard for string lists */
3572 ewah_free(wd.valid);
3573 ewah_free(wd.check_only);
3574 ewah_free(wd.sha1_valid);
3575 strbuf_release(&wd.out);
3576 strbuf_release(&wd.sb_stat);
3577 strbuf_release(&wd.sb_sha1);
3580 static void free_untracked(struct untracked_cache_dir *ucd)
3582 int i;
3583 if (!ucd)
3584 return;
3585 for (i = 0; i < ucd->dirs_nr; i++)
3586 free_untracked(ucd->dirs[i]);
3587 for (i = 0; i < ucd->untracked_nr; i++)
3588 free(ucd->untracked[i]);
3589 free(ucd->untracked);
3590 free(ucd->dirs);
3591 free(ucd);
3594 void free_untracked_cache(struct untracked_cache *uc)
3596 if (!uc)
3597 return;
3599 free(uc->exclude_per_dir_to_free);
3600 strbuf_release(&uc->ident);
3601 free_untracked(uc->root);
3602 free(uc);
3605 struct read_data {
3606 int index;
3607 struct untracked_cache_dir **ucd;
3608 struct ewah_bitmap *check_only;
3609 struct ewah_bitmap *valid;
3610 struct ewah_bitmap *sha1_valid;
3611 const unsigned char *data;
3612 const unsigned char *end;
3615 static void stat_data_from_disk(struct stat_data *to, const unsigned char *data)
3617 memcpy(to, data, sizeof(*to));
3618 to->sd_ctime.sec = ntohl(to->sd_ctime.sec);
3619 to->sd_ctime.nsec = ntohl(to->sd_ctime.nsec);
3620 to->sd_mtime.sec = ntohl(to->sd_mtime.sec);
3621 to->sd_mtime.nsec = ntohl(to->sd_mtime.nsec);
3622 to->sd_dev = ntohl(to->sd_dev);
3623 to->sd_ino = ntohl(to->sd_ino);
3624 to->sd_uid = ntohl(to->sd_uid);
3625 to->sd_gid = ntohl(to->sd_gid);
3626 to->sd_size = ntohl(to->sd_size);
3629 static int read_one_dir(struct untracked_cache_dir **untracked_,
3630 struct read_data *rd)
3632 struct untracked_cache_dir ud, *untracked;
3633 const unsigned char *data = rd->data, *end = rd->end;
3634 const unsigned char *eos;
3635 unsigned int value;
3636 int i;
3638 memset(&ud, 0, sizeof(ud));
3640 value = decode_varint(&data);
3641 if (data > end)
3642 return -1;
3643 ud.recurse = 1;
3644 ud.untracked_alloc = value;
3645 ud.untracked_nr = value;
3646 if (ud.untracked_nr)
3647 ALLOC_ARRAY(ud.untracked, ud.untracked_nr);
3649 ud.dirs_alloc = ud.dirs_nr = decode_varint(&data);
3650 if (data > end)
3651 return -1;
3652 ALLOC_ARRAY(ud.dirs, ud.dirs_nr);
3654 eos = memchr(data, '\0', end - data);
3655 if (!eos || eos == end)
3656 return -1;
3658 *untracked_ = untracked = xmalloc(st_add3(sizeof(*untracked), eos - data, 1));
3659 memcpy(untracked, &ud, sizeof(ud));
3660 memcpy(untracked->name, data, eos - data + 1);
3661 data = eos + 1;
3663 for (i = 0; i < untracked->untracked_nr; i++) {
3664 eos = memchr(data, '\0', end - data);
3665 if (!eos || eos == end)
3666 return -1;
3667 untracked->untracked[i] = xmemdupz(data, eos - data);
3668 data = eos + 1;
3671 rd->ucd[rd->index++] = untracked;
3672 rd->data = data;
3674 for (i = 0; i < untracked->dirs_nr; i++) {
3675 if (read_one_dir(untracked->dirs + i, rd) < 0)
3676 return -1;
3678 return 0;
3681 static void set_check_only(size_t pos, void *cb)
3683 struct read_data *rd = cb;
3684 struct untracked_cache_dir *ud = rd->ucd[pos];
3685 ud->check_only = 1;
3688 static void read_stat(size_t pos, void *cb)
3690 struct read_data *rd = cb;
3691 struct untracked_cache_dir *ud = rd->ucd[pos];
3692 if (rd->data + sizeof(struct stat_data) > rd->end) {
3693 rd->data = rd->end + 1;
3694 return;
3696 stat_data_from_disk(&ud->stat_data, rd->data);
3697 rd->data += sizeof(struct stat_data);
3698 ud->valid = 1;
3701 static void read_oid(size_t pos, void *cb)
3703 struct read_data *rd = cb;
3704 struct untracked_cache_dir *ud = rd->ucd[pos];
3705 if (rd->data + the_hash_algo->rawsz > rd->end) {
3706 rd->data = rd->end + 1;
3707 return;
3709 oidread(&ud->exclude_oid, rd->data);
3710 rd->data += the_hash_algo->rawsz;
3713 static void load_oid_stat(struct oid_stat *oid_stat, const unsigned char *data,
3714 const unsigned char *sha1)
3716 stat_data_from_disk(&oid_stat->stat, data);
3717 oidread(&oid_stat->oid, sha1);
3718 oid_stat->valid = 1;
3721 struct untracked_cache *read_untracked_extension(const void *data, unsigned long sz)
3723 struct untracked_cache *uc;
3724 struct read_data rd;
3725 const unsigned char *next = data, *end = (const unsigned char *)data + sz;
3726 const char *ident;
3727 int ident_len;
3728 ssize_t len;
3729 const char *exclude_per_dir;
3730 const unsigned hashsz = the_hash_algo->rawsz;
3731 const unsigned offset = sizeof(struct ondisk_untracked_cache);
3732 const unsigned exclude_per_dir_offset = offset + 2 * hashsz;
3734 if (sz <= 1 || end[-1] != '\0')
3735 return NULL;
3736 end--;
3738 ident_len = decode_varint(&next);
3739 if (next + ident_len > end)
3740 return NULL;
3741 ident = (const char *)next;
3742 next += ident_len;
3744 if (next + exclude_per_dir_offset + 1 > end)
3745 return NULL;
3747 CALLOC_ARRAY(uc, 1);
3748 strbuf_init(&uc->ident, ident_len);
3749 strbuf_add(&uc->ident, ident, ident_len);
3750 load_oid_stat(&uc->ss_info_exclude,
3751 next + ouc_offset(info_exclude_stat),
3752 next + offset);
3753 load_oid_stat(&uc->ss_excludes_file,
3754 next + ouc_offset(excludes_file_stat),
3755 next + offset + hashsz);
3756 uc->dir_flags = get_be32(next + ouc_offset(dir_flags));
3757 exclude_per_dir = (const char *)next + exclude_per_dir_offset;
3758 uc->exclude_per_dir = uc->exclude_per_dir_to_free = xstrdup(exclude_per_dir);
3759 /* NUL after exclude_per_dir is covered by sizeof(*ouc) */
3760 next += exclude_per_dir_offset + strlen(exclude_per_dir) + 1;
3761 if (next >= end)
3762 goto done2;
3764 len = decode_varint(&next);
3765 if (next > end || len == 0)
3766 goto done2;
3768 rd.valid = ewah_new();
3769 rd.check_only = ewah_new();
3770 rd.sha1_valid = ewah_new();
3771 rd.data = next;
3772 rd.end = end;
3773 rd.index = 0;
3774 ALLOC_ARRAY(rd.ucd, len);
3776 if (read_one_dir(&uc->root, &rd) || rd.index != len)
3777 goto done;
3779 next = rd.data;
3780 len = ewah_read_mmap(rd.valid, next, end - next);
3781 if (len < 0)
3782 goto done;
3784 next += len;
3785 len = ewah_read_mmap(rd.check_only, next, end - next);
3786 if (len < 0)
3787 goto done;
3789 next += len;
3790 len = ewah_read_mmap(rd.sha1_valid, next, end - next);
3791 if (len < 0)
3792 goto done;
3794 ewah_each_bit(rd.check_only, set_check_only, &rd);
3795 rd.data = next + len;
3796 ewah_each_bit(rd.valid, read_stat, &rd);
3797 ewah_each_bit(rd.sha1_valid, read_oid, &rd);
3798 next = rd.data;
3800 done:
3801 free(rd.ucd);
3802 ewah_free(rd.valid);
3803 ewah_free(rd.check_only);
3804 ewah_free(rd.sha1_valid);
3805 done2:
3806 if (next != end) {
3807 free_untracked_cache(uc);
3808 uc = NULL;
3810 return uc;
3813 static void invalidate_one_directory(struct untracked_cache *uc,
3814 struct untracked_cache_dir *ucd)
3816 uc->dir_invalidated++;
3817 ucd->valid = 0;
3818 ucd->untracked_nr = 0;
3822 * Normally when an entry is added or removed from a directory,
3823 * invalidating that directory is enough. No need to touch its
3824 * ancestors. When a directory is shown as "foo/bar/" in git-status
3825 * however, deleting or adding an entry may have cascading effect.
3827 * Say the "foo/bar/file" has become untracked, we need to tell the
3828 * untracked_cache_dir of "foo" that "bar/" is not an untracked
3829 * directory any more (because "bar" is managed by foo as an untracked
3830 * "file").
3832 * Similarly, if "foo/bar/file" moves from untracked to tracked and it
3833 * was the last untracked entry in the entire "foo", we should show
3834 * "foo/" instead. Which means we have to invalidate past "bar" up to
3835 * "foo".
3837 * This function traverses all directories from root to leaf. If there
3838 * is a chance of one of the above cases happening, we invalidate back
3839 * to root. Otherwise we just invalidate the leaf. There may be a more
3840 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to
3841 * detect these cases and avoid unnecessary invalidation, for example,
3842 * checking for the untracked entry named "bar/" in "foo", but for now
3843 * stick to something safe and simple.
3845 static int invalidate_one_component(struct untracked_cache *uc,
3846 struct untracked_cache_dir *dir,
3847 const char *path, int len)
3849 const char *rest = strchr(path, '/');
3851 if (rest) {
3852 int component_len = rest - path;
3853 struct untracked_cache_dir *d =
3854 lookup_untracked(uc, dir, path, component_len);
3855 int ret =
3856 invalidate_one_component(uc, d, rest + 1,
3857 len - (component_len + 1));
3858 if (ret)
3859 invalidate_one_directory(uc, dir);
3860 return ret;
3863 invalidate_one_directory(uc, dir);
3864 return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;
3867 void untracked_cache_invalidate_path(struct index_state *istate,
3868 const char *path, int safe_path)
3870 if (!istate->untracked || !istate->untracked->root)
3871 return;
3872 if (!safe_path && !verify_path(path, 0))
3873 return;
3874 invalidate_one_component(istate->untracked, istate->untracked->root,
3875 path, strlen(path));
3878 void untracked_cache_remove_from_index(struct index_state *istate,
3879 const char *path)
3881 untracked_cache_invalidate_path(istate, path, 1);
3884 void untracked_cache_add_to_index(struct index_state *istate,
3885 const char *path)
3887 untracked_cache_invalidate_path(istate, path, 1);
3890 static void connect_wt_gitdir_in_nested(const char *sub_worktree,
3891 const char *sub_gitdir)
3893 int i;
3894 struct repository subrepo;
3895 struct strbuf sub_wt = STRBUF_INIT;
3896 struct strbuf sub_gd = STRBUF_INIT;
3898 const struct submodule *sub;
3900 /* If the submodule has no working tree, we can ignore it. */
3901 if (repo_init(&subrepo, sub_gitdir, sub_worktree))
3902 return;
3904 if (repo_read_index(&subrepo) < 0)
3905 die(_("index file corrupt in repo %s"), subrepo.gitdir);
3907 /* TODO: audit for interaction with sparse-index. */
3908 ensure_full_index(subrepo.index);
3909 for (i = 0; i < subrepo.index->cache_nr; i++) {
3910 const struct cache_entry *ce = subrepo.index->cache[i];
3912 if (!S_ISGITLINK(ce->ce_mode))
3913 continue;
3915 while (i + 1 < subrepo.index->cache_nr &&
3916 !strcmp(ce->name, subrepo.index->cache[i + 1]->name))
3918 * Skip entries with the same name in different stages
3919 * to make sure an entry is returned only once.
3921 i++;
3923 sub = submodule_from_path(&subrepo, null_oid(), ce->name);
3924 if (!sub || !is_submodule_active(&subrepo, ce->name))
3925 /* .gitmodules broken or inactive sub */
3926 continue;
3928 strbuf_reset(&sub_wt);
3929 strbuf_reset(&sub_gd);
3930 strbuf_addf(&sub_wt, "%s/%s", sub_worktree, sub->path);
3931 submodule_name_to_gitdir(&sub_gd, &subrepo, sub->name);
3933 connect_work_tree_and_git_dir(sub_wt.buf, sub_gd.buf, 1);
3935 strbuf_release(&sub_wt);
3936 strbuf_release(&sub_gd);
3937 repo_clear(&subrepo);
3940 void connect_work_tree_and_git_dir(const char *work_tree_,
3941 const char *git_dir_,
3942 int recurse_into_nested)
3944 struct strbuf gitfile_sb = STRBUF_INIT;
3945 struct strbuf cfg_sb = STRBUF_INIT;
3946 struct strbuf rel_path = STRBUF_INIT;
3947 char *git_dir, *work_tree;
3949 /* Prepare .git file */
3950 strbuf_addf(&gitfile_sb, "%s/.git", work_tree_);
3951 if (safe_create_leading_directories_const(gitfile_sb.buf))
3952 die(_("could not create directories for %s"), gitfile_sb.buf);
3954 /* Prepare config file */
3955 strbuf_addf(&cfg_sb, "%s/config", git_dir_);
3956 if (safe_create_leading_directories_const(cfg_sb.buf))
3957 die(_("could not create directories for %s"), cfg_sb.buf);
3959 git_dir = real_pathdup(git_dir_, 1);
3960 work_tree = real_pathdup(work_tree_, 1);
3962 /* Write .git file */
3963 write_file(gitfile_sb.buf, "gitdir: %s",
3964 relative_path(git_dir, work_tree, &rel_path));
3965 /* Update core.worktree setting */
3966 git_config_set_in_file(cfg_sb.buf, "core.worktree",
3967 relative_path(work_tree, git_dir, &rel_path));
3969 strbuf_release(&gitfile_sb);
3970 strbuf_release(&cfg_sb);
3971 strbuf_release(&rel_path);
3973 if (recurse_into_nested)
3974 connect_wt_gitdir_in_nested(work_tree, git_dir);
3976 free(work_tree);
3977 free(git_dir);
3981 * Migrate the git directory of the given path from old_git_dir to new_git_dir.
3983 void relocate_gitdir(const char *path, const char *old_git_dir, const char *new_git_dir)
3985 if (rename(old_git_dir, new_git_dir) < 0)
3986 die_errno(_("could not migrate git directory from '%s' to '%s'"),
3987 old_git_dir, new_git_dir);
3989 connect_work_tree_and_git_dir(path, new_git_dir, 0);
3992 int path_match_flags(const char *const str, const enum path_match_flags flags)
3994 const char *p = str;
3996 if (flags & PATH_MATCH_NATIVE &&
3997 flags & PATH_MATCH_XPLATFORM)
3998 BUG("path_match_flags() must get one match kind, not multiple!");
3999 else if (!(flags & PATH_MATCH_KINDS_MASK))
4000 BUG("path_match_flags() must get at least one match kind!");
4002 if (flags & PATH_MATCH_STARTS_WITH_DOT_SLASH &&
4003 flags & PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH)
4004 BUG("path_match_flags() must get one platform kind, not multiple!");
4005 else if (!(flags & PATH_MATCH_PLATFORM_MASK))
4006 BUG("path_match_flags() must get at least one platform kind!");
4008 if (*p++ != '.')
4009 return 0;
4010 if (flags & PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH &&
4011 *p++ != '.')
4012 return 0;
4014 if (flags & PATH_MATCH_NATIVE)
4015 return is_dir_sep(*p);
4016 else if (flags & PATH_MATCH_XPLATFORM)
4017 return is_xplatform_dir_sep(*p);
4018 BUG("unreachable");