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