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