untracked cache: initial untracked cache validation
[git/debian.git] / dir.c
bloba0654885b6d04a473c9296277746d5cf9e107e8a
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
34 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
35 const char *path, int len, struct untracked_cache_dir *untracked,
36 int check_only, const struct path_simplify *simplify);
37 static int get_dtype(struct dirent *de, const char *path, int len);
39 /* helper string functions with support for the ignore_case flag */
40 int strcmp_icase(const char *a, const char *b)
42 return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
45 int strncmp_icase(const char *a, const char *b, size_t count)
47 return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
50 int fnmatch_icase(const char *pattern, const char *string, int flags)
52 return wildmatch(pattern, string,
53 flags | (ignore_case ? WM_CASEFOLD : 0),
54 NULL);
57 int git_fnmatch(const struct pathspec_item *item,
58 const char *pattern, const char *string,
59 int prefix)
61 if (prefix > 0) {
62 if (ps_strncmp(item, pattern, string, prefix))
63 return WM_NOMATCH;
64 pattern += prefix;
65 string += prefix;
67 if (item->flags & PATHSPEC_ONESTAR) {
68 int pattern_len = strlen(++pattern);
69 int string_len = strlen(string);
70 return string_len < pattern_len ||
71 ps_strcmp(item, pattern,
72 string + string_len - pattern_len);
74 if (item->magic & PATHSPEC_GLOB)
75 return wildmatch(pattern, string,
76 WM_PATHNAME |
77 (item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0),
78 NULL);
79 else
80 /* wildmatch has not learned no FNM_PATHNAME mode yet */
81 return wildmatch(pattern, string,
82 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0,
83 NULL);
86 static int fnmatch_icase_mem(const char *pattern, int patternlen,
87 const char *string, int stringlen,
88 int flags)
90 int match_status;
91 struct strbuf pat_buf = STRBUF_INIT;
92 struct strbuf str_buf = STRBUF_INIT;
93 const char *use_pat = pattern;
94 const char *use_str = string;
96 if (pattern[patternlen]) {
97 strbuf_add(&pat_buf, pattern, patternlen);
98 use_pat = pat_buf.buf;
100 if (string[stringlen]) {
101 strbuf_add(&str_buf, string, stringlen);
102 use_str = str_buf.buf;
105 if (ignore_case)
106 flags |= WM_CASEFOLD;
107 match_status = wildmatch(use_pat, use_str, flags, NULL);
109 strbuf_release(&pat_buf);
110 strbuf_release(&str_buf);
112 return match_status;
115 static size_t common_prefix_len(const struct pathspec *pathspec)
117 int n;
118 size_t max = 0;
121 * ":(icase)path" is treated as a pathspec full of
122 * wildcard. In other words, only prefix is considered common
123 * prefix. If the pathspec is abc/foo abc/bar, running in
124 * subdir xyz, the common prefix is still xyz, not xuz/abc as
125 * in non-:(icase).
127 GUARD_PATHSPEC(pathspec,
128 PATHSPEC_FROMTOP |
129 PATHSPEC_MAXDEPTH |
130 PATHSPEC_LITERAL |
131 PATHSPEC_GLOB |
132 PATHSPEC_ICASE |
133 PATHSPEC_EXCLUDE);
135 for (n = 0; n < pathspec->nr; n++) {
136 size_t i = 0, len = 0, item_len;
137 if (pathspec->items[n].magic & PATHSPEC_EXCLUDE)
138 continue;
139 if (pathspec->items[n].magic & PATHSPEC_ICASE)
140 item_len = pathspec->items[n].prefix;
141 else
142 item_len = pathspec->items[n].nowildcard_len;
143 while (i < item_len && (n == 0 || i < max)) {
144 char c = pathspec->items[n].match[i];
145 if (c != pathspec->items[0].match[i])
146 break;
147 if (c == '/')
148 len = i + 1;
149 i++;
151 if (n == 0 || len < max) {
152 max = len;
153 if (!max)
154 break;
157 return max;
161 * Returns a copy of the longest leading path common among all
162 * pathspecs.
164 char *common_prefix(const struct pathspec *pathspec)
166 unsigned long len = common_prefix_len(pathspec);
168 return len ? xmemdupz(pathspec->items[0].match, len) : NULL;
171 int fill_directory(struct dir_struct *dir, const struct pathspec *pathspec)
173 size_t len;
176 * Calculate common prefix for the pathspec, and
177 * use that to optimize the directory walk
179 len = common_prefix_len(pathspec);
181 /* Read the directory and prune it */
182 read_directory(dir, pathspec->nr ? pathspec->_raw[0] : "", len, pathspec);
183 return len;
186 int within_depth(const char *name, int namelen,
187 int depth, int max_depth)
189 const char *cp = name, *cpe = name + namelen;
191 while (cp < cpe) {
192 if (*cp++ != '/')
193 continue;
194 depth++;
195 if (depth > max_depth)
196 return 0;
198 return 1;
201 #define DO_MATCH_EXCLUDE 1
202 #define DO_MATCH_DIRECTORY 2
205 * Does 'match' match the given name?
206 * A match is found if
208 * (1) the 'match' string is leading directory of 'name', or
209 * (2) the 'match' string is a wildcard and matches 'name', or
210 * (3) the 'match' string is exactly the same as 'name'.
212 * and the return value tells which case it was.
214 * It returns 0 when there is no match.
216 static int match_pathspec_item(const struct pathspec_item *item, int prefix,
217 const char *name, int namelen, unsigned flags)
219 /* name/namelen has prefix cut off by caller */
220 const char *match = item->match + prefix;
221 int matchlen = item->len - prefix;
224 * The normal call pattern is:
225 * 1. prefix = common_prefix_len(ps);
226 * 2. prune something, or fill_directory
227 * 3. match_pathspec()
229 * 'prefix' at #1 may be shorter than the command's prefix and
230 * it's ok for #2 to match extra files. Those extras will be
231 * trimmed at #3.
233 * Suppose the pathspec is 'foo' and '../bar' running from
234 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
235 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
236 * user does not want XYZ/foo, only the "foo" part should be
237 * case-insensitive. We need to filter out XYZ/foo here. In
238 * other words, we do not trust the caller on comparing the
239 * prefix part when :(icase) is involved. We do exact
240 * comparison ourselves.
242 * Normally the caller (common_prefix_len() in fact) does
243 * _exact_ matching on name[-prefix+1..-1] and we do not need
244 * to check that part. Be defensive and check it anyway, in
245 * case common_prefix_len is changed, or a new caller is
246 * introduced that does not use common_prefix_len.
248 * If the penalty turns out too high when prefix is really
249 * long, maybe change it to
250 * strncmp(match, name, item->prefix - prefix)
252 if (item->prefix && (item->magic & PATHSPEC_ICASE) &&
253 strncmp(item->match, name - prefix, item->prefix))
254 return 0;
256 /* If the match was just the prefix, we matched */
257 if (!*match)
258 return MATCHED_RECURSIVELY;
260 if (matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) {
261 if (matchlen == namelen)
262 return MATCHED_EXACTLY;
264 if (match[matchlen-1] == '/' || name[matchlen] == '/')
265 return MATCHED_RECURSIVELY;
266 } else if ((flags & DO_MATCH_DIRECTORY) &&
267 match[matchlen - 1] == '/' &&
268 namelen == matchlen - 1 &&
269 !ps_strncmp(item, match, name, namelen))
270 return MATCHED_EXACTLY;
272 if (item->nowildcard_len < item->len &&
273 !git_fnmatch(item, match, name,
274 item->nowildcard_len - prefix))
275 return MATCHED_FNMATCH;
277 return 0;
281 * Given a name and a list of pathspecs, returns the nature of the
282 * closest (i.e. most specific) match of the name to any of the
283 * pathspecs.
285 * The caller typically calls this multiple times with the same
286 * pathspec and seen[] array but with different name/namelen
287 * (e.g. entries from the index) and is interested in seeing if and
288 * how each pathspec matches all the names it calls this function
289 * with. A mark is left in the seen[] array for each pathspec element
290 * indicating the closest type of match that element achieved, so if
291 * seen[n] remains zero after multiple invocations, that means the nth
292 * pathspec did not match any names, which could indicate that the
293 * user mistyped the nth pathspec.
295 static int do_match_pathspec(const struct pathspec *ps,
296 const char *name, int namelen,
297 int prefix, char *seen,
298 unsigned flags)
300 int i, retval = 0, exclude = flags & DO_MATCH_EXCLUDE;
302 GUARD_PATHSPEC(ps,
303 PATHSPEC_FROMTOP |
304 PATHSPEC_MAXDEPTH |
305 PATHSPEC_LITERAL |
306 PATHSPEC_GLOB |
307 PATHSPEC_ICASE |
308 PATHSPEC_EXCLUDE);
310 if (!ps->nr) {
311 if (!ps->recursive ||
312 !(ps->magic & PATHSPEC_MAXDEPTH) ||
313 ps->max_depth == -1)
314 return MATCHED_RECURSIVELY;
316 if (within_depth(name, namelen, 0, ps->max_depth))
317 return MATCHED_EXACTLY;
318 else
319 return 0;
322 name += prefix;
323 namelen -= prefix;
325 for (i = ps->nr - 1; i >= 0; i--) {
326 int how;
328 if ((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) ||
329 ( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE)))
330 continue;
332 if (seen && seen[i] == MATCHED_EXACTLY)
333 continue;
335 * Make exclude patterns optional and never report
336 * "pathspec ':(exclude)foo' matches no files"
338 if (seen && ps->items[i].magic & PATHSPEC_EXCLUDE)
339 seen[i] = MATCHED_FNMATCH;
340 how = match_pathspec_item(ps->items+i, prefix, name,
341 namelen, flags);
342 if (ps->recursive &&
343 (ps->magic & PATHSPEC_MAXDEPTH) &&
344 ps->max_depth != -1 &&
345 how && how != MATCHED_FNMATCH) {
346 int len = ps->items[i].len;
347 if (name[len] == '/')
348 len++;
349 if (within_depth(name+len, namelen-len, 0, ps->max_depth))
350 how = MATCHED_EXACTLY;
351 else
352 how = 0;
354 if (how) {
355 if (retval < how)
356 retval = how;
357 if (seen && seen[i] < how)
358 seen[i] = how;
361 return retval;
364 int match_pathspec(const struct pathspec *ps,
365 const char *name, int namelen,
366 int prefix, char *seen, int is_dir)
368 int positive, negative;
369 unsigned flags = is_dir ? DO_MATCH_DIRECTORY : 0;
370 positive = do_match_pathspec(ps, name, namelen,
371 prefix, seen, flags);
372 if (!(ps->magic & PATHSPEC_EXCLUDE) || !positive)
373 return positive;
374 negative = do_match_pathspec(ps, name, namelen,
375 prefix, seen,
376 flags | DO_MATCH_EXCLUDE);
377 return negative ? 0 : positive;
381 * Return the length of the "simple" part of a path match limiter.
383 int simple_length(const char *match)
385 int len = -1;
387 for (;;) {
388 unsigned char c = *match++;
389 len++;
390 if (c == '\0' || is_glob_special(c))
391 return len;
395 int no_wildcard(const char *string)
397 return string[simple_length(string)] == '\0';
400 void parse_exclude_pattern(const char **pattern,
401 int *patternlen,
402 int *flags,
403 int *nowildcardlen)
405 const char *p = *pattern;
406 size_t i, len;
408 *flags = 0;
409 if (*p == '!') {
410 *flags |= EXC_FLAG_NEGATIVE;
411 p++;
413 len = strlen(p);
414 if (len && p[len - 1] == '/') {
415 len--;
416 *flags |= EXC_FLAG_MUSTBEDIR;
418 for (i = 0; i < len; i++) {
419 if (p[i] == '/')
420 break;
422 if (i == len)
423 *flags |= EXC_FLAG_NODIR;
424 *nowildcardlen = simple_length(p);
426 * we should have excluded the trailing slash from 'p' too,
427 * but that's one more allocation. Instead just make sure
428 * nowildcardlen does not exceed real patternlen
430 if (*nowildcardlen > len)
431 *nowildcardlen = len;
432 if (*p == '*' && no_wildcard(p + 1))
433 *flags |= EXC_FLAG_ENDSWITH;
434 *pattern = p;
435 *patternlen = len;
438 void add_exclude(const char *string, const char *base,
439 int baselen, struct exclude_list *el, int srcpos)
441 struct exclude *x;
442 int patternlen;
443 int flags;
444 int nowildcardlen;
446 parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen);
447 if (flags & EXC_FLAG_MUSTBEDIR) {
448 char *s;
449 x = xmalloc(sizeof(*x) + patternlen + 1);
450 s = (char *)(x+1);
451 memcpy(s, string, patternlen);
452 s[patternlen] = '\0';
453 x->pattern = s;
454 } else {
455 x = xmalloc(sizeof(*x));
456 x->pattern = string;
458 x->patternlen = patternlen;
459 x->nowildcardlen = nowildcardlen;
460 x->base = base;
461 x->baselen = baselen;
462 x->flags = flags;
463 x->srcpos = srcpos;
464 ALLOC_GROW(el->excludes, el->nr + 1, el->alloc);
465 el->excludes[el->nr++] = x;
466 x->el = el;
469 static void *read_skip_worktree_file_from_index(const char *path, size_t *size,
470 struct sha1_stat *sha1_stat)
472 int pos, len;
473 unsigned long sz;
474 enum object_type type;
475 void *data;
477 len = strlen(path);
478 pos = cache_name_pos(path, len);
479 if (pos < 0)
480 return NULL;
481 if (!ce_skip_worktree(active_cache[pos]))
482 return NULL;
483 data = read_sha1_file(active_cache[pos]->sha1, &type, &sz);
484 if (!data || type != OBJ_BLOB) {
485 free(data);
486 return NULL;
488 *size = xsize_t(sz);
489 if (sha1_stat) {
490 memset(&sha1_stat->stat, 0, sizeof(sha1_stat->stat));
491 hashcpy(sha1_stat->sha1, active_cache[pos]->sha1);
493 return data;
497 * Frees memory within el which was allocated for exclude patterns and
498 * the file buffer. Does not free el itself.
500 void clear_exclude_list(struct exclude_list *el)
502 int i;
504 for (i = 0; i < el->nr; i++)
505 free(el->excludes[i]);
506 free(el->excludes);
507 free(el->filebuf);
509 el->nr = 0;
510 el->excludes = NULL;
511 el->filebuf = NULL;
514 static void trim_trailing_spaces(char *buf)
516 char *p, *last_space = NULL;
518 for (p = buf; *p; p++)
519 switch (*p) {
520 case ' ':
521 if (!last_space)
522 last_space = p;
523 break;
524 case '\\':
525 p++;
526 if (!*p)
527 return;
528 /* fallthrough */
529 default:
530 last_space = NULL;
533 if (last_space)
534 *last_space = '\0';
538 * Given a subdirectory name and "dir" of the current directory,
539 * search the subdir in "dir" and return it, or create a new one if it
540 * does not exist in "dir".
542 * If "name" has the trailing slash, it'll be excluded in the search.
544 static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc,
545 struct untracked_cache_dir *dir,
546 const char *name, int len)
548 int first, last;
549 struct untracked_cache_dir *d;
550 if (!dir)
551 return NULL;
552 if (len && name[len - 1] == '/')
553 len--;
554 first = 0;
555 last = dir->dirs_nr;
556 while (last > first) {
557 int cmp, next = (last + first) >> 1;
558 d = dir->dirs[next];
559 cmp = strncmp(name, d->name, len);
560 if (!cmp && strlen(d->name) > len)
561 cmp = -1;
562 if (!cmp)
563 return d;
564 if (cmp < 0) {
565 last = next;
566 continue;
568 first = next+1;
571 uc->dir_created++;
572 d = xmalloc(sizeof(*d) + len + 1);
573 memset(d, 0, sizeof(*d));
574 memcpy(d->name, name, len);
575 d->name[len] = '\0';
577 ALLOC_GROW(dir->dirs, dir->dirs_nr + 1, dir->dirs_alloc);
578 memmove(dir->dirs + first + 1, dir->dirs + first,
579 (dir->dirs_nr - first) * sizeof(*dir->dirs));
580 dir->dirs_nr++;
581 dir->dirs[first] = d;
582 return d;
585 static void do_invalidate_gitignore(struct untracked_cache_dir *dir)
587 int i;
588 dir->valid = 0;
589 dir->untracked_nr = 0;
590 for (i = 0; i < dir->dirs_nr; i++)
591 do_invalidate_gitignore(dir->dirs[i]);
594 static void invalidate_gitignore(struct untracked_cache *uc,
595 struct untracked_cache_dir *dir)
597 uc->gitignore_invalidated++;
598 do_invalidate_gitignore(dir);
602 * Given a file with name "fname", read it (either from disk, or from
603 * the index if "check_index" is non-zero), parse it and store the
604 * exclude rules in "el".
606 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill
607 * stat data from disk (only valid if add_excludes returns zero). If
608 * ss_valid is non-zero, "ss" must contain good value as input.
610 static int add_excludes(const char *fname, const char *base, int baselen,
611 struct exclude_list *el, int check_index,
612 struct sha1_stat *sha1_stat)
614 struct stat st;
615 int fd, i, lineno = 1;
616 size_t size = 0;
617 char *buf, *entry;
619 fd = open(fname, O_RDONLY);
620 if (fd < 0 || fstat(fd, &st) < 0) {
621 if (errno != ENOENT)
622 warn_on_inaccessible(fname);
623 if (0 <= fd)
624 close(fd);
625 if (!check_index ||
626 (buf = read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL)
627 return -1;
628 if (size == 0) {
629 free(buf);
630 return 0;
632 if (buf[size-1] != '\n') {
633 buf = xrealloc(buf, size+1);
634 buf[size++] = '\n';
636 } else {
637 size = xsize_t(st.st_size);
638 if (size == 0) {
639 if (sha1_stat) {
640 fill_stat_data(&sha1_stat->stat, &st);
641 hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN);
642 sha1_stat->valid = 1;
644 close(fd);
645 return 0;
647 buf = xmalloc(size+1);
648 if (read_in_full(fd, buf, size) != size) {
649 free(buf);
650 close(fd);
651 return -1;
653 buf[size++] = '\n';
654 close(fd);
655 if (sha1_stat) {
656 int pos;
657 if (sha1_stat->valid &&
658 !match_stat_data(&sha1_stat->stat, &st))
659 ; /* no content change, ss->sha1 still good */
660 else if (check_index &&
661 (pos = cache_name_pos(fname, strlen(fname))) >= 0 &&
662 !ce_stage(active_cache[pos]) &&
663 ce_uptodate(active_cache[pos]) &&
664 !would_convert_to_git(fname))
665 hashcpy(sha1_stat->sha1, active_cache[pos]->sha1);
666 else
667 hash_sha1_file(buf, size, "blob", sha1_stat->sha1);
668 fill_stat_data(&sha1_stat->stat, &st);
669 sha1_stat->valid = 1;
673 el->filebuf = buf;
674 entry = buf;
675 for (i = 0; i < size; i++) {
676 if (buf[i] == '\n') {
677 if (entry != buf + i && entry[0] != '#') {
678 buf[i - (i && buf[i-1] == '\r')] = 0;
679 trim_trailing_spaces(entry);
680 add_exclude(entry, base, baselen, el, lineno);
682 lineno++;
683 entry = buf + i + 1;
686 return 0;
689 int add_excludes_from_file_to_list(const char *fname, const char *base,
690 int baselen, struct exclude_list *el,
691 int check_index)
693 return add_excludes(fname, base, baselen, el, check_index, NULL);
696 struct exclude_list *add_exclude_list(struct dir_struct *dir,
697 int group_type, const char *src)
699 struct exclude_list *el;
700 struct exclude_list_group *group;
702 group = &dir->exclude_list_group[group_type];
703 ALLOC_GROW(group->el, group->nr + 1, group->alloc);
704 el = &group->el[group->nr++];
705 memset(el, 0, sizeof(*el));
706 el->src = src;
707 return el;
711 * Used to set up core.excludesfile and .git/info/exclude lists.
713 static void add_excludes_from_file_1(struct dir_struct *dir, const char *fname,
714 struct sha1_stat *sha1_stat)
716 struct exclude_list *el;
718 * catch setup_standard_excludes() that's called before
719 * dir->untracked is assigned. That function behaves
720 * differently when dir->untracked is non-NULL.
722 if (!dir->untracked)
723 dir->unmanaged_exclude_files++;
724 el = add_exclude_list(dir, EXC_FILE, fname);
725 if (add_excludes(fname, "", 0, el, 0, sha1_stat) < 0)
726 die("cannot use %s as an exclude file", fname);
729 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
731 dir->unmanaged_exclude_files++; /* see validate_untracked_cache() */
732 add_excludes_from_file_1(dir, fname, NULL);
735 int match_basename(const char *basename, int basenamelen,
736 const char *pattern, int prefix, int patternlen,
737 int flags)
739 if (prefix == patternlen) {
740 if (patternlen == basenamelen &&
741 !strncmp_icase(pattern, basename, basenamelen))
742 return 1;
743 } else if (flags & EXC_FLAG_ENDSWITH) {
744 /* "*literal" matching against "fooliteral" */
745 if (patternlen - 1 <= basenamelen &&
746 !strncmp_icase(pattern + 1,
747 basename + basenamelen - (patternlen - 1),
748 patternlen - 1))
749 return 1;
750 } else {
751 if (fnmatch_icase_mem(pattern, patternlen,
752 basename, basenamelen,
753 0) == 0)
754 return 1;
756 return 0;
759 int match_pathname(const char *pathname, int pathlen,
760 const char *base, int baselen,
761 const char *pattern, int prefix, int patternlen,
762 int flags)
764 const char *name;
765 int namelen;
768 * match with FNM_PATHNAME; the pattern has base implicitly
769 * in front of it.
771 if (*pattern == '/') {
772 pattern++;
773 patternlen--;
774 prefix--;
778 * baselen does not count the trailing slash. base[] may or
779 * may not end with a trailing slash though.
781 if (pathlen < baselen + 1 ||
782 (baselen && pathname[baselen] != '/') ||
783 strncmp_icase(pathname, base, baselen))
784 return 0;
786 namelen = baselen ? pathlen - baselen - 1 : pathlen;
787 name = pathname + pathlen - namelen;
789 if (prefix) {
791 * if the non-wildcard part is longer than the
792 * remaining pathname, surely it cannot match.
794 if (prefix > namelen)
795 return 0;
797 if (strncmp_icase(pattern, name, prefix))
798 return 0;
799 pattern += prefix;
800 patternlen -= prefix;
801 name += prefix;
802 namelen -= prefix;
805 * If the whole pattern did not have a wildcard,
806 * then our prefix match is all we need; we
807 * do not need to call fnmatch at all.
809 if (!patternlen && !namelen)
810 return 1;
813 return fnmatch_icase_mem(pattern, patternlen,
814 name, namelen,
815 WM_PATHNAME) == 0;
819 * Scan the given exclude list in reverse to see whether pathname
820 * should be ignored. The first match (i.e. the last on the list), if
821 * any, determines the fate. Returns the exclude_list element which
822 * matched, or NULL for undecided.
824 static struct exclude *last_exclude_matching_from_list(const char *pathname,
825 int pathlen,
826 const char *basename,
827 int *dtype,
828 struct exclude_list *el)
830 int i;
832 if (!el->nr)
833 return NULL; /* undefined */
835 for (i = el->nr - 1; 0 <= i; i--) {
836 struct exclude *x = el->excludes[i];
837 const char *exclude = x->pattern;
838 int prefix = x->nowildcardlen;
840 if (x->flags & EXC_FLAG_MUSTBEDIR) {
841 if (*dtype == DT_UNKNOWN)
842 *dtype = get_dtype(NULL, pathname, pathlen);
843 if (*dtype != DT_DIR)
844 continue;
847 if (x->flags & EXC_FLAG_NODIR) {
848 if (match_basename(basename,
849 pathlen - (basename - pathname),
850 exclude, prefix, x->patternlen,
851 x->flags))
852 return x;
853 continue;
856 assert(x->baselen == 0 || x->base[x->baselen - 1] == '/');
857 if (match_pathname(pathname, pathlen,
858 x->base, x->baselen ? x->baselen - 1 : 0,
859 exclude, prefix, x->patternlen, x->flags))
860 return x;
862 return NULL; /* undecided */
866 * Scan the list and let the last match determine the fate.
867 * Return 1 for exclude, 0 for include and -1 for undecided.
869 int is_excluded_from_list(const char *pathname,
870 int pathlen, const char *basename, int *dtype,
871 struct exclude_list *el)
873 struct exclude *exclude;
874 exclude = last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el);
875 if (exclude)
876 return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
877 return -1; /* undecided */
880 static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir,
881 const char *pathname, int pathlen, const char *basename,
882 int *dtype_p)
884 int i, j;
885 struct exclude_list_group *group;
886 struct exclude *exclude;
887 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
888 group = &dir->exclude_list_group[i];
889 for (j = group->nr - 1; j >= 0; j--) {
890 exclude = last_exclude_matching_from_list(
891 pathname, pathlen, basename, dtype_p,
892 &group->el[j]);
893 if (exclude)
894 return exclude;
897 return NULL;
901 * Loads the per-directory exclude list for the substring of base
902 * which has a char length of baselen.
904 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
906 struct exclude_list_group *group;
907 struct exclude_list *el;
908 struct exclude_stack *stk = NULL;
909 struct untracked_cache_dir *untracked;
910 int current;
912 group = &dir->exclude_list_group[EXC_DIRS];
915 * Pop the exclude lists from the EXCL_DIRS exclude_list_group
916 * which originate from directories not in the prefix of the
917 * path being checked.
919 while ((stk = dir->exclude_stack) != NULL) {
920 if (stk->baselen <= baselen &&
921 !strncmp(dir->basebuf.buf, base, stk->baselen))
922 break;
923 el = &group->el[dir->exclude_stack->exclude_ix];
924 dir->exclude_stack = stk->prev;
925 dir->exclude = NULL;
926 free((char *)el->src); /* see strbuf_detach() below */
927 clear_exclude_list(el);
928 free(stk);
929 group->nr--;
932 /* Skip traversing into sub directories if the parent is excluded */
933 if (dir->exclude)
934 return;
937 * Lazy initialization. All call sites currently just
938 * memset(dir, 0, sizeof(*dir)) before use. Changing all of
939 * them seems lots of work for little benefit.
941 if (!dir->basebuf.buf)
942 strbuf_init(&dir->basebuf, PATH_MAX);
944 /* Read from the parent directories and push them down. */
945 current = stk ? stk->baselen : -1;
946 strbuf_setlen(&dir->basebuf, current < 0 ? 0 : current);
947 if (dir->untracked)
948 untracked = stk ? stk->ucd : dir->untracked->root;
949 else
950 untracked = NULL;
952 while (current < baselen) {
953 const char *cp;
954 struct sha1_stat sha1_stat;
956 stk = xcalloc(1, sizeof(*stk));
957 if (current < 0) {
958 cp = base;
959 current = 0;
960 } else {
961 cp = strchr(base + current + 1, '/');
962 if (!cp)
963 die("oops in prep_exclude");
964 cp++;
965 untracked =
966 lookup_untracked(dir->untracked, untracked,
967 base + current,
968 cp - base - current);
970 stk->prev = dir->exclude_stack;
971 stk->baselen = cp - base;
972 stk->exclude_ix = group->nr;
973 stk->ucd = untracked;
974 el = add_exclude_list(dir, EXC_DIRS, NULL);
975 strbuf_add(&dir->basebuf, base + current, stk->baselen - current);
976 assert(stk->baselen == dir->basebuf.len);
978 /* Abort if the directory is excluded */
979 if (stk->baselen) {
980 int dt = DT_DIR;
981 dir->basebuf.buf[stk->baselen - 1] = 0;
982 dir->exclude = last_exclude_matching_from_lists(dir,
983 dir->basebuf.buf, stk->baselen - 1,
984 dir->basebuf.buf + current, &dt);
985 dir->basebuf.buf[stk->baselen - 1] = '/';
986 if (dir->exclude &&
987 dir->exclude->flags & EXC_FLAG_NEGATIVE)
988 dir->exclude = NULL;
989 if (dir->exclude) {
990 dir->exclude_stack = stk;
991 return;
995 /* Try to read per-directory file */
996 hashclr(sha1_stat.sha1);
997 sha1_stat.valid = 0;
998 if (dir->exclude_per_dir) {
1000 * dir->basebuf gets reused by the traversal, but we
1001 * need fname to remain unchanged to ensure the src
1002 * member of each struct exclude correctly
1003 * back-references its source file. Other invocations
1004 * of add_exclude_list provide stable strings, so we
1005 * strbuf_detach() and free() here in the caller.
1007 struct strbuf sb = STRBUF_INIT;
1008 strbuf_addbuf(&sb, &dir->basebuf);
1009 strbuf_addstr(&sb, dir->exclude_per_dir);
1010 el->src = strbuf_detach(&sb, NULL);
1011 add_excludes(el->src, el->src, stk->baselen, el, 1,
1012 untracked ? &sha1_stat : NULL);
1014 if (untracked) {
1015 hashcpy(untracked->exclude_sha1, sha1_stat.sha1);
1017 dir->exclude_stack = stk;
1018 current = stk->baselen;
1020 strbuf_setlen(&dir->basebuf, baselen);
1024 * Loads the exclude lists for the directory containing pathname, then
1025 * scans all exclude lists to determine whether pathname is excluded.
1026 * Returns the exclude_list element which matched, or NULL for
1027 * undecided.
1029 struct exclude *last_exclude_matching(struct dir_struct *dir,
1030 const char *pathname,
1031 int *dtype_p)
1033 int pathlen = strlen(pathname);
1034 const char *basename = strrchr(pathname, '/');
1035 basename = (basename) ? basename+1 : pathname;
1037 prep_exclude(dir, pathname, basename-pathname);
1039 if (dir->exclude)
1040 return dir->exclude;
1042 return last_exclude_matching_from_lists(dir, pathname, pathlen,
1043 basename, dtype_p);
1047 * Loads the exclude lists for the directory containing pathname, then
1048 * scans all exclude lists to determine whether pathname is excluded.
1049 * Returns 1 if true, otherwise 0.
1051 int is_excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
1053 struct exclude *exclude =
1054 last_exclude_matching(dir, pathname, dtype_p);
1055 if (exclude)
1056 return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
1057 return 0;
1060 static struct dir_entry *dir_entry_new(const char *pathname, int len)
1062 struct dir_entry *ent;
1064 ent = xmalloc(sizeof(*ent) + len + 1);
1065 ent->len = len;
1066 memcpy(ent->name, pathname, len);
1067 ent->name[len] = 0;
1068 return ent;
1071 static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
1073 if (cache_file_exists(pathname, len, ignore_case))
1074 return NULL;
1076 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
1077 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
1080 struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
1082 if (!cache_name_is_other(pathname, len))
1083 return NULL;
1085 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
1086 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
1089 enum exist_status {
1090 index_nonexistent = 0,
1091 index_directory,
1092 index_gitdir
1096 * Do not use the alphabetically sorted index to look up
1097 * the directory name; instead, use the case insensitive
1098 * directory hash.
1100 static enum exist_status directory_exists_in_index_icase(const char *dirname, int len)
1102 const struct cache_entry *ce = cache_dir_exists(dirname, len);
1103 unsigned char endchar;
1105 if (!ce)
1106 return index_nonexistent;
1107 endchar = ce->name[len];
1110 * The cache_entry structure returned will contain this dirname
1111 * and possibly additional path components.
1113 if (endchar == '/')
1114 return index_directory;
1117 * If there are no additional path components, then this cache_entry
1118 * represents a submodule. Submodules, despite being directories,
1119 * are stored in the cache without a closing slash.
1121 if (!endchar && S_ISGITLINK(ce->ce_mode))
1122 return index_gitdir;
1124 /* This should never be hit, but it exists just in case. */
1125 return index_nonexistent;
1129 * The index sorts alphabetically by entry name, which
1130 * means that a gitlink sorts as '\0' at the end, while
1131 * a directory (which is defined not as an entry, but as
1132 * the files it contains) will sort with the '/' at the
1133 * end.
1135 static enum exist_status directory_exists_in_index(const char *dirname, int len)
1137 int pos;
1139 if (ignore_case)
1140 return directory_exists_in_index_icase(dirname, len);
1142 pos = cache_name_pos(dirname, len);
1143 if (pos < 0)
1144 pos = -pos-1;
1145 while (pos < active_nr) {
1146 const struct cache_entry *ce = active_cache[pos++];
1147 unsigned char endchar;
1149 if (strncmp(ce->name, dirname, len))
1150 break;
1151 endchar = ce->name[len];
1152 if (endchar > '/')
1153 break;
1154 if (endchar == '/')
1155 return index_directory;
1156 if (!endchar && S_ISGITLINK(ce->ce_mode))
1157 return index_gitdir;
1159 return index_nonexistent;
1163 * When we find a directory when traversing the filesystem, we
1164 * have three distinct cases:
1166 * - ignore it
1167 * - see it as a directory
1168 * - recurse into it
1170 * and which one we choose depends on a combination of existing
1171 * git index contents and the flags passed into the directory
1172 * traversal routine.
1174 * Case 1: If we *already* have entries in the index under that
1175 * directory name, we always recurse into the directory to see
1176 * all the files.
1178 * Case 2: If we *already* have that directory name as a gitlink,
1179 * we always continue to see it as a gitlink, regardless of whether
1180 * there is an actual git directory there or not (it might not
1181 * be checked out as a subproject!)
1183 * Case 3: if we didn't have it in the index previously, we
1184 * have a few sub-cases:
1186 * (a) if "show_other_directories" is true, we show it as
1187 * just a directory, unless "hide_empty_directories" is
1188 * also true, in which case we need to check if it contains any
1189 * untracked and / or ignored files.
1190 * (b) if it looks like a git directory, and we don't have
1191 * 'no_gitlinks' set we treat it as a gitlink, and show it
1192 * as a directory.
1193 * (c) otherwise, we recurse into it.
1195 static enum path_treatment treat_directory(struct dir_struct *dir,
1196 struct untracked_cache_dir *untracked,
1197 const char *dirname, int len, int exclude,
1198 const struct path_simplify *simplify)
1200 /* The "len-1" is to strip the final '/' */
1201 switch (directory_exists_in_index(dirname, len-1)) {
1202 case index_directory:
1203 return path_recurse;
1205 case index_gitdir:
1206 return path_none;
1208 case index_nonexistent:
1209 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
1210 break;
1211 if (!(dir->flags & DIR_NO_GITLINKS)) {
1212 unsigned char sha1[20];
1213 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
1214 return path_untracked;
1216 return path_recurse;
1219 /* This is the "show_other_directories" case */
1221 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1222 return exclude ? path_excluded : path_untracked;
1224 untracked = lookup_untracked(dir->untracked, untracked, dirname, len);
1225 return read_directory_recursive(dir, dirname, len,
1226 untracked, 1, simplify);
1230 * This is an inexact early pruning of any recursive directory
1231 * reading - if the path cannot possibly be in the pathspec,
1232 * return true, and we'll skip it early.
1234 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
1236 if (simplify) {
1237 for (;;) {
1238 const char *match = simplify->path;
1239 int len = simplify->len;
1241 if (!match)
1242 break;
1243 if (len > pathlen)
1244 len = pathlen;
1245 if (!memcmp(path, match, len))
1246 return 0;
1247 simplify++;
1249 return 1;
1251 return 0;
1255 * This function tells us whether an excluded path matches a
1256 * list of "interesting" pathspecs. That is, whether a path matched
1257 * by any of the pathspecs could possibly be ignored by excluding
1258 * the specified path. This can happen if:
1260 * 1. the path is mentioned explicitly in the pathspec
1262 * 2. the path is a directory prefix of some element in the
1263 * pathspec
1265 static int exclude_matches_pathspec(const char *path, int len,
1266 const struct path_simplify *simplify)
1268 if (simplify) {
1269 for (; simplify->path; simplify++) {
1270 if (len == simplify->len
1271 && !memcmp(path, simplify->path, len))
1272 return 1;
1273 if (len < simplify->len
1274 && simplify->path[len] == '/'
1275 && !memcmp(path, simplify->path, len))
1276 return 1;
1279 return 0;
1282 static int get_index_dtype(const char *path, int len)
1284 int pos;
1285 const struct cache_entry *ce;
1287 ce = cache_file_exists(path, len, 0);
1288 if (ce) {
1289 if (!ce_uptodate(ce))
1290 return DT_UNKNOWN;
1291 if (S_ISGITLINK(ce->ce_mode))
1292 return DT_DIR;
1294 * Nobody actually cares about the
1295 * difference between DT_LNK and DT_REG
1297 return DT_REG;
1300 /* Try to look it up as a directory */
1301 pos = cache_name_pos(path, len);
1302 if (pos >= 0)
1303 return DT_UNKNOWN;
1304 pos = -pos-1;
1305 while (pos < active_nr) {
1306 ce = active_cache[pos++];
1307 if (strncmp(ce->name, path, len))
1308 break;
1309 if (ce->name[len] > '/')
1310 break;
1311 if (ce->name[len] < '/')
1312 continue;
1313 if (!ce_uptodate(ce))
1314 break; /* continue? */
1315 return DT_DIR;
1317 return DT_UNKNOWN;
1320 static int get_dtype(struct dirent *de, const char *path, int len)
1322 int dtype = de ? DTYPE(de) : DT_UNKNOWN;
1323 struct stat st;
1325 if (dtype != DT_UNKNOWN)
1326 return dtype;
1327 dtype = get_index_dtype(path, len);
1328 if (dtype != DT_UNKNOWN)
1329 return dtype;
1330 if (lstat(path, &st))
1331 return dtype;
1332 if (S_ISREG(st.st_mode))
1333 return DT_REG;
1334 if (S_ISDIR(st.st_mode))
1335 return DT_DIR;
1336 if (S_ISLNK(st.st_mode))
1337 return DT_LNK;
1338 return dtype;
1341 static enum path_treatment treat_one_path(struct dir_struct *dir,
1342 struct untracked_cache_dir *untracked,
1343 struct strbuf *path,
1344 const struct path_simplify *simplify,
1345 int dtype, struct dirent *de)
1347 int exclude;
1348 int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);
1350 if (dtype == DT_UNKNOWN)
1351 dtype = get_dtype(de, path->buf, path->len);
1353 /* Always exclude indexed files */
1354 if (dtype != DT_DIR && has_path_in_index)
1355 return path_none;
1358 * When we are looking at a directory P in the working tree,
1359 * there are three cases:
1361 * (1) P exists in the index. Everything inside the directory P in
1362 * the working tree needs to go when P is checked out from the
1363 * index.
1365 * (2) P does not exist in the index, but there is P/Q in the index.
1366 * We know P will stay a directory when we check out the contents
1367 * of the index, but we do not know yet if there is a directory
1368 * P/Q in the working tree to be killed, so we need to recurse.
1370 * (3) P does not exist in the index, and there is no P/Q in the index
1371 * to require P to be a directory, either. Only in this case, we
1372 * know that everything inside P will not be killed without
1373 * recursing.
1375 if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
1376 (dtype == DT_DIR) &&
1377 !has_path_in_index &&
1378 (directory_exists_in_index(path->buf, path->len) == index_nonexistent))
1379 return path_none;
1381 exclude = is_excluded(dir, path->buf, &dtype);
1384 * Excluded? If we don't explicitly want to show
1385 * ignored files, ignore it
1387 if (exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
1388 return path_excluded;
1390 switch (dtype) {
1391 default:
1392 return path_none;
1393 case DT_DIR:
1394 strbuf_addch(path, '/');
1395 return treat_directory(dir, untracked, path->buf, path->len, exclude,
1396 simplify);
1397 case DT_REG:
1398 case DT_LNK:
1399 return exclude ? path_excluded : path_untracked;
1403 static enum path_treatment treat_path(struct dir_struct *dir,
1404 struct untracked_cache_dir *untracked,
1405 struct dirent *de,
1406 struct strbuf *path,
1407 int baselen,
1408 const struct path_simplify *simplify)
1410 int dtype;
1412 if (is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name, ".git"))
1413 return path_none;
1414 strbuf_setlen(path, baselen);
1415 strbuf_addstr(path, de->d_name);
1416 if (simplify_away(path->buf, path->len, simplify))
1417 return path_none;
1419 dtype = DTYPE(de);
1420 return treat_one_path(dir, untracked, path, simplify, dtype, de);
1423 static void add_untracked(struct untracked_cache_dir *dir, const char *name)
1425 if (!dir)
1426 return;
1427 ALLOC_GROW(dir->untracked, dir->untracked_nr + 1,
1428 dir->untracked_alloc);
1429 dir->untracked[dir->untracked_nr++] = xstrdup(name);
1433 * Read a directory tree. We currently ignore anything but
1434 * directories, regular files and symlinks. That's because git
1435 * doesn't handle them at all yet. Maybe that will change some
1436 * day.
1438 * Also, we ignore the name ".git" (even if it is not a directory).
1439 * That likely will not change.
1441 * Returns the most significant path_treatment value encountered in the scan.
1443 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
1444 const char *base, int baselen,
1445 struct untracked_cache_dir *untracked, int check_only,
1446 const struct path_simplify *simplify)
1448 DIR *fdir;
1449 enum path_treatment state, subdir_state, dir_state = path_none;
1450 struct dirent *de;
1451 struct strbuf path = STRBUF_INIT;
1453 strbuf_add(&path, base, baselen);
1455 fdir = opendir(path.len ? path.buf : ".");
1456 if (!fdir)
1457 goto out;
1459 if (untracked)
1460 untracked->check_only = !!check_only;
1462 while ((de = readdir(fdir)) != NULL) {
1463 /* check how the file or directory should be treated */
1464 state = treat_path(dir, untracked, de, &path, baselen, simplify);
1466 if (state > dir_state)
1467 dir_state = state;
1469 /* recurse into subdir if instructed by treat_path */
1470 if (state == path_recurse) {
1471 struct untracked_cache_dir *ud;
1472 ud = lookup_untracked(dir->untracked, untracked,
1473 path.buf + baselen,
1474 path.len - baselen);
1475 subdir_state =
1476 read_directory_recursive(dir, path.buf, path.len,
1477 ud, check_only, simplify);
1478 if (subdir_state > dir_state)
1479 dir_state = subdir_state;
1482 if (check_only) {
1483 /* abort early if maximum state has been reached */
1484 if (dir_state == path_untracked) {
1485 if (untracked)
1486 add_untracked(untracked, path.buf + baselen);
1487 break;
1489 /* skip the dir_add_* part */
1490 continue;
1493 /* add the path to the appropriate result list */
1494 switch (state) {
1495 case path_excluded:
1496 if (dir->flags & DIR_SHOW_IGNORED)
1497 dir_add_name(dir, path.buf, path.len);
1498 else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
1499 ((dir->flags & DIR_COLLECT_IGNORED) &&
1500 exclude_matches_pathspec(path.buf, path.len,
1501 simplify)))
1502 dir_add_ignored(dir, path.buf, path.len);
1503 break;
1505 case path_untracked:
1506 if (dir->flags & DIR_SHOW_IGNORED)
1507 break;
1508 dir_add_name(dir, path.buf, path.len);
1509 if (untracked)
1510 add_untracked(untracked, path.buf + baselen);
1511 break;
1513 default:
1514 break;
1517 closedir(fdir);
1518 out:
1519 strbuf_release(&path);
1521 return dir_state;
1524 static int cmp_name(const void *p1, const void *p2)
1526 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
1527 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
1529 return name_compare(e1->name, e1->len, e2->name, e2->len);
1532 static struct path_simplify *create_simplify(const char **pathspec)
1534 int nr, alloc = 0;
1535 struct path_simplify *simplify = NULL;
1537 if (!pathspec)
1538 return NULL;
1540 for (nr = 0 ; ; nr++) {
1541 const char *match;
1542 ALLOC_GROW(simplify, nr + 1, alloc);
1543 match = *pathspec++;
1544 if (!match)
1545 break;
1546 simplify[nr].path = match;
1547 simplify[nr].len = simple_length(match);
1549 simplify[nr].path = NULL;
1550 simplify[nr].len = 0;
1551 return simplify;
1554 static void free_simplify(struct path_simplify *simplify)
1556 free(simplify);
1559 static int treat_leading_path(struct dir_struct *dir,
1560 const char *path, int len,
1561 const struct path_simplify *simplify)
1563 struct strbuf sb = STRBUF_INIT;
1564 int baselen, rc = 0;
1565 const char *cp;
1566 int old_flags = dir->flags;
1568 while (len && path[len - 1] == '/')
1569 len--;
1570 if (!len)
1571 return 1;
1572 baselen = 0;
1573 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;
1574 while (1) {
1575 cp = path + baselen + !!baselen;
1576 cp = memchr(cp, '/', path + len - cp);
1577 if (!cp)
1578 baselen = len;
1579 else
1580 baselen = cp - path;
1581 strbuf_setlen(&sb, 0);
1582 strbuf_add(&sb, path, baselen);
1583 if (!is_directory(sb.buf))
1584 break;
1585 if (simplify_away(sb.buf, sb.len, simplify))
1586 break;
1587 if (treat_one_path(dir, NULL, &sb, simplify,
1588 DT_DIR, NULL) == path_none)
1589 break; /* do not recurse into it */
1590 if (len <= baselen) {
1591 rc = 1;
1592 break; /* finished checking */
1595 strbuf_release(&sb);
1596 dir->flags = old_flags;
1597 return rc;
1600 static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,
1601 int base_len,
1602 const struct pathspec *pathspec)
1604 struct untracked_cache_dir *root;
1606 if (!dir->untracked)
1607 return NULL;
1610 * We only support $GIT_DIR/info/exclude and core.excludesfile
1611 * as the global ignore rule files. Any other additions
1612 * (e.g. from command line) invalidate the cache. This
1613 * condition also catches running setup_standard_excludes()
1614 * before setting dir->untracked!
1616 if (dir->unmanaged_exclude_files)
1617 return NULL;
1620 * Optimize for the main use case only: whole-tree git
1621 * status. More work involved in treat_leading_path() if we
1622 * use cache on just a subset of the worktree. pathspec
1623 * support could make the matter even worse.
1625 if (base_len || (pathspec && pathspec->nr))
1626 return NULL;
1628 /* Different set of flags may produce different results */
1629 if (dir->flags != dir->untracked->dir_flags ||
1631 * See treat_directory(), case index_nonexistent. Without
1632 * this flag, we may need to also cache .git file content
1633 * for the resolve_gitlink_ref() call, which we don't.
1635 !(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||
1636 /* We don't support collecting ignore files */
1637 (dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |
1638 DIR_COLLECT_IGNORED)))
1639 return NULL;
1642 * If we use .gitignore in the cache and now you change it to
1643 * .gitexclude, everything will go wrong.
1645 if (dir->exclude_per_dir != dir->untracked->exclude_per_dir &&
1646 strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))
1647 return NULL;
1650 * EXC_CMDL is not considered in the cache. If people set it,
1651 * skip the cache.
1653 if (dir->exclude_list_group[EXC_CMDL].nr)
1654 return NULL;
1656 if (!dir->untracked->root) {
1657 const int len = sizeof(*dir->untracked->root);
1658 dir->untracked->root = xmalloc(len);
1659 memset(dir->untracked->root, 0, len);
1662 /* Validate $GIT_DIR/info/exclude and core.excludesfile */
1663 root = dir->untracked->root;
1664 if (hashcmp(dir->ss_info_exclude.sha1,
1665 dir->untracked->ss_info_exclude.sha1)) {
1666 invalidate_gitignore(dir->untracked, root);
1667 dir->untracked->ss_info_exclude = dir->ss_info_exclude;
1669 if (hashcmp(dir->ss_excludes_file.sha1,
1670 dir->untracked->ss_excludes_file.sha1)) {
1671 invalidate_gitignore(dir->untracked, root);
1672 dir->untracked->ss_excludes_file = dir->ss_excludes_file;
1674 return root;
1677 int read_directory(struct dir_struct *dir, const char *path, int len, const struct pathspec *pathspec)
1679 struct path_simplify *simplify;
1680 struct untracked_cache_dir *untracked;
1683 * Check out create_simplify()
1685 if (pathspec)
1686 GUARD_PATHSPEC(pathspec,
1687 PATHSPEC_FROMTOP |
1688 PATHSPEC_MAXDEPTH |
1689 PATHSPEC_LITERAL |
1690 PATHSPEC_GLOB |
1691 PATHSPEC_ICASE |
1692 PATHSPEC_EXCLUDE);
1694 if (has_symlink_leading_path(path, len))
1695 return dir->nr;
1698 * exclude patterns are treated like positive ones in
1699 * create_simplify. Usually exclude patterns should be a
1700 * subset of positive ones, which has no impacts on
1701 * create_simplify().
1703 simplify = create_simplify(pathspec ? pathspec->_raw : NULL);
1704 untracked = validate_untracked_cache(dir, len, pathspec);
1705 if (!untracked)
1707 * make sure untracked cache code path is disabled,
1708 * e.g. prep_exclude()
1710 dir->untracked = NULL;
1711 if (!len || treat_leading_path(dir, path, len, simplify))
1712 read_directory_recursive(dir, path, len, untracked, 0, simplify);
1713 free_simplify(simplify);
1714 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
1715 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
1716 return dir->nr;
1719 int file_exists(const char *f)
1721 struct stat sb;
1722 return lstat(f, &sb) == 0;
1726 * Given two normalized paths (a trailing slash is ok), if subdir is
1727 * outside dir, return -1. Otherwise return the offset in subdir that
1728 * can be used as relative path to dir.
1730 int dir_inside_of(const char *subdir, const char *dir)
1732 int offset = 0;
1734 assert(dir && subdir && *dir && *subdir);
1736 while (*dir && *subdir && *dir == *subdir) {
1737 dir++;
1738 subdir++;
1739 offset++;
1742 /* hel[p]/me vs hel[l]/yeah */
1743 if (*dir && *subdir)
1744 return -1;
1746 if (!*subdir)
1747 return !*dir ? offset : -1; /* same dir */
1749 /* foo/[b]ar vs foo/[] */
1750 if (is_dir_sep(dir[-1]))
1751 return is_dir_sep(subdir[-1]) ? offset : -1;
1753 /* foo[/]bar vs foo[] */
1754 return is_dir_sep(*subdir) ? offset + 1 : -1;
1757 int is_inside_dir(const char *dir)
1759 char *cwd;
1760 int rc;
1762 if (!dir)
1763 return 0;
1765 cwd = xgetcwd();
1766 rc = (dir_inside_of(cwd, dir) >= 0);
1767 free(cwd);
1768 return rc;
1771 int is_empty_dir(const char *path)
1773 DIR *dir = opendir(path);
1774 struct dirent *e;
1775 int ret = 1;
1777 if (!dir)
1778 return 0;
1780 while ((e = readdir(dir)) != NULL)
1781 if (!is_dot_or_dotdot(e->d_name)) {
1782 ret = 0;
1783 break;
1786 closedir(dir);
1787 return ret;
1790 static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
1792 DIR *dir;
1793 struct dirent *e;
1794 int ret = 0, original_len = path->len, len, kept_down = 0;
1795 int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
1796 int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
1797 unsigned char submodule_head[20];
1799 if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
1800 !resolve_gitlink_ref(path->buf, "HEAD", submodule_head)) {
1801 /* Do not descend and nuke a nested git work tree. */
1802 if (kept_up)
1803 *kept_up = 1;
1804 return 0;
1807 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
1808 dir = opendir(path->buf);
1809 if (!dir) {
1810 if (errno == ENOENT)
1811 return keep_toplevel ? -1 : 0;
1812 else if (errno == EACCES && !keep_toplevel)
1814 * An empty dir could be removable even if it
1815 * is unreadable:
1817 return rmdir(path->buf);
1818 else
1819 return -1;
1821 if (path->buf[original_len - 1] != '/')
1822 strbuf_addch(path, '/');
1824 len = path->len;
1825 while ((e = readdir(dir)) != NULL) {
1826 struct stat st;
1827 if (is_dot_or_dotdot(e->d_name))
1828 continue;
1830 strbuf_setlen(path, len);
1831 strbuf_addstr(path, e->d_name);
1832 if (lstat(path->buf, &st)) {
1833 if (errno == ENOENT)
1835 * file disappeared, which is what we
1836 * wanted anyway
1838 continue;
1839 /* fall thru */
1840 } else if (S_ISDIR(st.st_mode)) {
1841 if (!remove_dir_recurse(path, flag, &kept_down))
1842 continue; /* happy */
1843 } else if (!only_empty &&
1844 (!unlink(path->buf) || errno == ENOENT)) {
1845 continue; /* happy, too */
1848 /* path too long, stat fails, or non-directory still exists */
1849 ret = -1;
1850 break;
1852 closedir(dir);
1854 strbuf_setlen(path, original_len);
1855 if (!ret && !keep_toplevel && !kept_down)
1856 ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1;
1857 else if (kept_up)
1859 * report the uplevel that it is not an error that we
1860 * did not rmdir() our directory.
1862 *kept_up = !ret;
1863 return ret;
1866 int remove_dir_recursively(struct strbuf *path, int flag)
1868 return remove_dir_recurse(path, flag, NULL);
1871 void setup_standard_excludes(struct dir_struct *dir)
1873 const char *path;
1874 char *xdg_path;
1876 dir->exclude_per_dir = ".gitignore";
1877 path = git_path("info/exclude");
1878 if (!excludes_file) {
1879 home_config_paths(NULL, &xdg_path, "ignore");
1880 excludes_file = xdg_path;
1882 if (!access_or_warn(path, R_OK, 0))
1883 add_excludes_from_file_1(dir, path,
1884 dir->untracked ? &dir->ss_info_exclude : NULL);
1885 if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
1886 add_excludes_from_file_1(dir, excludes_file,
1887 dir->untracked ? &dir->ss_excludes_file : NULL);
1890 int remove_path(const char *name)
1892 char *slash;
1894 if (unlink(name) && errno != ENOENT && errno != ENOTDIR)
1895 return -1;
1897 slash = strrchr(name, '/');
1898 if (slash) {
1899 char *dirs = xstrdup(name);
1900 slash = dirs + (slash - name);
1901 do {
1902 *slash = '\0';
1903 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
1904 free(dirs);
1906 return 0;
1910 * Frees memory within dir which was allocated for exclude lists and
1911 * the exclude_stack. Does not free dir itself.
1913 void clear_directory(struct dir_struct *dir)
1915 int i, j;
1916 struct exclude_list_group *group;
1917 struct exclude_list *el;
1918 struct exclude_stack *stk;
1920 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
1921 group = &dir->exclude_list_group[i];
1922 for (j = 0; j < group->nr; j++) {
1923 el = &group->el[j];
1924 if (i == EXC_DIRS)
1925 free((char *)el->src);
1926 clear_exclude_list(el);
1928 free(group->el);
1931 stk = dir->exclude_stack;
1932 while (stk) {
1933 struct exclude_stack *prev = stk->prev;
1934 free(stk);
1935 stk = prev;
1937 strbuf_release(&dir->basebuf);