dir: ignore trailing spaces in exclude patterns
[git] / dir.c
1 /*
2  * This handles recursive filename detection with exclude
3  * files, index knowledge etc..
4  *
5  * See Documentation/technical/api-directory-listing.txt
6  *
7  * Copyright (C) Linus Torvalds, 2005-2006
8  *               Junio Hamano, 2005-2006
9  */
10 #include "cache.h"
11 #include "dir.h"
12 #include "refs.h"
13 #include "wildmatch.h"
14 #include "pathspec.h"
15
16 struct path_simplify {
17         int len;
18         const char *path;
19 };
20
21 /*
22  * Tells read_directory_recursive how a file or directory should be treated.
23  * Values are ordered by significance, e.g. if a directory contains both
24  * excluded and untracked files, it is listed as untracked because
25  * path_untracked > path_excluded.
26  */
27 enum path_treatment {
28         path_none = 0,
29         path_recurse,
30         path_excluded,
31         path_untracked
32 };
33
34 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
35         const char *path, int len,
36         int check_only, const struct path_simplify *simplify);
37 static int get_dtype(struct dirent *de, const char *path, int len);
38
39 /* helper string functions with support for the ignore_case flag */
40 int strcmp_icase(const char *a, const char *b)
41 {
42         return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
43 }
44
45 int strncmp_icase(const char *a, const char *b, size_t count)
46 {
47         return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
48 }
49
50 int fnmatch_icase(const char *pattern, const char *string, int flags)
51 {
52         return fnmatch(pattern, string, flags | (ignore_case ? FNM_CASEFOLD : 0));
53 }
54
55 inline int git_fnmatch(const struct pathspec_item *item,
56                        const char *pattern, const char *string,
57                        int prefix)
58 {
59         if (prefix > 0) {
60                 if (ps_strncmp(item, pattern, string, prefix))
61                         return FNM_NOMATCH;
62                 pattern += prefix;
63                 string += prefix;
64         }
65         if (item->flags & PATHSPEC_ONESTAR) {
66                 int pattern_len = strlen(++pattern);
67                 int string_len = strlen(string);
68                 return string_len < pattern_len ||
69                         ps_strcmp(item, pattern,
70                                   string + string_len - pattern_len);
71         }
72         if (item->magic & PATHSPEC_GLOB)
73                 return wildmatch(pattern, string,
74                                  WM_PATHNAME |
75                                  (item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0),
76                                  NULL);
77         else
78                 /* wildmatch has not learned no FNM_PATHNAME mode yet */
79                 return fnmatch(pattern, string,
80                                item->magic & PATHSPEC_ICASE ? FNM_CASEFOLD : 0);
81 }
82
83 static int fnmatch_icase_mem(const char *pattern, int patternlen,
84                              const char *string, int stringlen,
85                              int flags)
86 {
87         int match_status;
88         struct strbuf pat_buf = STRBUF_INIT;
89         struct strbuf str_buf = STRBUF_INIT;
90         const char *use_pat = pattern;
91         const char *use_str = string;
92
93         if (pattern[patternlen]) {
94                 strbuf_add(&pat_buf, pattern, patternlen);
95                 use_pat = pat_buf.buf;
96         }
97         if (string[stringlen]) {
98                 strbuf_add(&str_buf, string, stringlen);
99                 use_str = str_buf.buf;
100         }
101
102         if (ignore_case)
103                 flags |= WM_CASEFOLD;
104         match_status = wildmatch(use_pat, use_str, flags, NULL);
105
106         strbuf_release(&pat_buf);
107         strbuf_release(&str_buf);
108
109         return match_status;
110 }
111
112 static size_t common_prefix_len(const struct pathspec *pathspec)
113 {
114         int n;
115         size_t max = 0;
116
117         /*
118          * ":(icase)path" is treated as a pathspec full of
119          * wildcard. In other words, only prefix is considered common
120          * prefix. If the pathspec is abc/foo abc/bar, running in
121          * subdir xyz, the common prefix is still xyz, not xuz/abc as
122          * in non-:(icase).
123          */
124         GUARD_PATHSPEC(pathspec,
125                        PATHSPEC_FROMTOP |
126                        PATHSPEC_MAXDEPTH |
127                        PATHSPEC_LITERAL |
128                        PATHSPEC_GLOB |
129                        PATHSPEC_ICASE);
130
131         for (n = 0; n < pathspec->nr; n++) {
132                 size_t i = 0, len = 0, item_len;
133                 if (pathspec->items[n].magic & PATHSPEC_ICASE)
134                         item_len = pathspec->items[n].prefix;
135                 else
136                         item_len = pathspec->items[n].nowildcard_len;
137                 while (i < item_len && (n == 0 || i < max)) {
138                         char c = pathspec->items[n].match[i];
139                         if (c != pathspec->items[0].match[i])
140                                 break;
141                         if (c == '/')
142                                 len = i + 1;
143                         i++;
144                 }
145                 if (n == 0 || len < max) {
146                         max = len;
147                         if (!max)
148                                 break;
149                 }
150         }
151         return max;
152 }
153
154 /*
155  * Returns a copy of the longest leading path common among all
156  * pathspecs.
157  */
158 char *common_prefix(const struct pathspec *pathspec)
159 {
160         unsigned long len = common_prefix_len(pathspec);
161
162         return len ? xmemdupz(pathspec->items[0].match, len) : NULL;
163 }
164
165 int fill_directory(struct dir_struct *dir, const struct pathspec *pathspec)
166 {
167         size_t len;
168
169         /*
170          * Calculate common prefix for the pathspec, and
171          * use that to optimize the directory walk
172          */
173         len = common_prefix_len(pathspec);
174
175         /* Read the directory and prune it */
176         read_directory(dir, pathspec->nr ? pathspec->_raw[0] : "", len, pathspec);
177         return len;
178 }
179
180 int within_depth(const char *name, int namelen,
181                         int depth, int max_depth)
182 {
183         const char *cp = name, *cpe = name + namelen;
184
185         while (cp < cpe) {
186                 if (*cp++ != '/')
187                         continue;
188                 depth++;
189                 if (depth > max_depth)
190                         return 0;
191         }
192         return 1;
193 }
194
195 /*
196  * Does 'match' match the given name?
197  * A match is found if
198  *
199  * (1) the 'match' string is leading directory of 'name', or
200  * (2) the 'match' string is a wildcard and matches 'name', or
201  * (3) the 'match' string is exactly the same as 'name'.
202  *
203  * and the return value tells which case it was.
204  *
205  * It returns 0 when there is no match.
206  */
207 static int match_pathspec_item(const struct pathspec_item *item, int prefix,
208                                const char *name, int namelen)
209 {
210         /* name/namelen has prefix cut off by caller */
211         const char *match = item->match + prefix;
212         int matchlen = item->len - prefix;
213
214         /*
215          * The normal call pattern is:
216          * 1. prefix = common_prefix_len(ps);
217          * 2. prune something, or fill_directory
218          * 3. match_pathspec_depth()
219          *
220          * 'prefix' at #1 may be shorter than the command's prefix and
221          * it's ok for #2 to match extra files. Those extras will be
222          * trimmed at #3.
223          *
224          * Suppose the pathspec is 'foo' and '../bar' running from
225          * subdir 'xyz'. The common prefix at #1 will be empty, thanks
226          * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
227          * user does not want XYZ/foo, only the "foo" part should be
228          * case-insensitive. We need to filter out XYZ/foo here. In
229          * other words, we do not trust the caller on comparing the
230          * prefix part when :(icase) is involved. We do exact
231          * comparison ourselves.
232          *
233          * Normally the caller (common_prefix_len() in fact) does
234          * _exact_ matching on name[-prefix+1..-1] and we do not need
235          * to check that part. Be defensive and check it anyway, in
236          * case common_prefix_len is changed, or a new caller is
237          * introduced that does not use common_prefix_len.
238          *
239          * If the penalty turns out too high when prefix is really
240          * long, maybe change it to
241          * strncmp(match, name, item->prefix - prefix)
242          */
243         if (item->prefix && (item->magic & PATHSPEC_ICASE) &&
244             strncmp(item->match, name - prefix, item->prefix))
245                 return 0;
246
247         /* If the match was just the prefix, we matched */
248         if (!*match)
249                 return MATCHED_RECURSIVELY;
250
251         if (matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) {
252                 if (matchlen == namelen)
253                         return MATCHED_EXACTLY;
254
255                 if (match[matchlen-1] == '/' || name[matchlen] == '/')
256                         return MATCHED_RECURSIVELY;
257         }
258
259         if (item->nowildcard_len < item->len &&
260             !git_fnmatch(item, match, name,
261                          item->nowildcard_len - prefix))
262                 return MATCHED_FNMATCH;
263
264         return 0;
265 }
266
267 /*
268  * Given a name and a list of pathspecs, returns the nature of the
269  * closest (i.e. most specific) match of the name to any of the
270  * pathspecs.
271  *
272  * The caller typically calls this multiple times with the same
273  * pathspec and seen[] array but with different name/namelen
274  * (e.g. entries from the index) and is interested in seeing if and
275  * how each pathspec matches all the names it calls this function
276  * with.  A mark is left in the seen[] array for each pathspec element
277  * indicating the closest type of match that element achieved, so if
278  * seen[n] remains zero after multiple invocations, that means the nth
279  * pathspec did not match any names, which could indicate that the
280  * user mistyped the nth pathspec.
281  */
282 int match_pathspec_depth(const struct pathspec *ps,
283                          const char *name, int namelen,
284                          int prefix, char *seen)
285 {
286         int i, retval = 0;
287
288         GUARD_PATHSPEC(ps,
289                        PATHSPEC_FROMTOP |
290                        PATHSPEC_MAXDEPTH |
291                        PATHSPEC_LITERAL |
292                        PATHSPEC_GLOB |
293                        PATHSPEC_ICASE);
294
295         if (!ps->nr) {
296                 if (!ps->recursive ||
297                     !(ps->magic & PATHSPEC_MAXDEPTH) ||
298                     ps->max_depth == -1)
299                         return MATCHED_RECURSIVELY;
300
301                 if (within_depth(name, namelen, 0, ps->max_depth))
302                         return MATCHED_EXACTLY;
303                 else
304                         return 0;
305         }
306
307         name += prefix;
308         namelen -= prefix;
309
310         for (i = ps->nr - 1; i >= 0; i--) {
311                 int how;
312                 if (seen && seen[i] == MATCHED_EXACTLY)
313                         continue;
314                 how = match_pathspec_item(ps->items+i, prefix, name, namelen);
315                 if (ps->recursive &&
316                     (ps->magic & PATHSPEC_MAXDEPTH) &&
317                     ps->max_depth != -1 &&
318                     how && how != MATCHED_FNMATCH) {
319                         int len = ps->items[i].len;
320                         if (name[len] == '/')
321                                 len++;
322                         if (within_depth(name+len, namelen-len, 0, ps->max_depth))
323                                 how = MATCHED_EXACTLY;
324                         else
325                                 how = 0;
326                 }
327                 if (how) {
328                         if (retval < how)
329                                 retval = how;
330                         if (seen && seen[i] < how)
331                                 seen[i] = how;
332                 }
333         }
334         return retval;
335 }
336
337 /*
338  * Return the length of the "simple" part of a path match limiter.
339  */
340 int simple_length(const char *match)
341 {
342         int len = -1;
343
344         for (;;) {
345                 unsigned char c = *match++;
346                 len++;
347                 if (c == '\0' || is_glob_special(c))
348                         return len;
349         }
350 }
351
352 int no_wildcard(const char *string)
353 {
354         return string[simple_length(string)] == '\0';
355 }
356
357 void parse_exclude_pattern(const char **pattern,
358                            int *patternlen,
359                            int *flags,
360                            int *nowildcardlen)
361 {
362         const char *p = *pattern;
363         size_t i, len;
364
365         *flags = 0;
366         if (*p == '!') {
367                 *flags |= EXC_FLAG_NEGATIVE;
368                 p++;
369         }
370         len = strlen(p);
371         if (len && p[len - 1] == '/') {
372                 len--;
373                 *flags |= EXC_FLAG_MUSTBEDIR;
374         }
375         for (i = 0; i < len; i++) {
376                 if (p[i] == '/')
377                         break;
378         }
379         if (i == len)
380                 *flags |= EXC_FLAG_NODIR;
381         *nowildcardlen = simple_length(p);
382         /*
383          * we should have excluded the trailing slash from 'p' too,
384          * but that's one more allocation. Instead just make sure
385          * nowildcardlen does not exceed real patternlen
386          */
387         if (*nowildcardlen > len)
388                 *nowildcardlen = len;
389         if (*p == '*' && no_wildcard(p + 1))
390                 *flags |= EXC_FLAG_ENDSWITH;
391         *pattern = p;
392         *patternlen = len;
393 }
394
395 void add_exclude(const char *string, const char *base,
396                  int baselen, struct exclude_list *el, int srcpos)
397 {
398         struct exclude *x;
399         int patternlen;
400         int flags;
401         int nowildcardlen;
402
403         parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen);
404         if (flags & EXC_FLAG_MUSTBEDIR) {
405                 char *s;
406                 x = xmalloc(sizeof(*x) + patternlen + 1);
407                 s = (char *)(x+1);
408                 memcpy(s, string, patternlen);
409                 s[patternlen] = '\0';
410                 x->pattern = s;
411         } else {
412                 x = xmalloc(sizeof(*x));
413                 x->pattern = string;
414         }
415         x->patternlen = patternlen;
416         x->nowildcardlen = nowildcardlen;
417         x->base = base;
418         x->baselen = baselen;
419         x->flags = flags;
420         x->srcpos = srcpos;
421         ALLOC_GROW(el->excludes, el->nr + 1, el->alloc);
422         el->excludes[el->nr++] = x;
423         x->el = el;
424 }
425
426 static void *read_skip_worktree_file_from_index(const char *path, size_t *size)
427 {
428         int pos, len;
429         unsigned long sz;
430         enum object_type type;
431         void *data;
432
433         len = strlen(path);
434         pos = cache_name_pos(path, len);
435         if (pos < 0)
436                 return NULL;
437         if (!ce_skip_worktree(active_cache[pos]))
438                 return NULL;
439         data = read_sha1_file(active_cache[pos]->sha1, &type, &sz);
440         if (!data || type != OBJ_BLOB) {
441                 free(data);
442                 return NULL;
443         }
444         *size = xsize_t(sz);
445         return data;
446 }
447
448 /*
449  * Frees memory within el which was allocated for exclude patterns and
450  * the file buffer.  Does not free el itself.
451  */
452 void clear_exclude_list(struct exclude_list *el)
453 {
454         int i;
455
456         for (i = 0; i < el->nr; i++)
457                 free(el->excludes[i]);
458         free(el->excludes);
459         free(el->filebuf);
460
461         el->nr = 0;
462         el->excludes = NULL;
463         el->filebuf = NULL;
464 }
465
466 static void trim_trailing_spaces(char *buf)
467 {
468         int i, last_space = -1, nr_spaces, len = strlen(buf);
469         for (i = 0; i < len; i++)
470                 if (buf[i] == '\\')
471                         i++;
472                 else if (buf[i] == ' ') {
473                         if (last_space == -1) {
474                                 last_space = i;
475                                 nr_spaces = 1;
476                         } else
477                                 nr_spaces++;
478                 } else
479                         last_space = -1;
480
481         if (last_space != -1 && last_space + nr_spaces == len)
482                 buf[last_space] = '\0';
483 }
484
485 int add_excludes_from_file_to_list(const char *fname,
486                                    const char *base,
487                                    int baselen,
488                                    struct exclude_list *el,
489                                    int check_index)
490 {
491         struct stat st;
492         int fd, i, lineno = 1;
493         size_t size = 0;
494         char *buf, *entry;
495
496         fd = open(fname, O_RDONLY);
497         if (fd < 0 || fstat(fd, &st) < 0) {
498                 if (errno != ENOENT)
499                         warn_on_inaccessible(fname);
500                 if (0 <= fd)
501                         close(fd);
502                 if (!check_index ||
503                     (buf = read_skip_worktree_file_from_index(fname, &size)) == NULL)
504                         return -1;
505                 if (size == 0) {
506                         free(buf);
507                         return 0;
508                 }
509                 if (buf[size-1] != '\n') {
510                         buf = xrealloc(buf, size+1);
511                         buf[size++] = '\n';
512                 }
513         }
514         else {
515                 size = xsize_t(st.st_size);
516                 if (size == 0) {
517                         close(fd);
518                         return 0;
519                 }
520                 buf = xmalloc(size+1);
521                 if (read_in_full(fd, buf, size) != size) {
522                         free(buf);
523                         close(fd);
524                         return -1;
525                 }
526                 buf[size++] = '\n';
527                 close(fd);
528         }
529
530         el->filebuf = buf;
531         entry = buf;
532         for (i = 0; i < size; i++) {
533                 if (buf[i] == '\n') {
534                         if (entry != buf + i && entry[0] != '#') {
535                                 buf[i - (i && buf[i-1] == '\r')] = 0;
536                                 trim_trailing_spaces(entry);
537                                 add_exclude(entry, base, baselen, el, lineno);
538                         }
539                         lineno++;
540                         entry = buf + i + 1;
541                 }
542         }
543         return 0;
544 }
545
546 struct exclude_list *add_exclude_list(struct dir_struct *dir,
547                                       int group_type, const char *src)
548 {
549         struct exclude_list *el;
550         struct exclude_list_group *group;
551
552         group = &dir->exclude_list_group[group_type];
553         ALLOC_GROW(group->el, group->nr + 1, group->alloc);
554         el = &group->el[group->nr++];
555         memset(el, 0, sizeof(*el));
556         el->src = src;
557         return el;
558 }
559
560 /*
561  * Used to set up core.excludesfile and .git/info/exclude lists.
562  */
563 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
564 {
565         struct exclude_list *el;
566         el = add_exclude_list(dir, EXC_FILE, fname);
567         if (add_excludes_from_file_to_list(fname, "", 0, el, 0) < 0)
568                 die("cannot use %s as an exclude file", fname);
569 }
570
571 int match_basename(const char *basename, int basenamelen,
572                    const char *pattern, int prefix, int patternlen,
573                    int flags)
574 {
575         if (prefix == patternlen) {
576                 if (patternlen == basenamelen &&
577                     !strncmp_icase(pattern, basename, basenamelen))
578                         return 1;
579         } else if (flags & EXC_FLAG_ENDSWITH) {
580                 /* "*literal" matching against "fooliteral" */
581                 if (patternlen - 1 <= basenamelen &&
582                     !strncmp_icase(pattern + 1,
583                                    basename + basenamelen - (patternlen - 1),
584                                    patternlen - 1))
585                         return 1;
586         } else {
587                 if (fnmatch_icase_mem(pattern, patternlen,
588                                       basename, basenamelen,
589                                       0) == 0)
590                         return 1;
591         }
592         return 0;
593 }
594
595 int match_pathname(const char *pathname, int pathlen,
596                    const char *base, int baselen,
597                    const char *pattern, int prefix, int patternlen,
598                    int flags)
599 {
600         const char *name;
601         int namelen;
602
603         /*
604          * match with FNM_PATHNAME; the pattern has base implicitly
605          * in front of it.
606          */
607         if (*pattern == '/') {
608                 pattern++;
609                 patternlen--;
610                 prefix--;
611         }
612
613         /*
614          * baselen does not count the trailing slash. base[] may or
615          * may not end with a trailing slash though.
616          */
617         if (pathlen < baselen + 1 ||
618             (baselen && pathname[baselen] != '/') ||
619             strncmp_icase(pathname, base, baselen))
620                 return 0;
621
622         namelen = baselen ? pathlen - baselen - 1 : pathlen;
623         name = pathname + pathlen - namelen;
624
625         if (prefix) {
626                 /*
627                  * if the non-wildcard part is longer than the
628                  * remaining pathname, surely it cannot match.
629                  */
630                 if (prefix > namelen)
631                         return 0;
632
633                 if (strncmp_icase(pattern, name, prefix))
634                         return 0;
635                 pattern += prefix;
636                 patternlen -= prefix;
637                 name    += prefix;
638                 namelen -= prefix;
639
640                 /*
641                  * If the whole pattern did not have a wildcard,
642                  * then our prefix match is all we need; we
643                  * do not need to call fnmatch at all.
644                  */
645                 if (!patternlen && !namelen)
646                         return 1;
647         }
648
649         return fnmatch_icase_mem(pattern, patternlen,
650                                  name, namelen,
651                                  WM_PATHNAME) == 0;
652 }
653
654 /*
655  * Scan the given exclude list in reverse to see whether pathname
656  * should be ignored.  The first match (i.e. the last on the list), if
657  * any, determines the fate.  Returns the exclude_list element which
658  * matched, or NULL for undecided.
659  */
660 static struct exclude *last_exclude_matching_from_list(const char *pathname,
661                                                        int pathlen,
662                                                        const char *basename,
663                                                        int *dtype,
664                                                        struct exclude_list *el)
665 {
666         int i;
667
668         if (!el->nr)
669                 return NULL;    /* undefined */
670
671         for (i = el->nr - 1; 0 <= i; i--) {
672                 struct exclude *x = el->excludes[i];
673                 const char *exclude = x->pattern;
674                 int prefix = x->nowildcardlen;
675
676                 if (x->flags & EXC_FLAG_MUSTBEDIR) {
677                         if (*dtype == DT_UNKNOWN)
678                                 *dtype = get_dtype(NULL, pathname, pathlen);
679                         if (*dtype != DT_DIR)
680                                 continue;
681                 }
682
683                 if (x->flags & EXC_FLAG_NODIR) {
684                         if (match_basename(basename,
685                                            pathlen - (basename - pathname),
686                                            exclude, prefix, x->patternlen,
687                                            x->flags))
688                                 return x;
689                         continue;
690                 }
691
692                 assert(x->baselen == 0 || x->base[x->baselen - 1] == '/');
693                 if (match_pathname(pathname, pathlen,
694                                    x->base, x->baselen ? x->baselen - 1 : 0,
695                                    exclude, prefix, x->patternlen, x->flags))
696                         return x;
697         }
698         return NULL; /* undecided */
699 }
700
701 /*
702  * Scan the list and let the last match determine the fate.
703  * Return 1 for exclude, 0 for include and -1 for undecided.
704  */
705 int is_excluded_from_list(const char *pathname,
706                           int pathlen, const char *basename, int *dtype,
707                           struct exclude_list *el)
708 {
709         struct exclude *exclude;
710         exclude = last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el);
711         if (exclude)
712                 return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
713         return -1; /* undecided */
714 }
715
716 static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir,
717                 const char *pathname, int pathlen, const char *basename,
718                 int *dtype_p)
719 {
720         int i, j;
721         struct exclude_list_group *group;
722         struct exclude *exclude;
723         for (i = EXC_CMDL; i <= EXC_FILE; i++) {
724                 group = &dir->exclude_list_group[i];
725                 for (j = group->nr - 1; j >= 0; j--) {
726                         exclude = last_exclude_matching_from_list(
727                                 pathname, pathlen, basename, dtype_p,
728                                 &group->el[j]);
729                         if (exclude)
730                                 return exclude;
731                 }
732         }
733         return NULL;
734 }
735
736 /*
737  * Loads the per-directory exclude list for the substring of base
738  * which has a char length of baselen.
739  */
740 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
741 {
742         struct exclude_list_group *group;
743         struct exclude_list *el;
744         struct exclude_stack *stk = NULL;
745         int current;
746
747         group = &dir->exclude_list_group[EXC_DIRS];
748
749         /* Pop the exclude lists from the EXCL_DIRS exclude_list_group
750          * which originate from directories not in the prefix of the
751          * path being checked. */
752         while ((stk = dir->exclude_stack) != NULL) {
753                 if (stk->baselen <= baselen &&
754                     !strncmp(dir->basebuf, base, stk->baselen))
755                         break;
756                 el = &group->el[dir->exclude_stack->exclude_ix];
757                 dir->exclude_stack = stk->prev;
758                 dir->exclude = NULL;
759                 free((char *)el->src); /* see strdup() below */
760                 clear_exclude_list(el);
761                 free(stk);
762                 group->nr--;
763         }
764
765         /* Skip traversing into sub directories if the parent is excluded */
766         if (dir->exclude)
767                 return;
768
769         /* Read from the parent directories and push them down. */
770         current = stk ? stk->baselen : -1;
771         while (current < baselen) {
772                 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
773                 const char *cp;
774
775                 if (current < 0) {
776                         cp = base;
777                         current = 0;
778                 }
779                 else {
780                         cp = strchr(base + current + 1, '/');
781                         if (!cp)
782                                 die("oops in prep_exclude");
783                         cp++;
784                 }
785                 stk->prev = dir->exclude_stack;
786                 stk->baselen = cp - base;
787                 stk->exclude_ix = group->nr;
788                 el = add_exclude_list(dir, EXC_DIRS, NULL);
789                 memcpy(dir->basebuf + current, base + current,
790                        stk->baselen - current);
791
792                 /* Abort if the directory is excluded */
793                 if (stk->baselen) {
794                         int dt = DT_DIR;
795                         dir->basebuf[stk->baselen - 1] = 0;
796                         dir->exclude = last_exclude_matching_from_lists(dir,
797                                 dir->basebuf, stk->baselen - 1,
798                                 dir->basebuf + current, &dt);
799                         dir->basebuf[stk->baselen - 1] = '/';
800                         if (dir->exclude &&
801                             dir->exclude->flags & EXC_FLAG_NEGATIVE)
802                                 dir->exclude = NULL;
803                         if (dir->exclude) {
804                                 dir->basebuf[stk->baselen] = 0;
805                                 dir->exclude_stack = stk;
806                                 return;
807                         }
808                 }
809
810                 /* Try to read per-directory file unless path is too long */
811                 if (dir->exclude_per_dir &&
812                     stk->baselen + strlen(dir->exclude_per_dir) < PATH_MAX) {
813                         strcpy(dir->basebuf + stk->baselen,
814                                         dir->exclude_per_dir);
815                         /*
816                          * dir->basebuf gets reused by the traversal, but we
817                          * need fname to remain unchanged to ensure the src
818                          * member of each struct exclude correctly
819                          * back-references its source file.  Other invocations
820                          * of add_exclude_list provide stable strings, so we
821                          * strdup() and free() here in the caller.
822                          */
823                         el->src = strdup(dir->basebuf);
824                         add_excludes_from_file_to_list(dir->basebuf,
825                                         dir->basebuf, stk->baselen, el, 1);
826                 }
827                 dir->exclude_stack = stk;
828                 current = stk->baselen;
829         }
830         dir->basebuf[baselen] = '\0';
831 }
832
833 /*
834  * Loads the exclude lists for the directory containing pathname, then
835  * scans all exclude lists to determine whether pathname is excluded.
836  * Returns the exclude_list element which matched, or NULL for
837  * undecided.
838  */
839 struct exclude *last_exclude_matching(struct dir_struct *dir,
840                                              const char *pathname,
841                                              int *dtype_p)
842 {
843         int pathlen = strlen(pathname);
844         const char *basename = strrchr(pathname, '/');
845         basename = (basename) ? basename+1 : pathname;
846
847         prep_exclude(dir, pathname, basename-pathname);
848
849         if (dir->exclude)
850                 return dir->exclude;
851
852         return last_exclude_matching_from_lists(dir, pathname, pathlen,
853                         basename, dtype_p);
854 }
855
856 /*
857  * Loads the exclude lists for the directory containing pathname, then
858  * scans all exclude lists to determine whether pathname is excluded.
859  * Returns 1 if true, otherwise 0.
860  */
861 int is_excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
862 {
863         struct exclude *exclude =
864                 last_exclude_matching(dir, pathname, dtype_p);
865         if (exclude)
866                 return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
867         return 0;
868 }
869
870 static struct dir_entry *dir_entry_new(const char *pathname, int len)
871 {
872         struct dir_entry *ent;
873
874         ent = xmalloc(sizeof(*ent) + len + 1);
875         ent->len = len;
876         memcpy(ent->name, pathname, len);
877         ent->name[len] = 0;
878         return ent;
879 }
880
881 static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
882 {
883         if (cache_file_exists(pathname, len, ignore_case))
884                 return NULL;
885
886         ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
887         return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
888 }
889
890 struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
891 {
892         if (!cache_name_is_other(pathname, len))
893                 return NULL;
894
895         ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
896         return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
897 }
898
899 enum exist_status {
900         index_nonexistent = 0,
901         index_directory,
902         index_gitdir
903 };
904
905 /*
906  * Do not use the alphabetically sorted index to look up
907  * the directory name; instead, use the case insensitive
908  * directory hash.
909  */
910 static enum exist_status directory_exists_in_index_icase(const char *dirname, int len)
911 {
912         const struct cache_entry *ce = cache_dir_exists(dirname, len);
913         unsigned char endchar;
914
915         if (!ce)
916                 return index_nonexistent;
917         endchar = ce->name[len];
918
919         /*
920          * The cache_entry structure returned will contain this dirname
921          * and possibly additional path components.
922          */
923         if (endchar == '/')
924                 return index_directory;
925
926         /*
927          * If there are no additional path components, then this cache_entry
928          * represents a submodule.  Submodules, despite being directories,
929          * are stored in the cache without a closing slash.
930          */
931         if (!endchar && S_ISGITLINK(ce->ce_mode))
932                 return index_gitdir;
933
934         /* This should never be hit, but it exists just in case. */
935         return index_nonexistent;
936 }
937
938 /*
939  * The index sorts alphabetically by entry name, which
940  * means that a gitlink sorts as '\0' at the end, while
941  * a directory (which is defined not as an entry, but as
942  * the files it contains) will sort with the '/' at the
943  * end.
944  */
945 static enum exist_status directory_exists_in_index(const char *dirname, int len)
946 {
947         int pos;
948
949         if (ignore_case)
950                 return directory_exists_in_index_icase(dirname, len);
951
952         pos = cache_name_pos(dirname, len);
953         if (pos < 0)
954                 pos = -pos-1;
955         while (pos < active_nr) {
956                 const struct cache_entry *ce = active_cache[pos++];
957                 unsigned char endchar;
958
959                 if (strncmp(ce->name, dirname, len))
960                         break;
961                 endchar = ce->name[len];
962                 if (endchar > '/')
963                         break;
964                 if (endchar == '/')
965                         return index_directory;
966                 if (!endchar && S_ISGITLINK(ce->ce_mode))
967                         return index_gitdir;
968         }
969         return index_nonexistent;
970 }
971
972 /*
973  * When we find a directory when traversing the filesystem, we
974  * have three distinct cases:
975  *
976  *  - ignore it
977  *  - see it as a directory
978  *  - recurse into it
979  *
980  * and which one we choose depends on a combination of existing
981  * git index contents and the flags passed into the directory
982  * traversal routine.
983  *
984  * Case 1: If we *already* have entries in the index under that
985  * directory name, we always recurse into the directory to see
986  * all the files.
987  *
988  * Case 2: If we *already* have that directory name as a gitlink,
989  * we always continue to see it as a gitlink, regardless of whether
990  * there is an actual git directory there or not (it might not
991  * be checked out as a subproject!)
992  *
993  * Case 3: if we didn't have it in the index previously, we
994  * have a few sub-cases:
995  *
996  *  (a) if "show_other_directories" is true, we show it as
997  *      just a directory, unless "hide_empty_directories" is
998  *      also true, in which case we need to check if it contains any
999  *      untracked and / or ignored files.
1000  *  (b) if it looks like a git directory, and we don't have
1001  *      'no_gitlinks' set we treat it as a gitlink, and show it
1002  *      as a directory.
1003  *  (c) otherwise, we recurse into it.
1004  */
1005 static enum path_treatment treat_directory(struct dir_struct *dir,
1006         const char *dirname, int len, int exclude,
1007         const struct path_simplify *simplify)
1008 {
1009         /* The "len-1" is to strip the final '/' */
1010         switch (directory_exists_in_index(dirname, len-1)) {
1011         case index_directory:
1012                 return path_recurse;
1013
1014         case index_gitdir:
1015                 return path_none;
1016
1017         case index_nonexistent:
1018                 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
1019                         break;
1020                 if (!(dir->flags & DIR_NO_GITLINKS)) {
1021                         unsigned char sha1[20];
1022                         if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
1023                                 return path_untracked;
1024                 }
1025                 return path_recurse;
1026         }
1027
1028         /* This is the "show_other_directories" case */
1029
1030         if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1031                 return exclude ? path_excluded : path_untracked;
1032
1033         return read_directory_recursive(dir, dirname, len, 1, simplify);
1034 }
1035
1036 /*
1037  * This is an inexact early pruning of any recursive directory
1038  * reading - if the path cannot possibly be in the pathspec,
1039  * return true, and we'll skip it early.
1040  */
1041 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
1042 {
1043         if (simplify) {
1044                 for (;;) {
1045                         const char *match = simplify->path;
1046                         int len = simplify->len;
1047
1048                         if (!match)
1049                                 break;
1050                         if (len > pathlen)
1051                                 len = pathlen;
1052                         if (!memcmp(path, match, len))
1053                                 return 0;
1054                         simplify++;
1055                 }
1056                 return 1;
1057         }
1058         return 0;
1059 }
1060
1061 /*
1062  * This function tells us whether an excluded path matches a
1063  * list of "interesting" pathspecs. That is, whether a path matched
1064  * by any of the pathspecs could possibly be ignored by excluding
1065  * the specified path. This can happen if:
1066  *
1067  *   1. the path is mentioned explicitly in the pathspec
1068  *
1069  *   2. the path is a directory prefix of some element in the
1070  *      pathspec
1071  */
1072 static int exclude_matches_pathspec(const char *path, int len,
1073                 const struct path_simplify *simplify)
1074 {
1075         if (simplify) {
1076                 for (; simplify->path; simplify++) {
1077                         if (len == simplify->len
1078                             && !memcmp(path, simplify->path, len))
1079                                 return 1;
1080                         if (len < simplify->len
1081                             && simplify->path[len] == '/'
1082                             && !memcmp(path, simplify->path, len))
1083                                 return 1;
1084                 }
1085         }
1086         return 0;
1087 }
1088
1089 static int get_index_dtype(const char *path, int len)
1090 {
1091         int pos;
1092         const struct cache_entry *ce;
1093
1094         ce = cache_file_exists(path, len, 0);
1095         if (ce) {
1096                 if (!ce_uptodate(ce))
1097                         return DT_UNKNOWN;
1098                 if (S_ISGITLINK(ce->ce_mode))
1099                         return DT_DIR;
1100                 /*
1101                  * Nobody actually cares about the
1102                  * difference between DT_LNK and DT_REG
1103                  */
1104                 return DT_REG;
1105         }
1106
1107         /* Try to look it up as a directory */
1108         pos = cache_name_pos(path, len);
1109         if (pos >= 0)
1110                 return DT_UNKNOWN;
1111         pos = -pos-1;
1112         while (pos < active_nr) {
1113                 ce = active_cache[pos++];
1114                 if (strncmp(ce->name, path, len))
1115                         break;
1116                 if (ce->name[len] > '/')
1117                         break;
1118                 if (ce->name[len] < '/')
1119                         continue;
1120                 if (!ce_uptodate(ce))
1121                         break;  /* continue? */
1122                 return DT_DIR;
1123         }
1124         return DT_UNKNOWN;
1125 }
1126
1127 static int get_dtype(struct dirent *de, const char *path, int len)
1128 {
1129         int dtype = de ? DTYPE(de) : DT_UNKNOWN;
1130         struct stat st;
1131
1132         if (dtype != DT_UNKNOWN)
1133                 return dtype;
1134         dtype = get_index_dtype(path, len);
1135         if (dtype != DT_UNKNOWN)
1136                 return dtype;
1137         if (lstat(path, &st))
1138                 return dtype;
1139         if (S_ISREG(st.st_mode))
1140                 return DT_REG;
1141         if (S_ISDIR(st.st_mode))
1142                 return DT_DIR;
1143         if (S_ISLNK(st.st_mode))
1144                 return DT_LNK;
1145         return dtype;
1146 }
1147
1148 static enum path_treatment treat_one_path(struct dir_struct *dir,
1149                                           struct strbuf *path,
1150                                           const struct path_simplify *simplify,
1151                                           int dtype, struct dirent *de)
1152 {
1153         int exclude;
1154         int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);
1155
1156         if (dtype == DT_UNKNOWN)
1157                 dtype = get_dtype(de, path->buf, path->len);
1158
1159         /* Always exclude indexed files */
1160         if (dtype != DT_DIR && has_path_in_index)
1161                 return path_none;
1162
1163         /*
1164          * When we are looking at a directory P in the working tree,
1165          * there are three cases:
1166          *
1167          * (1) P exists in the index.  Everything inside the directory P in
1168          * the working tree needs to go when P is checked out from the
1169          * index.
1170          *
1171          * (2) P does not exist in the index, but there is P/Q in the index.
1172          * We know P will stay a directory when we check out the contents
1173          * of the index, but we do not know yet if there is a directory
1174          * P/Q in the working tree to be killed, so we need to recurse.
1175          *
1176          * (3) P does not exist in the index, and there is no P/Q in the index
1177          * to require P to be a directory, either.  Only in this case, we
1178          * know that everything inside P will not be killed without
1179          * recursing.
1180          */
1181         if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
1182             (dtype == DT_DIR) &&
1183             !has_path_in_index &&
1184             (directory_exists_in_index(path->buf, path->len) == index_nonexistent))
1185                 return path_none;
1186
1187         exclude = is_excluded(dir, path->buf, &dtype);
1188
1189         /*
1190          * Excluded? If we don't explicitly want to show
1191          * ignored files, ignore it
1192          */
1193         if (exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
1194                 return path_excluded;
1195
1196         switch (dtype) {
1197         default:
1198                 return path_none;
1199         case DT_DIR:
1200                 strbuf_addch(path, '/');
1201                 return treat_directory(dir, path->buf, path->len, exclude,
1202                         simplify);
1203         case DT_REG:
1204         case DT_LNK:
1205                 return exclude ? path_excluded : path_untracked;
1206         }
1207 }
1208
1209 static enum path_treatment treat_path(struct dir_struct *dir,
1210                                       struct dirent *de,
1211                                       struct strbuf *path,
1212                                       int baselen,
1213                                       const struct path_simplify *simplify)
1214 {
1215         int dtype;
1216
1217         if (is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name, ".git"))
1218                 return path_none;
1219         strbuf_setlen(path, baselen);
1220         strbuf_addstr(path, de->d_name);
1221         if (simplify_away(path->buf, path->len, simplify))
1222                 return path_none;
1223
1224         dtype = DTYPE(de);
1225         return treat_one_path(dir, path, simplify, dtype, de);
1226 }
1227
1228 /*
1229  * Read a directory tree. We currently ignore anything but
1230  * directories, regular files and symlinks. That's because git
1231  * doesn't handle them at all yet. Maybe that will change some
1232  * day.
1233  *
1234  * Also, we ignore the name ".git" (even if it is not a directory).
1235  * That likely will not change.
1236  *
1237  * Returns the most significant path_treatment value encountered in the scan.
1238  */
1239 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
1240                                     const char *base, int baselen,
1241                                     int check_only,
1242                                     const struct path_simplify *simplify)
1243 {
1244         DIR *fdir;
1245         enum path_treatment state, subdir_state, dir_state = path_none;
1246         struct dirent *de;
1247         struct strbuf path = STRBUF_INIT;
1248
1249         strbuf_add(&path, base, baselen);
1250
1251         fdir = opendir(path.len ? path.buf : ".");
1252         if (!fdir)
1253                 goto out;
1254
1255         while ((de = readdir(fdir)) != NULL) {
1256                 /* check how the file or directory should be treated */
1257                 state = treat_path(dir, de, &path, baselen, simplify);
1258                 if (state > dir_state)
1259                         dir_state = state;
1260
1261                 /* recurse into subdir if instructed by treat_path */
1262                 if (state == path_recurse) {
1263                         subdir_state = read_directory_recursive(dir, path.buf,
1264                                 path.len, check_only, simplify);
1265                         if (subdir_state > dir_state)
1266                                 dir_state = subdir_state;
1267                 }
1268
1269                 if (check_only) {
1270                         /* abort early if maximum state has been reached */
1271                         if (dir_state == path_untracked)
1272                                 break;
1273                         /* skip the dir_add_* part */
1274                         continue;
1275                 }
1276
1277                 /* add the path to the appropriate result list */
1278                 switch (state) {
1279                 case path_excluded:
1280                         if (dir->flags & DIR_SHOW_IGNORED)
1281                                 dir_add_name(dir, path.buf, path.len);
1282                         else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
1283                                 ((dir->flags & DIR_COLLECT_IGNORED) &&
1284                                 exclude_matches_pathspec(path.buf, path.len,
1285                                         simplify)))
1286                                 dir_add_ignored(dir, path.buf, path.len);
1287                         break;
1288
1289                 case path_untracked:
1290                         if (!(dir->flags & DIR_SHOW_IGNORED))
1291                                 dir_add_name(dir, path.buf, path.len);
1292                         break;
1293
1294                 default:
1295                         break;
1296                 }
1297         }
1298         closedir(fdir);
1299  out:
1300         strbuf_release(&path);
1301
1302         return dir_state;
1303 }
1304
1305 static int cmp_name(const void *p1, const void *p2)
1306 {
1307         const struct dir_entry *e1 = *(const struct dir_entry **)p1;
1308         const struct dir_entry *e2 = *(const struct dir_entry **)p2;
1309
1310         return cache_name_compare(e1->name, e1->len,
1311                                   e2->name, e2->len);
1312 }
1313
1314 static struct path_simplify *create_simplify(const char **pathspec)
1315 {
1316         int nr, alloc = 0;
1317         struct path_simplify *simplify = NULL;
1318
1319         if (!pathspec)
1320                 return NULL;
1321
1322         for (nr = 0 ; ; nr++) {
1323                 const char *match;
1324                 if (nr >= alloc) {
1325                         alloc = alloc_nr(alloc);
1326                         simplify = xrealloc(simplify, alloc * sizeof(*simplify));
1327                 }
1328                 match = *pathspec++;
1329                 if (!match)
1330                         break;
1331                 simplify[nr].path = match;
1332                 simplify[nr].len = simple_length(match);
1333         }
1334         simplify[nr].path = NULL;
1335         simplify[nr].len = 0;
1336         return simplify;
1337 }
1338
1339 static void free_simplify(struct path_simplify *simplify)
1340 {
1341         free(simplify);
1342 }
1343
1344 static int treat_leading_path(struct dir_struct *dir,
1345                               const char *path, int len,
1346                               const struct path_simplify *simplify)
1347 {
1348         struct strbuf sb = STRBUF_INIT;
1349         int baselen, rc = 0;
1350         const char *cp;
1351         int old_flags = dir->flags;
1352
1353         while (len && path[len - 1] == '/')
1354                 len--;
1355         if (!len)
1356                 return 1;
1357         baselen = 0;
1358         dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;
1359         while (1) {
1360                 cp = path + baselen + !!baselen;
1361                 cp = memchr(cp, '/', path + len - cp);
1362                 if (!cp)
1363                         baselen = len;
1364                 else
1365                         baselen = cp - path;
1366                 strbuf_setlen(&sb, 0);
1367                 strbuf_add(&sb, path, baselen);
1368                 if (!is_directory(sb.buf))
1369                         break;
1370                 if (simplify_away(sb.buf, sb.len, simplify))
1371                         break;
1372                 if (treat_one_path(dir, &sb, simplify,
1373                                    DT_DIR, NULL) == path_none)
1374                         break; /* do not recurse into it */
1375                 if (len <= baselen) {
1376                         rc = 1;
1377                         break; /* finished checking */
1378                 }
1379         }
1380         strbuf_release(&sb);
1381         dir->flags = old_flags;
1382         return rc;
1383 }
1384
1385 int read_directory(struct dir_struct *dir, const char *path, int len, const struct pathspec *pathspec)
1386 {
1387         struct path_simplify *simplify;
1388
1389         /*
1390          * Check out create_simplify()
1391          */
1392         if (pathspec)
1393                 GUARD_PATHSPEC(pathspec,
1394                                PATHSPEC_FROMTOP |
1395                                PATHSPEC_MAXDEPTH |
1396                                PATHSPEC_LITERAL |
1397                                PATHSPEC_GLOB |
1398                                PATHSPEC_ICASE);
1399
1400         if (has_symlink_leading_path(path, len))
1401                 return dir->nr;
1402
1403         simplify = create_simplify(pathspec ? pathspec->_raw : NULL);
1404         if (!len || treat_leading_path(dir, path, len, simplify))
1405                 read_directory_recursive(dir, path, len, 0, simplify);
1406         free_simplify(simplify);
1407         qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
1408         qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
1409         return dir->nr;
1410 }
1411
1412 int file_exists(const char *f)
1413 {
1414         struct stat sb;
1415         return lstat(f, &sb) == 0;
1416 }
1417
1418 /*
1419  * Given two normalized paths (a trailing slash is ok), if subdir is
1420  * outside dir, return -1.  Otherwise return the offset in subdir that
1421  * can be used as relative path to dir.
1422  */
1423 int dir_inside_of(const char *subdir, const char *dir)
1424 {
1425         int offset = 0;
1426
1427         assert(dir && subdir && *dir && *subdir);
1428
1429         while (*dir && *subdir && *dir == *subdir) {
1430                 dir++;
1431                 subdir++;
1432                 offset++;
1433         }
1434
1435         /* hel[p]/me vs hel[l]/yeah */
1436         if (*dir && *subdir)
1437                 return -1;
1438
1439         if (!*subdir)
1440                 return !*dir ? offset : -1; /* same dir */
1441
1442         /* foo/[b]ar vs foo/[] */
1443         if (is_dir_sep(dir[-1]))
1444                 return is_dir_sep(subdir[-1]) ? offset : -1;
1445
1446         /* foo[/]bar vs foo[] */
1447         return is_dir_sep(*subdir) ? offset + 1 : -1;
1448 }
1449
1450 int is_inside_dir(const char *dir)
1451 {
1452         char cwd[PATH_MAX];
1453         if (!dir)
1454                 return 0;
1455         if (!getcwd(cwd, sizeof(cwd)))
1456                 die_errno("can't find the current directory");
1457         return dir_inside_of(cwd, dir) >= 0;
1458 }
1459
1460 int is_empty_dir(const char *path)
1461 {
1462         DIR *dir = opendir(path);
1463         struct dirent *e;
1464         int ret = 1;
1465
1466         if (!dir)
1467                 return 0;
1468
1469         while ((e = readdir(dir)) != NULL)
1470                 if (!is_dot_or_dotdot(e->d_name)) {
1471                         ret = 0;
1472                         break;
1473                 }
1474
1475         closedir(dir);
1476         return ret;
1477 }
1478
1479 static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
1480 {
1481         DIR *dir;
1482         struct dirent *e;
1483         int ret = 0, original_len = path->len, len, kept_down = 0;
1484         int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
1485         int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
1486         unsigned char submodule_head[20];
1487
1488         if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
1489             !resolve_gitlink_ref(path->buf, "HEAD", submodule_head)) {
1490                 /* Do not descend and nuke a nested git work tree. */
1491                 if (kept_up)
1492                         *kept_up = 1;
1493                 return 0;
1494         }
1495
1496         flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
1497         dir = opendir(path->buf);
1498         if (!dir) {
1499                 /* an empty dir could be removed even if it is unreadble */
1500                 if (!keep_toplevel)
1501                         return rmdir(path->buf);
1502                 else
1503                         return -1;
1504         }
1505         if (path->buf[original_len - 1] != '/')
1506                 strbuf_addch(path, '/');
1507
1508         len = path->len;
1509         while ((e = readdir(dir)) != NULL) {
1510                 struct stat st;
1511                 if (is_dot_or_dotdot(e->d_name))
1512                         continue;
1513
1514                 strbuf_setlen(path, len);
1515                 strbuf_addstr(path, e->d_name);
1516                 if (lstat(path->buf, &st))
1517                         ; /* fall thru */
1518                 else if (S_ISDIR(st.st_mode)) {
1519                         if (!remove_dir_recurse(path, flag, &kept_down))
1520                                 continue; /* happy */
1521                 } else if (!only_empty && !unlink(path->buf))
1522                         continue; /* happy, too */
1523
1524                 /* path too long, stat fails, or non-directory still exists */
1525                 ret = -1;
1526                 break;
1527         }
1528         closedir(dir);
1529
1530         strbuf_setlen(path, original_len);
1531         if (!ret && !keep_toplevel && !kept_down)
1532                 ret = rmdir(path->buf);
1533         else if (kept_up)
1534                 /*
1535                  * report the uplevel that it is not an error that we
1536                  * did not rmdir() our directory.
1537                  */
1538                 *kept_up = !ret;
1539         return ret;
1540 }
1541
1542 int remove_dir_recursively(struct strbuf *path, int flag)
1543 {
1544         return remove_dir_recurse(path, flag, NULL);
1545 }
1546
1547 void setup_standard_excludes(struct dir_struct *dir)
1548 {
1549         const char *path;
1550         char *xdg_path;
1551
1552         dir->exclude_per_dir = ".gitignore";
1553         path = git_path("info/exclude");
1554         if (!excludes_file) {
1555                 home_config_paths(NULL, &xdg_path, "ignore");
1556                 excludes_file = xdg_path;
1557         }
1558         if (!access_or_warn(path, R_OK, 0))
1559                 add_excludes_from_file(dir, path);
1560         if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
1561                 add_excludes_from_file(dir, excludes_file);
1562 }
1563
1564 int remove_path(const char *name)
1565 {
1566         char *slash;
1567
1568         if (unlink(name) && errno != ENOENT && errno != ENOTDIR)
1569                 return -1;
1570
1571         slash = strrchr(name, '/');
1572         if (slash) {
1573                 char *dirs = xstrdup(name);
1574                 slash = dirs + (slash - name);
1575                 do {
1576                         *slash = '\0';
1577                 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
1578                 free(dirs);
1579         }
1580         return 0;
1581 }
1582
1583 /*
1584  * Frees memory within dir which was allocated for exclude lists and
1585  * the exclude_stack.  Does not free dir itself.
1586  */
1587 void clear_directory(struct dir_struct *dir)
1588 {
1589         int i, j;
1590         struct exclude_list_group *group;
1591         struct exclude_list *el;
1592         struct exclude_stack *stk;
1593
1594         for (i = EXC_CMDL; i <= EXC_FILE; i++) {
1595                 group = &dir->exclude_list_group[i];
1596                 for (j = 0; j < group->nr; j++) {
1597                         el = &group->el[j];
1598                         if (i == EXC_DIRS)
1599                                 free((char *)el->src);
1600                         clear_exclude_list(el);
1601                 }
1602                 free(group->el);
1603         }
1604
1605         stk = dir->exclude_stack;
1606         while (stk) {
1607                 struct exclude_stack *prev = stk->prev;
1608                 free(stk);
1609                 stk = prev;
1610         }
1611 }