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