untracked cache: make a wrapper around {open,read,close}dir()
[git/gitster.git] / dir.c
blob86bf6e9311cc7b08c89f9c362c7ed6b259a40bd8
1 /*
2 * This handles recursive filename detection with exclude
3 * files, index knowledge etc..
5 * See Documentation/technical/api-directory-listing.txt
7 * Copyright (C) Linus Torvalds, 2005-2006
8 * Junio Hamano, 2005-2006
9 */
10 #include "cache.h"
11 #include "dir.h"
12 #include "refs.h"
13 #include "wildmatch.h"
14 #include "pathspec.h"
16 struct path_simplify {
17 int len;
18 const char *path;
22 * Tells read_directory_recursive how a file or directory should be treated.
23 * Values are ordered by significance, e.g. if a directory contains both
24 * excluded and untracked files, it is listed as untracked because
25 * path_untracked > path_excluded.
27 enum path_treatment {
28 path_none = 0,
29 path_recurse,
30 path_excluded,
31 path_untracked
35 * Support data structure for our opendir/readdir/closedir wrappers
37 struct cached_dir {
38 DIR *fdir;
39 struct untracked_cache_dir *untracked;
40 struct dirent *de;
43 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
44 const char *path, int len, struct untracked_cache_dir *untracked,
45 int check_only, const struct path_simplify *simplify);
46 static int get_dtype(struct dirent *de, const char *path, int len);
48 /* helper string functions with support for the ignore_case flag */
49 int strcmp_icase(const char *a, const char *b)
51 return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
54 int strncmp_icase(const char *a, const char *b, size_t count)
56 return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
59 int fnmatch_icase(const char *pattern, const char *string, int flags)
61 return wildmatch(pattern, string,
62 flags | (ignore_case ? WM_CASEFOLD : 0),
63 NULL);
66 int git_fnmatch(const struct pathspec_item *item,
67 const char *pattern, const char *string,
68 int prefix)
70 if (prefix > 0) {
71 if (ps_strncmp(item, pattern, string, prefix))
72 return WM_NOMATCH;
73 pattern += prefix;
74 string += prefix;
76 if (item->flags & PATHSPEC_ONESTAR) {
77 int pattern_len = strlen(++pattern);
78 int string_len = strlen(string);
79 return string_len < pattern_len ||
80 ps_strcmp(item, pattern,
81 string + string_len - pattern_len);
83 if (item->magic & PATHSPEC_GLOB)
84 return wildmatch(pattern, string,
85 WM_PATHNAME |
86 (item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0),
87 NULL);
88 else
89 /* wildmatch has not learned no FNM_PATHNAME mode yet */
90 return wildmatch(pattern, string,
91 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0,
92 NULL);
95 static int fnmatch_icase_mem(const char *pattern, int patternlen,
96 const char *string, int stringlen,
97 int flags)
99 int match_status;
100 struct strbuf pat_buf = STRBUF_INIT;
101 struct strbuf str_buf = STRBUF_INIT;
102 const char *use_pat = pattern;
103 const char *use_str = string;
105 if (pattern[patternlen]) {
106 strbuf_add(&pat_buf, pattern, patternlen);
107 use_pat = pat_buf.buf;
109 if (string[stringlen]) {
110 strbuf_add(&str_buf, string, stringlen);
111 use_str = str_buf.buf;
114 if (ignore_case)
115 flags |= WM_CASEFOLD;
116 match_status = wildmatch(use_pat, use_str, flags, NULL);
118 strbuf_release(&pat_buf);
119 strbuf_release(&str_buf);
121 return match_status;
124 static size_t common_prefix_len(const struct pathspec *pathspec)
126 int n;
127 size_t max = 0;
130 * ":(icase)path" is treated as a pathspec full of
131 * wildcard. In other words, only prefix is considered common
132 * prefix. If the pathspec is abc/foo abc/bar, running in
133 * subdir xyz, the common prefix is still xyz, not xuz/abc as
134 * in non-:(icase).
136 GUARD_PATHSPEC(pathspec,
137 PATHSPEC_FROMTOP |
138 PATHSPEC_MAXDEPTH |
139 PATHSPEC_LITERAL |
140 PATHSPEC_GLOB |
141 PATHSPEC_ICASE |
142 PATHSPEC_EXCLUDE);
144 for (n = 0; n < pathspec->nr; n++) {
145 size_t i = 0, len = 0, item_len;
146 if (pathspec->items[n].magic & PATHSPEC_EXCLUDE)
147 continue;
148 if (pathspec->items[n].magic & PATHSPEC_ICASE)
149 item_len = pathspec->items[n].prefix;
150 else
151 item_len = pathspec->items[n].nowildcard_len;
152 while (i < item_len && (n == 0 || i < max)) {
153 char c = pathspec->items[n].match[i];
154 if (c != pathspec->items[0].match[i])
155 break;
156 if (c == '/')
157 len = i + 1;
158 i++;
160 if (n == 0 || len < max) {
161 max = len;
162 if (!max)
163 break;
166 return max;
170 * Returns a copy of the longest leading path common among all
171 * pathspecs.
173 char *common_prefix(const struct pathspec *pathspec)
175 unsigned long len = common_prefix_len(pathspec);
177 return len ? xmemdupz(pathspec->items[0].match, len) : NULL;
180 int fill_directory(struct dir_struct *dir, const struct pathspec *pathspec)
182 size_t len;
185 * Calculate common prefix for the pathspec, and
186 * use that to optimize the directory walk
188 len = common_prefix_len(pathspec);
190 /* Read the directory and prune it */
191 read_directory(dir, pathspec->nr ? pathspec->_raw[0] : "", len, pathspec);
192 return len;
195 int within_depth(const char *name, int namelen,
196 int depth, int max_depth)
198 const char *cp = name, *cpe = name + namelen;
200 while (cp < cpe) {
201 if (*cp++ != '/')
202 continue;
203 depth++;
204 if (depth > max_depth)
205 return 0;
207 return 1;
210 #define DO_MATCH_EXCLUDE 1
211 #define DO_MATCH_DIRECTORY 2
214 * Does 'match' match the given name?
215 * A match is found if
217 * (1) the 'match' string is leading directory of 'name', or
218 * (2) the 'match' string is a wildcard and matches 'name', or
219 * (3) the 'match' string is exactly the same as 'name'.
221 * and the return value tells which case it was.
223 * It returns 0 when there is no match.
225 static int match_pathspec_item(const struct pathspec_item *item, int prefix,
226 const char *name, int namelen, unsigned flags)
228 /* name/namelen has prefix cut off by caller */
229 const char *match = item->match + prefix;
230 int matchlen = item->len - prefix;
233 * The normal call pattern is:
234 * 1. prefix = common_prefix_len(ps);
235 * 2. prune something, or fill_directory
236 * 3. match_pathspec()
238 * 'prefix' at #1 may be shorter than the command's prefix and
239 * it's ok for #2 to match extra files. Those extras will be
240 * trimmed at #3.
242 * Suppose the pathspec is 'foo' and '../bar' running from
243 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
244 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
245 * user does not want XYZ/foo, only the "foo" part should be
246 * case-insensitive. We need to filter out XYZ/foo here. In
247 * other words, we do not trust the caller on comparing the
248 * prefix part when :(icase) is involved. We do exact
249 * comparison ourselves.
251 * Normally the caller (common_prefix_len() in fact) does
252 * _exact_ matching on name[-prefix+1..-1] and we do not need
253 * to check that part. Be defensive and check it anyway, in
254 * case common_prefix_len is changed, or a new caller is
255 * introduced that does not use common_prefix_len.
257 * If the penalty turns out too high when prefix is really
258 * long, maybe change it to
259 * strncmp(match, name, item->prefix - prefix)
261 if (item->prefix && (item->magic & PATHSPEC_ICASE) &&
262 strncmp(item->match, name - prefix, item->prefix))
263 return 0;
265 /* If the match was just the prefix, we matched */
266 if (!*match)
267 return MATCHED_RECURSIVELY;
269 if (matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) {
270 if (matchlen == namelen)
271 return MATCHED_EXACTLY;
273 if (match[matchlen-1] == '/' || name[matchlen] == '/')
274 return MATCHED_RECURSIVELY;
275 } else if ((flags & DO_MATCH_DIRECTORY) &&
276 match[matchlen - 1] == '/' &&
277 namelen == matchlen - 1 &&
278 !ps_strncmp(item, match, name, namelen))
279 return MATCHED_EXACTLY;
281 if (item->nowildcard_len < item->len &&
282 !git_fnmatch(item, match, name,
283 item->nowildcard_len - prefix))
284 return MATCHED_FNMATCH;
286 return 0;
290 * Given a name and a list of pathspecs, returns the nature of the
291 * closest (i.e. most specific) match of the name to any of the
292 * pathspecs.
294 * The caller typically calls this multiple times with the same
295 * pathspec and seen[] array but with different name/namelen
296 * (e.g. entries from the index) and is interested in seeing if and
297 * how each pathspec matches all the names it calls this function
298 * with. A mark is left in the seen[] array for each pathspec element
299 * indicating the closest type of match that element achieved, so if
300 * seen[n] remains zero after multiple invocations, that means the nth
301 * pathspec did not match any names, which could indicate that the
302 * user mistyped the nth pathspec.
304 static int do_match_pathspec(const struct pathspec *ps,
305 const char *name, int namelen,
306 int prefix, char *seen,
307 unsigned flags)
309 int i, retval = 0, exclude = flags & DO_MATCH_EXCLUDE;
311 GUARD_PATHSPEC(ps,
312 PATHSPEC_FROMTOP |
313 PATHSPEC_MAXDEPTH |
314 PATHSPEC_LITERAL |
315 PATHSPEC_GLOB |
316 PATHSPEC_ICASE |
317 PATHSPEC_EXCLUDE);
319 if (!ps->nr) {
320 if (!ps->recursive ||
321 !(ps->magic & PATHSPEC_MAXDEPTH) ||
322 ps->max_depth == -1)
323 return MATCHED_RECURSIVELY;
325 if (within_depth(name, namelen, 0, ps->max_depth))
326 return MATCHED_EXACTLY;
327 else
328 return 0;
331 name += prefix;
332 namelen -= prefix;
334 for (i = ps->nr - 1; i >= 0; i--) {
335 int how;
337 if ((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) ||
338 ( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE)))
339 continue;
341 if (seen && seen[i] == MATCHED_EXACTLY)
342 continue;
344 * Make exclude patterns optional and never report
345 * "pathspec ':(exclude)foo' matches no files"
347 if (seen && ps->items[i].magic & PATHSPEC_EXCLUDE)
348 seen[i] = MATCHED_FNMATCH;
349 how = match_pathspec_item(ps->items+i, prefix, name,
350 namelen, flags);
351 if (ps->recursive &&
352 (ps->magic & PATHSPEC_MAXDEPTH) &&
353 ps->max_depth != -1 &&
354 how && how != MATCHED_FNMATCH) {
355 int len = ps->items[i].len;
356 if (name[len] == '/')
357 len++;
358 if (within_depth(name+len, namelen-len, 0, ps->max_depth))
359 how = MATCHED_EXACTLY;
360 else
361 how = 0;
363 if (how) {
364 if (retval < how)
365 retval = how;
366 if (seen && seen[i] < how)
367 seen[i] = how;
370 return retval;
373 int match_pathspec(const struct pathspec *ps,
374 const char *name, int namelen,
375 int prefix, char *seen, int is_dir)
377 int positive, negative;
378 unsigned flags = is_dir ? DO_MATCH_DIRECTORY : 0;
379 positive = do_match_pathspec(ps, name, namelen,
380 prefix, seen, flags);
381 if (!(ps->magic & PATHSPEC_EXCLUDE) || !positive)
382 return positive;
383 negative = do_match_pathspec(ps, name, namelen,
384 prefix, seen,
385 flags | DO_MATCH_EXCLUDE);
386 return negative ? 0 : positive;
390 * Return the length of the "simple" part of a path match limiter.
392 int simple_length(const char *match)
394 int len = -1;
396 for (;;) {
397 unsigned char c = *match++;
398 len++;
399 if (c == '\0' || is_glob_special(c))
400 return len;
404 int no_wildcard(const char *string)
406 return string[simple_length(string)] == '\0';
409 void parse_exclude_pattern(const char **pattern,
410 int *patternlen,
411 int *flags,
412 int *nowildcardlen)
414 const char *p = *pattern;
415 size_t i, len;
417 *flags = 0;
418 if (*p == '!') {
419 *flags |= EXC_FLAG_NEGATIVE;
420 p++;
422 len = strlen(p);
423 if (len && p[len - 1] == '/') {
424 len--;
425 *flags |= EXC_FLAG_MUSTBEDIR;
427 for (i = 0; i < len; i++) {
428 if (p[i] == '/')
429 break;
431 if (i == len)
432 *flags |= EXC_FLAG_NODIR;
433 *nowildcardlen = simple_length(p);
435 * we should have excluded the trailing slash from 'p' too,
436 * but that's one more allocation. Instead just make sure
437 * nowildcardlen does not exceed real patternlen
439 if (*nowildcardlen > len)
440 *nowildcardlen = len;
441 if (*p == '*' && no_wildcard(p + 1))
442 *flags |= EXC_FLAG_ENDSWITH;
443 *pattern = p;
444 *patternlen = len;
447 void add_exclude(const char *string, const char *base,
448 int baselen, struct exclude_list *el, int srcpos)
450 struct exclude *x;
451 int patternlen;
452 int flags;
453 int nowildcardlen;
455 parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen);
456 if (flags & EXC_FLAG_MUSTBEDIR) {
457 char *s;
458 x = xmalloc(sizeof(*x) + patternlen + 1);
459 s = (char *)(x+1);
460 memcpy(s, string, patternlen);
461 s[patternlen] = '\0';
462 x->pattern = s;
463 } else {
464 x = xmalloc(sizeof(*x));
465 x->pattern = string;
467 x->patternlen = patternlen;
468 x->nowildcardlen = nowildcardlen;
469 x->base = base;
470 x->baselen = baselen;
471 x->flags = flags;
472 x->srcpos = srcpos;
473 ALLOC_GROW(el->excludes, el->nr + 1, el->alloc);
474 el->excludes[el->nr++] = x;
475 x->el = el;
478 static void *read_skip_worktree_file_from_index(const char *path, size_t *size,
479 struct sha1_stat *sha1_stat)
481 int pos, len;
482 unsigned long sz;
483 enum object_type type;
484 void *data;
486 len = strlen(path);
487 pos = cache_name_pos(path, len);
488 if (pos < 0)
489 return NULL;
490 if (!ce_skip_worktree(active_cache[pos]))
491 return NULL;
492 data = read_sha1_file(active_cache[pos]->sha1, &type, &sz);
493 if (!data || type != OBJ_BLOB) {
494 free(data);
495 return NULL;
497 *size = xsize_t(sz);
498 if (sha1_stat) {
499 memset(&sha1_stat->stat, 0, sizeof(sha1_stat->stat));
500 hashcpy(sha1_stat->sha1, active_cache[pos]->sha1);
502 return data;
506 * Frees memory within el which was allocated for exclude patterns and
507 * the file buffer. Does not free el itself.
509 void clear_exclude_list(struct exclude_list *el)
511 int i;
513 for (i = 0; i < el->nr; i++)
514 free(el->excludes[i]);
515 free(el->excludes);
516 free(el->filebuf);
518 el->nr = 0;
519 el->excludes = NULL;
520 el->filebuf = NULL;
523 static void trim_trailing_spaces(char *buf)
525 char *p, *last_space = NULL;
527 for (p = buf; *p; p++)
528 switch (*p) {
529 case ' ':
530 if (!last_space)
531 last_space = p;
532 break;
533 case '\\':
534 p++;
535 if (!*p)
536 return;
537 /* fallthrough */
538 default:
539 last_space = NULL;
542 if (last_space)
543 *last_space = '\0';
547 * Given a subdirectory name and "dir" of the current directory,
548 * search the subdir in "dir" and return it, or create a new one if it
549 * does not exist in "dir".
551 * If "name" has the trailing slash, it'll be excluded in the search.
553 static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc,
554 struct untracked_cache_dir *dir,
555 const char *name, int len)
557 int first, last;
558 struct untracked_cache_dir *d;
559 if (!dir)
560 return NULL;
561 if (len && name[len - 1] == '/')
562 len--;
563 first = 0;
564 last = dir->dirs_nr;
565 while (last > first) {
566 int cmp, next = (last + first) >> 1;
567 d = dir->dirs[next];
568 cmp = strncmp(name, d->name, len);
569 if (!cmp && strlen(d->name) > len)
570 cmp = -1;
571 if (!cmp)
572 return d;
573 if (cmp < 0) {
574 last = next;
575 continue;
577 first = next+1;
580 uc->dir_created++;
581 d = xmalloc(sizeof(*d) + len + 1);
582 memset(d, 0, sizeof(*d));
583 memcpy(d->name, name, len);
584 d->name[len] = '\0';
586 ALLOC_GROW(dir->dirs, dir->dirs_nr + 1, dir->dirs_alloc);
587 memmove(dir->dirs + first + 1, dir->dirs + first,
588 (dir->dirs_nr - first) * sizeof(*dir->dirs));
589 dir->dirs_nr++;
590 dir->dirs[first] = d;
591 return d;
594 static void do_invalidate_gitignore(struct untracked_cache_dir *dir)
596 int i;
597 dir->valid = 0;
598 dir->untracked_nr = 0;
599 for (i = 0; i < dir->dirs_nr; i++)
600 do_invalidate_gitignore(dir->dirs[i]);
603 static void invalidate_gitignore(struct untracked_cache *uc,
604 struct untracked_cache_dir *dir)
606 uc->gitignore_invalidated++;
607 do_invalidate_gitignore(dir);
611 * Given a file with name "fname", read it (either from disk, or from
612 * the index if "check_index" is non-zero), parse it and store the
613 * exclude rules in "el".
615 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill
616 * stat data from disk (only valid if add_excludes returns zero). If
617 * ss_valid is non-zero, "ss" must contain good value as input.
619 static int add_excludes(const char *fname, const char *base, int baselen,
620 struct exclude_list *el, int check_index,
621 struct sha1_stat *sha1_stat)
623 struct stat st;
624 int fd, i, lineno = 1;
625 size_t size = 0;
626 char *buf, *entry;
628 fd = open(fname, O_RDONLY);
629 if (fd < 0 || fstat(fd, &st) < 0) {
630 if (errno != ENOENT)
631 warn_on_inaccessible(fname);
632 if (0 <= fd)
633 close(fd);
634 if (!check_index ||
635 (buf = read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL)
636 return -1;
637 if (size == 0) {
638 free(buf);
639 return 0;
641 if (buf[size-1] != '\n') {
642 buf = xrealloc(buf, size+1);
643 buf[size++] = '\n';
645 } else {
646 size = xsize_t(st.st_size);
647 if (size == 0) {
648 if (sha1_stat) {
649 fill_stat_data(&sha1_stat->stat, &st);
650 hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN);
651 sha1_stat->valid = 1;
653 close(fd);
654 return 0;
656 buf = xmalloc(size+1);
657 if (read_in_full(fd, buf, size) != size) {
658 free(buf);
659 close(fd);
660 return -1;
662 buf[size++] = '\n';
663 close(fd);
664 if (sha1_stat) {
665 int pos;
666 if (sha1_stat->valid &&
667 !match_stat_data(&sha1_stat->stat, &st))
668 ; /* no content change, ss->sha1 still good */
669 else if (check_index &&
670 (pos = cache_name_pos(fname, strlen(fname))) >= 0 &&
671 !ce_stage(active_cache[pos]) &&
672 ce_uptodate(active_cache[pos]) &&
673 !would_convert_to_git(fname))
674 hashcpy(sha1_stat->sha1, active_cache[pos]->sha1);
675 else
676 hash_sha1_file(buf, size, "blob", sha1_stat->sha1);
677 fill_stat_data(&sha1_stat->stat, &st);
678 sha1_stat->valid = 1;
682 el->filebuf = buf;
683 entry = buf;
684 for (i = 0; i < size; i++) {
685 if (buf[i] == '\n') {
686 if (entry != buf + i && entry[0] != '#') {
687 buf[i - (i && buf[i-1] == '\r')] = 0;
688 trim_trailing_spaces(entry);
689 add_exclude(entry, base, baselen, el, lineno);
691 lineno++;
692 entry = buf + i + 1;
695 return 0;
698 int add_excludes_from_file_to_list(const char *fname, const char *base,
699 int baselen, struct exclude_list *el,
700 int check_index)
702 return add_excludes(fname, base, baselen, el, check_index, NULL);
705 struct exclude_list *add_exclude_list(struct dir_struct *dir,
706 int group_type, const char *src)
708 struct exclude_list *el;
709 struct exclude_list_group *group;
711 group = &dir->exclude_list_group[group_type];
712 ALLOC_GROW(group->el, group->nr + 1, group->alloc);
713 el = &group->el[group->nr++];
714 memset(el, 0, sizeof(*el));
715 el->src = src;
716 return el;
720 * Used to set up core.excludesfile and .git/info/exclude lists.
722 static void add_excludes_from_file_1(struct dir_struct *dir, const char *fname,
723 struct sha1_stat *sha1_stat)
725 struct exclude_list *el;
727 * catch setup_standard_excludes() that's called before
728 * dir->untracked is assigned. That function behaves
729 * differently when dir->untracked is non-NULL.
731 if (!dir->untracked)
732 dir->unmanaged_exclude_files++;
733 el = add_exclude_list(dir, EXC_FILE, fname);
734 if (add_excludes(fname, "", 0, el, 0, sha1_stat) < 0)
735 die("cannot use %s as an exclude file", fname);
738 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
740 dir->unmanaged_exclude_files++; /* see validate_untracked_cache() */
741 add_excludes_from_file_1(dir, fname, NULL);
744 int match_basename(const char *basename, int basenamelen,
745 const char *pattern, int prefix, int patternlen,
746 int flags)
748 if (prefix == patternlen) {
749 if (patternlen == basenamelen &&
750 !strncmp_icase(pattern, basename, basenamelen))
751 return 1;
752 } else if (flags & EXC_FLAG_ENDSWITH) {
753 /* "*literal" matching against "fooliteral" */
754 if (patternlen - 1 <= basenamelen &&
755 !strncmp_icase(pattern + 1,
756 basename + basenamelen - (patternlen - 1),
757 patternlen - 1))
758 return 1;
759 } else {
760 if (fnmatch_icase_mem(pattern, patternlen,
761 basename, basenamelen,
762 0) == 0)
763 return 1;
765 return 0;
768 int match_pathname(const char *pathname, int pathlen,
769 const char *base, int baselen,
770 const char *pattern, int prefix, int patternlen,
771 int flags)
773 const char *name;
774 int namelen;
777 * match with FNM_PATHNAME; the pattern has base implicitly
778 * in front of it.
780 if (*pattern == '/') {
781 pattern++;
782 patternlen--;
783 prefix--;
787 * baselen does not count the trailing slash. base[] may or
788 * may not end with a trailing slash though.
790 if (pathlen < baselen + 1 ||
791 (baselen && pathname[baselen] != '/') ||
792 strncmp_icase(pathname, base, baselen))
793 return 0;
795 namelen = baselen ? pathlen - baselen - 1 : pathlen;
796 name = pathname + pathlen - namelen;
798 if (prefix) {
800 * if the non-wildcard part is longer than the
801 * remaining pathname, surely it cannot match.
803 if (prefix > namelen)
804 return 0;
806 if (strncmp_icase(pattern, name, prefix))
807 return 0;
808 pattern += prefix;
809 patternlen -= prefix;
810 name += prefix;
811 namelen -= prefix;
814 * If the whole pattern did not have a wildcard,
815 * then our prefix match is all we need; we
816 * do not need to call fnmatch at all.
818 if (!patternlen && !namelen)
819 return 1;
822 return fnmatch_icase_mem(pattern, patternlen,
823 name, namelen,
824 WM_PATHNAME) == 0;
828 * Scan the given exclude list in reverse to see whether pathname
829 * should be ignored. The first match (i.e. the last on the list), if
830 * any, determines the fate. Returns the exclude_list element which
831 * matched, or NULL for undecided.
833 static struct exclude *last_exclude_matching_from_list(const char *pathname,
834 int pathlen,
835 const char *basename,
836 int *dtype,
837 struct exclude_list *el)
839 int i;
841 if (!el->nr)
842 return NULL; /* undefined */
844 for (i = el->nr - 1; 0 <= i; i--) {
845 struct exclude *x = el->excludes[i];
846 const char *exclude = x->pattern;
847 int prefix = x->nowildcardlen;
849 if (x->flags & EXC_FLAG_MUSTBEDIR) {
850 if (*dtype == DT_UNKNOWN)
851 *dtype = get_dtype(NULL, pathname, pathlen);
852 if (*dtype != DT_DIR)
853 continue;
856 if (x->flags & EXC_FLAG_NODIR) {
857 if (match_basename(basename,
858 pathlen - (basename - pathname),
859 exclude, prefix, x->patternlen,
860 x->flags))
861 return x;
862 continue;
865 assert(x->baselen == 0 || x->base[x->baselen - 1] == '/');
866 if (match_pathname(pathname, pathlen,
867 x->base, x->baselen ? x->baselen - 1 : 0,
868 exclude, prefix, x->patternlen, x->flags))
869 return x;
871 return NULL; /* undecided */
875 * Scan the list and let the last match determine the fate.
876 * Return 1 for exclude, 0 for include and -1 for undecided.
878 int is_excluded_from_list(const char *pathname,
879 int pathlen, const char *basename, int *dtype,
880 struct exclude_list *el)
882 struct exclude *exclude;
883 exclude = last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el);
884 if (exclude)
885 return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
886 return -1; /* undecided */
889 static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir,
890 const char *pathname, int pathlen, const char *basename,
891 int *dtype_p)
893 int i, j;
894 struct exclude_list_group *group;
895 struct exclude *exclude;
896 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
897 group = &dir->exclude_list_group[i];
898 for (j = group->nr - 1; j >= 0; j--) {
899 exclude = last_exclude_matching_from_list(
900 pathname, pathlen, basename, dtype_p,
901 &group->el[j]);
902 if (exclude)
903 return exclude;
906 return NULL;
910 * Loads the per-directory exclude list for the substring of base
911 * which has a char length of baselen.
913 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
915 struct exclude_list_group *group;
916 struct exclude_list *el;
917 struct exclude_stack *stk = NULL;
918 struct untracked_cache_dir *untracked;
919 int current;
921 group = &dir->exclude_list_group[EXC_DIRS];
924 * Pop the exclude lists from the EXCL_DIRS exclude_list_group
925 * which originate from directories not in the prefix of the
926 * path being checked.
928 while ((stk = dir->exclude_stack) != NULL) {
929 if (stk->baselen <= baselen &&
930 !strncmp(dir->basebuf.buf, base, stk->baselen))
931 break;
932 el = &group->el[dir->exclude_stack->exclude_ix];
933 dir->exclude_stack = stk->prev;
934 dir->exclude = NULL;
935 free((char *)el->src); /* see strbuf_detach() below */
936 clear_exclude_list(el);
937 free(stk);
938 group->nr--;
941 /* Skip traversing into sub directories if the parent is excluded */
942 if (dir->exclude)
943 return;
946 * Lazy initialization. All call sites currently just
947 * memset(dir, 0, sizeof(*dir)) before use. Changing all of
948 * them seems lots of work for little benefit.
950 if (!dir->basebuf.buf)
951 strbuf_init(&dir->basebuf, PATH_MAX);
953 /* Read from the parent directories and push them down. */
954 current = stk ? stk->baselen : -1;
955 strbuf_setlen(&dir->basebuf, current < 0 ? 0 : current);
956 if (dir->untracked)
957 untracked = stk ? stk->ucd : dir->untracked->root;
958 else
959 untracked = NULL;
961 while (current < baselen) {
962 const char *cp;
963 struct sha1_stat sha1_stat;
965 stk = xcalloc(1, sizeof(*stk));
966 if (current < 0) {
967 cp = base;
968 current = 0;
969 } else {
970 cp = strchr(base + current + 1, '/');
971 if (!cp)
972 die("oops in prep_exclude");
973 cp++;
974 untracked =
975 lookup_untracked(dir->untracked, untracked,
976 base + current,
977 cp - base - current);
979 stk->prev = dir->exclude_stack;
980 stk->baselen = cp - base;
981 stk->exclude_ix = group->nr;
982 stk->ucd = untracked;
983 el = add_exclude_list(dir, EXC_DIRS, NULL);
984 strbuf_add(&dir->basebuf, base + current, stk->baselen - current);
985 assert(stk->baselen == dir->basebuf.len);
987 /* Abort if the directory is excluded */
988 if (stk->baselen) {
989 int dt = DT_DIR;
990 dir->basebuf.buf[stk->baselen - 1] = 0;
991 dir->exclude = last_exclude_matching_from_lists(dir,
992 dir->basebuf.buf, stk->baselen - 1,
993 dir->basebuf.buf + current, &dt);
994 dir->basebuf.buf[stk->baselen - 1] = '/';
995 if (dir->exclude &&
996 dir->exclude->flags & EXC_FLAG_NEGATIVE)
997 dir->exclude = NULL;
998 if (dir->exclude) {
999 dir->exclude_stack = stk;
1000 return;
1004 /* Try to read per-directory file */
1005 hashclr(sha1_stat.sha1);
1006 sha1_stat.valid = 0;
1007 if (dir->exclude_per_dir) {
1009 * dir->basebuf gets reused by the traversal, but we
1010 * need fname to remain unchanged to ensure the src
1011 * member of each struct exclude correctly
1012 * back-references its source file. Other invocations
1013 * of add_exclude_list provide stable strings, so we
1014 * strbuf_detach() and free() here in the caller.
1016 struct strbuf sb = STRBUF_INIT;
1017 strbuf_addbuf(&sb, &dir->basebuf);
1018 strbuf_addstr(&sb, dir->exclude_per_dir);
1019 el->src = strbuf_detach(&sb, NULL);
1020 add_excludes(el->src, el->src, stk->baselen, el, 1,
1021 untracked ? &sha1_stat : NULL);
1024 * NEEDSWORK: when untracked cache is enabled, prep_exclude()
1025 * will first be called in valid_cached_dir() then maybe many
1026 * times more in last_exclude_matching(). When the cache is
1027 * used, last_exclude_matching() will not be called and
1028 * reading .gitignore content will be a waste.
1030 * So when it's called by valid_cached_dir() and we can get
1031 * .gitignore SHA-1 from the index (i.e. .gitignore is not
1032 * modified on work tree), we could delay reading the
1033 * .gitignore content until we absolutely need it in
1034 * last_exclude_matching(). Be careful about ignore rule
1035 * order, though, if you do that.
1037 if (untracked &&
1038 hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {
1039 invalidate_gitignore(dir->untracked, untracked);
1040 hashcpy(untracked->exclude_sha1, sha1_stat.sha1);
1042 dir->exclude_stack = stk;
1043 current = stk->baselen;
1045 strbuf_setlen(&dir->basebuf, baselen);
1049 * Loads the exclude lists for the directory containing pathname, then
1050 * scans all exclude lists to determine whether pathname is excluded.
1051 * Returns the exclude_list element which matched, or NULL for
1052 * undecided.
1054 struct exclude *last_exclude_matching(struct dir_struct *dir,
1055 const char *pathname,
1056 int *dtype_p)
1058 int pathlen = strlen(pathname);
1059 const char *basename = strrchr(pathname, '/');
1060 basename = (basename) ? basename+1 : pathname;
1062 prep_exclude(dir, pathname, basename-pathname);
1064 if (dir->exclude)
1065 return dir->exclude;
1067 return last_exclude_matching_from_lists(dir, pathname, pathlen,
1068 basename, dtype_p);
1072 * Loads the exclude lists for the directory containing pathname, then
1073 * scans all exclude lists to determine whether pathname is excluded.
1074 * Returns 1 if true, otherwise 0.
1076 int is_excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
1078 struct exclude *exclude =
1079 last_exclude_matching(dir, pathname, dtype_p);
1080 if (exclude)
1081 return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
1082 return 0;
1085 static struct dir_entry *dir_entry_new(const char *pathname, int len)
1087 struct dir_entry *ent;
1089 ent = xmalloc(sizeof(*ent) + len + 1);
1090 ent->len = len;
1091 memcpy(ent->name, pathname, len);
1092 ent->name[len] = 0;
1093 return ent;
1096 static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
1098 if (cache_file_exists(pathname, len, ignore_case))
1099 return NULL;
1101 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
1102 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
1105 struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
1107 if (!cache_name_is_other(pathname, len))
1108 return NULL;
1110 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
1111 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
1114 enum exist_status {
1115 index_nonexistent = 0,
1116 index_directory,
1117 index_gitdir
1121 * Do not use the alphabetically sorted index to look up
1122 * the directory name; instead, use the case insensitive
1123 * directory hash.
1125 static enum exist_status directory_exists_in_index_icase(const char *dirname, int len)
1127 const struct cache_entry *ce = cache_dir_exists(dirname, len);
1128 unsigned char endchar;
1130 if (!ce)
1131 return index_nonexistent;
1132 endchar = ce->name[len];
1135 * The cache_entry structure returned will contain this dirname
1136 * and possibly additional path components.
1138 if (endchar == '/')
1139 return index_directory;
1142 * If there are no additional path components, then this cache_entry
1143 * represents a submodule. Submodules, despite being directories,
1144 * are stored in the cache without a closing slash.
1146 if (!endchar && S_ISGITLINK(ce->ce_mode))
1147 return index_gitdir;
1149 /* This should never be hit, but it exists just in case. */
1150 return index_nonexistent;
1154 * The index sorts alphabetically by entry name, which
1155 * means that a gitlink sorts as '\0' at the end, while
1156 * a directory (which is defined not as an entry, but as
1157 * the files it contains) will sort with the '/' at the
1158 * end.
1160 static enum exist_status directory_exists_in_index(const char *dirname, int len)
1162 int pos;
1164 if (ignore_case)
1165 return directory_exists_in_index_icase(dirname, len);
1167 pos = cache_name_pos(dirname, len);
1168 if (pos < 0)
1169 pos = -pos-1;
1170 while (pos < active_nr) {
1171 const struct cache_entry *ce = active_cache[pos++];
1172 unsigned char endchar;
1174 if (strncmp(ce->name, dirname, len))
1175 break;
1176 endchar = ce->name[len];
1177 if (endchar > '/')
1178 break;
1179 if (endchar == '/')
1180 return index_directory;
1181 if (!endchar && S_ISGITLINK(ce->ce_mode))
1182 return index_gitdir;
1184 return index_nonexistent;
1188 * When we find a directory when traversing the filesystem, we
1189 * have three distinct cases:
1191 * - ignore it
1192 * - see it as a directory
1193 * - recurse into it
1195 * and which one we choose depends on a combination of existing
1196 * git index contents and the flags passed into the directory
1197 * traversal routine.
1199 * Case 1: If we *already* have entries in the index under that
1200 * directory name, we always recurse into the directory to see
1201 * all the files.
1203 * Case 2: If we *already* have that directory name as a gitlink,
1204 * we always continue to see it as a gitlink, regardless of whether
1205 * there is an actual git directory there or not (it might not
1206 * be checked out as a subproject!)
1208 * Case 3: if we didn't have it in the index previously, we
1209 * have a few sub-cases:
1211 * (a) if "show_other_directories" is true, we show it as
1212 * just a directory, unless "hide_empty_directories" is
1213 * also true, in which case we need to check if it contains any
1214 * untracked and / or ignored files.
1215 * (b) if it looks like a git directory, and we don't have
1216 * 'no_gitlinks' set we treat it as a gitlink, and show it
1217 * as a directory.
1218 * (c) otherwise, we recurse into it.
1220 static enum path_treatment treat_directory(struct dir_struct *dir,
1221 struct untracked_cache_dir *untracked,
1222 const char *dirname, int len, int exclude,
1223 const struct path_simplify *simplify)
1225 /* The "len-1" is to strip the final '/' */
1226 switch (directory_exists_in_index(dirname, len-1)) {
1227 case index_directory:
1228 return path_recurse;
1230 case index_gitdir:
1231 return path_none;
1233 case index_nonexistent:
1234 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
1235 break;
1236 if (!(dir->flags & DIR_NO_GITLINKS)) {
1237 unsigned char sha1[20];
1238 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
1239 return path_untracked;
1241 return path_recurse;
1244 /* This is the "show_other_directories" case */
1246 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1247 return exclude ? path_excluded : path_untracked;
1249 untracked = lookup_untracked(dir->untracked, untracked, dirname, len);
1250 return read_directory_recursive(dir, dirname, len,
1251 untracked, 1, simplify);
1255 * This is an inexact early pruning of any recursive directory
1256 * reading - if the path cannot possibly be in the pathspec,
1257 * return true, and we'll skip it early.
1259 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
1261 if (simplify) {
1262 for (;;) {
1263 const char *match = simplify->path;
1264 int len = simplify->len;
1266 if (!match)
1267 break;
1268 if (len > pathlen)
1269 len = pathlen;
1270 if (!memcmp(path, match, len))
1271 return 0;
1272 simplify++;
1274 return 1;
1276 return 0;
1280 * This function tells us whether an excluded path matches a
1281 * list of "interesting" pathspecs. That is, whether a path matched
1282 * by any of the pathspecs could possibly be ignored by excluding
1283 * the specified path. This can happen if:
1285 * 1. the path is mentioned explicitly in the pathspec
1287 * 2. the path is a directory prefix of some element in the
1288 * pathspec
1290 static int exclude_matches_pathspec(const char *path, int len,
1291 const struct path_simplify *simplify)
1293 if (simplify) {
1294 for (; simplify->path; simplify++) {
1295 if (len == simplify->len
1296 && !memcmp(path, simplify->path, len))
1297 return 1;
1298 if (len < simplify->len
1299 && simplify->path[len] == '/'
1300 && !memcmp(path, simplify->path, len))
1301 return 1;
1304 return 0;
1307 static int get_index_dtype(const char *path, int len)
1309 int pos;
1310 const struct cache_entry *ce;
1312 ce = cache_file_exists(path, len, 0);
1313 if (ce) {
1314 if (!ce_uptodate(ce))
1315 return DT_UNKNOWN;
1316 if (S_ISGITLINK(ce->ce_mode))
1317 return DT_DIR;
1319 * Nobody actually cares about the
1320 * difference between DT_LNK and DT_REG
1322 return DT_REG;
1325 /* Try to look it up as a directory */
1326 pos = cache_name_pos(path, len);
1327 if (pos >= 0)
1328 return DT_UNKNOWN;
1329 pos = -pos-1;
1330 while (pos < active_nr) {
1331 ce = active_cache[pos++];
1332 if (strncmp(ce->name, path, len))
1333 break;
1334 if (ce->name[len] > '/')
1335 break;
1336 if (ce->name[len] < '/')
1337 continue;
1338 if (!ce_uptodate(ce))
1339 break; /* continue? */
1340 return DT_DIR;
1342 return DT_UNKNOWN;
1345 static int get_dtype(struct dirent *de, const char *path, int len)
1347 int dtype = de ? DTYPE(de) : DT_UNKNOWN;
1348 struct stat st;
1350 if (dtype != DT_UNKNOWN)
1351 return dtype;
1352 dtype = get_index_dtype(path, len);
1353 if (dtype != DT_UNKNOWN)
1354 return dtype;
1355 if (lstat(path, &st))
1356 return dtype;
1357 if (S_ISREG(st.st_mode))
1358 return DT_REG;
1359 if (S_ISDIR(st.st_mode))
1360 return DT_DIR;
1361 if (S_ISLNK(st.st_mode))
1362 return DT_LNK;
1363 return dtype;
1366 static enum path_treatment treat_one_path(struct dir_struct *dir,
1367 struct untracked_cache_dir *untracked,
1368 struct strbuf *path,
1369 const struct path_simplify *simplify,
1370 int dtype, struct dirent *de)
1372 int exclude;
1373 int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);
1375 if (dtype == DT_UNKNOWN)
1376 dtype = get_dtype(de, path->buf, path->len);
1378 /* Always exclude indexed files */
1379 if (dtype != DT_DIR && has_path_in_index)
1380 return path_none;
1383 * When we are looking at a directory P in the working tree,
1384 * there are three cases:
1386 * (1) P exists in the index. Everything inside the directory P in
1387 * the working tree needs to go when P is checked out from the
1388 * index.
1390 * (2) P does not exist in the index, but there is P/Q in the index.
1391 * We know P will stay a directory when we check out the contents
1392 * of the index, but we do not know yet if there is a directory
1393 * P/Q in the working tree to be killed, so we need to recurse.
1395 * (3) P does not exist in the index, and there is no P/Q in the index
1396 * to require P to be a directory, either. Only in this case, we
1397 * know that everything inside P will not be killed without
1398 * recursing.
1400 if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
1401 (dtype == DT_DIR) &&
1402 !has_path_in_index &&
1403 (directory_exists_in_index(path->buf, path->len) == index_nonexistent))
1404 return path_none;
1406 exclude = is_excluded(dir, path->buf, &dtype);
1409 * Excluded? If we don't explicitly want to show
1410 * ignored files, ignore it
1412 if (exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
1413 return path_excluded;
1415 switch (dtype) {
1416 default:
1417 return path_none;
1418 case DT_DIR:
1419 strbuf_addch(path, '/');
1420 return treat_directory(dir, untracked, path->buf, path->len, exclude,
1421 simplify);
1422 case DT_REG:
1423 case DT_LNK:
1424 return exclude ? path_excluded : path_untracked;
1428 static enum path_treatment treat_path(struct dir_struct *dir,
1429 struct untracked_cache_dir *untracked,
1430 struct cached_dir *cdir,
1431 struct strbuf *path,
1432 int baselen,
1433 const struct path_simplify *simplify)
1435 int dtype;
1436 struct dirent *de = cdir->de;
1438 if (is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name, ".git"))
1439 return path_none;
1440 strbuf_setlen(path, baselen);
1441 strbuf_addstr(path, de->d_name);
1442 if (simplify_away(path->buf, path->len, simplify))
1443 return path_none;
1445 dtype = DTYPE(de);
1446 return treat_one_path(dir, untracked, path, simplify, dtype, de);
1449 static void add_untracked(struct untracked_cache_dir *dir, const char *name)
1451 if (!dir)
1452 return;
1453 ALLOC_GROW(dir->untracked, dir->untracked_nr + 1,
1454 dir->untracked_alloc);
1455 dir->untracked[dir->untracked_nr++] = xstrdup(name);
1458 static int open_cached_dir(struct cached_dir *cdir,
1459 struct dir_struct *dir,
1460 struct untracked_cache_dir *untracked,
1461 struct strbuf *path,
1462 int check_only)
1464 memset(cdir, 0, sizeof(*cdir));
1465 cdir->untracked = untracked;
1466 cdir->fdir = opendir(path->len ? path->buf : ".");
1467 if (!cdir->fdir)
1468 return -1;
1469 return 0;
1472 static int read_cached_dir(struct cached_dir *cdir)
1474 if (cdir->fdir) {
1475 cdir->de = readdir(cdir->fdir);
1476 if (!cdir->de)
1477 return -1;
1478 return 0;
1480 return -1;
1483 static void close_cached_dir(struct cached_dir *cdir)
1485 if (cdir->fdir)
1486 closedir(cdir->fdir);
1490 * Read a directory tree. We currently ignore anything but
1491 * directories, regular files and symlinks. That's because git
1492 * doesn't handle them at all yet. Maybe that will change some
1493 * day.
1495 * Also, we ignore the name ".git" (even if it is not a directory).
1496 * That likely will not change.
1498 * Returns the most significant path_treatment value encountered in the scan.
1500 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
1501 const char *base, int baselen,
1502 struct untracked_cache_dir *untracked, int check_only,
1503 const struct path_simplify *simplify)
1505 struct cached_dir cdir;
1506 enum path_treatment state, subdir_state, dir_state = path_none;
1507 struct strbuf path = STRBUF_INIT;
1509 strbuf_add(&path, base, baselen);
1511 if (open_cached_dir(&cdir, dir, untracked, &path, check_only))
1512 goto out;
1514 if (untracked)
1515 untracked->check_only = !!check_only;
1517 while (!read_cached_dir(&cdir)) {
1518 /* check how the file or directory should be treated */
1519 state = treat_path(dir, untracked, &cdir, &path, baselen, simplify);
1521 if (state > dir_state)
1522 dir_state = state;
1524 /* recurse into subdir if instructed by treat_path */
1525 if (state == path_recurse) {
1526 struct untracked_cache_dir *ud;
1527 ud = lookup_untracked(dir->untracked, untracked,
1528 path.buf + baselen,
1529 path.len - baselen);
1530 subdir_state =
1531 read_directory_recursive(dir, path.buf, path.len,
1532 ud, check_only, simplify);
1533 if (subdir_state > dir_state)
1534 dir_state = subdir_state;
1537 if (check_only) {
1538 /* abort early if maximum state has been reached */
1539 if (dir_state == path_untracked) {
1540 if (untracked)
1541 add_untracked(untracked, path.buf + baselen);
1542 break;
1544 /* skip the dir_add_* part */
1545 continue;
1548 /* add the path to the appropriate result list */
1549 switch (state) {
1550 case path_excluded:
1551 if (dir->flags & DIR_SHOW_IGNORED)
1552 dir_add_name(dir, path.buf, path.len);
1553 else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
1554 ((dir->flags & DIR_COLLECT_IGNORED) &&
1555 exclude_matches_pathspec(path.buf, path.len,
1556 simplify)))
1557 dir_add_ignored(dir, path.buf, path.len);
1558 break;
1560 case path_untracked:
1561 if (dir->flags & DIR_SHOW_IGNORED)
1562 break;
1563 dir_add_name(dir, path.buf, path.len);
1564 if (untracked)
1565 add_untracked(untracked, path.buf + baselen);
1566 break;
1568 default:
1569 break;
1572 close_cached_dir(&cdir);
1573 out:
1574 strbuf_release(&path);
1576 return dir_state;
1579 static int cmp_name(const void *p1, const void *p2)
1581 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
1582 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
1584 return name_compare(e1->name, e1->len, e2->name, e2->len);
1587 static struct path_simplify *create_simplify(const char **pathspec)
1589 int nr, alloc = 0;
1590 struct path_simplify *simplify = NULL;
1592 if (!pathspec)
1593 return NULL;
1595 for (nr = 0 ; ; nr++) {
1596 const char *match;
1597 ALLOC_GROW(simplify, nr + 1, alloc);
1598 match = *pathspec++;
1599 if (!match)
1600 break;
1601 simplify[nr].path = match;
1602 simplify[nr].len = simple_length(match);
1604 simplify[nr].path = NULL;
1605 simplify[nr].len = 0;
1606 return simplify;
1609 static void free_simplify(struct path_simplify *simplify)
1611 free(simplify);
1614 static int treat_leading_path(struct dir_struct *dir,
1615 const char *path, int len,
1616 const struct path_simplify *simplify)
1618 struct strbuf sb = STRBUF_INIT;
1619 int baselen, rc = 0;
1620 const char *cp;
1621 int old_flags = dir->flags;
1623 while (len && path[len - 1] == '/')
1624 len--;
1625 if (!len)
1626 return 1;
1627 baselen = 0;
1628 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;
1629 while (1) {
1630 cp = path + baselen + !!baselen;
1631 cp = memchr(cp, '/', path + len - cp);
1632 if (!cp)
1633 baselen = len;
1634 else
1635 baselen = cp - path;
1636 strbuf_setlen(&sb, 0);
1637 strbuf_add(&sb, path, baselen);
1638 if (!is_directory(sb.buf))
1639 break;
1640 if (simplify_away(sb.buf, sb.len, simplify))
1641 break;
1642 if (treat_one_path(dir, NULL, &sb, simplify,
1643 DT_DIR, NULL) == path_none)
1644 break; /* do not recurse into it */
1645 if (len <= baselen) {
1646 rc = 1;
1647 break; /* finished checking */
1650 strbuf_release(&sb);
1651 dir->flags = old_flags;
1652 return rc;
1655 static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,
1656 int base_len,
1657 const struct pathspec *pathspec)
1659 struct untracked_cache_dir *root;
1661 if (!dir->untracked)
1662 return NULL;
1665 * We only support $GIT_DIR/info/exclude and core.excludesfile
1666 * as the global ignore rule files. Any other additions
1667 * (e.g. from command line) invalidate the cache. This
1668 * condition also catches running setup_standard_excludes()
1669 * before setting dir->untracked!
1671 if (dir->unmanaged_exclude_files)
1672 return NULL;
1675 * Optimize for the main use case only: whole-tree git
1676 * status. More work involved in treat_leading_path() if we
1677 * use cache on just a subset of the worktree. pathspec
1678 * support could make the matter even worse.
1680 if (base_len || (pathspec && pathspec->nr))
1681 return NULL;
1683 /* Different set of flags may produce different results */
1684 if (dir->flags != dir->untracked->dir_flags ||
1686 * See treat_directory(), case index_nonexistent. Without
1687 * this flag, we may need to also cache .git file content
1688 * for the resolve_gitlink_ref() call, which we don't.
1690 !(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||
1691 /* We don't support collecting ignore files */
1692 (dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |
1693 DIR_COLLECT_IGNORED)))
1694 return NULL;
1697 * If we use .gitignore in the cache and now you change it to
1698 * .gitexclude, everything will go wrong.
1700 if (dir->exclude_per_dir != dir->untracked->exclude_per_dir &&
1701 strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))
1702 return NULL;
1705 * EXC_CMDL is not considered in the cache. If people set it,
1706 * skip the cache.
1708 if (dir->exclude_list_group[EXC_CMDL].nr)
1709 return NULL;
1711 if (!dir->untracked->root) {
1712 const int len = sizeof(*dir->untracked->root);
1713 dir->untracked->root = xmalloc(len);
1714 memset(dir->untracked->root, 0, len);
1717 /* Validate $GIT_DIR/info/exclude and core.excludesfile */
1718 root = dir->untracked->root;
1719 if (hashcmp(dir->ss_info_exclude.sha1,
1720 dir->untracked->ss_info_exclude.sha1)) {
1721 invalidate_gitignore(dir->untracked, root);
1722 dir->untracked->ss_info_exclude = dir->ss_info_exclude;
1724 if (hashcmp(dir->ss_excludes_file.sha1,
1725 dir->untracked->ss_excludes_file.sha1)) {
1726 invalidate_gitignore(dir->untracked, root);
1727 dir->untracked->ss_excludes_file = dir->ss_excludes_file;
1729 return root;
1732 int read_directory(struct dir_struct *dir, const char *path, int len, const struct pathspec *pathspec)
1734 struct path_simplify *simplify;
1735 struct untracked_cache_dir *untracked;
1738 * Check out create_simplify()
1740 if (pathspec)
1741 GUARD_PATHSPEC(pathspec,
1742 PATHSPEC_FROMTOP |
1743 PATHSPEC_MAXDEPTH |
1744 PATHSPEC_LITERAL |
1745 PATHSPEC_GLOB |
1746 PATHSPEC_ICASE |
1747 PATHSPEC_EXCLUDE);
1749 if (has_symlink_leading_path(path, len))
1750 return dir->nr;
1753 * exclude patterns are treated like positive ones in
1754 * create_simplify. Usually exclude patterns should be a
1755 * subset of positive ones, which has no impacts on
1756 * create_simplify().
1758 simplify = create_simplify(pathspec ? pathspec->_raw : NULL);
1759 untracked = validate_untracked_cache(dir, len, pathspec);
1760 if (!untracked)
1762 * make sure untracked cache code path is disabled,
1763 * e.g. prep_exclude()
1765 dir->untracked = NULL;
1766 if (!len || treat_leading_path(dir, path, len, simplify))
1767 read_directory_recursive(dir, path, len, untracked, 0, simplify);
1768 free_simplify(simplify);
1769 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
1770 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
1771 return dir->nr;
1774 int file_exists(const char *f)
1776 struct stat sb;
1777 return lstat(f, &sb) == 0;
1781 * Given two normalized paths (a trailing slash is ok), if subdir is
1782 * outside dir, return -1. Otherwise return the offset in subdir that
1783 * can be used as relative path to dir.
1785 int dir_inside_of(const char *subdir, const char *dir)
1787 int offset = 0;
1789 assert(dir && subdir && *dir && *subdir);
1791 while (*dir && *subdir && *dir == *subdir) {
1792 dir++;
1793 subdir++;
1794 offset++;
1797 /* hel[p]/me vs hel[l]/yeah */
1798 if (*dir && *subdir)
1799 return -1;
1801 if (!*subdir)
1802 return !*dir ? offset : -1; /* same dir */
1804 /* foo/[b]ar vs foo/[] */
1805 if (is_dir_sep(dir[-1]))
1806 return is_dir_sep(subdir[-1]) ? offset : -1;
1808 /* foo[/]bar vs foo[] */
1809 return is_dir_sep(*subdir) ? offset + 1 : -1;
1812 int is_inside_dir(const char *dir)
1814 char *cwd;
1815 int rc;
1817 if (!dir)
1818 return 0;
1820 cwd = xgetcwd();
1821 rc = (dir_inside_of(cwd, dir) >= 0);
1822 free(cwd);
1823 return rc;
1826 int is_empty_dir(const char *path)
1828 DIR *dir = opendir(path);
1829 struct dirent *e;
1830 int ret = 1;
1832 if (!dir)
1833 return 0;
1835 while ((e = readdir(dir)) != NULL)
1836 if (!is_dot_or_dotdot(e->d_name)) {
1837 ret = 0;
1838 break;
1841 closedir(dir);
1842 return ret;
1845 static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
1847 DIR *dir;
1848 struct dirent *e;
1849 int ret = 0, original_len = path->len, len, kept_down = 0;
1850 int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
1851 int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
1852 unsigned char submodule_head[20];
1854 if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
1855 !resolve_gitlink_ref(path->buf, "HEAD", submodule_head)) {
1856 /* Do not descend and nuke a nested git work tree. */
1857 if (kept_up)
1858 *kept_up = 1;
1859 return 0;
1862 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
1863 dir = opendir(path->buf);
1864 if (!dir) {
1865 if (errno == ENOENT)
1866 return keep_toplevel ? -1 : 0;
1867 else if (errno == EACCES && !keep_toplevel)
1869 * An empty dir could be removable even if it
1870 * is unreadable:
1872 return rmdir(path->buf);
1873 else
1874 return -1;
1876 if (path->buf[original_len - 1] != '/')
1877 strbuf_addch(path, '/');
1879 len = path->len;
1880 while ((e = readdir(dir)) != NULL) {
1881 struct stat st;
1882 if (is_dot_or_dotdot(e->d_name))
1883 continue;
1885 strbuf_setlen(path, len);
1886 strbuf_addstr(path, e->d_name);
1887 if (lstat(path->buf, &st)) {
1888 if (errno == ENOENT)
1890 * file disappeared, which is what we
1891 * wanted anyway
1893 continue;
1894 /* fall thru */
1895 } else if (S_ISDIR(st.st_mode)) {
1896 if (!remove_dir_recurse(path, flag, &kept_down))
1897 continue; /* happy */
1898 } else if (!only_empty &&
1899 (!unlink(path->buf) || errno == ENOENT)) {
1900 continue; /* happy, too */
1903 /* path too long, stat fails, or non-directory still exists */
1904 ret = -1;
1905 break;
1907 closedir(dir);
1909 strbuf_setlen(path, original_len);
1910 if (!ret && !keep_toplevel && !kept_down)
1911 ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1;
1912 else if (kept_up)
1914 * report the uplevel that it is not an error that we
1915 * did not rmdir() our directory.
1917 *kept_up = !ret;
1918 return ret;
1921 int remove_dir_recursively(struct strbuf *path, int flag)
1923 return remove_dir_recurse(path, flag, NULL);
1926 void setup_standard_excludes(struct dir_struct *dir)
1928 const char *path;
1929 char *xdg_path;
1931 dir->exclude_per_dir = ".gitignore";
1932 path = git_path("info/exclude");
1933 if (!excludes_file) {
1934 home_config_paths(NULL, &xdg_path, "ignore");
1935 excludes_file = xdg_path;
1937 if (!access_or_warn(path, R_OK, 0))
1938 add_excludes_from_file_1(dir, path,
1939 dir->untracked ? &dir->ss_info_exclude : NULL);
1940 if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
1941 add_excludes_from_file_1(dir, excludes_file,
1942 dir->untracked ? &dir->ss_excludes_file : NULL);
1945 int remove_path(const char *name)
1947 char *slash;
1949 if (unlink(name) && errno != ENOENT && errno != ENOTDIR)
1950 return -1;
1952 slash = strrchr(name, '/');
1953 if (slash) {
1954 char *dirs = xstrdup(name);
1955 slash = dirs + (slash - name);
1956 do {
1957 *slash = '\0';
1958 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
1959 free(dirs);
1961 return 0;
1965 * Frees memory within dir which was allocated for exclude lists and
1966 * the exclude_stack. Does not free dir itself.
1968 void clear_directory(struct dir_struct *dir)
1970 int i, j;
1971 struct exclude_list_group *group;
1972 struct exclude_list *el;
1973 struct exclude_stack *stk;
1975 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
1976 group = &dir->exclude_list_group[i];
1977 for (j = 0; j < group->nr; j++) {
1978 el = &group->el[j];
1979 if (i == EXC_DIRS)
1980 free((char *)el->src);
1981 clear_exclude_list(el);
1983 free(group->el);
1986 stk = dir->exclude_stack;
1987 while (stk) {
1988 struct exclude_stack *prev = stk->prev;
1989 free(stk);
1990 stk = prev;
1992 strbuf_release(&dir->basebuf);