Fix builtin checkout crashing when given an invalid path
[git/spearce.git] / dir.c
blobedc458e020772a7ab704e9cf69786d3aa641bcd4
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;
56 * Does 'match' matches the given name?
57 * A match is found if
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)
69 int matchlen;
71 /* If the match was just the prefix, we matched */
72 matchlen = strlen(match);
73 if (!matchlen)
74 return MATCHED_RECURSIVELY;
77 * If we don't match the matchstring exactly,
78 * we need to match by fnmatch
80 if (strncmp(match, name, matchlen))
81 return !fnmatch(match, name, 0) ? MATCHED_FNMATCH : 0;
83 if (!name[matchlen])
84 return MATCHED_EXACTLY;
85 if (match[matchlen-1] == '/' || name[matchlen] == '/')
86 return MATCHED_RECURSIVELY;
87 return 0;
91 * Given a name and a list of pathspecs, see if the name matches
92 * any of the pathspecs. The caller is also interested in seeing
93 * all pathspec matches some names it calls this function with
94 * (otherwise the user could have mistyped the unmatched pathspec),
95 * and a mark is left in seen[] array for pathspec element that
96 * actually matched anything.
98 int match_pathspec(const char **pathspec, const char *name, int namelen, int prefix, char *seen)
100 int retval;
101 const char *match;
103 name += prefix;
104 namelen -= prefix;
106 for (retval = 0; (match = *pathspec++) != NULL; seen++) {
107 int how;
108 if (retval && *seen == MATCHED_EXACTLY)
109 continue;
110 match += prefix;
111 how = match_one(match, name, namelen);
112 if (how) {
113 if (retval < how)
114 retval = how;
115 if (*seen < how)
116 *seen = how;
119 return retval;
122 static int no_wildcard(const char *string)
124 return string[strcspn(string, "*?[{")] == '\0';
127 void add_exclude(const char *string, const char *base,
128 int baselen, struct exclude_list *which)
130 struct exclude *x;
131 size_t len;
132 int to_exclude = 1;
133 int flags = 0;
135 if (*string == '!') {
136 to_exclude = 0;
137 string++;
139 len = strlen(string);
140 if (len && string[len - 1] == '/') {
141 char *s;
142 x = xmalloc(sizeof(*x) + len);
143 s = (char*)(x+1);
144 memcpy(s, string, len - 1);
145 s[len - 1] = '\0';
146 string = s;
147 x->pattern = s;
148 flags = EXC_FLAG_MUSTBEDIR;
149 } else {
150 x = xmalloc(sizeof(*x));
151 x->pattern = string;
153 x->to_exclude = to_exclude;
154 x->patternlen = strlen(string);
155 x->base = base;
156 x->baselen = baselen;
157 x->flags = flags;
158 if (!strchr(string, '/'))
159 x->flags |= EXC_FLAG_NODIR;
160 if (no_wildcard(string))
161 x->flags |= EXC_FLAG_NOWILDCARD;
162 if (*string == '*' && no_wildcard(string+1))
163 x->flags |= EXC_FLAG_ENDSWITH;
164 ALLOC_GROW(which->excludes, which->nr + 1, which->alloc);
165 which->excludes[which->nr++] = x;
168 static int add_excludes_from_file_1(const char *fname,
169 const char *base,
170 int baselen,
171 char **buf_p,
172 struct exclude_list *which)
174 struct stat st;
175 int fd, i;
176 size_t size;
177 char *buf, *entry;
179 fd = open(fname, O_RDONLY);
180 if (fd < 0 || fstat(fd, &st) < 0)
181 goto err;
182 size = xsize_t(st.st_size);
183 if (size == 0) {
184 close(fd);
185 return 0;
187 buf = xmalloc(size+1);
188 if (read_in_full(fd, buf, size) != size)
190 free(buf);
191 goto err;
193 close(fd);
195 if (buf_p)
196 *buf_p = buf;
197 buf[size++] = '\n';
198 entry = buf;
199 for (i = 0; i < size; i++) {
200 if (buf[i] == '\n') {
201 if (entry != buf + i && entry[0] != '#') {
202 buf[i - (i && buf[i-1] == '\r')] = 0;
203 add_exclude(entry, base, baselen, which);
205 entry = buf + i + 1;
208 return 0;
210 err:
211 if (0 <= fd)
212 close(fd);
213 return -1;
216 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
218 if (add_excludes_from_file_1(fname, "", 0, NULL,
219 &dir->exclude_list[EXC_FILE]) < 0)
220 die("cannot use %s as an exclude file", fname);
223 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
225 struct exclude_list *el;
226 struct exclude_stack *stk = NULL;
227 int current;
229 if ((!dir->exclude_per_dir) ||
230 (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
231 return; /* too long a path -- ignore */
233 /* Pop the ones that are not the prefix of the path being checked. */
234 el = &dir->exclude_list[EXC_DIRS];
235 while ((stk = dir->exclude_stack) != NULL) {
236 if (stk->baselen <= baselen &&
237 !strncmp(dir->basebuf, base, stk->baselen))
238 break;
239 dir->exclude_stack = stk->prev;
240 while (stk->exclude_ix < el->nr)
241 free(el->excludes[--el->nr]);
242 free(stk->filebuf);
243 free(stk);
246 /* Read from the parent directories and push them down. */
247 current = stk ? stk->baselen : -1;
248 while (current < baselen) {
249 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
250 const char *cp;
252 if (current < 0) {
253 cp = base;
254 current = 0;
256 else {
257 cp = strchr(base + current + 1, '/');
258 if (!cp)
259 die("oops in prep_exclude");
260 cp++;
262 stk->prev = dir->exclude_stack;
263 stk->baselen = cp - base;
264 stk->exclude_ix = el->nr;
265 memcpy(dir->basebuf + current, base + current,
266 stk->baselen - current);
267 strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
268 add_excludes_from_file_1(dir->basebuf,
269 dir->basebuf, stk->baselen,
270 &stk->filebuf, el);
271 dir->exclude_stack = stk;
272 current = stk->baselen;
274 dir->basebuf[baselen] = '\0';
277 /* Scan the list and let the last match determines the fate.
278 * Return 1 for exclude, 0 for include and -1 for undecided.
280 static int excluded_1(const char *pathname,
281 int pathlen, const char *basename, int *dtype,
282 struct exclude_list *el)
284 int i;
286 if (el->nr) {
287 for (i = el->nr - 1; 0 <= i; i--) {
288 struct exclude *x = el->excludes[i];
289 const char *exclude = x->pattern;
290 int to_exclude = x->to_exclude;
292 if (x->flags & EXC_FLAG_MUSTBEDIR) {
293 if (*dtype == DT_UNKNOWN)
294 *dtype = get_dtype(NULL, pathname);
295 if (*dtype != DT_DIR)
296 continue;
299 if (x->flags & EXC_FLAG_NODIR) {
300 /* match basename */
301 if (x->flags & EXC_FLAG_NOWILDCARD) {
302 if (!strcmp(exclude, basename))
303 return to_exclude;
304 } else if (x->flags & EXC_FLAG_ENDSWITH) {
305 if (x->patternlen - 1 <= pathlen &&
306 !strcmp(exclude + 1, pathname + pathlen - x->patternlen + 1))
307 return to_exclude;
308 } else {
309 if (fnmatch(exclude, basename, 0) == 0)
310 return to_exclude;
313 else {
314 /* match with FNM_PATHNAME:
315 * exclude has base (baselen long) implicitly
316 * in front of it.
318 int baselen = x->baselen;
319 if (*exclude == '/')
320 exclude++;
322 if (pathlen < baselen ||
323 (baselen && pathname[baselen-1] != '/') ||
324 strncmp(pathname, x->base, baselen))
325 continue;
327 if (x->flags & EXC_FLAG_NOWILDCARD) {
328 if (!strcmp(exclude, pathname + baselen))
329 return to_exclude;
330 } else {
331 if (fnmatch(exclude, pathname+baselen,
332 FNM_PATHNAME) == 0)
333 return to_exclude;
338 return -1; /* undecided */
341 int excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
343 int pathlen = strlen(pathname);
344 int st;
345 const char *basename = strrchr(pathname, '/');
346 basename = (basename) ? basename+1 : pathname;
348 prep_exclude(dir, pathname, basename-pathname);
349 for (st = EXC_CMDL; st <= EXC_FILE; st++) {
350 switch (excluded_1(pathname, pathlen, basename,
351 dtype_p, &dir->exclude_list[st])) {
352 case 0:
353 return 0;
354 case 1:
355 return 1;
358 return 0;
361 static struct dir_entry *dir_entry_new(const char *pathname, int len)
363 struct dir_entry *ent;
365 ent = xmalloc(sizeof(*ent) + len + 1);
366 ent->len = len;
367 memcpy(ent->name, pathname, len);
368 ent->name[len] = 0;
369 return ent;
372 struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
374 if (cache_name_exists(pathname, len))
375 return NULL;
377 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
378 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
381 struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
383 if (cache_name_pos(pathname, len) >= 0)
384 return NULL;
386 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
387 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
390 enum exist_status {
391 index_nonexistent = 0,
392 index_directory,
393 index_gitdir,
397 * The index sorts alphabetically by entry name, which
398 * means that a gitlink sorts as '\0' at the end, while
399 * a directory (which is defined not as an entry, but as
400 * the files it contains) will sort with the '/' at the
401 * end.
403 static enum exist_status directory_exists_in_index(const char *dirname, int len)
405 int pos = cache_name_pos(dirname, len);
406 if (pos < 0)
407 pos = -pos-1;
408 while (pos < active_nr) {
409 struct cache_entry *ce = active_cache[pos++];
410 unsigned char endchar;
412 if (strncmp(ce->name, dirname, len))
413 break;
414 endchar = ce->name[len];
415 if (endchar > '/')
416 break;
417 if (endchar == '/')
418 return index_directory;
419 if (!endchar && S_ISGITLINK(ce->ce_mode))
420 return index_gitdir;
422 return index_nonexistent;
426 * When we find a directory when traversing the filesystem, we
427 * have three distinct cases:
429 * - ignore it
430 * - see it as a directory
431 * - recurse into it
433 * and which one we choose depends on a combination of existing
434 * git index contents and the flags passed into the directory
435 * traversal routine.
437 * Case 1: If we *already* have entries in the index under that
438 * directory name, we always recurse into the directory to see
439 * all the files.
441 * Case 2: If we *already* have that directory name as a gitlink,
442 * we always continue to see it as a gitlink, regardless of whether
443 * there is an actual git directory there or not (it might not
444 * be checked out as a subproject!)
446 * Case 3: if we didn't have it in the index previously, we
447 * have a few sub-cases:
449 * (a) if "show_other_directories" is true, we show it as
450 * just a directory, unless "hide_empty_directories" is
451 * also true and the directory is empty, in which case
452 * we just ignore it entirely.
453 * (b) if it looks like a git directory, and we don't have
454 * 'no_gitlinks' set we treat it as a gitlink, and show it
455 * as a directory.
456 * (c) otherwise, we recurse into it.
458 enum directory_treatment {
459 show_directory,
460 ignore_directory,
461 recurse_into_directory,
464 static enum directory_treatment treat_directory(struct dir_struct *dir,
465 const char *dirname, int len,
466 const struct path_simplify *simplify)
468 /* The "len-1" is to strip the final '/' */
469 switch (directory_exists_in_index(dirname, len-1)) {
470 case index_directory:
471 return recurse_into_directory;
473 case index_gitdir:
474 if (dir->show_other_directories)
475 return ignore_directory;
476 return show_directory;
478 case index_nonexistent:
479 if (dir->show_other_directories)
480 break;
481 if (!dir->no_gitlinks) {
482 unsigned char sha1[20];
483 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
484 return show_directory;
486 return recurse_into_directory;
489 /* This is the "show_other_directories" case */
490 if (!dir->hide_empty_directories)
491 return show_directory;
492 if (!read_directory_recursive(dir, dirname, dirname, len, 1, simplify))
493 return ignore_directory;
494 return show_directory;
498 * This is an inexact early pruning of any recursive directory
499 * reading - if the path cannot possibly be in the pathspec,
500 * return true, and we'll skip it early.
502 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
504 if (simplify) {
505 for (;;) {
506 const char *match = simplify->path;
507 int len = simplify->len;
509 if (!match)
510 break;
511 if (len > pathlen)
512 len = pathlen;
513 if (!memcmp(path, match, len))
514 return 0;
515 simplify++;
517 return 1;
519 return 0;
522 static int in_pathspec(const char *path, int len, const struct path_simplify *simplify)
524 if (simplify) {
525 for (; simplify->path; simplify++) {
526 if (len == simplify->len
527 && !memcmp(path, simplify->path, len))
528 return 1;
531 return 0;
534 static int get_dtype(struct dirent *de, const char *path)
536 int dtype = de ? DTYPE(de) : DT_UNKNOWN;
537 struct stat st;
539 if (dtype != DT_UNKNOWN)
540 return dtype;
541 if (lstat(path, &st))
542 return dtype;
543 if (S_ISREG(st.st_mode))
544 return DT_REG;
545 if (S_ISDIR(st.st_mode))
546 return DT_DIR;
547 if (S_ISLNK(st.st_mode))
548 return DT_LNK;
549 return dtype;
553 * Read a directory tree. We currently ignore anything but
554 * directories, regular files and symlinks. That's because git
555 * doesn't handle them at all yet. Maybe that will change some
556 * day.
558 * Also, we ignore the name ".git" (even if it is not a directory).
559 * That likely will not change.
561 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)
563 DIR *fdir = opendir(path);
564 int contents = 0;
566 if (fdir) {
567 struct dirent *de;
568 char fullname[PATH_MAX + 1];
569 memcpy(fullname, base, baselen);
571 while ((de = readdir(fdir)) != NULL) {
572 int len, dtype;
573 int exclude;
575 if ((de->d_name[0] == '.') &&
576 (de->d_name[1] == 0 ||
577 !strcmp(de->d_name + 1, ".") ||
578 !strcmp(de->d_name + 1, "git")))
579 continue;
580 len = strlen(de->d_name);
581 /* Ignore overly long pathnames! */
582 if (len + baselen + 8 > sizeof(fullname))
583 continue;
584 memcpy(fullname + baselen, de->d_name, len+1);
585 if (simplify_away(fullname, baselen + len, simplify))
586 continue;
588 dtype = DTYPE(de);
589 exclude = excluded(dir, fullname, &dtype);
590 if (exclude && dir->collect_ignored
591 && in_pathspec(fullname, baselen + len, simplify))
592 dir_add_ignored(dir, fullname, baselen + len);
595 * Excluded? If we don't explicitly want to show
596 * ignored files, ignore it
598 if (exclude && !dir->show_ignored)
599 continue;
601 if (dtype == DT_UNKNOWN)
602 dtype = get_dtype(de, fullname);
605 * Do we want to see just the ignored files?
606 * We still need to recurse into directories,
607 * even if we don't ignore them, since the
608 * directory may contain files that we do..
610 if (!exclude && dir->show_ignored) {
611 if (dtype != DT_DIR)
612 continue;
615 switch (dtype) {
616 default:
617 continue;
618 case DT_DIR:
619 memcpy(fullname + baselen + len, "/", 2);
620 len++;
621 switch (treat_directory(dir, fullname, baselen + len, simplify)) {
622 case show_directory:
623 if (exclude != dir->show_ignored)
624 continue;
625 break;
626 case recurse_into_directory:
627 contents += read_directory_recursive(dir,
628 fullname, fullname, baselen + len, 0, simplify);
629 continue;
630 case ignore_directory:
631 continue;
633 break;
634 case DT_REG:
635 case DT_LNK:
636 break;
638 contents++;
639 if (check_only)
640 goto exit_early;
641 else
642 dir_add_name(dir, fullname, baselen + len);
644 exit_early:
645 closedir(fdir);
648 return contents;
651 static int cmp_name(const void *p1, const void *p2)
653 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
654 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
656 return cache_name_compare(e1->name, e1->len,
657 e2->name, e2->len);
661 * Return the length of the "simple" part of a path match limiter.
663 static int simple_length(const char *match)
665 const char special[256] = {
666 [0] = 1, ['?'] = 1,
667 ['\\'] = 1, ['*'] = 1,
668 ['['] = 1
670 int len = -1;
672 for (;;) {
673 unsigned char c = *match++;
674 len++;
675 if (special[c])
676 return len;
680 static struct path_simplify *create_simplify(const char **pathspec)
682 int nr, alloc = 0;
683 struct path_simplify *simplify = NULL;
685 if (!pathspec)
686 return NULL;
688 for (nr = 0 ; ; nr++) {
689 const char *match;
690 if (nr >= alloc) {
691 alloc = alloc_nr(alloc);
692 simplify = xrealloc(simplify, alloc * sizeof(*simplify));
694 match = *pathspec++;
695 if (!match)
696 break;
697 simplify[nr].path = match;
698 simplify[nr].len = simple_length(match);
700 simplify[nr].path = NULL;
701 simplify[nr].len = 0;
702 return simplify;
705 static void free_simplify(struct path_simplify *simplify)
707 free(simplify);
710 int read_directory(struct dir_struct *dir, const char *path, const char *base, int baselen, const char **pathspec)
712 struct path_simplify *simplify = create_simplify(pathspec);
714 read_directory_recursive(dir, path, base, baselen, 0, simplify);
715 free_simplify(simplify);
716 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
717 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
718 return dir->nr;
721 int file_exists(const char *f)
723 struct stat sb;
724 return lstat(f, &sb) == 0;
728 * get_relative_cwd() gets the prefix of the current working directory
729 * relative to 'dir'. If we are not inside 'dir', it returns NULL.
731 * As a convenience, it also returns NULL if 'dir' is already NULL. The
732 * reason for this behaviour is that it is natural for functions returning
733 * directory names to return NULL to say "this directory does not exist"
734 * or "this directory is invalid". These cases are usually handled the
735 * same as if the cwd is not inside 'dir' at all, so get_relative_cwd()
736 * returns NULL for both of them.
738 * Most notably, get_relative_cwd(buffer, size, get_git_work_tree())
739 * unifies the handling of "outside work tree" with "no work tree at all".
741 char *get_relative_cwd(char *buffer, int size, const char *dir)
743 char *cwd = buffer;
745 if (!dir)
746 return NULL;
747 if (!getcwd(buffer, size))
748 die("can't find the current directory: %s", strerror(errno));
750 if (!is_absolute_path(dir))
751 dir = make_absolute_path(dir);
753 while (*dir && *dir == *cwd) {
754 dir++;
755 cwd++;
757 if (*dir)
758 return NULL;
759 if (*cwd == '/')
760 return cwd + 1;
761 return cwd;
764 int is_inside_dir(const char *dir)
766 char buffer[PATH_MAX];
767 return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
770 int remove_dir_recursively(struct strbuf *path, int only_empty)
772 DIR *dir = opendir(path->buf);
773 struct dirent *e;
774 int ret = 0, original_len = path->len, len;
776 if (!dir)
777 return -1;
778 if (path->buf[original_len - 1] != '/')
779 strbuf_addch(path, '/');
781 len = path->len;
782 while ((e = readdir(dir)) != NULL) {
783 struct stat st;
784 if ((e->d_name[0] == '.') &&
785 ((e->d_name[1] == 0) ||
786 ((e->d_name[1] == '.') && e->d_name[2] == 0)))
787 continue; /* "." and ".." */
789 strbuf_setlen(path, len);
790 strbuf_addstr(path, e->d_name);
791 if (lstat(path->buf, &st))
792 ; /* fall thru */
793 else if (S_ISDIR(st.st_mode)) {
794 if (!remove_dir_recursively(path, only_empty))
795 continue; /* happy */
796 } else if (!only_empty && !unlink(path->buf))
797 continue; /* happy, too */
799 /* path too long, stat fails, or non-directory still exists */
800 ret = -1;
801 break;
803 closedir(dir);
805 strbuf_setlen(path, original_len);
806 if (!ret)
807 ret = rmdir(path->buf);
808 return ret;
811 void setup_standard_excludes(struct dir_struct *dir)
813 const char *path;
815 dir->exclude_per_dir = ".gitignore";
816 path = git_path("info/exclude");
817 if (!access(path, R_OK))
818 add_excludes_from_file(dir, path);
819 if (excludes_file && !access(excludes_file, R_OK))
820 add_excludes_from_file(dir, excludes_file);