sha1_name: support @{-N} syntax in get_sha1()
[git/dscho.git] / dir.c
blob0131983dfbc143ce5dae77e067663bb2e7d5f126
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 if (!*match)
73 return MATCHED_RECURSIVELY;
75 for (;;) {
76 unsigned char c1 = *match;
77 unsigned char c2 = *name;
78 if (isspecial(c1))
79 break;
80 if (c1 != c2)
81 return 0;
82 match++;
83 name++;
84 namelen--;
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;
100 return 0;
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, int prefix, char *seen)
113 int retval;
114 const char *match;
116 name += prefix;
117 namelen -= prefix;
119 for (retval = 0; (match = *pathspec++) != NULL; seen++) {
120 int how;
121 if (retval && *seen == MATCHED_EXACTLY)
122 continue;
123 match += prefix;
124 how = match_one(match, name, namelen);
125 if (how) {
126 if (retval < how)
127 retval = how;
128 if (*seen < how)
129 *seen = how;
132 return retval;
135 static int no_wildcard(const char *string)
137 return string[strcspn(string, "*?[{")] == '\0';
140 void add_exclude(const char *string, const char *base,
141 int baselen, struct exclude_list *which)
143 struct exclude *x;
144 size_t len;
145 int to_exclude = 1;
146 int flags = 0;
148 if (*string == '!') {
149 to_exclude = 0;
150 string++;
152 len = strlen(string);
153 if (len && string[len - 1] == '/') {
154 char *s;
155 x = xmalloc(sizeof(*x) + len);
156 s = (char*)(x+1);
157 memcpy(s, string, len - 1);
158 s[len - 1] = '\0';
159 string = s;
160 x->pattern = s;
161 flags = EXC_FLAG_MUSTBEDIR;
162 } else {
163 x = xmalloc(sizeof(*x));
164 x->pattern = string;
166 x->to_exclude = to_exclude;
167 x->patternlen = strlen(string);
168 x->base = base;
169 x->baselen = baselen;
170 x->flags = flags;
171 if (!strchr(string, '/'))
172 x->flags |= EXC_FLAG_NODIR;
173 if (no_wildcard(string))
174 x->flags |= EXC_FLAG_NOWILDCARD;
175 if (*string == '*' && no_wildcard(string+1))
176 x->flags |= EXC_FLAG_ENDSWITH;
177 ALLOC_GROW(which->excludes, which->nr + 1, which->alloc);
178 which->excludes[which->nr++] = x;
181 static int add_excludes_from_file_1(const char *fname,
182 const char *base,
183 int baselen,
184 char **buf_p,
185 struct exclude_list *which)
187 struct stat st;
188 int fd, i;
189 size_t size;
190 char *buf, *entry;
192 fd = open(fname, O_RDONLY);
193 if (fd < 0 || fstat(fd, &st) < 0)
194 goto err;
195 size = xsize_t(st.st_size);
196 if (size == 0) {
197 close(fd);
198 return 0;
200 buf = xmalloc(size+1);
201 if (read_in_full(fd, buf, size) != size)
203 free(buf);
204 goto err;
206 close(fd);
208 if (buf_p)
209 *buf_p = buf;
210 buf[size++] = '\n';
211 entry = buf;
212 for (i = 0; i < size; i++) {
213 if (buf[i] == '\n') {
214 if (entry != buf + i && entry[0] != '#') {
215 buf[i - (i && buf[i-1] == '\r')] = 0;
216 add_exclude(entry, base, baselen, which);
218 entry = buf + i + 1;
221 return 0;
223 err:
224 if (0 <= fd)
225 close(fd);
226 return -1;
229 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
231 if (add_excludes_from_file_1(fname, "", 0, NULL,
232 &dir->exclude_list[EXC_FILE]) < 0)
233 die("cannot use %s as an exclude file", fname);
236 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
238 struct exclude_list *el;
239 struct exclude_stack *stk = NULL;
240 int current;
242 if ((!dir->exclude_per_dir) ||
243 (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
244 return; /* too long a path -- ignore */
246 /* Pop the ones that are not the prefix of the path being checked. */
247 el = &dir->exclude_list[EXC_DIRS];
248 while ((stk = dir->exclude_stack) != NULL) {
249 if (stk->baselen <= baselen &&
250 !strncmp(dir->basebuf, base, stk->baselen))
251 break;
252 dir->exclude_stack = stk->prev;
253 while (stk->exclude_ix < el->nr)
254 free(el->excludes[--el->nr]);
255 free(stk->filebuf);
256 free(stk);
259 /* Read from the parent directories and push them down. */
260 current = stk ? stk->baselen : -1;
261 while (current < baselen) {
262 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
263 const char *cp;
265 if (current < 0) {
266 cp = base;
267 current = 0;
269 else {
270 cp = strchr(base + current + 1, '/');
271 if (!cp)
272 die("oops in prep_exclude");
273 cp++;
275 stk->prev = dir->exclude_stack;
276 stk->baselen = cp - base;
277 stk->exclude_ix = el->nr;
278 memcpy(dir->basebuf + current, base + current,
279 stk->baselen - current);
280 strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
281 add_excludes_from_file_1(dir->basebuf,
282 dir->basebuf, stk->baselen,
283 &stk->filebuf, el);
284 dir->exclude_stack = stk;
285 current = stk->baselen;
287 dir->basebuf[baselen] = '\0';
290 /* Scan the list and let the last match determines the fate.
291 * Return 1 for exclude, 0 for include and -1 for undecided.
293 static int excluded_1(const char *pathname,
294 int pathlen, const char *basename, int *dtype,
295 struct exclude_list *el)
297 int i;
299 if (el->nr) {
300 for (i = el->nr - 1; 0 <= i; i--) {
301 struct exclude *x = el->excludes[i];
302 const char *exclude = x->pattern;
303 int to_exclude = x->to_exclude;
305 if (x->flags & EXC_FLAG_MUSTBEDIR) {
306 if (*dtype == DT_UNKNOWN)
307 *dtype = get_dtype(NULL, pathname);
308 if (*dtype != DT_DIR)
309 continue;
312 if (x->flags & EXC_FLAG_NODIR) {
313 /* match basename */
314 if (x->flags & EXC_FLAG_NOWILDCARD) {
315 if (!strcmp(exclude, basename))
316 return to_exclude;
317 } else if (x->flags & EXC_FLAG_ENDSWITH) {
318 if (x->patternlen - 1 <= pathlen &&
319 !strcmp(exclude + 1, pathname + pathlen - x->patternlen + 1))
320 return to_exclude;
321 } else {
322 if (fnmatch(exclude, basename, 0) == 0)
323 return to_exclude;
326 else {
327 /* match with FNM_PATHNAME:
328 * exclude has base (baselen long) implicitly
329 * in front of it.
331 int baselen = x->baselen;
332 if (*exclude == '/')
333 exclude++;
335 if (pathlen < baselen ||
336 (baselen && pathname[baselen-1] != '/') ||
337 strncmp(pathname, x->base, baselen))
338 continue;
340 if (x->flags & EXC_FLAG_NOWILDCARD) {
341 if (!strcmp(exclude, pathname + baselen))
342 return to_exclude;
343 } else {
344 if (fnmatch(exclude, pathname+baselen,
345 FNM_PATHNAME) == 0)
346 return to_exclude;
351 return -1; /* undecided */
354 int excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
356 int pathlen = strlen(pathname);
357 int st;
358 const char *basename = strrchr(pathname, '/');
359 basename = (basename) ? basename+1 : pathname;
361 prep_exclude(dir, pathname, basename-pathname);
362 for (st = EXC_CMDL; st <= EXC_FILE; st++) {
363 switch (excluded_1(pathname, pathlen, basename,
364 dtype_p, &dir->exclude_list[st])) {
365 case 0:
366 return 0;
367 case 1:
368 return 1;
371 return 0;
374 static struct dir_entry *dir_entry_new(const char *pathname, int len)
376 struct dir_entry *ent;
378 ent = xmalloc(sizeof(*ent) + len + 1);
379 ent->len = len;
380 memcpy(ent->name, pathname, len);
381 ent->name[len] = 0;
382 return ent;
385 static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
387 if (cache_name_exists(pathname, len, ignore_case))
388 return NULL;
390 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
391 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
394 static struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
396 if (cache_name_pos(pathname, len) >= 0)
397 return NULL;
399 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
400 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
403 enum exist_status {
404 index_nonexistent = 0,
405 index_directory,
406 index_gitdir,
410 * The index sorts alphabetically by entry name, which
411 * means that a gitlink sorts as '\0' at the end, while
412 * a directory (which is defined not as an entry, but as
413 * the files it contains) will sort with the '/' at the
414 * end.
416 static enum exist_status directory_exists_in_index(const char *dirname, int len)
418 int pos = cache_name_pos(dirname, len);
419 if (pos < 0)
420 pos = -pos-1;
421 while (pos < active_nr) {
422 struct cache_entry *ce = active_cache[pos++];
423 unsigned char endchar;
425 if (strncmp(ce->name, dirname, len))
426 break;
427 endchar = ce->name[len];
428 if (endchar > '/')
429 break;
430 if (endchar == '/')
431 return index_directory;
432 if (!endchar && S_ISGITLINK(ce->ce_mode))
433 return index_gitdir;
435 return index_nonexistent;
439 * When we find a directory when traversing the filesystem, we
440 * have three distinct cases:
442 * - ignore it
443 * - see it as a directory
444 * - recurse into it
446 * and which one we choose depends on a combination of existing
447 * git index contents and the flags passed into the directory
448 * traversal routine.
450 * Case 1: If we *already* have entries in the index under that
451 * directory name, we always recurse into the directory to see
452 * all the files.
454 * Case 2: If we *already* have that directory name as a gitlink,
455 * we always continue to see it as a gitlink, regardless of whether
456 * there is an actual git directory there or not (it might not
457 * be checked out as a subproject!)
459 * Case 3: if we didn't have it in the index previously, we
460 * have a few sub-cases:
462 * (a) if "show_other_directories" is true, we show it as
463 * just a directory, unless "hide_empty_directories" is
464 * also true and the directory is empty, in which case
465 * we just ignore it entirely.
466 * (b) if it looks like a git directory, and we don't have
467 * 'no_gitlinks' set we treat it as a gitlink, and show it
468 * as a directory.
469 * (c) otherwise, we recurse into it.
471 enum directory_treatment {
472 show_directory,
473 ignore_directory,
474 recurse_into_directory,
477 static enum directory_treatment treat_directory(struct dir_struct *dir,
478 const char *dirname, int len,
479 const struct path_simplify *simplify)
481 /* The "len-1" is to strip the final '/' */
482 switch (directory_exists_in_index(dirname, len-1)) {
483 case index_directory:
484 return recurse_into_directory;
486 case index_gitdir:
487 if (dir->show_other_directories)
488 return ignore_directory;
489 return show_directory;
491 case index_nonexistent:
492 if (dir->show_other_directories)
493 break;
494 if (!dir->no_gitlinks) {
495 unsigned char sha1[20];
496 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
497 return show_directory;
499 return recurse_into_directory;
502 /* This is the "show_other_directories" case */
503 if (!dir->hide_empty_directories)
504 return show_directory;
505 if (!read_directory_recursive(dir, dirname, dirname, len, 1, simplify))
506 return ignore_directory;
507 return show_directory;
511 * This is an inexact early pruning of any recursive directory
512 * reading - if the path cannot possibly be in the pathspec,
513 * return true, and we'll skip it early.
515 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
517 if (simplify) {
518 for (;;) {
519 const char *match = simplify->path;
520 int len = simplify->len;
522 if (!match)
523 break;
524 if (len > pathlen)
525 len = pathlen;
526 if (!memcmp(path, match, len))
527 return 0;
528 simplify++;
530 return 1;
532 return 0;
535 static int in_pathspec(const char *path, int len, const struct path_simplify *simplify)
537 if (simplify) {
538 for (; simplify->path; simplify++) {
539 if (len == simplify->len
540 && !memcmp(path, simplify->path, len))
541 return 1;
544 return 0;
547 static int get_dtype(struct dirent *de, const char *path)
549 int dtype = de ? DTYPE(de) : DT_UNKNOWN;
550 struct stat st;
552 if (dtype != DT_UNKNOWN)
553 return dtype;
554 if (lstat(path, &st))
555 return dtype;
556 if (S_ISREG(st.st_mode))
557 return DT_REG;
558 if (S_ISDIR(st.st_mode))
559 return DT_DIR;
560 if (S_ISLNK(st.st_mode))
561 return DT_LNK;
562 return dtype;
566 * Read a directory tree. We currently ignore anything but
567 * directories, regular files and symlinks. That's because git
568 * doesn't handle them at all yet. Maybe that will change some
569 * day.
571 * Also, we ignore the name ".git" (even if it is not a directory).
572 * That likely will not change.
574 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)
576 DIR *fdir = opendir(path);
577 int contents = 0;
579 if (fdir) {
580 struct dirent *de;
581 char fullname[PATH_MAX + 1];
582 memcpy(fullname, base, baselen);
584 while ((de = readdir(fdir)) != NULL) {
585 int len, dtype;
586 int exclude;
588 if ((de->d_name[0] == '.') &&
589 (de->d_name[1] == 0 ||
590 !strcmp(de->d_name + 1, ".") ||
591 !strcmp(de->d_name + 1, "git")))
592 continue;
593 len = strlen(de->d_name);
594 /* Ignore overly long pathnames! */
595 if (len + baselen + 8 > sizeof(fullname))
596 continue;
597 memcpy(fullname + baselen, de->d_name, len+1);
598 if (simplify_away(fullname, baselen + len, simplify))
599 continue;
601 dtype = DTYPE(de);
602 exclude = excluded(dir, fullname, &dtype);
603 if (exclude && dir->collect_ignored
604 && in_pathspec(fullname, baselen + len, simplify))
605 dir_add_ignored(dir, fullname, baselen + len);
608 * Excluded? If we don't explicitly want to show
609 * ignored files, ignore it
611 if (exclude && !dir->show_ignored)
612 continue;
614 if (dtype == DT_UNKNOWN)
615 dtype = get_dtype(de, fullname);
618 * Do we want to see just the ignored files?
619 * We still need to recurse into directories,
620 * even if we don't ignore them, since the
621 * directory may contain files that we do..
623 if (!exclude && dir->show_ignored) {
624 if (dtype != DT_DIR)
625 continue;
628 switch (dtype) {
629 default:
630 continue;
631 case DT_DIR:
632 memcpy(fullname + baselen + len, "/", 2);
633 len++;
634 switch (treat_directory(dir, fullname, baselen + len, simplify)) {
635 case show_directory:
636 if (exclude != dir->show_ignored)
637 continue;
638 break;
639 case recurse_into_directory:
640 contents += read_directory_recursive(dir,
641 fullname, fullname, baselen + len, 0, simplify);
642 continue;
643 case ignore_directory:
644 continue;
646 break;
647 case DT_REG:
648 case DT_LNK:
649 break;
651 contents++;
652 if (check_only)
653 goto exit_early;
654 else
655 dir_add_name(dir, fullname, baselen + len);
657 exit_early:
658 closedir(fdir);
661 return contents;
664 static int cmp_name(const void *p1, const void *p2)
666 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
667 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
669 return cache_name_compare(e1->name, e1->len,
670 e2->name, e2->len);
674 * Return the length of the "simple" part of a path match limiter.
676 static int simple_length(const char *match)
678 int len = -1;
680 for (;;) {
681 unsigned char c = *match++;
682 len++;
683 if (isspecial(c))
684 return len;
688 static struct path_simplify *create_simplify(const char **pathspec)
690 int nr, alloc = 0;
691 struct path_simplify *simplify = NULL;
693 if (!pathspec)
694 return NULL;
696 for (nr = 0 ; ; nr++) {
697 const char *match;
698 if (nr >= alloc) {
699 alloc = alloc_nr(alloc);
700 simplify = xrealloc(simplify, alloc * sizeof(*simplify));
702 match = *pathspec++;
703 if (!match)
704 break;
705 simplify[nr].path = match;
706 simplify[nr].len = simple_length(match);
708 simplify[nr].path = NULL;
709 simplify[nr].len = 0;
710 return simplify;
713 static void free_simplify(struct path_simplify *simplify)
715 free(simplify);
718 int read_directory(struct dir_struct *dir, const char *path, const char *base, int baselen, const char **pathspec)
720 struct path_simplify *simplify;
722 if (has_symlink_leading_path(strlen(path), path))
723 return dir->nr;
725 simplify = create_simplify(pathspec);
726 read_directory_recursive(dir, path, base, baselen, 0, simplify);
727 free_simplify(simplify);
728 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
729 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
730 return dir->nr;
733 int file_exists(const char *f)
735 struct stat sb;
736 return lstat(f, &sb) == 0;
740 * get_relative_cwd() gets the prefix of the current working directory
741 * relative to 'dir'. If we are not inside 'dir', it returns NULL.
743 * As a convenience, it also returns NULL if 'dir' is already NULL. The
744 * reason for this behaviour is that it is natural for functions returning
745 * directory names to return NULL to say "this directory does not exist"
746 * or "this directory is invalid". These cases are usually handled the
747 * same as if the cwd is not inside 'dir' at all, so get_relative_cwd()
748 * returns NULL for both of them.
750 * Most notably, get_relative_cwd(buffer, size, get_git_work_tree())
751 * unifies the handling of "outside work tree" with "no work tree at all".
753 char *get_relative_cwd(char *buffer, int size, const char *dir)
755 char *cwd = buffer;
757 if (!dir)
758 return NULL;
759 if (!getcwd(buffer, size))
760 die("can't find the current directory: %s", strerror(errno));
762 if (!is_absolute_path(dir))
763 dir = make_absolute_path(dir);
765 while (*dir && *dir == *cwd) {
766 dir++;
767 cwd++;
769 if (*dir)
770 return NULL;
771 if (*cwd == '/')
772 return cwd + 1;
773 return cwd;
776 int is_inside_dir(const char *dir)
778 char buffer[PATH_MAX];
779 return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
782 int remove_dir_recursively(struct strbuf *path, int only_empty)
784 DIR *dir = opendir(path->buf);
785 struct dirent *e;
786 int ret = 0, original_len = path->len, len;
788 if (!dir)
789 return -1;
790 if (path->buf[original_len - 1] != '/')
791 strbuf_addch(path, '/');
793 len = path->len;
794 while ((e = readdir(dir)) != NULL) {
795 struct stat st;
796 if ((e->d_name[0] == '.') &&
797 ((e->d_name[1] == 0) ||
798 ((e->d_name[1] == '.') && e->d_name[2] == 0)))
799 continue; /* "." and ".." */
801 strbuf_setlen(path, len);
802 strbuf_addstr(path, e->d_name);
803 if (lstat(path->buf, &st))
804 ; /* fall thru */
805 else if (S_ISDIR(st.st_mode)) {
806 if (!remove_dir_recursively(path, only_empty))
807 continue; /* happy */
808 } else if (!only_empty && !unlink(path->buf))
809 continue; /* happy, too */
811 /* path too long, stat fails, or non-directory still exists */
812 ret = -1;
813 break;
815 closedir(dir);
817 strbuf_setlen(path, original_len);
818 if (!ret)
819 ret = rmdir(path->buf);
820 return ret;
823 void setup_standard_excludes(struct dir_struct *dir)
825 const char *path;
827 dir->exclude_per_dir = ".gitignore";
828 path = git_path("info/exclude");
829 if (!access(path, R_OK))
830 add_excludes_from_file(dir, path);
831 if (excludes_file && !access(excludes_file, R_OK))
832 add_excludes_from_file(dir, excludes_file);
835 int remove_path(const char *name)
837 char *slash;
839 if (unlink(name) && errno != ENOENT)
840 return -1;
842 slash = strrchr(name, '/');
843 if (slash) {
844 char *dirs = xstrdup(name);
845 slash = dirs + (slash - name);
846 do {
847 *slash = '\0';
848 } while (rmdir(dirs) && (slash = strrchr(dirs, '/')));
849 free(dirs);
851 return 0;