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 int add_excludes_from_file_1(const char *fname,
207 struct exclude_list *which)
214 fd = open(fname, O_RDONLY);
215 if (fd < 0 || fstat(fd, &st) < 0)
217 size = xsize_t(st.st_size);
222 buf = xmalloc(size+1);
223 if (read_in_full(fd, buf, size) != size)
233 for (i = 0; i <= size; i++) {
234 if (i == size || buf[i] == '\n') {
235 if (entry != buf + i && entry[0] != '#') {
236 buf[i - (i && buf[i-1] == '\r')] = 0;
237 add_exclude(entry, base, baselen, which);
250 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
252 if (add_excludes_from_file_1(fname, "", 0, NULL,
253 &dir->exclude_list[EXC_FILE]) < 0)
254 die("cannot use %s as an exclude file", fname);
257 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
259 struct exclude_list *el;
260 struct exclude_stack *stk = NULL;
263 if ((!dir->exclude_per_dir) ||
264 (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
265 return; /* too long a path -- ignore */
267 /* Pop the ones that are not the prefix of the path being checked. */
268 el = &dir->exclude_list[EXC_DIRS];
269 while ((stk = dir->exclude_stack) != NULL) {
270 if (stk->baselen <= baselen &&
271 !strncmp(dir->basebuf, base, stk->baselen))
273 dir->exclude_stack = stk->prev;
274 while (stk->exclude_ix < el->nr)
275 free(el->excludes[--el->nr]);
280 /* Read from the parent directories and push them down. */
281 current = stk ? stk->baselen : -1;
282 while (current < baselen) {
283 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
291 cp = strchr(base + current + 1, '/');
293 die("oops in prep_exclude");
296 stk->prev = dir->exclude_stack;
297 stk->baselen = cp - base;
298 stk->exclude_ix = el->nr;
299 memcpy(dir->basebuf + current, base + current,
300 stk->baselen - current);
301 strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
302 add_excludes_from_file_1(dir->basebuf,
303 dir->basebuf, stk->baselen,
305 dir->exclude_stack = stk;
306 current = stk->baselen;
308 dir->basebuf[baselen] = '\0';
311 /* Scan the list and let the last match determine the fate.
312 * Return 1 for exclude, 0 for include and -1 for undecided.
314 static int excluded_1(const char *pathname,
315 int pathlen, const char *basename, int *dtype,
316 struct exclude_list *el)
321 for (i = el->nr - 1; 0 <= i; i--) {
322 struct exclude *x = el->excludes[i];
323 const char *exclude = x->pattern;
324 int to_exclude = x->to_exclude;
326 if (x->flags & EXC_FLAG_MUSTBEDIR) {
327 if (*dtype == DT_UNKNOWN)
328 *dtype = get_dtype(NULL, pathname, pathlen);
329 if (*dtype != DT_DIR)
333 if (x->flags & EXC_FLAG_NODIR) {
335 if (x->flags & EXC_FLAG_NOWILDCARD) {
336 if (!strcmp(exclude, basename))
338 } else if (x->flags & EXC_FLAG_ENDSWITH) {
339 if (x->patternlen - 1 <= pathlen &&
340 !strcmp(exclude + 1, pathname + pathlen - x->patternlen + 1))
343 if (fnmatch(exclude, basename, 0) == 0)
348 /* match with FNM_PATHNAME:
349 * exclude has base (baselen long) implicitly
352 int baselen = x->baselen;
356 if (pathlen < baselen ||
357 (baselen && pathname[baselen-1] != '/') ||
358 strncmp(pathname, x->base, baselen))
361 if (x->flags & EXC_FLAG_NOWILDCARD) {
362 if (!strcmp(exclude, pathname + baselen))
365 if (fnmatch(exclude, pathname+baselen,
372 return -1; /* undecided */
375 int excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
377 int pathlen = strlen(pathname);
379 const char *basename = strrchr(pathname, '/');
380 basename = (basename) ? basename+1 : pathname;
382 prep_exclude(dir, pathname, basename-pathname);
383 for (st = EXC_CMDL; st <= EXC_FILE; st++) {
384 switch (excluded_1(pathname, pathlen, basename,
385 dtype_p, &dir->exclude_list[st])) {
395 static struct dir_entry *dir_entry_new(const char *pathname, int len)
397 struct dir_entry *ent;
399 ent = xmalloc(sizeof(*ent) + len + 1);
401 memcpy(ent->name, pathname, len);
406 static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
408 if (cache_name_exists(pathname, len, ignore_case))
411 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
412 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
415 static struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
417 if (!cache_name_is_other(pathname, len))
420 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
421 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
425 index_nonexistent = 0,
431 * The index sorts alphabetically by entry name, which
432 * means that a gitlink sorts as '\0' at the end, while
433 * a directory (which is defined not as an entry, but as
434 * the files it contains) will sort with the '/' at the
437 static enum exist_status directory_exists_in_index(const char *dirname, int len)
439 int pos = cache_name_pos(dirname, len);
442 while (pos < active_nr) {
443 struct cache_entry *ce = active_cache[pos++];
444 unsigned char endchar;
446 if (strncmp(ce->name, dirname, len))
448 endchar = ce->name[len];
452 return index_directory;
453 if (!endchar && S_ISGITLINK(ce->ce_mode))
456 return index_nonexistent;
460 * When we find a directory when traversing the filesystem, we
461 * have three distinct cases:
464 * - see it as a directory
467 * and which one we choose depends on a combination of existing
468 * git index contents and the flags passed into the directory
471 * Case 1: If we *already* have entries in the index under that
472 * directory name, we always recurse into the directory to see
475 * Case 2: If we *already* have that directory name as a gitlink,
476 * we always continue to see it as a gitlink, regardless of whether
477 * there is an actual git directory there or not (it might not
478 * be checked out as a subproject!)
480 * Case 3: if we didn't have it in the index previously, we
481 * have a few sub-cases:
483 * (a) if "show_other_directories" is true, we show it as
484 * just a directory, unless "hide_empty_directories" is
485 * also true and the directory is empty, in which case
486 * we just ignore it entirely.
487 * (b) if it looks like a git directory, and we don't have
488 * 'no_gitlinks' set we treat it as a gitlink, and show it
490 * (c) otherwise, we recurse into it.
492 enum directory_treatment {
495 recurse_into_directory,
498 static enum directory_treatment treat_directory(struct dir_struct *dir,
499 const char *dirname, int len,
500 const struct path_simplify *simplify)
502 /* The "len-1" is to strip the final '/' */
503 switch (directory_exists_in_index(dirname, len-1)) {
504 case index_directory:
505 return recurse_into_directory;
508 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
509 return ignore_directory;
510 return show_directory;
512 case index_nonexistent:
513 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
515 if (!(dir->flags & DIR_NO_GITLINKS)) {
516 unsigned char sha1[20];
517 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
518 return show_directory;
520 return recurse_into_directory;
523 /* This is the "show_other_directories" case */
524 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
525 return show_directory;
526 if (!read_directory_recursive(dir, dirname, len, 1, simplify))
527 return ignore_directory;
528 return show_directory;
532 * This is an inexact early pruning of any recursive directory
533 * reading - if the path cannot possibly be in the pathspec,
534 * return true, and we'll skip it early.
536 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
540 const char *match = simplify->path;
541 int len = simplify->len;
547 if (!memcmp(path, match, len))
556 static int in_pathspec(const char *path, int len, const struct path_simplify *simplify)
559 for (; simplify->path; simplify++) {
560 if (len == simplify->len
561 && !memcmp(path, simplify->path, len))
568 static int get_index_dtype(const char *path, int len)
571 struct cache_entry *ce;
573 ce = cache_name_exists(path, len, 0);
575 if (!ce_uptodate(ce))
577 if (S_ISGITLINK(ce->ce_mode))
580 * Nobody actually cares about the
581 * difference between DT_LNK and DT_REG
586 /* Try to look it up as a directory */
587 pos = cache_name_pos(path, len);
591 while (pos < active_nr) {
592 ce = active_cache[pos++];
593 if (strncmp(ce->name, path, len))
595 if (ce->name[len] > '/')
597 if (ce->name[len] < '/')
599 if (!ce_uptodate(ce))
600 break; /* continue? */
606 static int get_dtype(struct dirent *de, const char *path, int len)
608 int dtype = de ? DTYPE(de) : DT_UNKNOWN;
611 if (dtype != DT_UNKNOWN)
613 dtype = get_index_dtype(path, len);
614 if (dtype != DT_UNKNOWN)
616 if (lstat(path, &st))
618 if (S_ISREG(st.st_mode))
620 if (S_ISDIR(st.st_mode))
622 if (S_ISLNK(st.st_mode))
628 * Read a directory tree. We currently ignore anything but
629 * directories, regular files and symlinks. That's because git
630 * doesn't handle them at all yet. Maybe that will change some
633 * Also, we ignore the name ".git" (even if it is not a directory).
634 * That likely will not change.
636 static int read_directory_recursive(struct dir_struct *dir, const char *base, int baselen, int check_only, const struct path_simplify *simplify)
638 DIR *fdir = opendir(*base ? base : ".");
643 char path[PATH_MAX + 1];
644 memcpy(path, base, baselen);
646 while ((de = readdir(fdir)) != NULL) {
650 if (is_dot_or_dotdot(de->d_name) ||
651 !strcmp(de->d_name, ".git"))
653 len = strlen(de->d_name);
654 /* Ignore overly long pathnames! */
655 if (len + baselen + 8 > sizeof(path))
657 memcpy(path + baselen, de->d_name, len+1);
659 if (simplify_away(path, len, simplify))
663 exclude = excluded(dir, path, &dtype);
664 if (exclude && (dir->flags & DIR_COLLECT_IGNORED)
665 && in_pathspec(path, len, simplify))
666 dir_add_ignored(dir, path,len);
669 * Excluded? If we don't explicitly want to show
670 * ignored files, ignore it
672 if (exclude && !(dir->flags & DIR_SHOW_IGNORED))
675 if (dtype == DT_UNKNOWN)
676 dtype = get_dtype(de, path, len);
679 * Do we want to see just the ignored files?
680 * We still need to recurse into directories,
681 * even if we don't ignore them, since the
682 * directory may contain files that we do..
684 if (!exclude && (dir->flags & DIR_SHOW_IGNORED)) {
693 memcpy(path + len, "/", 2);
695 switch (treat_directory(dir, path, len, simplify)) {
697 if (exclude != !!(dir->flags
701 case recurse_into_directory:
702 contents += read_directory_recursive(dir,
703 path, len, 0, simplify);
705 case ignore_directory:
717 dir_add_name(dir, path, len);
726 static int cmp_name(const void *p1, const void *p2)
728 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
729 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
731 return cache_name_compare(e1->name, e1->len,
736 * Return the length of the "simple" part of a path match limiter.
738 static int simple_length(const char *match)
743 unsigned char c = *match++;
745 if (c == '\0' || is_glob_special(c))
750 static struct path_simplify *create_simplify(const char **pathspec)
753 struct path_simplify *simplify = NULL;
758 for (nr = 0 ; ; nr++) {
761 alloc = alloc_nr(alloc);
762 simplify = xrealloc(simplify, alloc * sizeof(*simplify));
767 simplify[nr].path = match;
768 simplify[nr].len = simple_length(match);
770 simplify[nr].path = NULL;
771 simplify[nr].len = 0;
775 static void free_simplify(struct path_simplify *simplify)
780 int read_directory(struct dir_struct *dir, const char *path, int len, const char **pathspec)
782 struct path_simplify *simplify;
784 if (has_symlink_leading_path(path, len))
787 simplify = create_simplify(pathspec);
788 read_directory_recursive(dir, path, len, 0, simplify);
789 free_simplify(simplify);
790 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
791 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
795 int file_exists(const char *f)
798 return lstat(f, &sb) == 0;
802 * get_relative_cwd() gets the prefix of the current working directory
803 * relative to 'dir'. If we are not inside 'dir', it returns NULL.
805 * As a convenience, it also returns NULL if 'dir' is already NULL. The
806 * reason for this behaviour is that it is natural for functions returning
807 * directory names to return NULL to say "this directory does not exist"
808 * or "this directory is invalid". These cases are usually handled the
809 * same as if the cwd is not inside 'dir' at all, so get_relative_cwd()
810 * returns NULL for both of them.
812 * Most notably, get_relative_cwd(buffer, size, get_git_work_tree())
813 * unifies the handling of "outside work tree" with "no work tree at all".
815 char *get_relative_cwd(char *buffer, int size, const char *dir)
821 if (!getcwd(buffer, size))
822 die_errno("can't find the current directory");
824 if (!is_absolute_path(dir))
825 dir = make_absolute_path(dir);
827 while (*dir && *dir == *cwd) {
838 int is_inside_dir(const char *dir)
840 char buffer[PATH_MAX];
841 return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
844 int is_empty_dir(const char *path)
846 DIR *dir = opendir(path);
853 while ((e = readdir(dir)) != NULL)
854 if (!is_dot_or_dotdot(e->d_name)) {
863 int remove_dir_recursively(struct strbuf *path, int only_empty)
865 DIR *dir = opendir(path->buf);
867 int ret = 0, original_len = path->len, len;
871 if (path->buf[original_len - 1] != '/')
872 strbuf_addch(path, '/');
875 while ((e = readdir(dir)) != NULL) {
877 if (is_dot_or_dotdot(e->d_name))
880 strbuf_setlen(path, len);
881 strbuf_addstr(path, e->d_name);
882 if (lstat(path->buf, &st))
884 else if (S_ISDIR(st.st_mode)) {
885 if (!remove_dir_recursively(path, only_empty))
886 continue; /* happy */
887 } else if (!only_empty && !unlink(path->buf))
888 continue; /* happy, too */
890 /* path too long, stat fails, or non-directory still exists */
896 strbuf_setlen(path, original_len);
898 ret = rmdir(path->buf);
902 void setup_standard_excludes(struct dir_struct *dir)
906 dir->exclude_per_dir = ".gitignore";
907 path = git_path("info/exclude");
908 if (!access(path, R_OK))
909 add_excludes_from_file(dir, path);
910 if (excludes_file && !access(excludes_file, R_OK))
911 add_excludes_from_file(dir, excludes_file);
914 int remove_path(const char *name)
918 if (unlink(name) && errno != ENOENT)
921 slash = strrchr(name, '/');
923 char *dirs = xstrdup(name);
924 slash = dirs + (slash - name);
927 } while (rmdir(dirs) && (slash = strrchr(dirs, '/')));