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