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