2 * This handles recursive filename detection with exclude
3 * files, index knowledge etc..
5 * Copyright (C) Linus Torvalds, 2005-2006
6 * Junio Hamano, 2005-2006
12 struct path_simplify {
17 static int read_directory_recursive(struct dir_struct *dir, const char *path, int len,
18 int check_only, const struct path_simplify *simplify);
19 static int get_dtype(struct dirent *de, const char *path, int len);
21 static int common_prefix(const char **pathspec)
23 const char *path, *slash, *next;
30 slash = strrchr(path, '/');
34 prefix = slash - path + 1;
35 while ((next = *++pathspec) != NULL) {
36 int len = strlen(next);
37 if (len >= prefix && !memcmp(path, next, prefix))
43 if (next[--len] != '/')
45 if (memcmp(path, next, len+1))
54 int fill_directory(struct dir_struct *dir, const char **pathspec)
60 * Calculate common prefix for the pathspec, and
61 * use that to optimize the directory walk
63 len = common_prefix(pathspec);
67 path = xmemdupz(*pathspec, len);
69 /* Read the directory and prune it */
70 read_directory(dir, path, len, pathspec);
75 * Does 'match' match the given name?
78 * (1) the 'match' string is leading directory of 'name', or
79 * (2) the 'match' string is a wildcard and matches 'name', or
80 * (3) the 'match' string is exactly the same as 'name'.
82 * and the return value tells which case it was.
84 * It returns 0 when there is no match.
86 static int match_one(const char *match, const char *name, int namelen)
90 /* If the match was just the prefix, we matched */
92 return MATCHED_RECURSIVELY;
95 unsigned char c1 = *match;
96 unsigned char c2 = *name;
97 if (c1 == '\0' || is_glob_special(c1))
108 * If we don't match the matchstring exactly,
109 * we need to match by fnmatch
111 matchlen = strlen(match);
112 if (strncmp(match, name, matchlen))
113 return !fnmatch(match, name, 0) ? MATCHED_FNMATCH : 0;
115 if (namelen == matchlen)
116 return MATCHED_EXACTLY;
117 if (match[matchlen-1] == '/' || name[matchlen] == '/')
118 return MATCHED_RECURSIVELY;
123 * Given a name and a list of pathspecs, see if the name matches
124 * any of the pathspecs. The caller is also interested in seeing
125 * all pathspec matches some names it calls this function with
126 * (otherwise the user could have mistyped the unmatched pathspec),
127 * and a mark is left in seen[] array for pathspec element that
128 * actually matched anything.
130 int match_pathspec(const char **pathspec, const char *name, int namelen,
131 int prefix, char *seen)
141 for (i = 0; pathspec[i] != NULL; i++) {
143 const char *match = pathspec[i] + prefix;
144 if (seen && seen[i] == MATCHED_EXACTLY)
146 how = match_one(match, name, namelen);
150 if (seen && seen[i] < how)
157 static int no_wildcard(const char *string)
159 return string[strcspn(string, "*?[{\\")] == '\0';
162 void add_exclude(const char *string, const char *base,
163 int baselen, struct exclude_list *which)
170 if (*string == '!') {
174 len = strlen(string);
175 if (len && string[len - 1] == '/') {
177 x = xmalloc(sizeof(*x) + len);
179 memcpy(s, string, len - 1);
183 flags = EXC_FLAG_MUSTBEDIR;
185 x = xmalloc(sizeof(*x));
188 x->to_exclude = to_exclude;
189 x->patternlen = strlen(string);
191 x->baselen = baselen;
193 if (!strchr(string, '/'))
194 x->flags |= EXC_FLAG_NODIR;
195 if (no_wildcard(string))
196 x->flags |= EXC_FLAG_NOWILDCARD;
197 if (*string == '*' && no_wildcard(string+1))
198 x->flags |= EXC_FLAG_ENDSWITH;
199 ALLOC_GROW(which->excludes, which->nr + 1, which->alloc);
200 which->excludes[which->nr++] = x;
203 static void *read_skip_worktree_file_from_index(const char *path, size_t *size)
207 enum object_type type;
209 struct index_state *istate = &the_index;
212 pos = index_name_pos(istate, path, len);
215 if (!ce_skip_worktree(istate->cache[pos]))
217 data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
218 if (!data || type != OBJ_BLOB) {
226 int add_excludes_from_file_to_list(const char *fname,
230 struct exclude_list *which,
238 fd = open(fname, O_RDONLY);
239 if (fd < 0 || fstat(fd, &st) < 0) {
243 (buf = read_skip_worktree_file_from_index(fname, &size)) == NULL)
249 if (buf[size-1] != '\n') {
250 buf = xrealloc(buf, size+1);
255 size = xsize_t(st.st_size);
260 buf = xmalloc(size+1);
261 if (read_in_full(fd, buf, size) != size) {
273 for (i = 0; i < size; i++) {
274 if (buf[i] == '\n') {
275 if (entry != buf + i && entry[0] != '#') {
276 buf[i - (i && buf[i-1] == '\r')] = 0;
277 add_exclude(entry, base, baselen, which);
285 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
287 if (add_excludes_from_file_to_list(fname, "", 0, NULL,
288 &dir->exclude_list[EXC_FILE], 0) < 0)
289 die("cannot use %s as an exclude file", fname);
292 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
294 struct exclude_list *el;
295 struct exclude_stack *stk = NULL;
298 if ((!dir->exclude_per_dir) ||
299 (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
300 return; /* too long a path -- ignore */
302 /* Pop the ones that are not the prefix of the path being checked. */
303 el = &dir->exclude_list[EXC_DIRS];
304 while ((stk = dir->exclude_stack) != NULL) {
305 if (stk->baselen <= baselen &&
306 !strncmp(dir->basebuf, base, stk->baselen))
308 dir->exclude_stack = stk->prev;
309 while (stk->exclude_ix < el->nr)
310 free(el->excludes[--el->nr]);
315 /* Read from the parent directories and push them down. */
316 current = stk ? stk->baselen : -1;
317 while (current < baselen) {
318 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
326 cp = strchr(base + current + 1, '/');
328 die("oops in prep_exclude");
331 stk->prev = dir->exclude_stack;
332 stk->baselen = cp - base;
333 stk->exclude_ix = el->nr;
334 memcpy(dir->basebuf + current, base + current,
335 stk->baselen - current);
336 strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
337 add_excludes_from_file_to_list(dir->basebuf,
338 dir->basebuf, stk->baselen,
339 &stk->filebuf, el, 1);
340 dir->exclude_stack = stk;
341 current = stk->baselen;
343 dir->basebuf[baselen] = '\0';
346 /* Scan the list and let the last match determine the fate.
347 * Return 1 for exclude, 0 for include and -1 for undecided.
349 int excluded_from_list(const char *pathname,
350 int pathlen, const char *basename, int *dtype,
351 struct exclude_list *el)
356 for (i = el->nr - 1; 0 <= i; i--) {
357 struct exclude *x = el->excludes[i];
358 const char *exclude = x->pattern;
359 int to_exclude = x->to_exclude;
361 if (x->flags & EXC_FLAG_MUSTBEDIR) {
363 if (!prefixcmp(pathname, exclude))
368 if (*dtype == DT_UNKNOWN)
369 *dtype = get_dtype(NULL, pathname, pathlen);
370 if (*dtype != DT_DIR)
374 if (x->flags & EXC_FLAG_NODIR) {
376 if (x->flags & EXC_FLAG_NOWILDCARD) {
377 if (!strcmp(exclude, basename))
379 } else if (x->flags & EXC_FLAG_ENDSWITH) {
380 if (x->patternlen - 1 <= pathlen &&
381 !strcmp(exclude + 1, pathname + pathlen - x->patternlen + 1))
384 if (fnmatch(exclude, basename, 0) == 0)
389 /* match with FNM_PATHNAME:
390 * exclude has base (baselen long) implicitly
393 int baselen = x->baselen;
397 if (pathlen < baselen ||
398 (baselen && pathname[baselen-1] != '/') ||
399 strncmp(pathname, x->base, baselen))
402 if (x->flags & EXC_FLAG_NOWILDCARD) {
403 if (!strcmp(exclude, pathname + baselen))
406 if (fnmatch(exclude, pathname+baselen,
413 return -1; /* undecided */
416 int excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
418 int pathlen = strlen(pathname);
420 const char *basename = strrchr(pathname, '/');
421 basename = (basename) ? basename+1 : pathname;
423 prep_exclude(dir, pathname, basename-pathname);
424 for (st = EXC_CMDL; st <= EXC_FILE; st++) {
425 switch (excluded_from_list(pathname, pathlen, basename,
426 dtype_p, &dir->exclude_list[st])) {
436 static struct dir_entry *dir_entry_new(const char *pathname, int len)
438 struct dir_entry *ent;
440 ent = xmalloc(sizeof(*ent) + len + 1);
442 memcpy(ent->name, pathname, len);
447 static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
449 if (cache_name_exists(pathname, len, ignore_case))
452 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
453 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
456 static struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
458 if (!cache_name_is_other(pathname, len))
461 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
462 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
466 index_nonexistent = 0,
472 * The index sorts alphabetically by entry name, which
473 * means that a gitlink sorts as '\0' at the end, while
474 * a directory (which is defined not as an entry, but as
475 * the files it contains) will sort with the '/' at the
478 static enum exist_status directory_exists_in_index(const char *dirname, int len)
480 int pos = cache_name_pos(dirname, len);
483 while (pos < active_nr) {
484 struct cache_entry *ce = active_cache[pos++];
485 unsigned char endchar;
487 if (strncmp(ce->name, dirname, len))
489 endchar = ce->name[len];
493 return index_directory;
494 if (!endchar && S_ISGITLINK(ce->ce_mode))
497 return index_nonexistent;
501 * When we find a directory when traversing the filesystem, we
502 * have three distinct cases:
505 * - see it as a directory
508 * and which one we choose depends on a combination of existing
509 * git index contents and the flags passed into the directory
512 * Case 1: If we *already* have entries in the index under that
513 * directory name, we always recurse into the directory to see
516 * Case 2: If we *already* have that directory name as a gitlink,
517 * we always continue to see it as a gitlink, regardless of whether
518 * there is an actual git directory there or not (it might not
519 * be checked out as a subproject!)
521 * Case 3: if we didn't have it in the index previously, we
522 * have a few sub-cases:
524 * (a) if "show_other_directories" is true, we show it as
525 * just a directory, unless "hide_empty_directories" is
526 * also true and the directory is empty, in which case
527 * we just ignore it entirely.
528 * (b) if it looks like a git directory, and we don't have
529 * 'no_gitlinks' set we treat it as a gitlink, and show it
531 * (c) otherwise, we recurse into it.
533 enum directory_treatment {
536 recurse_into_directory,
539 static enum directory_treatment treat_directory(struct dir_struct *dir,
540 const char *dirname, int len,
541 const struct path_simplify *simplify)
543 /* The "len-1" is to strip the final '/' */
544 switch (directory_exists_in_index(dirname, len-1)) {
545 case index_directory:
546 return recurse_into_directory;
549 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
550 return ignore_directory;
551 return show_directory;
553 case index_nonexistent:
554 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
556 if (!(dir->flags & DIR_NO_GITLINKS)) {
557 unsigned char sha1[20];
558 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
559 return show_directory;
561 return recurse_into_directory;
564 /* This is the "show_other_directories" case */
565 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
566 return show_directory;
567 if (!read_directory_recursive(dir, dirname, len, 1, simplify))
568 return ignore_directory;
569 return show_directory;
573 * This is an inexact early pruning of any recursive directory
574 * reading - if the path cannot possibly be in the pathspec,
575 * return true, and we'll skip it early.
577 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
581 const char *match = simplify->path;
582 int len = simplify->len;
588 if (!memcmp(path, match, len))
597 static int in_pathspec(const char *path, int len, const struct path_simplify *simplify)
600 for (; simplify->path; simplify++) {
601 if (len == simplify->len
602 && !memcmp(path, simplify->path, len))
609 static int get_index_dtype(const char *path, int len)
612 struct cache_entry *ce;
614 ce = cache_name_exists(path, len, 0);
616 if (!ce_uptodate(ce))
618 if (S_ISGITLINK(ce->ce_mode))
621 * Nobody actually cares about the
622 * difference between DT_LNK and DT_REG
627 /* Try to look it up as a directory */
628 pos = cache_name_pos(path, len);
632 while (pos < active_nr) {
633 ce = active_cache[pos++];
634 if (strncmp(ce->name, path, len))
636 if (ce->name[len] > '/')
638 if (ce->name[len] < '/')
640 if (!ce_uptodate(ce))
641 break; /* continue? */
647 static int get_dtype(struct dirent *de, const char *path, int len)
649 int dtype = de ? DTYPE(de) : DT_UNKNOWN;
652 if (dtype != DT_UNKNOWN)
654 dtype = get_index_dtype(path, len);
655 if (dtype != DT_UNKNOWN)
657 if (lstat(path, &st))
659 if (S_ISREG(st.st_mode))
661 if (S_ISDIR(st.st_mode))
663 if (S_ISLNK(st.st_mode))
668 enum path_treatment {
674 static enum path_treatment treat_one_path(struct dir_struct *dir,
675 char *path, int *len,
676 const struct path_simplify *simplify,
677 int dtype, struct dirent *de)
679 int exclude = excluded(dir, path, &dtype);
680 if (exclude && (dir->flags & DIR_COLLECT_IGNORED)
681 && in_pathspec(path, *len, simplify))
682 dir_add_ignored(dir, path, *len);
685 * Excluded? If we don't explicitly want to show
686 * ignored files, ignore it
688 if (exclude && !(dir->flags & DIR_SHOW_IGNORED))
691 if (dtype == DT_UNKNOWN)
692 dtype = get_dtype(de, path, *len);
695 * Do we want to see just the ignored files?
696 * We still need to recurse into directories,
697 * even if we don't ignore them, since the
698 * directory may contain files that we do..
700 if (!exclude && (dir->flags & DIR_SHOW_IGNORED)) {
709 memcpy(path + *len, "/", 2);
711 switch (treat_directory(dir, path, *len, simplify)) {
713 if (exclude != !!(dir->flags
717 case recurse_into_directory:
719 case ignore_directory:
730 static enum path_treatment treat_path(struct dir_struct *dir,
732 char *path, int path_max,
734 const struct path_simplify *simplify,
739 if (is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name, ".git"))
741 *len = strlen(de->d_name);
742 /* Ignore overly long pathnames! */
743 if (*len + baselen + 8 > path_max)
745 memcpy(path + baselen, de->d_name, *len + 1);
747 if (simplify_away(path, *len, simplify))
751 return treat_one_path(dir, path, len, simplify, dtype, de);
755 * Read a directory tree. We currently ignore anything but
756 * directories, regular files and symlinks. That's because git
757 * doesn't handle them at all yet. Maybe that will change some
760 * Also, we ignore the name ".git" (even if it is not a directory).
761 * That likely will not change.
763 static int read_directory_recursive(struct dir_struct *dir,
764 const char *base, int baselen,
766 const struct path_simplify *simplify)
768 DIR *fdir = opendir(*base ? base : ".");
773 char path[PATH_MAX + 1];
774 memcpy(path, base, baselen);
776 while ((de = readdir(fdir)) != NULL) {
778 switch (treat_path(dir, de, path, sizeof(path),
779 baselen, simplify, &len)) {
781 contents += read_directory_recursive
782 (dir, path, len, 0, simplify);
793 dir_add_name(dir, path, len);
802 static int cmp_name(const void *p1, const void *p2)
804 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
805 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
807 return cache_name_compare(e1->name, e1->len,
812 * Return the length of the "simple" part of a path match limiter.
814 static int simple_length(const char *match)
819 unsigned char c = *match++;
821 if (c == '\0' || is_glob_special(c))
826 static struct path_simplify *create_simplify(const char **pathspec)
829 struct path_simplify *simplify = NULL;
834 for (nr = 0 ; ; nr++) {
837 alloc = alloc_nr(alloc);
838 simplify = xrealloc(simplify, alloc * sizeof(*simplify));
843 simplify[nr].path = match;
844 simplify[nr].len = simple_length(match);
846 simplify[nr].path = NULL;
847 simplify[nr].len = 0;
851 static void free_simplify(struct path_simplify *simplify)
856 static int treat_leading_path(struct dir_struct *dir,
857 const char *path, int len,
858 const struct path_simplify *simplify)
860 char pathbuf[PATH_MAX];
864 while (len && path[len - 1] == '/')
870 cp = path + baselen + !!baselen;
871 cp = memchr(cp, '/', path + len - cp);
876 memcpy(pathbuf, path, baselen);
877 pathbuf[baselen] = '\0';
878 if (!is_directory(pathbuf))
880 if (simplify_away(pathbuf, baselen, simplify))
883 if (treat_one_path(dir, pathbuf, &blen, simplify,
884 DT_DIR, NULL) == path_ignored)
885 return 0; /* do not recurse into it */
887 return 1; /* finished checking */
891 int read_directory(struct dir_struct *dir, const char *path, int len, const char **pathspec)
893 struct path_simplify *simplify;
895 if (has_symlink_leading_path(path, len))
898 simplify = create_simplify(pathspec);
899 if (!len || treat_leading_path(dir, path, len, simplify))
900 read_directory_recursive(dir, path, len, 0, simplify);
901 free_simplify(simplify);
902 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
903 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
907 int file_exists(const char *f)
910 return lstat(f, &sb) == 0;
914 * get_relative_cwd() gets the prefix of the current working directory
915 * relative to 'dir'. If we are not inside 'dir', it returns NULL.
917 * As a convenience, it also returns NULL if 'dir' is already NULL. The
918 * reason for this behaviour is that it is natural for functions returning
919 * directory names to return NULL to say "this directory does not exist"
920 * or "this directory is invalid". These cases are usually handled the
921 * same as if the cwd is not inside 'dir' at all, so get_relative_cwd()
922 * returns NULL for both of them.
924 * Most notably, get_relative_cwd(buffer, size, get_git_work_tree())
925 * unifies the handling of "outside work tree" with "no work tree at all".
927 char *get_relative_cwd(char *buffer, int size, const char *dir)
933 if (!getcwd(buffer, size))
934 die_errno("can't find the current directory");
936 if (!is_absolute_path(dir))
937 dir = make_absolute_path(dir);
939 while (*dir && *dir == *cwd) {
950 int is_inside_dir(const char *dir)
952 char buffer[PATH_MAX];
953 return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
956 int is_empty_dir(const char *path)
958 DIR *dir = opendir(path);
965 while ((e = readdir(dir)) != NULL)
966 if (!is_dot_or_dotdot(e->d_name)) {
975 int remove_dir_recursively(struct strbuf *path, int flag)
979 int ret = 0, original_len = path->len, len;
980 int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
981 unsigned char submodule_head[20];
983 if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
984 !resolve_gitlink_ref(path->buf, "HEAD", submodule_head))
985 /* Do not descend and nuke a nested git work tree. */
988 dir = opendir(path->buf);
991 if (path->buf[original_len - 1] != '/')
992 strbuf_addch(path, '/');
995 while ((e = readdir(dir)) != NULL) {
997 if (is_dot_or_dotdot(e->d_name))
1000 strbuf_setlen(path, len);
1001 strbuf_addstr(path, e->d_name);
1002 if (lstat(path->buf, &st))
1004 else if (S_ISDIR(st.st_mode)) {
1005 if (!remove_dir_recursively(path, only_empty))
1006 continue; /* happy */
1007 } else if (!only_empty && !unlink(path->buf))
1008 continue; /* happy, too */
1010 /* path too long, stat fails, or non-directory still exists */
1016 strbuf_setlen(path, original_len);
1018 ret = rmdir(path->buf);
1022 void setup_standard_excludes(struct dir_struct *dir)
1026 dir->exclude_per_dir = ".gitignore";
1027 path = git_path("info/exclude");
1028 if (!access(path, R_OK))
1029 add_excludes_from_file(dir, path);
1030 if (excludes_file && !access(excludes_file, R_OK))
1031 add_excludes_from_file(dir, excludes_file);
1034 int remove_path(const char *name)
1038 if (unlink(name) && errno != ENOENT)
1041 slash = strrchr(name, '/');
1043 char *dirs = xstrdup(name);
1044 slash = dirs + (slash - name);
1047 } while (rmdir(dirs) && (slash = strrchr(dirs, '/')));