Revert "excluded_1(): support exclude files in index"
[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, 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);
20
21 static int 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         /*
35          * The first 'prefix' characters of 'path' are common leading
36          * path components among the pathspecs we have seen so far,
37          * including the trailing slash.
38          */
39         prefix = slash - path + 1;
40         while ((next = *++pathspec) != NULL) {
41                 int len, last_matching_slash = -1;
42                 for (len = 0; len < prefix && next[len] == path[len]; len++)
43                         if (next[len] == '/')
44                                 last_matching_slash = len;
45                 if (len == prefix)
46                         continue;
47                 if (last_matching_slash < 0)
48                         return 0;
49                 prefix = last_matching_slash + 1;
50         }
51         return prefix;
52 }
53
54 int fill_directory(struct dir_struct *dir, const char **pathspec)
55 {
56         const char *path;
57         int len;
58
59         /*
60          * Calculate common prefix for the pathspec, and
61          * use that to optimize the directory walk
62          */
63         len = common_prefix(pathspec);
64         path = "";
65
66         if (len)
67                 path = xmemdupz(*pathspec, len);
68
69         /* Read the directory and prune it */
70         read_directory(dir, path, len, pathspec);
71         return len;
72 }
73
74 /*
75  * Does 'match' match the given name?
76  * A match is found if
77  *
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'.
81  *
82  * and the return value tells which case it was.
83  *
84  * It returns 0 when there is no match.
85  */
86 static int match_one(const char *match, const char *name, int namelen)
87 {
88         int matchlen;
89
90         /* If the match was just the prefix, we matched */
91         if (!*match)
92                 return MATCHED_RECURSIVELY;
93
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--;
104         }
105
106
107         /*
108          * If we don't match the matchstring exactly,
109          * we need to match by fnmatch
110          */
111         matchlen = strlen(match);
112         if (strncmp(match, name, matchlen))
113                 return !fnmatch(match, name, 0) ? MATCHED_FNMATCH : 0;
114
115         if (namelen == matchlen)
116                 return MATCHED_EXACTLY;
117         if (match[matchlen-1] == '/' || name[matchlen] == '/')
118                 return MATCHED_RECURSIVELY;
119         return 0;
120 }
121
122 /*
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.
129  */
130 int match_pathspec(const char **pathspec, const char *name, int namelen,
131                 int prefix, char *seen)
132 {
133         int i, retval = 0;
134
135         if (!pathspec)
136                 return 1;
137
138         name += prefix;
139         namelen -= prefix;
140
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;
152                 }
153         }
154         return retval;
155 }
156
157 static int no_wildcard(const char *string)
158 {
159         return string[strcspn(string, "*?[{\\")] == '\0';
160 }
161
162 void add_exclude(const char *string, const char *base,
163                  int baselen, struct exclude_list *which)
164 {
165         struct exclude *x;
166         size_t len;
167         int to_exclude = 1;
168         int flags = 0;
169
170         if (*string == '!') {
171                 to_exclude = 0;
172                 string++;
173         }
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;
187         }
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;
201 }
202
203 static void *read_skip_worktree_file_from_index(const char *path, size_t *size)
204 {
205         int pos, len;
206         unsigned long sz;
207         enum object_type type;
208         void *data;
209         struct index_state *istate = &the_index;
210
211         len = strlen(path);
212         pos = index_name_pos(istate, path, len);
213         if (pos < 0)
214                 return NULL;
215         if (!ce_skip_worktree(istate->cache[pos]))
216                 return NULL;
217         data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
218         if (!data || type != OBJ_BLOB) {
219                 free(data);
220                 return NULL;
221         }
222         *size = xsize_t(sz);
223         return data;
224 }
225
226 void free_excludes(struct exclude_list *el)
227 {
228         int i;
229
230         for (i = 0; i < el->nr; i++)
231                 free(el->excludes[i]);
232         free(el->excludes);
233
234         el->nr = 0;
235         el->excludes = NULL;
236 }
237
238 int add_excludes_from_file_to_list(const char *fname,
239                                    const char *base,
240                                    int baselen,
241                                    char **buf_p,
242                                    struct exclude_list *which,
243                                    int check_index)
244 {
245         struct stat st;
246         int fd, i;
247         size_t size = 0;
248         char *buf, *entry;
249
250         fd = open(fname, O_RDONLY);
251         if (fd < 0 || fstat(fd, &st) < 0) {
252                 if (0 <= fd)
253                         close(fd);
254                 if (!check_index ||
255                     (buf = read_skip_worktree_file_from_index(fname, &size)) == NULL)
256                         return -1;
257                 if (size == 0) {
258                         free(buf);
259                         return 0;
260                 }
261                 if (buf[size-1] != '\n') {
262                         buf = xrealloc(buf, size+1);
263                         buf[size++] = '\n';
264                 }
265         }
266         else {
267                 size = xsize_t(st.st_size);
268                 if (size == 0) {
269                         close(fd);
270                         return 0;
271                 }
272                 buf = xmalloc(size+1);
273                 if (read_in_full(fd, buf, size) != size) {
274                         free(buf);
275                         close(fd);
276                         return -1;
277                 }
278                 buf[size++] = '\n';
279                 close(fd);
280         }
281
282         if (buf_p)
283                 *buf_p = buf;
284         entry = buf;
285         for (i = 0; i < size; i++) {
286                 if (buf[i] == '\n') {
287                         if (entry != buf + i && entry[0] != '#') {
288                                 buf[i - (i && buf[i-1] == '\r')] = 0;
289                                 add_exclude(entry, base, baselen, which);
290                         }
291                         entry = buf + i + 1;
292                 }
293         }
294         return 0;
295 }
296
297 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
298 {
299         if (add_excludes_from_file_to_list(fname, "", 0, NULL,
300                                            &dir->exclude_list[EXC_FILE], 0) < 0)
301                 die("cannot use %s as an exclude file", fname);
302 }
303
304 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
305 {
306         struct exclude_list *el;
307         struct exclude_stack *stk = NULL;
308         int current;
309
310         if ((!dir->exclude_per_dir) ||
311             (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
312                 return; /* too long a path -- ignore */
313
314         /* Pop the ones that are not the prefix of the path being checked. */
315         el = &dir->exclude_list[EXC_DIRS];
316         while ((stk = dir->exclude_stack) != NULL) {
317                 if (stk->baselen <= baselen &&
318                     !strncmp(dir->basebuf, base, stk->baselen))
319                         break;
320                 dir->exclude_stack = stk->prev;
321                 while (stk->exclude_ix < el->nr)
322                         free(el->excludes[--el->nr]);
323                 free(stk->filebuf);
324                 free(stk);
325         }
326
327         /* Read from the parent directories and push them down. */
328         current = stk ? stk->baselen : -1;
329         while (current < baselen) {
330                 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
331                 const char *cp;
332
333                 if (current < 0) {
334                         cp = base;
335                         current = 0;
336                 }
337                 else {
338                         cp = strchr(base + current + 1, '/');
339                         if (!cp)
340                                 die("oops in prep_exclude");
341                         cp++;
342                 }
343                 stk->prev = dir->exclude_stack;
344                 stk->baselen = cp - base;
345                 stk->exclude_ix = el->nr;
346                 memcpy(dir->basebuf + current, base + current,
347                        stk->baselen - current);
348                 strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
349                 add_excludes_from_file_to_list(dir->basebuf,
350                                                dir->basebuf, stk->baselen,
351                                                &stk->filebuf, el, 1);
352                 dir->exclude_stack = stk;
353                 current = stk->baselen;
354         }
355         dir->basebuf[baselen] = '\0';
356 }
357
358 /* Scan the list and let the last match determine the fate.
359  * Return 1 for exclude, 0 for include and -1 for undecided.
360  */
361 int excluded_from_list(const char *pathname,
362                        int pathlen, const char *basename, int *dtype,
363                        struct exclude_list *el)
364 {
365         int i;
366
367         if (el->nr) {
368                 for (i = el->nr - 1; 0 <= i; i--) {
369                         struct exclude *x = el->excludes[i];
370                         const char *exclude = x->pattern;
371                         int to_exclude = x->to_exclude;
372
373                         if (x->flags & EXC_FLAG_MUSTBEDIR) {
374                                 if (*dtype == DT_UNKNOWN)
375                                         *dtype = get_dtype(NULL, pathname, pathlen);
376                                 if (*dtype != DT_DIR)
377                                         continue;
378                         }
379
380                         if (x->flags & EXC_FLAG_NODIR) {
381                                 /* match basename */
382                                 if (x->flags & EXC_FLAG_NOWILDCARD) {
383                                         if (!strcmp(exclude, basename))
384                                                 return to_exclude;
385                                 } else if (x->flags & EXC_FLAG_ENDSWITH) {
386                                         if (x->patternlen - 1 <= pathlen &&
387                                             !strcmp(exclude + 1, pathname + pathlen - x->patternlen + 1))
388                                                 return to_exclude;
389                                 } else {
390                                         if (fnmatch(exclude, basename, 0) == 0)
391                                                 return to_exclude;
392                                 }
393                         }
394                         else {
395                                 /* match with FNM_PATHNAME:
396                                  * exclude has base (baselen long) implicitly
397                                  * in front of it.
398                                  */
399                                 int baselen = x->baselen;
400                                 if (*exclude == '/')
401                                         exclude++;
402
403                                 if (pathlen < baselen ||
404                                     (baselen && pathname[baselen-1] != '/') ||
405                                     strncmp(pathname, x->base, baselen))
406                                     continue;
407
408                                 if (x->flags & EXC_FLAG_NOWILDCARD) {
409                                         if (!strcmp(exclude, pathname + baselen))
410                                                 return to_exclude;
411                                 } else {
412                                         if (fnmatch(exclude, pathname+baselen,
413                                                     FNM_PATHNAME) == 0)
414                                             return to_exclude;
415                                 }
416                         }
417                 }
418         }
419         return -1; /* undecided */
420 }
421
422 int excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
423 {
424         int pathlen = strlen(pathname);
425         int st;
426         const char *basename = strrchr(pathname, '/');
427         basename = (basename) ? basename+1 : pathname;
428
429         prep_exclude(dir, pathname, basename-pathname);
430         for (st = EXC_CMDL; st <= EXC_FILE; st++) {
431                 switch (excluded_from_list(pathname, pathlen, basename,
432                                            dtype_p, &dir->exclude_list[st])) {
433                 case 0:
434                         return 0;
435                 case 1:
436                         return 1;
437                 }
438         }
439         return 0;
440 }
441
442 static struct dir_entry *dir_entry_new(const char *pathname, int len)
443 {
444         struct dir_entry *ent;
445
446         ent = xmalloc(sizeof(*ent) + len + 1);
447         ent->len = len;
448         memcpy(ent->name, pathname, len);
449         ent->name[len] = 0;
450         return ent;
451 }
452
453 static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
454 {
455         if (cache_name_exists(pathname, len, ignore_case))
456                 return NULL;
457
458         ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
459         return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
460 }
461
462 struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
463 {
464         if (!cache_name_is_other(pathname, len))
465                 return NULL;
466
467         ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
468         return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
469 }
470
471 enum exist_status {
472         index_nonexistent = 0,
473         index_directory,
474         index_gitdir
475 };
476
477 /*
478  * The index sorts alphabetically by entry name, which
479  * means that a gitlink sorts as '\0' at the end, while
480  * a directory (which is defined not as an entry, but as
481  * the files it contains) will sort with the '/' at the
482  * end.
483  */
484 static enum exist_status directory_exists_in_index(const char *dirname, int len)
485 {
486         int pos = cache_name_pos(dirname, len);
487         if (pos < 0)
488                 pos = -pos-1;
489         while (pos < active_nr) {
490                 struct cache_entry *ce = active_cache[pos++];
491                 unsigned char endchar;
492
493                 if (strncmp(ce->name, dirname, len))
494                         break;
495                 endchar = ce->name[len];
496                 if (endchar > '/')
497                         break;
498                 if (endchar == '/')
499                         return index_directory;
500                 if (!endchar && S_ISGITLINK(ce->ce_mode))
501                         return index_gitdir;
502         }
503         return index_nonexistent;
504 }
505
506 /*
507  * When we find a directory when traversing the filesystem, we
508  * have three distinct cases:
509  *
510  *  - ignore it
511  *  - see it as a directory
512  *  - recurse into it
513  *
514  * and which one we choose depends on a combination of existing
515  * git index contents and the flags passed into the directory
516  * traversal routine.
517  *
518  * Case 1: If we *already* have entries in the index under that
519  * directory name, we always recurse into the directory to see
520  * all the files.
521  *
522  * Case 2: If we *already* have that directory name as a gitlink,
523  * we always continue to see it as a gitlink, regardless of whether
524  * there is an actual git directory there or not (it might not
525  * be checked out as a subproject!)
526  *
527  * Case 3: if we didn't have it in the index previously, we
528  * have a few sub-cases:
529  *
530  *  (a) if "show_other_directories" is true, we show it as
531  *      just a directory, unless "hide_empty_directories" is
532  *      also true and the directory is empty, in which case
533  *      we just ignore it entirely.
534  *  (b) if it looks like a git directory, and we don't have
535  *      'no_gitlinks' set we treat it as a gitlink, and show it
536  *      as a directory.
537  *  (c) otherwise, we recurse into it.
538  */
539 enum directory_treatment {
540         show_directory,
541         ignore_directory,
542         recurse_into_directory
543 };
544
545 static enum directory_treatment treat_directory(struct dir_struct *dir,
546         const char *dirname, int len,
547         const struct path_simplify *simplify)
548 {
549         /* The "len-1" is to strip the final '/' */
550         switch (directory_exists_in_index(dirname, len-1)) {
551         case index_directory:
552                 return recurse_into_directory;
553
554         case index_gitdir:
555                 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
556                         return ignore_directory;
557                 return show_directory;
558
559         case index_nonexistent:
560                 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
561                         break;
562                 if (!(dir->flags & DIR_NO_GITLINKS)) {
563                         unsigned char sha1[20];
564                         if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
565                                 return show_directory;
566                 }
567                 return recurse_into_directory;
568         }
569
570         /* This is the "show_other_directories" case */
571         if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
572                 return show_directory;
573         if (!read_directory_recursive(dir, dirname, len, 1, simplify))
574                 return ignore_directory;
575         return show_directory;
576 }
577
578 /*
579  * This is an inexact early pruning of any recursive directory
580  * reading - if the path cannot possibly be in the pathspec,
581  * return true, and we'll skip it early.
582  */
583 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
584 {
585         if (simplify) {
586                 for (;;) {
587                         const char *match = simplify->path;
588                         int len = simplify->len;
589
590                         if (!match)
591                                 break;
592                         if (len > pathlen)
593                                 len = pathlen;
594                         if (!memcmp(path, match, len))
595                                 return 0;
596                         simplify++;
597                 }
598                 return 1;
599         }
600         return 0;
601 }
602
603 /*
604  * This function tells us whether an excluded path matches a
605  * list of "interesting" pathspecs. That is, whether a path matched
606  * by any of the pathspecs could possibly be ignored by excluding
607  * the specified path. This can happen if:
608  *
609  *   1. the path is mentioned explicitly in the pathspec
610  *
611  *   2. the path is a directory prefix of some element in the
612  *      pathspec
613  */
614 static int exclude_matches_pathspec(const char *path, int len,
615                 const struct path_simplify *simplify)
616 {
617         if (simplify) {
618                 for (; simplify->path; simplify++) {
619                         if (len == simplify->len
620                             && !memcmp(path, simplify->path, len))
621                                 return 1;
622                         if (len < simplify->len
623                             && simplify->path[len] == '/'
624                             && !memcmp(path, simplify->path, len))
625                                 return 1;
626                 }
627         }
628         return 0;
629 }
630
631 static int get_index_dtype(const char *path, int len)
632 {
633         int pos;
634         struct cache_entry *ce;
635
636         ce = cache_name_exists(path, len, 0);
637         if (ce) {
638                 if (!ce_uptodate(ce))
639                         return DT_UNKNOWN;
640                 if (S_ISGITLINK(ce->ce_mode))
641                         return DT_DIR;
642                 /*
643                  * Nobody actually cares about the
644                  * difference between DT_LNK and DT_REG
645                  */
646                 return DT_REG;
647         }
648
649         /* Try to look it up as a directory */
650         pos = cache_name_pos(path, len);
651         if (pos >= 0)
652                 return DT_UNKNOWN;
653         pos = -pos-1;
654         while (pos < active_nr) {
655                 ce = active_cache[pos++];
656                 if (strncmp(ce->name, path, len))
657                         break;
658                 if (ce->name[len] > '/')
659                         break;
660                 if (ce->name[len] < '/')
661                         continue;
662                 if (!ce_uptodate(ce))
663                         break;  /* continue? */
664                 return DT_DIR;
665         }
666         return DT_UNKNOWN;
667 }
668
669 static int get_dtype(struct dirent *de, const char *path, int len)
670 {
671         int dtype = de ? DTYPE(de) : DT_UNKNOWN;
672         struct stat st;
673
674         if (dtype != DT_UNKNOWN)
675                 return dtype;
676         dtype = get_index_dtype(path, len);
677         if (dtype != DT_UNKNOWN)
678                 return dtype;
679         if (lstat(path, &st))
680                 return dtype;
681         if (S_ISREG(st.st_mode))
682                 return DT_REG;
683         if (S_ISDIR(st.st_mode))
684                 return DT_DIR;
685         if (S_ISLNK(st.st_mode))
686                 return DT_LNK;
687         return dtype;
688 }
689
690 enum path_treatment {
691         path_ignored,
692         path_handled,
693         path_recurse
694 };
695
696 static enum path_treatment treat_one_path(struct dir_struct *dir,
697                                           char *path, int *len,
698                                           const struct path_simplify *simplify,
699                                           int dtype, struct dirent *de)
700 {
701         int exclude = excluded(dir, path, &dtype);
702         if (exclude && (dir->flags & DIR_COLLECT_IGNORED)
703             && exclude_matches_pathspec(path, *len, simplify))
704                 dir_add_ignored(dir, path, *len);
705
706         /*
707          * Excluded? If we don't explicitly want to show
708          * ignored files, ignore it
709          */
710         if (exclude && !(dir->flags & DIR_SHOW_IGNORED))
711                 return path_ignored;
712
713         if (dtype == DT_UNKNOWN)
714                 dtype = get_dtype(de, path, *len);
715
716         /*
717          * Do we want to see just the ignored files?
718          * We still need to recurse into directories,
719          * even if we don't ignore them, since the
720          * directory may contain files that we do..
721          */
722         if (!exclude && (dir->flags & DIR_SHOW_IGNORED)) {
723                 if (dtype != DT_DIR)
724                         return path_ignored;
725         }
726
727         switch (dtype) {
728         default:
729                 return path_ignored;
730         case DT_DIR:
731                 memcpy(path + *len, "/", 2);
732                 (*len)++;
733                 switch (treat_directory(dir, path, *len, simplify)) {
734                 case show_directory:
735                         if (exclude != !!(dir->flags
736                                           & DIR_SHOW_IGNORED))
737                                 return path_ignored;
738                         break;
739                 case recurse_into_directory:
740                         return path_recurse;
741                 case ignore_directory:
742                         return path_ignored;
743                 }
744                 break;
745         case DT_REG:
746         case DT_LNK:
747                 break;
748         }
749         return path_handled;
750 }
751
752 static enum path_treatment treat_path(struct dir_struct *dir,
753                                       struct dirent *de,
754                                       char *path, int path_max,
755                                       int baselen,
756                                       const struct path_simplify *simplify,
757                                       int *len)
758 {
759         int dtype;
760
761         if (is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name, ".git"))
762                 return path_ignored;
763         *len = strlen(de->d_name);
764         /* Ignore overly long pathnames! */
765         if (*len + baselen + 8 > path_max)
766                 return path_ignored;
767         memcpy(path + baselen, de->d_name, *len + 1);
768         *len += baselen;
769         if (simplify_away(path, *len, simplify))
770                 return path_ignored;
771
772         dtype = DTYPE(de);
773         return treat_one_path(dir, path, len, simplify, dtype, de);
774 }
775
776 /*
777  * Read a directory tree. We currently ignore anything but
778  * directories, regular files and symlinks. That's because git
779  * doesn't handle them at all yet. Maybe that will change some
780  * day.
781  *
782  * Also, we ignore the name ".git" (even if it is not a directory).
783  * That likely will not change.
784  */
785 static int read_directory_recursive(struct dir_struct *dir,
786                                     const char *base, int baselen,
787                                     int check_only,
788                                     const struct path_simplify *simplify)
789 {
790         DIR *fdir = opendir(*base ? base : ".");
791         int contents = 0;
792
793         if (fdir) {
794                 struct dirent *de;
795                 char path[PATH_MAX + 1];
796                 memcpy(path, base, baselen);
797
798                 while ((de = readdir(fdir)) != NULL) {
799                         int len;
800                         switch (treat_path(dir, de, path, sizeof(path),
801                                            baselen, simplify, &len)) {
802                         case path_recurse:
803                                 contents += read_directory_recursive
804                                         (dir, path, len, 0, simplify);
805                                 continue;
806                         case path_ignored:
807                                 continue;
808                         case path_handled:
809                                 break;
810                         }
811                         contents++;
812                         if (check_only)
813                                 goto exit_early;
814                         else
815                                 dir_add_name(dir, path, len);
816                 }
817 exit_early:
818                 closedir(fdir);
819         }
820
821         return contents;
822 }
823
824 static int cmp_name(const void *p1, const void *p2)
825 {
826         const struct dir_entry *e1 = *(const struct dir_entry **)p1;
827         const struct dir_entry *e2 = *(const struct dir_entry **)p2;
828
829         return cache_name_compare(e1->name, e1->len,
830                                   e2->name, e2->len);
831 }
832
833 /*
834  * Return the length of the "simple" part of a path match limiter.
835  */
836 static int simple_length(const char *match)
837 {
838         int len = -1;
839
840         for (;;) {
841                 unsigned char c = *match++;
842                 len++;
843                 if (c == '\0' || is_glob_special(c))
844                         return len;
845         }
846 }
847
848 static struct path_simplify *create_simplify(const char **pathspec)
849 {
850         int nr, alloc = 0;
851         struct path_simplify *simplify = NULL;
852
853         if (!pathspec)
854                 return NULL;
855
856         for (nr = 0 ; ; nr++) {
857                 const char *match;
858                 if (nr >= alloc) {
859                         alloc = alloc_nr(alloc);
860                         simplify = xrealloc(simplify, alloc * sizeof(*simplify));
861                 }
862                 match = *pathspec++;
863                 if (!match)
864                         break;
865                 simplify[nr].path = match;
866                 simplify[nr].len = simple_length(match);
867         }
868         simplify[nr].path = NULL;
869         simplify[nr].len = 0;
870         return simplify;
871 }
872
873 static void free_simplify(struct path_simplify *simplify)
874 {
875         free(simplify);
876 }
877
878 static int treat_leading_path(struct dir_struct *dir,
879                               const char *path, int len,
880                               const struct path_simplify *simplify)
881 {
882         char pathbuf[PATH_MAX];
883         int baselen, blen;
884         const char *cp;
885
886         while (len && path[len - 1] == '/')
887                 len--;
888         if (!len)
889                 return 1;
890         baselen = 0;
891         while (1) {
892                 cp = path + baselen + !!baselen;
893                 cp = memchr(cp, '/', path + len - cp);
894                 if (!cp)
895                         baselen = len;
896                 else
897                         baselen = cp - path;
898                 memcpy(pathbuf, path, baselen);
899                 pathbuf[baselen] = '\0';
900                 if (!is_directory(pathbuf))
901                         return 0;
902                 if (simplify_away(pathbuf, baselen, simplify))
903                         return 0;
904                 blen = baselen;
905                 if (treat_one_path(dir, pathbuf, &blen, simplify,
906                                    DT_DIR, NULL) == path_ignored)
907                         return 0; /* do not recurse into it */
908                 if (len <= baselen)
909                         return 1; /* finished checking */
910         }
911 }
912
913 int read_directory(struct dir_struct *dir, const char *path, int len, const char **pathspec)
914 {
915         struct path_simplify *simplify;
916
917         if (has_symlink_leading_path(path, len))
918                 return dir->nr;
919
920         simplify = create_simplify(pathspec);
921         if (!len || treat_leading_path(dir, path, len, simplify))
922                 read_directory_recursive(dir, path, len, 0, simplify);
923         free_simplify(simplify);
924         qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
925         qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
926         return dir->nr;
927 }
928
929 int file_exists(const char *f)
930 {
931         struct stat sb;
932         return lstat(f, &sb) == 0;
933 }
934
935 /*
936  * get_relative_cwd() gets the prefix of the current working directory
937  * relative to 'dir'.  If we are not inside 'dir', it returns NULL.
938  *
939  * As a convenience, it also returns NULL if 'dir' is already NULL.  The
940  * reason for this behaviour is that it is natural for functions returning
941  * directory names to return NULL to say "this directory does not exist"
942  * or "this directory is invalid".  These cases are usually handled the
943  * same as if the cwd is not inside 'dir' at all, so get_relative_cwd()
944  * returns NULL for both of them.
945  *
946  * Most notably, get_relative_cwd(buffer, size, get_git_work_tree())
947  * unifies the handling of "outside work tree" with "no work tree at all".
948  */
949 char *get_relative_cwd(char *buffer, int size, const char *dir)
950 {
951         char *cwd = buffer;
952
953         if (!dir)
954                 return NULL;
955         if (!getcwd(buffer, size))
956                 die_errno("can't find the current directory");
957
958         if (!is_absolute_path(dir))
959                 dir = make_absolute_path(dir);
960
961         while (*dir && *dir == *cwd) {
962                 dir++;
963                 cwd++;
964         }
965         if (*dir)
966                 return NULL;
967         switch (*cwd) {
968         case '\0':
969                 return cwd;
970         case '/':
971                 return cwd + 1;
972         default:
973                 return NULL;
974         }
975 }
976
977 int is_inside_dir(const char *dir)
978 {
979         char buffer[PATH_MAX];
980         return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
981 }
982
983 int is_empty_dir(const char *path)
984 {
985         DIR *dir = opendir(path);
986         struct dirent *e;
987         int ret = 1;
988
989         if (!dir)
990                 return 0;
991
992         while ((e = readdir(dir)) != NULL)
993                 if (!is_dot_or_dotdot(e->d_name)) {
994                         ret = 0;
995                         break;
996                 }
997
998         closedir(dir);
999         return ret;
1000 }
1001
1002 int remove_dir_recursively(struct strbuf *path, int flag)
1003 {
1004         DIR *dir;
1005         struct dirent *e;
1006         int ret = 0, original_len = path->len, len;
1007         int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
1008         unsigned char submodule_head[20];
1009
1010         if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
1011             !resolve_gitlink_ref(path->buf, "HEAD", submodule_head))
1012                 /* Do not descend and nuke a nested git work tree. */
1013                 return 0;
1014
1015         dir = opendir(path->buf);
1016         if (!dir)
1017                 return -1;
1018         if (path->buf[original_len - 1] != '/')
1019                 strbuf_addch(path, '/');
1020
1021         len = path->len;
1022         while ((e = readdir(dir)) != NULL) {
1023                 struct stat st;
1024                 if (is_dot_or_dotdot(e->d_name))
1025                         continue;
1026
1027                 strbuf_setlen(path, len);
1028                 strbuf_addstr(path, e->d_name);
1029                 if (lstat(path->buf, &st))
1030                         ; /* fall thru */
1031                 else if (S_ISDIR(st.st_mode)) {
1032                         if (!remove_dir_recursively(path, only_empty))
1033                                 continue; /* happy */
1034                 } else if (!only_empty && !unlink(path->buf))
1035                         continue; /* happy, too */
1036
1037                 /* path too long, stat fails, or non-directory still exists */
1038                 ret = -1;
1039                 break;
1040         }
1041         closedir(dir);
1042
1043         strbuf_setlen(path, original_len);
1044         if (!ret)
1045                 ret = rmdir(path->buf);
1046         return ret;
1047 }
1048
1049 void setup_standard_excludes(struct dir_struct *dir)
1050 {
1051         const char *path;
1052
1053         dir->exclude_per_dir = ".gitignore";
1054         path = git_path("info/exclude");
1055         if (!access(path, R_OK))
1056                 add_excludes_from_file(dir, path);
1057         if (excludes_file && !access(excludes_file, R_OK))
1058                 add_excludes_from_file(dir, excludes_file);
1059 }
1060
1061 int remove_path(const char *name)
1062 {
1063         char *slash;
1064
1065         if (unlink(name) && errno != ENOENT)
1066                 return -1;
1067
1068         slash = strrchr(name, '/');
1069         if (slash) {
1070                 char *dirs = xstrdup(name);
1071                 slash = dirs + (slash - name);
1072                 do {
1073                         *slash = '\0';
1074                 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
1075                 free(dirs);
1076         }
1077         return 0;
1078 }
1079