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,
18 const char *path, const char *base, int baselen,
19 int check_only, const struct path_simplify *simplify);
20 static int get_dtype(struct dirent *de, const char *path);
22 int common_prefix(const char **pathspec)
24 const char *path, *slash, *next;
31 slash = strrchr(path, '/');
35 prefix = slash - path + 1;
36 while ((next = *++pathspec) != NULL) {
37 int len = strlen(next);
38 if (len >= prefix && !memcmp(path, next, prefix))
44 if (next[--len] != '/')
46 if (memcmp(path, next, len+1))
56 * Does 'match' matches the given name?
59 * (1) the 'match' string is leading directory of 'name', or
60 * (2) the 'match' string is a wildcard and matches 'name', or
61 * (3) the 'match' string is exactly the same as 'name'.
63 * and the return value tells which case it was.
65 * It returns 0 when there is no match.
67 static int match_one(const char *match, const char *name, int namelen)
71 /* If the match was just the prefix, we matched */
73 return MATCHED_RECURSIVELY;
76 unsigned char c1 = *match;
77 unsigned char c2 = *name;
78 if (c1 == '\0' || is_glob_special(c1))
89 * If we don't match the matchstring exactly,
90 * we need to match by fnmatch
92 matchlen = strlen(match);
93 if (strncmp(match, name, matchlen))
94 return !fnmatch(match, name, 0) ? MATCHED_FNMATCH : 0;
96 if (namelen == matchlen)
97 return MATCHED_EXACTLY;
98 if (match[matchlen-1] == '/' || name[matchlen] == '/')
99 return MATCHED_RECURSIVELY;
104 * Given a name and a list of pathspecs, see if the name matches
105 * any of the pathspecs. The caller is also interested in seeing
106 * all pathspec matches some names it calls this function with
107 * (otherwise the user could have mistyped the unmatched pathspec),
108 * and a mark is left in seen[] array for pathspec element that
109 * actually matched anything.
111 int match_pathspec(const char **pathspec, const char *name, int namelen,
112 int prefix, char *seen)
122 for (i = 0; pathspec[i] != NULL; i++) {
124 const char *match = pathspec[i] + prefix;
125 if (seen && seen[i] == MATCHED_EXACTLY)
127 how = match_one(match, name, namelen);
131 if (seen && seen[i] < how)
138 static int no_wildcard(const char *string)
140 return string[strcspn(string, "*?[{\\")] == '\0';
143 void add_exclude(const char *string, const char *base,
144 int baselen, struct exclude_list *which)
151 if (*string == '!') {
155 len = strlen(string);
156 if (len && string[len - 1] == '/') {
158 x = xmalloc(sizeof(*x) + len);
160 memcpy(s, string, len - 1);
164 flags = EXC_FLAG_MUSTBEDIR;
166 x = xmalloc(sizeof(*x));
169 x->to_exclude = to_exclude;
170 x->patternlen = strlen(string);
172 x->baselen = baselen;
174 if (!strchr(string, '/'))
175 x->flags |= EXC_FLAG_NODIR;
176 if (no_wildcard(string))
177 x->flags |= EXC_FLAG_NOWILDCARD;
178 if (*string == '*' && no_wildcard(string+1))
179 x->flags |= EXC_FLAG_ENDSWITH;
180 ALLOC_GROW(which->excludes, which->nr + 1, which->alloc);
181 which->excludes[which->nr++] = x;
184 static int add_excludes_from_file_1(const char *fname,
188 struct exclude_list *which)
195 fd = open(fname, O_RDONLY);
196 if (fd < 0 || fstat(fd, &st) < 0)
198 size = xsize_t(st.st_size);
203 buf = xmalloc(size+1);
204 if (read_in_full(fd, buf, size) != size)
215 for (i = 0; i < size; i++) {
216 if (buf[i] == '\n') {
217 if (entry != buf + i && entry[0] != '#') {
218 buf[i - (i && buf[i-1] == '\r')] = 0;
219 add_exclude(entry, base, baselen, which);
232 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
234 if (add_excludes_from_file_1(fname, "", 0, NULL,
235 &dir->exclude_list[EXC_FILE]) < 0)
236 die("cannot use %s as an exclude file", fname);
239 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
241 struct exclude_list *el;
242 struct exclude_stack *stk = NULL;
245 if ((!dir->exclude_per_dir) ||
246 (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
247 return; /* too long a path -- ignore */
249 /* Pop the ones that are not the prefix of the path being checked. */
250 el = &dir->exclude_list[EXC_DIRS];
251 while ((stk = dir->exclude_stack) != NULL) {
252 if (stk->baselen <= baselen &&
253 !strncmp(dir->basebuf, base, stk->baselen))
255 dir->exclude_stack = stk->prev;
256 while (stk->exclude_ix < el->nr)
257 free(el->excludes[--el->nr]);
262 /* Read from the parent directories and push them down. */
263 current = stk ? stk->baselen : -1;
264 while (current < baselen) {
265 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
273 cp = strchr(base + current + 1, '/');
275 die("oops in prep_exclude");
278 stk->prev = dir->exclude_stack;
279 stk->baselen = cp - base;
280 stk->exclude_ix = el->nr;
281 memcpy(dir->basebuf + current, base + current,
282 stk->baselen - current);
283 strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
284 add_excludes_from_file_1(dir->basebuf,
285 dir->basebuf, stk->baselen,
287 dir->exclude_stack = stk;
288 current = stk->baselen;
290 dir->basebuf[baselen] = '\0';
293 /* Scan the list and let the last match determines the fate.
294 * Return 1 for exclude, 0 for include and -1 for undecided.
296 static int excluded_1(const char *pathname,
297 int pathlen, const char *basename, int *dtype,
298 struct exclude_list *el)
303 for (i = el->nr - 1; 0 <= i; i--) {
304 struct exclude *x = el->excludes[i];
305 const char *exclude = x->pattern;
306 int to_exclude = x->to_exclude;
308 if (x->flags & EXC_FLAG_MUSTBEDIR) {
309 if (*dtype == DT_UNKNOWN)
310 *dtype = get_dtype(NULL, pathname);
311 if (*dtype != DT_DIR)
315 if (x->flags & EXC_FLAG_NODIR) {
317 if (x->flags & EXC_FLAG_NOWILDCARD) {
318 if (!strcmp(exclude, basename))
320 } else if (x->flags & EXC_FLAG_ENDSWITH) {
321 if (x->patternlen - 1 <= pathlen &&
322 !strcmp(exclude + 1, pathname + pathlen - x->patternlen + 1))
325 if (fnmatch(exclude, basename, 0) == 0)
330 /* match with FNM_PATHNAME:
331 * exclude has base (baselen long) implicitly
334 int baselen = x->baselen;
338 if (pathlen < baselen ||
339 (baselen && pathname[baselen-1] != '/') ||
340 strncmp(pathname, x->base, baselen))
343 if (x->flags & EXC_FLAG_NOWILDCARD) {
344 if (!strcmp(exclude, pathname + baselen))
347 if (fnmatch(exclude, pathname+baselen,
354 return -1; /* undecided */
357 int excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
359 int pathlen = strlen(pathname);
361 const char *basename = strrchr(pathname, '/');
362 basename = (basename) ? basename+1 : pathname;
364 prep_exclude(dir, pathname, basename-pathname);
365 for (st = EXC_CMDL; st <= EXC_FILE; st++) {
366 switch (excluded_1(pathname, pathlen, basename,
367 dtype_p, &dir->exclude_list[st])) {
377 static struct dir_entry *dir_entry_new(const char *pathname, int len)
379 struct dir_entry *ent;
381 ent = xmalloc(sizeof(*ent) + len + 1);
383 memcpy(ent->name, pathname, len);
388 static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
390 if (cache_name_exists(pathname, len, ignore_case))
393 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
394 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
397 static struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
399 if (cache_name_pos(pathname, len) >= 0)
402 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
403 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
407 index_nonexistent = 0,
413 * The index sorts alphabetically by entry name, which
414 * means that a gitlink sorts as '\0' at the end, while
415 * a directory (which is defined not as an entry, but as
416 * the files it contains) will sort with the '/' at the
419 static enum exist_status directory_exists_in_index(const char *dirname, int len)
421 int pos = cache_name_pos(dirname, len);
424 while (pos < active_nr) {
425 struct cache_entry *ce = active_cache[pos++];
426 unsigned char endchar;
428 if (strncmp(ce->name, dirname, len))
430 endchar = ce->name[len];
434 return index_directory;
435 if (!endchar && S_ISGITLINK(ce->ce_mode))
438 return index_nonexistent;
442 * When we find a directory when traversing the filesystem, we
443 * have three distinct cases:
446 * - see it as a directory
449 * and which one we choose depends on a combination of existing
450 * git index contents and the flags passed into the directory
453 * Case 1: If we *already* have entries in the index under that
454 * directory name, we always recurse into the directory to see
457 * Case 2: If we *already* have that directory name as a gitlink,
458 * we always continue to see it as a gitlink, regardless of whether
459 * there is an actual git directory there or not (it might not
460 * be checked out as a subproject!)
462 * Case 3: if we didn't have it in the index previously, we
463 * have a few sub-cases:
465 * (a) if "show_other_directories" is true, we show it as
466 * just a directory, unless "hide_empty_directories" is
467 * also true and the directory is empty, in which case
468 * we just ignore it entirely.
469 * (b) if it looks like a git directory, and we don't have
470 * 'no_gitlinks' set we treat it as a gitlink, and show it
472 * (c) otherwise, we recurse into it.
474 enum directory_treatment {
477 recurse_into_directory,
480 static enum directory_treatment treat_directory(struct dir_struct *dir,
481 const char *dirname, int len,
482 const struct path_simplify *simplify)
484 /* The "len-1" is to strip the final '/' */
485 switch (directory_exists_in_index(dirname, len-1)) {
486 case index_directory:
487 return recurse_into_directory;
490 if (dir->show_other_directories)
491 return ignore_directory;
492 return show_directory;
494 case index_nonexistent:
495 if (dir->show_other_directories)
497 if (!dir->no_gitlinks) {
498 unsigned char sha1[20];
499 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
500 return show_directory;
502 return recurse_into_directory;
505 /* This is the "show_other_directories" case */
506 if (!dir->hide_empty_directories)
507 return show_directory;
508 if (!read_directory_recursive(dir, dirname, dirname, len, 1, simplify))
509 return ignore_directory;
510 return show_directory;
514 * This is an inexact early pruning of any recursive directory
515 * reading - if the path cannot possibly be in the pathspec,
516 * return true, and we'll skip it early.
518 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
522 const char *match = simplify->path;
523 int len = simplify->len;
529 if (!memcmp(path, match, len))
538 static int in_pathspec(const char *path, int len, const struct path_simplify *simplify)
541 for (; simplify->path; simplify++) {
542 if (len == simplify->len
543 && !memcmp(path, simplify->path, len))
550 static int get_dtype(struct dirent *de, const char *path)
552 int dtype = de ? DTYPE(de) : DT_UNKNOWN;
555 if (dtype != DT_UNKNOWN)
557 if (lstat(path, &st))
559 if (S_ISREG(st.st_mode))
561 if (S_ISDIR(st.st_mode))
563 if (S_ISLNK(st.st_mode))
569 * Read a directory tree. We currently ignore anything but
570 * directories, regular files and symlinks. That's because git
571 * doesn't handle them at all yet. Maybe that will change some
574 * Also, we ignore the name ".git" (even if it is not a directory).
575 * That likely will not change.
577 static int read_directory_recursive(struct dir_struct *dir, const char *path, const char *base, int baselen, int check_only, const struct path_simplify *simplify)
579 DIR *fdir = opendir(path);
584 char fullname[PATH_MAX + 1];
585 memcpy(fullname, base, baselen);
587 while ((de = readdir(fdir)) != NULL) {
591 if (is_dot_or_dotdot(de->d_name) ||
592 !strcmp(de->d_name, ".git"))
594 len = strlen(de->d_name);
595 /* Ignore overly long pathnames! */
596 if (len + baselen + 8 > sizeof(fullname))
598 memcpy(fullname + baselen, de->d_name, len+1);
599 if (simplify_away(fullname, baselen + len, simplify))
603 exclude = excluded(dir, fullname, &dtype);
604 if (exclude && dir->collect_ignored
605 && in_pathspec(fullname, baselen + len, simplify))
606 dir_add_ignored(dir, fullname, baselen + len);
609 * Excluded? If we don't explicitly want to show
610 * ignored files, ignore it
612 if (exclude && !dir->show_ignored)
615 if (dtype == DT_UNKNOWN)
616 dtype = get_dtype(de, fullname);
619 * Do we want to see just the ignored files?
620 * We still need to recurse into directories,
621 * even if we don't ignore them, since the
622 * directory may contain files that we do..
624 if (!exclude && dir->show_ignored) {
633 memcpy(fullname + baselen + len, "/", 2);
635 switch (treat_directory(dir, fullname, baselen + len, simplify)) {
637 if (exclude != dir->show_ignored)
640 case recurse_into_directory:
641 contents += read_directory_recursive(dir,
642 fullname, fullname, baselen + len, 0, simplify);
644 case ignore_directory:
656 dir_add_name(dir, fullname, baselen + len);
665 static int cmp_name(const void *p1, const void *p2)
667 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
668 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
670 return cache_name_compare(e1->name, e1->len,
675 * Return the length of the "simple" part of a path match limiter.
677 static int simple_length(const char *match)
682 unsigned char c = *match++;
684 if (c == '\0' || is_glob_special(c))
689 static struct path_simplify *create_simplify(const char **pathspec)
692 struct path_simplify *simplify = NULL;
697 for (nr = 0 ; ; nr++) {
700 alloc = alloc_nr(alloc);
701 simplify = xrealloc(simplify, alloc * sizeof(*simplify));
706 simplify[nr].path = match;
707 simplify[nr].len = simple_length(match);
709 simplify[nr].path = NULL;
710 simplify[nr].len = 0;
714 static void free_simplify(struct path_simplify *simplify)
719 int read_directory(struct dir_struct *dir, const char *path, const char *base, int baselen, const char **pathspec)
721 struct path_simplify *simplify;
723 if (has_symlink_leading_path(strlen(path), path))
726 simplify = create_simplify(pathspec);
727 read_directory_recursive(dir, path, base, baselen, 0, simplify);
728 free_simplify(simplify);
729 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
730 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
734 int file_exists(const char *f)
737 return lstat(f, &sb) == 0;
741 * get_relative_cwd() gets the prefix of the current working directory
742 * relative to 'dir'. If we are not inside 'dir', it returns NULL.
744 * As a convenience, it also returns NULL if 'dir' is already NULL. The
745 * reason for this behaviour is that it is natural for functions returning
746 * directory names to return NULL to say "this directory does not exist"
747 * or "this directory is invalid". These cases are usually handled the
748 * same as if the cwd is not inside 'dir' at all, so get_relative_cwd()
749 * returns NULL for both of them.
751 * Most notably, get_relative_cwd(buffer, size, get_git_work_tree())
752 * unifies the handling of "outside work tree" with "no work tree at all".
754 char *get_relative_cwd(char *buffer, int size, const char *dir)
760 if (!getcwd(buffer, size))
761 die("can't find the current directory: %s", strerror(errno));
763 if (!is_absolute_path(dir))
764 dir = make_absolute_path(dir);
766 while (*dir && *dir == *cwd) {
777 int is_inside_dir(const char *dir)
779 char buffer[PATH_MAX];
780 return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
783 int is_empty_dir(const char *path)
785 DIR *dir = opendir(path);
792 while ((e = readdir(dir)) != NULL)
793 if (!is_dot_or_dotdot(e->d_name)) {
802 int remove_dir_recursively(struct strbuf *path, int only_empty)
804 DIR *dir = opendir(path->buf);
806 int ret = 0, original_len = path->len, len;
810 if (path->buf[original_len - 1] != '/')
811 strbuf_addch(path, '/');
814 while ((e = readdir(dir)) != NULL) {
816 if (is_dot_or_dotdot(e->d_name))
819 strbuf_setlen(path, len);
820 strbuf_addstr(path, e->d_name);
821 if (lstat(path->buf, &st))
823 else if (S_ISDIR(st.st_mode)) {
824 if (!remove_dir_recursively(path, only_empty))
825 continue; /* happy */
826 } else if (!only_empty && !unlink(path->buf))
827 continue; /* happy, too */
829 /* path too long, stat fails, or non-directory still exists */
835 strbuf_setlen(path, original_len);
837 ret = rmdir(path->buf);
841 void setup_standard_excludes(struct dir_struct *dir)
845 dir->exclude_per_dir = ".gitignore";
846 path = git_path("info/exclude");
847 if (!access(path, R_OK))
848 add_excludes_from_file(dir, path);
849 if (excludes_file && !access(excludes_file, R_OK))
850 add_excludes_from_file(dir, excludes_file);
853 int remove_path(const char *name)
857 if (unlink(name) && errno != ENOENT)
860 slash = strrchr(name, '/');
862 char *dirs = xstrdup(name);
863 slash = dirs + (slash - name);
866 } while (rmdir(dirs) && (slash = strrchr(dirs, '/')));