Teach --find-copies-harder to "git blame"
[git/git-p4.git] / dir.c
blob29d1d5ba31def46ba8b55905dc60773cc6cc167e
1 /*
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
7 */
8 #include "cache.h"
9 #include "dir.h"
10 #include "refs.h"
12 struct path_simplify {
13 int len;
14 const char *path;
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;
25 int prefix;
27 if (!pathspec)
28 return 0;
30 path = *pathspec;
31 slash = strrchr(path, '/');
32 if (!slash)
33 return 0;
35 prefix = slash - path + 1;
36 while ((next = *++pathspec) != NULL) {
37 int len = strlen(next);
38 if (len >= prefix && !memcmp(path, next, prefix))
39 continue;
40 len = prefix - 1;
41 for (;;) {
42 if (!len)
43 return 0;
44 if (next[--len] != '/')
45 continue;
46 if (memcmp(path, next, len+1))
47 continue;
48 prefix = len + 1;
49 break;
52 return prefix;
55 static inline int special_char(unsigned char c1)
57 return !c1 || c1 == '*' || c1 == '[' || c1 == '?';
61 * Does 'match' matches the given name?
62 * A match is found if
64 * (1) the 'match' string is leading directory of 'name', or
65 * (2) the 'match' string is a wildcard and matches 'name', or
66 * (3) the 'match' string is exactly the same as 'name'.
68 * and the return value tells which case it was.
70 * It returns 0 when there is no match.
72 static int match_one(const char *match, const char *name, int namelen)
74 int matchlen;
76 /* If the match was just the prefix, we matched */
77 if (!*match)
78 return MATCHED_RECURSIVELY;
80 for (;;) {
81 unsigned char c1 = *match;
82 unsigned char c2 = *name;
83 if (special_char(c1))
84 break;
85 if (c1 != c2)
86 return 0;
87 match++;
88 name++;
89 namelen--;
94 * If we don't match the matchstring exactly,
95 * we need to match by fnmatch
97 matchlen = strlen(match);
98 if (strncmp(match, name, matchlen))
99 return !fnmatch(match, name, 0) ? MATCHED_FNMATCH : 0;
101 if (namelen == matchlen)
102 return MATCHED_EXACTLY;
103 if (match[matchlen-1] == '/' || name[matchlen] == '/')
104 return MATCHED_RECURSIVELY;
105 return 0;
109 * Given a name and a list of pathspecs, see if the name matches
110 * any of the pathspecs. The caller is also interested in seeing
111 * all pathspec matches some names it calls this function with
112 * (otherwise the user could have mistyped the unmatched pathspec),
113 * and a mark is left in seen[] array for pathspec element that
114 * actually matched anything.
116 int match_pathspec(const char **pathspec, const char *name, int namelen, int prefix, char *seen)
118 int retval;
119 const char *match;
121 name += prefix;
122 namelen -= prefix;
124 for (retval = 0; (match = *pathspec++) != NULL; seen++) {
125 int how;
126 if (retval && *seen == MATCHED_EXACTLY)
127 continue;
128 match += prefix;
129 how = match_one(match, name, namelen);
130 if (how) {
131 if (retval < how)
132 retval = how;
133 if (*seen < how)
134 *seen = how;
137 return retval;
140 static int no_wildcard(const char *string)
142 return string[strcspn(string, "*?[{")] == '\0';
145 void add_exclude(const char *string, const char *base,
146 int baselen, struct exclude_list *which)
148 struct exclude *x;
149 size_t len;
150 int to_exclude = 1;
151 int flags = 0;
153 if (*string == '!') {
154 to_exclude = 0;
155 string++;
157 len = strlen(string);
158 if (len && string[len - 1] == '/') {
159 char *s;
160 x = xmalloc(sizeof(*x) + len);
161 s = (char*)(x+1);
162 memcpy(s, string, len - 1);
163 s[len - 1] = '\0';
164 string = s;
165 x->pattern = s;
166 flags = EXC_FLAG_MUSTBEDIR;
167 } else {
168 x = xmalloc(sizeof(*x));
169 x->pattern = string;
171 x->to_exclude = to_exclude;
172 x->patternlen = strlen(string);
173 x->base = base;
174 x->baselen = baselen;
175 x->flags = flags;
176 if (!strchr(string, '/'))
177 x->flags |= EXC_FLAG_NODIR;
178 if (no_wildcard(string))
179 x->flags |= EXC_FLAG_NOWILDCARD;
180 if (*string == '*' && no_wildcard(string+1))
181 x->flags |= EXC_FLAG_ENDSWITH;
182 ALLOC_GROW(which->excludes, which->nr + 1, which->alloc);
183 which->excludes[which->nr++] = x;
186 static int add_excludes_from_file_1(const char *fname,
187 const char *base,
188 int baselen,
189 char **buf_p,
190 struct exclude_list *which)
192 struct stat st;
193 int fd, i;
194 size_t size;
195 char *buf, *entry;
197 fd = open(fname, O_RDONLY);
198 if (fd < 0 || fstat(fd, &st) < 0)
199 goto err;
200 size = xsize_t(st.st_size);
201 if (size == 0) {
202 close(fd);
203 return 0;
205 buf = xmalloc(size+1);
206 if (read_in_full(fd, buf, size) != size)
208 free(buf);
209 goto err;
211 close(fd);
213 if (buf_p)
214 *buf_p = buf;
215 buf[size++] = '\n';
216 entry = buf;
217 for (i = 0; i < size; i++) {
218 if (buf[i] == '\n') {
219 if (entry != buf + i && entry[0] != '#') {
220 buf[i - (i && buf[i-1] == '\r')] = 0;
221 add_exclude(entry, base, baselen, which);
223 entry = buf + i + 1;
226 return 0;
228 err:
229 if (0 <= fd)
230 close(fd);
231 return -1;
234 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
236 if (add_excludes_from_file_1(fname, "", 0, NULL,
237 &dir->exclude_list[EXC_FILE]) < 0)
238 die("cannot use %s as an exclude file", fname);
241 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
243 struct exclude_list *el;
244 struct exclude_stack *stk = NULL;
245 int current;
247 if ((!dir->exclude_per_dir) ||
248 (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
249 return; /* too long a path -- ignore */
251 /* Pop the ones that are not the prefix of the path being checked. */
252 el = &dir->exclude_list[EXC_DIRS];
253 while ((stk = dir->exclude_stack) != NULL) {
254 if (stk->baselen <= baselen &&
255 !strncmp(dir->basebuf, base, stk->baselen))
256 break;
257 dir->exclude_stack = stk->prev;
258 while (stk->exclude_ix < el->nr)
259 free(el->excludes[--el->nr]);
260 free(stk->filebuf);
261 free(stk);
264 /* Read from the parent directories and push them down. */
265 current = stk ? stk->baselen : -1;
266 while (current < baselen) {
267 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
268 const char *cp;
270 if (current < 0) {
271 cp = base;
272 current = 0;
274 else {
275 cp = strchr(base + current + 1, '/');
276 if (!cp)
277 die("oops in prep_exclude");
278 cp++;
280 stk->prev = dir->exclude_stack;
281 stk->baselen = cp - base;
282 stk->exclude_ix = el->nr;
283 memcpy(dir->basebuf + current, base + current,
284 stk->baselen - current);
285 strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
286 add_excludes_from_file_1(dir->basebuf,
287 dir->basebuf, stk->baselen,
288 &stk->filebuf, el);
289 dir->exclude_stack = stk;
290 current = stk->baselen;
292 dir->basebuf[baselen] = '\0';
295 /* Scan the list and let the last match determines the fate.
296 * Return 1 for exclude, 0 for include and -1 for undecided.
298 static int excluded_1(const char *pathname,
299 int pathlen, const char *basename, int *dtype,
300 struct exclude_list *el)
302 int i;
304 if (el->nr) {
305 for (i = el->nr - 1; 0 <= i; i--) {
306 struct exclude *x = el->excludes[i];
307 const char *exclude = x->pattern;
308 int to_exclude = x->to_exclude;
310 if (x->flags & EXC_FLAG_MUSTBEDIR) {
311 if (*dtype == DT_UNKNOWN)
312 *dtype = get_dtype(NULL, pathname);
313 if (*dtype != DT_DIR)
314 continue;
317 if (x->flags & EXC_FLAG_NODIR) {
318 /* match basename */
319 if (x->flags & EXC_FLAG_NOWILDCARD) {
320 if (!strcmp(exclude, basename))
321 return to_exclude;
322 } else if (x->flags & EXC_FLAG_ENDSWITH) {
323 if (x->patternlen - 1 <= pathlen &&
324 !strcmp(exclude + 1, pathname + pathlen - x->patternlen + 1))
325 return to_exclude;
326 } else {
327 if (fnmatch(exclude, basename, 0) == 0)
328 return to_exclude;
331 else {
332 /* match with FNM_PATHNAME:
333 * exclude has base (baselen long) implicitly
334 * in front of it.
336 int baselen = x->baselen;
337 if (*exclude == '/')
338 exclude++;
340 if (pathlen < baselen ||
341 (baselen && pathname[baselen-1] != '/') ||
342 strncmp(pathname, x->base, baselen))
343 continue;
345 if (x->flags & EXC_FLAG_NOWILDCARD) {
346 if (!strcmp(exclude, pathname + baselen))
347 return to_exclude;
348 } else {
349 if (fnmatch(exclude, pathname+baselen,
350 FNM_PATHNAME) == 0)
351 return to_exclude;
356 return -1; /* undecided */
359 int excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
361 int pathlen = strlen(pathname);
362 int st;
363 const char *basename = strrchr(pathname, '/');
364 basename = (basename) ? basename+1 : pathname;
366 prep_exclude(dir, pathname, basename-pathname);
367 for (st = EXC_CMDL; st <= EXC_FILE; st++) {
368 switch (excluded_1(pathname, pathlen, basename,
369 dtype_p, &dir->exclude_list[st])) {
370 case 0:
371 return 0;
372 case 1:
373 return 1;
376 return 0;
379 static struct dir_entry *dir_entry_new(const char *pathname, int len)
381 struct dir_entry *ent;
383 ent = xmalloc(sizeof(*ent) + len + 1);
384 ent->len = len;
385 memcpy(ent->name, pathname, len);
386 ent->name[len] = 0;
387 return ent;
390 struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
392 if (cache_name_exists(pathname, len, ignore_case))
393 return NULL;
395 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
396 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
399 struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
401 if (cache_name_pos(pathname, len) >= 0)
402 return NULL;
404 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
405 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
408 enum exist_status {
409 index_nonexistent = 0,
410 index_directory,
411 index_gitdir,
415 * The index sorts alphabetically by entry name, which
416 * means that a gitlink sorts as '\0' at the end, while
417 * a directory (which is defined not as an entry, but as
418 * the files it contains) will sort with the '/' at the
419 * end.
421 static enum exist_status directory_exists_in_index(const char *dirname, int len)
423 int pos = cache_name_pos(dirname, len);
424 if (pos < 0)
425 pos = -pos-1;
426 while (pos < active_nr) {
427 struct cache_entry *ce = active_cache[pos++];
428 unsigned char endchar;
430 if (strncmp(ce->name, dirname, len))
431 break;
432 endchar = ce->name[len];
433 if (endchar > '/')
434 break;
435 if (endchar == '/')
436 return index_directory;
437 if (!endchar && S_ISGITLINK(ce->ce_mode))
438 return index_gitdir;
440 return index_nonexistent;
444 * When we find a directory when traversing the filesystem, we
445 * have three distinct cases:
447 * - ignore it
448 * - see it as a directory
449 * - recurse into it
451 * and which one we choose depends on a combination of existing
452 * git index contents and the flags passed into the directory
453 * traversal routine.
455 * Case 1: If we *already* have entries in the index under that
456 * directory name, we always recurse into the directory to see
457 * all the files.
459 * Case 2: If we *already* have that directory name as a gitlink,
460 * we always continue to see it as a gitlink, regardless of whether
461 * there is an actual git directory there or not (it might not
462 * be checked out as a subproject!)
464 * Case 3: if we didn't have it in the index previously, we
465 * have a few sub-cases:
467 * (a) if "show_other_directories" is true, we show it as
468 * just a directory, unless "hide_empty_directories" is
469 * also true and the directory is empty, in which case
470 * we just ignore it entirely.
471 * (b) if it looks like a git directory, and we don't have
472 * 'no_gitlinks' set we treat it as a gitlink, and show it
473 * as a directory.
474 * (c) otherwise, we recurse into it.
476 enum directory_treatment {
477 show_directory,
478 ignore_directory,
479 recurse_into_directory,
482 static enum directory_treatment treat_directory(struct dir_struct *dir,
483 const char *dirname, int len,
484 const struct path_simplify *simplify)
486 /* The "len-1" is to strip the final '/' */
487 switch (directory_exists_in_index(dirname, len-1)) {
488 case index_directory:
489 return recurse_into_directory;
491 case index_gitdir:
492 if (dir->show_other_directories)
493 return ignore_directory;
494 return show_directory;
496 case index_nonexistent:
497 if (dir->show_other_directories)
498 break;
499 if (!dir->no_gitlinks) {
500 unsigned char sha1[20];
501 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
502 return show_directory;
504 return recurse_into_directory;
507 /* This is the "show_other_directories" case */
508 if (!dir->hide_empty_directories)
509 return show_directory;
510 if (!read_directory_recursive(dir, dirname, dirname, len, 1, simplify))
511 return ignore_directory;
512 return show_directory;
516 * This is an inexact early pruning of any recursive directory
517 * reading - if the path cannot possibly be in the pathspec,
518 * return true, and we'll skip it early.
520 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
522 if (simplify) {
523 for (;;) {
524 const char *match = simplify->path;
525 int len = simplify->len;
527 if (!match)
528 break;
529 if (len > pathlen)
530 len = pathlen;
531 if (!memcmp(path, match, len))
532 return 0;
533 simplify++;
535 return 1;
537 return 0;
540 static int in_pathspec(const char *path, int len, const struct path_simplify *simplify)
542 if (simplify) {
543 for (; simplify->path; simplify++) {
544 if (len == simplify->len
545 && !memcmp(path, simplify->path, len))
546 return 1;
549 return 0;
552 static int get_dtype(struct dirent *de, const char *path)
554 int dtype = de ? DTYPE(de) : DT_UNKNOWN;
555 struct stat st;
557 if (dtype != DT_UNKNOWN)
558 return dtype;
559 if (lstat(path, &st))
560 return dtype;
561 if (S_ISREG(st.st_mode))
562 return DT_REG;
563 if (S_ISDIR(st.st_mode))
564 return DT_DIR;
565 if (S_ISLNK(st.st_mode))
566 return DT_LNK;
567 return dtype;
571 * Read a directory tree. We currently ignore anything but
572 * directories, regular files and symlinks. That's because git
573 * doesn't handle them at all yet. Maybe that will change some
574 * day.
576 * Also, we ignore the name ".git" (even if it is not a directory).
577 * That likely will not change.
579 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)
581 DIR *fdir = opendir(path);
582 int contents = 0;
584 if (fdir) {
585 struct dirent *de;
586 char fullname[PATH_MAX + 1];
587 memcpy(fullname, base, baselen);
589 while ((de = readdir(fdir)) != NULL) {
590 int len, dtype;
591 int exclude;
593 if ((de->d_name[0] == '.') &&
594 (de->d_name[1] == 0 ||
595 !strcmp(de->d_name + 1, ".") ||
596 !strcmp(de->d_name + 1, "git")))
597 continue;
598 len = strlen(de->d_name);
599 /* Ignore overly long pathnames! */
600 if (len + baselen + 8 > sizeof(fullname))
601 continue;
602 memcpy(fullname + baselen, de->d_name, len+1);
603 if (simplify_away(fullname, baselen + len, simplify))
604 continue;
606 dtype = DTYPE(de);
607 exclude = excluded(dir, fullname, &dtype);
608 if (exclude && dir->collect_ignored
609 && in_pathspec(fullname, baselen + len, simplify))
610 dir_add_ignored(dir, fullname, baselen + len);
613 * Excluded? If we don't explicitly want to show
614 * ignored files, ignore it
616 if (exclude && !dir->show_ignored)
617 continue;
619 if (dtype == DT_UNKNOWN)
620 dtype = get_dtype(de, fullname);
623 * Do we want to see just the ignored files?
624 * We still need to recurse into directories,
625 * even if we don't ignore them, since the
626 * directory may contain files that we do..
628 if (!exclude && dir->show_ignored) {
629 if (dtype != DT_DIR)
630 continue;
633 switch (dtype) {
634 default:
635 continue;
636 case DT_DIR:
637 memcpy(fullname + baselen + len, "/", 2);
638 len++;
639 switch (treat_directory(dir, fullname, baselen + len, simplify)) {
640 case show_directory:
641 if (exclude != dir->show_ignored)
642 continue;
643 break;
644 case recurse_into_directory:
645 contents += read_directory_recursive(dir,
646 fullname, fullname, baselen + len, 0, simplify);
647 continue;
648 case ignore_directory:
649 continue;
651 break;
652 case DT_REG:
653 case DT_LNK:
654 break;
656 contents++;
657 if (check_only)
658 goto exit_early;
659 else
660 dir_add_name(dir, fullname, baselen + len);
662 exit_early:
663 closedir(fdir);
666 return contents;
669 static int cmp_name(const void *p1, const void *p2)
671 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
672 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
674 return cache_name_compare(e1->name, e1->len,
675 e2->name, e2->len);
679 * Return the length of the "simple" part of a path match limiter.
681 static int simple_length(const char *match)
683 const char special[256] = {
684 [0] = 1, ['?'] = 1,
685 ['\\'] = 1, ['*'] = 1,
686 ['['] = 1
688 int len = -1;
690 for (;;) {
691 unsigned char c = *match++;
692 len++;
693 if (special[c])
694 return len;
698 static struct path_simplify *create_simplify(const char **pathspec)
700 int nr, alloc = 0;
701 struct path_simplify *simplify = NULL;
703 if (!pathspec)
704 return NULL;
706 for (nr = 0 ; ; nr++) {
707 const char *match;
708 if (nr >= alloc) {
709 alloc = alloc_nr(alloc);
710 simplify = xrealloc(simplify, alloc * sizeof(*simplify));
712 match = *pathspec++;
713 if (!match)
714 break;
715 simplify[nr].path = match;
716 simplify[nr].len = simple_length(match);
718 simplify[nr].path = NULL;
719 simplify[nr].len = 0;
720 return simplify;
723 static void free_simplify(struct path_simplify *simplify)
725 free(simplify);
728 int read_directory(struct dir_struct *dir, const char *path, const char *base, int baselen, const char **pathspec)
730 struct path_simplify *simplify = create_simplify(pathspec);
732 read_directory_recursive(dir, path, base, baselen, 0, simplify);
733 free_simplify(simplify);
734 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
735 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
736 return dir->nr;
739 int file_exists(const char *f)
741 struct stat sb;
742 return lstat(f, &sb) == 0;
746 * get_relative_cwd() gets the prefix of the current working directory
747 * relative to 'dir'. If we are not inside 'dir', it returns NULL.
749 * As a convenience, it also returns NULL if 'dir' is already NULL. The
750 * reason for this behaviour is that it is natural for functions returning
751 * directory names to return NULL to say "this directory does not exist"
752 * or "this directory is invalid". These cases are usually handled the
753 * same as if the cwd is not inside 'dir' at all, so get_relative_cwd()
754 * returns NULL for both of them.
756 * Most notably, get_relative_cwd(buffer, size, get_git_work_tree())
757 * unifies the handling of "outside work tree" with "no work tree at all".
759 char *get_relative_cwd(char *buffer, int size, const char *dir)
761 char *cwd = buffer;
763 if (!dir)
764 return NULL;
765 if (!getcwd(buffer, size))
766 die("can't find the current directory: %s", strerror(errno));
768 if (!is_absolute_path(dir))
769 dir = make_absolute_path(dir);
771 while (*dir && *dir == *cwd) {
772 dir++;
773 cwd++;
775 if (*dir)
776 return NULL;
777 if (*cwd == '/')
778 return cwd + 1;
779 return cwd;
782 int is_inside_dir(const char *dir)
784 char buffer[PATH_MAX];
785 return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
788 int remove_dir_recursively(struct strbuf *path, int only_empty)
790 DIR *dir = opendir(path->buf);
791 struct dirent *e;
792 int ret = 0, original_len = path->len, len;
794 if (!dir)
795 return -1;
796 if (path->buf[original_len - 1] != '/')
797 strbuf_addch(path, '/');
799 len = path->len;
800 while ((e = readdir(dir)) != NULL) {
801 struct stat st;
802 if ((e->d_name[0] == '.') &&
803 ((e->d_name[1] == 0) ||
804 ((e->d_name[1] == '.') && e->d_name[2] == 0)))
805 continue; /* "." and ".." */
807 strbuf_setlen(path, len);
808 strbuf_addstr(path, e->d_name);
809 if (lstat(path->buf, &st))
810 ; /* fall thru */
811 else if (S_ISDIR(st.st_mode)) {
812 if (!remove_dir_recursively(path, only_empty))
813 continue; /* happy */
814 } else if (!only_empty && !unlink(path->buf))
815 continue; /* happy, too */
817 /* path too long, stat fails, or non-directory still exists */
818 ret = -1;
819 break;
821 closedir(dir);
823 strbuf_setlen(path, original_len);
824 if (!ret)
825 ret = rmdir(path->buf);
826 return ret;
829 void setup_standard_excludes(struct dir_struct *dir)
831 const char *path;
833 dir->exclude_per_dir = ".gitignore";
834 path = git_path("info/exclude");
835 if (!access(path, R_OK))
836 add_excludes_from_file(dir, path);
837 if (excludes_file && !access(excludes_file, R_OK))
838 add_excludes_from_file(dir, excludes_file);