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 static int add_excludes_from_file_1(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)
247 size = xsize_t(st.st_size);
253 if (read_in_full(fd, buf, size) != size) {
263 for (i = 0; i <= size; i++) {
264 if (i == size || buf[i] == '\n') {
265 if (entry != buf + i && entry[0] != '#') {
266 buf[i - (i && buf[i-1] == '\r')] = 0;
267 add_exclude(entry, base, baselen, which);
275 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
277 if (add_excludes_from_file_1(fname, "", 0, NULL,
278 &dir->exclude_list[EXC_FILE], 0) < 0)
279 die("cannot use %s as an exclude file", fname);
282 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
284 struct exclude_list *el;
285 struct exclude_stack *stk = NULL;
288 if ((!dir->exclude_per_dir) ||
289 (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
290 return; /* too long a path -- ignore */
292 /* Pop the ones that are not the prefix of the path being checked. */
293 el = &dir->exclude_list[EXC_DIRS];
294 while ((stk = dir->exclude_stack) != NULL) {
295 if (stk->baselen <= baselen &&
296 !strncmp(dir->basebuf, base, stk->baselen))
298 dir->exclude_stack = stk->prev;
299 while (stk->exclude_ix < el->nr)
300 free(el->excludes[--el->nr]);
305 /* Read from the parent directories and push them down. */
306 current = stk ? stk->baselen : -1;
307 while (current < baselen) {
308 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
316 cp = strchr(base + current + 1, '/');
318 die("oops in prep_exclude");
321 stk->prev = dir->exclude_stack;
322 stk->baselen = cp - base;
323 stk->exclude_ix = el->nr;
324 memcpy(dir->basebuf + current, base + current,
325 stk->baselen - current);
326 strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
327 add_excludes_from_file_1(dir->basebuf,
328 dir->basebuf, stk->baselen,
329 &stk->filebuf, el, 1);
330 dir->exclude_stack = stk;
331 current = stk->baselen;
333 dir->basebuf[baselen] = '\0';
336 /* Scan the list and let the last match determine the fate.
337 * Return 1 for exclude, 0 for include and -1 for undecided.
339 static int excluded_1(const char *pathname,
340 int pathlen, const char *basename, int *dtype,
341 struct exclude_list *el)
346 for (i = el->nr - 1; 0 <= i; i--) {
347 struct exclude *x = el->excludes[i];
348 const char *exclude = x->pattern;
349 int to_exclude = x->to_exclude;
351 if (x->flags & EXC_FLAG_MUSTBEDIR) {
352 if (*dtype == DT_UNKNOWN)
353 *dtype = get_dtype(NULL, pathname, pathlen);
354 if (*dtype != DT_DIR)
358 if (x->flags & EXC_FLAG_NODIR) {
360 if (x->flags & EXC_FLAG_NOWILDCARD) {
361 if (!strcmp(exclude, basename))
363 } else if (x->flags & EXC_FLAG_ENDSWITH) {
364 if (x->patternlen - 1 <= pathlen &&
365 !strcmp(exclude + 1, pathname + pathlen - x->patternlen + 1))
368 if (fnmatch(exclude, basename, 0) == 0)
373 /* match with FNM_PATHNAME:
374 * exclude has base (baselen long) implicitly
377 int baselen = x->baselen;
381 if (pathlen < baselen ||
382 (baselen && pathname[baselen-1] != '/') ||
383 strncmp(pathname, x->base, baselen))
386 if (x->flags & EXC_FLAG_NOWILDCARD) {
387 if (!strcmp(exclude, pathname + baselen))
390 if (fnmatch(exclude, pathname+baselen,
397 return -1; /* undecided */
400 int excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
402 int pathlen = strlen(pathname);
404 const char *basename = strrchr(pathname, '/');
405 basename = (basename) ? basename+1 : pathname;
407 prep_exclude(dir, pathname, basename-pathname);
408 for (st = EXC_CMDL; st <= EXC_FILE; st++) {
409 switch (excluded_1(pathname, pathlen, basename,
410 dtype_p, &dir->exclude_list[st])) {
420 static struct dir_entry *dir_entry_new(const char *pathname, int len)
422 struct dir_entry *ent;
424 ent = xmalloc(sizeof(*ent) + len + 1);
426 memcpy(ent->name, pathname, len);
431 static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
433 if (cache_name_exists(pathname, len, ignore_case))
436 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
437 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
440 static struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
442 if (!cache_name_is_other(pathname, len))
445 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
446 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
450 index_nonexistent = 0,
456 * The index sorts alphabetically by entry name, which
457 * means that a gitlink sorts as '\0' at the end, while
458 * a directory (which is defined not as an entry, but as
459 * the files it contains) will sort with the '/' at the
462 static enum exist_status directory_exists_in_index(const char *dirname, int len)
464 int pos = cache_name_pos(dirname, len);
467 while (pos < active_nr) {
468 struct cache_entry *ce = active_cache[pos++];
469 unsigned char endchar;
471 if (strncmp(ce->name, dirname, len))
473 endchar = ce->name[len];
477 return index_directory;
478 if (!endchar && S_ISGITLINK(ce->ce_mode))
481 return index_nonexistent;
485 * When we find a directory when traversing the filesystem, we
486 * have three distinct cases:
489 * - see it as a directory
492 * and which one we choose depends on a combination of existing
493 * git index contents and the flags passed into the directory
496 * Case 1: If we *already* have entries in the index under that
497 * directory name, we always recurse into the directory to see
500 * Case 2: If we *already* have that directory name as a gitlink,
501 * we always continue to see it as a gitlink, regardless of whether
502 * there is an actual git directory there or not (it might not
503 * be checked out as a subproject!)
505 * Case 3: if we didn't have it in the index previously, we
506 * have a few sub-cases:
508 * (a) if "show_other_directories" is true, we show it as
509 * just a directory, unless "hide_empty_directories" is
510 * also true and the directory is empty, in which case
511 * we just ignore it entirely.
512 * (b) if it looks like a git directory, and we don't have
513 * 'no_gitlinks' set we treat it as a gitlink, and show it
515 * (c) otherwise, we recurse into it.
517 enum directory_treatment {
520 recurse_into_directory,
523 static enum directory_treatment treat_directory(struct dir_struct *dir,
524 const char *dirname, int len,
525 const struct path_simplify *simplify)
527 /* The "len-1" is to strip the final '/' */
528 switch (directory_exists_in_index(dirname, len-1)) {
529 case index_directory:
530 return recurse_into_directory;
533 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
534 return ignore_directory;
535 return show_directory;
537 case index_nonexistent:
538 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
540 if (!(dir->flags & DIR_NO_GITLINKS)) {
541 unsigned char sha1[20];
542 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
543 return show_directory;
545 return recurse_into_directory;
548 /* This is the "show_other_directories" case */
549 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
550 return show_directory;
551 if (!read_directory_recursive(dir, dirname, len, 1, simplify))
552 return ignore_directory;
553 return show_directory;
557 * This is an inexact early pruning of any recursive directory
558 * reading - if the path cannot possibly be in the pathspec,
559 * return true, and we'll skip it early.
561 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
565 const char *match = simplify->path;
566 int len = simplify->len;
572 if (!memcmp(path, match, len))
581 static int in_pathspec(const char *path, int len, const struct path_simplify *simplify)
584 for (; simplify->path; simplify++) {
585 if (len == simplify->len
586 && !memcmp(path, simplify->path, len))
593 static int get_index_dtype(const char *path, int len)
596 struct cache_entry *ce;
598 ce = cache_name_exists(path, len, 0);
600 if (!ce_uptodate(ce))
602 if (S_ISGITLINK(ce->ce_mode))
605 * Nobody actually cares about the
606 * difference between DT_LNK and DT_REG
611 /* Try to look it up as a directory */
612 pos = cache_name_pos(path, len);
616 while (pos < active_nr) {
617 ce = active_cache[pos++];
618 if (strncmp(ce->name, path, len))
620 if (ce->name[len] > '/')
622 if (ce->name[len] < '/')
624 if (!ce_uptodate(ce))
625 break; /* continue? */
631 static int get_dtype(struct dirent *de, const char *path, int len)
633 int dtype = de ? DTYPE(de) : DT_UNKNOWN;
636 if (dtype != DT_UNKNOWN)
638 dtype = get_index_dtype(path, len);
639 if (dtype != DT_UNKNOWN)
641 if (lstat(path, &st))
643 if (S_ISREG(st.st_mode))
645 if (S_ISDIR(st.st_mode))
647 if (S_ISLNK(st.st_mode))
653 * Read a directory tree. We currently ignore anything but
654 * directories, regular files and symlinks. That's because git
655 * doesn't handle them at all yet. Maybe that will change some
658 * Also, we ignore the name ".git" (even if it is not a directory).
659 * That likely will not change.
661 static int read_directory_recursive(struct dir_struct *dir, const char *base, int baselen, int check_only, const struct path_simplify *simplify)
663 DIR *fdir = opendir(*base ? base : ".");
668 char path[PATH_MAX + 1];
669 memcpy(path, base, baselen);
671 while ((de = readdir(fdir)) != NULL) {
675 if (is_dot_or_dotdot(de->d_name) ||
676 !strcmp(de->d_name, ".git"))
678 len = strlen(de->d_name);
679 /* Ignore overly long pathnames! */
680 if (len + baselen + 8 > sizeof(path))
682 memcpy(path + baselen, de->d_name, len+1);
684 if (simplify_away(path, len, simplify))
688 exclude = excluded(dir, path, &dtype);
689 if (exclude && (dir->flags & DIR_COLLECT_IGNORED)
690 && in_pathspec(path, len, simplify))
691 dir_add_ignored(dir, path,len);
694 * Excluded? If we don't explicitly want to show
695 * ignored files, ignore it
697 if (exclude && !(dir->flags & DIR_SHOW_IGNORED))
700 if (dtype == DT_UNKNOWN)
701 dtype = get_dtype(de, path, len);
704 * Do we want to see just the ignored files?
705 * We still need to recurse into directories,
706 * even if we don't ignore them, since the
707 * directory may contain files that we do..
709 if (!exclude && (dir->flags & DIR_SHOW_IGNORED)) {
718 memcpy(path + len, "/", 2);
720 switch (treat_directory(dir, path, len, simplify)) {
722 if (exclude != !!(dir->flags
726 case recurse_into_directory:
727 contents += read_directory_recursive(dir,
728 path, len, 0, simplify);
730 case ignore_directory:
742 dir_add_name(dir, path, len);
751 static int cmp_name(const void *p1, const void *p2)
753 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
754 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
756 return cache_name_compare(e1->name, e1->len,
761 * Return the length of the "simple" part of a path match limiter.
763 static int simple_length(const char *match)
768 unsigned char c = *match++;
770 if (c == '\0' || is_glob_special(c))
775 static struct path_simplify *create_simplify(const char **pathspec)
778 struct path_simplify *simplify = NULL;
783 for (nr = 0 ; ; nr++) {
786 alloc = alloc_nr(alloc);
787 simplify = xrealloc(simplify, alloc * sizeof(*simplify));
792 simplify[nr].path = match;
793 simplify[nr].len = simple_length(match);
795 simplify[nr].path = NULL;
796 simplify[nr].len = 0;
800 static void free_simplify(struct path_simplify *simplify)
805 int read_directory(struct dir_struct *dir, const char *path, int len, const char **pathspec)
807 struct path_simplify *simplify;
809 if (has_symlink_leading_path(path, len))
812 simplify = create_simplify(pathspec);
813 read_directory_recursive(dir, path, len, 0, simplify);
814 free_simplify(simplify);
815 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
816 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
820 int file_exists(const char *f)
823 return lstat(f, &sb) == 0;
827 * get_relative_cwd() gets the prefix of the current working directory
828 * relative to 'dir'. If we are not inside 'dir', it returns NULL.
830 * As a convenience, it also returns NULL if 'dir' is already NULL. The
831 * reason for this behaviour is that it is natural for functions returning
832 * directory names to return NULL to say "this directory does not exist"
833 * or "this directory is invalid". These cases are usually handled the
834 * same as if the cwd is not inside 'dir' at all, so get_relative_cwd()
835 * returns NULL for both of them.
837 * Most notably, get_relative_cwd(buffer, size, get_git_work_tree())
838 * unifies the handling of "outside work tree" with "no work tree at all".
840 char *get_relative_cwd(char *buffer, int size, const char *dir)
846 if (!getcwd(buffer, size))
847 die_errno("can't find the current directory");
849 if (!is_absolute_path(dir))
850 dir = make_absolute_path(dir);
852 while (*dir && *dir == *cwd) {
863 int is_inside_dir(const char *dir)
865 char buffer[PATH_MAX];
866 return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
869 int is_empty_dir(const char *path)
871 DIR *dir = opendir(path);
878 while ((e = readdir(dir)) != NULL)
879 if (!is_dot_or_dotdot(e->d_name)) {
888 int remove_dir_recursively(struct strbuf *path, int only_empty)
890 DIR *dir = opendir(path->buf);
892 int ret = 0, original_len = path->len, len;
896 if (path->buf[original_len - 1] != '/')
897 strbuf_addch(path, '/');
900 while ((e = readdir(dir)) != NULL) {
902 if (is_dot_or_dotdot(e->d_name))
905 strbuf_setlen(path, len);
906 strbuf_addstr(path, e->d_name);
907 if (lstat(path->buf, &st))
909 else if (S_ISDIR(st.st_mode)) {
910 if (!remove_dir_recursively(path, only_empty))
911 continue; /* happy */
912 } else if (!only_empty && !unlink(path->buf))
913 continue; /* happy, too */
915 /* path too long, stat fails, or non-directory still exists */
921 strbuf_setlen(path, original_len);
923 ret = rmdir(path->buf);
927 void setup_standard_excludes(struct dir_struct *dir)
931 dir->exclude_per_dir = ".gitignore";
932 path = git_path("info/exclude");
933 if (!access(path, R_OK))
934 add_excludes_from_file(dir, path);
935 if (excludes_file && !access(excludes_file, R_OK))
936 add_excludes_from_file(dir, excludes_file);
939 int remove_path(const char *name)
943 if (unlink(name) && errno != ENOENT)
946 slash = strrchr(name, '/');
948 char *dirs = xstrdup(name);
949 slash = dirs + (slash - name);
952 } while (rmdir(dirs) && (slash = strrchr(dirs, '/')));