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"
11
12struct path_simplify {
13 int len;
14 const char *path;
15};
16
17static 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
21int common_prefix(const char **pathspec)
22{
23 const char *path, *slash, *next;
24 int prefix;
25
26 if (!pathspec)
27 return 0;
28
29 path = *pathspec;
30 slash = strrchr(path, '/');
31 if (!slash)
32 return 0;
33
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}
53
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 */
66static int match_one(const char *match, const char *name, int namelen)
67{
68 int matchlen;
69
70 /* If the match was just the prefix, we matched */
71 matchlen = strlen(match);
72 if (!matchlen)
73 return MATCHED_RECURSIVELY;
74
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;
81
82 if (!name[matchlen])
83 return MATCHED_EXACTLY;
84 if (match[matchlen-1] == '/' || name[matchlen] == '/')
85 return MATCHED_RECURSIVELY;
86 return 0;
87}
88
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 */
97int match_pathspec(const char **pathspec, const char *name, int namelen, int prefix, char *seen)
98{
99 int retval;
100 const char *match;
101
102 name += prefix;
103 namelen -= prefix;
104
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}
120
121static int no_wildcard(const char *string)
122{
123 return string[strcspn(string, "*?[{")] == '\0';
124}
125
126void add_exclude(const char *string, const char *base,
127 int baselen, struct exclude_list *which)
128{
129 struct exclude *x = xmalloc(sizeof (*x));
130
131 x->to_exclude = 1;
132 if (*string == '!') {
133 x->to_exclude = 0;
134 string++;
135 }
136 x->pattern = string;
137 x->patternlen = strlen(string);
138 x->base = base;
139 x->baselen = baselen;
140 x->flags = 0;
141 if (!strchr(string, '/'))
142 x->flags |= EXC_FLAG_NODIR;
143 if (no_wildcard(string))
144 x->flags |= EXC_FLAG_NOWILDCARD;
145 if (*string == '*' && no_wildcard(string+1))
146 x->flags |= EXC_FLAG_ENDSWITH;
147 if (which->nr == which->alloc) {
148 which->alloc = alloc_nr(which->alloc);
149 which->excludes = xrealloc(which->excludes,
150 which->alloc * sizeof(x));
151 }
152 which->excludes[which->nr++] = x;
153}
154
155static int add_excludes_from_file_1(const char *fname,
156 const char *base,
157 int baselen,
158 struct exclude_list *which)
159{
160 struct stat st;
161 int fd, i;
162 size_t size;
163 char *buf, *entry;
164
165 fd = open(fname, O_RDONLY);
166 if (fd < 0 || fstat(fd, &st) < 0)
167 goto err;
168 size = xsize_t(st.st_size);
169 if (size == 0) {
170 close(fd);
171 return 0;
172 }
173 buf = xmalloc(size+1);
174 if (read_in_full(fd, buf, size) != size)
175 goto err;
176 close(fd);
177
178 buf[size++] = '\n';
179 entry = buf;
180 for (i = 0; i < size; i++) {
181 if (buf[i] == '\n') {
182 if (entry != buf + i && entry[0] != '#') {
183 buf[i - (i && buf[i-1] == '\r')] = 0;
184 add_exclude(entry, base, baselen, which);
185 }
186 entry = buf + i + 1;
187 }
188 }
189 return 0;
190
191 err:
192 if (0 <= fd)
193 close(fd);
194 return -1;
195}
196
197void add_excludes_from_file(struct dir_struct *dir, const char *fname)
198{
199 if (add_excludes_from_file_1(fname, "", 0,
200 &dir->exclude_list[EXC_FILE]) < 0)
201 die("cannot use %s as an exclude file", fname);
202}
203
204int push_exclude_per_directory(struct dir_struct *dir, const char *base, int baselen)
205{
206 char exclude_file[PATH_MAX];
207 struct exclude_list *el = &dir->exclude_list[EXC_DIRS];
208 int current_nr = el->nr;
209
210 if (dir->exclude_per_dir) {
211 memcpy(exclude_file, base, baselen);
212 strcpy(exclude_file + baselen, dir->exclude_per_dir);
213 add_excludes_from_file_1(exclude_file, base, baselen, el);
214 }
215 return current_nr;
216}
217
218void pop_exclude_per_directory(struct dir_struct *dir, int stk)
219{
220 struct exclude_list *el = &dir->exclude_list[EXC_DIRS];
221
222 while (stk < el->nr)
223 free(el->excludes[--el->nr]);
224}
225
226/* Scan the list and let the last match determines the fate.
227 * Return 1 for exclude, 0 for include and -1 for undecided.
228 */
229static int excluded_1(const char *pathname,
230 int pathlen, const char *basename,
231 struct exclude_list *el)
232{
233 int i;
234
235 if (el->nr) {
236 for (i = el->nr - 1; 0 <= i; i--) {
237 struct exclude *x = el->excludes[i];
238 const char *exclude = x->pattern;
239 int to_exclude = x->to_exclude;
240
241 if (x->flags & EXC_FLAG_NODIR) {
242 /* match basename */
243 if (x->flags & EXC_FLAG_NOWILDCARD) {
244 if (!strcmp(exclude, basename))
245 return to_exclude;
246 } else if (x->flags & EXC_FLAG_ENDSWITH) {
247 if (x->patternlen - 1 <= pathlen &&
248 !strcmp(exclude + 1, pathname + pathlen - x->patternlen + 1))
249 return to_exclude;
250 } else {
251 if (fnmatch(exclude, basename, 0) == 0)
252 return to_exclude;
253 }
254 }
255 else {
256 /* match with FNM_PATHNAME:
257 * exclude has base (baselen long) implicitly
258 * in front of it.
259 */
260 int baselen = x->baselen;
261 if (*exclude == '/')
262 exclude++;
263
264 if (pathlen < baselen ||
265 (baselen && pathname[baselen-1] != '/') ||
266 strncmp(pathname, x->base, baselen))
267 continue;
268
269 if (x->flags & EXC_FLAG_NOWILDCARD) {
270 if (!strcmp(exclude, pathname + baselen))
271 return to_exclude;
272 } else {
273 if (fnmatch(exclude, pathname+baselen,
274 FNM_PATHNAME) == 0)
275 return to_exclude;
276 }
277 }
278 }
279 }
280 return -1; /* undecided */
281}
282
283int excluded(struct dir_struct *dir, const char *pathname)
284{
285 int pathlen = strlen(pathname);
286 int st;
287 const char *basename = strrchr(pathname, '/');
288 basename = (basename) ? basename+1 : pathname;
289
290 for (st = EXC_CMDL; st <= EXC_FILE; st++) {
291 switch (excluded_1(pathname, pathlen, basename, &dir->exclude_list[st])) {
292 case 0:
293 return 0;
294 case 1:
295 return 1;
296 }
297 }
298 return 0;
299}
300
301static struct dir_entry *dir_entry_new(const char *pathname, int len)
302{
303 struct dir_entry *ent;
304
305 ent = xmalloc(sizeof(*ent) + len + 1);
306 ent->len = len;
307 memcpy(ent->name, pathname, len);
308 ent->name[len] = 0;
309 return ent;
310}
311
312struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
313{
314 if (cache_name_pos(pathname, len) >= 0)
315 return NULL;
316
317 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
318 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
319}
320
321struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
322{
323 if (cache_name_pos(pathname, len) >= 0)
324 return NULL;
325
326 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
327 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
328}
329
330enum exist_status {
331 index_nonexistent = 0,
332 index_directory,
333 index_gitdir,
334};
335
336/*
337 * The index sorts alphabetically by entry name, which
338 * means that a gitlink sorts as '\0' at the end, while
339 * a directory (which is defined not as an entry, but as
340 * the files it contains) will sort with the '/' at the
341 * end.
342 */
343static enum exist_status directory_exists_in_index(const char *dirname, int len)
344{
345 int pos = cache_name_pos(dirname, len);
346 if (pos < 0)
347 pos = -pos-1;
348 while (pos < active_nr) {
349 struct cache_entry *ce = active_cache[pos++];
350 unsigned char endchar;
351
352 if (strncmp(ce->name, dirname, len))
353 break;
354 endchar = ce->name[len];
355 if (endchar > '/')
356 break;
357 if (endchar == '/')
358 return index_directory;
359 if (!endchar && S_ISGITLINK(ntohl(ce->ce_mode)))
360 return index_gitdir;
361 }
362 return index_nonexistent;
363}
364
365/*
366 * When we find a directory when traversing the filesystem, we
367 * have three distinct cases:
368 *
369 * - ignore it
370 * - see it as a directory
371 * - recurse into it
372 *
373 * and which one we choose depends on a combination of existing
374 * git index contents and the flags passed into the directory
375 * traversal routine.
376 *
377 * Case 1: If we *already* have entries in the index under that
378 * directory name, we always recurse into the directory to see
379 * all the files.
380 *
381 * Case 2: If we *already* have that directory name as a gitlink,
382 * we always continue to see it as a gitlink, regardless of whether
383 * there is an actual git directory there or not (it might not
384 * be checked out as a subproject!)
385 *
386 * Case 3: if we didn't have it in the index previously, we
387 * have a few sub-cases:
388 *
389 * (a) if "show_other_directories" is true, we show it as
390 * just a directory, unless "hide_empty_directories" is
391 * also true and the directory is empty, in which case
392 * we just ignore it entirely.
393 * (b) if it looks like a git directory, and we don't have
394 * 'no_gitlinks' set we treat it as a gitlink, and show it
395 * as a directory.
396 * (c) otherwise, we recurse into it.
397 */
398enum directory_treatment {
399 show_directory,
400 ignore_directory,
401 recurse_into_directory,
402};
403
404static enum directory_treatment treat_directory(struct dir_struct *dir,
405 const char *dirname, int len,
406 const struct path_simplify *simplify)
407{
408 /* The "len-1" is to strip the final '/' */
409 switch (directory_exists_in_index(dirname, len-1)) {
410 case index_directory:
411 return recurse_into_directory;
412
413 case index_gitdir:
414 if (dir->show_other_directories)
415 return ignore_directory;
416 return show_directory;
417
418 case index_nonexistent:
419 if (dir->show_other_directories)
420 break;
421 if (!dir->no_gitlinks) {
422 unsigned char sha1[20];
423 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
424 return show_directory;
425 }
426 return recurse_into_directory;
427 }
428
429 /* This is the "show_other_directories" case */
430 if (!dir->hide_empty_directories)
431 return show_directory;
432 if (!read_directory_recursive(dir, dirname, dirname, len, 1, simplify))
433 return ignore_directory;
434 return show_directory;
435}
436
437/*
438 * This is an inexact early pruning of any recursive directory
439 * reading - if the path cannot possibly be in the pathspec,
440 * return true, and we'll skip it early.
441 */
442static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
443{
444 if (simplify) {
445 for (;;) {
446 const char *match = simplify->path;
447 int len = simplify->len;
448
449 if (!match)
450 break;
451 if (len > pathlen)
452 len = pathlen;
453 if (!memcmp(path, match, len))
454 return 0;
455 simplify++;
456 }
457 return 1;
458 }
459 return 0;
460}
461
462static int in_pathspec(const char *path, int len, const struct path_simplify *simplify)
463{
464 if (simplify) {
465 for (; simplify->path; simplify++) {
466 if (len == simplify->len
467 && !memcmp(path, simplify->path, len))
468 return 1;
469 }
470 }
471 return 0;
472}
473
474static int get_dtype(struct dirent *de, const char *path)
475{
476 int dtype = DTYPE(de);
477 struct stat st;
478
479 if (dtype != DT_UNKNOWN)
480 return dtype;
481 if (lstat(path, &st))
482 return dtype;
483 if (S_ISREG(st.st_mode))
484 return DT_REG;
485 if (S_ISDIR(st.st_mode))
486 return DT_DIR;
487 if (S_ISLNK(st.st_mode))
488 return DT_LNK;
489 return dtype;
490}
491
492/*
493 * Read a directory tree. We currently ignore anything but
494 * directories, regular files and symlinks. That's because git
495 * doesn't handle them at all yet. Maybe that will change some
496 * day.
497 *
498 * Also, we ignore the name ".git" (even if it is not a directory).
499 * That likely will not change.
500 */
501static int read_directory_recursive(struct dir_struct *dir, const char *path, const char *base, int baselen, int check_only, const struct path_simplify *simplify)
502{
503 DIR *fdir = opendir(path);
504 int contents = 0;
505
506 if (fdir) {
507 int exclude_stk;
508 struct dirent *de;
509 char fullname[PATH_MAX + 1];
510 memcpy(fullname, base, baselen);
511
512 exclude_stk = push_exclude_per_directory(dir, base, baselen);
513
514 while ((de = readdir(fdir)) != NULL) {
515 int len, dtype;
516 int exclude;
517
518 if ((de->d_name[0] == '.') &&
519 (de->d_name[1] == 0 ||
520 !strcmp(de->d_name + 1, ".") ||
521 !strcmp(de->d_name + 1, "git")))
522 continue;
523 len = strlen(de->d_name);
524 /* Ignore overly long pathnames! */
525 if (len + baselen + 8 > sizeof(fullname))
526 continue;
527 memcpy(fullname + baselen, de->d_name, len+1);
528 if (simplify_away(fullname, baselen + len, simplify))
529 continue;
530
531 exclude = excluded(dir, fullname);
532 if (exclude && dir->collect_ignored
533 && in_pathspec(fullname, baselen + len, simplify))
534 dir_add_ignored(dir, fullname, baselen + len);
535
536 /*
537 * Excluded? If we don't explicitly want to show
538 * ignored files, ignore it
539 */
540 if (exclude && !dir->show_ignored)
541 continue;
542
543 dtype = get_dtype(de, fullname);
544
545 /*
546 * Do we want to see just the ignored files?
547 * We still need to recurse into directories,
548 * even if we don't ignore them, since the
549 * directory may contain files that we do..
550 */
551 if (!exclude && dir->show_ignored) {
552 if (dtype != DT_DIR)
553 continue;
554 }
555
556 switch (dtype) {
557 default:
558 continue;
559 case DT_DIR:
560 memcpy(fullname + baselen + len, "/", 2);
561 len++;
562 switch (treat_directory(dir, fullname, baselen + len, simplify)) {
563 case show_directory:
564 if (exclude != dir->show_ignored)
565 continue;
566 break;
567 case recurse_into_directory:
568 contents += read_directory_recursive(dir,
569 fullname, fullname, baselen + len, 0, simplify);
570 continue;
571 case ignore_directory:
572 continue;
573 }
574 break;
575 case DT_REG:
576 case DT_LNK:
577 break;
578 }
579 contents++;
580 if (check_only)
581 goto exit_early;
582 else
583 dir_add_name(dir, fullname, baselen + len);
584 }
585exit_early:
586 closedir(fdir);
587
588 pop_exclude_per_directory(dir, exclude_stk);
589 }
590
591 return contents;
592}
593
594static int cmp_name(const void *p1, const void *p2)
595{
596 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
597 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
598
599 return cache_name_compare(e1->name, e1->len,
600 e2->name, e2->len);
601}
602
603/*
604 * Return the length of the "simple" part of a path match limiter.
605 */
606static int simple_length(const char *match)
607{
608 const char special[256] = {
609 [0] = 1, ['?'] = 1,
610 ['\\'] = 1, ['*'] = 1,
611 ['['] = 1
612 };
613 int len = -1;
614
615 for (;;) {
616 unsigned char c = *match++;
617 len++;
618 if (special[c])
619 return len;
620 }
621}
622
623static struct path_simplify *create_simplify(const char **pathspec)
624{
625 int nr, alloc = 0;
626 struct path_simplify *simplify = NULL;
627
628 if (!pathspec)
629 return NULL;
630
631 for (nr = 0 ; ; nr++) {
632 const char *match;
633 if (nr >= alloc) {
634 alloc = alloc_nr(alloc);
635 simplify = xrealloc(simplify, alloc * sizeof(*simplify));
636 }
637 match = *pathspec++;
638 if (!match)
639 break;
640 simplify[nr].path = match;
641 simplify[nr].len = simple_length(match);
642 }
643 simplify[nr].path = NULL;
644 simplify[nr].len = 0;
645 return simplify;
646}
647
648static void free_simplify(struct path_simplify *simplify)
649{
650 if (simplify)
651 free(simplify);
652}
653
654int read_directory(struct dir_struct *dir, const char *path, const char *base, int baselen, const char **pathspec)
655{
656 struct path_simplify *simplify = create_simplify(pathspec);
657
658 /*
659 * Make sure to do the per-directory exclude for all the
660 * directories leading up to our base.
661 */
662 if (baselen) {
663 if (dir->exclude_per_dir) {
664 char *p, *pp = xmalloc(baselen+1);
665 memcpy(pp, base, baselen+1);
666 p = pp;
667 while (1) {
668 char save = *p;
669 *p = 0;
670 push_exclude_per_directory(dir, pp, p-pp);
671 *p++ = save;
672 if (!save)
673 break;
674 p = strchr(p, '/');
675 if (p)
676 p++;
677 else
678 p = pp + baselen;
679 }
680 free(pp);
681 }
682 }
683
684 read_directory_recursive(dir, path, base, baselen, 0, simplify);
685 free_simplify(simplify);
686 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
687 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
688 return dir->nr;
689}
690
691int
692file_exists(const char *f)
693{
694 struct stat sb;
695 return stat(f, &sb) == 0;
696}
697
698/*
699 * get_relative_cwd() gets the prefix of the current working directory
700 * relative to 'dir'. If we are not inside 'dir', it returns NULL.
701 *
702 * As a convenience, it also returns NULL if 'dir' is already NULL. The
703 * reason for this behaviour is that it is natural for functions returning
704 * directory names to return NULL to say "this directory does not exist"
705 * or "this directory is invalid". These cases are usually handled the
706 * same as if the cwd is not inside 'dir' at all, so get_relative_cwd()
707 * returns NULL for both of them.
708 *
709 * Most notably, get_relative_cwd(buffer, size, get_git_work_tree())
710 * unifies the handling of "outside work tree" with "no work tree at all".
711 */
712char *get_relative_cwd(char *buffer, int size, const char *dir)
713{
714 char *cwd = buffer;
715
716 if (!dir)
717 return NULL;
718 if (!getcwd(buffer, size))
719 die("can't find the current directory: %s", strerror(errno));
720
721 if (!is_absolute_path(dir))
722 dir = make_absolute_path(dir);
723
724 while (*dir && *dir == *cwd) {
725 dir++;
726 cwd++;
727 }
728 if (*dir)
729 return NULL;
730 if (*cwd == '/')
731 return cwd + 1;
732 return cwd;
733}
734
735int is_inside_dir(const char *dir)
736{
737 char buffer[PATH_MAX];
738 return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
739}
740
741int remove_dir_recursively(struct strbuf *path, int only_empty)
742{
743 DIR *dir = opendir(path->buf);
744 struct dirent *e;
745 int ret = 0, original_len = path->len, len;
746
747 if (!dir)
748 return -1;
749 if (path->buf[original_len - 1] != '/')
750 strbuf_addch(path, '/');
751
752 len = path->len;
753 while ((e = readdir(dir)) != NULL) {
754 struct stat st;
755 if ((e->d_name[0] == '.') &&
756 ((e->d_name[1] == 0) ||
757 ((e->d_name[1] == '.') && e->d_name[2] == 0)))
758 continue; /* "." and ".." */
759
760 strbuf_setlen(path, len);
761 strbuf_addstr(path, e->d_name);
762 if (lstat(path->buf, &st))
763 ; /* fall thru */
764 else if (S_ISDIR(st.st_mode)) {
765 if (!remove_dir_recursively(path, only_empty))
766 continue; /* happy */
767 } else if (!only_empty && !unlink(path->buf))
768 continue; /* happy, too */
769
770 /* path too long, stat fails, or non-directory still exists */
771 ret = -1;
772 break;
773 }
774 closedir(dir);
775
776 strbuf_setlen(path, original_len);
777 if (!ret)
778 ret = rmdir(path->buf);
779 return ret;
780}