remove pathspec_match, use match_pathspec instead
[alt-git.git] / dir.c
blobc50ecc8d692a2cb3b29b256e1bcf9eeeadbc2a57
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,
112 int prefix, char *seen)
114 int i, retval = 0;
116 if (!pathspec)
117 return 1;
119 name += prefix;
120 namelen -= prefix;
122 for (i = 0; pathspec[i] != NULL; i++) {
123 int how;
124 const char *match = pathspec[i] + prefix;
125 if (seen && seen[i] == MATCHED_EXACTLY)
126 continue;
127 how = match_one(match, name, namelen);
128 if (how) {
129 if (retval < how)
130 retval = how;
131 if (seen && seen[i] < how)
132 seen[i] = how;
135 return retval;
138 static int no_wildcard(const char *string)
140 return string[strcspn(string, "*?[{")] == '\0';
143 void add_exclude(const char *string, const char *base,
144 int baselen, struct exclude_list *which)
146 struct exclude *x;
147 size_t len;
148 int to_exclude = 1;
149 int flags = 0;
151 if (*string == '!') {
152 to_exclude = 0;
153 string++;
155 len = strlen(string);
156 if (len && string[len - 1] == '/') {
157 char *s;
158 x = xmalloc(sizeof(*x) + len);
159 s = (char*)(x+1);
160 memcpy(s, string, len - 1);
161 s[len - 1] = '\0';
162 string = s;
163 x->pattern = s;
164 flags = EXC_FLAG_MUSTBEDIR;
165 } else {
166 x = xmalloc(sizeof(*x));
167 x->pattern = string;
169 x->to_exclude = to_exclude;
170 x->patternlen = strlen(string);
171 x->base = base;
172 x->baselen = baselen;
173 x->flags = flags;
174 if (!strchr(string, '/'))
175 x->flags |= EXC_FLAG_NODIR;
176 if (no_wildcard(string))
177 x->flags |= EXC_FLAG_NOWILDCARD;
178 if (*string == '*' && no_wildcard(string+1))
179 x->flags |= EXC_FLAG_ENDSWITH;
180 ALLOC_GROW(which->excludes, which->nr + 1, which->alloc);
181 which->excludes[which->nr++] = x;
184 static int add_excludes_from_file_1(const char *fname,
185 const char *base,
186 int baselen,
187 char **buf_p,
188 struct exclude_list *which)
190 struct stat st;
191 int fd, i;
192 size_t size;
193 char *buf, *entry;
195 fd = open(fname, O_RDONLY);
196 if (fd < 0 || fstat(fd, &st) < 0)
197 goto err;
198 size = xsize_t(st.st_size);
199 if (size == 0) {
200 close(fd);
201 return 0;
203 buf = xmalloc(size+1);
204 if (read_in_full(fd, buf, size) != size)
206 free(buf);
207 goto err;
209 close(fd);
211 if (buf_p)
212 *buf_p = buf;
213 buf[size++] = '\n';
214 entry = buf;
215 for (i = 0; i < size; i++) {
216 if (buf[i] == '\n') {
217 if (entry != buf + i && entry[0] != '#') {
218 buf[i - (i && buf[i-1] == '\r')] = 0;
219 add_exclude(entry, base, baselen, which);
221 entry = buf + i + 1;
224 return 0;
226 err:
227 if (0 <= fd)
228 close(fd);
229 return -1;
232 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
234 if (add_excludes_from_file_1(fname, "", 0, NULL,
235 &dir->exclude_list[EXC_FILE]) < 0)
236 die("cannot use %s as an exclude file", fname);
239 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
241 struct exclude_list *el;
242 struct exclude_stack *stk = NULL;
243 int current;
245 if ((!dir->exclude_per_dir) ||
246 (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
247 return; /* too long a path -- ignore */
249 /* Pop the ones that are not the prefix of the path being checked. */
250 el = &dir->exclude_list[EXC_DIRS];
251 while ((stk = dir->exclude_stack) != NULL) {
252 if (stk->baselen <= baselen &&
253 !strncmp(dir->basebuf, base, stk->baselen))
254 break;
255 dir->exclude_stack = stk->prev;
256 while (stk->exclude_ix < el->nr)
257 free(el->excludes[--el->nr]);
258 free(stk->filebuf);
259 free(stk);
262 /* Read from the parent directories and push them down. */
263 current = stk ? stk->baselen : -1;
264 while (current < baselen) {
265 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
266 const char *cp;
268 if (current < 0) {
269 cp = base;
270 current = 0;
272 else {
273 cp = strchr(base + current + 1, '/');
274 if (!cp)
275 die("oops in prep_exclude");
276 cp++;
278 stk->prev = dir->exclude_stack;
279 stk->baselen = cp - base;
280 stk->exclude_ix = el->nr;
281 memcpy(dir->basebuf + current, base + current,
282 stk->baselen - current);
283 strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
284 add_excludes_from_file_1(dir->basebuf,
285 dir->basebuf, stk->baselen,
286 &stk->filebuf, el);
287 dir->exclude_stack = stk;
288 current = stk->baselen;
290 dir->basebuf[baselen] = '\0';
293 /* Scan the list and let the last match determines the fate.
294 * Return 1 for exclude, 0 for include and -1 for undecided.
296 static int excluded_1(const char *pathname,
297 int pathlen, const char *basename, int *dtype,
298 struct exclude_list *el)
300 int i;
302 if (el->nr) {
303 for (i = el->nr - 1; 0 <= i; i--) {
304 struct exclude *x = el->excludes[i];
305 const char *exclude = x->pattern;
306 int to_exclude = x->to_exclude;
308 if (x->flags & EXC_FLAG_MUSTBEDIR) {
309 if (*dtype == DT_UNKNOWN)
310 *dtype = get_dtype(NULL, pathname);
311 if (*dtype != DT_DIR)
312 continue;
315 if (x->flags & EXC_FLAG_NODIR) {
316 /* match basename */
317 if (x->flags & EXC_FLAG_NOWILDCARD) {
318 if (!strcmp(exclude, basename))
319 return to_exclude;
320 } else if (x->flags & EXC_FLAG_ENDSWITH) {
321 if (x->patternlen - 1 <= pathlen &&
322 !strcmp(exclude + 1, pathname + pathlen - x->patternlen + 1))
323 return to_exclude;
324 } else {
325 if (fnmatch(exclude, basename, 0) == 0)
326 return to_exclude;
329 else {
330 /* match with FNM_PATHNAME:
331 * exclude has base (baselen long) implicitly
332 * in front of it.
334 int baselen = x->baselen;
335 if (*exclude == '/')
336 exclude++;
338 if (pathlen < baselen ||
339 (baselen && pathname[baselen-1] != '/') ||
340 strncmp(pathname, x->base, baselen))
341 continue;
343 if (x->flags & EXC_FLAG_NOWILDCARD) {
344 if (!strcmp(exclude, pathname + baselen))
345 return to_exclude;
346 } else {
347 if (fnmatch(exclude, pathname+baselen,
348 FNM_PATHNAME) == 0)
349 return to_exclude;
354 return -1; /* undecided */
357 int excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
359 int pathlen = strlen(pathname);
360 int st;
361 const char *basename = strrchr(pathname, '/');
362 basename = (basename) ? basename+1 : pathname;
364 prep_exclude(dir, pathname, basename-pathname);
365 for (st = EXC_CMDL; st <= EXC_FILE; st++) {
366 switch (excluded_1(pathname, pathlen, basename,
367 dtype_p, &dir->exclude_list[st])) {
368 case 0:
369 return 0;
370 case 1:
371 return 1;
374 return 0;
377 static struct dir_entry *dir_entry_new(const char *pathname, int len)
379 struct dir_entry *ent;
381 ent = xmalloc(sizeof(*ent) + len + 1);
382 ent->len = len;
383 memcpy(ent->name, pathname, len);
384 ent->name[len] = 0;
385 return ent;
388 static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
390 if (cache_name_exists(pathname, len, ignore_case))
391 return NULL;
393 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
394 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
397 static struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
399 if (cache_name_pos(pathname, len) >= 0)
400 return NULL;
402 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
403 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
406 enum exist_status {
407 index_nonexistent = 0,
408 index_directory,
409 index_gitdir,
413 * The index sorts alphabetically by entry name, which
414 * means that a gitlink sorts as '\0' at the end, while
415 * a directory (which is defined not as an entry, but as
416 * the files it contains) will sort with the '/' at the
417 * end.
419 static enum exist_status directory_exists_in_index(const char *dirname, int len)
421 int pos = cache_name_pos(dirname, len);
422 if (pos < 0)
423 pos = -pos-1;
424 while (pos < active_nr) {
425 struct cache_entry *ce = active_cache[pos++];
426 unsigned char endchar;
428 if (strncmp(ce->name, dirname, len))
429 break;
430 endchar = ce->name[len];
431 if (endchar > '/')
432 break;
433 if (endchar == '/')
434 return index_directory;
435 if (!endchar && S_ISGITLINK(ce->ce_mode))
436 return index_gitdir;
438 return index_nonexistent;
442 * When we find a directory when traversing the filesystem, we
443 * have three distinct cases:
445 * - ignore it
446 * - see it as a directory
447 * - recurse into it
449 * and which one we choose depends on a combination of existing
450 * git index contents and the flags passed into the directory
451 * traversal routine.
453 * Case 1: If we *already* have entries in the index under that
454 * directory name, we always recurse into the directory to see
455 * all the files.
457 * Case 2: If we *already* have that directory name as a gitlink,
458 * we always continue to see it as a gitlink, regardless of whether
459 * there is an actual git directory there or not (it might not
460 * be checked out as a subproject!)
462 * Case 3: if we didn't have it in the index previously, we
463 * have a few sub-cases:
465 * (a) if "show_other_directories" is true, we show it as
466 * just a directory, unless "hide_empty_directories" is
467 * also true and the directory is empty, in which case
468 * we just ignore it entirely.
469 * (b) if it looks like a git directory, and we don't have
470 * 'no_gitlinks' set we treat it as a gitlink, and show it
471 * as a directory.
472 * (c) otherwise, we recurse into it.
474 enum directory_treatment {
475 show_directory,
476 ignore_directory,
477 recurse_into_directory,
480 static enum directory_treatment treat_directory(struct dir_struct *dir,
481 const char *dirname, int len,
482 const struct path_simplify *simplify)
484 /* The "len-1" is to strip the final '/' */
485 switch (directory_exists_in_index(dirname, len-1)) {
486 case index_directory:
487 return recurse_into_directory;
489 case index_gitdir:
490 if (dir->show_other_directories)
491 return ignore_directory;
492 return show_directory;
494 case index_nonexistent:
495 if (dir->show_other_directories)
496 break;
497 if (!dir->no_gitlinks) {
498 unsigned char sha1[20];
499 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
500 return show_directory;
502 return recurse_into_directory;
505 /* This is the "show_other_directories" case */
506 if (!dir->hide_empty_directories)
507 return show_directory;
508 if (!read_directory_recursive(dir, dirname, dirname, len, 1, simplify))
509 return ignore_directory;
510 return show_directory;
514 * This is an inexact early pruning of any recursive directory
515 * reading - if the path cannot possibly be in the pathspec,
516 * return true, and we'll skip it early.
518 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
520 if (simplify) {
521 for (;;) {
522 const char *match = simplify->path;
523 int len = simplify->len;
525 if (!match)
526 break;
527 if (len > pathlen)
528 len = pathlen;
529 if (!memcmp(path, match, len))
530 return 0;
531 simplify++;
533 return 1;
535 return 0;
538 static int in_pathspec(const char *path, int len, const struct path_simplify *simplify)
540 if (simplify) {
541 for (; simplify->path; simplify++) {
542 if (len == simplify->len
543 && !memcmp(path, simplify->path, len))
544 return 1;
547 return 0;
550 static int get_dtype(struct dirent *de, const char *path)
552 int dtype = de ? DTYPE(de) : DT_UNKNOWN;
553 struct stat st;
555 if (dtype != DT_UNKNOWN)
556 return dtype;
557 if (lstat(path, &st))
558 return dtype;
559 if (S_ISREG(st.st_mode))
560 return DT_REG;
561 if (S_ISDIR(st.st_mode))
562 return DT_DIR;
563 if (S_ISLNK(st.st_mode))
564 return DT_LNK;
565 return dtype;
569 * Read a directory tree. We currently ignore anything but
570 * directories, regular files and symlinks. That's because git
571 * doesn't handle them at all yet. Maybe that will change some
572 * day.
574 * Also, we ignore the name ".git" (even if it is not a directory).
575 * That likely will not change.
577 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)
579 DIR *fdir = opendir(path);
580 int contents = 0;
582 if (fdir) {
583 struct dirent *de;
584 char fullname[PATH_MAX + 1];
585 memcpy(fullname, base, baselen);
587 while ((de = readdir(fdir)) != NULL) {
588 int len, dtype;
589 int exclude;
591 if ((de->d_name[0] == '.') &&
592 (de->d_name[1] == 0 ||
593 !strcmp(de->d_name + 1, ".") ||
594 !strcmp(de->d_name + 1, "git")))
595 continue;
596 len = strlen(de->d_name);
597 /* Ignore overly long pathnames! */
598 if (len + baselen + 8 > sizeof(fullname))
599 continue;
600 memcpy(fullname + baselen, de->d_name, len+1);
601 if (simplify_away(fullname, baselen + len, simplify))
602 continue;
604 dtype = DTYPE(de);
605 exclude = excluded(dir, fullname, &dtype);
606 if (exclude && dir->collect_ignored
607 && in_pathspec(fullname, baselen + len, simplify))
608 dir_add_ignored(dir, fullname, baselen + len);
611 * Excluded? If we don't explicitly want to show
612 * ignored files, ignore it
614 if (exclude && !dir->show_ignored)
615 continue;
617 if (dtype == DT_UNKNOWN)
618 dtype = get_dtype(de, fullname);
621 * Do we want to see just the ignored files?
622 * We still need to recurse into directories,
623 * even if we don't ignore them, since the
624 * directory may contain files that we do..
626 if (!exclude && dir->show_ignored) {
627 if (dtype != DT_DIR)
628 continue;
631 switch (dtype) {
632 default:
633 continue;
634 case DT_DIR:
635 memcpy(fullname + baselen + len, "/", 2);
636 len++;
637 switch (treat_directory(dir, fullname, baselen + len, simplify)) {
638 case show_directory:
639 if (exclude != dir->show_ignored)
640 continue;
641 break;
642 case recurse_into_directory:
643 contents += read_directory_recursive(dir,
644 fullname, fullname, baselen + len, 0, simplify);
645 continue;
646 case ignore_directory:
647 continue;
649 break;
650 case DT_REG:
651 case DT_LNK:
652 break;
654 contents++;
655 if (check_only)
656 goto exit_early;
657 else
658 dir_add_name(dir, fullname, baselen + len);
660 exit_early:
661 closedir(fdir);
664 return contents;
667 static int cmp_name(const void *p1, const void *p2)
669 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
670 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
672 return cache_name_compare(e1->name, e1->len,
673 e2->name, e2->len);
677 * Return the length of the "simple" part of a path match limiter.
679 static int simple_length(const char *match)
681 int len = -1;
683 for (;;) {
684 unsigned char c = *match++;
685 len++;
686 if (isspecial(c))
687 return len;
691 static struct path_simplify *create_simplify(const char **pathspec)
693 int nr, alloc = 0;
694 struct path_simplify *simplify = NULL;
696 if (!pathspec)
697 return NULL;
699 for (nr = 0 ; ; nr++) {
700 const char *match;
701 if (nr >= alloc) {
702 alloc = alloc_nr(alloc);
703 simplify = xrealloc(simplify, alloc * sizeof(*simplify));
705 match = *pathspec++;
706 if (!match)
707 break;
708 simplify[nr].path = match;
709 simplify[nr].len = simple_length(match);
711 simplify[nr].path = NULL;
712 simplify[nr].len = 0;
713 return simplify;
716 static void free_simplify(struct path_simplify *simplify)
718 free(simplify);
721 int read_directory(struct dir_struct *dir, const char *path, const char *base, int baselen, const char **pathspec)
723 struct path_simplify *simplify;
725 if (has_symlink_leading_path(strlen(path), path))
726 return dir->nr;
728 simplify = create_simplify(pathspec);
729 read_directory_recursive(dir, path, base, baselen, 0, simplify);
730 free_simplify(simplify);
731 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
732 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
733 return dir->nr;
736 int file_exists(const char *f)
738 struct stat sb;
739 return lstat(f, &sb) == 0;
743 * get_relative_cwd() gets the prefix of the current working directory
744 * relative to 'dir'. If we are not inside 'dir', it returns NULL.
746 * As a convenience, it also returns NULL if 'dir' is already NULL. The
747 * reason for this behaviour is that it is natural for functions returning
748 * directory names to return NULL to say "this directory does not exist"
749 * or "this directory is invalid". These cases are usually handled the
750 * same as if the cwd is not inside 'dir' at all, so get_relative_cwd()
751 * returns NULL for both of them.
753 * Most notably, get_relative_cwd(buffer, size, get_git_work_tree())
754 * unifies the handling of "outside work tree" with "no work tree at all".
756 char *get_relative_cwd(char *buffer, int size, const char *dir)
758 char *cwd = buffer;
760 if (!dir)
761 return NULL;
762 if (!getcwd(buffer, size))
763 die("can't find the current directory: %s", strerror(errno));
765 if (!is_absolute_path(dir))
766 dir = make_absolute_path(dir);
768 while (*dir && *dir == *cwd) {
769 dir++;
770 cwd++;
772 if (*dir)
773 return NULL;
774 if (*cwd == '/')
775 return cwd + 1;
776 return cwd;
779 int is_inside_dir(const char *dir)
781 char buffer[PATH_MAX];
782 return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
785 int remove_dir_recursively(struct strbuf *path, int only_empty)
787 DIR *dir = opendir(path->buf);
788 struct dirent *e;
789 int ret = 0, original_len = path->len, len;
791 if (!dir)
792 return -1;
793 if (path->buf[original_len - 1] != '/')
794 strbuf_addch(path, '/');
796 len = path->len;
797 while ((e = readdir(dir)) != NULL) {
798 struct stat st;
799 if ((e->d_name[0] == '.') &&
800 ((e->d_name[1] == 0) ||
801 ((e->d_name[1] == '.') && e->d_name[2] == 0)))
802 continue; /* "." and ".." */
804 strbuf_setlen(path, len);
805 strbuf_addstr(path, e->d_name);
806 if (lstat(path->buf, &st))
807 ; /* fall thru */
808 else if (S_ISDIR(st.st_mode)) {
809 if (!remove_dir_recursively(path, only_empty))
810 continue; /* happy */
811 } else if (!only_empty && !unlink(path->buf))
812 continue; /* happy, too */
814 /* path too long, stat fails, or non-directory still exists */
815 ret = -1;
816 break;
818 closedir(dir);
820 strbuf_setlen(path, original_len);
821 if (!ret)
822 ret = rmdir(path->buf);
823 return ret;
826 void setup_standard_excludes(struct dir_struct *dir)
828 const char *path;
830 dir->exclude_per_dir = ".gitignore";
831 path = git_path("info/exclude");
832 if (!access(path, R_OK))
833 add_excludes_from_file(dir, path);
834 if (excludes_file && !access(excludes_file, R_OK))
835 add_excludes_from_file(dir, excludes_file);
838 int remove_path(const char *name)
840 char *slash;
842 if (unlink(name) && errno != ENOENT)
843 return -1;
845 slash = strrchr(name, '/');
846 if (slash) {
847 char *dirs = xstrdup(name);
848 slash = dirs + (slash - name);
849 do {
850 *slash = '\0';
851 } while (rmdir(dirs) && (slash = strrchr(dirs, '/')));
852 free(dirs);
854 return 0;