1 /*
2 * This handles recursive filename detection with exclude
3 * files, index knowledge etc..
4 *
5 * Copyright (C) Linus Torvalds, 2005-2006
6 * Junio Hamano, 2005-2006
7 */
8 #include "cache.h"
9 #include "dir.h"
10 #include "refs.h"
12 struct path_simplify {
13 int len;
14 const char *path;
15 };
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)
22 {
23 const char *path, *slash, *next;
24 int prefix;
26 if (!pathspec)
27 return 0;
29 path = *pathspec;
30 slash = strrchr(path, '/');
31 if (!slash)
32 return 0;
34 prefix = slash - path + 1;
35 while ((next = *++pathspec) != NULL) {
36 int len = strlen(next);
37 if (len >= prefix && !memcmp(path, next, prefix))
38 continue;
39 len = prefix - 1;
40 for (;;) {
41 if (!len)
42 return 0;
43 if (next[--len] != '/')
44 continue;
45 if (memcmp(path, next, len+1))
46 continue;
47 prefix = len + 1;
48 break;
49 }
50 }
51 return prefix;
52 }
54 /*
55 * Does 'match' matches the given name?
56 * A match is found if
57 *
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'.
61 *
62 * and the return value tells which case it was.
63 *
64 * It returns 0 when there is no match.
65 */
66 static int match_one(const char *match, const char *name, int namelen)
67 {
68 int matchlen;
70 /* If the match was just the prefix, we matched */
71 matchlen = strlen(match);
72 if (!matchlen)
73 return MATCHED_RECURSIVELY;
75 /*
76 * If we don't match the matchstring exactly,
77 * we need to match by fnmatch
78 */
79 if (strncmp(match, name, matchlen))
80 return !fnmatch(match, name, 0) ? MATCHED_FNMATCH : 0;
82 if (!name[matchlen])
83 return MATCHED_EXACTLY;
84 if (match[matchlen-1] == '/' || name[matchlen] == '/')
85 return MATCHED_RECURSIVELY;
86 return 0;
87 }
89 /*
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.
96 */
97 int match_pathspec(const char **pathspec, const char *name, int namelen, int prefix, char *seen)
98 {
99 int retval;
100 const char *match;
102 name += prefix;
103 namelen -= prefix;
105 for (retval = 0; (match = *pathspec++) != NULL; seen++) {
106 int how;
107 if (retval && *seen == MATCHED_EXACTLY)
108 continue;
109 match += prefix;
110 how = match_one(match, name, namelen);
111 if (how) {
112 if (retval < how)
113 retval = how;
114 if (*seen < how)
115 *seen = how;
116 }
117 }
118 return retval;
119 }
121 static int no_wildcard(const char *string)
122 {
123 return string[strcspn(string, "*?[{")] == '\0';
124 }
126 void add_exclude(const char *string, const char *base,
127 int baselen, struct exclude_list *which)
128 {
129 struct exclude *x;
130 size_t len;
131 int to_exclude = 1;
132 int flags = 0;
134 if (*string == '!') {
135 to_exclude = 0;
136 string++;
137 }
138 len = strlen(string);
139 if (len && string[len - 1] == '/') {
140 char *s;
141 x = xmalloc(sizeof(*x) + len);
142 s = (char*)(x+1);
143 memcpy(s, string, len - 1);
144 s[len - 1] = '\0';
145 string = s;
146 x->pattern = s;
147 flags = EXC_FLAG_MUSTBEDIR;
148 } else {
149 x = xmalloc(sizeof(*x));
150 x->pattern = string;
151 }
152 x->to_exclude = to_exclude;
153 x->patternlen = strlen(string);
154 x->base = base;
155 x->baselen = baselen;
156 x->flags = flags;
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;
165 }
167 static int add_excludes_from_file_1(const char *fname,
168 const char *base,
169 int baselen,
170 char **buf_p,
171 struct exclude_list *which)
172 {
173 struct stat st;
174 int fd, i;
175 size_t size;
176 char *buf, *entry;
178 fd = open(fname, O_RDONLY);
179 if (fd < 0 || fstat(fd, &st) < 0)
180 goto err;
181 size = xsize_t(st.st_size);
182 if (size == 0) {
183 close(fd);
184 return 0;
185 }
186 buf = xmalloc(size+1);
187 if (read_in_full(fd, buf, size) != size)
188 {
189 free(buf);
190 goto err;
191 }
192 close(fd);
194 if (buf_p)
195 *buf_p = buf;
196 buf[size++] = '\n';
197 entry = buf;
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);
203 }
204 entry = buf + i + 1;
205 }
206 }
207 return 0;
209 err:
210 if (0 <= fd)
211 close(fd);
212 return -1;
213 }
215 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
216 {
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);
220 }
222 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
223 {
224 struct exclude_list *el;
225 struct exclude_stack *stk = NULL;
226 int current;
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))
237 break;
238 dir->exclude_stack = stk->prev;
239 while (stk->exclude_ix < el->nr)
240 free(el->excludes[--el->nr]);
241 free(stk->filebuf);
242 free(stk);
243 }
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));
249 const char *cp;
251 if (current < 0) {
252 cp = base;
253 current = 0;
254 }
255 else {
256 cp = strchr(base + current + 1, '/');
257 if (!cp)
258 die("oops in prep_exclude");
259 cp++;
260 }
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,
269 &stk->filebuf, el);
270 dir->exclude_stack = stk;
271 current = stk->baselen;
272 }
273 dir->basebuf[baselen] = '\0';
274 }
276 /* Scan the list and let the last match determines the fate.
277 * Return 1 for exclude, 0 for include and -1 for undecided.
278 */
279 static int excluded_1(const char *pathname,
280 int pathlen, const char *basename, int dtype,
281 struct exclude_list *el)
282 {
283 int i;
285 if (el->nr) {
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) &&
292 (dtype != DT_DIR))
293 continue;
295 if (x->flags & EXC_FLAG_NODIR) {
296 /* match basename */
297 if (x->flags & EXC_FLAG_NOWILDCARD) {
298 if (!strcmp(exclude, basename))
299 return to_exclude;
300 } else if (x->flags & EXC_FLAG_ENDSWITH) {
301 if (x->patternlen - 1 <= pathlen &&
302 !strcmp(exclude + 1, pathname + pathlen - x->patternlen + 1))
303 return to_exclude;
304 } else {
305 if (fnmatch(exclude, basename, 0) == 0)
306 return to_exclude;
307 }
308 }
309 else {
310 /* match with FNM_PATHNAME:
311 * exclude has base (baselen long) implicitly
312 * in front of it.
313 */
314 int baselen = x->baselen;
315 if (*exclude == '/')
316 exclude++;
318 if (pathlen < baselen ||
319 (baselen && pathname[baselen-1] != '/') ||
320 strncmp(pathname, x->base, baselen))
321 continue;
323 if (x->flags & EXC_FLAG_NOWILDCARD) {
324 if (!strcmp(exclude, pathname + baselen))
325 return to_exclude;
326 } else {
327 if (fnmatch(exclude, pathname+baselen,
328 FNM_PATHNAME) == 0)
329 return to_exclude;
330 }
331 }
332 }
333 }
334 return -1; /* undecided */
335 }
337 int excluded(struct dir_struct *dir, const char *pathname, int dtype)
338 {
339 int pathlen = strlen(pathname);
340 int st;
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])) {
348 case 0:
349 return 0;
350 case 1:
351 return 1;
352 }
353 }
354 return 0;
355 }
357 static struct dir_entry *dir_entry_new(const char *pathname, int len)
358 {
359 struct dir_entry *ent;
361 ent = xmalloc(sizeof(*ent) + len + 1);
362 ent->len = len;
363 memcpy(ent->name, pathname, len);
364 ent->name[len] = 0;
365 return ent;
366 }
368 struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
369 {
370 if (cache_name_pos(pathname, len) >= 0)
371 return NULL;
373 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
374 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
375 }
377 struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
378 {
379 if (cache_name_pos(pathname, len) >= 0)
380 return NULL;
382 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
383 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
384 }
386 enum exist_status {
387 index_nonexistent = 0,
388 index_directory,
389 index_gitdir,
390 };
392 /*
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
397 * end.
398 */
399 static enum exist_status directory_exists_in_index(const char *dirname, int len)
400 {
401 int pos = cache_name_pos(dirname, len);
402 if (pos < 0)
403 pos = -pos-1;
404 while (pos < active_nr) {
405 struct cache_entry *ce = active_cache[pos++];
406 unsigned char endchar;
408 if (strncmp(ce->name, dirname, len))
409 break;
410 endchar = ce->name[len];
411 if (endchar > '/')
412 break;
413 if (endchar == '/')
414 return index_directory;
415 if (!endchar && S_ISGITLINK(ntohl(ce->ce_mode)))
416 return index_gitdir;
417 }
418 return index_nonexistent;
419 }
421 /*
422 * When we find a directory when traversing the filesystem, we
423 * have three distinct cases:
424 *
425 * - ignore it
426 * - see it as a directory
427 * - recurse into it
428 *
429 * and which one we choose depends on a combination of existing
430 * git index contents and the flags passed into the directory
431 * traversal routine.
432 *
433 * Case 1: If we *already* have entries in the index under that
434 * directory name, we always recurse into the directory to see
435 * all the files.
436 *
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!)
441 *
442 * Case 3: if we didn't have it in the index previously, we
443 * have a few sub-cases:
444 *
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
451 * as a directory.
452 * (c) otherwise, we recurse into it.
453 */
454 enum directory_treatment {
455 show_directory,
456 ignore_directory,
457 recurse_into_directory,
458 };
460 static enum directory_treatment treat_directory(struct dir_struct *dir,
461 const char *dirname, int len,
462 const struct path_simplify *simplify)
463 {
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;
469 case index_gitdir:
470 if (dir->show_other_directories)
471 return ignore_directory;
472 return show_directory;
474 case index_nonexistent:
475 if (dir->show_other_directories)
476 break;
477 if (!dir->no_gitlinks) {
478 unsigned char sha1[20];
479 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
480 return show_directory;
481 }
482 return recurse_into_directory;
483 }
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;
491 }
493 /*
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.
497 */
498 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
499 {
500 if (simplify) {
501 for (;;) {
502 const char *match = simplify->path;
503 int len = simplify->len;
505 if (!match)
506 break;
507 if (len > pathlen)
508 len = pathlen;
509 if (!memcmp(path, match, len))
510 return 0;
511 simplify++;
512 }
513 return 1;
514 }
515 return 0;
516 }
518 static int in_pathspec(const char *path, int len, const struct path_simplify *simplify)
519 {
520 if (simplify) {
521 for (; simplify->path; simplify++) {
522 if (len == simplify->len
523 && !memcmp(path, simplify->path, len))
524 return 1;
525 }
526 }
527 return 0;
528 }
530 static int get_dtype(struct dirent *de, const char *path)
531 {
532 int dtype = DTYPE(de);
533 struct stat st;
535 if (dtype != DT_UNKNOWN)
536 return dtype;
537 if (lstat(path, &st))
538 return dtype;
539 if (S_ISREG(st.st_mode))
540 return DT_REG;
541 if (S_ISDIR(st.st_mode))
542 return DT_DIR;
543 if (S_ISLNK(st.st_mode))
544 return DT_LNK;
545 return dtype;
546 }
548 /*
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
552 * day.
553 *
554 * Also, we ignore the name ".git" (even if it is not a directory).
555 * That likely will not change.
556 */
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)
558 {
559 DIR *fdir = opendir(path);
560 int contents = 0;
562 if (fdir) {
563 struct dirent *de;
564 char fullname[PATH_MAX + 1];
565 memcpy(fullname, base, baselen);
567 while ((de = readdir(fdir)) != NULL) {
568 int len, dtype;
569 int exclude;
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")))
575 continue;
576 len = strlen(de->d_name);
577 /* Ignore overly long pathnames! */
578 if (len + baselen + 8 > sizeof(fullname))
579 continue;
580 memcpy(fullname + baselen, de->d_name, len+1);
581 if (simplify_away(fullname, baselen + len, simplify))
582 continue;
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);
590 /*
591 * Excluded? If we don't explicitly want to show
592 * ignored files, ignore it
593 */
594 if (exclude && !dir->show_ignored)
595 continue;
597 /*
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..
602 */
603 if (!exclude && dir->show_ignored) {
604 if (dtype != DT_DIR)
605 continue;
606 }
608 switch (dtype) {
609 default:
610 continue;
611 case DT_DIR:
612 memcpy(fullname + baselen + len, "/", 2);
613 len++;
614 switch (treat_directory(dir, fullname, baselen + len, simplify)) {
615 case show_directory:
616 if (exclude != dir->show_ignored)
617 continue;
618 break;
619 case recurse_into_directory:
620 contents += read_directory_recursive(dir,
621 fullname, fullname, baselen + len, 0, simplify);
622 continue;
623 case ignore_directory:
624 continue;
625 }
626 break;
627 case DT_REG:
628 case DT_LNK:
629 break;
630 }
631 contents++;
632 if (check_only)
633 goto exit_early;
634 else
635 dir_add_name(dir, fullname, baselen + len);
636 }
637 exit_early:
638 closedir(fdir);
639 }
641 return contents;
642 }
644 static int cmp_name(const void *p1, const void *p2)
645 {
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,
650 e2->name, e2->len);
651 }
653 /*
654 * Return the length of the "simple" part of a path match limiter.
655 */
656 static int simple_length(const char *match)
657 {
658 const char special[256] = {
659 [0] = 1, ['?'] = 1,
660 ['\\'] = 1, ['*'] = 1,
661 ['['] = 1
662 };
663 int len = -1;
665 for (;;) {
666 unsigned char c = *match++;
667 len++;
668 if (special[c])
669 return len;
670 }
671 }
673 static struct path_simplify *create_simplify(const char **pathspec)
674 {
675 int nr, alloc = 0;
676 struct path_simplify *simplify = NULL;
678 if (!pathspec)
679 return NULL;
681 for (nr = 0 ; ; nr++) {
682 const char *match;
683 if (nr >= alloc) {
684 alloc = alloc_nr(alloc);
685 simplify = xrealloc(simplify, alloc * sizeof(*simplify));
686 }
687 match = *pathspec++;
688 if (!match)
689 break;
690 simplify[nr].path = match;
691 simplify[nr].len = simple_length(match);
692 }
693 simplify[nr].path = NULL;
694 simplify[nr].len = 0;
695 return simplify;
696 }
698 static void free_simplify(struct path_simplify *simplify)
699 {
700 if (simplify)
701 free(simplify);
702 }
704 int read_directory(struct dir_struct *dir, const char *path, const char *base, int baselen, const char **pathspec)
705 {
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);
712 return dir->nr;
713 }
715 int file_exists(const char *f)
716 {
717 struct stat sb;
718 return lstat(f, &sb) == 0;
719 }
721 /*
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.
724 *
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.
731 *
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".
734 */
735 char *get_relative_cwd(char *buffer, int size, const char *dir)
736 {
737 char *cwd = buffer;
739 if (!dir)
740 return NULL;
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) {
748 dir++;
749 cwd++;
750 }
751 if (*dir)
752 return NULL;
753 if (*cwd == '/')
754 return cwd + 1;
755 return cwd;
756 }
758 int is_inside_dir(const char *dir)
759 {
760 char buffer[PATH_MAX];
761 return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
762 }
764 int remove_dir_recursively(struct strbuf *path, int only_empty)
765 {
766 DIR *dir = opendir(path->buf);
767 struct dirent *e;
768 int ret = 0, original_len = path->len, len;
770 if (!dir)
771 return -1;
772 if (path->buf[original_len - 1] != '/')
773 strbuf_addch(path, '/');
775 len = path->len;
776 while ((e = readdir(dir)) != NULL) {
777 struct stat st;
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))
786 ; /* fall thru */
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 */
794 ret = -1;
795 break;
796 }
797 closedir(dir);
799 strbuf_setlen(path, original_len);
800 if (!ret)
801 ret = rmdir(path->buf);
802 return ret;
803 }
805 void setup_standard_excludes(struct dir_struct *dir)
806 {
807 const char *path;
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);
815 }