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