diffcore-rename: move old_dir/new_dir definition to plug leak
[git/debian.git] / dir.c
blob313e9324597a1ae1b03b3979be412b86ab63dcd0
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 "cache.h"
9 #include "config.h"
10 #include "dir.h"
11 #include "object-store.h"
12 #include "attr.h"
13 #include "refs.h"
14 #include "wildmatch.h"
15 #include "pathspec.h"
16 #include "utf8.h"
17 #include "varint.h"
18 #include "ewah/ewok.h"
19 #include "fsmonitor.h"
20 #include "submodule-config.h"
23 * Tells read_directory_recursive how a file or directory should be treated.
24 * Values are ordered by significance, e.g. if a directory contains both
25 * excluded and untracked files, it is listed as untracked because
26 * path_untracked > path_excluded.
28 enum path_treatment {
29 path_none = 0,
30 path_recurse,
31 path_excluded,
32 path_untracked
36 * Support data structure for our opendir/readdir/closedir wrappers
38 struct cached_dir {
39 DIR *fdir;
40 struct untracked_cache_dir *untracked;
41 int nr_files;
42 int nr_dirs;
44 const char *d_name;
45 int d_type;
46 const char *file;
47 struct untracked_cache_dir *ucd;
50 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
51 struct index_state *istate, const char *path, int len,
52 struct untracked_cache_dir *untracked,
53 int check_only, int stop_at_first_file, const struct pathspec *pathspec);
54 static int resolve_dtype(int dtype, struct index_state *istate,
55 const char *path, int len);
56 struct dirent *readdir_skip_dot_and_dotdot(DIR *dirp)
58 struct dirent *e;
60 while ((e = readdir(dirp)) != NULL) {
61 if (!is_dot_or_dotdot(e->d_name))
62 break;
64 return e;
67 int count_slashes(const char *s)
69 int cnt = 0;
70 while (*s)
71 if (*s++ == '/')
72 cnt++;
73 return cnt;
76 int fspathcmp(const char *a, const char *b)
78 return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
81 int fspathncmp(const char *a, const char *b, size_t count)
83 return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
86 int git_fnmatch(const struct pathspec_item *item,
87 const char *pattern, const char *string,
88 int prefix)
90 if (prefix > 0) {
91 if (ps_strncmp(item, pattern, string, prefix))
92 return WM_NOMATCH;
93 pattern += prefix;
94 string += prefix;
96 if (item->flags & PATHSPEC_ONESTAR) {
97 int pattern_len = strlen(++pattern);
98 int string_len = strlen(string);
99 return string_len < pattern_len ||
100 ps_strcmp(item, pattern,
101 string + string_len - pattern_len);
103 if (item->magic & PATHSPEC_GLOB)
104 return wildmatch(pattern, string,
105 WM_PATHNAME |
106 (item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0));
107 else
108 /* wildmatch has not learned no FNM_PATHNAME mode yet */
109 return wildmatch(pattern, string,
110 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0);
113 static int fnmatch_icase_mem(const char *pattern, int patternlen,
114 const char *string, int stringlen,
115 int flags)
117 int match_status;
118 struct strbuf pat_buf = STRBUF_INIT;
119 struct strbuf str_buf = STRBUF_INIT;
120 const char *use_pat = pattern;
121 const char *use_str = string;
123 if (pattern[patternlen]) {
124 strbuf_add(&pat_buf, pattern, patternlen);
125 use_pat = pat_buf.buf;
127 if (string[stringlen]) {
128 strbuf_add(&str_buf, string, stringlen);
129 use_str = str_buf.buf;
132 if (ignore_case)
133 flags |= WM_CASEFOLD;
134 match_status = wildmatch(use_pat, use_str, flags);
136 strbuf_release(&pat_buf);
137 strbuf_release(&str_buf);
139 return match_status;
142 static size_t common_prefix_len(const struct pathspec *pathspec)
144 int n;
145 size_t max = 0;
148 * ":(icase)path" is treated as a pathspec full of
149 * wildcard. In other words, only prefix is considered common
150 * prefix. If the pathspec is abc/foo abc/bar, running in
151 * subdir xyz, the common prefix is still xyz, not xyz/abc as
152 * in non-:(icase).
154 GUARD_PATHSPEC(pathspec,
155 PATHSPEC_FROMTOP |
156 PATHSPEC_MAXDEPTH |
157 PATHSPEC_LITERAL |
158 PATHSPEC_GLOB |
159 PATHSPEC_ICASE |
160 PATHSPEC_EXCLUDE |
161 PATHSPEC_ATTR);
163 for (n = 0; n < pathspec->nr; n++) {
164 size_t i = 0, len = 0, item_len;
165 if (pathspec->items[n].magic & PATHSPEC_EXCLUDE)
166 continue;
167 if (pathspec->items[n].magic & PATHSPEC_ICASE)
168 item_len = pathspec->items[n].prefix;
169 else
170 item_len = pathspec->items[n].nowildcard_len;
171 while (i < item_len && (n == 0 || i < max)) {
172 char c = pathspec->items[n].match[i];
173 if (c != pathspec->items[0].match[i])
174 break;
175 if (c == '/')
176 len = i + 1;
177 i++;
179 if (n == 0 || len < max) {
180 max = len;
181 if (!max)
182 break;
185 return max;
189 * Returns a copy of the longest leading path common among all
190 * pathspecs.
192 char *common_prefix(const struct pathspec *pathspec)
194 unsigned long len = common_prefix_len(pathspec);
196 return len ? xmemdupz(pathspec->items[0].match, len) : NULL;
199 int fill_directory(struct dir_struct *dir,
200 struct index_state *istate,
201 const struct pathspec *pathspec)
203 const char *prefix;
204 size_t prefix_len;
206 unsigned exclusive_flags = DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO;
207 if ((dir->flags & exclusive_flags) == exclusive_flags)
208 BUG("DIR_SHOW_IGNORED and DIR_SHOW_IGNORED_TOO are exclusive");
211 * Calculate common prefix for the pathspec, and
212 * use that to optimize the directory walk
214 prefix_len = common_prefix_len(pathspec);
215 prefix = prefix_len ? pathspec->items[0].match : "";
217 /* Read the directory and prune it */
218 read_directory(dir, istate, prefix, prefix_len, pathspec);
220 return prefix_len;
223 int within_depth(const char *name, int namelen,
224 int depth, int max_depth)
226 const char *cp = name, *cpe = name + namelen;
228 while (cp < cpe) {
229 if (*cp++ != '/')
230 continue;
231 depth++;
232 if (depth > max_depth)
233 return 0;
235 return 1;
239 * Read the contents of the blob with the given OID into a buffer.
240 * Append a trailing LF to the end if the last line doesn't have one.
242 * Returns:
243 * -1 when the OID is invalid or unknown or does not refer to a blob.
244 * 0 when the blob is empty.
245 * 1 along with { data, size } of the (possibly augmented) buffer
246 * when successful.
248 * Optionally updates the given oid_stat with the given OID (when valid).
250 static int do_read_blob(const struct object_id *oid, struct oid_stat *oid_stat,
251 size_t *size_out, char **data_out)
253 enum object_type type;
254 unsigned long sz;
255 char *data;
257 *size_out = 0;
258 *data_out = NULL;
260 data = read_object_file(oid, &type, &sz);
261 if (!data || type != OBJ_BLOB) {
262 free(data);
263 return -1;
266 if (oid_stat) {
267 memset(&oid_stat->stat, 0, sizeof(oid_stat->stat));
268 oidcpy(&oid_stat->oid, oid);
271 if (sz == 0) {
272 free(data);
273 return 0;
276 if (data[sz - 1] != '\n') {
277 data = xrealloc(data, st_add(sz, 1));
278 data[sz++] = '\n';
281 *size_out = xsize_t(sz);
282 *data_out = data;
284 return 1;
287 #define DO_MATCH_EXCLUDE (1<<0)
288 #define DO_MATCH_DIRECTORY (1<<1)
289 #define DO_MATCH_LEADING_PATHSPEC (1<<2)
292 * Does the given pathspec match the given name? A match is found if
294 * (1) the pathspec string is leading directory of 'name' ("RECURSIVELY"), or
295 * (2) the pathspec string has a leading part matching 'name' ("LEADING"), or
296 * (3) the pathspec string is a wildcard and matches 'name' ("WILDCARD"), or
297 * (4) the pathspec string is exactly the same as 'name' ("EXACT").
299 * Return value tells which case it was (1-4), or 0 when there is no match.
301 * It may be instructive to look at a small table of concrete examples
302 * to understand the differences between 1, 2, and 4:
304 * Pathspecs
305 * | a/b | a/b/ | a/b/c
306 * ------+-----------+-----------+------------
307 * a/b | EXACT | EXACT[1] | LEADING[2]
308 * Names a/b/ | RECURSIVE | EXACT | LEADING[2]
309 * a/b/c | RECURSIVE | RECURSIVE | EXACT
311 * [1] Only if DO_MATCH_DIRECTORY is passed; otherwise, this is NOT a match.
312 * [2] Only if DO_MATCH_LEADING_PATHSPEC is passed; otherwise, not a match.
314 static int match_pathspec_item(struct index_state *istate,
315 const struct pathspec_item *item, int prefix,
316 const char *name, int namelen, unsigned flags)
318 /* name/namelen has prefix cut off by caller */
319 const char *match = item->match + prefix;
320 int matchlen = item->len - prefix;
323 * The normal call pattern is:
324 * 1. prefix = common_prefix_len(ps);
325 * 2. prune something, or fill_directory
326 * 3. match_pathspec()
328 * 'prefix' at #1 may be shorter than the command's prefix and
329 * it's ok for #2 to match extra files. Those extras will be
330 * trimmed at #3.
332 * Suppose the pathspec is 'foo' and '../bar' running from
333 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
334 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
335 * user does not want XYZ/foo, only the "foo" part should be
336 * case-insensitive. We need to filter out XYZ/foo here. In
337 * other words, we do not trust the caller on comparing the
338 * prefix part when :(icase) is involved. We do exact
339 * comparison ourselves.
341 * Normally the caller (common_prefix_len() in fact) does
342 * _exact_ matching on name[-prefix+1..-1] and we do not need
343 * to check that part. Be defensive and check it anyway, in
344 * case common_prefix_len is changed, or a new caller is
345 * introduced that does not use common_prefix_len.
347 * If the penalty turns out too high when prefix is really
348 * long, maybe change it to
349 * strncmp(match, name, item->prefix - prefix)
351 if (item->prefix && (item->magic & PATHSPEC_ICASE) &&
352 strncmp(item->match, name - prefix, item->prefix))
353 return 0;
355 if (item->attr_match_nr &&
356 !match_pathspec_attrs(istate, name, namelen, item))
357 return 0;
359 /* If the match was just the prefix, we matched */
360 if (!*match)
361 return MATCHED_RECURSIVELY;
363 if (matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) {
364 if (matchlen == namelen)
365 return MATCHED_EXACTLY;
367 if (match[matchlen-1] == '/' || name[matchlen] == '/')
368 return MATCHED_RECURSIVELY;
369 } else if ((flags & DO_MATCH_DIRECTORY) &&
370 match[matchlen - 1] == '/' &&
371 namelen == matchlen - 1 &&
372 !ps_strncmp(item, match, name, namelen))
373 return MATCHED_EXACTLY;
375 if (item->nowildcard_len < item->len &&
376 !git_fnmatch(item, match, name,
377 item->nowildcard_len - prefix))
378 return MATCHED_FNMATCH;
380 /* Perform checks to see if "name" is a leading string of the pathspec */
381 if ( (flags & DO_MATCH_LEADING_PATHSPEC) &&
382 !(flags & DO_MATCH_EXCLUDE)) {
383 /* name is a literal prefix of the pathspec */
384 int offset = name[namelen-1] == '/' ? 1 : 0;
385 if ((namelen < matchlen) &&
386 (match[namelen-offset] == '/') &&
387 !ps_strncmp(item, match, name, namelen))
388 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
390 /* name doesn't match up to the first wild character */
391 if (item->nowildcard_len < item->len &&
392 ps_strncmp(item, match, name,
393 item->nowildcard_len - prefix))
394 return 0;
397 * name has no wildcard, and it didn't match as a leading
398 * pathspec so return.
400 if (item->nowildcard_len == item->len)
401 return 0;
404 * Here is where we would perform a wildmatch to check if
405 * "name" can be matched as a directory (or a prefix) against
406 * the pathspec. Since wildmatch doesn't have this capability
407 * at the present we have to punt and say that it is a match,
408 * potentially returning a false positive
409 * The submodules themselves will be able to perform more
410 * accurate matching to determine if the pathspec matches.
412 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
415 return 0;
419 * do_match_pathspec() is meant to ONLY be called by
420 * match_pathspec_with_flags(); calling it directly risks pathspecs
421 * like ':!unwanted_path' being ignored.
423 * Given a name and a list of pathspecs, returns the nature of the
424 * closest (i.e. most specific) match of the name to any of the
425 * pathspecs.
427 * The caller typically calls this multiple times with the same
428 * pathspec and seen[] array but with different name/namelen
429 * (e.g. entries from the index) and is interested in seeing if and
430 * how each pathspec matches all the names it calls this function
431 * with. A mark is left in the seen[] array for each pathspec element
432 * indicating the closest type of match that element achieved, so if
433 * seen[n] remains zero after multiple invocations, that means the nth
434 * pathspec did not match any names, which could indicate that the
435 * user mistyped the nth pathspec.
437 static int do_match_pathspec(struct index_state *istate,
438 const struct pathspec *ps,
439 const char *name, int namelen,
440 int prefix, char *seen,
441 unsigned flags)
443 int i, retval = 0, exclude = flags & DO_MATCH_EXCLUDE;
445 GUARD_PATHSPEC(ps,
446 PATHSPEC_FROMTOP |
447 PATHSPEC_MAXDEPTH |
448 PATHSPEC_LITERAL |
449 PATHSPEC_GLOB |
450 PATHSPEC_ICASE |
451 PATHSPEC_EXCLUDE |
452 PATHSPEC_ATTR);
454 if (!ps->nr) {
455 if (!ps->recursive ||
456 !(ps->magic & PATHSPEC_MAXDEPTH) ||
457 ps->max_depth == -1)
458 return MATCHED_RECURSIVELY;
460 if (within_depth(name, namelen, 0, ps->max_depth))
461 return MATCHED_EXACTLY;
462 else
463 return 0;
466 name += prefix;
467 namelen -= prefix;
469 for (i = ps->nr - 1; i >= 0; i--) {
470 int how;
472 if ((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) ||
473 ( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE)))
474 continue;
476 if (seen && seen[i] == MATCHED_EXACTLY)
477 continue;
479 * Make exclude patterns optional and never report
480 * "pathspec ':(exclude)foo' matches no files"
482 if (seen && ps->items[i].magic & PATHSPEC_EXCLUDE)
483 seen[i] = MATCHED_FNMATCH;
484 how = match_pathspec_item(istate, ps->items+i, prefix, name,
485 namelen, flags);
486 if (ps->recursive &&
487 (ps->magic & PATHSPEC_MAXDEPTH) &&
488 ps->max_depth != -1 &&
489 how && how != MATCHED_FNMATCH) {
490 int len = ps->items[i].len;
491 if (name[len] == '/')
492 len++;
493 if (within_depth(name+len, namelen-len, 0, ps->max_depth))
494 how = MATCHED_EXACTLY;
495 else
496 how = 0;
498 if (how) {
499 if (retval < how)
500 retval = how;
501 if (seen && seen[i] < how)
502 seen[i] = how;
505 return retval;
508 static int match_pathspec_with_flags(struct index_state *istate,
509 const struct pathspec *ps,
510 const char *name, int namelen,
511 int prefix, char *seen, unsigned flags)
513 int positive, negative;
514 positive = do_match_pathspec(istate, ps, name, namelen,
515 prefix, seen, flags);
516 if (!(ps->magic & PATHSPEC_EXCLUDE) || !positive)
517 return positive;
518 negative = do_match_pathspec(istate, ps, name, namelen,
519 prefix, seen,
520 flags | DO_MATCH_EXCLUDE);
521 return negative ? 0 : positive;
524 int match_pathspec(struct index_state *istate,
525 const struct pathspec *ps,
526 const char *name, int namelen,
527 int prefix, char *seen, int is_dir)
529 unsigned flags = is_dir ? DO_MATCH_DIRECTORY : 0;
530 return match_pathspec_with_flags(istate, ps, name, namelen,
531 prefix, seen, flags);
535 * Check if a submodule is a superset of the pathspec
537 int submodule_path_match(struct index_state *istate,
538 const struct pathspec *ps,
539 const char *submodule_name,
540 char *seen)
542 int matched = match_pathspec_with_flags(istate, ps, submodule_name,
543 strlen(submodule_name),
544 0, seen,
545 DO_MATCH_DIRECTORY |
546 DO_MATCH_LEADING_PATHSPEC);
547 return matched;
550 int report_path_error(const char *ps_matched,
551 const struct pathspec *pathspec)
554 * Make sure all pathspec matched; otherwise it is an error.
556 int num, errors = 0;
557 for (num = 0; num < pathspec->nr; num++) {
558 int other, found_dup;
560 if (ps_matched[num])
561 continue;
563 * The caller might have fed identical pathspec
564 * twice. Do not barf on such a mistake.
565 * FIXME: parse_pathspec should have eliminated
566 * duplicate pathspec.
568 for (found_dup = other = 0;
569 !found_dup && other < pathspec->nr;
570 other++) {
571 if (other == num || !ps_matched[other])
572 continue;
573 if (!strcmp(pathspec->items[other].original,
574 pathspec->items[num].original))
576 * Ok, we have a match already.
578 found_dup = 1;
580 if (found_dup)
581 continue;
583 error(_("pathspec '%s' did not match any file(s) known to git"),
584 pathspec->items[num].original);
585 errors++;
587 return errors;
591 * Return the length of the "simple" part of a path match limiter.
593 int simple_length(const char *match)
595 int len = -1;
597 for (;;) {
598 unsigned char c = *match++;
599 len++;
600 if (c == '\0' || is_glob_special(c))
601 return len;
605 int no_wildcard(const char *string)
607 return string[simple_length(string)] == '\0';
610 void parse_path_pattern(const char **pattern,
611 int *patternlen,
612 unsigned *flags,
613 int *nowildcardlen)
615 const char *p = *pattern;
616 size_t i, len;
618 *flags = 0;
619 if (*p == '!') {
620 *flags |= PATTERN_FLAG_NEGATIVE;
621 p++;
623 len = strlen(p);
624 if (len && p[len - 1] == '/') {
625 len--;
626 *flags |= PATTERN_FLAG_MUSTBEDIR;
628 for (i = 0; i < len; i++) {
629 if (p[i] == '/')
630 break;
632 if (i == len)
633 *flags |= PATTERN_FLAG_NODIR;
634 *nowildcardlen = simple_length(p);
636 * we should have excluded the trailing slash from 'p' too,
637 * but that's one more allocation. Instead just make sure
638 * nowildcardlen does not exceed real patternlen
640 if (*nowildcardlen > len)
641 *nowildcardlen = len;
642 if (*p == '*' && no_wildcard(p + 1))
643 *flags |= PATTERN_FLAG_ENDSWITH;
644 *pattern = p;
645 *patternlen = len;
648 int pl_hashmap_cmp(const void *unused_cmp_data,
649 const struct hashmap_entry *a,
650 const struct hashmap_entry *b,
651 const void *key)
653 const struct pattern_entry *ee1 =
654 container_of(a, struct pattern_entry, ent);
655 const struct pattern_entry *ee2 =
656 container_of(b, struct pattern_entry, ent);
658 size_t min_len = ee1->patternlen <= ee2->patternlen
659 ? ee1->patternlen
660 : ee2->patternlen;
662 if (ignore_case)
663 return strncasecmp(ee1->pattern, ee2->pattern, min_len);
664 return strncmp(ee1->pattern, ee2->pattern, min_len);
667 static char *dup_and_filter_pattern(const char *pattern)
669 char *set, *read;
670 size_t count = 0;
671 char *result = xstrdup(pattern);
673 set = result;
674 read = result;
676 while (*read) {
677 /* skip escape characters (once) */
678 if (*read == '\\')
679 read++;
681 *set = *read;
683 set++;
684 read++;
685 count++;
687 *set = 0;
689 if (count > 2 &&
690 *(set - 1) == '*' &&
691 *(set - 2) == '/')
692 *(set - 2) = 0;
694 return result;
697 static void add_pattern_to_hashsets(struct pattern_list *pl, struct path_pattern *given)
699 struct pattern_entry *translated;
700 char *truncated;
701 char *data = NULL;
702 const char *prev, *cur, *next;
704 if (!pl->use_cone_patterns)
705 return;
707 if (given->flags & PATTERN_FLAG_NEGATIVE &&
708 given->flags & PATTERN_FLAG_MUSTBEDIR &&
709 !strcmp(given->pattern, "/*")) {
710 pl->full_cone = 0;
711 return;
714 if (!given->flags && !strcmp(given->pattern, "/*")) {
715 pl->full_cone = 1;
716 return;
719 if (given->patternlen < 2 ||
720 *given->pattern == '*' ||
721 strstr(given->pattern, "**")) {
722 /* Not a cone pattern. */
723 warning(_("unrecognized pattern: '%s'"), given->pattern);
724 goto clear_hashmaps;
727 prev = given->pattern;
728 cur = given->pattern + 1;
729 next = given->pattern + 2;
731 while (*cur) {
732 /* Watch for glob characters '*', '\', '[', '?' */
733 if (!is_glob_special(*cur))
734 goto increment;
736 /* But only if *prev != '\\' */
737 if (*prev == '\\')
738 goto increment;
740 /* But allow the initial '\' */
741 if (*cur == '\\' &&
742 is_glob_special(*next))
743 goto increment;
745 /* But a trailing '/' then '*' is fine */
746 if (*prev == '/' &&
747 *cur == '*' &&
748 *next == 0)
749 goto increment;
751 /* Not a cone pattern. */
752 warning(_("unrecognized pattern: '%s'"), given->pattern);
753 goto clear_hashmaps;
755 increment:
756 prev++;
757 cur++;
758 next++;
761 if (given->patternlen > 2 &&
762 !strcmp(given->pattern + given->patternlen - 2, "/*")) {
763 if (!(given->flags & PATTERN_FLAG_NEGATIVE)) {
764 /* Not a cone pattern. */
765 warning(_("unrecognized pattern: '%s'"), given->pattern);
766 goto clear_hashmaps;
769 truncated = dup_and_filter_pattern(given->pattern);
771 translated = xmalloc(sizeof(struct pattern_entry));
772 translated->pattern = truncated;
773 translated->patternlen = given->patternlen - 2;
774 hashmap_entry_init(&translated->ent,
775 ignore_case ?
776 strihash(translated->pattern) :
777 strhash(translated->pattern));
779 if (!hashmap_get_entry(&pl->recursive_hashmap,
780 translated, ent, NULL)) {
781 /* We did not see the "parent" included */
782 warning(_("unrecognized negative pattern: '%s'"),
783 given->pattern);
784 free(truncated);
785 free(translated);
786 goto clear_hashmaps;
789 hashmap_add(&pl->parent_hashmap, &translated->ent);
790 hashmap_remove(&pl->recursive_hashmap, &translated->ent, &data);
791 free(data);
792 return;
795 if (given->flags & PATTERN_FLAG_NEGATIVE) {
796 warning(_("unrecognized negative pattern: '%s'"),
797 given->pattern);
798 goto clear_hashmaps;
801 translated = xmalloc(sizeof(struct pattern_entry));
803 translated->pattern = dup_and_filter_pattern(given->pattern);
804 translated->patternlen = given->patternlen;
805 hashmap_entry_init(&translated->ent,
806 ignore_case ?
807 strihash(translated->pattern) :
808 strhash(translated->pattern));
810 hashmap_add(&pl->recursive_hashmap, &translated->ent);
812 if (hashmap_get_entry(&pl->parent_hashmap, translated, ent, NULL)) {
813 /* we already included this at the parent level */
814 warning(_("your sparse-checkout file may have issues: pattern '%s' is repeated"),
815 given->pattern);
816 hashmap_remove(&pl->parent_hashmap, &translated->ent, &data);
817 free(data);
818 free(translated);
821 return;
823 clear_hashmaps:
824 warning(_("disabling cone pattern matching"));
825 hashmap_clear_and_free(&pl->parent_hashmap, struct pattern_entry, ent);
826 hashmap_clear_and_free(&pl->recursive_hashmap, struct pattern_entry, ent);
827 pl->use_cone_patterns = 0;
830 static int hashmap_contains_path(struct hashmap *map,
831 struct strbuf *pattern)
833 struct pattern_entry p;
835 /* Check straight mapping */
836 p.pattern = pattern->buf;
837 p.patternlen = pattern->len;
838 hashmap_entry_init(&p.ent,
839 ignore_case ?
840 strihash(p.pattern) :
841 strhash(p.pattern));
842 return !!hashmap_get_entry(map, &p, ent, NULL);
845 int hashmap_contains_parent(struct hashmap *map,
846 const char *path,
847 struct strbuf *buffer)
849 char *slash_pos;
851 strbuf_setlen(buffer, 0);
853 if (path[0] != '/')
854 strbuf_addch(buffer, '/');
856 strbuf_addstr(buffer, path);
858 slash_pos = strrchr(buffer->buf, '/');
860 while (slash_pos > buffer->buf) {
861 strbuf_setlen(buffer, slash_pos - buffer->buf);
863 if (hashmap_contains_path(map, buffer))
864 return 1;
866 slash_pos = strrchr(buffer->buf, '/');
869 return 0;
872 void add_pattern(const char *string, const char *base,
873 int baselen, struct pattern_list *pl, int srcpos)
875 struct path_pattern *pattern;
876 int patternlen;
877 unsigned flags;
878 int nowildcardlen;
880 parse_path_pattern(&string, &patternlen, &flags, &nowildcardlen);
881 if (flags & PATTERN_FLAG_MUSTBEDIR) {
882 FLEXPTR_ALLOC_MEM(pattern, pattern, string, patternlen);
883 } else {
884 pattern = xmalloc(sizeof(*pattern));
885 pattern->pattern = string;
887 pattern->patternlen = patternlen;
888 pattern->nowildcardlen = nowildcardlen;
889 pattern->base = base;
890 pattern->baselen = baselen;
891 pattern->flags = flags;
892 pattern->srcpos = srcpos;
893 ALLOC_GROW(pl->patterns, pl->nr + 1, pl->alloc);
894 pl->patterns[pl->nr++] = pattern;
895 pattern->pl = pl;
897 add_pattern_to_hashsets(pl, pattern);
900 static int read_skip_worktree_file_from_index(struct index_state *istate,
901 const char *path,
902 size_t *size_out, char **data_out,
903 struct oid_stat *oid_stat)
905 int pos, len;
907 len = strlen(path);
908 pos = index_name_pos(istate, path, len);
909 if (pos < 0)
910 return -1;
911 if (!ce_skip_worktree(istate->cache[pos]))
912 return -1;
914 return do_read_blob(&istate->cache[pos]->oid, oid_stat, size_out, data_out);
918 * Frees memory within pl which was allocated for exclude patterns and
919 * the file buffer. Does not free pl itself.
921 void clear_pattern_list(struct pattern_list *pl)
923 int i;
925 for (i = 0; i < pl->nr; i++)
926 free(pl->patterns[i]);
927 free(pl->patterns);
928 free(pl->filebuf);
929 hashmap_clear_and_free(&pl->recursive_hashmap, struct pattern_entry, ent);
930 hashmap_clear_and_free(&pl->parent_hashmap, struct pattern_entry, ent);
932 memset(pl, 0, sizeof(*pl));
935 static void trim_trailing_spaces(char *buf)
937 char *p, *last_space = NULL;
939 for (p = buf; *p; p++)
940 switch (*p) {
941 case ' ':
942 if (!last_space)
943 last_space = p;
944 break;
945 case '\\':
946 p++;
947 if (!*p)
948 return;
949 /* fallthrough */
950 default:
951 last_space = NULL;
954 if (last_space)
955 *last_space = '\0';
959 * Given a subdirectory name and "dir" of the current directory,
960 * search the subdir in "dir" and return it, or create a new one if it
961 * does not exist in "dir".
963 * If "name" has the trailing slash, it'll be excluded in the search.
965 static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc,
966 struct untracked_cache_dir *dir,
967 const char *name, int len)
969 int first, last;
970 struct untracked_cache_dir *d;
971 if (!dir)
972 return NULL;
973 if (len && name[len - 1] == '/')
974 len--;
975 first = 0;
976 last = dir->dirs_nr;
977 while (last > first) {
978 int cmp, next = first + ((last - first) >> 1);
979 d = dir->dirs[next];
980 cmp = strncmp(name, d->name, len);
981 if (!cmp && strlen(d->name) > len)
982 cmp = -1;
983 if (!cmp)
984 return d;
985 if (cmp < 0) {
986 last = next;
987 continue;
989 first = next+1;
992 uc->dir_created++;
993 FLEX_ALLOC_MEM(d, name, name, len);
995 ALLOC_GROW(dir->dirs, dir->dirs_nr + 1, dir->dirs_alloc);
996 MOVE_ARRAY(dir->dirs + first + 1, dir->dirs + first,
997 dir->dirs_nr - first);
998 dir->dirs_nr++;
999 dir->dirs[first] = d;
1000 return d;
1003 static void do_invalidate_gitignore(struct untracked_cache_dir *dir)
1005 int i;
1006 dir->valid = 0;
1007 dir->untracked_nr = 0;
1008 for (i = 0; i < dir->dirs_nr; i++)
1009 do_invalidate_gitignore(dir->dirs[i]);
1012 static void invalidate_gitignore(struct untracked_cache *uc,
1013 struct untracked_cache_dir *dir)
1015 uc->gitignore_invalidated++;
1016 do_invalidate_gitignore(dir);
1019 static void invalidate_directory(struct untracked_cache *uc,
1020 struct untracked_cache_dir *dir)
1022 int i;
1025 * Invalidation increment here is just roughly correct. If
1026 * untracked_nr or any of dirs[].recurse is non-zero, we
1027 * should increment dir_invalidated too. But that's more
1028 * expensive to do.
1030 if (dir->valid)
1031 uc->dir_invalidated++;
1033 dir->valid = 0;
1034 dir->untracked_nr = 0;
1035 for (i = 0; i < dir->dirs_nr; i++)
1036 dir->dirs[i]->recurse = 0;
1039 static int add_patterns_from_buffer(char *buf, size_t size,
1040 const char *base, int baselen,
1041 struct pattern_list *pl);
1043 /* Flags for add_patterns() */
1044 #define PATTERN_NOFOLLOW (1<<0)
1047 * Given a file with name "fname", read it (either from disk, or from
1048 * an index if 'istate' is non-null), parse it and store the
1049 * exclude rules in "pl".
1051 * If "oid_stat" is not NULL, compute oid of the exclude file and fill
1052 * stat data from disk (only valid if add_patterns returns zero). If
1053 * oid_stat.valid is non-zero, "oid_stat" must contain good value as input.
1055 static int add_patterns(const char *fname, const char *base, int baselen,
1056 struct pattern_list *pl, struct index_state *istate,
1057 unsigned flags, struct oid_stat *oid_stat)
1059 struct stat st;
1060 int r;
1061 int fd;
1062 size_t size = 0;
1063 char *buf;
1065 if (flags & PATTERN_NOFOLLOW)
1066 fd = open_nofollow(fname, O_RDONLY);
1067 else
1068 fd = open(fname, O_RDONLY);
1070 if (fd < 0 || fstat(fd, &st) < 0) {
1071 if (fd < 0)
1072 warn_on_fopen_errors(fname);
1073 else
1074 close(fd);
1075 if (!istate)
1076 return -1;
1077 r = read_skip_worktree_file_from_index(istate, fname,
1078 &size, &buf,
1079 oid_stat);
1080 if (r != 1)
1081 return r;
1082 } else {
1083 size = xsize_t(st.st_size);
1084 if (size == 0) {
1085 if (oid_stat) {
1086 fill_stat_data(&oid_stat->stat, &st);
1087 oidcpy(&oid_stat->oid, the_hash_algo->empty_blob);
1088 oid_stat->valid = 1;
1090 close(fd);
1091 return 0;
1093 buf = xmallocz(size);
1094 if (read_in_full(fd, buf, size) != size) {
1095 free(buf);
1096 close(fd);
1097 return -1;
1099 buf[size++] = '\n';
1100 close(fd);
1101 if (oid_stat) {
1102 int pos;
1103 if (oid_stat->valid &&
1104 !match_stat_data_racy(istate, &oid_stat->stat, &st))
1105 ; /* no content change, oid_stat->oid still good */
1106 else if (istate &&
1107 (pos = index_name_pos(istate, fname, strlen(fname))) >= 0 &&
1108 !ce_stage(istate->cache[pos]) &&
1109 ce_uptodate(istate->cache[pos]) &&
1110 !would_convert_to_git(istate, fname))
1111 oidcpy(&oid_stat->oid,
1112 &istate->cache[pos]->oid);
1113 else
1114 hash_object_file(the_hash_algo, buf, size,
1115 "blob", &oid_stat->oid);
1116 fill_stat_data(&oid_stat->stat, &st);
1117 oid_stat->valid = 1;
1121 add_patterns_from_buffer(buf, size, base, baselen, pl);
1122 return 0;
1125 static int add_patterns_from_buffer(char *buf, size_t size,
1126 const char *base, int baselen,
1127 struct pattern_list *pl)
1129 int i, lineno = 1;
1130 char *entry;
1132 hashmap_init(&pl->recursive_hashmap, pl_hashmap_cmp, NULL, 0);
1133 hashmap_init(&pl->parent_hashmap, pl_hashmap_cmp, NULL, 0);
1135 pl->filebuf = buf;
1137 if (skip_utf8_bom(&buf, size))
1138 size -= buf - pl->filebuf;
1140 entry = buf;
1142 for (i = 0; i < size; i++) {
1143 if (buf[i] == '\n') {
1144 if (entry != buf + i && entry[0] != '#') {
1145 buf[i - (i && buf[i-1] == '\r')] = 0;
1146 trim_trailing_spaces(entry);
1147 add_pattern(entry, base, baselen, pl, lineno);
1149 lineno++;
1150 entry = buf + i + 1;
1153 return 0;
1156 int add_patterns_from_file_to_list(const char *fname, const char *base,
1157 int baselen, struct pattern_list *pl,
1158 struct index_state *istate,
1159 unsigned flags)
1161 return add_patterns(fname, base, baselen, pl, istate, flags, NULL);
1164 int add_patterns_from_blob_to_list(
1165 struct object_id *oid,
1166 const char *base, int baselen,
1167 struct pattern_list *pl)
1169 char *buf;
1170 size_t size;
1171 int r;
1173 r = do_read_blob(oid, NULL, &size, &buf);
1174 if (r != 1)
1175 return r;
1177 add_patterns_from_buffer(buf, size, base, baselen, pl);
1178 return 0;
1181 struct pattern_list *add_pattern_list(struct dir_struct *dir,
1182 int group_type, const char *src)
1184 struct pattern_list *pl;
1185 struct exclude_list_group *group;
1187 group = &dir->exclude_list_group[group_type];
1188 ALLOC_GROW(group->pl, group->nr + 1, group->alloc);
1189 pl = &group->pl[group->nr++];
1190 memset(pl, 0, sizeof(*pl));
1191 pl->src = src;
1192 return pl;
1196 * Used to set up core.excludesfile and .git/info/exclude lists.
1198 static void add_patterns_from_file_1(struct dir_struct *dir, const char *fname,
1199 struct oid_stat *oid_stat)
1201 struct pattern_list *pl;
1203 * catch setup_standard_excludes() that's called before
1204 * dir->untracked is assigned. That function behaves
1205 * differently when dir->untracked is non-NULL.
1207 if (!dir->untracked)
1208 dir->unmanaged_exclude_files++;
1209 pl = add_pattern_list(dir, EXC_FILE, fname);
1210 if (add_patterns(fname, "", 0, pl, NULL, 0, oid_stat) < 0)
1211 die(_("cannot use %s as an exclude file"), fname);
1214 void add_patterns_from_file(struct dir_struct *dir, const char *fname)
1216 dir->unmanaged_exclude_files++; /* see validate_untracked_cache() */
1217 add_patterns_from_file_1(dir, fname, NULL);
1220 int match_basename(const char *basename, int basenamelen,
1221 const char *pattern, int prefix, int patternlen,
1222 unsigned flags)
1224 if (prefix == patternlen) {
1225 if (patternlen == basenamelen &&
1226 !fspathncmp(pattern, basename, basenamelen))
1227 return 1;
1228 } else if (flags & PATTERN_FLAG_ENDSWITH) {
1229 /* "*literal" matching against "fooliteral" */
1230 if (patternlen - 1 <= basenamelen &&
1231 !fspathncmp(pattern + 1,
1232 basename + basenamelen - (patternlen - 1),
1233 patternlen - 1))
1234 return 1;
1235 } else {
1236 if (fnmatch_icase_mem(pattern, patternlen,
1237 basename, basenamelen,
1238 0) == 0)
1239 return 1;
1241 return 0;
1244 int match_pathname(const char *pathname, int pathlen,
1245 const char *base, int baselen,
1246 const char *pattern, int prefix, int patternlen,
1247 unsigned flags)
1249 const char *name;
1250 int namelen;
1253 * match with FNM_PATHNAME; the pattern has base implicitly
1254 * in front of it.
1256 if (*pattern == '/') {
1257 pattern++;
1258 patternlen--;
1259 prefix--;
1263 * baselen does not count the trailing slash. base[] may or
1264 * may not end with a trailing slash though.
1266 if (pathlen < baselen + 1 ||
1267 (baselen && pathname[baselen] != '/') ||
1268 fspathncmp(pathname, base, baselen))
1269 return 0;
1271 namelen = baselen ? pathlen - baselen - 1 : pathlen;
1272 name = pathname + pathlen - namelen;
1274 if (prefix) {
1276 * if the non-wildcard part is longer than the
1277 * remaining pathname, surely it cannot match.
1279 if (prefix > namelen)
1280 return 0;
1282 if (fspathncmp(pattern, name, prefix))
1283 return 0;
1284 pattern += prefix;
1285 patternlen -= prefix;
1286 name += prefix;
1287 namelen -= prefix;
1290 * If the whole pattern did not have a wildcard,
1291 * then our prefix match is all we need; we
1292 * do not need to call fnmatch at all.
1294 if (!patternlen && !namelen)
1295 return 1;
1298 return fnmatch_icase_mem(pattern, patternlen,
1299 name, namelen,
1300 WM_PATHNAME) == 0;
1304 * Scan the given exclude list in reverse to see whether pathname
1305 * should be ignored. The first match (i.e. the last on the list), if
1306 * any, determines the fate. Returns the exclude_list element which
1307 * matched, or NULL for undecided.
1309 static struct path_pattern *last_matching_pattern_from_list(const char *pathname,
1310 int pathlen,
1311 const char *basename,
1312 int *dtype,
1313 struct pattern_list *pl,
1314 struct index_state *istate)
1316 struct path_pattern *res = NULL; /* undecided */
1317 int i;
1319 if (!pl->nr)
1320 return NULL; /* undefined */
1322 for (i = pl->nr - 1; 0 <= i; i--) {
1323 struct path_pattern *pattern = pl->patterns[i];
1324 const char *exclude = pattern->pattern;
1325 int prefix = pattern->nowildcardlen;
1327 if (pattern->flags & PATTERN_FLAG_MUSTBEDIR) {
1328 *dtype = resolve_dtype(*dtype, istate, pathname, pathlen);
1329 if (*dtype != DT_DIR)
1330 continue;
1333 if (pattern->flags & PATTERN_FLAG_NODIR) {
1334 if (match_basename(basename,
1335 pathlen - (basename - pathname),
1336 exclude, prefix, pattern->patternlen,
1337 pattern->flags)) {
1338 res = pattern;
1339 break;
1341 continue;
1344 assert(pattern->baselen == 0 ||
1345 pattern->base[pattern->baselen - 1] == '/');
1346 if (match_pathname(pathname, pathlen,
1347 pattern->base,
1348 pattern->baselen ? pattern->baselen - 1 : 0,
1349 exclude, prefix, pattern->patternlen,
1350 pattern->flags)) {
1351 res = pattern;
1352 break;
1355 return res;
1359 * Scan the list of patterns to determine if the ordered list
1360 * of patterns matches on 'pathname'.
1362 * Return 1 for a match, 0 for not matched and -1 for undecided.
1364 enum pattern_match_result path_matches_pattern_list(
1365 const char *pathname, int pathlen,
1366 const char *basename, int *dtype,
1367 struct pattern_list *pl,
1368 struct index_state *istate)
1370 struct path_pattern *pattern;
1371 struct strbuf parent_pathname = STRBUF_INIT;
1372 int result = NOT_MATCHED;
1373 const char *slash_pos;
1375 if (!pl->use_cone_patterns) {
1376 pattern = last_matching_pattern_from_list(pathname, pathlen, basename,
1377 dtype, pl, istate);
1378 if (pattern) {
1379 if (pattern->flags & PATTERN_FLAG_NEGATIVE)
1380 return NOT_MATCHED;
1381 else
1382 return MATCHED;
1385 return UNDECIDED;
1388 if (pl->full_cone)
1389 return MATCHED;
1391 strbuf_addch(&parent_pathname, '/');
1392 strbuf_add(&parent_pathname, pathname, pathlen);
1394 if (hashmap_contains_path(&pl->recursive_hashmap,
1395 &parent_pathname)) {
1396 result = MATCHED_RECURSIVE;
1397 goto done;
1400 slash_pos = strrchr(parent_pathname.buf, '/');
1402 if (slash_pos == parent_pathname.buf) {
1403 /* include every file in root */
1404 result = MATCHED;
1405 goto done;
1408 strbuf_setlen(&parent_pathname, slash_pos - parent_pathname.buf);
1410 if (hashmap_contains_path(&pl->parent_hashmap, &parent_pathname)) {
1411 result = MATCHED;
1412 goto done;
1415 if (hashmap_contains_parent(&pl->recursive_hashmap,
1416 pathname,
1417 &parent_pathname))
1418 result = MATCHED_RECURSIVE;
1420 done:
1421 strbuf_release(&parent_pathname);
1422 return result;
1425 static struct path_pattern *last_matching_pattern_from_lists(
1426 struct dir_struct *dir, struct index_state *istate,
1427 const char *pathname, int pathlen,
1428 const char *basename, int *dtype_p)
1430 int i, j;
1431 struct exclude_list_group *group;
1432 struct path_pattern *pattern;
1433 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
1434 group = &dir->exclude_list_group[i];
1435 for (j = group->nr - 1; j >= 0; j--) {
1436 pattern = last_matching_pattern_from_list(
1437 pathname, pathlen, basename, dtype_p,
1438 &group->pl[j], istate);
1439 if (pattern)
1440 return pattern;
1443 return NULL;
1447 * Loads the per-directory exclude list for the substring of base
1448 * which has a char length of baselen.
1450 static void prep_exclude(struct dir_struct *dir,
1451 struct index_state *istate,
1452 const char *base, int baselen)
1454 struct exclude_list_group *group;
1455 struct pattern_list *pl;
1456 struct exclude_stack *stk = NULL;
1457 struct untracked_cache_dir *untracked;
1458 int current;
1460 group = &dir->exclude_list_group[EXC_DIRS];
1463 * Pop the exclude lists from the EXCL_DIRS exclude_list_group
1464 * which originate from directories not in the prefix of the
1465 * path being checked.
1467 while ((stk = dir->exclude_stack) != NULL) {
1468 if (stk->baselen <= baselen &&
1469 !strncmp(dir->basebuf.buf, base, stk->baselen))
1470 break;
1471 pl = &group->pl[dir->exclude_stack->exclude_ix];
1472 dir->exclude_stack = stk->prev;
1473 dir->pattern = NULL;
1474 free((char *)pl->src); /* see strbuf_detach() below */
1475 clear_pattern_list(pl);
1476 free(stk);
1477 group->nr--;
1480 /* Skip traversing into sub directories if the parent is excluded */
1481 if (dir->pattern)
1482 return;
1485 * Lazy initialization. All call sites currently just
1486 * memset(dir, 0, sizeof(*dir)) before use. Changing all of
1487 * them seems lots of work for little benefit.
1489 if (!dir->basebuf.buf)
1490 strbuf_init(&dir->basebuf, PATH_MAX);
1492 /* Read from the parent directories and push them down. */
1493 current = stk ? stk->baselen : -1;
1494 strbuf_setlen(&dir->basebuf, current < 0 ? 0 : current);
1495 if (dir->untracked)
1496 untracked = stk ? stk->ucd : dir->untracked->root;
1497 else
1498 untracked = NULL;
1500 while (current < baselen) {
1501 const char *cp;
1502 struct oid_stat oid_stat;
1504 CALLOC_ARRAY(stk, 1);
1505 if (current < 0) {
1506 cp = base;
1507 current = 0;
1508 } else {
1509 cp = strchr(base + current + 1, '/');
1510 if (!cp)
1511 die("oops in prep_exclude");
1512 cp++;
1513 untracked =
1514 lookup_untracked(dir->untracked, untracked,
1515 base + current,
1516 cp - base - current);
1518 stk->prev = dir->exclude_stack;
1519 stk->baselen = cp - base;
1520 stk->exclude_ix = group->nr;
1521 stk->ucd = untracked;
1522 pl = add_pattern_list(dir, EXC_DIRS, NULL);
1523 strbuf_add(&dir->basebuf, base + current, stk->baselen - current);
1524 assert(stk->baselen == dir->basebuf.len);
1526 /* Abort if the directory is excluded */
1527 if (stk->baselen) {
1528 int dt = DT_DIR;
1529 dir->basebuf.buf[stk->baselen - 1] = 0;
1530 dir->pattern = last_matching_pattern_from_lists(dir,
1531 istate,
1532 dir->basebuf.buf, stk->baselen - 1,
1533 dir->basebuf.buf + current, &dt);
1534 dir->basebuf.buf[stk->baselen - 1] = '/';
1535 if (dir->pattern &&
1536 dir->pattern->flags & PATTERN_FLAG_NEGATIVE)
1537 dir->pattern = NULL;
1538 if (dir->pattern) {
1539 dir->exclude_stack = stk;
1540 return;
1544 /* Try to read per-directory file */
1545 oidclr(&oid_stat.oid);
1546 oid_stat.valid = 0;
1547 if (dir->exclude_per_dir &&
1549 * If we know that no files have been added in
1550 * this directory (i.e. valid_cached_dir() has
1551 * been executed and set untracked->valid) ..
1553 (!untracked || !untracked->valid ||
1555 * .. and .gitignore does not exist before
1556 * (i.e. null exclude_oid). Then we can skip
1557 * loading .gitignore, which would result in
1558 * ENOENT anyway.
1560 !is_null_oid(&untracked->exclude_oid))) {
1562 * dir->basebuf gets reused by the traversal, but we
1563 * need fname to remain unchanged to ensure the src
1564 * member of each struct path_pattern correctly
1565 * back-references its source file. Other invocations
1566 * of add_pattern_list provide stable strings, so we
1567 * strbuf_detach() and free() here in the caller.
1569 struct strbuf sb = STRBUF_INIT;
1570 strbuf_addbuf(&sb, &dir->basebuf);
1571 strbuf_addstr(&sb, dir->exclude_per_dir);
1572 pl->src = strbuf_detach(&sb, NULL);
1573 add_patterns(pl->src, pl->src, stk->baselen, pl, istate,
1574 PATTERN_NOFOLLOW,
1575 untracked ? &oid_stat : NULL);
1578 * NEEDSWORK: when untracked cache is enabled, prep_exclude()
1579 * will first be called in valid_cached_dir() then maybe many
1580 * times more in last_matching_pattern(). When the cache is
1581 * used, last_matching_pattern() will not be called and
1582 * reading .gitignore content will be a waste.
1584 * So when it's called by valid_cached_dir() and we can get
1585 * .gitignore SHA-1 from the index (i.e. .gitignore is not
1586 * modified on work tree), we could delay reading the
1587 * .gitignore content until we absolutely need it in
1588 * last_matching_pattern(). Be careful about ignore rule
1589 * order, though, if you do that.
1591 if (untracked &&
1592 !oideq(&oid_stat.oid, &untracked->exclude_oid)) {
1593 invalidate_gitignore(dir->untracked, untracked);
1594 oidcpy(&untracked->exclude_oid, &oid_stat.oid);
1596 dir->exclude_stack = stk;
1597 current = stk->baselen;
1599 strbuf_setlen(&dir->basebuf, baselen);
1603 * Loads the exclude lists for the directory containing pathname, then
1604 * scans all exclude lists to determine whether pathname is excluded.
1605 * Returns the exclude_list element which matched, or NULL for
1606 * undecided.
1608 struct path_pattern *last_matching_pattern(struct dir_struct *dir,
1609 struct index_state *istate,
1610 const char *pathname,
1611 int *dtype_p)
1613 int pathlen = strlen(pathname);
1614 const char *basename = strrchr(pathname, '/');
1615 basename = (basename) ? basename+1 : pathname;
1617 prep_exclude(dir, istate, pathname, basename-pathname);
1619 if (dir->pattern)
1620 return dir->pattern;
1622 return last_matching_pattern_from_lists(dir, istate, pathname, pathlen,
1623 basename, dtype_p);
1627 * Loads the exclude lists for the directory containing pathname, then
1628 * scans all exclude lists to determine whether pathname is excluded.
1629 * Returns 1 if true, otherwise 0.
1631 int is_excluded(struct dir_struct *dir, struct index_state *istate,
1632 const char *pathname, int *dtype_p)
1634 struct path_pattern *pattern =
1635 last_matching_pattern(dir, istate, pathname, dtype_p);
1636 if (pattern)
1637 return pattern->flags & PATTERN_FLAG_NEGATIVE ? 0 : 1;
1638 return 0;
1641 static struct dir_entry *dir_entry_new(const char *pathname, int len)
1643 struct dir_entry *ent;
1645 FLEX_ALLOC_MEM(ent, name, pathname, len);
1646 ent->len = len;
1647 return ent;
1650 static struct dir_entry *dir_add_name(struct dir_struct *dir,
1651 struct index_state *istate,
1652 const char *pathname, int len)
1654 if (index_file_exists(istate, pathname, len, ignore_case))
1655 return NULL;
1657 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
1658 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
1661 struct dir_entry *dir_add_ignored(struct dir_struct *dir,
1662 struct index_state *istate,
1663 const char *pathname, int len)
1665 if (!index_name_is_other(istate, pathname, len))
1666 return NULL;
1668 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
1669 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
1672 enum exist_status {
1673 index_nonexistent = 0,
1674 index_directory,
1675 index_gitdir
1679 * Do not use the alphabetically sorted index to look up
1680 * the directory name; instead, use the case insensitive
1681 * directory hash.
1683 static enum exist_status directory_exists_in_index_icase(struct index_state *istate,
1684 const char *dirname, int len)
1686 struct cache_entry *ce;
1688 if (index_dir_exists(istate, dirname, len))
1689 return index_directory;
1691 ce = index_file_exists(istate, dirname, len, ignore_case);
1692 if (ce && S_ISGITLINK(ce->ce_mode))
1693 return index_gitdir;
1695 return index_nonexistent;
1699 * The index sorts alphabetically by entry name, which
1700 * means that a gitlink sorts as '\0' at the end, while
1701 * a directory (which is defined not as an entry, but as
1702 * the files it contains) will sort with the '/' at the
1703 * end.
1705 static enum exist_status directory_exists_in_index(struct index_state *istate,
1706 const char *dirname, int len)
1708 int pos;
1710 if (ignore_case)
1711 return directory_exists_in_index_icase(istate, dirname, len);
1713 pos = index_name_pos(istate, dirname, len);
1714 if (pos < 0)
1715 pos = -pos-1;
1716 while (pos < istate->cache_nr) {
1717 const struct cache_entry *ce = istate->cache[pos++];
1718 unsigned char endchar;
1720 if (strncmp(ce->name, dirname, len))
1721 break;
1722 endchar = ce->name[len];
1723 if (endchar > '/')
1724 break;
1725 if (endchar == '/')
1726 return index_directory;
1727 if (!endchar && S_ISGITLINK(ce->ce_mode))
1728 return index_gitdir;
1730 return index_nonexistent;
1734 * When we find a directory when traversing the filesystem, we
1735 * have three distinct cases:
1737 * - ignore it
1738 * - see it as a directory
1739 * - recurse into it
1741 * and which one we choose depends on a combination of existing
1742 * git index contents and the flags passed into the directory
1743 * traversal routine.
1745 * Case 1: If we *already* have entries in the index under that
1746 * directory name, we always recurse into the directory to see
1747 * all the files.
1749 * Case 2: If we *already* have that directory name as a gitlink,
1750 * we always continue to see it as a gitlink, regardless of whether
1751 * there is an actual git directory there or not (it might not
1752 * be checked out as a subproject!)
1754 * Case 3: if we didn't have it in the index previously, we
1755 * have a few sub-cases:
1757 * (a) if DIR_SHOW_OTHER_DIRECTORIES flag is set, we show it as
1758 * just a directory, unless DIR_HIDE_EMPTY_DIRECTORIES is
1759 * also true, in which case we need to check if it contains any
1760 * untracked and / or ignored files.
1761 * (b) if it looks like a git directory and we don't have the
1762 * DIR_NO_GITLINKS flag, then we treat it as a gitlink, and
1763 * show it as a directory.
1764 * (c) otherwise, we recurse into it.
1766 static enum path_treatment treat_directory(struct dir_struct *dir,
1767 struct index_state *istate,
1768 struct untracked_cache_dir *untracked,
1769 const char *dirname, int len, int baselen, int excluded,
1770 const struct pathspec *pathspec)
1773 * WARNING: From this function, you can return path_recurse or you
1774 * can call read_directory_recursive() (or neither), but
1775 * you CAN'T DO BOTH.
1777 enum path_treatment state;
1778 int matches_how = 0;
1779 int nested_repo = 0, check_only, stop_early;
1780 int old_ignored_nr, old_untracked_nr;
1781 /* The "len-1" is to strip the final '/' */
1782 enum exist_status status = directory_exists_in_index(istate, dirname, len-1);
1784 if (status == index_directory)
1785 return path_recurse;
1786 if (status == index_gitdir)
1787 return path_none;
1788 if (status != index_nonexistent)
1789 BUG("Unhandled value for directory_exists_in_index: %d\n", status);
1792 * We don't want to descend into paths that don't match the necessary
1793 * patterns. Clearly, if we don't have a pathspec, then we can't check
1794 * for matching patterns. Also, if (excluded) then we know we matched
1795 * the exclusion patterns so as an optimization we can skip checking
1796 * for matching patterns.
1798 if (pathspec && !excluded) {
1799 matches_how = match_pathspec_with_flags(istate, pathspec,
1800 dirname, len,
1801 0 /* prefix */,
1802 NULL /* seen */,
1803 DO_MATCH_LEADING_PATHSPEC);
1804 if (!matches_how)
1805 return path_none;
1809 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
1810 !(dir->flags & DIR_NO_GITLINKS)) {
1811 struct strbuf sb = STRBUF_INIT;
1812 strbuf_addstr(&sb, dirname);
1813 nested_repo = is_nonbare_repository_dir(&sb);
1814 strbuf_release(&sb);
1816 if (nested_repo) {
1817 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
1818 (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC))
1819 return path_none;
1820 return excluded ? path_excluded : path_untracked;
1823 if (!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)) {
1824 if (excluded &&
1825 (dir->flags & DIR_SHOW_IGNORED_TOO) &&
1826 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING)) {
1829 * This is an excluded directory and we are
1830 * showing ignored paths that match an exclude
1831 * pattern. (e.g. show directory as ignored
1832 * only if it matches an exclude pattern).
1833 * This path will either be 'path_excluded`
1834 * (if we are showing empty directories or if
1835 * the directory is not empty), or will be
1836 * 'path_none' (empty directory, and we are
1837 * not showing empty directories).
1839 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1840 return path_excluded;
1842 if (read_directory_recursive(dir, istate, dirname, len,
1843 untracked, 1, 1, pathspec) == path_excluded)
1844 return path_excluded;
1846 return path_none;
1848 return path_recurse;
1851 assert(dir->flags & DIR_SHOW_OTHER_DIRECTORIES);
1854 * If we have a pathspec which could match something _below_ this
1855 * directory (e.g. when checking 'subdir/' having a pathspec like
1856 * 'subdir/some/deep/path/file' or 'subdir/widget-*.c'), then we
1857 * need to recurse.
1859 if (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC)
1860 return path_recurse;
1862 /* Special cases for where this directory is excluded/ignored */
1863 if (excluded) {
1865 * If DIR_SHOW_OTHER_DIRECTORIES is set and we're not
1866 * hiding empty directories, there is no need to
1867 * recurse into an ignored directory.
1869 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1870 return path_excluded;
1873 * Even if we are hiding empty directories, we can still avoid
1874 * recursing into ignored directories for DIR_SHOW_IGNORED_TOO
1875 * if DIR_SHOW_IGNORED_TOO_MODE_MATCHING is also set.
1877 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
1878 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING))
1879 return path_excluded;
1883 * Other than the path_recurse case above, we only need to
1884 * recurse into untracked directories if any of the following
1885 * bits is set:
1886 * - DIR_SHOW_IGNORED (because then we need to determine if
1887 * there are ignored entries below)
1888 * - DIR_SHOW_IGNORED_TOO (same as above)
1889 * - DIR_HIDE_EMPTY_DIRECTORIES (because we have to determine if
1890 * the directory is empty)
1892 if (!excluded &&
1893 !(dir->flags & (DIR_SHOW_IGNORED |
1894 DIR_SHOW_IGNORED_TOO |
1895 DIR_HIDE_EMPTY_DIRECTORIES))) {
1896 return path_untracked;
1900 * Even if we don't want to know all the paths under an untracked or
1901 * ignored directory, we may still need to go into the directory to
1902 * determine if it is empty (because with DIR_HIDE_EMPTY_DIRECTORIES,
1903 * an empty directory should be path_none instead of path_excluded or
1904 * path_untracked).
1906 check_only = ((dir->flags & DIR_HIDE_EMPTY_DIRECTORIES) &&
1907 !(dir->flags & DIR_SHOW_IGNORED_TOO));
1910 * However, there's another optimization possible as a subset of
1911 * check_only, based on the cases we have to consider:
1912 * A) Directory matches no exclude patterns:
1913 * * Directory is empty => path_none
1914 * * Directory has an untracked file under it => path_untracked
1915 * * Directory has only ignored files under it => path_excluded
1916 * B) Directory matches an exclude pattern:
1917 * * Directory is empty => path_none
1918 * * Directory has an untracked file under it => path_excluded
1919 * * Directory has only ignored files under it => path_excluded
1920 * In case A, we can exit as soon as we've found an untracked
1921 * file but otherwise have to walk all files. In case B, though,
1922 * we can stop at the first file we find under the directory.
1924 stop_early = check_only && excluded;
1927 * If /every/ file within an untracked directory is ignored, then
1928 * we want to treat the directory as ignored (for e.g. status
1929 * --porcelain), without listing the individual ignored files
1930 * underneath. To do so, we'll save the current ignored_nr, and
1931 * pop all the ones added after it if it turns out the entire
1932 * directory is ignored. Also, when DIR_SHOW_IGNORED_TOO and
1933 * !DIR_KEEP_UNTRACKED_CONTENTS then we don't want to show
1934 * untracked paths so will need to pop all those off the last
1935 * after we traverse.
1937 old_ignored_nr = dir->ignored_nr;
1938 old_untracked_nr = dir->nr;
1940 /* Actually recurse into dirname now, we'll fixup the state later. */
1941 untracked = lookup_untracked(dir->untracked, untracked,
1942 dirname + baselen, len - baselen);
1943 state = read_directory_recursive(dir, istate, dirname, len, untracked,
1944 check_only, stop_early, pathspec);
1946 /* There are a variety of reasons we may need to fixup the state... */
1947 if (state == path_excluded) {
1948 /* state == path_excluded implies all paths under
1949 * dirname were ignored...
1951 * if running e.g. `git status --porcelain --ignored=matching`,
1952 * then we want to see the subpaths that are ignored.
1954 * if running e.g. just `git status --porcelain`, then
1955 * we just want the directory itself to be listed as ignored
1956 * and not the individual paths underneath.
1958 int want_ignored_subpaths =
1959 ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
1960 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING));
1962 if (want_ignored_subpaths) {
1964 * with --ignored=matching, we want the subpaths
1965 * INSTEAD of the directory itself.
1967 state = path_none;
1968 } else {
1969 int i;
1970 for (i = old_ignored_nr + 1; i<dir->ignored_nr; ++i)
1971 FREE_AND_NULL(dir->ignored[i]);
1972 dir->ignored_nr = old_ignored_nr;
1977 * We may need to ignore some of the untracked paths we found while
1978 * traversing subdirectories.
1980 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
1981 !(dir->flags & DIR_KEEP_UNTRACKED_CONTENTS)) {
1982 int i;
1983 for (i = old_untracked_nr + 1; i<dir->nr; ++i)
1984 FREE_AND_NULL(dir->entries[i]);
1985 dir->nr = old_untracked_nr;
1989 * If there is nothing under the current directory and we are not
1990 * hiding empty directories, then we need to report on the
1991 * untracked or ignored status of the directory itself.
1993 if (state == path_none && !(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1994 state = excluded ? path_excluded : path_untracked;
1996 return state;
2000 * This is an inexact early pruning of any recursive directory
2001 * reading - if the path cannot possibly be in the pathspec,
2002 * return true, and we'll skip it early.
2004 static int simplify_away(const char *path, int pathlen,
2005 const struct pathspec *pathspec)
2007 int i;
2009 if (!pathspec || !pathspec->nr)
2010 return 0;
2012 GUARD_PATHSPEC(pathspec,
2013 PATHSPEC_FROMTOP |
2014 PATHSPEC_MAXDEPTH |
2015 PATHSPEC_LITERAL |
2016 PATHSPEC_GLOB |
2017 PATHSPEC_ICASE |
2018 PATHSPEC_EXCLUDE |
2019 PATHSPEC_ATTR);
2021 for (i = 0; i < pathspec->nr; i++) {
2022 const struct pathspec_item *item = &pathspec->items[i];
2023 int len = item->nowildcard_len;
2025 if (len > pathlen)
2026 len = pathlen;
2027 if (!ps_strncmp(item, item->match, path, len))
2028 return 0;
2031 return 1;
2035 * This function tells us whether an excluded path matches a
2036 * list of "interesting" pathspecs. That is, whether a path matched
2037 * by any of the pathspecs could possibly be ignored by excluding
2038 * the specified path. This can happen if:
2040 * 1. the path is mentioned explicitly in the pathspec
2042 * 2. the path is a directory prefix of some element in the
2043 * pathspec
2045 static int exclude_matches_pathspec(const char *path, int pathlen,
2046 const struct pathspec *pathspec)
2048 int i;
2050 if (!pathspec || !pathspec->nr)
2051 return 0;
2053 GUARD_PATHSPEC(pathspec,
2054 PATHSPEC_FROMTOP |
2055 PATHSPEC_MAXDEPTH |
2056 PATHSPEC_LITERAL |
2057 PATHSPEC_GLOB |
2058 PATHSPEC_ICASE |
2059 PATHSPEC_EXCLUDE);
2061 for (i = 0; i < pathspec->nr; i++) {
2062 const struct pathspec_item *item = &pathspec->items[i];
2063 int len = item->nowildcard_len;
2065 if (len == pathlen &&
2066 !ps_strncmp(item, item->match, path, pathlen))
2067 return 1;
2068 if (len > pathlen &&
2069 item->match[pathlen] == '/' &&
2070 !ps_strncmp(item, item->match, path, pathlen))
2071 return 1;
2073 return 0;
2076 static int get_index_dtype(struct index_state *istate,
2077 const char *path, int len)
2079 int pos;
2080 const struct cache_entry *ce;
2082 ce = index_file_exists(istate, path, len, 0);
2083 if (ce) {
2084 if (!ce_uptodate(ce))
2085 return DT_UNKNOWN;
2086 if (S_ISGITLINK(ce->ce_mode))
2087 return DT_DIR;
2089 * Nobody actually cares about the
2090 * difference between DT_LNK and DT_REG
2092 return DT_REG;
2095 /* Try to look it up as a directory */
2096 pos = index_name_pos(istate, path, len);
2097 if (pos >= 0)
2098 return DT_UNKNOWN;
2099 pos = -pos-1;
2100 while (pos < istate->cache_nr) {
2101 ce = istate->cache[pos++];
2102 if (strncmp(ce->name, path, len))
2103 break;
2104 if (ce->name[len] > '/')
2105 break;
2106 if (ce->name[len] < '/')
2107 continue;
2108 if (!ce_uptodate(ce))
2109 break; /* continue? */
2110 return DT_DIR;
2112 return DT_UNKNOWN;
2115 static int resolve_dtype(int dtype, struct index_state *istate,
2116 const char *path, int len)
2118 struct stat st;
2120 if (dtype != DT_UNKNOWN)
2121 return dtype;
2122 dtype = get_index_dtype(istate, path, len);
2123 if (dtype != DT_UNKNOWN)
2124 return dtype;
2125 if (lstat(path, &st))
2126 return dtype;
2127 if (S_ISREG(st.st_mode))
2128 return DT_REG;
2129 if (S_ISDIR(st.st_mode))
2130 return DT_DIR;
2131 if (S_ISLNK(st.st_mode))
2132 return DT_LNK;
2133 return dtype;
2136 static enum path_treatment treat_path_fast(struct dir_struct *dir,
2137 struct cached_dir *cdir,
2138 struct index_state *istate,
2139 struct strbuf *path,
2140 int baselen,
2141 const struct pathspec *pathspec)
2144 * WARNING: From this function, you can return path_recurse or you
2145 * can call read_directory_recursive() (or neither), but
2146 * you CAN'T DO BOTH.
2148 strbuf_setlen(path, baselen);
2149 if (!cdir->ucd) {
2150 strbuf_addstr(path, cdir->file);
2151 return path_untracked;
2153 strbuf_addstr(path, cdir->ucd->name);
2154 /* treat_one_path() does this before it calls treat_directory() */
2155 strbuf_complete(path, '/');
2156 if (cdir->ucd->check_only)
2158 * check_only is set as a result of treat_directory() getting
2159 * to its bottom. Verify again the same set of directories
2160 * with check_only set.
2162 return read_directory_recursive(dir, istate, path->buf, path->len,
2163 cdir->ucd, 1, 0, pathspec);
2165 * We get path_recurse in the first run when
2166 * directory_exists_in_index() returns index_nonexistent. We
2167 * are sure that new changes in the index does not impact the
2168 * outcome. Return now.
2170 return path_recurse;
2173 static enum path_treatment treat_path(struct dir_struct *dir,
2174 struct untracked_cache_dir *untracked,
2175 struct cached_dir *cdir,
2176 struct index_state *istate,
2177 struct strbuf *path,
2178 int baselen,
2179 const struct pathspec *pathspec)
2181 int has_path_in_index, dtype, excluded;
2183 if (!cdir->d_name)
2184 return treat_path_fast(dir, cdir, istate, path,
2185 baselen, pathspec);
2186 if (is_dot_or_dotdot(cdir->d_name) || !fspathcmp(cdir->d_name, ".git"))
2187 return path_none;
2188 strbuf_setlen(path, baselen);
2189 strbuf_addstr(path, cdir->d_name);
2190 if (simplify_away(path->buf, path->len, pathspec))
2191 return path_none;
2193 dtype = resolve_dtype(cdir->d_type, istate, path->buf, path->len);
2195 /* Always exclude indexed files */
2196 has_path_in_index = !!index_file_exists(istate, path->buf, path->len,
2197 ignore_case);
2198 if (dtype != DT_DIR && has_path_in_index)
2199 return path_none;
2202 * When we are looking at a directory P in the working tree,
2203 * there are three cases:
2205 * (1) P exists in the index. Everything inside the directory P in
2206 * the working tree needs to go when P is checked out from the
2207 * index.
2209 * (2) P does not exist in the index, but there is P/Q in the index.
2210 * We know P will stay a directory when we check out the contents
2211 * of the index, but we do not know yet if there is a directory
2212 * P/Q in the working tree to be killed, so we need to recurse.
2214 * (3) P does not exist in the index, and there is no P/Q in the index
2215 * to require P to be a directory, either. Only in this case, we
2216 * know that everything inside P will not be killed without
2217 * recursing.
2219 if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
2220 (dtype == DT_DIR) &&
2221 !has_path_in_index &&
2222 (directory_exists_in_index(istate, path->buf, path->len) == index_nonexistent))
2223 return path_none;
2225 excluded = is_excluded(dir, istate, path->buf, &dtype);
2228 * Excluded? If we don't explicitly want to show
2229 * ignored files, ignore it
2231 if (excluded && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
2232 return path_excluded;
2234 switch (dtype) {
2235 default:
2236 return path_none;
2237 case DT_DIR:
2239 * WARNING: Do not ignore/amend the return value from
2240 * treat_directory(), and especially do not change it to return
2241 * path_recurse as that can cause exponential slowdown.
2242 * Instead, modify treat_directory() to return the right value.
2244 strbuf_addch(path, '/');
2245 return treat_directory(dir, istate, untracked,
2246 path->buf, path->len,
2247 baselen, excluded, pathspec);
2248 case DT_REG:
2249 case DT_LNK:
2250 if (pathspec &&
2251 !match_pathspec(istate, pathspec, path->buf, path->len,
2252 0 /* prefix */, NULL /* seen */,
2253 0 /* is_dir */))
2254 return path_none;
2255 if (excluded)
2256 return path_excluded;
2257 return path_untracked;
2261 static void add_untracked(struct untracked_cache_dir *dir, const char *name)
2263 if (!dir)
2264 return;
2265 ALLOC_GROW(dir->untracked, dir->untracked_nr + 1,
2266 dir->untracked_alloc);
2267 dir->untracked[dir->untracked_nr++] = xstrdup(name);
2270 static int valid_cached_dir(struct dir_struct *dir,
2271 struct untracked_cache_dir *untracked,
2272 struct index_state *istate,
2273 struct strbuf *path,
2274 int check_only)
2276 struct stat st;
2278 if (!untracked)
2279 return 0;
2282 * With fsmonitor, we can trust the untracked cache's valid field.
2284 refresh_fsmonitor(istate);
2285 if (!(dir->untracked->use_fsmonitor && untracked->valid)) {
2286 if (lstat(path->len ? path->buf : ".", &st)) {
2287 memset(&untracked->stat_data, 0, sizeof(untracked->stat_data));
2288 return 0;
2290 if (!untracked->valid ||
2291 match_stat_data_racy(istate, &untracked->stat_data, &st)) {
2292 fill_stat_data(&untracked->stat_data, &st);
2293 return 0;
2297 if (untracked->check_only != !!check_only)
2298 return 0;
2301 * prep_exclude will be called eventually on this directory,
2302 * but it's called much later in last_matching_pattern(). We
2303 * need it now to determine the validity of the cache for this
2304 * path. The next calls will be nearly no-op, the way
2305 * prep_exclude() is designed.
2307 if (path->len && path->buf[path->len - 1] != '/') {
2308 strbuf_addch(path, '/');
2309 prep_exclude(dir, istate, path->buf, path->len);
2310 strbuf_setlen(path, path->len - 1);
2311 } else
2312 prep_exclude(dir, istate, path->buf, path->len);
2314 /* hopefully prep_exclude() haven't invalidated this entry... */
2315 return untracked->valid;
2318 static int open_cached_dir(struct cached_dir *cdir,
2319 struct dir_struct *dir,
2320 struct untracked_cache_dir *untracked,
2321 struct index_state *istate,
2322 struct strbuf *path,
2323 int check_only)
2325 const char *c_path;
2327 memset(cdir, 0, sizeof(*cdir));
2328 cdir->untracked = untracked;
2329 if (valid_cached_dir(dir, untracked, istate, path, check_only))
2330 return 0;
2331 c_path = path->len ? path->buf : ".";
2332 cdir->fdir = opendir(c_path);
2333 if (!cdir->fdir)
2334 warning_errno(_("could not open directory '%s'"), c_path);
2335 if (dir->untracked) {
2336 invalidate_directory(dir->untracked, untracked);
2337 dir->untracked->dir_opened++;
2339 if (!cdir->fdir)
2340 return -1;
2341 return 0;
2344 static int read_cached_dir(struct cached_dir *cdir)
2346 struct dirent *de;
2348 if (cdir->fdir) {
2349 de = readdir_skip_dot_and_dotdot(cdir->fdir);
2350 if (!de) {
2351 cdir->d_name = NULL;
2352 cdir->d_type = DT_UNKNOWN;
2353 return -1;
2355 cdir->d_name = de->d_name;
2356 cdir->d_type = DTYPE(de);
2357 return 0;
2359 while (cdir->nr_dirs < cdir->untracked->dirs_nr) {
2360 struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];
2361 if (!d->recurse) {
2362 cdir->nr_dirs++;
2363 continue;
2365 cdir->ucd = d;
2366 cdir->nr_dirs++;
2367 return 0;
2369 cdir->ucd = NULL;
2370 if (cdir->nr_files < cdir->untracked->untracked_nr) {
2371 struct untracked_cache_dir *d = cdir->untracked;
2372 cdir->file = d->untracked[cdir->nr_files++];
2373 return 0;
2375 return -1;
2378 static void close_cached_dir(struct cached_dir *cdir)
2380 if (cdir->fdir)
2381 closedir(cdir->fdir);
2383 * We have gone through this directory and found no untracked
2384 * entries. Mark it valid.
2386 if (cdir->untracked) {
2387 cdir->untracked->valid = 1;
2388 cdir->untracked->recurse = 1;
2392 static void add_path_to_appropriate_result_list(struct dir_struct *dir,
2393 struct untracked_cache_dir *untracked,
2394 struct cached_dir *cdir,
2395 struct index_state *istate,
2396 struct strbuf *path,
2397 int baselen,
2398 const struct pathspec *pathspec,
2399 enum path_treatment state)
2401 /* add the path to the appropriate result list */
2402 switch (state) {
2403 case path_excluded:
2404 if (dir->flags & DIR_SHOW_IGNORED)
2405 dir_add_name(dir, istate, path->buf, path->len);
2406 else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
2407 ((dir->flags & DIR_COLLECT_IGNORED) &&
2408 exclude_matches_pathspec(path->buf, path->len,
2409 pathspec)))
2410 dir_add_ignored(dir, istate, path->buf, path->len);
2411 break;
2413 case path_untracked:
2414 if (dir->flags & DIR_SHOW_IGNORED)
2415 break;
2416 dir_add_name(dir, istate, path->buf, path->len);
2417 if (cdir->fdir)
2418 add_untracked(untracked, path->buf + baselen);
2419 break;
2421 default:
2422 break;
2427 * Read a directory tree. We currently ignore anything but
2428 * directories, regular files and symlinks. That's because git
2429 * doesn't handle them at all yet. Maybe that will change some
2430 * day.
2432 * Also, we ignore the name ".git" (even if it is not a directory).
2433 * That likely will not change.
2435 * If 'stop_at_first_file' is specified, 'path_excluded' is returned
2436 * to signal that a file was found. This is the least significant value that
2437 * indicates that a file was encountered that does not depend on the order of
2438 * whether an untracked or excluded path was encountered first.
2440 * Returns the most significant path_treatment value encountered in the scan.
2441 * If 'stop_at_first_file' is specified, `path_excluded` is the most
2442 * significant path_treatment value that will be returned.
2445 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
2446 struct index_state *istate, const char *base, int baselen,
2447 struct untracked_cache_dir *untracked, int check_only,
2448 int stop_at_first_file, const struct pathspec *pathspec)
2451 * WARNING: Do NOT recurse unless path_recurse is returned from
2452 * treat_path(). Recursing on any other return value
2453 * can result in exponential slowdown.
2455 struct cached_dir cdir;
2456 enum path_treatment state, subdir_state, dir_state = path_none;
2457 struct strbuf path = STRBUF_INIT;
2459 strbuf_add(&path, base, baselen);
2461 if (open_cached_dir(&cdir, dir, untracked, istate, &path, check_only))
2462 goto out;
2463 dir->visited_directories++;
2465 if (untracked)
2466 untracked->check_only = !!check_only;
2468 while (!read_cached_dir(&cdir)) {
2469 /* check how the file or directory should be treated */
2470 state = treat_path(dir, untracked, &cdir, istate, &path,
2471 baselen, pathspec);
2472 dir->visited_paths++;
2474 if (state > dir_state)
2475 dir_state = state;
2477 /* recurse into subdir if instructed by treat_path */
2478 if (state == path_recurse) {
2479 struct untracked_cache_dir *ud;
2480 ud = lookup_untracked(dir->untracked, untracked,
2481 path.buf + baselen,
2482 path.len - baselen);
2483 subdir_state =
2484 read_directory_recursive(dir, istate, path.buf,
2485 path.len, ud,
2486 check_only, stop_at_first_file, pathspec);
2487 if (subdir_state > dir_state)
2488 dir_state = subdir_state;
2490 if (pathspec &&
2491 !match_pathspec(istate, pathspec, path.buf, path.len,
2492 0 /* prefix */, NULL,
2493 0 /* do NOT special case dirs */))
2494 state = path_none;
2497 if (check_only) {
2498 if (stop_at_first_file) {
2500 * If stopping at first file, then
2501 * signal that a file was found by
2502 * returning `path_excluded`. This is
2503 * to return a consistent value
2504 * regardless of whether an ignored or
2505 * excluded file happened to be
2506 * encountered 1st.
2508 * In current usage, the
2509 * `stop_at_first_file` is passed when
2510 * an ancestor directory has matched
2511 * an exclude pattern, so any found
2512 * files will be excluded.
2514 if (dir_state >= path_excluded) {
2515 dir_state = path_excluded;
2516 break;
2520 /* abort early if maximum state has been reached */
2521 if (dir_state == path_untracked) {
2522 if (cdir.fdir)
2523 add_untracked(untracked, path.buf + baselen);
2524 break;
2526 /* skip the add_path_to_appropriate_result_list() */
2527 continue;
2530 add_path_to_appropriate_result_list(dir, untracked, &cdir,
2531 istate, &path, baselen,
2532 pathspec, state);
2534 close_cached_dir(&cdir);
2535 out:
2536 strbuf_release(&path);
2538 return dir_state;
2541 int cmp_dir_entry(const void *p1, const void *p2)
2543 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
2544 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
2546 return name_compare(e1->name, e1->len, e2->name, e2->len);
2549 /* check if *out lexically strictly contains *in */
2550 int check_dir_entry_contains(const struct dir_entry *out, const struct dir_entry *in)
2552 return (out->len < in->len) &&
2553 (out->name[out->len - 1] == '/') &&
2554 !memcmp(out->name, in->name, out->len);
2557 static int treat_leading_path(struct dir_struct *dir,
2558 struct index_state *istate,
2559 const char *path, int len,
2560 const struct pathspec *pathspec)
2562 struct strbuf sb = STRBUF_INIT;
2563 struct strbuf subdir = STRBUF_INIT;
2564 int prevlen, baselen;
2565 const char *cp;
2566 struct cached_dir cdir;
2567 enum path_treatment state = path_none;
2570 * For each directory component of path, we are going to check whether
2571 * that path is relevant given the pathspec. For example, if path is
2572 * foo/bar/baz/
2573 * then we will ask treat_path() whether we should go into foo, then
2574 * whether we should go into bar, then whether baz is relevant.
2575 * Checking each is important because e.g. if path is
2576 * .git/info/
2577 * then we need to check .git to know we shouldn't traverse it.
2578 * If the return from treat_path() is:
2579 * * path_none, for any path, we return false.
2580 * * path_recurse, for all path components, we return true
2581 * * <anything else> for some intermediate component, we make sure
2582 * to add that path to the relevant list but return false
2583 * signifying that we shouldn't recurse into it.
2586 while (len && path[len - 1] == '/')
2587 len--;
2588 if (!len)
2589 return 1;
2591 memset(&cdir, 0, sizeof(cdir));
2592 cdir.d_type = DT_DIR;
2593 baselen = 0;
2594 prevlen = 0;
2595 while (1) {
2596 prevlen = baselen + !!baselen;
2597 cp = path + prevlen;
2598 cp = memchr(cp, '/', path + len - cp);
2599 if (!cp)
2600 baselen = len;
2601 else
2602 baselen = cp - path;
2603 strbuf_reset(&sb);
2604 strbuf_add(&sb, path, baselen);
2605 if (!is_directory(sb.buf))
2606 break;
2607 strbuf_reset(&sb);
2608 strbuf_add(&sb, path, prevlen);
2609 strbuf_reset(&subdir);
2610 strbuf_add(&subdir, path+prevlen, baselen-prevlen);
2611 cdir.d_name = subdir.buf;
2612 state = treat_path(dir, NULL, &cdir, istate, &sb, prevlen, pathspec);
2614 if (state != path_recurse)
2615 break; /* do not recurse into it */
2616 if (len <= baselen)
2617 break; /* finished checking */
2619 add_path_to_appropriate_result_list(dir, NULL, &cdir, istate,
2620 &sb, baselen, pathspec,
2621 state);
2623 strbuf_release(&subdir);
2624 strbuf_release(&sb);
2625 return state == path_recurse;
2628 static const char *get_ident_string(void)
2630 static struct strbuf sb = STRBUF_INIT;
2631 struct utsname uts;
2633 if (sb.len)
2634 return sb.buf;
2635 if (uname(&uts) < 0)
2636 die_errno(_("failed to get kernel name and information"));
2637 strbuf_addf(&sb, "Location %s, system %s", get_git_work_tree(),
2638 uts.sysname);
2639 return sb.buf;
2642 static int ident_in_untracked(const struct untracked_cache *uc)
2645 * Previous git versions may have saved many NUL separated
2646 * strings in the "ident" field, but it is insane to manage
2647 * many locations, so just take care of the first one.
2650 return !strcmp(uc->ident.buf, get_ident_string());
2653 static void set_untracked_ident(struct untracked_cache *uc)
2655 strbuf_reset(&uc->ident);
2656 strbuf_addstr(&uc->ident, get_ident_string());
2659 * This strbuf used to contain a list of NUL separated
2660 * strings, so save NUL too for backward compatibility.
2662 strbuf_addch(&uc->ident, 0);
2665 static void new_untracked_cache(struct index_state *istate)
2667 struct untracked_cache *uc = xcalloc(1, sizeof(*uc));
2668 strbuf_init(&uc->ident, 100);
2669 uc->exclude_per_dir = ".gitignore";
2670 /* should be the same flags used by git-status */
2671 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;
2672 set_untracked_ident(uc);
2673 istate->untracked = uc;
2674 istate->cache_changed |= UNTRACKED_CHANGED;
2677 void add_untracked_cache(struct index_state *istate)
2679 if (!istate->untracked) {
2680 new_untracked_cache(istate);
2681 } else {
2682 if (!ident_in_untracked(istate->untracked)) {
2683 free_untracked_cache(istate->untracked);
2684 new_untracked_cache(istate);
2689 void remove_untracked_cache(struct index_state *istate)
2691 if (istate->untracked) {
2692 free_untracked_cache(istate->untracked);
2693 istate->untracked = NULL;
2694 istate->cache_changed |= UNTRACKED_CHANGED;
2698 static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,
2699 int base_len,
2700 const struct pathspec *pathspec)
2702 struct untracked_cache_dir *root;
2703 static int untracked_cache_disabled = -1;
2705 if (!dir->untracked)
2706 return NULL;
2707 if (untracked_cache_disabled < 0)
2708 untracked_cache_disabled = git_env_bool("GIT_DISABLE_UNTRACKED_CACHE", 0);
2709 if (untracked_cache_disabled)
2710 return NULL;
2713 * We only support $GIT_DIR/info/exclude and core.excludesfile
2714 * as the global ignore rule files. Any other additions
2715 * (e.g. from command line) invalidate the cache. This
2716 * condition also catches running setup_standard_excludes()
2717 * before setting dir->untracked!
2719 if (dir->unmanaged_exclude_files)
2720 return NULL;
2723 * Optimize for the main use case only: whole-tree git
2724 * status. More work involved in treat_leading_path() if we
2725 * use cache on just a subset of the worktree. pathspec
2726 * support could make the matter even worse.
2728 if (base_len || (pathspec && pathspec->nr))
2729 return NULL;
2731 /* Different set of flags may produce different results */
2732 if (dir->flags != dir->untracked->dir_flags ||
2734 * See treat_directory(), case index_nonexistent. Without
2735 * this flag, we may need to also cache .git file content
2736 * for the resolve_gitlink_ref() call, which we don't.
2738 !(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||
2739 /* We don't support collecting ignore files */
2740 (dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |
2741 DIR_COLLECT_IGNORED)))
2742 return NULL;
2745 * If we use .gitignore in the cache and now you change it to
2746 * .gitexclude, everything will go wrong.
2748 if (dir->exclude_per_dir != dir->untracked->exclude_per_dir &&
2749 strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))
2750 return NULL;
2753 * EXC_CMDL is not considered in the cache. If people set it,
2754 * skip the cache.
2756 if (dir->exclude_list_group[EXC_CMDL].nr)
2757 return NULL;
2759 if (!ident_in_untracked(dir->untracked)) {
2760 warning(_("untracked cache is disabled on this system or location"));
2761 return NULL;
2764 if (!dir->untracked->root)
2765 FLEX_ALLOC_STR(dir->untracked->root, name, "");
2767 /* Validate $GIT_DIR/info/exclude and core.excludesfile */
2768 root = dir->untracked->root;
2769 if (!oideq(&dir->ss_info_exclude.oid,
2770 &dir->untracked->ss_info_exclude.oid)) {
2771 invalidate_gitignore(dir->untracked, root);
2772 dir->untracked->ss_info_exclude = dir->ss_info_exclude;
2774 if (!oideq(&dir->ss_excludes_file.oid,
2775 &dir->untracked->ss_excludes_file.oid)) {
2776 invalidate_gitignore(dir->untracked, root);
2777 dir->untracked->ss_excludes_file = dir->ss_excludes_file;
2780 /* Make sure this directory is not dropped out at saving phase */
2781 root->recurse = 1;
2782 return root;
2785 static void emit_traversal_statistics(struct dir_struct *dir,
2786 struct repository *repo,
2787 const char *path,
2788 int path_len)
2790 if (!trace2_is_enabled())
2791 return;
2793 if (!path_len) {
2794 trace2_data_string("read_directory", repo, "path", "");
2795 } else {
2796 struct strbuf tmp = STRBUF_INIT;
2797 strbuf_add(&tmp, path, path_len);
2798 trace2_data_string("read_directory", repo, "path", tmp.buf);
2799 strbuf_release(&tmp);
2802 trace2_data_intmax("read_directory", repo,
2803 "directories-visited", dir->visited_directories);
2804 trace2_data_intmax("read_directory", repo,
2805 "paths-visited", dir->visited_paths);
2807 if (!dir->untracked)
2808 return;
2809 trace2_data_intmax("read_directory", repo,
2810 "node-creation", dir->untracked->dir_created);
2811 trace2_data_intmax("read_directory", repo,
2812 "gitignore-invalidation",
2813 dir->untracked->gitignore_invalidated);
2814 trace2_data_intmax("read_directory", repo,
2815 "directory-invalidation",
2816 dir->untracked->dir_invalidated);
2817 trace2_data_intmax("read_directory", repo,
2818 "opendir", dir->untracked->dir_opened);
2821 int read_directory(struct dir_struct *dir, struct index_state *istate,
2822 const char *path, int len, const struct pathspec *pathspec)
2824 struct untracked_cache_dir *untracked;
2826 trace2_region_enter("dir", "read_directory", istate->repo);
2827 dir->visited_paths = 0;
2828 dir->visited_directories = 0;
2830 if (has_symlink_leading_path(path, len)) {
2831 trace2_region_leave("dir", "read_directory", istate->repo);
2832 return dir->nr;
2835 untracked = validate_untracked_cache(dir, len, pathspec);
2836 if (!untracked)
2838 * make sure untracked cache code path is disabled,
2839 * e.g. prep_exclude()
2841 dir->untracked = NULL;
2842 if (!len || treat_leading_path(dir, istate, path, len, pathspec))
2843 read_directory_recursive(dir, istate, path, len, untracked, 0, 0, pathspec);
2844 QSORT(dir->entries, dir->nr, cmp_dir_entry);
2845 QSORT(dir->ignored, dir->ignored_nr, cmp_dir_entry);
2847 emit_traversal_statistics(dir, istate->repo, path, len);
2849 trace2_region_leave("dir", "read_directory", istate->repo);
2850 if (dir->untracked) {
2851 static int force_untracked_cache = -1;
2853 if (force_untracked_cache < 0)
2854 force_untracked_cache =
2855 git_env_bool("GIT_FORCE_UNTRACKED_CACHE", 0);
2856 if (force_untracked_cache &&
2857 dir->untracked == istate->untracked &&
2858 (dir->untracked->dir_opened ||
2859 dir->untracked->gitignore_invalidated ||
2860 dir->untracked->dir_invalidated))
2861 istate->cache_changed |= UNTRACKED_CHANGED;
2862 if (dir->untracked != istate->untracked) {
2863 FREE_AND_NULL(dir->untracked);
2867 return dir->nr;
2870 int file_exists(const char *f)
2872 struct stat sb;
2873 return lstat(f, &sb) == 0;
2876 int repo_file_exists(struct repository *repo, const char *path)
2878 if (repo != the_repository)
2879 BUG("do not know how to check file existence in arbitrary repo");
2881 return file_exists(path);
2884 static int cmp_icase(char a, char b)
2886 if (a == b)
2887 return 0;
2888 if (ignore_case)
2889 return toupper(a) - toupper(b);
2890 return a - b;
2894 * Given two normalized paths (a trailing slash is ok), if subdir is
2895 * outside dir, return -1. Otherwise return the offset in subdir that
2896 * can be used as relative path to dir.
2898 int dir_inside_of(const char *subdir, const char *dir)
2900 int offset = 0;
2902 assert(dir && subdir && *dir && *subdir);
2904 while (*dir && *subdir && !cmp_icase(*dir, *subdir)) {
2905 dir++;
2906 subdir++;
2907 offset++;
2910 /* hel[p]/me vs hel[l]/yeah */
2911 if (*dir && *subdir)
2912 return -1;
2914 if (!*subdir)
2915 return !*dir ? offset : -1; /* same dir */
2917 /* foo/[b]ar vs foo/[] */
2918 if (is_dir_sep(dir[-1]))
2919 return is_dir_sep(subdir[-1]) ? offset : -1;
2921 /* foo[/]bar vs foo[] */
2922 return is_dir_sep(*subdir) ? offset + 1 : -1;
2925 int is_inside_dir(const char *dir)
2927 char *cwd;
2928 int rc;
2930 if (!dir)
2931 return 0;
2933 cwd = xgetcwd();
2934 rc = (dir_inside_of(cwd, dir) >= 0);
2935 free(cwd);
2936 return rc;
2939 int is_empty_dir(const char *path)
2941 DIR *dir = opendir(path);
2942 struct dirent *e;
2943 int ret = 1;
2945 if (!dir)
2946 return 0;
2948 e = readdir_skip_dot_and_dotdot(dir);
2949 if (e)
2950 ret = 0;
2952 closedir(dir);
2953 return ret;
2956 static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
2958 DIR *dir;
2959 struct dirent *e;
2960 int ret = 0, original_len = path->len, len, kept_down = 0;
2961 int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
2962 int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
2963 struct object_id submodule_head;
2965 if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
2966 !resolve_gitlink_ref(path->buf, "HEAD", &submodule_head)) {
2967 /* Do not descend and nuke a nested git work tree. */
2968 if (kept_up)
2969 *kept_up = 1;
2970 return 0;
2973 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
2974 dir = opendir(path->buf);
2975 if (!dir) {
2976 if (errno == ENOENT)
2977 return keep_toplevel ? -1 : 0;
2978 else if (errno == EACCES && !keep_toplevel)
2980 * An empty dir could be removable even if it
2981 * is unreadable:
2983 return rmdir(path->buf);
2984 else
2985 return -1;
2987 strbuf_complete(path, '/');
2989 len = path->len;
2990 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
2991 struct stat st;
2993 strbuf_setlen(path, len);
2994 strbuf_addstr(path, e->d_name);
2995 if (lstat(path->buf, &st)) {
2996 if (errno == ENOENT)
2998 * file disappeared, which is what we
2999 * wanted anyway
3001 continue;
3002 /* fall through */
3003 } else if (S_ISDIR(st.st_mode)) {
3004 if (!remove_dir_recurse(path, flag, &kept_down))
3005 continue; /* happy */
3006 } else if (!only_empty &&
3007 (!unlink(path->buf) || errno == ENOENT)) {
3008 continue; /* happy, too */
3011 /* path too long, stat fails, or non-directory still exists */
3012 ret = -1;
3013 break;
3015 closedir(dir);
3017 strbuf_setlen(path, original_len);
3018 if (!ret && !keep_toplevel && !kept_down)
3019 ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1;
3020 else if (kept_up)
3022 * report the uplevel that it is not an error that we
3023 * did not rmdir() our directory.
3025 *kept_up = !ret;
3026 return ret;
3029 int remove_dir_recursively(struct strbuf *path, int flag)
3031 return remove_dir_recurse(path, flag, NULL);
3034 static GIT_PATH_FUNC(git_path_info_exclude, "info/exclude")
3036 void setup_standard_excludes(struct dir_struct *dir)
3038 dir->exclude_per_dir = ".gitignore";
3040 /* core.excludesfile defaulting to $XDG_CONFIG_HOME/git/ignore */
3041 if (!excludes_file)
3042 excludes_file = xdg_config_home("ignore");
3043 if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
3044 add_patterns_from_file_1(dir, excludes_file,
3045 dir->untracked ? &dir->ss_excludes_file : NULL);
3047 /* per repository user preference */
3048 if (startup_info->have_repository) {
3049 const char *path = git_path_info_exclude();
3050 if (!access_or_warn(path, R_OK, 0))
3051 add_patterns_from_file_1(dir, path,
3052 dir->untracked ? &dir->ss_info_exclude : NULL);
3056 char *get_sparse_checkout_filename(void)
3058 return git_pathdup("info/sparse-checkout");
3061 int get_sparse_checkout_patterns(struct pattern_list *pl)
3063 int res;
3064 char *sparse_filename = get_sparse_checkout_filename();
3066 pl->use_cone_patterns = core_sparse_checkout_cone;
3067 res = add_patterns_from_file_to_list(sparse_filename, "", 0, pl, NULL, 0);
3069 free(sparse_filename);
3070 return res;
3073 int remove_path(const char *name)
3075 char *slash;
3077 if (unlink(name) && !is_missing_file_error(errno))
3078 return -1;
3080 slash = strrchr(name, '/');
3081 if (slash) {
3082 char *dirs = xstrdup(name);
3083 slash = dirs + (slash - name);
3084 do {
3085 *slash = '\0';
3086 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
3087 free(dirs);
3089 return 0;
3093 * Frees memory within dir which was allocated, and resets fields for further
3094 * use. Does not free dir itself.
3096 void dir_clear(struct dir_struct *dir)
3098 int i, j;
3099 struct exclude_list_group *group;
3100 struct pattern_list *pl;
3101 struct exclude_stack *stk;
3102 struct dir_struct new = DIR_INIT;
3104 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
3105 group = &dir->exclude_list_group[i];
3106 for (j = 0; j < group->nr; j++) {
3107 pl = &group->pl[j];
3108 if (i == EXC_DIRS)
3109 free((char *)pl->src);
3110 clear_pattern_list(pl);
3112 free(group->pl);
3115 for (i = 0; i < dir->ignored_nr; i++)
3116 free(dir->ignored[i]);
3117 for (i = 0; i < dir->nr; i++)
3118 free(dir->entries[i]);
3119 free(dir->ignored);
3120 free(dir->entries);
3122 stk = dir->exclude_stack;
3123 while (stk) {
3124 struct exclude_stack *prev = stk->prev;
3125 free(stk);
3126 stk = prev;
3128 strbuf_release(&dir->basebuf);
3130 memcpy(dir, &new, sizeof(*dir));
3133 struct ondisk_untracked_cache {
3134 struct stat_data info_exclude_stat;
3135 struct stat_data excludes_file_stat;
3136 uint32_t dir_flags;
3139 #define ouc_offset(x) offsetof(struct ondisk_untracked_cache, x)
3141 struct write_data {
3142 int index; /* number of written untracked_cache_dir */
3143 struct ewah_bitmap *check_only; /* from untracked_cache_dir */
3144 struct ewah_bitmap *valid; /* from untracked_cache_dir */
3145 struct ewah_bitmap *sha1_valid; /* set if exclude_sha1 is not null */
3146 struct strbuf out;
3147 struct strbuf sb_stat;
3148 struct strbuf sb_sha1;
3151 static void stat_data_to_disk(struct stat_data *to, const struct stat_data *from)
3153 to->sd_ctime.sec = htonl(from->sd_ctime.sec);
3154 to->sd_ctime.nsec = htonl(from->sd_ctime.nsec);
3155 to->sd_mtime.sec = htonl(from->sd_mtime.sec);
3156 to->sd_mtime.nsec = htonl(from->sd_mtime.nsec);
3157 to->sd_dev = htonl(from->sd_dev);
3158 to->sd_ino = htonl(from->sd_ino);
3159 to->sd_uid = htonl(from->sd_uid);
3160 to->sd_gid = htonl(from->sd_gid);
3161 to->sd_size = htonl(from->sd_size);
3164 static void write_one_dir(struct untracked_cache_dir *untracked,
3165 struct write_data *wd)
3167 struct stat_data stat_data;
3168 struct strbuf *out = &wd->out;
3169 unsigned char intbuf[16];
3170 unsigned int intlen, value;
3171 int i = wd->index++;
3174 * untracked_nr should be reset whenever valid is clear, but
3175 * for safety..
3177 if (!untracked->valid) {
3178 untracked->untracked_nr = 0;
3179 untracked->check_only = 0;
3182 if (untracked->check_only)
3183 ewah_set(wd->check_only, i);
3184 if (untracked->valid) {
3185 ewah_set(wd->valid, i);
3186 stat_data_to_disk(&stat_data, &untracked->stat_data);
3187 strbuf_add(&wd->sb_stat, &stat_data, sizeof(stat_data));
3189 if (!is_null_oid(&untracked->exclude_oid)) {
3190 ewah_set(wd->sha1_valid, i);
3191 strbuf_add(&wd->sb_sha1, untracked->exclude_oid.hash,
3192 the_hash_algo->rawsz);
3195 intlen = encode_varint(untracked->untracked_nr, intbuf);
3196 strbuf_add(out, intbuf, intlen);
3198 /* skip non-recurse directories */
3199 for (i = 0, value = 0; i < untracked->dirs_nr; i++)
3200 if (untracked->dirs[i]->recurse)
3201 value++;
3202 intlen = encode_varint(value, intbuf);
3203 strbuf_add(out, intbuf, intlen);
3205 strbuf_add(out, untracked->name, strlen(untracked->name) + 1);
3207 for (i = 0; i < untracked->untracked_nr; i++)
3208 strbuf_add(out, untracked->untracked[i],
3209 strlen(untracked->untracked[i]) + 1);
3211 for (i = 0; i < untracked->dirs_nr; i++)
3212 if (untracked->dirs[i]->recurse)
3213 write_one_dir(untracked->dirs[i], wd);
3216 void write_untracked_extension(struct strbuf *out, struct untracked_cache *untracked)
3218 struct ondisk_untracked_cache *ouc;
3219 struct write_data wd;
3220 unsigned char varbuf[16];
3221 int varint_len;
3222 const unsigned hashsz = the_hash_algo->rawsz;
3224 CALLOC_ARRAY(ouc, 1);
3225 stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);
3226 stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);
3227 ouc->dir_flags = htonl(untracked->dir_flags);
3229 varint_len = encode_varint(untracked->ident.len, varbuf);
3230 strbuf_add(out, varbuf, varint_len);
3231 strbuf_addbuf(out, &untracked->ident);
3233 strbuf_add(out, ouc, sizeof(*ouc));
3234 strbuf_add(out, untracked->ss_info_exclude.oid.hash, hashsz);
3235 strbuf_add(out, untracked->ss_excludes_file.oid.hash, hashsz);
3236 strbuf_add(out, untracked->exclude_per_dir, strlen(untracked->exclude_per_dir) + 1);
3237 FREE_AND_NULL(ouc);
3239 if (!untracked->root) {
3240 varint_len = encode_varint(0, varbuf);
3241 strbuf_add(out, varbuf, varint_len);
3242 return;
3245 wd.index = 0;
3246 wd.check_only = ewah_new();
3247 wd.valid = ewah_new();
3248 wd.sha1_valid = ewah_new();
3249 strbuf_init(&wd.out, 1024);
3250 strbuf_init(&wd.sb_stat, 1024);
3251 strbuf_init(&wd.sb_sha1, 1024);
3252 write_one_dir(untracked->root, &wd);
3254 varint_len = encode_varint(wd.index, varbuf);
3255 strbuf_add(out, varbuf, varint_len);
3256 strbuf_addbuf(out, &wd.out);
3257 ewah_serialize_strbuf(wd.valid, out);
3258 ewah_serialize_strbuf(wd.check_only, out);
3259 ewah_serialize_strbuf(wd.sha1_valid, out);
3260 strbuf_addbuf(out, &wd.sb_stat);
3261 strbuf_addbuf(out, &wd.sb_sha1);
3262 strbuf_addch(out, '\0'); /* safe guard for string lists */
3264 ewah_free(wd.valid);
3265 ewah_free(wd.check_only);
3266 ewah_free(wd.sha1_valid);
3267 strbuf_release(&wd.out);
3268 strbuf_release(&wd.sb_stat);
3269 strbuf_release(&wd.sb_sha1);
3272 static void free_untracked(struct untracked_cache_dir *ucd)
3274 int i;
3275 if (!ucd)
3276 return;
3277 for (i = 0; i < ucd->dirs_nr; i++)
3278 free_untracked(ucd->dirs[i]);
3279 for (i = 0; i < ucd->untracked_nr; i++)
3280 free(ucd->untracked[i]);
3281 free(ucd->untracked);
3282 free(ucd->dirs);
3283 free(ucd);
3286 void free_untracked_cache(struct untracked_cache *uc)
3288 if (uc)
3289 free_untracked(uc->root);
3290 free(uc);
3293 struct read_data {
3294 int index;
3295 struct untracked_cache_dir **ucd;
3296 struct ewah_bitmap *check_only;
3297 struct ewah_bitmap *valid;
3298 struct ewah_bitmap *sha1_valid;
3299 const unsigned char *data;
3300 const unsigned char *end;
3303 static void stat_data_from_disk(struct stat_data *to, const unsigned char *data)
3305 memcpy(to, data, sizeof(*to));
3306 to->sd_ctime.sec = ntohl(to->sd_ctime.sec);
3307 to->sd_ctime.nsec = ntohl(to->sd_ctime.nsec);
3308 to->sd_mtime.sec = ntohl(to->sd_mtime.sec);
3309 to->sd_mtime.nsec = ntohl(to->sd_mtime.nsec);
3310 to->sd_dev = ntohl(to->sd_dev);
3311 to->sd_ino = ntohl(to->sd_ino);
3312 to->sd_uid = ntohl(to->sd_uid);
3313 to->sd_gid = ntohl(to->sd_gid);
3314 to->sd_size = ntohl(to->sd_size);
3317 static int read_one_dir(struct untracked_cache_dir **untracked_,
3318 struct read_data *rd)
3320 struct untracked_cache_dir ud, *untracked;
3321 const unsigned char *data = rd->data, *end = rd->end;
3322 const unsigned char *eos;
3323 unsigned int value;
3324 int i;
3326 memset(&ud, 0, sizeof(ud));
3328 value = decode_varint(&data);
3329 if (data > end)
3330 return -1;
3331 ud.recurse = 1;
3332 ud.untracked_alloc = value;
3333 ud.untracked_nr = value;
3334 if (ud.untracked_nr)
3335 ALLOC_ARRAY(ud.untracked, ud.untracked_nr);
3337 ud.dirs_alloc = ud.dirs_nr = decode_varint(&data);
3338 if (data > end)
3339 return -1;
3340 ALLOC_ARRAY(ud.dirs, ud.dirs_nr);
3342 eos = memchr(data, '\0', end - data);
3343 if (!eos || eos == end)
3344 return -1;
3346 *untracked_ = untracked = xmalloc(st_add3(sizeof(*untracked), eos - data, 1));
3347 memcpy(untracked, &ud, sizeof(ud));
3348 memcpy(untracked->name, data, eos - data + 1);
3349 data = eos + 1;
3351 for (i = 0; i < untracked->untracked_nr; i++) {
3352 eos = memchr(data, '\0', end - data);
3353 if (!eos || eos == end)
3354 return -1;
3355 untracked->untracked[i] = xmemdupz(data, eos - data);
3356 data = eos + 1;
3359 rd->ucd[rd->index++] = untracked;
3360 rd->data = data;
3362 for (i = 0; i < untracked->dirs_nr; i++) {
3363 if (read_one_dir(untracked->dirs + i, rd) < 0)
3364 return -1;
3366 return 0;
3369 static void set_check_only(size_t pos, void *cb)
3371 struct read_data *rd = cb;
3372 struct untracked_cache_dir *ud = rd->ucd[pos];
3373 ud->check_only = 1;
3376 static void read_stat(size_t pos, void *cb)
3378 struct read_data *rd = cb;
3379 struct untracked_cache_dir *ud = rd->ucd[pos];
3380 if (rd->data + sizeof(struct stat_data) > rd->end) {
3381 rd->data = rd->end + 1;
3382 return;
3384 stat_data_from_disk(&ud->stat_data, rd->data);
3385 rd->data += sizeof(struct stat_data);
3386 ud->valid = 1;
3389 static void read_oid(size_t pos, void *cb)
3391 struct read_data *rd = cb;
3392 struct untracked_cache_dir *ud = rd->ucd[pos];
3393 if (rd->data + the_hash_algo->rawsz > rd->end) {
3394 rd->data = rd->end + 1;
3395 return;
3397 oidread(&ud->exclude_oid, rd->data);
3398 rd->data += the_hash_algo->rawsz;
3401 static void load_oid_stat(struct oid_stat *oid_stat, const unsigned char *data,
3402 const unsigned char *sha1)
3404 stat_data_from_disk(&oid_stat->stat, data);
3405 oidread(&oid_stat->oid, sha1);
3406 oid_stat->valid = 1;
3409 struct untracked_cache *read_untracked_extension(const void *data, unsigned long sz)
3411 struct untracked_cache *uc;
3412 struct read_data rd;
3413 const unsigned char *next = data, *end = (const unsigned char *)data + sz;
3414 const char *ident;
3415 int ident_len;
3416 ssize_t len;
3417 const char *exclude_per_dir;
3418 const unsigned hashsz = the_hash_algo->rawsz;
3419 const unsigned offset = sizeof(struct ondisk_untracked_cache);
3420 const unsigned exclude_per_dir_offset = offset + 2 * hashsz;
3422 if (sz <= 1 || end[-1] != '\0')
3423 return NULL;
3424 end--;
3426 ident_len = decode_varint(&next);
3427 if (next + ident_len > end)
3428 return NULL;
3429 ident = (const char *)next;
3430 next += ident_len;
3432 if (next + exclude_per_dir_offset + 1 > end)
3433 return NULL;
3435 CALLOC_ARRAY(uc, 1);
3436 strbuf_init(&uc->ident, ident_len);
3437 strbuf_add(&uc->ident, ident, ident_len);
3438 load_oid_stat(&uc->ss_info_exclude,
3439 next + ouc_offset(info_exclude_stat),
3440 next + offset);
3441 load_oid_stat(&uc->ss_excludes_file,
3442 next + ouc_offset(excludes_file_stat),
3443 next + offset + hashsz);
3444 uc->dir_flags = get_be32(next + ouc_offset(dir_flags));
3445 exclude_per_dir = (const char *)next + exclude_per_dir_offset;
3446 uc->exclude_per_dir = xstrdup(exclude_per_dir);
3447 /* NUL after exclude_per_dir is covered by sizeof(*ouc) */
3448 next += exclude_per_dir_offset + strlen(exclude_per_dir) + 1;
3449 if (next >= end)
3450 goto done2;
3452 len = decode_varint(&next);
3453 if (next > end || len == 0)
3454 goto done2;
3456 rd.valid = ewah_new();
3457 rd.check_only = ewah_new();
3458 rd.sha1_valid = ewah_new();
3459 rd.data = next;
3460 rd.end = end;
3461 rd.index = 0;
3462 ALLOC_ARRAY(rd.ucd, len);
3464 if (read_one_dir(&uc->root, &rd) || rd.index != len)
3465 goto done;
3467 next = rd.data;
3468 len = ewah_read_mmap(rd.valid, next, end - next);
3469 if (len < 0)
3470 goto done;
3472 next += len;
3473 len = ewah_read_mmap(rd.check_only, next, end - next);
3474 if (len < 0)
3475 goto done;
3477 next += len;
3478 len = ewah_read_mmap(rd.sha1_valid, next, end - next);
3479 if (len < 0)
3480 goto done;
3482 ewah_each_bit(rd.check_only, set_check_only, &rd);
3483 rd.data = next + len;
3484 ewah_each_bit(rd.valid, read_stat, &rd);
3485 ewah_each_bit(rd.sha1_valid, read_oid, &rd);
3486 next = rd.data;
3488 done:
3489 free(rd.ucd);
3490 ewah_free(rd.valid);
3491 ewah_free(rd.check_only);
3492 ewah_free(rd.sha1_valid);
3493 done2:
3494 if (next != end) {
3495 free_untracked_cache(uc);
3496 uc = NULL;
3498 return uc;
3501 static void invalidate_one_directory(struct untracked_cache *uc,
3502 struct untracked_cache_dir *ucd)
3504 uc->dir_invalidated++;
3505 ucd->valid = 0;
3506 ucd->untracked_nr = 0;
3510 * Normally when an entry is added or removed from a directory,
3511 * invalidating that directory is enough. No need to touch its
3512 * ancestors. When a directory is shown as "foo/bar/" in git-status
3513 * however, deleting or adding an entry may have cascading effect.
3515 * Say the "foo/bar/file" has become untracked, we need to tell the
3516 * untracked_cache_dir of "foo" that "bar/" is not an untracked
3517 * directory any more (because "bar" is managed by foo as an untracked
3518 * "file").
3520 * Similarly, if "foo/bar/file" moves from untracked to tracked and it
3521 * was the last untracked entry in the entire "foo", we should show
3522 * "foo/" instead. Which means we have to invalidate past "bar" up to
3523 * "foo".
3525 * This function traverses all directories from root to leaf. If there
3526 * is a chance of one of the above cases happening, we invalidate back
3527 * to root. Otherwise we just invalidate the leaf. There may be a more
3528 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to
3529 * detect these cases and avoid unnecessary invalidation, for example,
3530 * checking for the untracked entry named "bar/" in "foo", but for now
3531 * stick to something safe and simple.
3533 static int invalidate_one_component(struct untracked_cache *uc,
3534 struct untracked_cache_dir *dir,
3535 const char *path, int len)
3537 const char *rest = strchr(path, '/');
3539 if (rest) {
3540 int component_len = rest - path;
3541 struct untracked_cache_dir *d =
3542 lookup_untracked(uc, dir, path, component_len);
3543 int ret =
3544 invalidate_one_component(uc, d, rest + 1,
3545 len - (component_len + 1));
3546 if (ret)
3547 invalidate_one_directory(uc, dir);
3548 return ret;
3551 invalidate_one_directory(uc, dir);
3552 return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;
3555 void untracked_cache_invalidate_path(struct index_state *istate,
3556 const char *path, int safe_path)
3558 if (!istate->untracked || !istate->untracked->root)
3559 return;
3560 if (!safe_path && !verify_path(path, 0))
3561 return;
3562 invalidate_one_component(istate->untracked, istate->untracked->root,
3563 path, strlen(path));
3566 void untracked_cache_remove_from_index(struct index_state *istate,
3567 const char *path)
3569 untracked_cache_invalidate_path(istate, path, 1);
3572 void untracked_cache_add_to_index(struct index_state *istate,
3573 const char *path)
3575 untracked_cache_invalidate_path(istate, path, 1);
3578 static void connect_wt_gitdir_in_nested(const char *sub_worktree,
3579 const char *sub_gitdir)
3581 int i;
3582 struct repository subrepo;
3583 struct strbuf sub_wt = STRBUF_INIT;
3584 struct strbuf sub_gd = STRBUF_INIT;
3586 const struct submodule *sub;
3588 /* If the submodule has no working tree, we can ignore it. */
3589 if (repo_init(&subrepo, sub_gitdir, sub_worktree))
3590 return;
3592 if (repo_read_index(&subrepo) < 0)
3593 die(_("index file corrupt in repo %s"), subrepo.gitdir);
3595 /* TODO: audit for interaction with sparse-index. */
3596 ensure_full_index(subrepo.index);
3597 for (i = 0; i < subrepo.index->cache_nr; i++) {
3598 const struct cache_entry *ce = subrepo.index->cache[i];
3600 if (!S_ISGITLINK(ce->ce_mode))
3601 continue;
3603 while (i + 1 < subrepo.index->cache_nr &&
3604 !strcmp(ce->name, subrepo.index->cache[i + 1]->name))
3606 * Skip entries with the same name in different stages
3607 * to make sure an entry is returned only once.
3609 i++;
3611 sub = submodule_from_path(&subrepo, null_oid(), ce->name);
3612 if (!sub || !is_submodule_active(&subrepo, ce->name))
3613 /* .gitmodules broken or inactive sub */
3614 continue;
3616 strbuf_reset(&sub_wt);
3617 strbuf_reset(&sub_gd);
3618 strbuf_addf(&sub_wt, "%s/%s", sub_worktree, sub->path);
3619 strbuf_addf(&sub_gd, "%s/modules/%s", sub_gitdir, sub->name);
3621 connect_work_tree_and_git_dir(sub_wt.buf, sub_gd.buf, 1);
3623 strbuf_release(&sub_wt);
3624 strbuf_release(&sub_gd);
3625 repo_clear(&subrepo);
3628 void connect_work_tree_and_git_dir(const char *work_tree_,
3629 const char *git_dir_,
3630 int recurse_into_nested)
3632 struct strbuf gitfile_sb = STRBUF_INIT;
3633 struct strbuf cfg_sb = STRBUF_INIT;
3634 struct strbuf rel_path = STRBUF_INIT;
3635 char *git_dir, *work_tree;
3637 /* Prepare .git file */
3638 strbuf_addf(&gitfile_sb, "%s/.git", work_tree_);
3639 if (safe_create_leading_directories_const(gitfile_sb.buf))
3640 die(_("could not create directories for %s"), gitfile_sb.buf);
3642 /* Prepare config file */
3643 strbuf_addf(&cfg_sb, "%s/config", git_dir_);
3644 if (safe_create_leading_directories_const(cfg_sb.buf))
3645 die(_("could not create directories for %s"), cfg_sb.buf);
3647 git_dir = real_pathdup(git_dir_, 1);
3648 work_tree = real_pathdup(work_tree_, 1);
3650 /* Write .git file */
3651 write_file(gitfile_sb.buf, "gitdir: %s",
3652 relative_path(git_dir, work_tree, &rel_path));
3653 /* Update core.worktree setting */
3654 git_config_set_in_file(cfg_sb.buf, "core.worktree",
3655 relative_path(work_tree, git_dir, &rel_path));
3657 strbuf_release(&gitfile_sb);
3658 strbuf_release(&cfg_sb);
3659 strbuf_release(&rel_path);
3661 if (recurse_into_nested)
3662 connect_wt_gitdir_in_nested(work_tree, git_dir);
3664 free(work_tree);
3665 free(git_dir);
3669 * Migrate the git directory of the given path from old_git_dir to new_git_dir.
3671 void relocate_gitdir(const char *path, const char *old_git_dir, const char *new_git_dir)
3673 if (rename(old_git_dir, new_git_dir) < 0)
3674 die_errno(_("could not migrate git directory from '%s' to '%s'"),
3675 old_git_dir, new_git_dir);
3677 connect_work_tree_and_git_dir(path, new_git_dir, 0);