treewide: be explicit about dependence on advice.h
[alt-git.git] / dir.c
blob10f6c38b93041cd6ba88bfa2495d31fb8bc71a8e
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 "environment.h"
14 #include "gettext.h"
15 #include "object-store.h"
16 #include "attr.h"
17 #include "refs.h"
18 #include "wildmatch.h"
19 #include "pathspec.h"
20 #include "utf8.h"
21 #include "varint.h"
22 #include "ewah/ewok.h"
23 #include "fsmonitor.h"
24 #include "setup.h"
25 #include "submodule-config.h"
26 #include "trace2.h"
27 #include "wrapper.h"
30 * Tells read_directory_recursive how a file or directory should be treated.
31 * Values are ordered by significance, e.g. if a directory contains both
32 * excluded and untracked files, it is listed as untracked because
33 * path_untracked > path_excluded.
35 enum path_treatment {
36 path_none = 0,
37 path_recurse,
38 path_excluded,
39 path_untracked
43 * Support data structure for our opendir/readdir/closedir wrappers
45 struct cached_dir {
46 DIR *fdir;
47 struct untracked_cache_dir *untracked;
48 int nr_files;
49 int nr_dirs;
51 const char *d_name;
52 int d_type;
53 const char *file;
54 struct untracked_cache_dir *ucd;
57 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
58 struct index_state *istate, const char *path, int len,
59 struct untracked_cache_dir *untracked,
60 int check_only, int stop_at_first_file, const struct pathspec *pathspec);
61 static int resolve_dtype(int dtype, struct index_state *istate,
62 const char *path, int len);
63 struct dirent *readdir_skip_dot_and_dotdot(DIR *dirp)
65 struct dirent *e;
67 while ((e = readdir(dirp)) != NULL) {
68 if (!is_dot_or_dotdot(e->d_name))
69 break;
71 return e;
74 int count_slashes(const char *s)
76 int cnt = 0;
77 while (*s)
78 if (*s++ == '/')
79 cnt++;
80 return cnt;
83 int fspathcmp(const char *a, const char *b)
85 return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
88 int fspatheq(const char *a, const char *b)
90 return !fspathcmp(a, b);
93 int fspathncmp(const char *a, const char *b, size_t count)
95 return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
98 unsigned int fspathhash(const char *str)
100 return ignore_case ? strihash(str) : strhash(str);
103 int git_fnmatch(const struct pathspec_item *item,
104 const char *pattern, const char *string,
105 int prefix)
107 if (prefix > 0) {
108 if (ps_strncmp(item, pattern, string, prefix))
109 return WM_NOMATCH;
110 pattern += prefix;
111 string += prefix;
113 if (item->flags & PATHSPEC_ONESTAR) {
114 int pattern_len = strlen(++pattern);
115 int string_len = strlen(string);
116 return string_len < pattern_len ||
117 ps_strcmp(item, pattern,
118 string + string_len - pattern_len);
120 if (item->magic & PATHSPEC_GLOB)
121 return wildmatch(pattern, string,
122 WM_PATHNAME |
123 (item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0));
124 else
125 /* wildmatch has not learned no FNM_PATHNAME mode yet */
126 return wildmatch(pattern, string,
127 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0);
130 static int fnmatch_icase_mem(const char *pattern, int patternlen,
131 const char *string, int stringlen,
132 int flags)
134 int match_status;
135 struct strbuf pat_buf = STRBUF_INIT;
136 struct strbuf str_buf = STRBUF_INIT;
137 const char *use_pat = pattern;
138 const char *use_str = string;
140 if (pattern[patternlen]) {
141 strbuf_add(&pat_buf, pattern, patternlen);
142 use_pat = pat_buf.buf;
144 if (string[stringlen]) {
145 strbuf_add(&str_buf, string, stringlen);
146 use_str = str_buf.buf;
149 if (ignore_case)
150 flags |= WM_CASEFOLD;
151 match_status = wildmatch(use_pat, use_str, flags);
153 strbuf_release(&pat_buf);
154 strbuf_release(&str_buf);
156 return match_status;
159 static size_t common_prefix_len(const struct pathspec *pathspec)
161 int n;
162 size_t max = 0;
165 * ":(icase)path" is treated as a pathspec full of
166 * wildcard. In other words, only prefix is considered common
167 * prefix. If the pathspec is abc/foo abc/bar, running in
168 * subdir xyz, the common prefix is still xyz, not xyz/abc as
169 * in non-:(icase).
171 GUARD_PATHSPEC(pathspec,
172 PATHSPEC_FROMTOP |
173 PATHSPEC_MAXDEPTH |
174 PATHSPEC_LITERAL |
175 PATHSPEC_GLOB |
176 PATHSPEC_ICASE |
177 PATHSPEC_EXCLUDE |
178 PATHSPEC_ATTR);
180 for (n = 0; n < pathspec->nr; n++) {
181 size_t i = 0, len = 0, item_len;
182 if (pathspec->items[n].magic & PATHSPEC_EXCLUDE)
183 continue;
184 if (pathspec->items[n].magic & PATHSPEC_ICASE)
185 item_len = pathspec->items[n].prefix;
186 else
187 item_len = pathspec->items[n].nowildcard_len;
188 while (i < item_len && (n == 0 || i < max)) {
189 char c = pathspec->items[n].match[i];
190 if (c != pathspec->items[0].match[i])
191 break;
192 if (c == '/')
193 len = i + 1;
194 i++;
196 if (n == 0 || len < max) {
197 max = len;
198 if (!max)
199 break;
202 return max;
206 * Returns a copy of the longest leading path common among all
207 * pathspecs.
209 char *common_prefix(const struct pathspec *pathspec)
211 unsigned long len = common_prefix_len(pathspec);
213 return len ? xmemdupz(pathspec->items[0].match, len) : NULL;
216 int fill_directory(struct dir_struct *dir,
217 struct index_state *istate,
218 const struct pathspec *pathspec)
220 const char *prefix;
221 size_t prefix_len;
223 unsigned exclusive_flags = DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO;
224 if ((dir->flags & exclusive_flags) == exclusive_flags)
225 BUG("DIR_SHOW_IGNORED and DIR_SHOW_IGNORED_TOO are exclusive");
228 * Calculate common prefix for the pathspec, and
229 * use that to optimize the directory walk
231 prefix_len = common_prefix_len(pathspec);
232 prefix = prefix_len ? pathspec->items[0].match : "";
234 /* Read the directory and prune it */
235 read_directory(dir, istate, prefix, prefix_len, pathspec);
237 return prefix_len;
240 int within_depth(const char *name, int namelen,
241 int depth, int max_depth)
243 const char *cp = name, *cpe = name + namelen;
245 while (cp < cpe) {
246 if (*cp++ != '/')
247 continue;
248 depth++;
249 if (depth > max_depth)
250 return 0;
252 return 1;
256 * Read the contents of the blob with the given OID into a buffer.
257 * Append a trailing LF to the end if the last line doesn't have one.
259 * Returns:
260 * -1 when the OID is invalid or unknown or does not refer to a blob.
261 * 0 when the blob is empty.
262 * 1 along with { data, size } of the (possibly augmented) buffer
263 * when successful.
265 * Optionally updates the given oid_stat with the given OID (when valid).
267 static int do_read_blob(const struct object_id *oid, struct oid_stat *oid_stat,
268 size_t *size_out, char **data_out)
270 enum object_type type;
271 unsigned long sz;
272 char *data;
274 *size_out = 0;
275 *data_out = NULL;
277 data = repo_read_object_file(the_repository, oid, &type, &sz);
278 if (!data || type != OBJ_BLOB) {
279 free(data);
280 return -1;
283 if (oid_stat) {
284 memset(&oid_stat->stat, 0, sizeof(oid_stat->stat));
285 oidcpy(&oid_stat->oid, oid);
288 if (sz == 0) {
289 free(data);
290 return 0;
293 if (data[sz - 1] != '\n') {
294 data = xrealloc(data, st_add(sz, 1));
295 data[sz++] = '\n';
298 *size_out = xsize_t(sz);
299 *data_out = data;
301 return 1;
304 #define DO_MATCH_EXCLUDE (1<<0)
305 #define DO_MATCH_DIRECTORY (1<<1)
306 #define DO_MATCH_LEADING_PATHSPEC (1<<2)
309 * Does the given pathspec match the given name? A match is found if
311 * (1) the pathspec string is leading directory of 'name' ("RECURSIVELY"), or
312 * (2) the pathspec string has a leading part matching 'name' ("LEADING"), or
313 * (3) the pathspec string is a wildcard and matches 'name' ("WILDCARD"), or
314 * (4) the pathspec string is exactly the same as 'name' ("EXACT").
316 * Return value tells which case it was (1-4), or 0 when there is no match.
318 * It may be instructive to look at a small table of concrete examples
319 * to understand the differences between 1, 2, and 4:
321 * Pathspecs
322 * | a/b | a/b/ | a/b/c
323 * ------+-----------+-----------+------------
324 * a/b | EXACT | EXACT[1] | LEADING[2]
325 * Names a/b/ | RECURSIVE | EXACT | LEADING[2]
326 * a/b/c | RECURSIVE | RECURSIVE | EXACT
328 * [1] Only if DO_MATCH_DIRECTORY is passed; otherwise, this is NOT a match.
329 * [2] Only if DO_MATCH_LEADING_PATHSPEC is passed; otherwise, not a match.
331 static int match_pathspec_item(struct index_state *istate,
332 const struct pathspec_item *item, int prefix,
333 const char *name, int namelen, unsigned flags)
335 /* name/namelen has prefix cut off by caller */
336 const char *match = item->match + prefix;
337 int matchlen = item->len - prefix;
340 * The normal call pattern is:
341 * 1. prefix = common_prefix_len(ps);
342 * 2. prune something, or fill_directory
343 * 3. match_pathspec()
345 * 'prefix' at #1 may be shorter than the command's prefix and
346 * it's ok for #2 to match extra files. Those extras will be
347 * trimmed at #3.
349 * Suppose the pathspec is 'foo' and '../bar' running from
350 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
351 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
352 * user does not want XYZ/foo, only the "foo" part should be
353 * case-insensitive. We need to filter out XYZ/foo here. In
354 * other words, we do not trust the caller on comparing the
355 * prefix part when :(icase) is involved. We do exact
356 * comparison ourselves.
358 * Normally the caller (common_prefix_len() in fact) does
359 * _exact_ matching on name[-prefix+1..-1] and we do not need
360 * to check that part. Be defensive and check it anyway, in
361 * case common_prefix_len is changed, or a new caller is
362 * introduced that does not use common_prefix_len.
364 * If the penalty turns out too high when prefix is really
365 * long, maybe change it to
366 * strncmp(match, name, item->prefix - prefix)
368 if (item->prefix && (item->magic & PATHSPEC_ICASE) &&
369 strncmp(item->match, name - prefix, item->prefix))
370 return 0;
372 if (item->attr_match_nr &&
373 !match_pathspec_attrs(istate, name, namelen, item))
374 return 0;
376 /* If the match was just the prefix, we matched */
377 if (!*match)
378 return MATCHED_RECURSIVELY;
380 if (matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) {
381 if (matchlen == namelen)
382 return MATCHED_EXACTLY;
384 if (match[matchlen-1] == '/' || name[matchlen] == '/')
385 return MATCHED_RECURSIVELY;
386 } else if ((flags & DO_MATCH_DIRECTORY) &&
387 match[matchlen - 1] == '/' &&
388 namelen == matchlen - 1 &&
389 !ps_strncmp(item, match, name, namelen))
390 return MATCHED_EXACTLY;
392 if (item->nowildcard_len < item->len &&
393 !git_fnmatch(item, match, name,
394 item->nowildcard_len - prefix))
395 return MATCHED_FNMATCH;
397 /* Perform checks to see if "name" is a leading string of the pathspec */
398 if ( (flags & DO_MATCH_LEADING_PATHSPEC) &&
399 !(flags & DO_MATCH_EXCLUDE)) {
400 /* name is a literal prefix of the pathspec */
401 int offset = name[namelen-1] == '/' ? 1 : 0;
402 if ((namelen < matchlen) &&
403 (match[namelen-offset] == '/') &&
404 !ps_strncmp(item, match, name, namelen))
405 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
407 /* name doesn't match up to the first wild character */
408 if (item->nowildcard_len < item->len &&
409 ps_strncmp(item, match, name,
410 item->nowildcard_len - prefix))
411 return 0;
414 * name has no wildcard, and it didn't match as a leading
415 * pathspec so return.
417 if (item->nowildcard_len == item->len)
418 return 0;
421 * Here is where we would perform a wildmatch to check if
422 * "name" can be matched as a directory (or a prefix) against
423 * the pathspec. Since wildmatch doesn't have this capability
424 * at the present we have to punt and say that it is a match,
425 * potentially returning a false positive
426 * The submodules themselves will be able to perform more
427 * accurate matching to determine if the pathspec matches.
429 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
432 return 0;
436 * do_match_pathspec() is meant to ONLY be called by
437 * match_pathspec_with_flags(); calling it directly risks pathspecs
438 * like ':!unwanted_path' being ignored.
440 * Given a name and a list of pathspecs, returns the nature of the
441 * closest (i.e. most specific) match of the name to any of the
442 * pathspecs.
444 * The caller typically calls this multiple times with the same
445 * pathspec and seen[] array but with different name/namelen
446 * (e.g. entries from the index) and is interested in seeing if and
447 * how each pathspec matches all the names it calls this function
448 * with. A mark is left in the seen[] array for each pathspec element
449 * indicating the closest type of match that element achieved, so if
450 * seen[n] remains zero after multiple invocations, that means the nth
451 * pathspec did not match any names, which could indicate that the
452 * user mistyped the nth pathspec.
454 static int do_match_pathspec(struct index_state *istate,
455 const struct pathspec *ps,
456 const char *name, int namelen,
457 int prefix, char *seen,
458 unsigned flags)
460 int i, retval = 0, exclude = flags & DO_MATCH_EXCLUDE;
462 GUARD_PATHSPEC(ps,
463 PATHSPEC_FROMTOP |
464 PATHSPEC_MAXDEPTH |
465 PATHSPEC_LITERAL |
466 PATHSPEC_GLOB |
467 PATHSPEC_ICASE |
468 PATHSPEC_EXCLUDE |
469 PATHSPEC_ATTR);
471 if (!ps->nr) {
472 if (!ps->recursive ||
473 !(ps->magic & PATHSPEC_MAXDEPTH) ||
474 ps->max_depth == -1)
475 return MATCHED_RECURSIVELY;
477 if (within_depth(name, namelen, 0, ps->max_depth))
478 return MATCHED_EXACTLY;
479 else
480 return 0;
483 name += prefix;
484 namelen -= prefix;
486 for (i = ps->nr - 1; i >= 0; i--) {
487 int how;
489 if ((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) ||
490 ( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE)))
491 continue;
493 if (seen && seen[i] == MATCHED_EXACTLY)
494 continue;
496 * Make exclude patterns optional and never report
497 * "pathspec ':(exclude)foo' matches no files"
499 if (seen && ps->items[i].magic & PATHSPEC_EXCLUDE)
500 seen[i] = MATCHED_FNMATCH;
501 how = match_pathspec_item(istate, ps->items+i, prefix, name,
502 namelen, flags);
503 if (ps->recursive &&
504 (ps->magic & PATHSPEC_MAXDEPTH) &&
505 ps->max_depth != -1 &&
506 how && how != MATCHED_FNMATCH) {
507 int len = ps->items[i].len;
508 if (name[len] == '/')
509 len++;
510 if (within_depth(name+len, namelen-len, 0, ps->max_depth))
511 how = MATCHED_EXACTLY;
512 else
513 how = 0;
515 if (how) {
516 if (retval < how)
517 retval = how;
518 if (seen && seen[i] < how)
519 seen[i] = how;
522 return retval;
525 static int match_pathspec_with_flags(struct index_state *istate,
526 const struct pathspec *ps,
527 const char *name, int namelen,
528 int prefix, char *seen, unsigned flags)
530 int positive, negative;
531 positive = do_match_pathspec(istate, ps, name, namelen,
532 prefix, seen, flags);
533 if (!(ps->magic & PATHSPEC_EXCLUDE) || !positive)
534 return positive;
535 negative = do_match_pathspec(istate, ps, name, namelen,
536 prefix, seen,
537 flags | DO_MATCH_EXCLUDE);
538 return negative ? 0 : positive;
541 int match_pathspec(struct index_state *istate,
542 const struct pathspec *ps,
543 const char *name, int namelen,
544 int prefix, char *seen, int is_dir)
546 unsigned flags = is_dir ? DO_MATCH_DIRECTORY : 0;
547 return match_pathspec_with_flags(istate, ps, name, namelen,
548 prefix, seen, flags);
552 * Check if a submodule is a superset of the pathspec
554 int submodule_path_match(struct index_state *istate,
555 const struct pathspec *ps,
556 const char *submodule_name,
557 char *seen)
559 int matched = match_pathspec_with_flags(istate, ps, submodule_name,
560 strlen(submodule_name),
561 0, seen,
562 DO_MATCH_DIRECTORY |
563 DO_MATCH_LEADING_PATHSPEC);
564 return matched;
567 int report_path_error(const char *ps_matched,
568 const struct pathspec *pathspec)
571 * Make sure all pathspec matched; otherwise it is an error.
573 int num, errors = 0;
574 for (num = 0; num < pathspec->nr; num++) {
575 int other, found_dup;
577 if (ps_matched[num])
578 continue;
580 * The caller might have fed identical pathspec
581 * twice. Do not barf on such a mistake.
582 * FIXME: parse_pathspec should have eliminated
583 * duplicate pathspec.
585 for (found_dup = other = 0;
586 !found_dup && other < pathspec->nr;
587 other++) {
588 if (other == num || !ps_matched[other])
589 continue;
590 if (!strcmp(pathspec->items[other].original,
591 pathspec->items[num].original))
593 * Ok, we have a match already.
595 found_dup = 1;
597 if (found_dup)
598 continue;
600 error(_("pathspec '%s' did not match any file(s) known to git"),
601 pathspec->items[num].original);
602 errors++;
604 return errors;
608 * Return the length of the "simple" part of a path match limiter.
610 int simple_length(const char *match)
612 int len = -1;
614 for (;;) {
615 unsigned char c = *match++;
616 len++;
617 if (c == '\0' || is_glob_special(c))
618 return len;
622 int no_wildcard(const char *string)
624 return string[simple_length(string)] == '\0';
627 void parse_path_pattern(const char **pattern,
628 int *patternlen,
629 unsigned *flags,
630 int *nowildcardlen)
632 const char *p = *pattern;
633 size_t i, len;
635 *flags = 0;
636 if (*p == '!') {
637 *flags |= PATTERN_FLAG_NEGATIVE;
638 p++;
640 len = strlen(p);
641 if (len && p[len - 1] == '/') {
642 len--;
643 *flags |= PATTERN_FLAG_MUSTBEDIR;
645 for (i = 0; i < len; i++) {
646 if (p[i] == '/')
647 break;
649 if (i == len)
650 *flags |= PATTERN_FLAG_NODIR;
651 *nowildcardlen = simple_length(p);
653 * we should have excluded the trailing slash from 'p' too,
654 * but that's one more allocation. Instead just make sure
655 * nowildcardlen does not exceed real patternlen
657 if (*nowildcardlen > len)
658 *nowildcardlen = len;
659 if (*p == '*' && no_wildcard(p + 1))
660 *flags |= PATTERN_FLAG_ENDSWITH;
661 *pattern = p;
662 *patternlen = len;
665 int pl_hashmap_cmp(const void *cmp_data UNUSED,
666 const struct hashmap_entry *a,
667 const struct hashmap_entry *b,
668 const void *key UNUSED)
670 const struct pattern_entry *ee1 =
671 container_of(a, struct pattern_entry, ent);
672 const struct pattern_entry *ee2 =
673 container_of(b, struct pattern_entry, ent);
675 size_t min_len = ee1->patternlen <= ee2->patternlen
676 ? ee1->patternlen
677 : ee2->patternlen;
679 return fspathncmp(ee1->pattern, ee2->pattern, min_len);
682 static char *dup_and_filter_pattern(const char *pattern)
684 char *set, *read;
685 size_t count = 0;
686 char *result = xstrdup(pattern);
688 set = result;
689 read = result;
691 while (*read) {
692 /* skip escape characters (once) */
693 if (*read == '\\')
694 read++;
696 *set = *read;
698 set++;
699 read++;
700 count++;
702 *set = 0;
704 if (count > 2 &&
705 *(set - 1) == '*' &&
706 *(set - 2) == '/')
707 *(set - 2) = 0;
709 return result;
712 static void add_pattern_to_hashsets(struct pattern_list *pl, struct path_pattern *given)
714 struct pattern_entry *translated;
715 char *truncated;
716 char *data = NULL;
717 const char *prev, *cur, *next;
719 if (!pl->use_cone_patterns)
720 return;
722 if (given->flags & PATTERN_FLAG_NEGATIVE &&
723 given->flags & PATTERN_FLAG_MUSTBEDIR &&
724 !strcmp(given->pattern, "/*")) {
725 pl->full_cone = 0;
726 return;
729 if (!given->flags && !strcmp(given->pattern, "/*")) {
730 pl->full_cone = 1;
731 return;
734 if (given->patternlen < 2 ||
735 *given->pattern != '/' ||
736 strstr(given->pattern, "**")) {
737 /* Not a cone pattern. */
738 warning(_("unrecognized pattern: '%s'"), given->pattern);
739 goto clear_hashmaps;
742 if (!(given->flags & PATTERN_FLAG_MUSTBEDIR) &&
743 strcmp(given->pattern, "/*")) {
744 /* Not a cone pattern. */
745 warning(_("unrecognized pattern: '%s'"), given->pattern);
746 goto clear_hashmaps;
749 prev = given->pattern;
750 cur = given->pattern + 1;
751 next = given->pattern + 2;
753 while (*cur) {
754 /* Watch for glob characters '*', '\', '[', '?' */
755 if (!is_glob_special(*cur))
756 goto increment;
758 /* But only if *prev != '\\' */
759 if (*prev == '\\')
760 goto increment;
762 /* But allow the initial '\' */
763 if (*cur == '\\' &&
764 is_glob_special(*next))
765 goto increment;
767 /* But a trailing '/' then '*' is fine */
768 if (*prev == '/' &&
769 *cur == '*' &&
770 *next == 0)
771 goto increment;
773 /* Not a cone pattern. */
774 warning(_("unrecognized pattern: '%s'"), given->pattern);
775 goto clear_hashmaps;
777 increment:
778 prev++;
779 cur++;
780 next++;
783 if (given->patternlen > 2 &&
784 !strcmp(given->pattern + given->patternlen - 2, "/*")) {
785 if (!(given->flags & PATTERN_FLAG_NEGATIVE)) {
786 /* Not a cone pattern. */
787 warning(_("unrecognized pattern: '%s'"), given->pattern);
788 goto clear_hashmaps;
791 truncated = dup_and_filter_pattern(given->pattern);
793 translated = xmalloc(sizeof(struct pattern_entry));
794 translated->pattern = truncated;
795 translated->patternlen = given->patternlen - 2;
796 hashmap_entry_init(&translated->ent,
797 fspathhash(translated->pattern));
799 if (!hashmap_get_entry(&pl->recursive_hashmap,
800 translated, ent, NULL)) {
801 /* We did not see the "parent" included */
802 warning(_("unrecognized negative pattern: '%s'"),
803 given->pattern);
804 free(truncated);
805 free(translated);
806 goto clear_hashmaps;
809 hashmap_add(&pl->parent_hashmap, &translated->ent);
810 hashmap_remove(&pl->recursive_hashmap, &translated->ent, &data);
811 free(data);
812 return;
815 if (given->flags & PATTERN_FLAG_NEGATIVE) {
816 warning(_("unrecognized negative pattern: '%s'"),
817 given->pattern);
818 goto clear_hashmaps;
821 translated = xmalloc(sizeof(struct pattern_entry));
823 translated->pattern = dup_and_filter_pattern(given->pattern);
824 translated->patternlen = given->patternlen;
825 hashmap_entry_init(&translated->ent,
826 fspathhash(translated->pattern));
828 hashmap_add(&pl->recursive_hashmap, &translated->ent);
830 if (hashmap_get_entry(&pl->parent_hashmap, translated, ent, NULL)) {
831 /* we already included this at the parent level */
832 warning(_("your sparse-checkout file may have issues: pattern '%s' is repeated"),
833 given->pattern);
834 goto clear_hashmaps;
837 return;
839 clear_hashmaps:
840 warning(_("disabling cone pattern matching"));
841 hashmap_clear_and_free(&pl->parent_hashmap, struct pattern_entry, ent);
842 hashmap_clear_and_free(&pl->recursive_hashmap, struct pattern_entry, ent);
843 pl->use_cone_patterns = 0;
846 static int hashmap_contains_path(struct hashmap *map,
847 struct strbuf *pattern)
849 struct pattern_entry p;
851 /* Check straight mapping */
852 p.pattern = pattern->buf;
853 p.patternlen = pattern->len;
854 hashmap_entry_init(&p.ent, fspathhash(p.pattern));
855 return !!hashmap_get_entry(map, &p, ent, NULL);
858 int hashmap_contains_parent(struct hashmap *map,
859 const char *path,
860 struct strbuf *buffer)
862 char *slash_pos;
864 strbuf_setlen(buffer, 0);
866 if (path[0] != '/')
867 strbuf_addch(buffer, '/');
869 strbuf_addstr(buffer, path);
871 slash_pos = strrchr(buffer->buf, '/');
873 while (slash_pos > buffer->buf) {
874 strbuf_setlen(buffer, slash_pos - buffer->buf);
876 if (hashmap_contains_path(map, buffer))
877 return 1;
879 slash_pos = strrchr(buffer->buf, '/');
882 return 0;
885 void add_pattern(const char *string, const char *base,
886 int baselen, struct pattern_list *pl, int srcpos)
888 struct path_pattern *pattern;
889 int patternlen;
890 unsigned flags;
891 int nowildcardlen;
893 parse_path_pattern(&string, &patternlen, &flags, &nowildcardlen);
894 if (flags & PATTERN_FLAG_MUSTBEDIR) {
895 FLEXPTR_ALLOC_MEM(pattern, pattern, string, patternlen);
896 } else {
897 pattern = xmalloc(sizeof(*pattern));
898 pattern->pattern = string;
900 pattern->patternlen = patternlen;
901 pattern->nowildcardlen = nowildcardlen;
902 pattern->base = base;
903 pattern->baselen = baselen;
904 pattern->flags = flags;
905 pattern->srcpos = srcpos;
906 ALLOC_GROW(pl->patterns, pl->nr + 1, pl->alloc);
907 pl->patterns[pl->nr++] = pattern;
908 pattern->pl = pl;
910 add_pattern_to_hashsets(pl, pattern);
913 static int read_skip_worktree_file_from_index(struct index_state *istate,
914 const char *path,
915 size_t *size_out, char **data_out,
916 struct oid_stat *oid_stat)
918 int pos, len;
920 len = strlen(path);
921 pos = index_name_pos(istate, path, len);
922 if (pos < 0)
923 return -1;
924 if (!ce_skip_worktree(istate->cache[pos]))
925 return -1;
927 return do_read_blob(&istate->cache[pos]->oid, oid_stat, size_out, data_out);
931 * Frees memory within pl which was allocated for exclude patterns and
932 * the file buffer. Does not free pl itself.
934 void clear_pattern_list(struct pattern_list *pl)
936 int i;
938 for (i = 0; i < pl->nr; i++)
939 free(pl->patterns[i]);
940 free(pl->patterns);
941 free(pl->filebuf);
942 hashmap_clear_and_free(&pl->recursive_hashmap, struct pattern_entry, ent);
943 hashmap_clear_and_free(&pl->parent_hashmap, struct pattern_entry, ent);
945 memset(pl, 0, sizeof(*pl));
948 static void trim_trailing_spaces(char *buf)
950 char *p, *last_space = NULL;
952 for (p = buf; *p; p++)
953 switch (*p) {
954 case ' ':
955 if (!last_space)
956 last_space = p;
957 break;
958 case '\\':
959 p++;
960 if (!*p)
961 return;
962 /* fallthrough */
963 default:
964 last_space = NULL;
967 if (last_space)
968 *last_space = '\0';
972 * Given a subdirectory name and "dir" of the current directory,
973 * search the subdir in "dir" and return it, or create a new one if it
974 * does not exist in "dir".
976 * If "name" has the trailing slash, it'll be excluded in the search.
978 static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc,
979 struct untracked_cache_dir *dir,
980 const char *name, int len)
982 int first, last;
983 struct untracked_cache_dir *d;
984 if (!dir)
985 return NULL;
986 if (len && name[len - 1] == '/')
987 len--;
988 first = 0;
989 last = dir->dirs_nr;
990 while (last > first) {
991 int cmp, next = first + ((last - first) >> 1);
992 d = dir->dirs[next];
993 cmp = strncmp(name, d->name, len);
994 if (!cmp && strlen(d->name) > len)
995 cmp = -1;
996 if (!cmp)
997 return d;
998 if (cmp < 0) {
999 last = next;
1000 continue;
1002 first = next+1;
1005 uc->dir_created++;
1006 FLEX_ALLOC_MEM(d, name, name, len);
1008 ALLOC_GROW(dir->dirs, dir->dirs_nr + 1, dir->dirs_alloc);
1009 MOVE_ARRAY(dir->dirs + first + 1, dir->dirs + first,
1010 dir->dirs_nr - first);
1011 dir->dirs_nr++;
1012 dir->dirs[first] = d;
1013 return d;
1016 static void do_invalidate_gitignore(struct untracked_cache_dir *dir)
1018 int i;
1019 dir->valid = 0;
1020 dir->untracked_nr = 0;
1021 for (i = 0; i < dir->dirs_nr; i++)
1022 do_invalidate_gitignore(dir->dirs[i]);
1025 static void invalidate_gitignore(struct untracked_cache *uc,
1026 struct untracked_cache_dir *dir)
1028 uc->gitignore_invalidated++;
1029 do_invalidate_gitignore(dir);
1032 static void invalidate_directory(struct untracked_cache *uc,
1033 struct untracked_cache_dir *dir)
1035 int i;
1038 * Invalidation increment here is just roughly correct. If
1039 * untracked_nr or any of dirs[].recurse is non-zero, we
1040 * should increment dir_invalidated too. But that's more
1041 * expensive to do.
1043 if (dir->valid)
1044 uc->dir_invalidated++;
1046 dir->valid = 0;
1047 dir->untracked_nr = 0;
1048 for (i = 0; i < dir->dirs_nr; i++)
1049 dir->dirs[i]->recurse = 0;
1052 static int add_patterns_from_buffer(char *buf, size_t size,
1053 const char *base, int baselen,
1054 struct pattern_list *pl);
1056 /* Flags for add_patterns() */
1057 #define PATTERN_NOFOLLOW (1<<0)
1060 * Given a file with name "fname", read it (either from disk, or from
1061 * an index if 'istate' is non-null), parse it and store the
1062 * exclude rules in "pl".
1064 * If "oid_stat" is not NULL, compute oid of the exclude file and fill
1065 * stat data from disk (only valid if add_patterns returns zero). If
1066 * oid_stat.valid is non-zero, "oid_stat" must contain good value as input.
1068 static int add_patterns(const char *fname, const char *base, int baselen,
1069 struct pattern_list *pl, struct index_state *istate,
1070 unsigned flags, struct oid_stat *oid_stat)
1072 struct stat st;
1073 int r;
1074 int fd;
1075 size_t size = 0;
1076 char *buf;
1078 if (flags & PATTERN_NOFOLLOW)
1079 fd = open_nofollow(fname, O_RDONLY);
1080 else
1081 fd = open(fname, O_RDONLY);
1083 if (fd < 0 || fstat(fd, &st) < 0) {
1084 if (fd < 0)
1085 warn_on_fopen_errors(fname);
1086 else
1087 close(fd);
1088 if (!istate)
1089 return -1;
1090 r = read_skip_worktree_file_from_index(istate, fname,
1091 &size, &buf,
1092 oid_stat);
1093 if (r != 1)
1094 return r;
1095 } else {
1096 size = xsize_t(st.st_size);
1097 if (size == 0) {
1098 if (oid_stat) {
1099 fill_stat_data(&oid_stat->stat, &st);
1100 oidcpy(&oid_stat->oid, the_hash_algo->empty_blob);
1101 oid_stat->valid = 1;
1103 close(fd);
1104 return 0;
1106 buf = xmallocz(size);
1107 if (read_in_full(fd, buf, size) != size) {
1108 free(buf);
1109 close(fd);
1110 return -1;
1112 buf[size++] = '\n';
1113 close(fd);
1114 if (oid_stat) {
1115 int pos;
1116 if (oid_stat->valid &&
1117 !match_stat_data_racy(istate, &oid_stat->stat, &st))
1118 ; /* no content change, oid_stat->oid still good */
1119 else if (istate &&
1120 (pos = index_name_pos(istate, fname, strlen(fname))) >= 0 &&
1121 !ce_stage(istate->cache[pos]) &&
1122 ce_uptodate(istate->cache[pos]) &&
1123 !would_convert_to_git(istate, fname))
1124 oidcpy(&oid_stat->oid,
1125 &istate->cache[pos]->oid);
1126 else
1127 hash_object_file(the_hash_algo, buf, size,
1128 OBJ_BLOB, &oid_stat->oid);
1129 fill_stat_data(&oid_stat->stat, &st);
1130 oid_stat->valid = 1;
1134 add_patterns_from_buffer(buf, size, base, baselen, pl);
1135 return 0;
1138 static int add_patterns_from_buffer(char *buf, size_t size,
1139 const char *base, int baselen,
1140 struct pattern_list *pl)
1142 int i, lineno = 1;
1143 char *entry;
1145 hashmap_init(&pl->recursive_hashmap, pl_hashmap_cmp, NULL, 0);
1146 hashmap_init(&pl->parent_hashmap, pl_hashmap_cmp, NULL, 0);
1148 pl->filebuf = buf;
1150 if (skip_utf8_bom(&buf, size))
1151 size -= buf - pl->filebuf;
1153 entry = buf;
1155 for (i = 0; i < size; i++) {
1156 if (buf[i] == '\n') {
1157 if (entry != buf + i && entry[0] != '#') {
1158 buf[i - (i && buf[i-1] == '\r')] = 0;
1159 trim_trailing_spaces(entry);
1160 add_pattern(entry, base, baselen, pl, lineno);
1162 lineno++;
1163 entry = buf + i + 1;
1166 return 0;
1169 int add_patterns_from_file_to_list(const char *fname, const char *base,
1170 int baselen, struct pattern_list *pl,
1171 struct index_state *istate,
1172 unsigned flags)
1174 return add_patterns(fname, base, baselen, pl, istate, flags, NULL);
1177 int add_patterns_from_blob_to_list(
1178 struct object_id *oid,
1179 const char *base, int baselen,
1180 struct pattern_list *pl)
1182 char *buf;
1183 size_t size;
1184 int r;
1186 r = do_read_blob(oid, NULL, &size, &buf);
1187 if (r != 1)
1188 return r;
1190 add_patterns_from_buffer(buf, size, base, baselen, pl);
1191 return 0;
1194 struct pattern_list *add_pattern_list(struct dir_struct *dir,
1195 int group_type, const char *src)
1197 struct pattern_list *pl;
1198 struct exclude_list_group *group;
1200 group = &dir->internal.exclude_list_group[group_type];
1201 ALLOC_GROW(group->pl, group->nr + 1, group->alloc);
1202 pl = &group->pl[group->nr++];
1203 memset(pl, 0, sizeof(*pl));
1204 pl->src = src;
1205 return pl;
1209 * Used to set up core.excludesfile and .git/info/exclude lists.
1211 static void add_patterns_from_file_1(struct dir_struct *dir, const char *fname,
1212 struct oid_stat *oid_stat)
1214 struct pattern_list *pl;
1216 * catch setup_standard_excludes() that's called before
1217 * dir->untracked is assigned. That function behaves
1218 * differently when dir->untracked is non-NULL.
1220 if (!dir->untracked)
1221 dir->internal.unmanaged_exclude_files++;
1222 pl = add_pattern_list(dir, EXC_FILE, fname);
1223 if (add_patterns(fname, "", 0, pl, NULL, 0, oid_stat) < 0)
1224 die(_("cannot use %s as an exclude file"), fname);
1227 void add_patterns_from_file(struct dir_struct *dir, const char *fname)
1229 dir->internal.unmanaged_exclude_files++; /* see validate_untracked_cache() */
1230 add_patterns_from_file_1(dir, fname, NULL);
1233 int match_basename(const char *basename, int basenamelen,
1234 const char *pattern, int prefix, int patternlen,
1235 unsigned flags)
1237 if (prefix == patternlen) {
1238 if (patternlen == basenamelen &&
1239 !fspathncmp(pattern, basename, basenamelen))
1240 return 1;
1241 } else if (flags & PATTERN_FLAG_ENDSWITH) {
1242 /* "*literal" matching against "fooliteral" */
1243 if (patternlen - 1 <= basenamelen &&
1244 !fspathncmp(pattern + 1,
1245 basename + basenamelen - (patternlen - 1),
1246 patternlen - 1))
1247 return 1;
1248 } else {
1249 if (fnmatch_icase_mem(pattern, patternlen,
1250 basename, basenamelen,
1251 0) == 0)
1252 return 1;
1254 return 0;
1257 int match_pathname(const char *pathname, int pathlen,
1258 const char *base, int baselen,
1259 const char *pattern, int prefix, int patternlen)
1261 const char *name;
1262 int namelen;
1265 * match with FNM_PATHNAME; the pattern has base implicitly
1266 * in front of it.
1268 if (*pattern == '/') {
1269 pattern++;
1270 patternlen--;
1271 prefix--;
1275 * baselen does not count the trailing slash. base[] may or
1276 * may not end with a trailing slash though.
1278 if (pathlen < baselen + 1 ||
1279 (baselen && pathname[baselen] != '/') ||
1280 fspathncmp(pathname, base, baselen))
1281 return 0;
1283 namelen = baselen ? pathlen - baselen - 1 : pathlen;
1284 name = pathname + pathlen - namelen;
1286 if (prefix) {
1288 * if the non-wildcard part is longer than the
1289 * remaining pathname, surely it cannot match.
1291 if (prefix > namelen)
1292 return 0;
1294 if (fspathncmp(pattern, name, prefix))
1295 return 0;
1296 pattern += prefix;
1297 patternlen -= prefix;
1298 name += prefix;
1299 namelen -= prefix;
1302 * If the whole pattern did not have a wildcard,
1303 * then our prefix match is all we need; we
1304 * do not need to call fnmatch at all.
1306 if (!patternlen && !namelen)
1307 return 1;
1310 return fnmatch_icase_mem(pattern, patternlen,
1311 name, namelen,
1312 WM_PATHNAME) == 0;
1316 * Scan the given exclude list in reverse to see whether pathname
1317 * should be ignored. The first match (i.e. the last on the list), if
1318 * any, determines the fate. Returns the exclude_list element which
1319 * matched, or NULL for undecided.
1321 static struct path_pattern *last_matching_pattern_from_list(const char *pathname,
1322 int pathlen,
1323 const char *basename,
1324 int *dtype,
1325 struct pattern_list *pl,
1326 struct index_state *istate)
1328 struct path_pattern *res = NULL; /* undecided */
1329 int i;
1331 if (!pl->nr)
1332 return NULL; /* undefined */
1334 for (i = pl->nr - 1; 0 <= i; i--) {
1335 struct path_pattern *pattern = pl->patterns[i];
1336 const char *exclude = pattern->pattern;
1337 int prefix = pattern->nowildcardlen;
1339 if (pattern->flags & PATTERN_FLAG_MUSTBEDIR) {
1340 *dtype = resolve_dtype(*dtype, istate, pathname, pathlen);
1341 if (*dtype != DT_DIR)
1342 continue;
1345 if (pattern->flags & PATTERN_FLAG_NODIR) {
1346 if (match_basename(basename,
1347 pathlen - (basename - pathname),
1348 exclude, prefix, pattern->patternlen,
1349 pattern->flags)) {
1350 res = pattern;
1351 break;
1353 continue;
1356 assert(pattern->baselen == 0 ||
1357 pattern->base[pattern->baselen - 1] == '/');
1358 if (match_pathname(pathname, pathlen,
1359 pattern->base,
1360 pattern->baselen ? pattern->baselen - 1 : 0,
1361 exclude, prefix, pattern->patternlen)) {
1362 res = pattern;
1363 break;
1366 return res;
1370 * Scan the list of patterns to determine if the ordered list
1371 * of patterns matches on 'pathname'.
1373 * Return 1 for a match, 0 for not matched and -1 for undecided.
1375 enum pattern_match_result path_matches_pattern_list(
1376 const char *pathname, int pathlen,
1377 const char *basename, int *dtype,
1378 struct pattern_list *pl,
1379 struct index_state *istate)
1381 struct path_pattern *pattern;
1382 struct strbuf parent_pathname = STRBUF_INIT;
1383 int result = NOT_MATCHED;
1384 size_t slash_pos;
1386 if (!pl->use_cone_patterns) {
1387 pattern = last_matching_pattern_from_list(pathname, pathlen, basename,
1388 dtype, pl, istate);
1389 if (pattern) {
1390 if (pattern->flags & PATTERN_FLAG_NEGATIVE)
1391 return NOT_MATCHED;
1392 else
1393 return MATCHED;
1396 return UNDECIDED;
1399 if (pl->full_cone)
1400 return MATCHED;
1402 strbuf_addch(&parent_pathname, '/');
1403 strbuf_add(&parent_pathname, pathname, pathlen);
1406 * Directory entries are matched if and only if a file
1407 * contained immediately within them is matched. For the
1408 * case of a directory entry, modify the path to create
1409 * a fake filename within this directory, allowing us to
1410 * use the file-base matching logic in an equivalent way.
1412 if (parent_pathname.len > 0 &&
1413 parent_pathname.buf[parent_pathname.len - 1] == '/') {
1414 slash_pos = parent_pathname.len - 1;
1415 strbuf_add(&parent_pathname, "-", 1);
1416 } else {
1417 const char *slash_ptr = strrchr(parent_pathname.buf, '/');
1418 slash_pos = slash_ptr ? slash_ptr - parent_pathname.buf : 0;
1421 if (hashmap_contains_path(&pl->recursive_hashmap,
1422 &parent_pathname)) {
1423 result = MATCHED_RECURSIVE;
1424 goto done;
1427 if (!slash_pos) {
1428 /* include every file in root */
1429 result = MATCHED;
1430 goto done;
1433 strbuf_setlen(&parent_pathname, slash_pos);
1435 if (hashmap_contains_path(&pl->parent_hashmap, &parent_pathname)) {
1436 result = MATCHED;
1437 goto done;
1440 if (hashmap_contains_parent(&pl->recursive_hashmap,
1441 pathname,
1442 &parent_pathname))
1443 result = MATCHED_RECURSIVE;
1445 done:
1446 strbuf_release(&parent_pathname);
1447 return result;
1450 int init_sparse_checkout_patterns(struct index_state *istate)
1452 if (!core_apply_sparse_checkout)
1453 return 1;
1454 if (istate->sparse_checkout_patterns)
1455 return 0;
1457 CALLOC_ARRAY(istate->sparse_checkout_patterns, 1);
1459 if (get_sparse_checkout_patterns(istate->sparse_checkout_patterns) < 0) {
1460 FREE_AND_NULL(istate->sparse_checkout_patterns);
1461 return -1;
1464 return 0;
1467 static int path_in_sparse_checkout_1(const char *path,
1468 struct index_state *istate,
1469 int require_cone_mode)
1471 int dtype = DT_REG;
1472 enum pattern_match_result match = UNDECIDED;
1473 const char *end, *slash;
1476 * We default to accepting a path if the path is empty, there are no
1477 * patterns, or the patterns are of the wrong type.
1479 if (!*path ||
1480 init_sparse_checkout_patterns(istate) ||
1481 (require_cone_mode &&
1482 !istate->sparse_checkout_patterns->use_cone_patterns))
1483 return 1;
1486 * If UNDECIDED, use the match from the parent dir (recursively), or
1487 * fall back to NOT_MATCHED at the topmost level. Note that cone mode
1488 * never returns UNDECIDED, so we will execute only one iteration in
1489 * this case.
1491 for (end = path + strlen(path);
1492 end > path && match == UNDECIDED;
1493 end = slash) {
1495 for (slash = end - 1; slash > path && *slash != '/'; slash--)
1496 ; /* do nothing */
1498 match = path_matches_pattern_list(path, end - path,
1499 slash > path ? slash + 1 : path, &dtype,
1500 istate->sparse_checkout_patterns, istate);
1502 /* We are going to match the parent dir now */
1503 dtype = DT_DIR;
1505 return match > 0;
1508 int path_in_sparse_checkout(const char *path,
1509 struct index_state *istate)
1511 return path_in_sparse_checkout_1(path, istate, 0);
1514 int path_in_cone_mode_sparse_checkout(const char *path,
1515 struct index_state *istate)
1517 return path_in_sparse_checkout_1(path, istate, 1);
1520 static struct path_pattern *last_matching_pattern_from_lists(
1521 struct dir_struct *dir, struct index_state *istate,
1522 const char *pathname, int pathlen,
1523 const char *basename, int *dtype_p)
1525 int i, j;
1526 struct exclude_list_group *group;
1527 struct path_pattern *pattern;
1528 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
1529 group = &dir->internal.exclude_list_group[i];
1530 for (j = group->nr - 1; j >= 0; j--) {
1531 pattern = last_matching_pattern_from_list(
1532 pathname, pathlen, basename, dtype_p,
1533 &group->pl[j], istate);
1534 if (pattern)
1535 return pattern;
1538 return NULL;
1542 * Loads the per-directory exclude list for the substring of base
1543 * which has a char length of baselen.
1545 static void prep_exclude(struct dir_struct *dir,
1546 struct index_state *istate,
1547 const char *base, int baselen)
1549 struct exclude_list_group *group;
1550 struct pattern_list *pl;
1551 struct exclude_stack *stk = NULL;
1552 struct untracked_cache_dir *untracked;
1553 int current;
1555 group = &dir->internal.exclude_list_group[EXC_DIRS];
1558 * Pop the exclude lists from the EXCL_DIRS exclude_list_group
1559 * which originate from directories not in the prefix of the
1560 * path being checked.
1562 while ((stk = dir->internal.exclude_stack) != NULL) {
1563 if (stk->baselen <= baselen &&
1564 !strncmp(dir->internal.basebuf.buf, base, stk->baselen))
1565 break;
1566 pl = &group->pl[dir->internal.exclude_stack->exclude_ix];
1567 dir->internal.exclude_stack = stk->prev;
1568 dir->internal.pattern = NULL;
1569 free((char *)pl->src); /* see strbuf_detach() below */
1570 clear_pattern_list(pl);
1571 free(stk);
1572 group->nr--;
1575 /* Skip traversing into sub directories if the parent is excluded */
1576 if (dir->internal.pattern)
1577 return;
1580 * Lazy initialization. All call sites currently just
1581 * memset(dir, 0, sizeof(*dir)) before use. Changing all of
1582 * them seems lots of work for little benefit.
1584 if (!dir->internal.basebuf.buf)
1585 strbuf_init(&dir->internal.basebuf, PATH_MAX);
1587 /* Read from the parent directories and push them down. */
1588 current = stk ? stk->baselen : -1;
1589 strbuf_setlen(&dir->internal.basebuf, current < 0 ? 0 : current);
1590 if (dir->untracked)
1591 untracked = stk ? stk->ucd : dir->untracked->root;
1592 else
1593 untracked = NULL;
1595 while (current < baselen) {
1596 const char *cp;
1597 struct oid_stat oid_stat;
1599 CALLOC_ARRAY(stk, 1);
1600 if (current < 0) {
1601 cp = base;
1602 current = 0;
1603 } else {
1604 cp = strchr(base + current + 1, '/');
1605 if (!cp)
1606 die("oops in prep_exclude");
1607 cp++;
1608 untracked =
1609 lookup_untracked(dir->untracked,
1610 untracked,
1611 base + current,
1612 cp - base - current);
1614 stk->prev = dir->internal.exclude_stack;
1615 stk->baselen = cp - base;
1616 stk->exclude_ix = group->nr;
1617 stk->ucd = untracked;
1618 pl = add_pattern_list(dir, EXC_DIRS, NULL);
1619 strbuf_add(&dir->internal.basebuf, base + current, stk->baselen - current);
1620 assert(stk->baselen == dir->internal.basebuf.len);
1622 /* Abort if the directory is excluded */
1623 if (stk->baselen) {
1624 int dt = DT_DIR;
1625 dir->internal.basebuf.buf[stk->baselen - 1] = 0;
1626 dir->internal.pattern = last_matching_pattern_from_lists(dir,
1627 istate,
1628 dir->internal.basebuf.buf, stk->baselen - 1,
1629 dir->internal.basebuf.buf + current, &dt);
1630 dir->internal.basebuf.buf[stk->baselen - 1] = '/';
1631 if (dir->internal.pattern &&
1632 dir->internal.pattern->flags & PATTERN_FLAG_NEGATIVE)
1633 dir->internal.pattern = NULL;
1634 if (dir->internal.pattern) {
1635 dir->internal.exclude_stack = stk;
1636 return;
1640 /* Try to read per-directory file */
1641 oidclr(&oid_stat.oid);
1642 oid_stat.valid = 0;
1643 if (dir->exclude_per_dir &&
1645 * If we know that no files have been added in
1646 * this directory (i.e. valid_cached_dir() has
1647 * been executed and set untracked->valid) ..
1649 (!untracked || !untracked->valid ||
1651 * .. and .gitignore does not exist before
1652 * (i.e. null exclude_oid). Then we can skip
1653 * loading .gitignore, which would result in
1654 * ENOENT anyway.
1656 !is_null_oid(&untracked->exclude_oid))) {
1658 * dir->internal.basebuf gets reused by the traversal,
1659 * but we need fname to remain unchanged to ensure the
1660 * src member of each struct path_pattern correctly
1661 * back-references its source file. Other invocations
1662 * of add_pattern_list provide stable strings, so we
1663 * strbuf_detach() and free() here in the caller.
1665 struct strbuf sb = STRBUF_INIT;
1666 strbuf_addbuf(&sb, &dir->internal.basebuf);
1667 strbuf_addstr(&sb, dir->exclude_per_dir);
1668 pl->src = strbuf_detach(&sb, NULL);
1669 add_patterns(pl->src, pl->src, stk->baselen, pl, istate,
1670 PATTERN_NOFOLLOW,
1671 untracked ? &oid_stat : NULL);
1674 * NEEDSWORK: when untracked cache is enabled, prep_exclude()
1675 * will first be called in valid_cached_dir() then maybe many
1676 * times more in last_matching_pattern(). When the cache is
1677 * used, last_matching_pattern() will not be called and
1678 * reading .gitignore content will be a waste.
1680 * So when it's called by valid_cached_dir() and we can get
1681 * .gitignore SHA-1 from the index (i.e. .gitignore is not
1682 * modified on work tree), we could delay reading the
1683 * .gitignore content until we absolutely need it in
1684 * last_matching_pattern(). Be careful about ignore rule
1685 * order, though, if you do that.
1687 if (untracked &&
1688 !oideq(&oid_stat.oid, &untracked->exclude_oid)) {
1689 invalidate_gitignore(dir->untracked, untracked);
1690 oidcpy(&untracked->exclude_oid, &oid_stat.oid);
1692 dir->internal.exclude_stack = stk;
1693 current = stk->baselen;
1695 strbuf_setlen(&dir->internal.basebuf, baselen);
1699 * Loads the exclude lists for the directory containing pathname, then
1700 * scans all exclude lists to determine whether pathname is excluded.
1701 * Returns the exclude_list element which matched, or NULL for
1702 * undecided.
1704 struct path_pattern *last_matching_pattern(struct dir_struct *dir,
1705 struct index_state *istate,
1706 const char *pathname,
1707 int *dtype_p)
1709 int pathlen = strlen(pathname);
1710 const char *basename = strrchr(pathname, '/');
1711 basename = (basename) ? basename+1 : pathname;
1713 prep_exclude(dir, istate, pathname, basename-pathname);
1715 if (dir->internal.pattern)
1716 return dir->internal.pattern;
1718 return last_matching_pattern_from_lists(dir, istate, pathname, pathlen,
1719 basename, dtype_p);
1723 * Loads the exclude lists for the directory containing pathname, then
1724 * scans all exclude lists to determine whether pathname is excluded.
1725 * Returns 1 if true, otherwise 0.
1727 int is_excluded(struct dir_struct *dir, struct index_state *istate,
1728 const char *pathname, int *dtype_p)
1730 struct path_pattern *pattern =
1731 last_matching_pattern(dir, istate, pathname, dtype_p);
1732 if (pattern)
1733 return pattern->flags & PATTERN_FLAG_NEGATIVE ? 0 : 1;
1734 return 0;
1737 static struct dir_entry *dir_entry_new(const char *pathname, int len)
1739 struct dir_entry *ent;
1741 FLEX_ALLOC_MEM(ent, name, pathname, len);
1742 ent->len = len;
1743 return ent;
1746 static struct dir_entry *dir_add_name(struct dir_struct *dir,
1747 struct index_state *istate,
1748 const char *pathname, int len)
1750 if (index_file_exists(istate, pathname, len, ignore_case))
1751 return NULL;
1753 ALLOC_GROW(dir->entries, dir->nr+1, dir->internal.alloc);
1754 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
1757 struct dir_entry *dir_add_ignored(struct dir_struct *dir,
1758 struct index_state *istate,
1759 const char *pathname, int len)
1761 if (!index_name_is_other(istate, pathname, len))
1762 return NULL;
1764 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->internal.ignored_alloc);
1765 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
1768 enum exist_status {
1769 index_nonexistent = 0,
1770 index_directory,
1771 index_gitdir
1775 * Do not use the alphabetically sorted index to look up
1776 * the directory name; instead, use the case insensitive
1777 * directory hash.
1779 static enum exist_status directory_exists_in_index_icase(struct index_state *istate,
1780 const char *dirname, int len)
1782 struct cache_entry *ce;
1784 if (index_dir_exists(istate, dirname, len))
1785 return index_directory;
1787 ce = index_file_exists(istate, dirname, len, ignore_case);
1788 if (ce && S_ISGITLINK(ce->ce_mode))
1789 return index_gitdir;
1791 return index_nonexistent;
1795 * The index sorts alphabetically by entry name, which
1796 * means that a gitlink sorts as '\0' at the end, while
1797 * a directory (which is defined not as an entry, but as
1798 * the files it contains) will sort with the '/' at the
1799 * end.
1801 static enum exist_status directory_exists_in_index(struct index_state *istate,
1802 const char *dirname, int len)
1804 int pos;
1806 if (ignore_case)
1807 return directory_exists_in_index_icase(istate, dirname, len);
1809 pos = index_name_pos(istate, dirname, len);
1810 if (pos < 0)
1811 pos = -pos-1;
1812 while (pos < istate->cache_nr) {
1813 const struct cache_entry *ce = istate->cache[pos++];
1814 unsigned char endchar;
1816 if (strncmp(ce->name, dirname, len))
1817 break;
1818 endchar = ce->name[len];
1819 if (endchar > '/')
1820 break;
1821 if (endchar == '/')
1822 return index_directory;
1823 if (!endchar && S_ISGITLINK(ce->ce_mode))
1824 return index_gitdir;
1826 return index_nonexistent;
1830 * When we find a directory when traversing the filesystem, we
1831 * have three distinct cases:
1833 * - ignore it
1834 * - see it as a directory
1835 * - recurse into it
1837 * and which one we choose depends on a combination of existing
1838 * git index contents and the flags passed into the directory
1839 * traversal routine.
1841 * Case 1: If we *already* have entries in the index under that
1842 * directory name, we always recurse into the directory to see
1843 * all the files.
1845 * Case 2: If we *already* have that directory name as a gitlink,
1846 * we always continue to see it as a gitlink, regardless of whether
1847 * there is an actual git directory there or not (it might not
1848 * be checked out as a subproject!)
1850 * Case 3: if we didn't have it in the index previously, we
1851 * have a few sub-cases:
1853 * (a) if DIR_SHOW_OTHER_DIRECTORIES flag is set, we show it as
1854 * just a directory, unless DIR_HIDE_EMPTY_DIRECTORIES is
1855 * also true, in which case we need to check if it contains any
1856 * untracked and / or ignored files.
1857 * (b) if it looks like a git directory and we don't have the
1858 * DIR_NO_GITLINKS flag, then we treat it as a gitlink, and
1859 * show it as a directory.
1860 * (c) otherwise, we recurse into it.
1862 static enum path_treatment treat_directory(struct dir_struct *dir,
1863 struct index_state *istate,
1864 struct untracked_cache_dir *untracked,
1865 const char *dirname, int len, int baselen, int excluded,
1866 const struct pathspec *pathspec)
1869 * WARNING: From this function, you can return path_recurse or you
1870 * can call read_directory_recursive() (or neither), but
1871 * you CAN'T DO BOTH.
1873 enum path_treatment state;
1874 int matches_how = 0;
1875 int check_only, stop_early;
1876 int old_ignored_nr, old_untracked_nr;
1877 /* The "len-1" is to strip the final '/' */
1878 enum exist_status status = directory_exists_in_index(istate, dirname, len-1);
1880 if (status == index_directory)
1881 return path_recurse;
1882 if (status == index_gitdir)
1883 return path_none;
1884 if (status != index_nonexistent)
1885 BUG("Unhandled value for directory_exists_in_index: %d\n", status);
1888 * We don't want to descend into paths that don't match the necessary
1889 * patterns. Clearly, if we don't have a pathspec, then we can't check
1890 * for matching patterns. Also, if (excluded) then we know we matched
1891 * the exclusion patterns so as an optimization we can skip checking
1892 * for matching patterns.
1894 if (pathspec && !excluded) {
1895 matches_how = match_pathspec_with_flags(istate, pathspec,
1896 dirname, len,
1897 0 /* prefix */,
1898 NULL /* seen */,
1899 DO_MATCH_LEADING_PATHSPEC);
1900 if (!matches_how)
1901 return path_none;
1905 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
1906 !(dir->flags & DIR_NO_GITLINKS)) {
1908 * Determine if `dirname` is a nested repo by confirming that:
1909 * 1) we are in a nonbare repository, and
1910 * 2) `dirname` is not an immediate parent of `the_repository->gitdir`,
1911 * which could occur if the git_dir or worktree location was
1912 * manually configured by the user; see t2205 testcases 1-3 for
1913 * examples where this matters
1915 int nested_repo;
1916 struct strbuf sb = STRBUF_INIT;
1917 strbuf_addstr(&sb, dirname);
1918 nested_repo = is_nonbare_repository_dir(&sb);
1920 if (nested_repo) {
1921 char *real_dirname, *real_gitdir;
1922 strbuf_addstr(&sb, ".git");
1923 real_dirname = real_pathdup(sb.buf, 1);
1924 real_gitdir = real_pathdup(the_repository->gitdir, 1);
1926 nested_repo = !!strcmp(real_dirname, real_gitdir);
1927 free(real_gitdir);
1928 free(real_dirname);
1930 strbuf_release(&sb);
1932 if (nested_repo) {
1933 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
1934 (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC))
1935 return path_none;
1936 return excluded ? path_excluded : path_untracked;
1940 if (!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)) {
1941 if (excluded &&
1942 (dir->flags & DIR_SHOW_IGNORED_TOO) &&
1943 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING)) {
1946 * This is an excluded directory and we are
1947 * showing ignored paths that match an exclude
1948 * pattern. (e.g. show directory as ignored
1949 * only if it matches an exclude pattern).
1950 * This path will either be 'path_excluded`
1951 * (if we are showing empty directories or if
1952 * the directory is not empty), or will be
1953 * 'path_none' (empty directory, and we are
1954 * not showing empty directories).
1956 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1957 return path_excluded;
1959 if (read_directory_recursive(dir, istate, dirname, len,
1960 untracked, 1, 1, pathspec) == path_excluded)
1961 return path_excluded;
1963 return path_none;
1965 return path_recurse;
1968 assert(dir->flags & DIR_SHOW_OTHER_DIRECTORIES);
1971 * If we have a pathspec which could match something _below_ this
1972 * directory (e.g. when checking 'subdir/' having a pathspec like
1973 * 'subdir/some/deep/path/file' or 'subdir/widget-*.c'), then we
1974 * need to recurse.
1976 if (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC)
1977 return path_recurse;
1979 /* Special cases for where this directory is excluded/ignored */
1980 if (excluded) {
1982 * If DIR_SHOW_OTHER_DIRECTORIES is set and we're not
1983 * hiding empty directories, there is no need to
1984 * recurse into an ignored directory.
1986 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1987 return path_excluded;
1990 * Even if we are hiding empty directories, we can still avoid
1991 * recursing into ignored directories for DIR_SHOW_IGNORED_TOO
1992 * if DIR_SHOW_IGNORED_TOO_MODE_MATCHING is also set.
1994 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
1995 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING))
1996 return path_excluded;
2000 * Other than the path_recurse case above, we only need to
2001 * recurse into untracked directories if any of the following
2002 * bits is set:
2003 * - DIR_SHOW_IGNORED (because then we need to determine if
2004 * there are ignored entries below)
2005 * - DIR_SHOW_IGNORED_TOO (same as above)
2006 * - DIR_HIDE_EMPTY_DIRECTORIES (because we have to determine if
2007 * the directory is empty)
2009 if (!excluded &&
2010 !(dir->flags & (DIR_SHOW_IGNORED |
2011 DIR_SHOW_IGNORED_TOO |
2012 DIR_HIDE_EMPTY_DIRECTORIES))) {
2013 return path_untracked;
2017 * Even if we don't want to know all the paths under an untracked or
2018 * ignored directory, we may still need to go into the directory to
2019 * determine if it is empty (because with DIR_HIDE_EMPTY_DIRECTORIES,
2020 * an empty directory should be path_none instead of path_excluded or
2021 * path_untracked).
2023 check_only = ((dir->flags & DIR_HIDE_EMPTY_DIRECTORIES) &&
2024 !(dir->flags & DIR_SHOW_IGNORED_TOO));
2027 * However, there's another optimization possible as a subset of
2028 * check_only, based on the cases we have to consider:
2029 * A) Directory matches no exclude patterns:
2030 * * Directory is empty => path_none
2031 * * Directory has an untracked file under it => path_untracked
2032 * * Directory has only ignored files under it => path_excluded
2033 * B) Directory matches an exclude pattern:
2034 * * Directory is empty => path_none
2035 * * Directory has an untracked file under it => path_excluded
2036 * * Directory has only ignored files under it => path_excluded
2037 * In case A, we can exit as soon as we've found an untracked
2038 * file but otherwise have to walk all files. In case B, though,
2039 * we can stop at the first file we find under the directory.
2041 stop_early = check_only && excluded;
2044 * If /every/ file within an untracked directory is ignored, then
2045 * we want to treat the directory as ignored (for e.g. status
2046 * --porcelain), without listing the individual ignored files
2047 * underneath. To do so, we'll save the current ignored_nr, and
2048 * pop all the ones added after it if it turns out the entire
2049 * directory is ignored. Also, when DIR_SHOW_IGNORED_TOO and
2050 * !DIR_KEEP_UNTRACKED_CONTENTS then we don't want to show
2051 * untracked paths so will need to pop all those off the last
2052 * after we traverse.
2054 old_ignored_nr = dir->ignored_nr;
2055 old_untracked_nr = dir->nr;
2057 /* Actually recurse into dirname now, we'll fixup the state later. */
2058 untracked = lookup_untracked(dir->untracked, untracked,
2059 dirname + baselen, len - baselen);
2060 state = read_directory_recursive(dir, istate, dirname, len, untracked,
2061 check_only, stop_early, pathspec);
2063 /* There are a variety of reasons we may need to fixup the state... */
2064 if (state == path_excluded) {
2065 /* state == path_excluded implies all paths under
2066 * dirname were ignored...
2068 * if running e.g. `git status --porcelain --ignored=matching`,
2069 * then we want to see the subpaths that are ignored.
2071 * if running e.g. just `git status --porcelain`, then
2072 * we just want the directory itself to be listed as ignored
2073 * and not the individual paths underneath.
2075 int want_ignored_subpaths =
2076 ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
2077 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING));
2079 if (want_ignored_subpaths) {
2081 * with --ignored=matching, we want the subpaths
2082 * INSTEAD of the directory itself.
2084 state = path_none;
2085 } else {
2086 int i;
2087 for (i = old_ignored_nr + 1; i<dir->ignored_nr; ++i)
2088 FREE_AND_NULL(dir->ignored[i]);
2089 dir->ignored_nr = old_ignored_nr;
2094 * We may need to ignore some of the untracked paths we found while
2095 * traversing subdirectories.
2097 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
2098 !(dir->flags & DIR_KEEP_UNTRACKED_CONTENTS)) {
2099 int i;
2100 for (i = old_untracked_nr + 1; i<dir->nr; ++i)
2101 FREE_AND_NULL(dir->entries[i]);
2102 dir->nr = old_untracked_nr;
2106 * If there is nothing under the current directory and we are not
2107 * hiding empty directories, then we need to report on the
2108 * untracked or ignored status of the directory itself.
2110 if (state == path_none && !(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
2111 state = excluded ? path_excluded : path_untracked;
2113 return state;
2117 * This is an inexact early pruning of any recursive directory
2118 * reading - if the path cannot possibly be in the pathspec,
2119 * return true, and we'll skip it early.
2121 static int simplify_away(const char *path, int pathlen,
2122 const struct pathspec *pathspec)
2124 int i;
2126 if (!pathspec || !pathspec->nr)
2127 return 0;
2129 GUARD_PATHSPEC(pathspec,
2130 PATHSPEC_FROMTOP |
2131 PATHSPEC_MAXDEPTH |
2132 PATHSPEC_LITERAL |
2133 PATHSPEC_GLOB |
2134 PATHSPEC_ICASE |
2135 PATHSPEC_EXCLUDE |
2136 PATHSPEC_ATTR);
2138 for (i = 0; i < pathspec->nr; i++) {
2139 const struct pathspec_item *item = &pathspec->items[i];
2140 int len = item->nowildcard_len;
2142 if (len > pathlen)
2143 len = pathlen;
2144 if (!ps_strncmp(item, item->match, path, len))
2145 return 0;
2148 return 1;
2152 * This function tells us whether an excluded path matches a
2153 * list of "interesting" pathspecs. That is, whether a path matched
2154 * by any of the pathspecs could possibly be ignored by excluding
2155 * the specified path. This can happen if:
2157 * 1. the path is mentioned explicitly in the pathspec
2159 * 2. the path is a directory prefix of some element in the
2160 * pathspec
2162 static int exclude_matches_pathspec(const char *path, int pathlen,
2163 const struct pathspec *pathspec)
2165 int i;
2167 if (!pathspec || !pathspec->nr)
2168 return 0;
2170 GUARD_PATHSPEC(pathspec,
2171 PATHSPEC_FROMTOP |
2172 PATHSPEC_MAXDEPTH |
2173 PATHSPEC_LITERAL |
2174 PATHSPEC_GLOB |
2175 PATHSPEC_ICASE |
2176 PATHSPEC_EXCLUDE);
2178 for (i = 0; i < pathspec->nr; i++) {
2179 const struct pathspec_item *item = &pathspec->items[i];
2180 int len = item->nowildcard_len;
2182 if (len == pathlen &&
2183 !ps_strncmp(item, item->match, path, pathlen))
2184 return 1;
2185 if (len > pathlen &&
2186 item->match[pathlen] == '/' &&
2187 !ps_strncmp(item, item->match, path, pathlen))
2188 return 1;
2190 return 0;
2193 static int get_index_dtype(struct index_state *istate,
2194 const char *path, int len)
2196 int pos;
2197 const struct cache_entry *ce;
2199 ce = index_file_exists(istate, path, len, 0);
2200 if (ce) {
2201 if (!ce_uptodate(ce))
2202 return DT_UNKNOWN;
2203 if (S_ISGITLINK(ce->ce_mode))
2204 return DT_DIR;
2206 * Nobody actually cares about the
2207 * difference between DT_LNK and DT_REG
2209 return DT_REG;
2212 /* Try to look it up as a directory */
2213 pos = index_name_pos(istate, path, len);
2214 if (pos >= 0)
2215 return DT_UNKNOWN;
2216 pos = -pos-1;
2217 while (pos < istate->cache_nr) {
2218 ce = istate->cache[pos++];
2219 if (strncmp(ce->name, path, len))
2220 break;
2221 if (ce->name[len] > '/')
2222 break;
2223 if (ce->name[len] < '/')
2224 continue;
2225 if (!ce_uptodate(ce))
2226 break; /* continue? */
2227 return DT_DIR;
2229 return DT_UNKNOWN;
2232 static int resolve_dtype(int dtype, struct index_state *istate,
2233 const char *path, int len)
2235 struct stat st;
2237 if (dtype != DT_UNKNOWN)
2238 return dtype;
2239 dtype = get_index_dtype(istate, path, len);
2240 if (dtype != DT_UNKNOWN)
2241 return dtype;
2242 if (lstat(path, &st))
2243 return dtype;
2244 if (S_ISREG(st.st_mode))
2245 return DT_REG;
2246 if (S_ISDIR(st.st_mode))
2247 return DT_DIR;
2248 if (S_ISLNK(st.st_mode))
2249 return DT_LNK;
2250 return dtype;
2253 static enum path_treatment treat_path_fast(struct dir_struct *dir,
2254 struct cached_dir *cdir,
2255 struct index_state *istate,
2256 struct strbuf *path,
2257 int baselen,
2258 const struct pathspec *pathspec)
2261 * WARNING: From this function, you can return path_recurse or you
2262 * can call read_directory_recursive() (or neither), but
2263 * you CAN'T DO BOTH.
2265 strbuf_setlen(path, baselen);
2266 if (!cdir->ucd) {
2267 strbuf_addstr(path, cdir->file);
2268 return path_untracked;
2270 strbuf_addstr(path, cdir->ucd->name);
2271 /* treat_one_path() does this before it calls treat_directory() */
2272 strbuf_complete(path, '/');
2273 if (cdir->ucd->check_only)
2275 * check_only is set as a result of treat_directory() getting
2276 * to its bottom. Verify again the same set of directories
2277 * with check_only set.
2279 return read_directory_recursive(dir, istate, path->buf, path->len,
2280 cdir->ucd, 1, 0, pathspec);
2282 * We get path_recurse in the first run when
2283 * directory_exists_in_index() returns index_nonexistent. We
2284 * are sure that new changes in the index does not impact the
2285 * outcome. Return now.
2287 return path_recurse;
2290 static enum path_treatment treat_path(struct dir_struct *dir,
2291 struct untracked_cache_dir *untracked,
2292 struct cached_dir *cdir,
2293 struct index_state *istate,
2294 struct strbuf *path,
2295 int baselen,
2296 const struct pathspec *pathspec)
2298 int has_path_in_index, dtype, excluded;
2300 if (!cdir->d_name)
2301 return treat_path_fast(dir, cdir, istate, path,
2302 baselen, pathspec);
2303 if (is_dot_or_dotdot(cdir->d_name) || !fspathcmp(cdir->d_name, ".git"))
2304 return path_none;
2305 strbuf_setlen(path, baselen);
2306 strbuf_addstr(path, cdir->d_name);
2307 if (simplify_away(path->buf, path->len, pathspec))
2308 return path_none;
2310 dtype = resolve_dtype(cdir->d_type, istate, path->buf, path->len);
2312 /* Always exclude indexed files */
2313 has_path_in_index = !!index_file_exists(istate, path->buf, path->len,
2314 ignore_case);
2315 if (dtype != DT_DIR && has_path_in_index)
2316 return path_none;
2319 * When we are looking at a directory P in the working tree,
2320 * there are three cases:
2322 * (1) P exists in the index. Everything inside the directory P in
2323 * the working tree needs to go when P is checked out from the
2324 * index.
2326 * (2) P does not exist in the index, but there is P/Q in the index.
2327 * We know P will stay a directory when we check out the contents
2328 * of the index, but we do not know yet if there is a directory
2329 * P/Q in the working tree to be killed, so we need to recurse.
2331 * (3) P does not exist in the index, and there is no P/Q in the index
2332 * to require P to be a directory, either. Only in this case, we
2333 * know that everything inside P will not be killed without
2334 * recursing.
2336 if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
2337 (dtype == DT_DIR) &&
2338 !has_path_in_index &&
2339 (directory_exists_in_index(istate, path->buf, path->len) == index_nonexistent))
2340 return path_none;
2342 excluded = is_excluded(dir, istate, path->buf, &dtype);
2345 * Excluded? If we don't explicitly want to show
2346 * ignored files, ignore it
2348 if (excluded && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
2349 return path_excluded;
2351 switch (dtype) {
2352 default:
2353 return path_none;
2354 case DT_DIR:
2356 * WARNING: Do not ignore/amend the return value from
2357 * treat_directory(), and especially do not change it to return
2358 * path_recurse as that can cause exponential slowdown.
2359 * Instead, modify treat_directory() to return the right value.
2361 strbuf_addch(path, '/');
2362 return treat_directory(dir, istate, untracked,
2363 path->buf, path->len,
2364 baselen, excluded, pathspec);
2365 case DT_REG:
2366 case DT_LNK:
2367 if (pathspec &&
2368 !match_pathspec(istate, pathspec, path->buf, path->len,
2369 0 /* prefix */, NULL /* seen */,
2370 0 /* is_dir */))
2371 return path_none;
2372 if (excluded)
2373 return path_excluded;
2374 return path_untracked;
2378 static void add_untracked(struct untracked_cache_dir *dir, const char *name)
2380 if (!dir)
2381 return;
2382 ALLOC_GROW(dir->untracked, dir->untracked_nr + 1,
2383 dir->untracked_alloc);
2384 dir->untracked[dir->untracked_nr++] = xstrdup(name);
2387 static int valid_cached_dir(struct dir_struct *dir,
2388 struct untracked_cache_dir *untracked,
2389 struct index_state *istate,
2390 struct strbuf *path,
2391 int check_only)
2393 struct stat st;
2395 if (!untracked)
2396 return 0;
2399 * With fsmonitor, we can trust the untracked cache's valid field.
2401 refresh_fsmonitor(istate);
2402 if (!(dir->untracked->use_fsmonitor && untracked->valid)) {
2403 if (lstat(path->len ? path->buf : ".", &st)) {
2404 memset(&untracked->stat_data, 0, sizeof(untracked->stat_data));
2405 return 0;
2407 if (!untracked->valid ||
2408 match_stat_data_racy(istate, &untracked->stat_data, &st)) {
2409 fill_stat_data(&untracked->stat_data, &st);
2410 return 0;
2414 if (untracked->check_only != !!check_only)
2415 return 0;
2418 * prep_exclude will be called eventually on this directory,
2419 * but it's called much later in last_matching_pattern(). We
2420 * need it now to determine the validity of the cache for this
2421 * path. The next calls will be nearly no-op, the way
2422 * prep_exclude() is designed.
2424 if (path->len && path->buf[path->len - 1] != '/') {
2425 strbuf_addch(path, '/');
2426 prep_exclude(dir, istate, path->buf, path->len);
2427 strbuf_setlen(path, path->len - 1);
2428 } else
2429 prep_exclude(dir, istate, path->buf, path->len);
2431 /* hopefully prep_exclude() haven't invalidated this entry... */
2432 return untracked->valid;
2435 static int open_cached_dir(struct cached_dir *cdir,
2436 struct dir_struct *dir,
2437 struct untracked_cache_dir *untracked,
2438 struct index_state *istate,
2439 struct strbuf *path,
2440 int check_only)
2442 const char *c_path;
2444 memset(cdir, 0, sizeof(*cdir));
2445 cdir->untracked = untracked;
2446 if (valid_cached_dir(dir, untracked, istate, path, check_only))
2447 return 0;
2448 c_path = path->len ? path->buf : ".";
2449 cdir->fdir = opendir(c_path);
2450 if (!cdir->fdir)
2451 warning_errno(_("could not open directory '%s'"), c_path);
2452 if (dir->untracked) {
2453 invalidate_directory(dir->untracked, untracked);
2454 dir->untracked->dir_opened++;
2456 if (!cdir->fdir)
2457 return -1;
2458 return 0;
2461 static int read_cached_dir(struct cached_dir *cdir)
2463 struct dirent *de;
2465 if (cdir->fdir) {
2466 de = readdir_skip_dot_and_dotdot(cdir->fdir);
2467 if (!de) {
2468 cdir->d_name = NULL;
2469 cdir->d_type = DT_UNKNOWN;
2470 return -1;
2472 cdir->d_name = de->d_name;
2473 cdir->d_type = DTYPE(de);
2474 return 0;
2476 while (cdir->nr_dirs < cdir->untracked->dirs_nr) {
2477 struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];
2478 if (!d->recurse) {
2479 cdir->nr_dirs++;
2480 continue;
2482 cdir->ucd = d;
2483 cdir->nr_dirs++;
2484 return 0;
2486 cdir->ucd = NULL;
2487 if (cdir->nr_files < cdir->untracked->untracked_nr) {
2488 struct untracked_cache_dir *d = cdir->untracked;
2489 cdir->file = d->untracked[cdir->nr_files++];
2490 return 0;
2492 return -1;
2495 static void close_cached_dir(struct cached_dir *cdir)
2497 if (cdir->fdir)
2498 closedir(cdir->fdir);
2500 * We have gone through this directory and found no untracked
2501 * entries. Mark it valid.
2503 if (cdir->untracked) {
2504 cdir->untracked->valid = 1;
2505 cdir->untracked->recurse = 1;
2509 static void add_path_to_appropriate_result_list(struct dir_struct *dir,
2510 struct untracked_cache_dir *untracked,
2511 struct cached_dir *cdir,
2512 struct index_state *istate,
2513 struct strbuf *path,
2514 int baselen,
2515 const struct pathspec *pathspec,
2516 enum path_treatment state)
2518 /* add the path to the appropriate result list */
2519 switch (state) {
2520 case path_excluded:
2521 if (dir->flags & DIR_SHOW_IGNORED)
2522 dir_add_name(dir, istate, path->buf, path->len);
2523 else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
2524 ((dir->flags & DIR_COLLECT_IGNORED) &&
2525 exclude_matches_pathspec(path->buf, path->len,
2526 pathspec)))
2527 dir_add_ignored(dir, istate, path->buf, path->len);
2528 break;
2530 case path_untracked:
2531 if (dir->flags & DIR_SHOW_IGNORED)
2532 break;
2533 dir_add_name(dir, istate, path->buf, path->len);
2534 if (cdir->fdir)
2535 add_untracked(untracked, path->buf + baselen);
2536 break;
2538 default:
2539 break;
2544 * Read a directory tree. We currently ignore anything but
2545 * directories, regular files and symlinks. That's because git
2546 * doesn't handle them at all yet. Maybe that will change some
2547 * day.
2549 * Also, we ignore the name ".git" (even if it is not a directory).
2550 * That likely will not change.
2552 * If 'stop_at_first_file' is specified, 'path_excluded' is returned
2553 * to signal that a file was found. This is the least significant value that
2554 * indicates that a file was encountered that does not depend on the order of
2555 * whether an untracked or excluded path was encountered first.
2557 * Returns the most significant path_treatment value encountered in the scan.
2558 * If 'stop_at_first_file' is specified, `path_excluded` is the most
2559 * significant path_treatment value that will be returned.
2562 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
2563 struct index_state *istate, const char *base, int baselen,
2564 struct untracked_cache_dir *untracked, int check_only,
2565 int stop_at_first_file, const struct pathspec *pathspec)
2568 * WARNING: Do NOT recurse unless path_recurse is returned from
2569 * treat_path(). Recursing on any other return value
2570 * can result in exponential slowdown.
2572 struct cached_dir cdir;
2573 enum path_treatment state, subdir_state, dir_state = path_none;
2574 struct strbuf path = STRBUF_INIT;
2576 strbuf_add(&path, base, baselen);
2578 if (open_cached_dir(&cdir, dir, untracked, istate, &path, check_only))
2579 goto out;
2580 dir->internal.visited_directories++;
2582 if (untracked)
2583 untracked->check_only = !!check_only;
2585 while (!read_cached_dir(&cdir)) {
2586 /* check how the file or directory should be treated */
2587 state = treat_path(dir, untracked, &cdir, istate, &path,
2588 baselen, pathspec);
2589 dir->internal.visited_paths++;
2591 if (state > dir_state)
2592 dir_state = state;
2594 /* recurse into subdir if instructed by treat_path */
2595 if (state == path_recurse) {
2596 struct untracked_cache_dir *ud;
2597 ud = lookup_untracked(dir->untracked,
2598 untracked,
2599 path.buf + baselen,
2600 path.len - baselen);
2601 subdir_state =
2602 read_directory_recursive(dir, istate, path.buf,
2603 path.len, ud,
2604 check_only, stop_at_first_file, pathspec);
2605 if (subdir_state > dir_state)
2606 dir_state = subdir_state;
2608 if (pathspec &&
2609 !match_pathspec(istate, pathspec, path.buf, path.len,
2610 0 /* prefix */, NULL,
2611 0 /* do NOT special case dirs */))
2612 state = path_none;
2615 if (check_only) {
2616 if (stop_at_first_file) {
2618 * If stopping at first file, then
2619 * signal that a file was found by
2620 * returning `path_excluded`. This is
2621 * to return a consistent value
2622 * regardless of whether an ignored or
2623 * excluded file happened to be
2624 * encountered 1st.
2626 * In current usage, the
2627 * `stop_at_first_file` is passed when
2628 * an ancestor directory has matched
2629 * an exclude pattern, so any found
2630 * files will be excluded.
2632 if (dir_state >= path_excluded) {
2633 dir_state = path_excluded;
2634 break;
2638 /* abort early if maximum state has been reached */
2639 if (dir_state == path_untracked) {
2640 if (cdir.fdir)
2641 add_untracked(untracked, path.buf + baselen);
2642 break;
2644 /* skip the add_path_to_appropriate_result_list() */
2645 continue;
2648 add_path_to_appropriate_result_list(dir, untracked, &cdir,
2649 istate, &path, baselen,
2650 pathspec, state);
2652 close_cached_dir(&cdir);
2653 out:
2654 strbuf_release(&path);
2656 return dir_state;
2659 int cmp_dir_entry(const void *p1, const void *p2)
2661 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
2662 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
2664 return name_compare(e1->name, e1->len, e2->name, e2->len);
2667 /* check if *out lexically strictly contains *in */
2668 int check_dir_entry_contains(const struct dir_entry *out, const struct dir_entry *in)
2670 return (out->len < in->len) &&
2671 (out->name[out->len - 1] == '/') &&
2672 !memcmp(out->name, in->name, out->len);
2675 static int treat_leading_path(struct dir_struct *dir,
2676 struct index_state *istate,
2677 const char *path, int len,
2678 const struct pathspec *pathspec)
2680 struct strbuf sb = STRBUF_INIT;
2681 struct strbuf subdir = STRBUF_INIT;
2682 int prevlen, baselen;
2683 const char *cp;
2684 struct cached_dir cdir;
2685 enum path_treatment state = path_none;
2688 * For each directory component of path, we are going to check whether
2689 * that path is relevant given the pathspec. For example, if path is
2690 * foo/bar/baz/
2691 * then we will ask treat_path() whether we should go into foo, then
2692 * whether we should go into bar, then whether baz is relevant.
2693 * Checking each is important because e.g. if path is
2694 * .git/info/
2695 * then we need to check .git to know we shouldn't traverse it.
2696 * If the return from treat_path() is:
2697 * * path_none, for any path, we return false.
2698 * * path_recurse, for all path components, we return true
2699 * * <anything else> for some intermediate component, we make sure
2700 * to add that path to the relevant list but return false
2701 * signifying that we shouldn't recurse into it.
2704 while (len && path[len - 1] == '/')
2705 len--;
2706 if (!len)
2707 return 1;
2709 memset(&cdir, 0, sizeof(cdir));
2710 cdir.d_type = DT_DIR;
2711 baselen = 0;
2712 prevlen = 0;
2713 while (1) {
2714 prevlen = baselen + !!baselen;
2715 cp = path + prevlen;
2716 cp = memchr(cp, '/', path + len - cp);
2717 if (!cp)
2718 baselen = len;
2719 else
2720 baselen = cp - path;
2721 strbuf_reset(&sb);
2722 strbuf_add(&sb, path, baselen);
2723 if (!is_directory(sb.buf))
2724 break;
2725 strbuf_reset(&sb);
2726 strbuf_add(&sb, path, prevlen);
2727 strbuf_reset(&subdir);
2728 strbuf_add(&subdir, path+prevlen, baselen-prevlen);
2729 cdir.d_name = subdir.buf;
2730 state = treat_path(dir, NULL, &cdir, istate, &sb, prevlen, pathspec);
2732 if (state != path_recurse)
2733 break; /* do not recurse into it */
2734 if (len <= baselen)
2735 break; /* finished checking */
2737 add_path_to_appropriate_result_list(dir, NULL, &cdir, istate,
2738 &sb, baselen, pathspec,
2739 state);
2741 strbuf_release(&subdir);
2742 strbuf_release(&sb);
2743 return state == path_recurse;
2746 static const char *get_ident_string(void)
2748 static struct strbuf sb = STRBUF_INIT;
2749 struct utsname uts;
2751 if (sb.len)
2752 return sb.buf;
2753 if (uname(&uts) < 0)
2754 die_errno(_("failed to get kernel name and information"));
2755 strbuf_addf(&sb, "Location %s, system %s", get_git_work_tree(),
2756 uts.sysname);
2757 return sb.buf;
2760 static int ident_in_untracked(const struct untracked_cache *uc)
2763 * Previous git versions may have saved many NUL separated
2764 * strings in the "ident" field, but it is insane to manage
2765 * many locations, so just take care of the first one.
2768 return !strcmp(uc->ident.buf, get_ident_string());
2771 static void set_untracked_ident(struct untracked_cache *uc)
2773 strbuf_reset(&uc->ident);
2774 strbuf_addstr(&uc->ident, get_ident_string());
2777 * This strbuf used to contain a list of NUL separated
2778 * strings, so save NUL too for backward compatibility.
2780 strbuf_addch(&uc->ident, 0);
2783 static unsigned new_untracked_cache_flags(struct index_state *istate)
2785 struct repository *repo = istate->repo;
2786 char *val;
2789 * This logic is coordinated with the setting of these flags in
2790 * wt-status.c#wt_status_collect_untracked(), and the evaluation
2791 * of the config setting in commit.c#git_status_config()
2793 if (!repo_config_get_string(repo, "status.showuntrackedfiles", &val) &&
2794 !strcmp(val, "all"))
2795 return 0;
2798 * The default, if "all" is not set, is "normal" - leading us here.
2799 * If the value is "none" then it really doesn't matter.
2801 return DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;
2804 static void new_untracked_cache(struct index_state *istate, int flags)
2806 struct untracked_cache *uc = xcalloc(1, sizeof(*uc));
2807 strbuf_init(&uc->ident, 100);
2808 uc->exclude_per_dir = ".gitignore";
2809 uc->dir_flags = flags >= 0 ? flags : new_untracked_cache_flags(istate);
2810 set_untracked_ident(uc);
2811 istate->untracked = uc;
2812 istate->cache_changed |= UNTRACKED_CHANGED;
2815 void add_untracked_cache(struct index_state *istate)
2817 if (!istate->untracked) {
2818 new_untracked_cache(istate, -1);
2819 } else {
2820 if (!ident_in_untracked(istate->untracked)) {
2821 free_untracked_cache(istate->untracked);
2822 new_untracked_cache(istate, -1);
2827 void remove_untracked_cache(struct index_state *istate)
2829 if (istate->untracked) {
2830 free_untracked_cache(istate->untracked);
2831 istate->untracked = NULL;
2832 istate->cache_changed |= UNTRACKED_CHANGED;
2836 static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,
2837 int base_len,
2838 const struct pathspec *pathspec,
2839 struct index_state *istate)
2841 struct untracked_cache_dir *root;
2842 static int untracked_cache_disabled = -1;
2844 if (!dir->untracked)
2845 return NULL;
2846 if (untracked_cache_disabled < 0)
2847 untracked_cache_disabled = git_env_bool("GIT_DISABLE_UNTRACKED_CACHE", 0);
2848 if (untracked_cache_disabled)
2849 return NULL;
2852 * We only support $GIT_DIR/info/exclude and core.excludesfile
2853 * as the global ignore rule files. Any other additions
2854 * (e.g. from command line) invalidate the cache. This
2855 * condition also catches running setup_standard_excludes()
2856 * before setting dir->untracked!
2858 if (dir->internal.unmanaged_exclude_files)
2859 return NULL;
2862 * Optimize for the main use case only: whole-tree git
2863 * status. More work involved in treat_leading_path() if we
2864 * use cache on just a subset of the worktree. pathspec
2865 * support could make the matter even worse.
2867 if (base_len || (pathspec && pathspec->nr))
2868 return NULL;
2870 /* We don't support collecting ignore files */
2871 if (dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |
2872 DIR_COLLECT_IGNORED))
2873 return NULL;
2876 * If we use .gitignore in the cache and now you change it to
2877 * .gitexclude, everything will go wrong.
2879 if (dir->exclude_per_dir != dir->untracked->exclude_per_dir &&
2880 strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))
2881 return NULL;
2884 * EXC_CMDL is not considered in the cache. If people set it,
2885 * skip the cache.
2887 if (dir->internal.exclude_list_group[EXC_CMDL].nr)
2888 return NULL;
2890 if (!ident_in_untracked(dir->untracked)) {
2891 warning(_("untracked cache is disabled on this system or location"));
2892 return NULL;
2896 * If the untracked structure we received does not have the same flags
2897 * as requested in this run, we're going to need to either discard the
2898 * existing structure (and potentially later recreate), or bypass the
2899 * untracked cache mechanism for this run.
2901 if (dir->flags != dir->untracked->dir_flags) {
2903 * If the untracked structure we received does not have the same flags
2904 * as configured, then we need to reset / create a new "untracked"
2905 * structure to match the new config.
2907 * Keeping the saved and used untracked cache consistent with the
2908 * configuration provides an opportunity for frequent users of
2909 * "git status -uall" to leverage the untracked cache by aligning their
2910 * configuration - setting "status.showuntrackedfiles" to "all" or
2911 * "normal" as appropriate.
2913 * Previously using -uall (or setting "status.showuntrackedfiles" to
2914 * "all") was incompatible with untracked cache and *consistently*
2915 * caused surprisingly bad performance (with fscache and fsmonitor
2916 * enabled) on Windows.
2918 * IMPROVEMENT OPPORTUNITY: If we reworked the untracked cache storage
2919 * to not be as bound up with the desired output in a given run,
2920 * and instead iterated through and stored enough information to
2921 * correctly serve both "modes", then users could get peak performance
2922 * with or without '-uall' regardless of their
2923 * "status.showuntrackedfiles" config.
2925 if (dir->untracked->dir_flags != new_untracked_cache_flags(istate)) {
2926 free_untracked_cache(istate->untracked);
2927 new_untracked_cache(istate, dir->flags);
2928 dir->untracked = istate->untracked;
2930 else {
2932 * Current untracked cache data is consistent with config, but not
2933 * usable in this request/run; just bypass untracked cache.
2935 return NULL;
2939 if (!dir->untracked->root) {
2940 /* Untracked cache existed but is not initialized; fix that */
2941 FLEX_ALLOC_STR(dir->untracked->root, name, "");
2942 istate->cache_changed |= UNTRACKED_CHANGED;
2945 /* Validate $GIT_DIR/info/exclude and core.excludesfile */
2946 root = dir->untracked->root;
2947 if (!oideq(&dir->internal.ss_info_exclude.oid,
2948 &dir->untracked->ss_info_exclude.oid)) {
2949 invalidate_gitignore(dir->untracked, root);
2950 dir->untracked->ss_info_exclude = dir->internal.ss_info_exclude;
2952 if (!oideq(&dir->internal.ss_excludes_file.oid,
2953 &dir->untracked->ss_excludes_file.oid)) {
2954 invalidate_gitignore(dir->untracked, root);
2955 dir->untracked->ss_excludes_file = dir->internal.ss_excludes_file;
2958 /* Make sure this directory is not dropped out at saving phase */
2959 root->recurse = 1;
2960 return root;
2963 static void emit_traversal_statistics(struct dir_struct *dir,
2964 struct repository *repo,
2965 const char *path,
2966 int path_len)
2968 if (!trace2_is_enabled())
2969 return;
2971 if (!path_len) {
2972 trace2_data_string("read_directory", repo, "path", "");
2973 } else {
2974 struct strbuf tmp = STRBUF_INIT;
2975 strbuf_add(&tmp, path, path_len);
2976 trace2_data_string("read_directory", repo, "path", tmp.buf);
2977 strbuf_release(&tmp);
2980 trace2_data_intmax("read_directory", repo,
2981 "directories-visited", dir->internal.visited_directories);
2982 trace2_data_intmax("read_directory", repo,
2983 "paths-visited", dir->internal.visited_paths);
2985 if (!dir->untracked)
2986 return;
2987 trace2_data_intmax("read_directory", repo,
2988 "node-creation", dir->untracked->dir_created);
2989 trace2_data_intmax("read_directory", repo,
2990 "gitignore-invalidation",
2991 dir->untracked->gitignore_invalidated);
2992 trace2_data_intmax("read_directory", repo,
2993 "directory-invalidation",
2994 dir->untracked->dir_invalidated);
2995 trace2_data_intmax("read_directory", repo,
2996 "opendir", dir->untracked->dir_opened);
2999 int read_directory(struct dir_struct *dir, struct index_state *istate,
3000 const char *path, int len, const struct pathspec *pathspec)
3002 struct untracked_cache_dir *untracked;
3004 trace2_region_enter("dir", "read_directory", istate->repo);
3005 dir->internal.visited_paths = 0;
3006 dir->internal.visited_directories = 0;
3008 if (has_symlink_leading_path(path, len)) {
3009 trace2_region_leave("dir", "read_directory", istate->repo);
3010 return dir->nr;
3013 untracked = validate_untracked_cache(dir, len, pathspec, istate);
3014 if (!untracked)
3016 * make sure untracked cache code path is disabled,
3017 * e.g. prep_exclude()
3019 dir->untracked = NULL;
3020 if (!len || treat_leading_path(dir, istate, path, len, pathspec))
3021 read_directory_recursive(dir, istate, path, len, untracked, 0, 0, pathspec);
3022 QSORT(dir->entries, dir->nr, cmp_dir_entry);
3023 QSORT(dir->ignored, dir->ignored_nr, cmp_dir_entry);
3025 emit_traversal_statistics(dir, istate->repo, path, len);
3027 trace2_region_leave("dir", "read_directory", istate->repo);
3028 if (dir->untracked) {
3029 static int force_untracked_cache = -1;
3031 if (force_untracked_cache < 0)
3032 force_untracked_cache =
3033 git_env_bool("GIT_FORCE_UNTRACKED_CACHE", -1);
3034 if (force_untracked_cache < 0)
3035 force_untracked_cache = (istate->repo->settings.core_untracked_cache == UNTRACKED_CACHE_WRITE);
3036 if (force_untracked_cache &&
3037 dir->untracked == istate->untracked &&
3038 (dir->untracked->dir_opened ||
3039 dir->untracked->gitignore_invalidated ||
3040 dir->untracked->dir_invalidated))
3041 istate->cache_changed |= UNTRACKED_CHANGED;
3042 if (dir->untracked != istate->untracked) {
3043 FREE_AND_NULL(dir->untracked);
3047 return dir->nr;
3050 int file_exists(const char *f)
3052 struct stat sb;
3053 return lstat(f, &sb) == 0;
3056 int repo_file_exists(struct repository *repo, const char *path)
3058 if (repo != the_repository)
3059 BUG("do not know how to check file existence in arbitrary repo");
3061 return file_exists(path);
3064 static int cmp_icase(char a, char b)
3066 if (a == b)
3067 return 0;
3068 if (ignore_case)
3069 return toupper(a) - toupper(b);
3070 return a - b;
3074 * Given two normalized paths (a trailing slash is ok), if subdir is
3075 * outside dir, return -1. Otherwise return the offset in subdir that
3076 * can be used as relative path to dir.
3078 int dir_inside_of(const char *subdir, const char *dir)
3080 int offset = 0;
3082 assert(dir && subdir && *dir && *subdir);
3084 while (*dir && *subdir && !cmp_icase(*dir, *subdir)) {
3085 dir++;
3086 subdir++;
3087 offset++;
3090 /* hel[p]/me vs hel[l]/yeah */
3091 if (*dir && *subdir)
3092 return -1;
3094 if (!*subdir)
3095 return !*dir ? offset : -1; /* same dir */
3097 /* foo/[b]ar vs foo/[] */
3098 if (is_dir_sep(dir[-1]))
3099 return is_dir_sep(subdir[-1]) ? offset : -1;
3101 /* foo[/]bar vs foo[] */
3102 return is_dir_sep(*subdir) ? offset + 1 : -1;
3105 int is_inside_dir(const char *dir)
3107 char *cwd;
3108 int rc;
3110 if (!dir)
3111 return 0;
3113 cwd = xgetcwd();
3114 rc = (dir_inside_of(cwd, dir) >= 0);
3115 free(cwd);
3116 return rc;
3119 int is_empty_dir(const char *path)
3121 DIR *dir = opendir(path);
3122 struct dirent *e;
3123 int ret = 1;
3125 if (!dir)
3126 return 0;
3128 e = readdir_skip_dot_and_dotdot(dir);
3129 if (e)
3130 ret = 0;
3132 closedir(dir);
3133 return ret;
3136 char *git_url_basename(const char *repo, int is_bundle, int is_bare)
3138 const char *end = repo + strlen(repo), *start, *ptr;
3139 size_t len;
3140 char *dir;
3143 * Skip scheme.
3145 start = strstr(repo, "://");
3146 if (!start)
3147 start = repo;
3148 else
3149 start += 3;
3152 * Skip authentication data. The stripping does happen
3153 * greedily, such that we strip up to the last '@' inside
3154 * the host part.
3156 for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
3157 if (*ptr == '@')
3158 start = ptr + 1;
3162 * Strip trailing spaces, slashes and /.git
3164 while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
3165 end--;
3166 if (end - start > 5 && is_dir_sep(end[-5]) &&
3167 !strncmp(end - 4, ".git", 4)) {
3168 end -= 5;
3169 while (start < end && is_dir_sep(end[-1]))
3170 end--;
3174 * It should not be possible to overflow `ptrdiff_t` by passing in an
3175 * insanely long URL, but GCC does not know that and will complain
3176 * without this check.
3178 if (end - start < 0)
3179 die(_("No directory name could be guessed.\n"
3180 "Please specify a directory on the command line"));
3183 * Strip trailing port number if we've got only a
3184 * hostname (that is, there is no dir separator but a
3185 * colon). This check is required such that we do not
3186 * strip URI's like '/foo/bar:2222.git', which should
3187 * result in a dir '2222' being guessed due to backwards
3188 * compatibility.
3190 if (memchr(start, '/', end - start) == NULL
3191 && memchr(start, ':', end - start) != NULL) {
3192 ptr = end;
3193 while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
3194 ptr--;
3195 if (start < ptr && ptr[-1] == ':')
3196 end = ptr - 1;
3200 * Find last component. To remain backwards compatible we
3201 * also regard colons as path separators, such that
3202 * cloning a repository 'foo:bar.git' would result in a
3203 * directory 'bar' being guessed.
3205 ptr = end;
3206 while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
3207 ptr--;
3208 start = ptr;
3211 * Strip .{bundle,git}.
3213 len = end - start;
3214 strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
3216 if (!len || (len == 1 && *start == '/'))
3217 die(_("No directory name could be guessed.\n"
3218 "Please specify a directory on the command line"));
3220 if (is_bare)
3221 dir = xstrfmt("%.*s.git", (int)len, start);
3222 else
3223 dir = xstrndup(start, len);
3225 * Replace sequences of 'control' characters and whitespace
3226 * with one ascii space, remove leading and trailing spaces.
3228 if (*dir) {
3229 char *out = dir;
3230 int prev_space = 1 /* strip leading whitespace */;
3231 for (end = dir; *end; ++end) {
3232 char ch = *end;
3233 if ((unsigned char)ch < '\x20')
3234 ch = '\x20';
3235 if (isspace(ch)) {
3236 if (prev_space)
3237 continue;
3238 prev_space = 1;
3239 } else
3240 prev_space = 0;
3241 *out++ = ch;
3243 *out = '\0';
3244 if (out > dir && prev_space)
3245 out[-1] = '\0';
3247 return dir;
3250 void strip_dir_trailing_slashes(char *dir)
3252 char *end = dir + strlen(dir);
3254 while (dir < end - 1 && is_dir_sep(end[-1]))
3255 end--;
3256 *end = '\0';
3259 static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
3261 DIR *dir;
3262 struct dirent *e;
3263 int ret = 0, original_len = path->len, len, kept_down = 0;
3264 int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
3265 int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
3266 int purge_original_cwd = (flag & REMOVE_DIR_PURGE_ORIGINAL_CWD);
3267 struct object_id submodule_head;
3269 if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
3270 !resolve_gitlink_ref(path->buf, "HEAD", &submodule_head)) {
3271 /* Do not descend and nuke a nested git work tree. */
3272 if (kept_up)
3273 *kept_up = 1;
3274 return 0;
3277 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
3278 dir = opendir(path->buf);
3279 if (!dir) {
3280 if (errno == ENOENT)
3281 return keep_toplevel ? -1 : 0;
3282 else if (errno == EACCES && !keep_toplevel)
3284 * An empty dir could be removable even if it
3285 * is unreadable:
3287 return rmdir(path->buf);
3288 else
3289 return -1;
3291 strbuf_complete(path, '/');
3293 len = path->len;
3294 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
3295 struct stat st;
3297 strbuf_setlen(path, len);
3298 strbuf_addstr(path, e->d_name);
3299 if (lstat(path->buf, &st)) {
3300 if (errno == ENOENT)
3302 * file disappeared, which is what we
3303 * wanted anyway
3305 continue;
3306 /* fall through */
3307 } else if (S_ISDIR(st.st_mode)) {
3308 if (!remove_dir_recurse(path, flag, &kept_down))
3309 continue; /* happy */
3310 } else if (!only_empty &&
3311 (!unlink(path->buf) || errno == ENOENT)) {
3312 continue; /* happy, too */
3315 /* path too long, stat fails, or non-directory still exists */
3316 ret = -1;
3317 break;
3319 closedir(dir);
3321 strbuf_setlen(path, original_len);
3322 if (!ret && !keep_toplevel && !kept_down) {
3323 if (!purge_original_cwd &&
3324 startup_info->original_cwd &&
3325 !strcmp(startup_info->original_cwd, path->buf))
3326 ret = -1; /* Do not remove current working directory */
3327 else
3328 ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1;
3329 } else if (kept_up)
3331 * report the uplevel that it is not an error that we
3332 * did not rmdir() our directory.
3334 *kept_up = !ret;
3335 return ret;
3338 int remove_dir_recursively(struct strbuf *path, int flag)
3340 return remove_dir_recurse(path, flag, NULL);
3343 static GIT_PATH_FUNC(git_path_info_exclude, "info/exclude")
3345 void setup_standard_excludes(struct dir_struct *dir)
3347 dir->exclude_per_dir = ".gitignore";
3349 /* core.excludesfile defaulting to $XDG_CONFIG_HOME/git/ignore */
3350 if (!excludes_file)
3351 excludes_file = xdg_config_home("ignore");
3352 if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
3353 add_patterns_from_file_1(dir, excludes_file,
3354 dir->untracked ? &dir->internal.ss_excludes_file : NULL);
3356 /* per repository user preference */
3357 if (startup_info->have_repository) {
3358 const char *path = git_path_info_exclude();
3359 if (!access_or_warn(path, R_OK, 0))
3360 add_patterns_from_file_1(dir, path,
3361 dir->untracked ? &dir->internal.ss_info_exclude : NULL);
3365 char *get_sparse_checkout_filename(void)
3367 return git_pathdup("info/sparse-checkout");
3370 int get_sparse_checkout_patterns(struct pattern_list *pl)
3372 int res;
3373 char *sparse_filename = get_sparse_checkout_filename();
3375 pl->use_cone_patterns = core_sparse_checkout_cone;
3376 res = add_patterns_from_file_to_list(sparse_filename, "", 0, pl, NULL, 0);
3378 free(sparse_filename);
3379 return res;
3382 int remove_path(const char *name)
3384 char *slash;
3386 if (unlink(name) && !is_missing_file_error(errno))
3387 return -1;
3389 slash = strrchr(name, '/');
3390 if (slash) {
3391 char *dirs = xstrdup(name);
3392 slash = dirs + (slash - name);
3393 do {
3394 *slash = '\0';
3395 if (startup_info->original_cwd &&
3396 !strcmp(startup_info->original_cwd, dirs))
3397 break;
3398 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
3399 free(dirs);
3401 return 0;
3405 * Frees memory within dir which was allocated, and resets fields for further
3406 * use. Does not free dir itself.
3408 void dir_clear(struct dir_struct *dir)
3410 int i, j;
3411 struct exclude_list_group *group;
3412 struct pattern_list *pl;
3413 struct exclude_stack *stk;
3414 struct dir_struct new = DIR_INIT;
3416 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
3417 group = &dir->internal.exclude_list_group[i];
3418 for (j = 0; j < group->nr; j++) {
3419 pl = &group->pl[j];
3420 if (i == EXC_DIRS)
3421 free((char *)pl->src);
3422 clear_pattern_list(pl);
3424 free(group->pl);
3427 for (i = 0; i < dir->ignored_nr; i++)
3428 free(dir->ignored[i]);
3429 for (i = 0; i < dir->nr; i++)
3430 free(dir->entries[i]);
3431 free(dir->ignored);
3432 free(dir->entries);
3434 stk = dir->internal.exclude_stack;
3435 while (stk) {
3436 struct exclude_stack *prev = stk->prev;
3437 free(stk);
3438 stk = prev;
3440 strbuf_release(&dir->internal.basebuf);
3442 memcpy(dir, &new, sizeof(*dir));
3445 struct ondisk_untracked_cache {
3446 struct stat_data info_exclude_stat;
3447 struct stat_data excludes_file_stat;
3448 uint32_t dir_flags;
3451 #define ouc_offset(x) offsetof(struct ondisk_untracked_cache, x)
3453 struct write_data {
3454 int index; /* number of written untracked_cache_dir */
3455 struct ewah_bitmap *check_only; /* from untracked_cache_dir */
3456 struct ewah_bitmap *valid; /* from untracked_cache_dir */
3457 struct ewah_bitmap *sha1_valid; /* set if exclude_sha1 is not null */
3458 struct strbuf out;
3459 struct strbuf sb_stat;
3460 struct strbuf sb_sha1;
3463 static void stat_data_to_disk(struct stat_data *to, const struct stat_data *from)
3465 to->sd_ctime.sec = htonl(from->sd_ctime.sec);
3466 to->sd_ctime.nsec = htonl(from->sd_ctime.nsec);
3467 to->sd_mtime.sec = htonl(from->sd_mtime.sec);
3468 to->sd_mtime.nsec = htonl(from->sd_mtime.nsec);
3469 to->sd_dev = htonl(from->sd_dev);
3470 to->sd_ino = htonl(from->sd_ino);
3471 to->sd_uid = htonl(from->sd_uid);
3472 to->sd_gid = htonl(from->sd_gid);
3473 to->sd_size = htonl(from->sd_size);
3476 static void write_one_dir(struct untracked_cache_dir *untracked,
3477 struct write_data *wd)
3479 struct stat_data stat_data;
3480 struct strbuf *out = &wd->out;
3481 unsigned char intbuf[16];
3482 unsigned int intlen, value;
3483 int i = wd->index++;
3486 * untracked_nr should be reset whenever valid is clear, but
3487 * for safety..
3489 if (!untracked->valid) {
3490 untracked->untracked_nr = 0;
3491 untracked->check_only = 0;
3494 if (untracked->check_only)
3495 ewah_set(wd->check_only, i);
3496 if (untracked->valid) {
3497 ewah_set(wd->valid, i);
3498 stat_data_to_disk(&stat_data, &untracked->stat_data);
3499 strbuf_add(&wd->sb_stat, &stat_data, sizeof(stat_data));
3501 if (!is_null_oid(&untracked->exclude_oid)) {
3502 ewah_set(wd->sha1_valid, i);
3503 strbuf_add(&wd->sb_sha1, untracked->exclude_oid.hash,
3504 the_hash_algo->rawsz);
3507 intlen = encode_varint(untracked->untracked_nr, intbuf);
3508 strbuf_add(out, intbuf, intlen);
3510 /* skip non-recurse directories */
3511 for (i = 0, value = 0; i < untracked->dirs_nr; i++)
3512 if (untracked->dirs[i]->recurse)
3513 value++;
3514 intlen = encode_varint(value, intbuf);
3515 strbuf_add(out, intbuf, intlen);
3517 strbuf_add(out, untracked->name, strlen(untracked->name) + 1);
3519 for (i = 0; i < untracked->untracked_nr; i++)
3520 strbuf_add(out, untracked->untracked[i],
3521 strlen(untracked->untracked[i]) + 1);
3523 for (i = 0; i < untracked->dirs_nr; i++)
3524 if (untracked->dirs[i]->recurse)
3525 write_one_dir(untracked->dirs[i], wd);
3528 void write_untracked_extension(struct strbuf *out, struct untracked_cache *untracked)
3530 struct ondisk_untracked_cache *ouc;
3531 struct write_data wd;
3532 unsigned char varbuf[16];
3533 int varint_len;
3534 const unsigned hashsz = the_hash_algo->rawsz;
3536 CALLOC_ARRAY(ouc, 1);
3537 stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);
3538 stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);
3539 ouc->dir_flags = htonl(untracked->dir_flags);
3541 varint_len = encode_varint(untracked->ident.len, varbuf);
3542 strbuf_add(out, varbuf, varint_len);
3543 strbuf_addbuf(out, &untracked->ident);
3545 strbuf_add(out, ouc, sizeof(*ouc));
3546 strbuf_add(out, untracked->ss_info_exclude.oid.hash, hashsz);
3547 strbuf_add(out, untracked->ss_excludes_file.oid.hash, hashsz);
3548 strbuf_add(out, untracked->exclude_per_dir, strlen(untracked->exclude_per_dir) + 1);
3549 FREE_AND_NULL(ouc);
3551 if (!untracked->root) {
3552 varint_len = encode_varint(0, varbuf);
3553 strbuf_add(out, varbuf, varint_len);
3554 return;
3557 wd.index = 0;
3558 wd.check_only = ewah_new();
3559 wd.valid = ewah_new();
3560 wd.sha1_valid = ewah_new();
3561 strbuf_init(&wd.out, 1024);
3562 strbuf_init(&wd.sb_stat, 1024);
3563 strbuf_init(&wd.sb_sha1, 1024);
3564 write_one_dir(untracked->root, &wd);
3566 varint_len = encode_varint(wd.index, varbuf);
3567 strbuf_add(out, varbuf, varint_len);
3568 strbuf_addbuf(out, &wd.out);
3569 ewah_serialize_strbuf(wd.valid, out);
3570 ewah_serialize_strbuf(wd.check_only, out);
3571 ewah_serialize_strbuf(wd.sha1_valid, out);
3572 strbuf_addbuf(out, &wd.sb_stat);
3573 strbuf_addbuf(out, &wd.sb_sha1);
3574 strbuf_addch(out, '\0'); /* safe guard for string lists */
3576 ewah_free(wd.valid);
3577 ewah_free(wd.check_only);
3578 ewah_free(wd.sha1_valid);
3579 strbuf_release(&wd.out);
3580 strbuf_release(&wd.sb_stat);
3581 strbuf_release(&wd.sb_sha1);
3584 static void free_untracked(struct untracked_cache_dir *ucd)
3586 int i;
3587 if (!ucd)
3588 return;
3589 for (i = 0; i < ucd->dirs_nr; i++)
3590 free_untracked(ucd->dirs[i]);
3591 for (i = 0; i < ucd->untracked_nr; i++)
3592 free(ucd->untracked[i]);
3593 free(ucd->untracked);
3594 free(ucd->dirs);
3595 free(ucd);
3598 void free_untracked_cache(struct untracked_cache *uc)
3600 if (!uc)
3601 return;
3603 free(uc->exclude_per_dir_to_free);
3604 strbuf_release(&uc->ident);
3605 free_untracked(uc->root);
3606 free(uc);
3609 struct read_data {
3610 int index;
3611 struct untracked_cache_dir **ucd;
3612 struct ewah_bitmap *check_only;
3613 struct ewah_bitmap *valid;
3614 struct ewah_bitmap *sha1_valid;
3615 const unsigned char *data;
3616 const unsigned char *end;
3619 static void stat_data_from_disk(struct stat_data *to, const unsigned char *data)
3621 memcpy(to, data, sizeof(*to));
3622 to->sd_ctime.sec = ntohl(to->sd_ctime.sec);
3623 to->sd_ctime.nsec = ntohl(to->sd_ctime.nsec);
3624 to->sd_mtime.sec = ntohl(to->sd_mtime.sec);
3625 to->sd_mtime.nsec = ntohl(to->sd_mtime.nsec);
3626 to->sd_dev = ntohl(to->sd_dev);
3627 to->sd_ino = ntohl(to->sd_ino);
3628 to->sd_uid = ntohl(to->sd_uid);
3629 to->sd_gid = ntohl(to->sd_gid);
3630 to->sd_size = ntohl(to->sd_size);
3633 static int read_one_dir(struct untracked_cache_dir **untracked_,
3634 struct read_data *rd)
3636 struct untracked_cache_dir ud, *untracked;
3637 const unsigned char *data = rd->data, *end = rd->end;
3638 const unsigned char *eos;
3639 unsigned int value;
3640 int i;
3642 memset(&ud, 0, sizeof(ud));
3644 value = decode_varint(&data);
3645 if (data > end)
3646 return -1;
3647 ud.recurse = 1;
3648 ud.untracked_alloc = value;
3649 ud.untracked_nr = value;
3650 if (ud.untracked_nr)
3651 ALLOC_ARRAY(ud.untracked, ud.untracked_nr);
3653 ud.dirs_alloc = ud.dirs_nr = decode_varint(&data);
3654 if (data > end)
3655 return -1;
3656 ALLOC_ARRAY(ud.dirs, ud.dirs_nr);
3658 eos = memchr(data, '\0', end - data);
3659 if (!eos || eos == end)
3660 return -1;
3662 *untracked_ = untracked = xmalloc(st_add3(sizeof(*untracked), eos - data, 1));
3663 memcpy(untracked, &ud, sizeof(ud));
3664 memcpy(untracked->name, data, eos - data + 1);
3665 data = eos + 1;
3667 for (i = 0; i < untracked->untracked_nr; i++) {
3668 eos = memchr(data, '\0', end - data);
3669 if (!eos || eos == end)
3670 return -1;
3671 untracked->untracked[i] = xmemdupz(data, eos - data);
3672 data = eos + 1;
3675 rd->ucd[rd->index++] = untracked;
3676 rd->data = data;
3678 for (i = 0; i < untracked->dirs_nr; i++) {
3679 if (read_one_dir(untracked->dirs + i, rd) < 0)
3680 return -1;
3682 return 0;
3685 static void set_check_only(size_t pos, void *cb)
3687 struct read_data *rd = cb;
3688 struct untracked_cache_dir *ud = rd->ucd[pos];
3689 ud->check_only = 1;
3692 static void read_stat(size_t pos, void *cb)
3694 struct read_data *rd = cb;
3695 struct untracked_cache_dir *ud = rd->ucd[pos];
3696 if (rd->data + sizeof(struct stat_data) > rd->end) {
3697 rd->data = rd->end + 1;
3698 return;
3700 stat_data_from_disk(&ud->stat_data, rd->data);
3701 rd->data += sizeof(struct stat_data);
3702 ud->valid = 1;
3705 static void read_oid(size_t pos, void *cb)
3707 struct read_data *rd = cb;
3708 struct untracked_cache_dir *ud = rd->ucd[pos];
3709 if (rd->data + the_hash_algo->rawsz > rd->end) {
3710 rd->data = rd->end + 1;
3711 return;
3713 oidread(&ud->exclude_oid, rd->data);
3714 rd->data += the_hash_algo->rawsz;
3717 static void load_oid_stat(struct oid_stat *oid_stat, const unsigned char *data,
3718 const unsigned char *sha1)
3720 stat_data_from_disk(&oid_stat->stat, data);
3721 oidread(&oid_stat->oid, sha1);
3722 oid_stat->valid = 1;
3725 struct untracked_cache *read_untracked_extension(const void *data, unsigned long sz)
3727 struct untracked_cache *uc;
3728 struct read_data rd;
3729 const unsigned char *next = data, *end = (const unsigned char *)data + sz;
3730 const char *ident;
3731 int ident_len;
3732 ssize_t len;
3733 const char *exclude_per_dir;
3734 const unsigned hashsz = the_hash_algo->rawsz;
3735 const unsigned offset = sizeof(struct ondisk_untracked_cache);
3736 const unsigned exclude_per_dir_offset = offset + 2 * hashsz;
3738 if (sz <= 1 || end[-1] != '\0')
3739 return NULL;
3740 end--;
3742 ident_len = decode_varint(&next);
3743 if (next + ident_len > end)
3744 return NULL;
3745 ident = (const char *)next;
3746 next += ident_len;
3748 if (next + exclude_per_dir_offset + 1 > end)
3749 return NULL;
3751 CALLOC_ARRAY(uc, 1);
3752 strbuf_init(&uc->ident, ident_len);
3753 strbuf_add(&uc->ident, ident, ident_len);
3754 load_oid_stat(&uc->ss_info_exclude,
3755 next + ouc_offset(info_exclude_stat),
3756 next + offset);
3757 load_oid_stat(&uc->ss_excludes_file,
3758 next + ouc_offset(excludes_file_stat),
3759 next + offset + hashsz);
3760 uc->dir_flags = get_be32(next + ouc_offset(dir_flags));
3761 exclude_per_dir = (const char *)next + exclude_per_dir_offset;
3762 uc->exclude_per_dir = uc->exclude_per_dir_to_free = xstrdup(exclude_per_dir);
3763 /* NUL after exclude_per_dir is covered by sizeof(*ouc) */
3764 next += exclude_per_dir_offset + strlen(exclude_per_dir) + 1;
3765 if (next >= end)
3766 goto done2;
3768 len = decode_varint(&next);
3769 if (next > end || len == 0)
3770 goto done2;
3772 rd.valid = ewah_new();
3773 rd.check_only = ewah_new();
3774 rd.sha1_valid = ewah_new();
3775 rd.data = next;
3776 rd.end = end;
3777 rd.index = 0;
3778 ALLOC_ARRAY(rd.ucd, len);
3780 if (read_one_dir(&uc->root, &rd) || rd.index != len)
3781 goto done;
3783 next = rd.data;
3784 len = ewah_read_mmap(rd.valid, next, end - next);
3785 if (len < 0)
3786 goto done;
3788 next += len;
3789 len = ewah_read_mmap(rd.check_only, next, end - next);
3790 if (len < 0)
3791 goto done;
3793 next += len;
3794 len = ewah_read_mmap(rd.sha1_valid, next, end - next);
3795 if (len < 0)
3796 goto done;
3798 ewah_each_bit(rd.check_only, set_check_only, &rd);
3799 rd.data = next + len;
3800 ewah_each_bit(rd.valid, read_stat, &rd);
3801 ewah_each_bit(rd.sha1_valid, read_oid, &rd);
3802 next = rd.data;
3804 done:
3805 free(rd.ucd);
3806 ewah_free(rd.valid);
3807 ewah_free(rd.check_only);
3808 ewah_free(rd.sha1_valid);
3809 done2:
3810 if (next != end) {
3811 free_untracked_cache(uc);
3812 uc = NULL;
3814 return uc;
3817 static void invalidate_one_directory(struct untracked_cache *uc,
3818 struct untracked_cache_dir *ucd)
3820 uc->dir_invalidated++;
3821 ucd->valid = 0;
3822 ucd->untracked_nr = 0;
3826 * Normally when an entry is added or removed from a directory,
3827 * invalidating that directory is enough. No need to touch its
3828 * ancestors. When a directory is shown as "foo/bar/" in git-status
3829 * however, deleting or adding an entry may have cascading effect.
3831 * Say the "foo/bar/file" has become untracked, we need to tell the
3832 * untracked_cache_dir of "foo" that "bar/" is not an untracked
3833 * directory any more (because "bar" is managed by foo as an untracked
3834 * "file").
3836 * Similarly, if "foo/bar/file" moves from untracked to tracked and it
3837 * was the last untracked entry in the entire "foo", we should show
3838 * "foo/" instead. Which means we have to invalidate past "bar" up to
3839 * "foo".
3841 * This function traverses all directories from root to leaf. If there
3842 * is a chance of one of the above cases happening, we invalidate back
3843 * to root. Otherwise we just invalidate the leaf. There may be a more
3844 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to
3845 * detect these cases and avoid unnecessary invalidation, for example,
3846 * checking for the untracked entry named "bar/" in "foo", but for now
3847 * stick to something safe and simple.
3849 static int invalidate_one_component(struct untracked_cache *uc,
3850 struct untracked_cache_dir *dir,
3851 const char *path, int len)
3853 const char *rest = strchr(path, '/');
3855 if (rest) {
3856 int component_len = rest - path;
3857 struct untracked_cache_dir *d =
3858 lookup_untracked(uc, dir, path, component_len);
3859 int ret =
3860 invalidate_one_component(uc, d, rest + 1,
3861 len - (component_len + 1));
3862 if (ret)
3863 invalidate_one_directory(uc, dir);
3864 return ret;
3867 invalidate_one_directory(uc, dir);
3868 return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;
3871 void untracked_cache_invalidate_path(struct index_state *istate,
3872 const char *path, int safe_path)
3874 if (!istate->untracked || !istate->untracked->root)
3875 return;
3876 if (!safe_path && !verify_path(path, 0))
3877 return;
3878 invalidate_one_component(istate->untracked, istate->untracked->root,
3879 path, strlen(path));
3882 void untracked_cache_remove_from_index(struct index_state *istate,
3883 const char *path)
3885 untracked_cache_invalidate_path(istate, path, 1);
3888 void untracked_cache_add_to_index(struct index_state *istate,
3889 const char *path)
3891 untracked_cache_invalidate_path(istate, path, 1);
3894 static void connect_wt_gitdir_in_nested(const char *sub_worktree,
3895 const char *sub_gitdir)
3897 int i;
3898 struct repository subrepo;
3899 struct strbuf sub_wt = STRBUF_INIT;
3900 struct strbuf sub_gd = STRBUF_INIT;
3902 const struct submodule *sub;
3904 /* If the submodule has no working tree, we can ignore it. */
3905 if (repo_init(&subrepo, sub_gitdir, sub_worktree))
3906 return;
3908 if (repo_read_index(&subrepo) < 0)
3909 die(_("index file corrupt in repo %s"), subrepo.gitdir);
3911 /* TODO: audit for interaction with sparse-index. */
3912 ensure_full_index(subrepo.index);
3913 for (i = 0; i < subrepo.index->cache_nr; i++) {
3914 const struct cache_entry *ce = subrepo.index->cache[i];
3916 if (!S_ISGITLINK(ce->ce_mode))
3917 continue;
3919 while (i + 1 < subrepo.index->cache_nr &&
3920 !strcmp(ce->name, subrepo.index->cache[i + 1]->name))
3922 * Skip entries with the same name in different stages
3923 * to make sure an entry is returned only once.
3925 i++;
3927 sub = submodule_from_path(&subrepo, null_oid(), ce->name);
3928 if (!sub || !is_submodule_active(&subrepo, ce->name))
3929 /* .gitmodules broken or inactive sub */
3930 continue;
3932 strbuf_reset(&sub_wt);
3933 strbuf_reset(&sub_gd);
3934 strbuf_addf(&sub_wt, "%s/%s", sub_worktree, sub->path);
3935 submodule_name_to_gitdir(&sub_gd, &subrepo, sub->name);
3937 connect_work_tree_and_git_dir(sub_wt.buf, sub_gd.buf, 1);
3939 strbuf_release(&sub_wt);
3940 strbuf_release(&sub_gd);
3941 repo_clear(&subrepo);
3944 void connect_work_tree_and_git_dir(const char *work_tree_,
3945 const char *git_dir_,
3946 int recurse_into_nested)
3948 struct strbuf gitfile_sb = STRBUF_INIT;
3949 struct strbuf cfg_sb = STRBUF_INIT;
3950 struct strbuf rel_path = STRBUF_INIT;
3951 char *git_dir, *work_tree;
3953 /* Prepare .git file */
3954 strbuf_addf(&gitfile_sb, "%s/.git", work_tree_);
3955 if (safe_create_leading_directories_const(gitfile_sb.buf))
3956 die(_("could not create directories for %s"), gitfile_sb.buf);
3958 /* Prepare config file */
3959 strbuf_addf(&cfg_sb, "%s/config", git_dir_);
3960 if (safe_create_leading_directories_const(cfg_sb.buf))
3961 die(_("could not create directories for %s"), cfg_sb.buf);
3963 git_dir = real_pathdup(git_dir_, 1);
3964 work_tree = real_pathdup(work_tree_, 1);
3966 /* Write .git file */
3967 write_file(gitfile_sb.buf, "gitdir: %s",
3968 relative_path(git_dir, work_tree, &rel_path));
3969 /* Update core.worktree setting */
3970 git_config_set_in_file(cfg_sb.buf, "core.worktree",
3971 relative_path(work_tree, git_dir, &rel_path));
3973 strbuf_release(&gitfile_sb);
3974 strbuf_release(&cfg_sb);
3975 strbuf_release(&rel_path);
3977 if (recurse_into_nested)
3978 connect_wt_gitdir_in_nested(work_tree, git_dir);
3980 free(work_tree);
3981 free(git_dir);
3985 * Migrate the git directory of the given path from old_git_dir to new_git_dir.
3987 void relocate_gitdir(const char *path, const char *old_git_dir, const char *new_git_dir)
3989 if (rename(old_git_dir, new_git_dir) < 0)
3990 die_errno(_("could not migrate git directory from '%s' to '%s'"),
3991 old_git_dir, new_git_dir);
3993 connect_work_tree_and_git_dir(path, new_git_dir, 0);
3996 int path_match_flags(const char *const str, const enum path_match_flags flags)
3998 const char *p = str;
4000 if (flags & PATH_MATCH_NATIVE &&
4001 flags & PATH_MATCH_XPLATFORM)
4002 BUG("path_match_flags() must get one match kind, not multiple!");
4003 else if (!(flags & PATH_MATCH_KINDS_MASK))
4004 BUG("path_match_flags() must get at least one match kind!");
4006 if (flags & PATH_MATCH_STARTS_WITH_DOT_SLASH &&
4007 flags & PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH)
4008 BUG("path_match_flags() must get one platform kind, not multiple!");
4009 else if (!(flags & PATH_MATCH_PLATFORM_MASK))
4010 BUG("path_match_flags() must get at least one platform kind!");
4012 if (*p++ != '.')
4013 return 0;
4014 if (flags & PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH &&
4015 *p++ != '.')
4016 return 0;
4018 if (flags & PATH_MATCH_NATIVE)
4019 return is_dir_sep(*p);
4020 else if (flags & PATH_MATCH_XPLATFORM)
4021 return is_xplatform_dir_sep(*p);
4022 BUG("unreachable");