dir: fix COLLECT_IGNORED on excluded prefixes
[git/srabbelier.git] / dir.c
blob14ac91a7bbdecc8406a675c766a6c922a70608fe
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, const char *path, int len,
18 int check_only, const struct path_simplify *simplify);
19 static int get_dtype(struct dirent *de, const char *path, int len);
21 static int common_prefix(const char **pathspec)
23 const char *path, *slash, *next;
24 int prefix;
26 if (!pathspec)
27 return 0;
29 path = *pathspec;
30 slash = strrchr(path, '/');
31 if (!slash)
32 return 0;
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;
51 return prefix;
54 int fill_directory(struct dir_struct *dir, const char **pathspec)
56 const char *path;
57 int len;
60 * Calculate common prefix for the pathspec, and
61 * use that to optimize the directory walk
63 len = common_prefix(pathspec);
64 path = "";
66 if (len)
67 path = xmemdupz(*pathspec, len);
69 /* Read the directory and prune it */
70 read_directory(dir, path, len, pathspec);
71 return len;
75 * Does 'match' match the given name?
76 * A match is found if
78 * (1) the 'match' string is leading directory of 'name', or
79 * (2) the 'match' string is a wildcard and matches 'name', or
80 * (3) the 'match' string is exactly the same as 'name'.
82 * and the return value tells which case it was.
84 * It returns 0 when there is no match.
86 static int match_one(const char *match, const char *name, int namelen)
88 int matchlen;
90 /* If the match was just the prefix, we matched */
91 if (!*match)
92 return MATCHED_RECURSIVELY;
94 for (;;) {
95 unsigned char c1 = *match;
96 unsigned char c2 = *name;
97 if (c1 == '\0' || is_glob_special(c1))
98 break;
99 if (c1 != c2)
100 return 0;
101 match++;
102 name++;
103 namelen--;
108 * If we don't match the matchstring exactly,
109 * we need to match by fnmatch
111 matchlen = strlen(match);
112 if (strncmp(match, name, matchlen))
113 return !fnmatch(match, name, 0) ? MATCHED_FNMATCH : 0;
115 if (namelen == matchlen)
116 return MATCHED_EXACTLY;
117 if (match[matchlen-1] == '/' || name[matchlen] == '/')
118 return MATCHED_RECURSIVELY;
119 return 0;
123 * Given a name and a list of pathspecs, see if the name matches
124 * any of the pathspecs. The caller is also interested in seeing
125 * all pathspec matches some names it calls this function with
126 * (otherwise the user could have mistyped the unmatched pathspec),
127 * and a mark is left in seen[] array for pathspec element that
128 * actually matched anything.
130 int match_pathspec(const char **pathspec, const char *name, int namelen,
131 int prefix, char *seen)
133 int i, retval = 0;
135 if (!pathspec)
136 return 1;
138 name += prefix;
139 namelen -= prefix;
141 for (i = 0; pathspec[i] != NULL; i++) {
142 int how;
143 const char *match = pathspec[i] + prefix;
144 if (seen && seen[i] == MATCHED_EXACTLY)
145 continue;
146 how = match_one(match, name, namelen);
147 if (how) {
148 if (retval < how)
149 retval = how;
150 if (seen && seen[i] < how)
151 seen[i] = how;
154 return retval;
157 static int no_wildcard(const char *string)
159 return string[strcspn(string, "*?[{\\")] == '\0';
162 void add_exclude(const char *string, const char *base,
163 int baselen, struct exclude_list *which)
165 struct exclude *x;
166 size_t len;
167 int to_exclude = 1;
168 int flags = 0;
170 if (*string == '!') {
171 to_exclude = 0;
172 string++;
174 len = strlen(string);
175 if (len && string[len - 1] == '/') {
176 char *s;
177 x = xmalloc(sizeof(*x) + len);
178 s = (char *)(x+1);
179 memcpy(s, string, len - 1);
180 s[len - 1] = '\0';
181 string = s;
182 x->pattern = s;
183 flags = EXC_FLAG_MUSTBEDIR;
184 } else {
185 x = xmalloc(sizeof(*x));
186 x->pattern = string;
188 x->to_exclude = to_exclude;
189 x->patternlen = strlen(string);
190 x->base = base;
191 x->baselen = baselen;
192 x->flags = flags;
193 if (!strchr(string, '/'))
194 x->flags |= EXC_FLAG_NODIR;
195 if (no_wildcard(string))
196 x->flags |= EXC_FLAG_NOWILDCARD;
197 if (*string == '*' && no_wildcard(string+1))
198 x->flags |= EXC_FLAG_ENDSWITH;
199 ALLOC_GROW(which->excludes, which->nr + 1, which->alloc);
200 which->excludes[which->nr++] = x;
203 static int add_excludes_from_file_1(const char *fname,
204 const char *base,
205 int baselen,
206 char **buf_p,
207 struct exclude_list *which)
209 struct stat st;
210 int fd, i;
211 size_t size;
212 char *buf, *entry;
214 fd = open(fname, O_RDONLY);
215 if (fd < 0 || fstat(fd, &st) < 0)
216 goto err;
217 size = xsize_t(st.st_size);
218 if (size == 0) {
219 close(fd);
220 return 0;
222 buf = xmalloc(size+1);
223 if (read_in_full(fd, buf, size) != size)
225 free(buf);
226 goto err;
228 close(fd);
230 if (buf_p)
231 *buf_p = buf;
232 buf[size++] = '\n';
233 entry = buf;
234 for (i = 0; i < size; i++) {
235 if (buf[i] == '\n') {
236 if (entry != buf + i && entry[0] != '#') {
237 buf[i - (i && buf[i-1] == '\r')] = 0;
238 add_exclude(entry, base, baselen, which);
240 entry = buf + i + 1;
243 return 0;
245 err:
246 if (0 <= fd)
247 close(fd);
248 return -1;
251 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
253 if (add_excludes_from_file_1(fname, "", 0, NULL,
254 &dir->exclude_list[EXC_FILE]) < 0)
255 die("cannot use %s as an exclude file", fname);
258 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
260 struct exclude_list *el;
261 struct exclude_stack *stk = NULL;
262 int current;
264 if ((!dir->exclude_per_dir) ||
265 (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
266 return; /* too long a path -- ignore */
268 /* Pop the ones that are not the prefix of the path being checked. */
269 el = &dir->exclude_list[EXC_DIRS];
270 while ((stk = dir->exclude_stack) != NULL) {
271 if (stk->baselen <= baselen &&
272 !strncmp(dir->basebuf, base, stk->baselen))
273 break;
274 dir->exclude_stack = stk->prev;
275 while (stk->exclude_ix < el->nr)
276 free(el->excludes[--el->nr]);
277 free(stk->filebuf);
278 free(stk);
281 /* Read from the parent directories and push them down. */
282 current = stk ? stk->baselen : -1;
283 while (current < baselen) {
284 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
285 const char *cp;
287 if (current < 0) {
288 cp = base;
289 current = 0;
291 else {
292 cp = strchr(base + current + 1, '/');
293 if (!cp)
294 die("oops in prep_exclude");
295 cp++;
297 stk->prev = dir->exclude_stack;
298 stk->baselen = cp - base;
299 stk->exclude_ix = el->nr;
300 memcpy(dir->basebuf + current, base + current,
301 stk->baselen - current);
302 strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
303 add_excludes_from_file_1(dir->basebuf,
304 dir->basebuf, stk->baselen,
305 &stk->filebuf, el);
306 dir->exclude_stack = stk;
307 current = stk->baselen;
309 dir->basebuf[baselen] = '\0';
312 /* Scan the list and let the last match determine the fate.
313 * Return 1 for exclude, 0 for include and -1 for undecided.
315 static int excluded_1(const char *pathname,
316 int pathlen, const char *basename, int *dtype,
317 struct exclude_list *el)
319 int i;
321 if (el->nr) {
322 for (i = el->nr - 1; 0 <= i; i--) {
323 struct exclude *x = el->excludes[i];
324 const char *exclude = x->pattern;
325 int to_exclude = x->to_exclude;
327 if (x->flags & EXC_FLAG_MUSTBEDIR) {
328 if (*dtype == DT_UNKNOWN)
329 *dtype = get_dtype(NULL, pathname, pathlen);
330 if (*dtype != DT_DIR)
331 continue;
334 if (x->flags & EXC_FLAG_NODIR) {
335 /* match basename */
336 if (x->flags & EXC_FLAG_NOWILDCARD) {
337 if (!strcmp(exclude, basename))
338 return to_exclude;
339 } else if (x->flags & EXC_FLAG_ENDSWITH) {
340 if (x->patternlen - 1 <= pathlen &&
341 !strcmp(exclude + 1, pathname + pathlen - x->patternlen + 1))
342 return to_exclude;
343 } else {
344 if (fnmatch(exclude, basename, 0) == 0)
345 return to_exclude;
348 else {
349 /* match with FNM_PATHNAME:
350 * exclude has base (baselen long) implicitly
351 * in front of it.
353 int baselen = x->baselen;
354 if (*exclude == '/')
355 exclude++;
357 if (pathlen < baselen ||
358 (baselen && pathname[baselen-1] != '/') ||
359 strncmp(pathname, x->base, baselen))
360 continue;
362 if (x->flags & EXC_FLAG_NOWILDCARD) {
363 if (!strcmp(exclude, pathname + baselen))
364 return to_exclude;
365 } else {
366 if (fnmatch(exclude, pathname+baselen,
367 FNM_PATHNAME) == 0)
368 return to_exclude;
373 return -1; /* undecided */
376 int excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
378 int pathlen = strlen(pathname);
379 int st;
380 const char *basename = strrchr(pathname, '/');
381 basename = (basename) ? basename+1 : pathname;
383 prep_exclude(dir, pathname, basename-pathname);
384 for (st = EXC_CMDL; st <= EXC_FILE; st++) {
385 switch (excluded_1(pathname, pathlen, basename,
386 dtype_p, &dir->exclude_list[st])) {
387 case 0:
388 return 0;
389 case 1:
390 return 1;
393 return 0;
396 static struct dir_entry *dir_entry_new(const char *pathname, int len)
398 struct dir_entry *ent;
400 ent = xmalloc(sizeof(*ent) + len + 1);
401 ent->len = len;
402 memcpy(ent->name, pathname, len);
403 ent->name[len] = 0;
404 return ent;
407 static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
409 if (cache_name_exists(pathname, len, ignore_case))
410 return NULL;
412 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
413 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
416 static struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
418 if (!cache_name_is_other(pathname, len))
419 return NULL;
421 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
422 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
425 enum exist_status {
426 index_nonexistent = 0,
427 index_directory,
428 index_gitdir,
432 * The index sorts alphabetically by entry name, which
433 * means that a gitlink sorts as '\0' at the end, while
434 * a directory (which is defined not as an entry, but as
435 * the files it contains) will sort with the '/' at the
436 * end.
438 static enum exist_status directory_exists_in_index(const char *dirname, int len)
440 int pos = cache_name_pos(dirname, len);
441 if (pos < 0)
442 pos = -pos-1;
443 while (pos < active_nr) {
444 struct cache_entry *ce = active_cache[pos++];
445 unsigned char endchar;
447 if (strncmp(ce->name, dirname, len))
448 break;
449 endchar = ce->name[len];
450 if (endchar > '/')
451 break;
452 if (endchar == '/')
453 return index_directory;
454 if (!endchar && S_ISGITLINK(ce->ce_mode))
455 return index_gitdir;
457 return index_nonexistent;
461 * When we find a directory when traversing the filesystem, we
462 * have three distinct cases:
464 * - ignore it
465 * - see it as a directory
466 * - recurse into it
468 * and which one we choose depends on a combination of existing
469 * git index contents and the flags passed into the directory
470 * traversal routine.
472 * Case 1: If we *already* have entries in the index under that
473 * directory name, we always recurse into the directory to see
474 * all the files.
476 * Case 2: If we *already* have that directory name as a gitlink,
477 * we always continue to see it as a gitlink, regardless of whether
478 * there is an actual git directory there or not (it might not
479 * be checked out as a subproject!)
481 * Case 3: if we didn't have it in the index previously, we
482 * have a few sub-cases:
484 * (a) if "show_other_directories" is true, we show it as
485 * just a directory, unless "hide_empty_directories" is
486 * also true and the directory is empty, in which case
487 * we just ignore it entirely.
488 * (b) if it looks like a git directory, and we don't have
489 * 'no_gitlinks' set we treat it as a gitlink, and show it
490 * as a directory.
491 * (c) otherwise, we recurse into it.
493 enum directory_treatment {
494 show_directory,
495 ignore_directory,
496 recurse_into_directory,
499 static enum directory_treatment treat_directory(struct dir_struct *dir,
500 const char *dirname, int len,
501 const struct path_simplify *simplify)
503 /* The "len-1" is to strip the final '/' */
504 switch (directory_exists_in_index(dirname, len-1)) {
505 case index_directory:
506 return recurse_into_directory;
508 case index_gitdir:
509 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
510 return ignore_directory;
511 return show_directory;
513 case index_nonexistent:
514 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
515 break;
516 if (!(dir->flags & DIR_NO_GITLINKS)) {
517 unsigned char sha1[20];
518 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
519 return show_directory;
521 return recurse_into_directory;
524 /* This is the "show_other_directories" case */
525 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
526 return show_directory;
527 if (!read_directory_recursive(dir, dirname, len, 1, simplify))
528 return ignore_directory;
529 return show_directory;
533 * This is an inexact early pruning of any recursive directory
534 * reading - if the path cannot possibly be in the pathspec,
535 * return true, and we'll skip it early.
537 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
539 if (simplify) {
540 for (;;) {
541 const char *match = simplify->path;
542 int len = simplify->len;
544 if (!match)
545 break;
546 if (len > pathlen)
547 len = pathlen;
548 if (!memcmp(path, match, len))
549 return 0;
550 simplify++;
552 return 1;
554 return 0;
558 * This function tells us whether an excluded path matches a
559 * list of "interesting" pathspecs. That is, whether a path matched
560 * by any of the pathspecs could possibly be ignored by excluding
561 * the specified path. This can happen if:
563 * 1. the path is mentioned explicitly in the pathspec
565 * 2. the path is a directory prefix of some element in the
566 * pathspec
568 static int exclude_matches_pathspec(const char *path, int len,
569 const struct path_simplify *simplify)
571 if (simplify) {
572 for (; simplify->path; simplify++) {
573 if (len == simplify->len
574 && !memcmp(path, simplify->path, len))
575 return 1;
576 if (len < simplify->len
577 && simplify->path[len] == '/'
578 && !memcmp(path, simplify->path, len))
579 return 1;
582 return 0;
585 static int get_index_dtype(const char *path, int len)
587 int pos;
588 struct cache_entry *ce;
590 ce = cache_name_exists(path, len, 0);
591 if (ce) {
592 if (!ce_uptodate(ce))
593 return DT_UNKNOWN;
594 if (S_ISGITLINK(ce->ce_mode))
595 return DT_DIR;
597 * Nobody actually cares about the
598 * difference between DT_LNK and DT_REG
600 return DT_REG;
603 /* Try to look it up as a directory */
604 pos = cache_name_pos(path, len);
605 if (pos >= 0)
606 return DT_UNKNOWN;
607 pos = -pos-1;
608 while (pos < active_nr) {
609 ce = active_cache[pos++];
610 if (strncmp(ce->name, path, len))
611 break;
612 if (ce->name[len] > '/')
613 break;
614 if (ce->name[len] < '/')
615 continue;
616 if (!ce_uptodate(ce))
617 break; /* continue? */
618 return DT_DIR;
620 return DT_UNKNOWN;
623 static int get_dtype(struct dirent *de, const char *path, int len)
625 int dtype = de ? DTYPE(de) : DT_UNKNOWN;
626 struct stat st;
628 if (dtype != DT_UNKNOWN)
629 return dtype;
630 dtype = get_index_dtype(path, len);
631 if (dtype != DT_UNKNOWN)
632 return dtype;
633 if (lstat(path, &st))
634 return dtype;
635 if (S_ISREG(st.st_mode))
636 return DT_REG;
637 if (S_ISDIR(st.st_mode))
638 return DT_DIR;
639 if (S_ISLNK(st.st_mode))
640 return DT_LNK;
641 return dtype;
644 enum path_treatment {
645 path_ignored,
646 path_handled,
647 path_recurse,
650 static enum path_treatment treat_one_path(struct dir_struct *dir,
651 char *path, int *len,
652 const struct path_simplify *simplify,
653 int dtype, struct dirent *de)
655 int exclude = excluded(dir, path, &dtype);
656 if (exclude && (dir->flags & DIR_COLLECT_IGNORED)
657 && exclude_matches_pathspec(path, *len, simplify))
658 dir_add_ignored(dir, path, *len);
661 * Excluded? If we don't explicitly want to show
662 * ignored files, ignore it
664 if (exclude && !(dir->flags & DIR_SHOW_IGNORED))
665 return path_ignored;
667 if (dtype == DT_UNKNOWN)
668 dtype = get_dtype(de, path, *len);
671 * Do we want to see just the ignored files?
672 * We still need to recurse into directories,
673 * even if we don't ignore them, since the
674 * directory may contain files that we do..
676 if (!exclude && (dir->flags & DIR_SHOW_IGNORED)) {
677 if (dtype != DT_DIR)
678 return path_ignored;
681 switch (dtype) {
682 default:
683 return path_ignored;
684 case DT_DIR:
685 memcpy(path + *len, "/", 2);
686 (*len)++;
687 switch (treat_directory(dir, path, *len, simplify)) {
688 case show_directory:
689 if (exclude != !!(dir->flags
690 & DIR_SHOW_IGNORED))
691 return path_ignored;
692 break;
693 case recurse_into_directory:
694 return path_recurse;
695 case ignore_directory:
696 return path_ignored;
698 break;
699 case DT_REG:
700 case DT_LNK:
701 break;
703 return path_handled;
706 static enum path_treatment treat_path(struct dir_struct *dir,
707 struct dirent *de,
708 char *path, int path_max,
709 int baselen,
710 const struct path_simplify *simplify,
711 int *len)
713 int dtype;
715 if (is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name, ".git"))
716 return path_ignored;
717 *len = strlen(de->d_name);
718 /* Ignore overly long pathnames! */
719 if (*len + baselen + 8 > path_max)
720 return path_ignored;
721 memcpy(path + baselen, de->d_name, *len + 1);
722 *len += baselen;
723 if (simplify_away(path, *len, simplify))
724 return path_ignored;
726 dtype = DTYPE(de);
727 return treat_one_path(dir, path, len, simplify, dtype, de);
731 * Read a directory tree. We currently ignore anything but
732 * directories, regular files and symlinks. That's because git
733 * doesn't handle them at all yet. Maybe that will change some
734 * day.
736 * Also, we ignore the name ".git" (even if it is not a directory).
737 * That likely will not change.
739 static int read_directory_recursive(struct dir_struct *dir,
740 const char *base, int baselen,
741 int check_only,
742 const struct path_simplify *simplify)
744 DIR *fdir = opendir(*base ? base : ".");
745 int contents = 0;
747 if (fdir) {
748 struct dirent *de;
749 char path[PATH_MAX + 1];
750 memcpy(path, base, baselen);
752 while ((de = readdir(fdir)) != NULL) {
753 int len;
754 switch (treat_path(dir, de, path, sizeof(path),
755 baselen, simplify, &len)) {
756 case path_recurse:
757 contents += read_directory_recursive
758 (dir, path, len, 0, simplify);
759 continue;
760 case path_ignored:
761 continue;
762 case path_handled:
763 break;
765 contents++;
766 if (check_only)
767 goto exit_early;
768 else
769 dir_add_name(dir, path, len);
771 exit_early:
772 closedir(fdir);
775 return contents;
778 static int cmp_name(const void *p1, const void *p2)
780 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
781 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
783 return cache_name_compare(e1->name, e1->len,
784 e2->name, e2->len);
788 * Return the length of the "simple" part of a path match limiter.
790 static int simple_length(const char *match)
792 int len = -1;
794 for (;;) {
795 unsigned char c = *match++;
796 len++;
797 if (c == '\0' || is_glob_special(c))
798 return len;
802 static struct path_simplify *create_simplify(const char **pathspec)
804 int nr, alloc = 0;
805 struct path_simplify *simplify = NULL;
807 if (!pathspec)
808 return NULL;
810 for (nr = 0 ; ; nr++) {
811 const char *match;
812 if (nr >= alloc) {
813 alloc = alloc_nr(alloc);
814 simplify = xrealloc(simplify, alloc * sizeof(*simplify));
816 match = *pathspec++;
817 if (!match)
818 break;
819 simplify[nr].path = match;
820 simplify[nr].len = simple_length(match);
822 simplify[nr].path = NULL;
823 simplify[nr].len = 0;
824 return simplify;
827 static void free_simplify(struct path_simplify *simplify)
829 free(simplify);
832 static int treat_leading_path(struct dir_struct *dir,
833 const char *path, int len,
834 const struct path_simplify *simplify)
836 char pathbuf[PATH_MAX];
837 int baselen, blen;
838 const char *cp;
840 while (len && path[len - 1] == '/')
841 len--;
842 if (!len)
843 return 1;
844 baselen = 0;
845 while (1) {
846 cp = path + baselen + !!baselen;
847 cp = memchr(cp, '/', path + len - cp);
848 if (!cp)
849 baselen = len;
850 else
851 baselen = cp - path;
852 memcpy(pathbuf, path, baselen);
853 pathbuf[baselen] = '\0';
854 if (!is_directory(pathbuf))
855 return 0;
856 if (simplify_away(pathbuf, baselen, simplify))
857 return 0;
858 blen = baselen;
859 if (treat_one_path(dir, pathbuf, &blen, simplify,
860 DT_DIR, NULL) == path_ignored)
861 return 0; /* do not recurse into it */
862 if (len <= baselen)
863 return 1; /* finished checking */
867 int read_directory(struct dir_struct *dir, const char *path, int len, const char **pathspec)
869 struct path_simplify *simplify;
871 if (has_symlink_leading_path(path, len))
872 return dir->nr;
874 simplify = create_simplify(pathspec);
875 if (!len || treat_leading_path(dir, path, len, simplify))
876 read_directory_recursive(dir, path, len, 0, simplify);
877 free_simplify(simplify);
878 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
879 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
880 return dir->nr;
883 int file_exists(const char *f)
885 struct stat sb;
886 return lstat(f, &sb) == 0;
890 * get_relative_cwd() gets the prefix of the current working directory
891 * relative to 'dir'. If we are not inside 'dir', it returns NULL.
893 * As a convenience, it also returns NULL if 'dir' is already NULL. The
894 * reason for this behaviour is that it is natural for functions returning
895 * directory names to return NULL to say "this directory does not exist"
896 * or "this directory is invalid". These cases are usually handled the
897 * same as if the cwd is not inside 'dir' at all, so get_relative_cwd()
898 * returns NULL for both of them.
900 * Most notably, get_relative_cwd(buffer, size, get_git_work_tree())
901 * unifies the handling of "outside work tree" with "no work tree at all".
903 char *get_relative_cwd(char *buffer, int size, const char *dir)
905 char *cwd = buffer;
907 if (!dir)
908 return NULL;
909 if (!getcwd(buffer, size))
910 die_errno("can't find the current directory");
912 if (!is_absolute_path(dir))
913 dir = make_absolute_path(dir);
915 while (*dir && *dir == *cwd) {
916 dir++;
917 cwd++;
919 if (*dir)
920 return NULL;
921 if (*cwd == '/')
922 return cwd + 1;
923 return cwd;
926 int is_inside_dir(const char *dir)
928 char buffer[PATH_MAX];
929 return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
932 int is_empty_dir(const char *path)
934 DIR *dir = opendir(path);
935 struct dirent *e;
936 int ret = 1;
938 if (!dir)
939 return 0;
941 while ((e = readdir(dir)) != NULL)
942 if (!is_dot_or_dotdot(e->d_name)) {
943 ret = 0;
944 break;
947 closedir(dir);
948 return ret;
951 int remove_dir_recursively(struct strbuf *path, int flag)
953 DIR *dir;
954 struct dirent *e;
955 int ret = 0, original_len = path->len, len;
956 int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
957 unsigned char submodule_head[20];
959 if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
960 !resolve_gitlink_ref(path->buf, "HEAD", submodule_head))
961 /* Do not descend and nuke a nested git work tree. */
962 return 0;
964 dir = opendir(path->buf);
965 if (!dir)
966 return -1;
967 if (path->buf[original_len - 1] != '/')
968 strbuf_addch(path, '/');
970 len = path->len;
971 while ((e = readdir(dir)) != NULL) {
972 struct stat st;
973 if (is_dot_or_dotdot(e->d_name))
974 continue;
976 strbuf_setlen(path, len);
977 strbuf_addstr(path, e->d_name);
978 if (lstat(path->buf, &st))
979 ; /* fall thru */
980 else if (S_ISDIR(st.st_mode)) {
981 if (!remove_dir_recursively(path, only_empty))
982 continue; /* happy */
983 } else if (!only_empty && !unlink(path->buf))
984 continue; /* happy, too */
986 /* path too long, stat fails, or non-directory still exists */
987 ret = -1;
988 break;
990 closedir(dir);
992 strbuf_setlen(path, original_len);
993 if (!ret)
994 ret = rmdir(path->buf);
995 return ret;
998 void setup_standard_excludes(struct dir_struct *dir)
1000 const char *path;
1002 dir->exclude_per_dir = ".gitignore";
1003 path = git_path("info/exclude");
1004 if (!access(path, R_OK))
1005 add_excludes_from_file(dir, path);
1006 if (excludes_file && !access(excludes_file, R_OK))
1007 add_excludes_from_file(dir, excludes_file);
1010 int remove_path(const char *name)
1012 char *slash;
1014 if (unlink(name) && errno != ENOENT)
1015 return -1;
1017 slash = strrchr(name, '/');
1018 if (slash) {
1019 char *dirs = xstrdup(name);
1020 slash = dirs + (slash - name);
1021 do {
1022 *slash = '\0';
1023 } while (rmdir(dirs) && (slash = strrchr(dirs, '/')));
1024 free(dirs);
1026 return 0;