Merge branch 'nd/fix-perf-parameters-in-tests'
[git.git] / dir.c
blob9dde68a2f3a1a325d2c5b90fa4d20dbf7670652c
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"
15 struct path_simplify {
16 int len;
17 const char *path;
20 static int read_directory_recursive(struct dir_struct *dir, const char *path, int len,
21 int check_only, const struct path_simplify *simplify);
22 static int get_dtype(struct dirent *de, const char *path, int len);
24 /* helper string functions with support for the ignore_case flag */
25 int strcmp_icase(const char *a, const char *b)
27 return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
30 int strncmp_icase(const char *a, const char *b, size_t count)
32 return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
35 int fnmatch_icase(const char *pattern, const char *string, int flags)
37 return fnmatch(pattern, string, flags | (ignore_case ? FNM_CASEFOLD : 0));
40 inline int git_fnmatch(const char *pattern, const char *string,
41 int flags, int prefix)
43 int fnm_flags = 0;
44 if (flags & GFNM_PATHNAME)
45 fnm_flags |= FNM_PATHNAME;
46 if (prefix > 0) {
47 if (strncmp(pattern, string, prefix))
48 return FNM_NOMATCH;
49 pattern += prefix;
50 string += prefix;
52 if (flags & GFNM_ONESTAR) {
53 int pattern_len = strlen(++pattern);
54 int string_len = strlen(string);
55 return string_len < pattern_len ||
56 strcmp(pattern,
57 string + string_len - pattern_len);
59 return fnmatch(pattern, string, fnm_flags);
62 static size_t common_prefix_len(const char **pathspec)
64 const char *n, *first;
65 size_t max = 0;
66 int literal = limit_pathspec_to_literal();
68 if (!pathspec)
69 return max;
71 first = *pathspec;
72 while ((n = *pathspec++)) {
73 size_t i, len = 0;
74 for (i = 0; first == n || i < max; i++) {
75 char c = n[i];
76 if (!c || c != first[i] || (!literal && is_glob_special(c)))
77 break;
78 if (c == '/')
79 len = i + 1;
81 if (first == n || len < max) {
82 max = len;
83 if (!max)
84 break;
87 return max;
91 * Returns a copy of the longest leading path common among all
92 * pathspecs.
94 char *common_prefix(const char **pathspec)
96 unsigned long len = common_prefix_len(pathspec);
98 return len ? xmemdupz(*pathspec, len) : NULL;
101 int fill_directory(struct dir_struct *dir, const char **pathspec)
103 size_t len;
106 * Calculate common prefix for the pathspec, and
107 * use that to optimize the directory walk
109 len = common_prefix_len(pathspec);
111 /* Read the directory and prune it */
112 read_directory(dir, pathspec ? *pathspec : "", len, pathspec);
113 return len;
116 int within_depth(const char *name, int namelen,
117 int depth, int max_depth)
119 const char *cp = name, *cpe = name + namelen;
121 while (cp < cpe) {
122 if (*cp++ != '/')
123 continue;
124 depth++;
125 if (depth > max_depth)
126 return 0;
128 return 1;
132 * Does 'match' match the given name?
133 * A match is found if
135 * (1) the 'match' string is leading directory of 'name', or
136 * (2) the 'match' string is a wildcard and matches 'name', or
137 * (3) the 'match' string is exactly the same as 'name'.
139 * and the return value tells which case it was.
141 * It returns 0 when there is no match.
143 static int match_one(const char *match, const char *name, int namelen)
145 int matchlen;
146 int literal = limit_pathspec_to_literal();
148 /* If the match was just the prefix, we matched */
149 if (!*match)
150 return MATCHED_RECURSIVELY;
152 if (ignore_case) {
153 for (;;) {
154 unsigned char c1 = tolower(*match);
155 unsigned char c2 = tolower(*name);
156 if (c1 == '\0' || (!literal && is_glob_special(c1)))
157 break;
158 if (c1 != c2)
159 return 0;
160 match++;
161 name++;
162 namelen--;
164 } else {
165 for (;;) {
166 unsigned char c1 = *match;
167 unsigned char c2 = *name;
168 if (c1 == '\0' || (!literal && is_glob_special(c1)))
169 break;
170 if (c1 != c2)
171 return 0;
172 match++;
173 name++;
174 namelen--;
179 * If we don't match the matchstring exactly,
180 * we need to match by fnmatch
182 matchlen = strlen(match);
183 if (strncmp_icase(match, name, matchlen)) {
184 if (literal)
185 return 0;
186 return !fnmatch_icase(match, name, 0) ? MATCHED_FNMATCH : 0;
189 if (namelen == matchlen)
190 return MATCHED_EXACTLY;
191 if (match[matchlen-1] == '/' || name[matchlen] == '/')
192 return MATCHED_RECURSIVELY;
193 return 0;
197 * Given a name and a list of pathspecs, see if the name matches
198 * any of the pathspecs. The caller is also interested in seeing
199 * all pathspec matches some names it calls this function with
200 * (otherwise the user could have mistyped the unmatched pathspec),
201 * and a mark is left in seen[] array for pathspec element that
202 * actually matched anything.
204 int match_pathspec(const char **pathspec, const char *name, int namelen,
205 int prefix, char *seen)
207 int i, retval = 0;
209 if (!pathspec)
210 return 1;
212 name += prefix;
213 namelen -= prefix;
215 for (i = 0; pathspec[i] != NULL; i++) {
216 int how;
217 const char *match = pathspec[i] + prefix;
218 if (seen && seen[i] == MATCHED_EXACTLY)
219 continue;
220 how = match_one(match, name, namelen);
221 if (how) {
222 if (retval < how)
223 retval = how;
224 if (seen && seen[i] < how)
225 seen[i] = how;
228 return retval;
232 * Does 'match' match the given name?
233 * A match is found if
235 * (1) the 'match' string is leading directory of 'name', or
236 * (2) the 'match' string is a wildcard and matches 'name', or
237 * (3) the 'match' string is exactly the same as 'name'.
239 * and the return value tells which case it was.
241 * It returns 0 when there is no match.
243 static int match_pathspec_item(const struct pathspec_item *item, int prefix,
244 const char *name, int namelen)
246 /* name/namelen has prefix cut off by caller */
247 const char *match = item->match + prefix;
248 int matchlen = item->len - prefix;
250 /* If the match was just the prefix, we matched */
251 if (!*match)
252 return MATCHED_RECURSIVELY;
254 if (matchlen <= namelen && !strncmp(match, name, matchlen)) {
255 if (matchlen == namelen)
256 return MATCHED_EXACTLY;
258 if (match[matchlen-1] == '/' || name[matchlen] == '/')
259 return MATCHED_RECURSIVELY;
262 if (item->nowildcard_len < item->len &&
263 !git_fnmatch(match, name,
264 item->flags & PATHSPEC_ONESTAR ? GFNM_ONESTAR : 0,
265 item->nowildcard_len - prefix))
266 return MATCHED_FNMATCH;
268 return 0;
272 * Given a name and a list of pathspecs, see if the name matches
273 * any of the pathspecs. The caller is also interested in seeing
274 * all pathspec matches some names it calls this function with
275 * (otherwise the user could have mistyped the unmatched pathspec),
276 * and a mark is left in seen[] array for pathspec element that
277 * actually matched anything.
279 int match_pathspec_depth(const struct pathspec *ps,
280 const char *name, int namelen,
281 int prefix, char *seen)
283 int i, retval = 0;
285 if (!ps->nr) {
286 if (!ps->recursive || ps->max_depth == -1)
287 return MATCHED_RECURSIVELY;
289 if (within_depth(name, namelen, 0, ps->max_depth))
290 return MATCHED_EXACTLY;
291 else
292 return 0;
295 name += prefix;
296 namelen -= prefix;
298 for (i = ps->nr - 1; i >= 0; i--) {
299 int how;
300 if (seen && seen[i] == MATCHED_EXACTLY)
301 continue;
302 how = match_pathspec_item(ps->items+i, prefix, name, namelen);
303 if (ps->recursive && ps->max_depth != -1 &&
304 how && how != MATCHED_FNMATCH) {
305 int len = ps->items[i].len;
306 if (name[len] == '/')
307 len++;
308 if (within_depth(name+len, namelen-len, 0, ps->max_depth))
309 how = MATCHED_EXACTLY;
310 else
311 how = 0;
313 if (how) {
314 if (retval < how)
315 retval = how;
316 if (seen && seen[i] < how)
317 seen[i] = how;
320 return retval;
324 * Return the length of the "simple" part of a path match limiter.
326 static int simple_length(const char *match)
328 int len = -1;
330 for (;;) {
331 unsigned char c = *match++;
332 len++;
333 if (c == '\0' || is_glob_special(c))
334 return len;
338 static int no_wildcard(const char *string)
340 return string[simple_length(string)] == '\0';
343 void parse_exclude_pattern(const char **pattern,
344 int *patternlen,
345 int *flags,
346 int *nowildcardlen)
348 const char *p = *pattern;
349 size_t i, len;
351 *flags = 0;
352 if (*p == '!') {
353 *flags |= EXC_FLAG_NEGATIVE;
354 p++;
356 len = strlen(p);
357 if (len && p[len - 1] == '/') {
358 len--;
359 *flags |= EXC_FLAG_MUSTBEDIR;
361 for (i = 0; i < len; i++) {
362 if (p[i] == '/')
363 break;
365 if (i == len)
366 *flags |= EXC_FLAG_NODIR;
367 *nowildcardlen = simple_length(p);
369 * we should have excluded the trailing slash from 'p' too,
370 * but that's one more allocation. Instead just make sure
371 * nowildcardlen does not exceed real patternlen
373 if (*nowildcardlen > len)
374 *nowildcardlen = len;
375 if (*p == '*' && no_wildcard(p + 1))
376 *flags |= EXC_FLAG_ENDSWITH;
377 *pattern = p;
378 *patternlen = len;
381 void add_exclude(const char *string, const char *base,
382 int baselen, struct exclude_list *el)
384 struct exclude *x;
385 int patternlen;
386 int flags;
387 int nowildcardlen;
389 parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen);
390 if (flags & EXC_FLAG_MUSTBEDIR) {
391 char *s;
392 x = xmalloc(sizeof(*x) + patternlen + 1);
393 s = (char *)(x+1);
394 memcpy(s, string, patternlen);
395 s[patternlen] = '\0';
396 x->pattern = s;
397 } else {
398 x = xmalloc(sizeof(*x));
399 x->pattern = string;
401 x->patternlen = patternlen;
402 x->nowildcardlen = nowildcardlen;
403 x->base = base;
404 x->baselen = baselen;
405 x->flags = flags;
406 ALLOC_GROW(el->excludes, el->nr + 1, el->alloc);
407 el->excludes[el->nr++] = x;
410 static void *read_skip_worktree_file_from_index(const char *path, size_t *size)
412 int pos, len;
413 unsigned long sz;
414 enum object_type type;
415 void *data;
416 struct index_state *istate = &the_index;
418 len = strlen(path);
419 pos = index_name_pos(istate, path, len);
420 if (pos < 0)
421 return NULL;
422 if (!ce_skip_worktree(istate->cache[pos]))
423 return NULL;
424 data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
425 if (!data || type != OBJ_BLOB) {
426 free(data);
427 return NULL;
429 *size = xsize_t(sz);
430 return data;
434 * Frees memory within el which was allocated for exclude patterns and
435 * the file buffer. Does not free el itself.
437 void clear_exclude_list(struct exclude_list *el)
439 int i;
441 for (i = 0; i < el->nr; i++)
442 free(el->excludes[i]);
443 free(el->excludes);
445 el->nr = 0;
446 el->excludes = NULL;
449 int add_excludes_from_file_to_list(const char *fname,
450 const char *base,
451 int baselen,
452 char **buf_p,
453 struct exclude_list *el,
454 int check_index)
456 struct stat st;
457 int fd, i;
458 size_t size = 0;
459 char *buf, *entry;
461 fd = open(fname, O_RDONLY);
462 if (fd < 0 || fstat(fd, &st) < 0) {
463 if (errno != ENOENT)
464 warn_on_inaccessible(fname);
465 if (0 <= fd)
466 close(fd);
467 if (!check_index ||
468 (buf = read_skip_worktree_file_from_index(fname, &size)) == NULL)
469 return -1;
470 if (size == 0) {
471 free(buf);
472 return 0;
474 if (buf[size-1] != '\n') {
475 buf = xrealloc(buf, size+1);
476 buf[size++] = '\n';
479 else {
480 size = xsize_t(st.st_size);
481 if (size == 0) {
482 close(fd);
483 return 0;
485 buf = xmalloc(size+1);
486 if (read_in_full(fd, buf, size) != size) {
487 free(buf);
488 close(fd);
489 return -1;
491 buf[size++] = '\n';
492 close(fd);
495 if (buf_p)
496 *buf_p = buf;
497 entry = buf;
498 for (i = 0; i < size; i++) {
499 if (buf[i] == '\n') {
500 if (entry != buf + i && entry[0] != '#') {
501 buf[i - (i && buf[i-1] == '\r')] = 0;
502 add_exclude(entry, base, baselen, el);
504 entry = buf + i + 1;
507 return 0;
510 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
512 if (add_excludes_from_file_to_list(fname, "", 0, NULL,
513 &dir->exclude_list[EXC_FILE], 0) < 0)
514 die("cannot use %s as an exclude file", fname);
518 * Loads the per-directory exclude list for the substring of base
519 * which has a char length of baselen.
521 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
523 struct exclude_list *el;
524 struct exclude_stack *stk = NULL;
525 int current;
527 if ((!dir->exclude_per_dir) ||
528 (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
529 return; /* too long a path -- ignore */
531 /* Pop the directories that are not the prefix of the path being checked. */
532 el = &dir->exclude_list[EXC_DIRS];
533 while ((stk = dir->exclude_stack) != NULL) {
534 if (stk->baselen <= baselen &&
535 !strncmp(dir->basebuf, base, stk->baselen))
536 break;
537 dir->exclude_stack = stk->prev;
538 while (stk->exclude_ix < el->nr)
539 free(el->excludes[--el->nr]);
540 free(stk->filebuf);
541 free(stk);
544 /* Read from the parent directories and push them down. */
545 current = stk ? stk->baselen : -1;
546 while (current < baselen) {
547 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
548 const char *cp;
550 if (current < 0) {
551 cp = base;
552 current = 0;
554 else {
555 cp = strchr(base + current + 1, '/');
556 if (!cp)
557 die("oops in prep_exclude");
558 cp++;
560 stk->prev = dir->exclude_stack;
561 stk->baselen = cp - base;
562 stk->exclude_ix = el->nr;
563 memcpy(dir->basebuf + current, base + current,
564 stk->baselen - current);
565 strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
566 add_excludes_from_file_to_list(dir->basebuf,
567 dir->basebuf, stk->baselen,
568 &stk->filebuf, el, 1);
569 dir->exclude_stack = stk;
570 current = stk->baselen;
572 dir->basebuf[baselen] = '\0';
575 int match_basename(const char *basename, int basenamelen,
576 const char *pattern, int prefix, int patternlen,
577 int flags)
579 if (prefix == patternlen) {
580 if (!strcmp_icase(pattern, basename))
581 return 1;
582 } else if (flags & EXC_FLAG_ENDSWITH) {
583 if (patternlen - 1 <= basenamelen &&
584 !strcmp_icase(pattern + 1,
585 basename + basenamelen - patternlen + 1))
586 return 1;
587 } else {
588 if (fnmatch_icase(pattern, basename, 0) == 0)
589 return 1;
591 return 0;
594 int match_pathname(const char *pathname, int pathlen,
595 const char *base, int baselen,
596 const char *pattern, int prefix, int patternlen,
597 int flags)
599 const char *name;
600 int namelen;
603 * match with FNM_PATHNAME; the pattern has base implicitly
604 * in front of it.
606 if (*pattern == '/') {
607 pattern++;
608 prefix--;
612 * baselen does not count the trailing slash. base[] may or
613 * may not end with a trailing slash though.
615 if (pathlen < baselen + 1 ||
616 (baselen && pathname[baselen] != '/') ||
617 strncmp_icase(pathname, base, baselen))
618 return 0;
620 namelen = baselen ? pathlen - baselen - 1 : pathlen;
621 name = pathname + pathlen - namelen;
623 if (prefix) {
625 * if the non-wildcard part is longer than the
626 * remaining pathname, surely it cannot match.
628 if (prefix > namelen)
629 return 0;
631 if (strncmp_icase(pattern, name, prefix))
632 return 0;
633 pattern += prefix;
634 name += prefix;
635 namelen -= prefix;
638 return wildmatch(pattern, name,
639 ignore_case ? FNM_CASEFOLD : 0) == 0;
643 * Scan the given exclude list in reverse to see whether pathname
644 * should be ignored. The first match (i.e. the last on the list), if
645 * any, determines the fate. Returns the exclude_list element which
646 * matched, or NULL for undecided.
648 static struct exclude *last_exclude_matching_from_list(const char *pathname,
649 int pathlen,
650 const char *basename,
651 int *dtype,
652 struct exclude_list *el)
654 int i;
656 if (!el->nr)
657 return NULL; /* undefined */
659 for (i = el->nr - 1; 0 <= i; i--) {
660 struct exclude *x = el->excludes[i];
661 const char *exclude = x->pattern;
662 int prefix = x->nowildcardlen;
664 if (x->flags & EXC_FLAG_MUSTBEDIR) {
665 if (*dtype == DT_UNKNOWN)
666 *dtype = get_dtype(NULL, pathname, pathlen);
667 if (*dtype != DT_DIR)
668 continue;
671 if (x->flags & EXC_FLAG_NODIR) {
672 if (match_basename(basename,
673 pathlen - (basename - pathname),
674 exclude, prefix, x->patternlen,
675 x->flags))
676 return x;
677 continue;
680 assert(x->baselen == 0 || x->base[x->baselen - 1] == '/');
681 if (match_pathname(pathname, pathlen,
682 x->base, x->baselen ? x->baselen - 1 : 0,
683 exclude, prefix, x->patternlen, x->flags))
684 return x;
686 return NULL; /* undecided */
690 * Scan the list and let the last match determine the fate.
691 * Return 1 for exclude, 0 for include and -1 for undecided.
693 int is_excluded_from_list(const char *pathname,
694 int pathlen, const char *basename, int *dtype,
695 struct exclude_list *el)
697 struct exclude *exclude;
698 exclude = last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el);
699 if (exclude)
700 return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
701 return -1; /* undecided */
705 * Loads the exclude lists for the directory containing pathname, then
706 * scans all exclude lists to determine whether pathname is excluded.
707 * Returns the exclude_list element which matched, or NULL for
708 * undecided.
710 static struct exclude *last_exclude_matching(struct dir_struct *dir,
711 const char *pathname,
712 int *dtype_p)
714 int pathlen = strlen(pathname);
715 int st;
716 struct exclude *exclude;
717 const char *basename = strrchr(pathname, '/');
718 basename = (basename) ? basename+1 : pathname;
720 prep_exclude(dir, pathname, basename-pathname);
721 for (st = EXC_CMDL; st <= EXC_FILE; st++) {
722 exclude = last_exclude_matching_from_list(
723 pathname, pathlen, basename, dtype_p,
724 &dir->exclude_list[st]);
725 if (exclude)
726 return exclude;
728 return NULL;
732 * Loads the exclude lists for the directory containing pathname, then
733 * scans all exclude lists to determine whether pathname is excluded.
734 * Returns 1 if true, otherwise 0.
736 static int is_excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
738 struct exclude *exclude =
739 last_exclude_matching(dir, pathname, dtype_p);
740 if (exclude)
741 return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
742 return 0;
745 void path_exclude_check_init(struct path_exclude_check *check,
746 struct dir_struct *dir)
748 check->dir = dir;
749 check->exclude = NULL;
750 strbuf_init(&check->path, 256);
753 void path_exclude_check_clear(struct path_exclude_check *check)
755 strbuf_release(&check->path);
759 * For each subdirectory in name, starting with the top-most, checks
760 * to see if that subdirectory is excluded, and if so, returns the
761 * corresponding exclude structure. Otherwise, checks whether name
762 * itself (which is presumably a file) is excluded.
764 * A path to a directory known to be excluded is left in check->path to
765 * optimize for repeated checks for files in the same excluded directory.
767 struct exclude *last_exclude_matching_path(struct path_exclude_check *check,
768 const char *name, int namelen,
769 int *dtype)
771 int i;
772 struct strbuf *path = &check->path;
773 struct exclude *exclude;
776 * we allow the caller to pass namelen as an optimization; it
777 * must match the length of the name, as we eventually call
778 * is_excluded() on the whole name string.
780 if (namelen < 0)
781 namelen = strlen(name);
784 * If path is non-empty, and name is equal to path or a
785 * subdirectory of path, name should be excluded, because
786 * it's inside a directory which is already known to be
787 * excluded and was previously left in check->path.
789 if (path->len &&
790 path->len <= namelen &&
791 !memcmp(name, path->buf, path->len) &&
792 (!name[path->len] || name[path->len] == '/'))
793 return check->exclude;
795 strbuf_setlen(path, 0);
796 for (i = 0; name[i]; i++) {
797 int ch = name[i];
799 if (ch == '/') {
800 int dt = DT_DIR;
801 exclude = last_exclude_matching(check->dir,
802 path->buf, &dt);
803 if (exclude) {
804 check->exclude = exclude;
805 return exclude;
808 strbuf_addch(path, ch);
811 /* An entry in the index; cannot be a directory with subentries */
812 strbuf_setlen(path, 0);
814 return last_exclude_matching(check->dir, name, dtype);
818 * Is this name excluded? This is for a caller like show_files() that
819 * do not honor directory hierarchy and iterate through paths that are
820 * possibly in an ignored directory.
822 int is_path_excluded(struct path_exclude_check *check,
823 const char *name, int namelen, int *dtype)
825 struct exclude *exclude =
826 last_exclude_matching_path(check, name, namelen, dtype);
827 if (exclude)
828 return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
829 return 0;
832 static struct dir_entry *dir_entry_new(const char *pathname, int len)
834 struct dir_entry *ent;
836 ent = xmalloc(sizeof(*ent) + len + 1);
837 ent->len = len;
838 memcpy(ent->name, pathname, len);
839 ent->name[len] = 0;
840 return ent;
843 static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
845 if (!(dir->flags & DIR_SHOW_IGNORED) &&
846 cache_name_exists(pathname, len, ignore_case))
847 return NULL;
849 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
850 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
853 struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
855 if (!cache_name_is_other(pathname, len))
856 return NULL;
858 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
859 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
862 enum exist_status {
863 index_nonexistent = 0,
864 index_directory,
865 index_gitdir
869 * Do not use the alphabetically stored index to look up
870 * the directory name; instead, use the case insensitive
871 * name hash.
873 static enum exist_status directory_exists_in_index_icase(const char *dirname, int len)
875 struct cache_entry *ce = index_name_exists(&the_index, dirname, len + 1, ignore_case);
876 unsigned char endchar;
878 if (!ce)
879 return index_nonexistent;
880 endchar = ce->name[len];
883 * The cache_entry structure returned will contain this dirname
884 * and possibly additional path components.
886 if (endchar == '/')
887 return index_directory;
890 * If there are no additional path components, then this cache_entry
891 * represents a submodule. Submodules, despite being directories,
892 * are stored in the cache without a closing slash.
894 if (!endchar && S_ISGITLINK(ce->ce_mode))
895 return index_gitdir;
897 /* This should never be hit, but it exists just in case. */
898 return index_nonexistent;
902 * The index sorts alphabetically by entry name, which
903 * means that a gitlink sorts as '\0' at the end, while
904 * a directory (which is defined not as an entry, but as
905 * the files it contains) will sort with the '/' at the
906 * end.
908 static enum exist_status directory_exists_in_index(const char *dirname, int len)
910 int pos;
912 if (ignore_case)
913 return directory_exists_in_index_icase(dirname, len);
915 pos = cache_name_pos(dirname, len);
916 if (pos < 0)
917 pos = -pos-1;
918 while (pos < active_nr) {
919 struct cache_entry *ce = active_cache[pos++];
920 unsigned char endchar;
922 if (strncmp(ce->name, dirname, len))
923 break;
924 endchar = ce->name[len];
925 if (endchar > '/')
926 break;
927 if (endchar == '/')
928 return index_directory;
929 if (!endchar && S_ISGITLINK(ce->ce_mode))
930 return index_gitdir;
932 return index_nonexistent;
936 * When we find a directory when traversing the filesystem, we
937 * have three distinct cases:
939 * - ignore it
940 * - see it as a directory
941 * - recurse into it
943 * and which one we choose depends on a combination of existing
944 * git index contents and the flags passed into the directory
945 * traversal routine.
947 * Case 1: If we *already* have entries in the index under that
948 * directory name, we recurse into the directory to see all the files,
949 * unless the directory is excluded and we want to show ignored
950 * directories
952 * Case 2: If we *already* have that directory name as a gitlink,
953 * we always continue to see it as a gitlink, regardless of whether
954 * there is an actual git directory there or not (it might not
955 * be checked out as a subproject!)
957 * Case 3: if we didn't have it in the index previously, we
958 * have a few sub-cases:
960 * (a) if "show_other_directories" is true, we show it as
961 * just a directory, unless "hide_empty_directories" is
962 * also true and the directory is empty, in which case
963 * we just ignore it entirely.
964 * if we are looking for ignored directories, look if it
965 * contains only ignored files to decide if it must be shown as
966 * ignored or not.
967 * (b) if it looks like a git directory, and we don't have
968 * 'no_gitlinks' set we treat it as a gitlink, and show it
969 * as a directory.
970 * (c) otherwise, we recurse into it.
972 enum directory_treatment {
973 show_directory,
974 ignore_directory,
975 recurse_into_directory
978 static enum directory_treatment treat_directory(struct dir_struct *dir,
979 const char *dirname, int len, int exclude,
980 const struct path_simplify *simplify)
982 /* The "len-1" is to strip the final '/' */
983 switch (directory_exists_in_index(dirname, len-1)) {
984 case index_directory:
985 if ((dir->flags & DIR_SHOW_OTHER_DIRECTORIES) && exclude)
986 break;
988 return recurse_into_directory;
990 case index_gitdir:
991 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
992 return ignore_directory;
993 return show_directory;
995 case index_nonexistent:
996 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
997 break;
998 if (!(dir->flags & DIR_NO_GITLINKS)) {
999 unsigned char sha1[20];
1000 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
1001 return show_directory;
1003 return recurse_into_directory;
1006 /* This is the "show_other_directories" case */
1009 * We are looking for ignored files and our directory is not ignored,
1010 * check if it contains only ignored files
1012 if ((dir->flags & DIR_SHOW_IGNORED) && !exclude) {
1013 int ignored;
1014 dir->flags &= ~DIR_SHOW_IGNORED;
1015 dir->flags |= DIR_HIDE_EMPTY_DIRECTORIES;
1016 ignored = read_directory_recursive(dir, dirname, len, 1, simplify);
1017 dir->flags &= ~DIR_HIDE_EMPTY_DIRECTORIES;
1018 dir->flags |= DIR_SHOW_IGNORED;
1020 return ignored ? ignore_directory : show_directory;
1022 if (!(dir->flags & DIR_SHOW_IGNORED) &&
1023 !(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1024 return show_directory;
1025 if (!read_directory_recursive(dir, dirname, len, 1, simplify))
1026 return ignore_directory;
1027 return show_directory;
1031 * Decide what to do when we find a file while traversing the
1032 * filesystem. Mostly two cases:
1034 * 1. We are looking for ignored files
1035 * (a) File is ignored, include it
1036 * (b) File is in ignored path, include it
1037 * (c) File is not ignored, exclude it
1039 * 2. Other scenarios, include the file if not excluded
1041 * Return 1 for exclude, 0 for include.
1043 static int treat_file(struct dir_struct *dir, struct strbuf *path, int exclude, int *dtype)
1045 struct path_exclude_check check;
1046 int exclude_file = 0;
1048 if (exclude)
1049 exclude_file = !(dir->flags & DIR_SHOW_IGNORED);
1050 else if (dir->flags & DIR_SHOW_IGNORED) {
1051 /* Always exclude indexed files */
1052 struct cache_entry *ce = index_name_exists(&the_index,
1053 path->buf, path->len, ignore_case);
1055 if (ce)
1056 return 1;
1058 path_exclude_check_init(&check, dir);
1060 if (!is_path_excluded(&check, path->buf, path->len, dtype))
1061 exclude_file = 1;
1063 path_exclude_check_clear(&check);
1066 return exclude_file;
1070 * This is an inexact early pruning of any recursive directory
1071 * reading - if the path cannot possibly be in the pathspec,
1072 * return true, and we'll skip it early.
1074 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
1076 if (simplify) {
1077 for (;;) {
1078 const char *match = simplify->path;
1079 int len = simplify->len;
1081 if (!match)
1082 break;
1083 if (len > pathlen)
1084 len = pathlen;
1085 if (!memcmp(path, match, len))
1086 return 0;
1087 simplify++;
1089 return 1;
1091 return 0;
1095 * This function tells us whether an excluded path matches a
1096 * list of "interesting" pathspecs. That is, whether a path matched
1097 * by any of the pathspecs could possibly be ignored by excluding
1098 * the specified path. This can happen if:
1100 * 1. the path is mentioned explicitly in the pathspec
1102 * 2. the path is a directory prefix of some element in the
1103 * pathspec
1105 static int exclude_matches_pathspec(const char *path, int len,
1106 const struct path_simplify *simplify)
1108 if (simplify) {
1109 for (; simplify->path; simplify++) {
1110 if (len == simplify->len
1111 && !memcmp(path, simplify->path, len))
1112 return 1;
1113 if (len < simplify->len
1114 && simplify->path[len] == '/'
1115 && !memcmp(path, simplify->path, len))
1116 return 1;
1119 return 0;
1122 static int get_index_dtype(const char *path, int len)
1124 int pos;
1125 struct cache_entry *ce;
1127 ce = cache_name_exists(path, len, 0);
1128 if (ce) {
1129 if (!ce_uptodate(ce))
1130 return DT_UNKNOWN;
1131 if (S_ISGITLINK(ce->ce_mode))
1132 return DT_DIR;
1134 * Nobody actually cares about the
1135 * difference between DT_LNK and DT_REG
1137 return DT_REG;
1140 /* Try to look it up as a directory */
1141 pos = cache_name_pos(path, len);
1142 if (pos >= 0)
1143 return DT_UNKNOWN;
1144 pos = -pos-1;
1145 while (pos < active_nr) {
1146 ce = active_cache[pos++];
1147 if (strncmp(ce->name, path, len))
1148 break;
1149 if (ce->name[len] > '/')
1150 break;
1151 if (ce->name[len] < '/')
1152 continue;
1153 if (!ce_uptodate(ce))
1154 break; /* continue? */
1155 return DT_DIR;
1157 return DT_UNKNOWN;
1160 static int get_dtype(struct dirent *de, const char *path, int len)
1162 int dtype = de ? DTYPE(de) : DT_UNKNOWN;
1163 struct stat st;
1165 if (dtype != DT_UNKNOWN)
1166 return dtype;
1167 dtype = get_index_dtype(path, len);
1168 if (dtype != DT_UNKNOWN)
1169 return dtype;
1170 if (lstat(path, &st))
1171 return dtype;
1172 if (S_ISREG(st.st_mode))
1173 return DT_REG;
1174 if (S_ISDIR(st.st_mode))
1175 return DT_DIR;
1176 if (S_ISLNK(st.st_mode))
1177 return DT_LNK;
1178 return dtype;
1181 enum path_treatment {
1182 path_ignored,
1183 path_handled,
1184 path_recurse
1187 static enum path_treatment treat_one_path(struct dir_struct *dir,
1188 struct strbuf *path,
1189 const struct path_simplify *simplify,
1190 int dtype, struct dirent *de)
1192 int exclude = is_excluded(dir, path->buf, &dtype);
1193 if (exclude && (dir->flags & DIR_COLLECT_IGNORED)
1194 && exclude_matches_pathspec(path->buf, path->len, simplify))
1195 dir_add_ignored(dir, path->buf, path->len);
1198 * Excluded? If we don't explicitly want to show
1199 * ignored files, ignore it
1201 if (exclude && !(dir->flags & DIR_SHOW_IGNORED))
1202 return path_ignored;
1204 if (dtype == DT_UNKNOWN)
1205 dtype = get_dtype(de, path->buf, path->len);
1207 switch (dtype) {
1208 default:
1209 return path_ignored;
1210 case DT_DIR:
1211 strbuf_addch(path, '/');
1213 switch (treat_directory(dir, path->buf, path->len, exclude, simplify)) {
1214 case show_directory:
1215 break;
1216 case recurse_into_directory:
1217 return path_recurse;
1218 case ignore_directory:
1219 return path_ignored;
1221 break;
1222 case DT_REG:
1223 case DT_LNK:
1224 switch (treat_file(dir, path, exclude, &dtype)) {
1225 case 1:
1226 return path_ignored;
1227 default:
1228 break;
1231 return path_handled;
1234 static enum path_treatment treat_path(struct dir_struct *dir,
1235 struct dirent *de,
1236 struct strbuf *path,
1237 int baselen,
1238 const struct path_simplify *simplify)
1240 int dtype;
1242 if (is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name, ".git"))
1243 return path_ignored;
1244 strbuf_setlen(path, baselen);
1245 strbuf_addstr(path, de->d_name);
1246 if (simplify_away(path->buf, path->len, simplify))
1247 return path_ignored;
1249 dtype = DTYPE(de);
1250 return treat_one_path(dir, path, simplify, dtype, de);
1254 * Read a directory tree. We currently ignore anything but
1255 * directories, regular files and symlinks. That's because git
1256 * doesn't handle them at all yet. Maybe that will change some
1257 * day.
1259 * Also, we ignore the name ".git" (even if it is not a directory).
1260 * That likely will not change.
1262 static int read_directory_recursive(struct dir_struct *dir,
1263 const char *base, int baselen,
1264 int check_only,
1265 const struct path_simplify *simplify)
1267 DIR *fdir;
1268 int contents = 0;
1269 struct dirent *de;
1270 struct strbuf path = STRBUF_INIT;
1272 strbuf_add(&path, base, baselen);
1274 fdir = opendir(path.len ? path.buf : ".");
1275 if (!fdir)
1276 goto out;
1278 while ((de = readdir(fdir)) != NULL) {
1279 switch (treat_path(dir, de, &path, baselen, simplify)) {
1280 case path_recurse:
1281 contents += read_directory_recursive(dir, path.buf,
1282 path.len, 0,
1283 simplify);
1284 continue;
1285 case path_ignored:
1286 continue;
1287 case path_handled:
1288 break;
1290 contents++;
1291 if (check_only)
1292 break;
1293 dir_add_name(dir, path.buf, path.len);
1295 closedir(fdir);
1296 out:
1297 strbuf_release(&path);
1299 return contents;
1302 static int cmp_name(const void *p1, const void *p2)
1304 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
1305 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
1307 return cache_name_compare(e1->name, e1->len,
1308 e2->name, e2->len);
1311 static struct path_simplify *create_simplify(const char **pathspec)
1313 int nr, alloc = 0;
1314 struct path_simplify *simplify = NULL;
1316 if (!pathspec)
1317 return NULL;
1319 for (nr = 0 ; ; nr++) {
1320 const char *match;
1321 if (nr >= alloc) {
1322 alloc = alloc_nr(alloc);
1323 simplify = xrealloc(simplify, alloc * sizeof(*simplify));
1325 match = *pathspec++;
1326 if (!match)
1327 break;
1328 simplify[nr].path = match;
1329 simplify[nr].len = simple_length(match);
1331 simplify[nr].path = NULL;
1332 simplify[nr].len = 0;
1333 return simplify;
1336 static void free_simplify(struct path_simplify *simplify)
1338 free(simplify);
1341 static int treat_leading_path(struct dir_struct *dir,
1342 const char *path, int len,
1343 const struct path_simplify *simplify)
1345 struct strbuf sb = STRBUF_INIT;
1346 int baselen, rc = 0;
1347 const char *cp;
1349 while (len && path[len - 1] == '/')
1350 len--;
1351 if (!len)
1352 return 1;
1353 baselen = 0;
1354 while (1) {
1355 cp = path + baselen + !!baselen;
1356 cp = memchr(cp, '/', path + len - cp);
1357 if (!cp)
1358 baselen = len;
1359 else
1360 baselen = cp - path;
1361 strbuf_setlen(&sb, 0);
1362 strbuf_add(&sb, path, baselen);
1363 if (!is_directory(sb.buf))
1364 break;
1365 if (simplify_away(sb.buf, sb.len, simplify))
1366 break;
1367 if (treat_one_path(dir, &sb, simplify,
1368 DT_DIR, NULL) == path_ignored)
1369 break; /* do not recurse into it */
1370 if (len <= baselen) {
1371 rc = 1;
1372 break; /* finished checking */
1375 strbuf_release(&sb);
1376 return rc;
1379 int read_directory(struct dir_struct *dir, const char *path, int len, const char **pathspec)
1381 struct path_simplify *simplify;
1383 if (has_symlink_leading_path(path, len))
1384 return dir->nr;
1386 simplify = create_simplify(pathspec);
1387 if (!len || treat_leading_path(dir, path, len, simplify))
1388 read_directory_recursive(dir, path, len, 0, simplify);
1389 free_simplify(simplify);
1390 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
1391 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
1392 return dir->nr;
1395 int file_exists(const char *f)
1397 struct stat sb;
1398 return lstat(f, &sb) == 0;
1402 * Given two normalized paths (a trailing slash is ok), if subdir is
1403 * outside dir, return -1. Otherwise return the offset in subdir that
1404 * can be used as relative path to dir.
1406 int dir_inside_of(const char *subdir, const char *dir)
1408 int offset = 0;
1410 assert(dir && subdir && *dir && *subdir);
1412 while (*dir && *subdir && *dir == *subdir) {
1413 dir++;
1414 subdir++;
1415 offset++;
1418 /* hel[p]/me vs hel[l]/yeah */
1419 if (*dir && *subdir)
1420 return -1;
1422 if (!*subdir)
1423 return !*dir ? offset : -1; /* same dir */
1425 /* foo/[b]ar vs foo/[] */
1426 if (is_dir_sep(dir[-1]))
1427 return is_dir_sep(subdir[-1]) ? offset : -1;
1429 /* foo[/]bar vs foo[] */
1430 return is_dir_sep(*subdir) ? offset + 1 : -1;
1433 int is_inside_dir(const char *dir)
1435 char cwd[PATH_MAX];
1436 if (!dir)
1437 return 0;
1438 if (!getcwd(cwd, sizeof(cwd)))
1439 die_errno("can't find the current directory");
1440 return dir_inside_of(cwd, dir) >= 0;
1443 int is_empty_dir(const char *path)
1445 DIR *dir = opendir(path);
1446 struct dirent *e;
1447 int ret = 1;
1449 if (!dir)
1450 return 0;
1452 while ((e = readdir(dir)) != NULL)
1453 if (!is_dot_or_dotdot(e->d_name)) {
1454 ret = 0;
1455 break;
1458 closedir(dir);
1459 return ret;
1462 static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
1464 DIR *dir;
1465 struct dirent *e;
1466 int ret = 0, original_len = path->len, len, kept_down = 0;
1467 int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
1468 int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
1469 unsigned char submodule_head[20];
1471 if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
1472 !resolve_gitlink_ref(path->buf, "HEAD", submodule_head)) {
1473 /* Do not descend and nuke a nested git work tree. */
1474 if (kept_up)
1475 *kept_up = 1;
1476 return 0;
1479 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
1480 dir = opendir(path->buf);
1481 if (!dir) {
1482 /* an empty dir could be removed even if it is unreadble */
1483 if (!keep_toplevel)
1484 return rmdir(path->buf);
1485 else
1486 return -1;
1488 if (path->buf[original_len - 1] != '/')
1489 strbuf_addch(path, '/');
1491 len = path->len;
1492 while ((e = readdir(dir)) != NULL) {
1493 struct stat st;
1494 if (is_dot_or_dotdot(e->d_name))
1495 continue;
1497 strbuf_setlen(path, len);
1498 strbuf_addstr(path, e->d_name);
1499 if (lstat(path->buf, &st))
1500 ; /* fall thru */
1501 else if (S_ISDIR(st.st_mode)) {
1502 if (!remove_dir_recurse(path, flag, &kept_down))
1503 continue; /* happy */
1504 } else if (!only_empty && !unlink(path->buf))
1505 continue; /* happy, too */
1507 /* path too long, stat fails, or non-directory still exists */
1508 ret = -1;
1509 break;
1511 closedir(dir);
1513 strbuf_setlen(path, original_len);
1514 if (!ret && !keep_toplevel && !kept_down)
1515 ret = rmdir(path->buf);
1516 else if (kept_up)
1518 * report the uplevel that it is not an error that we
1519 * did not rmdir() our directory.
1521 *kept_up = !ret;
1522 return ret;
1525 int remove_dir_recursively(struct strbuf *path, int flag)
1527 return remove_dir_recurse(path, flag, NULL);
1530 void setup_standard_excludes(struct dir_struct *dir)
1532 const char *path;
1533 char *xdg_path;
1535 dir->exclude_per_dir = ".gitignore";
1536 path = git_path("info/exclude");
1537 if (!excludes_file) {
1538 home_config_paths(NULL, &xdg_path, "ignore");
1539 excludes_file = xdg_path;
1541 if (!access_or_warn(path, R_OK))
1542 add_excludes_from_file(dir, path);
1543 if (excludes_file && !access_or_warn(excludes_file, R_OK))
1544 add_excludes_from_file(dir, excludes_file);
1547 int remove_path(const char *name)
1549 char *slash;
1551 if (unlink(name) && errno != ENOENT)
1552 return -1;
1554 slash = strrchr(name, '/');
1555 if (slash) {
1556 char *dirs = xstrdup(name);
1557 slash = dirs + (slash - name);
1558 do {
1559 *slash = '\0';
1560 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
1561 free(dirs);
1563 return 0;
1566 static int pathspec_item_cmp(const void *a_, const void *b_)
1568 struct pathspec_item *a, *b;
1570 a = (struct pathspec_item *)a_;
1571 b = (struct pathspec_item *)b_;
1572 return strcmp(a->match, b->match);
1575 int init_pathspec(struct pathspec *pathspec, const char **paths)
1577 const char **p = paths;
1578 int i;
1580 memset(pathspec, 0, sizeof(*pathspec));
1581 if (!p)
1582 return 0;
1583 while (*p)
1584 p++;
1585 pathspec->raw = paths;
1586 pathspec->nr = p - paths;
1587 if (!pathspec->nr)
1588 return 0;
1590 pathspec->items = xmalloc(sizeof(struct pathspec_item)*pathspec->nr);
1591 for (i = 0; i < pathspec->nr; i++) {
1592 struct pathspec_item *item = pathspec->items+i;
1593 const char *path = paths[i];
1595 item->match = path;
1596 item->len = strlen(path);
1597 item->flags = 0;
1598 if (limit_pathspec_to_literal()) {
1599 item->nowildcard_len = item->len;
1600 } else {
1601 item->nowildcard_len = simple_length(path);
1602 if (item->nowildcard_len < item->len) {
1603 pathspec->has_wildcard = 1;
1604 if (path[item->nowildcard_len] == '*' &&
1605 no_wildcard(path + item->nowildcard_len + 1))
1606 item->flags |= PATHSPEC_ONESTAR;
1611 qsort(pathspec->items, pathspec->nr,
1612 sizeof(struct pathspec_item), pathspec_item_cmp);
1614 return 0;
1617 void free_pathspec(struct pathspec *pathspec)
1619 free(pathspec->items);
1620 pathspec->items = NULL;
1623 int limit_pathspec_to_literal(void)
1625 static int flag = -1;
1626 if (flag < 0)
1627 flag = git_env_bool(GIT_LITERAL_PATHSPECS_ENVIRONMENT, 0);
1628 return flag;