]> git.ipfire.org Git - thirdparty/git.git/blame - dir.c
untracked cache: mark what dirs should be recursed/saved
[thirdparty/git.git] / dir.c
CommitLineData
453ec4bd
LT
1/*
2 * This handles recursive filename detection with exclude
3 * files, index knowledge etc..
4 *
95a68344
AS
5 * See Documentation/technical/api-directory-listing.txt
6 *
453ec4bd
LT
7 * Copyright (C) Linus Torvalds, 2005-2006
8 * Junio Hamano, 2005-2006
9 */
453ec4bd
LT
10#include "cache.h"
11#include "dir.h"
09595258 12#include "refs.h"
237ec6e4 13#include "wildmatch.h"
64acde94 14#include "pathspec.h"
453ec4bd 15
9fc42d60
LT
16struct path_simplify {
17 int len;
18 const char *path;
19};
20
defd7c7b
KB
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 */
27enum path_treatment {
28 path_none = 0,
29 path_recurse,
30 path_excluded,
31 path_untracked
32};
33
cf7c6148
NTND
34/*
35 * Support data structure for our opendir/readdir/closedir wrappers
36 */
37struct cached_dir {
38 DIR *fdir;
39 struct untracked_cache_dir *untracked;
91a2288b
NTND
40 int nr_files;
41 int nr_dirs;
42
cf7c6148 43 struct dirent *de;
91a2288b
NTND
44 const char *file;
45 struct untracked_cache_dir *ucd;
cf7c6148
NTND
46};
47
defd7c7b 48static enum path_treatment read_directory_recursive(struct dir_struct *dir,
0dcb8d7f 49 const char *path, int len, struct untracked_cache_dir *untracked,
09595258 50 int check_only, const struct path_simplify *simplify);
caa6b782 51static int get_dtype(struct dirent *de, const char *path, int len);
09595258 52
8cf2a84e
JJ
53/* helper string functions with support for the ignore_case flag */
54int strcmp_icase(const char *a, const char *b)
55{
56 return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
57}
58
59int strncmp_icase(const char *a, const char *b, size_t count)
60{
61 return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
62}
63
64int fnmatch_icase(const char *pattern, const char *string, int flags)
65{
eb07894f
NTND
66 return wildmatch(pattern, string,
67 flags | (ignore_case ? WM_CASEFOLD : 0),
68 NULL);
8cf2a84e
JJ
69}
70
1f26ce61
CB
71int git_fnmatch(const struct pathspec_item *item,
72 const char *pattern, const char *string,
73 int prefix)
5d74762d 74{
5d74762d 75 if (prefix > 0) {
93d93537 76 if (ps_strncmp(item, pattern, string, prefix))
eb07894f 77 return WM_NOMATCH;
5d74762d
NTND
78 pattern += prefix;
79 string += prefix;
80 }
bd30c2e4 81 if (item->flags & PATHSPEC_ONESTAR) {
8c6abbcd
NTND
82 int pattern_len = strlen(++pattern);
83 int string_len = strlen(string);
84 return string_len < pattern_len ||
93d93537
NTND
85 ps_strcmp(item, pattern,
86 string + string_len - pattern_len);
8c6abbcd 87 }
bd30c2e4 88 if (item->magic & PATHSPEC_GLOB)
93d93537
NTND
89 return wildmatch(pattern, string,
90 WM_PATHNAME |
91 (item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0),
92 NULL);
bd30c2e4
NTND
93 else
94 /* wildmatch has not learned no FNM_PATHNAME mode yet */
eb07894f
NTND
95 return wildmatch(pattern, string,
96 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0,
97 NULL);
5d74762d
NTND
98}
99
0b6e56df
JH
100static int fnmatch_icase_mem(const char *pattern, int patternlen,
101 const char *string, int stringlen,
102 int flags)
103{
104 int match_status;
105 struct strbuf pat_buf = STRBUF_INIT;
106 struct strbuf str_buf = STRBUF_INIT;
107 const char *use_pat = pattern;
108 const char *use_str = string;
109
110 if (pattern[patternlen]) {
111 strbuf_add(&pat_buf, pattern, patternlen);
112 use_pat = pat_buf.buf;
113 }
114 if (string[stringlen]) {
115 strbuf_add(&str_buf, string, stringlen);
116 use_str = str_buf.buf;
117 }
118
f30366b2
JH
119 if (ignore_case)
120 flags |= WM_CASEFOLD;
121 match_status = wildmatch(use_pat, use_str, flags, NULL);
0b6e56df
JH
122
123 strbuf_release(&pat_buf);
124 strbuf_release(&str_buf);
125
126 return match_status;
127}
128
827f4d6c 129static size_t common_prefix_len(const struct pathspec *pathspec)
3c6a370b 130{
827f4d6c 131 int n;
4a085b16 132 size_t max = 0;
3c6a370b 133
93d93537
NTND
134 /*
135 * ":(icase)path" is treated as a pathspec full of
136 * wildcard. In other words, only prefix is considered common
137 * prefix. If the pathspec is abc/foo abc/bar, running in
138 * subdir xyz, the common prefix is still xyz, not xuz/abc as
139 * in non-:(icase).
140 */
5c6933d2
NTND
141 GUARD_PATHSPEC(pathspec,
142 PATHSPEC_FROMTOP |
143 PATHSPEC_MAXDEPTH |
bd30c2e4 144 PATHSPEC_LITERAL |
93d93537 145 PATHSPEC_GLOB |
ef79b1f8
NTND
146 PATHSPEC_ICASE |
147 PATHSPEC_EXCLUDE);
4a085b16 148
827f4d6c 149 for (n = 0; n < pathspec->nr; n++) {
93d93537 150 size_t i = 0, len = 0, item_len;
ef79b1f8
NTND
151 if (pathspec->items[n].magic & PATHSPEC_EXCLUDE)
152 continue;
93d93537
NTND
153 if (pathspec->items[n].magic & PATHSPEC_ICASE)
154 item_len = pathspec->items[n].prefix;
155 else
156 item_len = pathspec->items[n].nowildcard_len;
157 while (i < item_len && (n == 0 || i < max)) {
827f4d6c
NTND
158 char c = pathspec->items[n].match[i];
159 if (c != pathspec->items[0].match[i])
4a085b16
JH
160 break;
161 if (c == '/')
162 len = i + 1;
827f4d6c 163 i++;
4a085b16 164 }
827f4d6c 165 if (n == 0 || len < max) {
4a085b16
JH
166 max = len;
167 if (!max)
168 break;
169 }
3c6a370b 170 }
4a085b16 171 return max;
3c6a370b
LT
172}
173
f950eb95
CB
174/*
175 * Returns a copy of the longest leading path common among all
176 * pathspecs.
177 */
827f4d6c 178char *common_prefix(const struct pathspec *pathspec)
f950eb95
CB
179{
180 unsigned long len = common_prefix_len(pathspec);
181
827f4d6c 182 return len ? xmemdupz(pathspec->items[0].match, len) : NULL;
f950eb95
CB
183}
184
7327d3d1 185int fill_directory(struct dir_struct *dir, const struct pathspec *pathspec)
1d8842d9 186{
4a085b16 187 size_t len;
1d8842d9
LT
188
189 /*
190 * Calculate common prefix for the pathspec, and
191 * use that to optimize the directory walk
192 */
4a085b16 193 len = common_prefix_len(pathspec);
1d8842d9
LT
194
195 /* Read the directory and prune it */
b3920bbd 196 read_directory(dir, pathspec->nr ? pathspec->_raw[0] : "", len, pathspec);
dba2e203 197 return len;
1d8842d9
LT
198}
199
bc96cc87
NTND
200int within_depth(const char *name, int namelen,
201 int depth, int max_depth)
202{
203 const char *cp = name, *cpe = name + namelen;
204
205 while (cp < cpe) {
206 if (*cp++ != '/')
207 continue;
208 depth++;
209 if (depth > max_depth)
210 return 0;
211 }
212 return 1;
213}
214
42b0874a 215#define DO_MATCH_EXCLUDE 1
68690fdd 216#define DO_MATCH_DIRECTORY 2
42b0874a 217
61cf2820
NTND
218/*
219 * Does 'match' match the given name?
220 * A match is found if
221 *
222 * (1) the 'match' string is leading directory of 'name', or
223 * (2) the 'match' string is a wildcard and matches 'name', or
224 * (3) the 'match' string is exactly the same as 'name'.
225 *
226 * and the return value tells which case it was.
227 *
228 * It returns 0 when there is no match.
229 */
230static int match_pathspec_item(const struct pathspec_item *item, int prefix,
42b0874a 231 const char *name, int namelen, unsigned flags)
61cf2820
NTND
232{
233 /* name/namelen has prefix cut off by caller */
234 const char *match = item->match + prefix;
235 int matchlen = item->len - prefix;
236
93d93537
NTND
237 /*
238 * The normal call pattern is:
239 * 1. prefix = common_prefix_len(ps);
240 * 2. prune something, or fill_directory
854b0959 241 * 3. match_pathspec()
93d93537
NTND
242 *
243 * 'prefix' at #1 may be shorter than the command's prefix and
244 * it's ok for #2 to match extra files. Those extras will be
245 * trimmed at #3.
246 *
247 * Suppose the pathspec is 'foo' and '../bar' running from
248 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
249 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
250 * user does not want XYZ/foo, only the "foo" part should be
251 * case-insensitive. We need to filter out XYZ/foo here. In
252 * other words, we do not trust the caller on comparing the
253 * prefix part when :(icase) is involved. We do exact
254 * comparison ourselves.
255 *
256 * Normally the caller (common_prefix_len() in fact) does
257 * _exact_ matching on name[-prefix+1..-1] and we do not need
258 * to check that part. Be defensive and check it anyway, in
259 * case common_prefix_len is changed, or a new caller is
260 * introduced that does not use common_prefix_len.
261 *
262 * If the penalty turns out too high when prefix is really
263 * long, maybe change it to
264 * strncmp(match, name, item->prefix - prefix)
265 */
266 if (item->prefix && (item->magic & PATHSPEC_ICASE) &&
267 strncmp(item->match, name - prefix, item->prefix))
268 return 0;
269
61cf2820
NTND
270 /* If the match was just the prefix, we matched */
271 if (!*match)
272 return MATCHED_RECURSIVELY;
273
93d93537 274 if (matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) {
61cf2820
NTND
275 if (matchlen == namelen)
276 return MATCHED_EXACTLY;
277
278 if (match[matchlen-1] == '/' || name[matchlen] == '/')
279 return MATCHED_RECURSIVELY;
68690fdd
NTND
280 } else if ((flags & DO_MATCH_DIRECTORY) &&
281 match[matchlen - 1] == '/' &&
282 namelen == matchlen - 1 &&
283 !ps_strncmp(item, match, name, namelen))
284 return MATCHED_EXACTLY;
61cf2820 285
5d74762d 286 if (item->nowildcard_len < item->len &&
bd30c2e4 287 !git_fnmatch(item, match, name,
8c6abbcd 288 item->nowildcard_len - prefix))
61cf2820
NTND
289 return MATCHED_FNMATCH;
290
291 return 0;
292}
293
294/*
52ed1894
AS
295 * Given a name and a list of pathspecs, returns the nature of the
296 * closest (i.e. most specific) match of the name to any of the
297 * pathspecs.
298 *
299 * The caller typically calls this multiple times with the same
300 * pathspec and seen[] array but with different name/namelen
301 * (e.g. entries from the index) and is interested in seeing if and
302 * how each pathspec matches all the names it calls this function
303 * with. A mark is left in the seen[] array for each pathspec element
304 * indicating the closest type of match that element achieved, so if
305 * seen[n] remains zero after multiple invocations, that means the nth
306 * pathspec did not match any names, which could indicate that the
307 * user mistyped the nth pathspec.
61cf2820 308 */
854b0959
NTND
309static int do_match_pathspec(const struct pathspec *ps,
310 const char *name, int namelen,
311 int prefix, char *seen,
42b0874a 312 unsigned flags)
61cf2820 313{
42b0874a 314 int i, retval = 0, exclude = flags & DO_MATCH_EXCLUDE;
61cf2820 315
5c6933d2
NTND
316 GUARD_PATHSPEC(ps,
317 PATHSPEC_FROMTOP |
318 PATHSPEC_MAXDEPTH |
bd30c2e4 319 PATHSPEC_LITERAL |
93d93537 320 PATHSPEC_GLOB |
ef79b1f8
NTND
321 PATHSPEC_ICASE |
322 PATHSPEC_EXCLUDE);
8f4f8f45 323
61cf2820 324 if (!ps->nr) {
6330a171
NTND
325 if (!ps->recursive ||
326 !(ps->magic & PATHSPEC_MAXDEPTH) ||
327 ps->max_depth == -1)
61cf2820
NTND
328 return MATCHED_RECURSIVELY;
329
330 if (within_depth(name, namelen, 0, ps->max_depth))
331 return MATCHED_EXACTLY;
332 else
333 return 0;
334 }
335
336 name += prefix;
337 namelen -= prefix;
338
339 for (i = ps->nr - 1; i >= 0; i--) {
340 int how;
ef79b1f8
NTND
341
342 if ((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) ||
343 ( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE)))
344 continue;
345
61cf2820
NTND
346 if (seen && seen[i] == MATCHED_EXACTLY)
347 continue;
ef79b1f8
NTND
348 /*
349 * Make exclude patterns optional and never report
350 * "pathspec ':(exclude)foo' matches no files"
351 */
352 if (seen && ps->items[i].magic & PATHSPEC_EXCLUDE)
353 seen[i] = MATCHED_FNMATCH;
42b0874a
NTND
354 how = match_pathspec_item(ps->items+i, prefix, name,
355 namelen, flags);
6330a171
NTND
356 if (ps->recursive &&
357 (ps->magic & PATHSPEC_MAXDEPTH) &&
358 ps->max_depth != -1 &&
61cf2820
NTND
359 how && how != MATCHED_FNMATCH) {
360 int len = ps->items[i].len;
361 if (name[len] == '/')
362 len++;
363 if (within_depth(name+len, namelen-len, 0, ps->max_depth))
364 how = MATCHED_EXACTLY;
365 else
366 how = 0;
367 }
368 if (how) {
369 if (retval < how)
370 retval = how;
371 if (seen && seen[i] < how)
372 seen[i] = how;
373 }
374 }
375 return retval;
376}
377
854b0959
NTND
378int match_pathspec(const struct pathspec *ps,
379 const char *name, int namelen,
ae8d0824 380 int prefix, char *seen, int is_dir)
ef79b1f8
NTND
381{
382 int positive, negative;
ae8d0824 383 unsigned flags = is_dir ? DO_MATCH_DIRECTORY : 0;
42b0874a
NTND
384 positive = do_match_pathspec(ps, name, namelen,
385 prefix, seen, flags);
ef79b1f8
NTND
386 if (!(ps->magic & PATHSPEC_EXCLUDE) || !positive)
387 return positive;
42b0874a
NTND
388 negative = do_match_pathspec(ps, name, namelen,
389 prefix, seen,
390 flags | DO_MATCH_EXCLUDE);
ef79b1f8
NTND
391 return negative ? 0 : positive;
392}
393
fcd631ed
NTND
394/*
395 * Return the length of the "simple" part of a path match limiter.
396 */
87323bda 397int simple_length(const char *match)
fcd631ed
NTND
398{
399 int len = -1;
400
401 for (;;) {
402 unsigned char c = *match++;
403 len++;
404 if (c == '\0' || is_glob_special(c))
405 return len;
406 }
407}
408
87323bda 409int no_wildcard(const char *string)
68492fc7 410{
fcd631ed 411 return string[simple_length(string)] == '\0';
68492fc7
LK
412}
413
82dce998
NTND
414void parse_exclude_pattern(const char **pattern,
415 int *patternlen,
416 int *flags,
417 int *nowildcardlen)
84460eec
NTND
418{
419 const char *p = *pattern;
420 size_t i, len;
421
422 *flags = 0;
423 if (*p == '!') {
424 *flags |= EXC_FLAG_NEGATIVE;
425 p++;
426 }
427 len = strlen(p);
428 if (len && p[len - 1] == '/') {
429 len--;
430 *flags |= EXC_FLAG_MUSTBEDIR;
431 }
432 for (i = 0; i < len; i++) {
433 if (p[i] == '/')
434 break;
435 }
436 if (i == len)
437 *flags |= EXC_FLAG_NODIR;
438 *nowildcardlen = simple_length(p);
439 /*
440 * we should have excluded the trailing slash from 'p' too,
441 * but that's one more allocation. Instead just make sure
442 * nowildcardlen does not exceed real patternlen
443 */
444 if (*nowildcardlen > len)
445 *nowildcardlen = len;
446 if (*p == '*' && no_wildcard(p + 1))
447 *flags |= EXC_FLAG_ENDSWITH;
448 *pattern = p;
449 *patternlen = len;
450}
451
453ec4bd 452void add_exclude(const char *string, const char *base,
c04318e4 453 int baselen, struct exclude_list *el, int srcpos)
453ec4bd 454{
d6b8fc30 455 struct exclude *x;
84460eec
NTND
456 int patternlen;
457 int flags;
458 int nowildcardlen;
453ec4bd 459
84460eec
NTND
460 parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen);
461 if (flags & EXC_FLAG_MUSTBEDIR) {
d6b8fc30 462 char *s;
84460eec 463 x = xmalloc(sizeof(*x) + patternlen + 1);
4b25d091 464 s = (char *)(x+1);
84460eec
NTND
465 memcpy(s, string, patternlen);
466 s[patternlen] = '\0';
d6b8fc30 467 x->pattern = s;
d6b8fc30
JH
468 } else {
469 x = xmalloc(sizeof(*x));
470 x->pattern = string;
471 }
84460eec
NTND
472 x->patternlen = patternlen;
473 x->nowildcardlen = nowildcardlen;
453ec4bd
LT
474 x->base = base;
475 x->baselen = baselen;
d6b8fc30 476 x->flags = flags;
c04318e4 477 x->srcpos = srcpos;
840fc334
AS
478 ALLOC_GROW(el->excludes, el->nr + 1, el->alloc);
479 el->excludes[el->nr++] = x;
c04318e4 480 x->el = el;
453ec4bd
LT
481}
482
55fe6f51
NTND
483static void *read_skip_worktree_file_from_index(const char *path, size_t *size,
484 struct sha1_stat *sha1_stat)
c28b3d6e
NTND
485{
486 int pos, len;
487 unsigned long sz;
488 enum object_type type;
489 void *data;
c28b3d6e
NTND
490
491 len = strlen(path);
71261027 492 pos = cache_name_pos(path, len);
c28b3d6e
NTND
493 if (pos < 0)
494 return NULL;
71261027 495 if (!ce_skip_worktree(active_cache[pos]))
c28b3d6e 496 return NULL;
71261027 497 data = read_sha1_file(active_cache[pos]->sha1, &type, &sz);
c28b3d6e
NTND
498 if (!data || type != OBJ_BLOB) {
499 free(data);
500 return NULL;
501 }
502 *size = xsize_t(sz);
55fe6f51
NTND
503 if (sha1_stat) {
504 memset(&sha1_stat->stat, 0, sizeof(sha1_stat->stat));
505 hashcpy(sha1_stat->sha1, active_cache[pos]->sha1);
506 }
c28b3d6e
NTND
507 return data;
508}
509
f6198812
AS
510/*
511 * Frees memory within el which was allocated for exclude patterns and
512 * the file buffer. Does not free el itself.
513 */
514void clear_exclude_list(struct exclude_list *el)
0fd0e241
NTND
515{
516 int i;
517
518 for (i = 0; i < el->nr; i++)
519 free(el->excludes[i]);
520 free(el->excludes);
c082df24 521 free(el->filebuf);
0fd0e241
NTND
522
523 el->nr = 0;
524 el->excludes = NULL;
c082df24 525 el->filebuf = NULL;
0fd0e241
NTND
526}
527
7e2e4b37 528static void trim_trailing_spaces(char *buf)
16402b99 529{
e61a6c1d
PB
530 char *p, *last_space = NULL;
531
532 for (p = buf; *p; p++)
533 switch (*p) {
534 case ' ':
535 if (!last_space)
536 last_space = p;
537 break;
538 case '\\':
539 p++;
540 if (!*p)
541 return;
542 /* fallthrough */
543 default:
544 last_space = NULL;
545 }
546
547 if (last_space)
548 *last_space = '\0';
16402b99
NTND
549}
550
0dcb8d7f
NTND
551/*
552 * Given a subdirectory name and "dir" of the current directory,
553 * search the subdir in "dir" and return it, or create a new one if it
554 * does not exist in "dir".
555 *
556 * If "name" has the trailing slash, it'll be excluded in the search.
557 */
558static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc,
559 struct untracked_cache_dir *dir,
560 const char *name, int len)
561{
562 int first, last;
563 struct untracked_cache_dir *d;
564 if (!dir)
565 return NULL;
566 if (len && name[len - 1] == '/')
567 len--;
568 first = 0;
569 last = dir->dirs_nr;
570 while (last > first) {
571 int cmp, next = (last + first) >> 1;
572 d = dir->dirs[next];
573 cmp = strncmp(name, d->name, len);
574 if (!cmp && strlen(d->name) > len)
575 cmp = -1;
576 if (!cmp)
577 return d;
578 if (cmp < 0) {
579 last = next;
580 continue;
581 }
582 first = next+1;
583 }
584
585 uc->dir_created++;
586 d = xmalloc(sizeof(*d) + len + 1);
587 memset(d, 0, sizeof(*d));
588 memcpy(d->name, name, len);
589 d->name[len] = '\0';
590
591 ALLOC_GROW(dir->dirs, dir->dirs_nr + 1, dir->dirs_alloc);
592 memmove(dir->dirs + first + 1, dir->dirs + first,
593 (dir->dirs_nr - first) * sizeof(*dir->dirs));
594 dir->dirs_nr++;
595 dir->dirs[first] = d;
596 return d;
597}
598
ccad261f
NTND
599static void do_invalidate_gitignore(struct untracked_cache_dir *dir)
600{
601 int i;
602 dir->valid = 0;
603 dir->untracked_nr = 0;
604 for (i = 0; i < dir->dirs_nr; i++)
605 do_invalidate_gitignore(dir->dirs[i]);
606}
607
608static void invalidate_gitignore(struct untracked_cache *uc,
609 struct untracked_cache_dir *dir)
610{
611 uc->gitignore_invalidated++;
612 do_invalidate_gitignore(dir);
613}
614
91a2288b
NTND
615static void invalidate_directory(struct untracked_cache *uc,
616 struct untracked_cache_dir *dir)
617{
26cb0182 618 int i;
91a2288b
NTND
619 uc->dir_invalidated++;
620 dir->valid = 0;
621 dir->untracked_nr = 0;
26cb0182
NTND
622 for (i = 0; i < dir->dirs_nr; i++)
623 dir->dirs[i]->recurse = 0;
91a2288b
NTND
624}
625
55fe6f51
NTND
626/*
627 * Given a file with name "fname", read it (either from disk, or from
628 * the index if "check_index" is non-zero), parse it and store the
629 * exclude rules in "el".
630 *
631 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill
632 * stat data from disk (only valid if add_excludes returns zero). If
633 * ss_valid is non-zero, "ss" must contain good value as input.
634 */
635static int add_excludes(const char *fname, const char *base, int baselen,
636 struct exclude_list *el, int check_index,
637 struct sha1_stat *sha1_stat)
453ec4bd 638{
c470701a 639 struct stat st;
c04318e4 640 int fd, i, lineno = 1;
9d14017a 641 size_t size = 0;
453ec4bd
LT
642 char *buf, *entry;
643
644 fd = open(fname, O_RDONLY);
c28b3d6e 645 if (fd < 0 || fstat(fd, &st) < 0) {
69660731 646 if (errno != ENOENT)
55b38a48 647 warn_on_inaccessible(fname);
c28b3d6e
NTND
648 if (0 <= fd)
649 close(fd);
650 if (!check_index ||
55fe6f51 651 (buf = read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL)
c28b3d6e 652 return -1;
45d76f17
NTND
653 if (size == 0) {
654 free(buf);
655 return 0;
656 }
657 if (buf[size-1] != '\n') {
658 buf = xrealloc(buf, size+1);
659 buf[size++] = '\n';
660 }
d961baa8 661 } else {
c28b3d6e
NTND
662 size = xsize_t(st.st_size);
663 if (size == 0) {
55fe6f51
NTND
664 if (sha1_stat) {
665 fill_stat_data(&sha1_stat->stat, &st);
666 hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN);
667 sha1_stat->valid = 1;
668 }
c28b3d6e
NTND
669 close(fd);
670 return 0;
671 }
45d76f17 672 buf = xmalloc(size+1);
c28b3d6e 673 if (read_in_full(fd, buf, size) != size) {
45d76f17 674 free(buf);
c28b3d6e
NTND
675 close(fd);
676 return -1;
677 }
45d76f17 678 buf[size++] = '\n';
c28b3d6e 679 close(fd);
55fe6f51
NTND
680 if (sha1_stat) {
681 int pos;
682 if (sha1_stat->valid &&
683 !match_stat_data(&sha1_stat->stat, &st))
684 ; /* no content change, ss->sha1 still good */
685 else if (check_index &&
686 (pos = cache_name_pos(fname, strlen(fname))) >= 0 &&
687 !ce_stage(active_cache[pos]) &&
688 ce_uptodate(active_cache[pos]) &&
689 !would_convert_to_git(fname))
690 hashcpy(sha1_stat->sha1, active_cache[pos]->sha1);
691 else
692 hash_sha1_file(buf, size, "blob", sha1_stat->sha1);
693 fill_stat_data(&sha1_stat->stat, &st);
694 sha1_stat->valid = 1;
695 }
6ba78238 696 }
453ec4bd 697
c082df24 698 el->filebuf = buf;
453ec4bd 699 entry = buf;
45d76f17
NTND
700 for (i = 0; i < size; i++) {
701 if (buf[i] == '\n') {
453ec4bd
LT
702 if (entry != buf + i && entry[0] != '#') {
703 buf[i - (i && buf[i-1] == '\r')] = 0;
7e2e4b37 704 trim_trailing_spaces(entry);
c04318e4 705 add_exclude(entry, base, baselen, el, lineno);
453ec4bd 706 }
c04318e4 707 lineno++;
453ec4bd
LT
708 entry = buf + i + 1;
709 }
710 }
711 return 0;
453ec4bd
LT
712}
713
55fe6f51
NTND
714int add_excludes_from_file_to_list(const char *fname, const char *base,
715 int baselen, struct exclude_list *el,
716 int check_index)
717{
718 return add_excludes(fname, base, baselen, el, check_index, NULL);
719}
720
c04318e4
AS
721struct exclude_list *add_exclude_list(struct dir_struct *dir,
722 int group_type, const char *src)
c082df24
AS
723{
724 struct exclude_list *el;
725 struct exclude_list_group *group;
726
727 group = &dir->exclude_list_group[group_type];
728 ALLOC_GROW(group->el, group->nr + 1, group->alloc);
729 el = &group->el[group->nr++];
730 memset(el, 0, sizeof(*el));
c04318e4 731 el->src = src;
c082df24
AS
732 return el;
733}
734
735/*
736 * Used to set up core.excludesfile and .git/info/exclude lists.
737 */
0dcb8d7f
NTND
738static void add_excludes_from_file_1(struct dir_struct *dir, const char *fname,
739 struct sha1_stat *sha1_stat)
453ec4bd 740{
c082df24 741 struct exclude_list *el;
ccad261f
NTND
742 /*
743 * catch setup_standard_excludes() that's called before
744 * dir->untracked is assigned. That function behaves
745 * differently when dir->untracked is non-NULL.
746 */
747 if (!dir->untracked)
748 dir->unmanaged_exclude_files++;
c04318e4 749 el = add_exclude_list(dir, EXC_FILE, fname);
0dcb8d7f 750 if (add_excludes(fname, "", 0, el, 0, sha1_stat) < 0)
453ec4bd
LT
751 die("cannot use %s as an exclude file", fname);
752}
753
0dcb8d7f
NTND
754void add_excludes_from_file(struct dir_struct *dir, const char *fname)
755{
ccad261f 756 dir->unmanaged_exclude_files++; /* see validate_untracked_cache() */
0dcb8d7f
NTND
757 add_excludes_from_file_1(dir, fname, NULL);
758}
759
82dce998
NTND
760int match_basename(const char *basename, int basenamelen,
761 const char *pattern, int prefix, int patternlen,
762 int flags)
593cb880
NTND
763{
764 if (prefix == patternlen) {
0b6e56df
JH
765 if (patternlen == basenamelen &&
766 !strncmp_icase(pattern, basename, basenamelen))
593cb880
NTND
767 return 1;
768 } else if (flags & EXC_FLAG_ENDSWITH) {
0b6e56df 769 /* "*literal" matching against "fooliteral" */
593cb880 770 if (patternlen - 1 <= basenamelen &&
0b6e56df
JH
771 !strncmp_icase(pattern + 1,
772 basename + basenamelen - (patternlen - 1),
773 patternlen - 1))
593cb880
NTND
774 return 1;
775 } else {
0b6e56df
JH
776 if (fnmatch_icase_mem(pattern, patternlen,
777 basename, basenamelen,
778 0) == 0)
593cb880
NTND
779 return 1;
780 }
781 return 0;
782}
783
82dce998
NTND
784int match_pathname(const char *pathname, int pathlen,
785 const char *base, int baselen,
786 const char *pattern, int prefix, int patternlen,
787 int flags)
b5592632
NTND
788{
789 const char *name;
790 int namelen;
791
792 /*
793 * match with FNM_PATHNAME; the pattern has base implicitly
794 * in front of it.
795 */
796 if (*pattern == '/') {
797 pattern++;
982ac873 798 patternlen--;
b5592632
NTND
799 prefix--;
800 }
801
802 /*
803 * baselen does not count the trailing slash. base[] may or
804 * may not end with a trailing slash though.
805 */
806 if (pathlen < baselen + 1 ||
807 (baselen && pathname[baselen] != '/') ||
808 strncmp_icase(pathname, base, baselen))
809 return 0;
810
811 namelen = baselen ? pathlen - baselen - 1 : pathlen;
812 name = pathname + pathlen - namelen;
813
814 if (prefix) {
815 /*
816 * if the non-wildcard part is longer than the
817 * remaining pathname, surely it cannot match.
818 */
819 if (prefix > namelen)
820 return 0;
821
822 if (strncmp_icase(pattern, name, prefix))
823 return 0;
824 pattern += prefix;
ab3aebc1 825 patternlen -= prefix;
b5592632
NTND
826 name += prefix;
827 namelen -= prefix;
ab3aebc1
JK
828
829 /*
830 * If the whole pattern did not have a wildcard,
831 * then our prefix match is all we need; we
832 * do not need to call fnmatch at all.
833 */
834 if (!patternlen && !namelen)
835 return 1;
b5592632
NTND
836 }
837
ab3aebc1
JK
838 return fnmatch_icase_mem(pattern, patternlen,
839 name, namelen,
f30366b2 840 WM_PATHNAME) == 0;
b5592632
NTND
841}
842
578cd7c3
AS
843/*
844 * Scan the given exclude list in reverse to see whether pathname
845 * should be ignored. The first match (i.e. the last on the list), if
846 * any, determines the fate. Returns the exclude_list element which
847 * matched, or NULL for undecided.
453ec4bd 848 */
578cd7c3
AS
849static struct exclude *last_exclude_matching_from_list(const char *pathname,
850 int pathlen,
851 const char *basename,
852 int *dtype,
853 struct exclude_list *el)
453ec4bd
LT
854{
855 int i;
856
35a94d44 857 if (!el->nr)
578cd7c3 858 return NULL; /* undefined */
d6b8fc30 859
35a94d44
NTND
860 for (i = el->nr - 1; 0 <= i; i--) {
861 struct exclude *x = el->excludes[i];
b5592632 862 const char *exclude = x->pattern;
b5592632 863 int prefix = x->nowildcardlen;
35a94d44
NTND
864
865 if (x->flags & EXC_FLAG_MUSTBEDIR) {
866 if (*dtype == DT_UNKNOWN)
867 *dtype = get_dtype(NULL, pathname, pathlen);
868 if (*dtype != DT_DIR)
869 continue;
870 }
d6b8fc30 871
35a94d44 872 if (x->flags & EXC_FLAG_NODIR) {
593cb880
NTND
873 if (match_basename(basename,
874 pathlen - (basename - pathname),
875 exclude, prefix, x->patternlen,
876 x->flags))
578cd7c3 877 return x;
35a94d44
NTND
878 continue;
879 }
880
b5592632
NTND
881 assert(x->baselen == 0 || x->base[x->baselen - 1] == '/');
882 if (match_pathname(pathname, pathlen,
883 x->base, x->baselen ? x->baselen - 1 : 0,
884 exclude, prefix, x->patternlen, x->flags))
578cd7c3 885 return x;
453ec4bd 886 }
578cd7c3
AS
887 return NULL; /* undecided */
888}
889
890/*
891 * Scan the list and let the last match determine the fate.
892 * Return 1 for exclude, 0 for include and -1 for undecided.
893 */
894int is_excluded_from_list(const char *pathname,
895 int pathlen, const char *basename, int *dtype,
896 struct exclude_list *el)
897{
898 struct exclude *exclude;
899 exclude = last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el);
900 if (exclude)
901 return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
453ec4bd
LT
902 return -1; /* undecided */
903}
904
46aa2f95
KB
905static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir,
906 const char *pathname, int pathlen, const char *basename,
907 int *dtype_p)
908{
909 int i, j;
910 struct exclude_list_group *group;
911 struct exclude *exclude;
912 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
913 group = &dir->exclude_list_group[i];
914 for (j = group->nr - 1; j >= 0; j--) {
915 exclude = last_exclude_matching_from_list(
916 pathname, pathlen, basename, dtype_p,
917 &group->el[j]);
918 if (exclude)
919 return exclude;
920 }
921 }
922 return NULL;
923}
924
6cd5c582
KB
925/*
926 * Loads the per-directory exclude list for the substring of base
927 * which has a char length of baselen.
928 */
929static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
930{
931 struct exclude_list_group *group;
932 struct exclude_list *el;
933 struct exclude_stack *stk = NULL;
0dcb8d7f 934 struct untracked_cache_dir *untracked;
6cd5c582
KB
935 int current;
936
6cd5c582
KB
937 group = &dir->exclude_list_group[EXC_DIRS];
938
d961baa8
NTND
939 /*
940 * Pop the exclude lists from the EXCL_DIRS exclude_list_group
6cd5c582 941 * which originate from directories not in the prefix of the
d961baa8
NTND
942 * path being checked.
943 */
6cd5c582
KB
944 while ((stk = dir->exclude_stack) != NULL) {
945 if (stk->baselen <= baselen &&
aceb9429 946 !strncmp(dir->basebuf.buf, base, stk->baselen))
6cd5c582
KB
947 break;
948 el = &group->el[dir->exclude_stack->exclude_ix];
949 dir->exclude_stack = stk->prev;
95c6f271 950 dir->exclude = NULL;
aceb9429 951 free((char *)el->src); /* see strbuf_detach() below */
6cd5c582
KB
952 clear_exclude_list(el);
953 free(stk);
954 group->nr--;
955 }
956
95c6f271
KB
957 /* Skip traversing into sub directories if the parent is excluded */
958 if (dir->exclude)
959 return;
960
aceb9429
NTND
961 /*
962 * Lazy initialization. All call sites currently just
963 * memset(dir, 0, sizeof(*dir)) before use. Changing all of
964 * them seems lots of work for little benefit.
965 */
966 if (!dir->basebuf.buf)
967 strbuf_init(&dir->basebuf, PATH_MAX);
968
6cd5c582
KB
969 /* Read from the parent directories and push them down. */
970 current = stk ? stk->baselen : -1;
aceb9429 971 strbuf_setlen(&dir->basebuf, current < 0 ? 0 : current);
0dcb8d7f
NTND
972 if (dir->untracked)
973 untracked = stk ? stk->ucd : dir->untracked->root;
974 else
975 untracked = NULL;
976
6cd5c582 977 while (current < baselen) {
6cd5c582 978 const char *cp;
0dcb8d7f 979 struct sha1_stat sha1_stat;
6cd5c582 980
03e11a71 981 stk = xcalloc(1, sizeof(*stk));
6cd5c582
KB
982 if (current < 0) {
983 cp = base;
984 current = 0;
d961baa8 985 } else {
6cd5c582
KB
986 cp = strchr(base + current + 1, '/');
987 if (!cp)
988 die("oops in prep_exclude");
989 cp++;
0dcb8d7f
NTND
990 untracked =
991 lookup_untracked(dir->untracked, untracked,
992 base + current,
993 cp - base - current);
6cd5c582
KB
994 }
995 stk->prev = dir->exclude_stack;
996 stk->baselen = cp - base;
95c6f271 997 stk->exclude_ix = group->nr;
0dcb8d7f 998 stk->ucd = untracked;
95c6f271 999 el = add_exclude_list(dir, EXC_DIRS, NULL);
aceb9429
NTND
1000 strbuf_add(&dir->basebuf, base + current, stk->baselen - current);
1001 assert(stk->baselen == dir->basebuf.len);
95c6f271
KB
1002
1003 /* Abort if the directory is excluded */
1004 if (stk->baselen) {
1005 int dt = DT_DIR;
aceb9429 1006 dir->basebuf.buf[stk->baselen - 1] = 0;
95c6f271 1007 dir->exclude = last_exclude_matching_from_lists(dir,
aceb9429
NTND
1008 dir->basebuf.buf, stk->baselen - 1,
1009 dir->basebuf.buf + current, &dt);
1010 dir->basebuf.buf[stk->baselen - 1] = '/';
c3c327de
KB
1011 if (dir->exclude &&
1012 dir->exclude->flags & EXC_FLAG_NEGATIVE)
1013 dir->exclude = NULL;
95c6f271 1014 if (dir->exclude) {
95c6f271
KB
1015 dir->exclude_stack = stk;
1016 return;
1017 }
1018 }
1019
aceb9429 1020 /* Try to read per-directory file */
0dcb8d7f
NTND
1021 hashclr(sha1_stat.sha1);
1022 sha1_stat.valid = 0;
aceb9429 1023 if (dir->exclude_per_dir) {
95c6f271
KB
1024 /*
1025 * dir->basebuf gets reused by the traversal, but we
1026 * need fname to remain unchanged to ensure the src
1027 * member of each struct exclude correctly
1028 * back-references its source file. Other invocations
1029 * of add_exclude_list provide stable strings, so we
aceb9429 1030 * strbuf_detach() and free() here in the caller.
95c6f271 1031 */
aceb9429
NTND
1032 struct strbuf sb = STRBUF_INIT;
1033 strbuf_addbuf(&sb, &dir->basebuf);
1034 strbuf_addstr(&sb, dir->exclude_per_dir);
1035 el->src = strbuf_detach(&sb, NULL);
0dcb8d7f
NTND
1036 add_excludes(el->src, el->src, stk->baselen, el, 1,
1037 untracked ? &sha1_stat : NULL);
1038 }
5ebf79ad
NTND
1039 /*
1040 * NEEDSWORK: when untracked cache is enabled, prep_exclude()
1041 * will first be called in valid_cached_dir() then maybe many
1042 * times more in last_exclude_matching(). When the cache is
1043 * used, last_exclude_matching() will not be called and
1044 * reading .gitignore content will be a waste.
1045 *
1046 * So when it's called by valid_cached_dir() and we can get
1047 * .gitignore SHA-1 from the index (i.e. .gitignore is not
1048 * modified on work tree), we could delay reading the
1049 * .gitignore content until we absolutely need it in
1050 * last_exclude_matching(). Be careful about ignore rule
1051 * order, though, if you do that.
1052 */
1053 if (untracked &&
1054 hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {
1055 invalidate_gitignore(dir->untracked, untracked);
0dcb8d7f 1056 hashcpy(untracked->exclude_sha1, sha1_stat.sha1);
95c6f271 1057 }
6cd5c582
KB
1058 dir->exclude_stack = stk;
1059 current = stk->baselen;
1060 }
aceb9429 1061 strbuf_setlen(&dir->basebuf, baselen);
6cd5c582
KB
1062}
1063
f4cd69a6
AS
1064/*
1065 * Loads the exclude lists for the directory containing pathname, then
1066 * scans all exclude lists to determine whether pathname is excluded.
1067 * Returns the exclude_list element which matched, or NULL for
1068 * undecided.
1069 */
b07bc8c8 1070struct exclude *last_exclude_matching(struct dir_struct *dir,
f4cd69a6
AS
1071 const char *pathname,
1072 int *dtype_p)
453ec4bd
LT
1073{
1074 int pathlen = strlen(pathname);
68492fc7
LK
1075 const char *basename = strrchr(pathname, '/');
1076 basename = (basename) ? basename+1 : pathname;
453ec4bd 1077
63d285c8 1078 prep_exclude(dir, pathname, basename-pathname);
c082df24 1079
95c6f271
KB
1080 if (dir->exclude)
1081 return dir->exclude;
1082
46aa2f95
KB
1083 return last_exclude_matching_from_lists(dir, pathname, pathlen,
1084 basename, dtype_p);
f4cd69a6
AS
1085}
1086
1087/*
1088 * Loads the exclude lists for the directory containing pathname, then
1089 * scans all exclude lists to determine whether pathname is excluded.
1090 * Returns 1 if true, otherwise 0.
1091 */
b07bc8c8 1092int is_excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
f4cd69a6
AS
1093{
1094 struct exclude *exclude =
1095 last_exclude_matching(dir, pathname, dtype_p);
1096 if (exclude)
1097 return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
453ec4bd
LT
1098 return 0;
1099}
1100
f3fa1838
JH
1101static struct dir_entry *dir_entry_new(const char *pathname, int len)
1102{
453ec4bd
LT
1103 struct dir_entry *ent;
1104
453ec4bd
LT
1105 ent = xmalloc(sizeof(*ent) + len + 1);
1106 ent->len = len;
1107 memcpy(ent->name, pathname, len);
1108 ent->name[len] = 0;
4d06f8ac 1109 return ent;
453ec4bd
LT
1110}
1111
159b3212 1112static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
6815e569 1113{
ebbd7439 1114 if (cache_file_exists(pathname, len, ignore_case))
6815e569
JK
1115 return NULL;
1116
25fd2f7a 1117 ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
6815e569
JK
1118 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
1119}
1120
108da0db 1121struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
2abd31b0 1122{
6e4f981f 1123 if (!cache_name_is_other(pathname, len))
2abd31b0
JK
1124 return NULL;
1125
25fd2f7a 1126 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
2abd31b0
JK
1127 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
1128}
1129
09595258
LT
1130enum exist_status {
1131 index_nonexistent = 0,
1132 index_directory,
4b05548f 1133 index_gitdir
09595258
LT
1134};
1135
5102c617 1136/*
71261027 1137 * Do not use the alphabetically sorted index to look up
5102c617 1138 * the directory name; instead, use the case insensitive
ebbd7439 1139 * directory hash.
5102c617
JJ
1140 */
1141static enum exist_status directory_exists_in_index_icase(const char *dirname, int len)
1142{
d28eec26 1143 const struct cache_entry *ce = cache_dir_exists(dirname, len);
5102c617
JJ
1144 unsigned char endchar;
1145
1146 if (!ce)
1147 return index_nonexistent;
1148 endchar = ce->name[len];
1149
1150 /*
1151 * The cache_entry structure returned will contain this dirname
1152 * and possibly additional path components.
1153 */
1154 if (endchar == '/')
1155 return index_directory;
1156
1157 /*
1158 * If there are no additional path components, then this cache_entry
1159 * represents a submodule. Submodules, despite being directories,
1160 * are stored in the cache without a closing slash.
1161 */
1162 if (!endchar && S_ISGITLINK(ce->ce_mode))
1163 return index_gitdir;
1164
1165 /* This should never be hit, but it exists just in case. */
1166 return index_nonexistent;
1167}
1168
09595258
LT
1169/*
1170 * The index sorts alphabetically by entry name, which
1171 * means that a gitlink sorts as '\0' at the end, while
1172 * a directory (which is defined not as an entry, but as
1173 * the files it contains) will sort with the '/' at the
1174 * end.
1175 */
1176static enum exist_status directory_exists_in_index(const char *dirname, int len)
453ec4bd 1177{
5102c617
JJ
1178 int pos;
1179
1180 if (ignore_case)
1181 return directory_exists_in_index_icase(dirname, len);
1182
1183 pos = cache_name_pos(dirname, len);
09595258
LT
1184 if (pos < 0)
1185 pos = -pos-1;
1186 while (pos < active_nr) {
9c5e6c80 1187 const struct cache_entry *ce = active_cache[pos++];
09595258
LT
1188 unsigned char endchar;
1189
1190 if (strncmp(ce->name, dirname, len))
1191 break;
1192 endchar = ce->name[len];
1193 if (endchar > '/')
1194 break;
1195 if (endchar == '/')
1196 return index_directory;
7a51ed66 1197 if (!endchar && S_ISGITLINK(ce->ce_mode))
09595258
LT
1198 return index_gitdir;
1199 }
1200 return index_nonexistent;
1201}
1202
1203/*
1204 * When we find a directory when traversing the filesystem, we
1205 * have three distinct cases:
1206 *
1207 * - ignore it
1208 * - see it as a directory
1209 * - recurse into it
1210 *
1211 * and which one we choose depends on a combination of existing
1212 * git index contents and the flags passed into the directory
1213 * traversal routine.
1214 *
1215 * Case 1: If we *already* have entries in the index under that
5bd8e2d8
KB
1216 * directory name, we always recurse into the directory to see
1217 * all the files.
09595258
LT
1218 *
1219 * Case 2: If we *already* have that directory name as a gitlink,
1220 * we always continue to see it as a gitlink, regardless of whether
1221 * there is an actual git directory there or not (it might not
1222 * be checked out as a subproject!)
1223 *
1224 * Case 3: if we didn't have it in the index previously, we
1225 * have a few sub-cases:
1226 *
1227 * (a) if "show_other_directories" is true, we show it as
1228 * just a directory, unless "hide_empty_directories" is
defd7c7b
KB
1229 * also true, in which case we need to check if it contains any
1230 * untracked and / or ignored files.
09595258 1231 * (b) if it looks like a git directory, and we don't have
302b9282 1232 * 'no_gitlinks' set we treat it as a gitlink, and show it
09595258
LT
1233 * as a directory.
1234 * (c) otherwise, we recurse into it.
1235 */
defd7c7b 1236static enum path_treatment treat_directory(struct dir_struct *dir,
0dcb8d7f 1237 struct untracked_cache_dir *untracked,
721ac4ed 1238 const char *dirname, int len, int exclude,
09595258
LT
1239 const struct path_simplify *simplify)
1240{
1241 /* The "len-1" is to strip the final '/' */
1242 switch (directory_exists_in_index(dirname, len-1)) {
1243 case index_directory:
defd7c7b 1244 return path_recurse;
09595258
LT
1245
1246 case index_gitdir:
26c986e1 1247 return path_none;
09595258
LT
1248
1249 case index_nonexistent:
7c4c97c0 1250 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
09595258 1251 break;
7c4c97c0 1252 if (!(dir->flags & DIR_NO_GITLINKS)) {
09595258
LT
1253 unsigned char sha1[20];
1254 if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
defd7c7b 1255 return path_untracked;
09595258 1256 }
defd7c7b 1257 return path_recurse;
09595258
LT
1258 }
1259
1260 /* This is the "show_other_directories" case */
721ac4ed 1261
184d2a8e 1262 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
defd7c7b
KB
1263 return exclude ? path_excluded : path_untracked;
1264
0dcb8d7f
NTND
1265 untracked = lookup_untracked(dir->untracked, untracked, dirname, len);
1266 return read_directory_recursive(dir, dirname, len,
1267 untracked, 1, simplify);
453ec4bd
LT
1268}
1269
9fc42d60
LT
1270/*
1271 * This is an inexact early pruning of any recursive directory
1272 * reading - if the path cannot possibly be in the pathspec,
1273 * return true, and we'll skip it early.
1274 */
1275static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
1276{
1277 if (simplify) {
1278 for (;;) {
1279 const char *match = simplify->path;
1280 int len = simplify->len;
1281
1282 if (!match)
1283 break;
1284 if (len > pathlen)
1285 len = pathlen;
1286 if (!memcmp(path, match, len))
1287 return 0;
1288 simplify++;
1289 }
1290 return 1;
1291 }
1292 return 0;
1293}
1294
29209cbe
JK
1295/*
1296 * This function tells us whether an excluded path matches a
1297 * list of "interesting" pathspecs. That is, whether a path matched
1298 * by any of the pathspecs could possibly be ignored by excluding
1299 * the specified path. This can happen if:
1300 *
1301 * 1. the path is mentioned explicitly in the pathspec
1302 *
1303 * 2. the path is a directory prefix of some element in the
1304 * pathspec
1305 */
1306static int exclude_matches_pathspec(const char *path, int len,
1307 const struct path_simplify *simplify)
e96980ef
JK
1308{
1309 if (simplify) {
1310 for (; simplify->path; simplify++) {
1311 if (len == simplify->len
1312 && !memcmp(path, simplify->path, len))
1313 return 1;
29209cbe
JK
1314 if (len < simplify->len
1315 && simplify->path[len] == '/'
1316 && !memcmp(path, simplify->path, len))
1317 return 1;
e96980ef
JK
1318 }
1319 }
1320 return 0;
1321}
1322
443e061a
LT
1323static int get_index_dtype(const char *path, int len)
1324{
1325 int pos;
9c5e6c80 1326 const struct cache_entry *ce;
443e061a 1327
ebbd7439 1328 ce = cache_file_exists(path, len, 0);
443e061a
LT
1329 if (ce) {
1330 if (!ce_uptodate(ce))
1331 return DT_UNKNOWN;
1332 if (S_ISGITLINK(ce->ce_mode))
1333 return DT_DIR;
1334 /*
1335 * Nobody actually cares about the
1336 * difference between DT_LNK and DT_REG
1337 */
1338 return DT_REG;
1339 }
1340
1341 /* Try to look it up as a directory */
1342 pos = cache_name_pos(path, len);
1343 if (pos >= 0)
1344 return DT_UNKNOWN;
1345 pos = -pos-1;
1346 while (pos < active_nr) {
1347 ce = active_cache[pos++];
1348 if (strncmp(ce->name, path, len))
1349 break;
1350 if (ce->name[len] > '/')
1351 break;
1352 if (ce->name[len] < '/')
1353 continue;
1354 if (!ce_uptodate(ce))
1355 break; /* continue? */
1356 return DT_DIR;
1357 }
1358 return DT_UNKNOWN;
1359}
1360
caa6b782 1361static int get_dtype(struct dirent *de, const char *path, int len)
07134421 1362{
6831a88a 1363 int dtype = de ? DTYPE(de) : DT_UNKNOWN;
07134421
LT
1364 struct stat st;
1365
1366 if (dtype != DT_UNKNOWN)
1367 return dtype;
443e061a
LT
1368 dtype = get_index_dtype(path, len);
1369 if (dtype != DT_UNKNOWN)
1370 return dtype;
1371 if (lstat(path, &st))
07134421
LT
1372 return dtype;
1373 if (S_ISREG(st.st_mode))
1374 return DT_REG;
1375 if (S_ISDIR(st.st_mode))
1376 return DT_DIR;
1377 if (S_ISLNK(st.st_mode))
1378 return DT_LNK;
1379 return dtype;
1380}
1381
16e2cfa9 1382static enum path_treatment treat_one_path(struct dir_struct *dir,
0dcb8d7f 1383 struct untracked_cache_dir *untracked,
49dc2cc2 1384 struct strbuf *path,
16e2cfa9
JH
1385 const struct path_simplify *simplify,
1386 int dtype, struct dirent *de)
53cc5356 1387{
8aaf8d77 1388 int exclude;
ebbd7439 1389 int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);
2eac2a4c 1390
8aaf8d77
KB
1391 if (dtype == DT_UNKNOWN)
1392 dtype = get_dtype(de, path->buf, path->len);
1393
1394 /* Always exclude indexed files */
2eac2a4c 1395 if (dtype != DT_DIR && has_path_in_index)
defd7c7b 1396 return path_none;
8aaf8d77 1397
2eac2a4c
JH
1398 /*
1399 * When we are looking at a directory P in the working tree,
1400 * there are three cases:
1401 *
1402 * (1) P exists in the index. Everything inside the directory P in
1403 * the working tree needs to go when P is checked out from the
1404 * index.
1405 *
1406 * (2) P does not exist in the index, but there is P/Q in the index.
1407 * We know P will stay a directory when we check out the contents
1408 * of the index, but we do not know yet if there is a directory
1409 * P/Q in the working tree to be killed, so we need to recurse.
1410 *
1411 * (3) P does not exist in the index, and there is no P/Q in the index
1412 * to require P to be a directory, either. Only in this case, we
1413 * know that everything inside P will not be killed without
1414 * recursing.
1415 */
1416 if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
1417 (dtype == DT_DIR) &&
de372b1b
ES
1418 !has_path_in_index &&
1419 (directory_exists_in_index(path->buf, path->len) == index_nonexistent))
1420 return path_none;
8aaf8d77
KB
1421
1422 exclude = is_excluded(dir, path->buf, &dtype);
53cc5356
JH
1423
1424 /*
1425 * Excluded? If we don't explicitly want to show
1426 * ignored files, ignore it
1427 */
0aaf62b6 1428 if (exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
defd7c7b 1429 return path_excluded;
53cc5356 1430
53cc5356
JH
1431 switch (dtype) {
1432 default:
defd7c7b 1433 return path_none;
53cc5356 1434 case DT_DIR:
49dc2cc2 1435 strbuf_addch(path, '/');
0dcb8d7f 1436 return treat_directory(dir, untracked, path->buf, path->len, exclude,
defd7c7b 1437 simplify);
53cc5356
JH
1438 case DT_REG:
1439 case DT_LNK:
defd7c7b 1440 return exclude ? path_excluded : path_untracked;
53cc5356 1441 }
53cc5356
JH
1442}
1443
91a2288b
NTND
1444static enum path_treatment treat_path_fast(struct dir_struct *dir,
1445 struct untracked_cache_dir *untracked,
1446 struct cached_dir *cdir,
1447 struct strbuf *path,
1448 int baselen,
1449 const struct path_simplify *simplify)
1450{
1451 strbuf_setlen(path, baselen);
1452 if (!cdir->ucd) {
1453 strbuf_addstr(path, cdir->file);
1454 return path_untracked;
1455 }
1456 strbuf_addstr(path, cdir->ucd->name);
1457 /* treat_one_path() does this before it calls treat_directory() */
1458 if (path->buf[path->len - 1] != '/')
1459 strbuf_addch(path, '/');
1460 if (cdir->ucd->check_only)
1461 /*
1462 * check_only is set as a result of treat_directory() getting
1463 * to its bottom. Verify again the same set of directories
1464 * with check_only set.
1465 */
1466 return read_directory_recursive(dir, path->buf, path->len,
1467 cdir->ucd, 1, simplify);
1468 /*
1469 * We get path_recurse in the first run when
1470 * directory_exists_in_index() returns index_nonexistent. We
1471 * are sure that new changes in the index does not impact the
1472 * outcome. Return now.
1473 */
1474 return path_recurse;
1475}
1476
16e2cfa9 1477static enum path_treatment treat_path(struct dir_struct *dir,
0dcb8d7f 1478 struct untracked_cache_dir *untracked,
cf7c6148 1479 struct cached_dir *cdir,
49dc2cc2 1480 struct strbuf *path,
16e2cfa9 1481 int baselen,
49dc2cc2 1482 const struct path_simplify *simplify)
16e2cfa9
JH
1483{
1484 int dtype;
cf7c6148 1485 struct dirent *de = cdir->de;
16e2cfa9 1486
91a2288b
NTND
1487 if (!de)
1488 return treat_path_fast(dir, untracked, cdir, path,
1489 baselen, simplify);
16e2cfa9 1490 if (is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name, ".git"))
defd7c7b 1491 return path_none;
49dc2cc2
RS
1492 strbuf_setlen(path, baselen);
1493 strbuf_addstr(path, de->d_name);
1494 if (simplify_away(path->buf, path->len, simplify))
defd7c7b 1495 return path_none;
16e2cfa9
JH
1496
1497 dtype = DTYPE(de);
0dcb8d7f
NTND
1498 return treat_one_path(dir, untracked, path, simplify, dtype, de);
1499}
1500
1501static void add_untracked(struct untracked_cache_dir *dir, const char *name)
1502{
1503 if (!dir)
1504 return;
1505 ALLOC_GROW(dir->untracked, dir->untracked_nr + 1,
1506 dir->untracked_alloc);
1507 dir->untracked[dir->untracked_nr++] = xstrdup(name);
16e2cfa9
JH
1508}
1509
91a2288b
NTND
1510static int valid_cached_dir(struct dir_struct *dir,
1511 struct untracked_cache_dir *untracked,
1512 struct strbuf *path,
1513 int check_only)
1514{
1515 struct stat st;
1516
1517 if (!untracked)
1518 return 0;
1519
1520 if (stat(path->len ? path->buf : ".", &st)) {
1521 invalidate_directory(dir->untracked, untracked);
1522 memset(&untracked->stat_data, 0, sizeof(untracked->stat_data));
1523 return 0;
1524 }
1525 if (!untracked->valid ||
1526 match_stat_data(&untracked->stat_data, &st)) {
1527 if (untracked->valid)
1528 invalidate_directory(dir->untracked, untracked);
1529 fill_stat_data(&untracked->stat_data, &st);
1530 return 0;
1531 }
1532
1533 if (untracked->check_only != !!check_only) {
1534 invalidate_directory(dir->untracked, untracked);
1535 return 0;
1536 }
1537
1538 /*
1539 * prep_exclude will be called eventually on this directory,
1540 * but it's called much later in last_exclude_matching(). We
1541 * need it now to determine the validity of the cache for this
1542 * path. The next calls will be nearly no-op, the way
1543 * prep_exclude() is designed.
1544 */
1545 if (path->len && path->buf[path->len - 1] != '/') {
1546 strbuf_addch(path, '/');
1547 prep_exclude(dir, path->buf, path->len);
1548 strbuf_setlen(path, path->len - 1);
1549 } else
1550 prep_exclude(dir, path->buf, path->len);
1551
1552 /* hopefully prep_exclude() haven't invalidated this entry... */
1553 return untracked->valid;
1554}
1555
cf7c6148
NTND
1556static int open_cached_dir(struct cached_dir *cdir,
1557 struct dir_struct *dir,
1558 struct untracked_cache_dir *untracked,
1559 struct strbuf *path,
1560 int check_only)
1561{
1562 memset(cdir, 0, sizeof(*cdir));
1563 cdir->untracked = untracked;
91a2288b
NTND
1564 if (valid_cached_dir(dir, untracked, path, check_only))
1565 return 0;
cf7c6148 1566 cdir->fdir = opendir(path->len ? path->buf : ".");
91a2288b
NTND
1567 if (dir->untracked)
1568 dir->untracked->dir_opened++;
cf7c6148
NTND
1569 if (!cdir->fdir)
1570 return -1;
1571 return 0;
1572}
1573
1574static int read_cached_dir(struct cached_dir *cdir)
1575{
1576 if (cdir->fdir) {
1577 cdir->de = readdir(cdir->fdir);
1578 if (!cdir->de)
1579 return -1;
1580 return 0;
1581 }
91a2288b
NTND
1582 while (cdir->nr_dirs < cdir->untracked->dirs_nr) {
1583 struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];
26cb0182
NTND
1584 if (!d->recurse) {
1585 cdir->nr_dirs++;
1586 continue;
1587 }
91a2288b
NTND
1588 cdir->ucd = d;
1589 cdir->nr_dirs++;
1590 return 0;
1591 }
1592 cdir->ucd = NULL;
1593 if (cdir->nr_files < cdir->untracked->untracked_nr) {
1594 struct untracked_cache_dir *d = cdir->untracked;
1595 cdir->file = d->untracked[cdir->nr_files++];
1596 return 0;
1597 }
cf7c6148
NTND
1598 return -1;
1599}
1600
1601static void close_cached_dir(struct cached_dir *cdir)
1602{
1603 if (cdir->fdir)
1604 closedir(cdir->fdir);
91a2288b
NTND
1605 /*
1606 * We have gone through this directory and found no untracked
1607 * entries. Mark it valid.
1608 */
26cb0182 1609 if (cdir->untracked) {
91a2288b 1610 cdir->untracked->valid = 1;
26cb0182
NTND
1611 cdir->untracked->recurse = 1;
1612 }
cf7c6148
NTND
1613}
1614
453ec4bd
LT
1615/*
1616 * Read a directory tree. We currently ignore anything but
1617 * directories, regular files and symlinks. That's because git
1618 * doesn't handle them at all yet. Maybe that will change some
1619 * day.
1620 *
1621 * Also, we ignore the name ".git" (even if it is not a directory).
1622 * That likely will not change.
defd7c7b
KB
1623 *
1624 * Returns the most significant path_treatment value encountered in the scan.
453ec4bd 1625 */
defd7c7b 1626static enum path_treatment read_directory_recursive(struct dir_struct *dir,
53cc5356 1627 const char *base, int baselen,
0dcb8d7f 1628 struct untracked_cache_dir *untracked, int check_only,
53cc5356 1629 const struct path_simplify *simplify)
453ec4bd 1630{
cf7c6148 1631 struct cached_dir cdir;
defd7c7b 1632 enum path_treatment state, subdir_state, dir_state = path_none;
bef36921 1633 struct strbuf path = STRBUF_INIT;
453ec4bd 1634
bef36921 1635 strbuf_add(&path, base, baselen);
02cb6753 1636
cf7c6148 1637 if (open_cached_dir(&cdir, dir, untracked, &path, check_only))
1528d247
RS
1638 goto out;
1639
0dcb8d7f
NTND
1640 if (untracked)
1641 untracked->check_only = !!check_only;
1642
cf7c6148 1643 while (!read_cached_dir(&cdir)) {
defd7c7b 1644 /* check how the file or directory should be treated */
cf7c6148 1645 state = treat_path(dir, untracked, &cdir, &path, baselen, simplify);
0dcb8d7f 1646
defd7c7b
KB
1647 if (state > dir_state)
1648 dir_state = state;
1649
1650 /* recurse into subdir if instructed by treat_path */
1651 if (state == path_recurse) {
0dcb8d7f
NTND
1652 struct untracked_cache_dir *ud;
1653 ud = lookup_untracked(dir->untracked, untracked,
1654 path.buf + baselen,
1655 path.len - baselen);
1656 subdir_state =
1657 read_directory_recursive(dir, path.buf, path.len,
1658 ud, check_only, simplify);
defd7c7b
KB
1659 if (subdir_state > dir_state)
1660 dir_state = subdir_state;
1661 }
1662
1663 if (check_only) {
1664 /* abort early if maximum state has been reached */
0dcb8d7f 1665 if (dir_state == path_untracked) {
91a2288b 1666 if (cdir.fdir)
0dcb8d7f 1667 add_untracked(untracked, path.buf + baselen);
defd7c7b 1668 break;
0dcb8d7f 1669 }
defd7c7b 1670 /* skip the dir_add_* part */
02cb6753 1671 continue;
453ec4bd 1672 }
defd7c7b
KB
1673
1674 /* add the path to the appropriate result list */
1675 switch (state) {
1676 case path_excluded:
1677 if (dir->flags & DIR_SHOW_IGNORED)
1678 dir_add_name(dir, path.buf, path.len);
0aaf62b6
KB
1679 else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
1680 ((dir->flags & DIR_COLLECT_IGNORED) &&
1681 exclude_matches_pathspec(path.buf, path.len,
1682 simplify)))
1683 dir_add_ignored(dir, path.buf, path.len);
defd7c7b
KB
1684 break;
1685
1686 case path_untracked:
0dcb8d7f
NTND
1687 if (dir->flags & DIR_SHOW_IGNORED)
1688 break;
1689 dir_add_name(dir, path.buf, path.len);
91a2288b 1690 if (cdir.fdir)
0dcb8d7f 1691 add_untracked(untracked, path.buf + baselen);
1528d247 1692 break;
defd7c7b
KB
1693
1694 default:
1695 break;
1696 }
453ec4bd 1697 }
cf7c6148 1698 close_cached_dir(&cdir);
1528d247 1699 out:
bef36921 1700 strbuf_release(&path);
453ec4bd 1701
defd7c7b 1702 return dir_state;
453ec4bd
LT
1703}
1704
1705static int cmp_name(const void *p1, const void *p2)
1706{
1707 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
1708 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
1709
ccdd4a0f 1710 return name_compare(e1->name, e1->len, e2->name, e2->len);
453ec4bd
LT
1711}
1712
9fc42d60
LT
1713static struct path_simplify *create_simplify(const char **pathspec)
1714{
1715 int nr, alloc = 0;
1716 struct path_simplify *simplify = NULL;
1717
1718 if (!pathspec)
1719 return NULL;
1720
1721 for (nr = 0 ; ; nr++) {
1722 const char *match;
9af49f82 1723 ALLOC_GROW(simplify, nr + 1, alloc);
9fc42d60
LT
1724 match = *pathspec++;
1725 if (!match)
1726 break;
1727 simplify[nr].path = match;
1728 simplify[nr].len = simple_length(match);
1729 }
1730 simplify[nr].path = NULL;
1731 simplify[nr].len = 0;
1732 return simplify;
1733}
1734
1735static void free_simplify(struct path_simplify *simplify)
1736{
8e0f7003 1737 free(simplify);
9fc42d60
LT
1738}
1739
48ffef96
JH
1740static int treat_leading_path(struct dir_struct *dir,
1741 const char *path, int len,
1742 const struct path_simplify *simplify)
1743{
49dc2cc2
RS
1744 struct strbuf sb = STRBUF_INIT;
1745 int baselen, rc = 0;
48ffef96 1746 const char *cp;
be8a84c5 1747 int old_flags = dir->flags;
48ffef96
JH
1748
1749 while (len && path[len - 1] == '/')
1750 len--;
1751 if (!len)
1752 return 1;
1753 baselen = 0;
be8a84c5 1754 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;
48ffef96
JH
1755 while (1) {
1756 cp = path + baselen + !!baselen;
1757 cp = memchr(cp, '/', path + len - cp);
1758 if (!cp)
1759 baselen = len;
1760 else
1761 baselen = cp - path;
49dc2cc2
RS
1762 strbuf_setlen(&sb, 0);
1763 strbuf_add(&sb, path, baselen);
1764 if (!is_directory(sb.buf))
1765 break;
1766 if (simplify_away(sb.buf, sb.len, simplify))
1767 break;
0dcb8d7f 1768 if (treat_one_path(dir, NULL, &sb, simplify,
defd7c7b 1769 DT_DIR, NULL) == path_none)
49dc2cc2
RS
1770 break; /* do not recurse into it */
1771 if (len <= baselen) {
1772 rc = 1;
1773 break; /* finished checking */
1774 }
48ffef96 1775 }
49dc2cc2 1776 strbuf_release(&sb);
be8a84c5 1777 dir->flags = old_flags;
49dc2cc2 1778 return rc;
48ffef96
JH
1779}
1780
ccad261f
NTND
1781static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,
1782 int base_len,
1783 const struct pathspec *pathspec)
1784{
1785 struct untracked_cache_dir *root;
1786
1787 if (!dir->untracked)
1788 return NULL;
1789
1790 /*
1791 * We only support $GIT_DIR/info/exclude and core.excludesfile
1792 * as the global ignore rule files. Any other additions
1793 * (e.g. from command line) invalidate the cache. This
1794 * condition also catches running setup_standard_excludes()
1795 * before setting dir->untracked!
1796 */
1797 if (dir->unmanaged_exclude_files)
1798 return NULL;
1799
1800 /*
1801 * Optimize for the main use case only: whole-tree git
1802 * status. More work involved in treat_leading_path() if we
1803 * use cache on just a subset of the worktree. pathspec
1804 * support could make the matter even worse.
1805 */
1806 if (base_len || (pathspec && pathspec->nr))
1807 return NULL;
1808
1809 /* Different set of flags may produce different results */
1810 if (dir->flags != dir->untracked->dir_flags ||
1811 /*
1812 * See treat_directory(), case index_nonexistent. Without
1813 * this flag, we may need to also cache .git file content
1814 * for the resolve_gitlink_ref() call, which we don't.
1815 */
1816 !(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||
1817 /* We don't support collecting ignore files */
1818 (dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |
1819 DIR_COLLECT_IGNORED)))
1820 return NULL;
1821
1822 /*
1823 * If we use .gitignore in the cache and now you change it to
1824 * .gitexclude, everything will go wrong.
1825 */
1826 if (dir->exclude_per_dir != dir->untracked->exclude_per_dir &&
1827 strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))
1828 return NULL;
1829
1830 /*
1831 * EXC_CMDL is not considered in the cache. If people set it,
1832 * skip the cache.
1833 */
1834 if (dir->exclude_list_group[EXC_CMDL].nr)
1835 return NULL;
1836
1837 if (!dir->untracked->root) {
1838 const int len = sizeof(*dir->untracked->root);
1839 dir->untracked->root = xmalloc(len);
1840 memset(dir->untracked->root, 0, len);
1841 }
1842
1843 /* Validate $GIT_DIR/info/exclude and core.excludesfile */
1844 root = dir->untracked->root;
1845 if (hashcmp(dir->ss_info_exclude.sha1,
1846 dir->untracked->ss_info_exclude.sha1)) {
1847 invalidate_gitignore(dir->untracked, root);
1848 dir->untracked->ss_info_exclude = dir->ss_info_exclude;
1849 }
1850 if (hashcmp(dir->ss_excludes_file.sha1,
1851 dir->untracked->ss_excludes_file.sha1)) {
1852 invalidate_gitignore(dir->untracked, root);
1853 dir->untracked->ss_excludes_file = dir->ss_excludes_file;
1854 }
26cb0182
NTND
1855
1856 /* Make sure this directory is not dropped out at saving phase */
1857 root->recurse = 1;
ccad261f
NTND
1858 return root;
1859}
1860
7327d3d1 1861int read_directory(struct dir_struct *dir, const char *path, int len, const struct pathspec *pathspec)
9fc42d60 1862{
725b0605 1863 struct path_simplify *simplify;
ccad261f 1864 struct untracked_cache_dir *untracked;
b4189aa8 1865
7327d3d1
NTND
1866 /*
1867 * Check out create_simplify()
1868 */
1869 if (pathspec)
5c6933d2
NTND
1870 GUARD_PATHSPEC(pathspec,
1871 PATHSPEC_FROMTOP |
1872 PATHSPEC_MAXDEPTH |
bd30c2e4 1873 PATHSPEC_LITERAL |
93d93537 1874 PATHSPEC_GLOB |
ef79b1f8
NTND
1875 PATHSPEC_ICASE |
1876 PATHSPEC_EXCLUDE);
7327d3d1 1877
dba2e203 1878 if (has_symlink_leading_path(path, len))
725b0605
JH
1879 return dir->nr;
1880
ef79b1f8
NTND
1881 /*
1882 * exclude patterns are treated like positive ones in
1883 * create_simplify. Usually exclude patterns should be a
1884 * subset of positive ones, which has no impacts on
1885 * create_simplify().
1886 */
b3920bbd 1887 simplify = create_simplify(pathspec ? pathspec->_raw : NULL);
ccad261f
NTND
1888 untracked = validate_untracked_cache(dir, len, pathspec);
1889 if (!untracked)
1890 /*
1891 * make sure untracked cache code path is disabled,
1892 * e.g. prep_exclude()
1893 */
1894 dir->untracked = NULL;
48ffef96 1895 if (!len || treat_leading_path(dir, path, len, simplify))
ccad261f 1896 read_directory_recursive(dir, path, len, untracked, 0, simplify);
9fc42d60 1897 free_simplify(simplify);
453ec4bd 1898 qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
2abd31b0 1899 qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
453ec4bd
LT
1900 return dir->nr;
1901}
c91f0d92 1902
686a4a06 1903int file_exists(const char *f)
c91f0d92 1904{
686a4a06 1905 struct stat sb;
a50f9fc5 1906 return lstat(f, &sb) == 0;
c91f0d92 1907}
e6636747
JS
1908
1909/*
9b125da4
NTND
1910 * Given two normalized paths (a trailing slash is ok), if subdir is
1911 * outside dir, return -1. Otherwise return the offset in subdir that
1912 * can be used as relative path to dir.
e6636747 1913 */
9b125da4 1914int dir_inside_of(const char *subdir, const char *dir)
e6636747 1915{
9b125da4 1916 int offset = 0;
e6636747 1917
9b125da4 1918 assert(dir && subdir && *dir && *subdir);
e6636747 1919
9b125da4 1920 while (*dir && *subdir && *dir == *subdir) {
e6636747 1921 dir++;
9b125da4
NTND
1922 subdir++;
1923 offset++;
490544b1 1924 }
9b125da4
NTND
1925
1926 /* hel[p]/me vs hel[l]/yeah */
1927 if (*dir && *subdir)
1928 return -1;
1929
1930 if (!*subdir)
1931 return !*dir ? offset : -1; /* same dir */
1932
1933 /* foo/[b]ar vs foo/[] */
1934 if (is_dir_sep(dir[-1]))
1935 return is_dir_sep(subdir[-1]) ? offset : -1;
1936
1937 /* foo[/]bar vs foo[] */
1938 return is_dir_sep(*subdir) ? offset + 1 : -1;
e6636747
JS
1939}
1940
1941int is_inside_dir(const char *dir)
1942{
56b9f6e7
RS
1943 char *cwd;
1944 int rc;
1945
b892913d
NTND
1946 if (!dir)
1947 return 0;
56b9f6e7
RS
1948
1949 cwd = xgetcwd();
1950 rc = (dir_inside_of(cwd, dir) >= 0);
1951 free(cwd);
1952 return rc;
e6636747 1953}
7155b727 1954
55892d23
AP
1955int is_empty_dir(const char *path)
1956{
1957 DIR *dir = opendir(path);
1958 struct dirent *e;
1959 int ret = 1;
1960
1961 if (!dir)
1962 return 0;
1963
1964 while ((e = readdir(dir)) != NULL)
1965 if (!is_dot_or_dotdot(e->d_name)) {
1966 ret = 0;
1967 break;
1968 }
1969
1970 closedir(dir);
1971 return ret;
1972}
1973
ae2f203e 1974static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
7155b727 1975{
a0f4afbe 1976 DIR *dir;
7155b727 1977 struct dirent *e;
ae2f203e 1978 int ret = 0, original_len = path->len, len, kept_down = 0;
a0f4afbe 1979 int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
c844a803 1980 int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
a0f4afbe 1981 unsigned char submodule_head[20];
7155b727 1982
a0f4afbe 1983 if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
ae2f203e 1984 !resolve_gitlink_ref(path->buf, "HEAD", submodule_head)) {
a0f4afbe 1985 /* Do not descend and nuke a nested git work tree. */
ae2f203e
JH
1986 if (kept_up)
1987 *kept_up = 1;
a0f4afbe 1988 return 0;
ae2f203e 1989 }
a0f4afbe 1990
ae2f203e 1991 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
a0f4afbe 1992 dir = opendir(path->buf);
c844a803 1993 if (!dir) {
863808cd
MH
1994 if (errno == ENOENT)
1995 return keep_toplevel ? -1 : 0;
1996 else if (errno == EACCES && !keep_toplevel)
ecb2c282
MH
1997 /*
1998 * An empty dir could be removable even if it
1999 * is unreadable:
2000 */
c844a803
JH
2001 return rmdir(path->buf);
2002 else
2003 return -1;
2004 }
7155b727
JS
2005 if (path->buf[original_len - 1] != '/')
2006 strbuf_addch(path, '/');
2007
2008 len = path->len;
2009 while ((e = readdir(dir)) != NULL) {
2010 struct stat st;
8ca12c0d
AP
2011 if (is_dot_or_dotdot(e->d_name))
2012 continue;
7155b727
JS
2013
2014 strbuf_setlen(path, len);
2015 strbuf_addstr(path, e->d_name);
863808cd
MH
2016 if (lstat(path->buf, &st)) {
2017 if (errno == ENOENT)
2018 /*
2019 * file disappeared, which is what we
2020 * wanted anyway
2021 */
2022 continue;
2023 /* fall thru */
2024 } else if (S_ISDIR(st.st_mode)) {
ae2f203e 2025 if (!remove_dir_recurse(path, flag, &kept_down))
7155b727 2026 continue; /* happy */
863808cd
MH
2027 } else if (!only_empty &&
2028 (!unlink(path->buf) || errno == ENOENT)) {
7155b727 2029 continue; /* happy, too */
863808cd 2030 }
7155b727
JS
2031
2032 /* path too long, stat fails, or non-directory still exists */
2033 ret = -1;
2034 break;
2035 }
2036 closedir(dir);
2037
2038 strbuf_setlen(path, original_len);
ae2f203e 2039 if (!ret && !keep_toplevel && !kept_down)
863808cd 2040 ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1;
ae2f203e
JH
2041 else if (kept_up)
2042 /*
2043 * report the uplevel that it is not an error that we
2044 * did not rmdir() our directory.
2045 */
2046 *kept_up = !ret;
7155b727
JS
2047 return ret;
2048}
039bc64e 2049
ae2f203e
JH
2050int remove_dir_recursively(struct strbuf *path, int flag)
2051{
2052 return remove_dir_recurse(path, flag, NULL);
2053}
2054
039bc64e
JH
2055void setup_standard_excludes(struct dir_struct *dir)
2056{
2057 const char *path;
dc79687e 2058 char *xdg_path;
039bc64e
JH
2059
2060 dir->exclude_per_dir = ".gitignore";
2061 path = git_path("info/exclude");
dc79687e
HKNN
2062 if (!excludes_file) {
2063 home_config_paths(NULL, &xdg_path, "ignore");
2064 excludes_file = xdg_path;
2065 }
4698c8fe 2066 if (!access_or_warn(path, R_OK, 0))
0dcb8d7f
NTND
2067 add_excludes_from_file_1(dir, path,
2068 dir->untracked ? &dir->ss_info_exclude : NULL);
4698c8fe 2069 if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
0dcb8d7f
NTND
2070 add_excludes_from_file_1(dir, excludes_file,
2071 dir->untracked ? &dir->ss_excludes_file : NULL);
039bc64e 2072}
4a92d1bf
AR
2073
2074int remove_path(const char *name)
2075{
2076 char *slash;
2077
9a6728d4 2078 if (unlink(name) && errno != ENOENT && errno != ENOTDIR)
4a92d1bf
AR
2079 return -1;
2080
2081 slash = strrchr(name, '/');
2082 if (slash) {
2083 char *dirs = xstrdup(name);
2084 slash = dirs + (slash - name);
2085 do {
2086 *slash = '\0';
3fc0d131 2087 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
4a92d1bf
AR
2088 free(dirs);
2089 }
2090 return 0;
2091}
2092
270be816
AS
2093/*
2094 * Frees memory within dir which was allocated for exclude lists and
2095 * the exclude_stack. Does not free dir itself.
2096 */
2097void clear_directory(struct dir_struct *dir)
2098{
2099 int i, j;
2100 struct exclude_list_group *group;
2101 struct exclude_list *el;
2102 struct exclude_stack *stk;
2103
2104 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
2105 group = &dir->exclude_list_group[i];
2106 for (j = 0; j < group->nr; j++) {
2107 el = &group->el[j];
2108 if (i == EXC_DIRS)
2109 free((char *)el->src);
2110 clear_exclude_list(el);
2111 }
2112 free(group->el);
2113 }
2114
2115 stk = dir->exclude_stack;
2116 while (stk) {
2117 struct exclude_stack *prev = stk->prev;
2118 free(stk);
2119 stk = prev;
2120 }
aceb9429 2121 strbuf_release(&dir->basebuf);
270be816 2122}