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