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);
21 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))
55 * Does 'match' matches the given name?
58 * (1) the 'match' string is leading directory of 'name', or
59 * (2) the 'match' string is a wildcard and matches 'name', or
60 * (3) the 'match' string is exactly the same as 'name'.
62 * and the return value tells which case it was.
64 * It returns 0 when there is no match.
66 static int match_one(const char *match, const char *name, int namelen)
70 /* If the match was just the prefix, we matched */
71 matchlen = strlen(match);
73 return MATCHED_RECURSIVELY;
76 * If we don't match the matchstring exactly,
77 * we need to match by fnmatch
79 if (strncmp(match, name, matchlen))
80 return !fnmatch(match, name, 0) ? MATCHED_FNMATCH : 0;
83 return MATCHED_EXACTLY;
84 if (match[matchlen-1] == '/' || name[matchlen] == '/')
85 return MATCHED_RECURSIVELY;
90 * Given a name and a list of pathspecs, see if the name matches
91 * any of the pathspecs. The caller is also interested in seeing
92 * all pathspec matches some names it calls this function with
93 * (otherwise the user could have mistyped the unmatched pathspec),
94 * and a mark is left in seen[] array for pathspec element that
95 * actually matched anything.
97 int match_pathspec(const char **pathspec, const char *name, int namelen, int prefix, char *seen)
105 for (retval = 0; (match = *pathspec++) != NULL; seen++) {
107 if (retval && *seen == MATCHED_EXACTLY)
110 how = match_one(match, name, namelen);
121 static int no_wildcard(const char *string)
123 return string[strcspn(string, "*?[{")] == '\0';
126 void add_exclude(const char *string, const char *base,
127 int baselen, struct exclude_list *which)
134 if (*string == '!') {
138 len = strlen(string);
139 if (len && string[len - 1] == '/') {
141 x = xmalloc(sizeof(*x) + len);
143 memcpy(s, string, len - 1);
147 flags = EXC_FLAG_MUSTBEDIR;
149 x = xmalloc(sizeof(*x));
152 x->to_exclude = to_exclude;
153 x->patternlen = strlen(string);
155 x->baselen = baselen;
157 if (!strchr(string, '/'))
158 x->flags |= EXC_FLAG_NODIR;
159 if (no_wildcard(string))
160 x->flags |= EXC_FLAG_NOWILDCARD;
161 if (*string == '*' && no_wildcard(string+1))
162 x->flags |= EXC_FLAG_ENDSWITH;
163 ALLOC_GROW(which->excludes, which->nr + 1, which->alloc);
164 which->excludes[which->nr++] = x;
167 static int add_excludes_from_file_1(const char *fname,
171 struct exclude_list *which)
178 fd = open(fname, O_RDONLY);
179 if (fd < 0 || fstat(fd, &st) < 0)
181 size = xsize_t(st.st_size);
186 buf = xmalloc(size+1);
187 if (read_in_full(fd, buf, size) != size)
198 for (i = 0; i < size; i++) {
199 if (buf[i] == '\n') {
200 if (entry != buf + i && entry[0] != '#') {
201 buf[i - (i && buf[i-1] == '\r')] = 0;
202 add_exclude(entry, base, baselen, which);
215 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
217 if (add_excludes_from_file_1(fname, "", 0, NULL,
218 &dir->exclude_list[EXC_FILE]) < 0)
219 die("cannot use %s as an exclude file", fname);
222 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
224 struct exclude_list *el;
225 struct exclude_stack *stk = NULL;
228 if ((!dir->exclude_per_dir) ||
229 (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
230 return; /* too long a path -- ignore */
232 /* Pop the ones that are not the prefix of the path being checked. */
233 el = &dir->exclude_list[EXC_DIRS];
234 while ((stk = dir->exclude_stack) != NULL) {
235 if (stk->baselen <= baselen &&
236 !strncmp(dir->basebuf, base, stk->baselen))
238 dir->exclude_stack = stk->prev;
239 while (stk->exclude_ix < el->nr)
240 free(el->excludes[--el->nr]);
245 /* Read from the parent directories and push them down. */
246 current = stk ? stk->baselen : -1;
247 while (current < baselen) {
248 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
256 cp = strchr(base + current + 1, '/');
258 die("oops in prep_exclude");
261 stk->prev = dir->exclude_stack;
262 stk->baselen = cp - base;
263 stk->exclude_ix = el->nr;
264 memcpy(dir->basebuf + current, base + current,
265 stk->baselen - current);
266 strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
267 add_excludes_from_file_1(dir->basebuf,
268 dir->basebuf, stk->baselen,
270 dir->exclude_stack = stk;
271 current = stk->baselen;
273 dir->basebuf[baselen] = '\0';
276 /* Scan the list and let the last match determines the fate.
277 * Return 1 for exclude, 0 for include and -1 for undecided.
279 static int excluded_1(const char *pathname,
280 int pathlen, const char *basename, int dtype,
281 struct exclude_list *el)
286 for (i = el->nr - 1; 0 <= i; i--) {
287 struct exclude *x = el->excludes[i];
288 const char *exclude = x->pattern;
289 int to_exclude = x->to_exclude;
291 if ((x->flags & EXC_FLAG_MUSTBEDIR) &&
295 if (x->flags & EXC_FLAG_NODIR) {
297 if (x->flags & EXC_FLAG_NOWILDCARD) {
298 if (!strcmp(exclude, basename))
300 } else if (x->flags & EXC_FLAG_ENDSWITH) {
301 if (x->patternlen - 1 <= pathlen &&
302 !strcmp(exclude + 1, pathname + pathlen - x->patternlen + 1))
305 if (fnmatch(exclude, basename, 0) == 0)
310 /* match with FNM_PATHNAME:
311 * exclude has base (baselen long) implicitly
314 int baselen = x->baselen;
318 if (pathlen < baselen ||
319 (baselen && pathname[baselen-1] != '/') ||
320 strncmp(pathname, x->base, baselen))
323 if (x->flags & EXC_FLAG_NOWILDCARD) {
324 if (!strcmp(exclude, pathname + baselen))
327 if (fnmatch(exclude, pathname+baselen,
334 return -1; /* undecided */
337 int excluded(struct dir_struct *dir, const char *pathname, int dtype)
339 int pathlen = strlen(pathname);
341 const char *basename = strrchr(pathname, '/');
342 basename = (basename) ? basename+1 : pathname;
344 prep_exclude(dir, pathname, basename-pathname);
345 for (st = EXC_CMDL; st <= EXC_FILE; st++) {
346 switch (excluded_1(pathname, pathlen, basename,
347 dtype, &dir->exclude_list[st])) {
357 static struct dir_entry *dir_entry_new(const char *pathname, int len)
359 struct dir_entry *ent;
361 ent = xmalloc(sizeof(*ent) + len + 1);
363 memcpy(ent->name, pathname, len);
368 struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
370 if (cache_name_pos(pathname, len) >= 0)
373 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
374 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
377 struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
379 if (cache_name_pos(pathname, len) >= 0)
382 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
383 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
387 index_nonexistent = 0,
393 * The index sorts alphabetically by entry name, which
394 * means that a gitlink sorts as '\0' at the end, while
395 * a directory (which is defined not as an entry, but as
396 * the files it contains) will sort with the '/' at the
399 static enum exist_status directory_exists_in_index(const char *dirname, int len)
401 int pos = cache_name_pos(dirname, len);
404 while (pos < active_nr) {
405 struct cache_entry *ce = active_cache[pos++];
406 unsigned char endchar;
408 if (strncmp(ce->name, dirname, len))
410 endchar = ce->name[len];
414 return index_directory;
415 if (!endchar && S_ISGITLINK(ntohl(ce->ce_mode)))
418 return index_nonexistent;
422 * When we find a directory when traversing the filesystem, we
423 * have three distinct cases:
426 * - see it as a directory
429 * and which one we choose depends on a combination of existing
430 * git index contents and the flags passed into the directory
433 * Case 1: If we *already* have entries in the index under that
434 * directory name, we always recurse into the directory to see
437 * Case 2: If we *already* have that directory name as a gitlink,
438 * we always continue to see it as a gitlink, regardless of whether
439 * there is an actual git directory there or not (it might not
440 * be checked out as a subproject!)
442 * Case 3: if we didn't have it in the index previously, we
443 * have a few sub-cases:
445 * (a) if "show_other_directories" is true, we show it as
446 * just a directory, unless "hide_empty_directories" is
447 * also true and the directory is empty, in which case
448 * we just ignore it entirely.
449 * (b) if it looks like a git directory, and we don't have
450 * 'no_gitlinks' set we treat it as a gitlink, and show it
452 * (c) otherwise, we recurse into it.
454 enum directory_treatment {
457 recurse_into_directory,
460 static enum directory_treatment treat_directory(struct dir_struct *dir,
461 const char *dirname, int len,
462 const struct path_simplify *simplify)
464 /* The "len-1" is to strip the final '/' */
465 switch (directory_exists_in_index(dirname, len-1)) {
466 case index_directory:
467 return recurse_into_directory;
470 if (dir->show_other_directories)
471 return ignore_directory;
472 return show_directory;
474 case index_nonexistent:
475 if (dir->show_other_directories)
477 if (!dir->no_gitlinks) {
478 unsigned char sha1[20];
479 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
480 return show_directory;
482 return recurse_into_directory;
485 /* This is the "show_other_directories" case */
486 if (!dir->hide_empty_directories)
487 return show_directory;
488 if (!read_directory_recursive(dir, dirname, dirname, len, 1, simplify))
489 return ignore_directory;
490 return show_directory;
494 * This is an inexact early pruning of any recursive directory
495 * reading - if the path cannot possibly be in the pathspec,
496 * return true, and we'll skip it early.
498 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
502 const char *match = simplify->path;
503 int len = simplify->len;
509 if (!memcmp(path, match, len))
518 static int in_pathspec(const char *path, int len, const struct path_simplify *simplify)
521 for (; simplify->path; simplify++) {
522 if (len == simplify->len
523 && !memcmp(path, simplify->path, len))
530 static int get_dtype(struct dirent *de, const char *path)
532 int dtype = DTYPE(de);
535 if (dtype != DT_UNKNOWN)
537 if (lstat(path, &st))
539 if (S_ISREG(st.st_mode))
541 if (S_ISDIR(st.st_mode))
543 if (S_ISLNK(st.st_mode))
549 * Read a directory tree. We currently ignore anything but
550 * directories, regular files and symlinks. That's because git
551 * doesn't handle them at all yet. Maybe that will change some
554 * Also, we ignore the name ".git" (even if it is not a directory).
555 * That likely will not change.
557 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)
559 DIR *fdir = opendir(path);
564 char fullname[PATH_MAX + 1];
565 memcpy(fullname, base, baselen);
567 while ((de = readdir(fdir)) != NULL) {
571 if ((de->d_name[0] == '.') &&
572 (de->d_name[1] == 0 ||
573 !strcmp(de->d_name + 1, ".") ||
574 !strcmp(de->d_name + 1, "git")))
576 len = strlen(de->d_name);
577 /* Ignore overly long pathnames! */
578 if (len + baselen + 8 > sizeof(fullname))
580 memcpy(fullname + baselen, de->d_name, len+1);
581 if (simplify_away(fullname, baselen + len, simplify))
584 dtype = get_dtype(de, fullname);
585 exclude = excluded(dir, fullname, dtype);
586 if (exclude && dir->collect_ignored
587 && in_pathspec(fullname, baselen + len, simplify))
588 dir_add_ignored(dir, fullname, baselen + len);
591 * Excluded? If we don't explicitly want to show
592 * ignored files, ignore it
594 if (exclude && !dir->show_ignored)
598 * Do we want to see just the ignored files?
599 * We still need to recurse into directories,
600 * even if we don't ignore them, since the
601 * directory may contain files that we do..
603 if (!exclude && dir->show_ignored) {
612 memcpy(fullname + baselen + len, "/", 2);
614 switch (treat_directory(dir, fullname, baselen + len, simplify)) {
616 if (exclude != dir->show_ignored)
619 case recurse_into_directory:
620 contents += read_directory_recursive(dir,
621 fullname, fullname, baselen + len, 0, simplify);
623 case ignore_directory:
635 dir_add_name(dir, fullname, baselen + len);
644 static int cmp_name(const void *p1, const void *p2)
646 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
647 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
649 return cache_name_compare(e1->name, e1->len,
654 * Return the length of the "simple" part of a path match limiter.
656 static int simple_length(const char *match)
658 const char special[256] = {
660 ['\\'] = 1, ['*'] = 1,
666 unsigned char c = *match++;
673 static struct path_simplify *create_simplify(const char **pathspec)
676 struct path_simplify *simplify = NULL;
681 for (nr = 0 ; ; nr++) {
684 alloc = alloc_nr(alloc);
685 simplify = xrealloc(simplify, alloc * sizeof(*simplify));
690 simplify[nr].path = match;
691 simplify[nr].len = simple_length(match);
693 simplify[nr].path = NULL;
694 simplify[nr].len = 0;
698 static void free_simplify(struct path_simplify *simplify)
704 int read_directory(struct dir_struct *dir, const char *path, const char *base, int baselen, const char **pathspec)
706 struct path_simplify *simplify = create_simplify(pathspec);
708 read_directory_recursive(dir, path, base, baselen, 0, simplify);
709 free_simplify(simplify);
710 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
711 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
715 int file_exists(const char *f)
718 return lstat(f, &sb) == 0;
722 * get_relative_cwd() gets the prefix of the current working directory
723 * relative to 'dir'. If we are not inside 'dir', it returns NULL.
725 * As a convenience, it also returns NULL if 'dir' is already NULL. The
726 * reason for this behaviour is that it is natural for functions returning
727 * directory names to return NULL to say "this directory does not exist"
728 * or "this directory is invalid". These cases are usually handled the
729 * same as if the cwd is not inside 'dir' at all, so get_relative_cwd()
730 * returns NULL for both of them.
732 * Most notably, get_relative_cwd(buffer, size, get_git_work_tree())
733 * unifies the handling of "outside work tree" with "no work tree at all".
735 char *get_relative_cwd(char *buffer, int size, const char *dir)
741 if (!getcwd(buffer, size))
742 die("can't find the current directory: %s", strerror(errno));
744 if (!is_absolute_path(dir))
745 dir = make_absolute_path(dir);
747 while (*dir && *dir == *cwd) {
758 int is_inside_dir(const char *dir)
760 char buffer[PATH_MAX];
761 return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
764 int remove_dir_recursively(struct strbuf *path, int only_empty)
766 DIR *dir = opendir(path->buf);
768 int ret = 0, original_len = path->len, len;
772 if (path->buf[original_len - 1] != '/')
773 strbuf_addch(path, '/');
776 while ((e = readdir(dir)) != NULL) {
778 if ((e->d_name[0] == '.') &&
779 ((e->d_name[1] == 0) ||
780 ((e->d_name[1] == '.') && e->d_name[2] == 0)))
781 continue; /* "." and ".." */
783 strbuf_setlen(path, len);
784 strbuf_addstr(path, e->d_name);
785 if (lstat(path->buf, &st))
787 else if (S_ISDIR(st.st_mode)) {
788 if (!remove_dir_recursively(path, only_empty))
789 continue; /* happy */
790 } else if (!only_empty && !unlink(path->buf))
791 continue; /* happy, too */
793 /* path too long, stat fails, or non-directory still exists */
799 strbuf_setlen(path, original_len);
801 ret = rmdir(path->buf);
805 void setup_standard_excludes(struct dir_struct *dir)
809 dir->exclude_per_dir = ".gitignore";
810 path = git_path("info/exclude");
811 if (!access(path, R_OK))
812 add_excludes_from_file(dir, path);
813 if (excludes_file && !access(excludes_file, R_OK))
814 add_excludes_from_file(dir, excludes_file);