]> git.ipfire.org Git - thirdparty/git.git/blob - dir.c
c8c869faed2b8d8f54c34efb545e338c27a3423c
[thirdparty/git.git] / dir.c
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 */
8
9 #define USE_THE_REPOSITORY_VARIABLE
10 #define DISABLE_SIGN_COMPARE_WARNINGS
11
12 #include "git-compat-util.h"
13 #include "abspath.h"
14 #include "config.h"
15 #include "convert.h"
16 #include "dir.h"
17 #include "environment.h"
18 #include "gettext.h"
19 #include "name-hash.h"
20 #include "object-file.h"
21 #include "path.h"
22 #include "refs.h"
23 #include "repository.h"
24 #include "wildmatch.h"
25 #include "pathspec.h"
26 #include "utf8.h"
27 #include "varint.h"
28 #include "ewah/ewok.h"
29 #include "fsmonitor-ll.h"
30 #include "read-cache-ll.h"
31 #include "setup.h"
32 #include "sparse-index.h"
33 #include "submodule-config.h"
34 #include "symlinks.h"
35 #include "trace2.h"
36 #include "tree.h"
37 #include "hex.h"
38
39 /*
40 * The maximum size of a pattern/exclude file. If the file exceeds this size
41 * we will ignore it.
42 */
43 #define PATTERN_MAX_FILE_SIZE (100 * 1024 * 1024)
44
45 /*
46 * Tells read_directory_recursive how a file or directory should be treated.
47 * Values are ordered by significance, e.g. if a directory contains both
48 * excluded and untracked files, it is listed as untracked because
49 * path_untracked > path_excluded.
50 */
51 enum path_treatment {
52 path_none = 0,
53 path_recurse,
54 path_excluded,
55 path_untracked
56 };
57
58 /*
59 * Support data structure for our opendir/readdir/closedir wrappers
60 */
61 struct cached_dir {
62 DIR *fdir;
63 struct untracked_cache_dir *untracked;
64 int nr_files;
65 int nr_dirs;
66
67 const char *d_name;
68 int d_type;
69 const char *file;
70 struct untracked_cache_dir *ucd;
71 };
72
73 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
74 struct index_state *istate, const char *path, int len,
75 struct untracked_cache_dir *untracked,
76 int check_only, int stop_at_first_file, const struct pathspec *pathspec);
77 static int resolve_dtype(int dtype, struct index_state *istate,
78 const char *path, int len);
79 struct dirent *readdir_skip_dot_and_dotdot(DIR *dirp)
80 {
81 struct dirent *e;
82
83 while ((e = readdir(dirp)) != NULL) {
84 if (!is_dot_or_dotdot(e->d_name))
85 break;
86 }
87 return e;
88 }
89
90 int count_slashes(const char *s)
91 {
92 int cnt = 0;
93 while (*s)
94 if (*s++ == '/')
95 cnt++;
96 return cnt;
97 }
98
99 int git_fspathcmp(const char *a, const char *b)
100 {
101 return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
102 }
103
104 int fspatheq(const char *a, const char *b)
105 {
106 return !fspathcmp(a, b);
107 }
108
109 int git_fspathncmp(const char *a, const char *b, size_t count)
110 {
111 return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
112 }
113
114 int paths_collide(const char *a, const char *b)
115 {
116 size_t len_a = strlen(a), len_b = strlen(b);
117
118 if (len_a == len_b)
119 return fspatheq(a, b);
120
121 if (len_a < len_b)
122 return is_dir_sep(b[len_a]) && !fspathncmp(a, b, len_a);
123 return is_dir_sep(a[len_b]) && !fspathncmp(a, b, len_b);
124 }
125
126 unsigned int fspathhash(const char *str)
127 {
128 return ignore_case ? strihash(str) : strhash(str);
129 }
130
131 int git_fnmatch(const struct pathspec_item *item,
132 const char *pattern, const char *string,
133 int prefix)
134 {
135 if (prefix > 0) {
136 if (ps_strncmp(item, pattern, string, prefix))
137 return WM_NOMATCH;
138 pattern += prefix;
139 string += prefix;
140 }
141 if (item->flags & PATHSPEC_ONESTAR) {
142 int pattern_len = strlen(++pattern);
143 int string_len = strlen(string);
144 return string_len < pattern_len ||
145 ps_strcmp(item, pattern,
146 string + string_len - pattern_len);
147 }
148 if (item->magic & PATHSPEC_GLOB)
149 return wildmatch(pattern, string,
150 WM_PATHNAME |
151 (item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0));
152 else
153 /* wildmatch has not learned no FNM_PATHNAME mode yet */
154 return wildmatch(pattern, string,
155 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0);
156 }
157
158 static int fnmatch_icase_mem(const char *pattern, int patternlen,
159 const char *string, int stringlen,
160 int flags)
161 {
162 int match_status;
163 struct strbuf pat_buf = STRBUF_INIT;
164 struct strbuf str_buf = STRBUF_INIT;
165 const char *use_pat = pattern;
166 const char *use_str = string;
167
168 if (pattern[patternlen]) {
169 strbuf_add(&pat_buf, pattern, patternlen);
170 use_pat = pat_buf.buf;
171 }
172 if (string[stringlen]) {
173 strbuf_add(&str_buf, string, stringlen);
174 use_str = str_buf.buf;
175 }
176
177 if (ignore_case)
178 flags |= WM_CASEFOLD;
179 match_status = wildmatch(use_pat, use_str, flags);
180
181 strbuf_release(&pat_buf);
182 strbuf_release(&str_buf);
183
184 return match_status;
185 }
186
187 static size_t common_prefix_len(const struct pathspec *pathspec)
188 {
189 int n;
190 size_t max = 0;
191
192 /*
193 * ":(icase)path" is treated as a pathspec full of
194 * wildcard. In other words, only prefix is considered common
195 * prefix. If the pathspec is abc/foo abc/bar, running in
196 * subdir xyz, the common prefix is still xyz, not xyz/abc as
197 * in non-:(icase).
198 */
199 GUARD_PATHSPEC(pathspec,
200 PATHSPEC_FROMTOP |
201 PATHSPEC_MAXDEPTH |
202 PATHSPEC_LITERAL |
203 PATHSPEC_GLOB |
204 PATHSPEC_ICASE |
205 PATHSPEC_EXCLUDE |
206 PATHSPEC_ATTR);
207
208 for (n = 0; n < pathspec->nr; n++) {
209 size_t i = 0, len = 0, item_len;
210 if (pathspec->items[n].magic & PATHSPEC_EXCLUDE)
211 continue;
212 if (pathspec->items[n].magic & PATHSPEC_ICASE)
213 item_len = pathspec->items[n].prefix;
214 else
215 item_len = pathspec->items[n].nowildcard_len;
216 while (i < item_len && (n == 0 || i < max)) {
217 char c = pathspec->items[n].match[i];
218 if (c != pathspec->items[0].match[i])
219 break;
220 if (c == '/')
221 len = i + 1;
222 i++;
223 }
224 if (n == 0 || len < max) {
225 max = len;
226 if (!max)
227 break;
228 }
229 }
230 return max;
231 }
232
233 /*
234 * Returns a copy of the longest leading path common among all
235 * pathspecs.
236 */
237 char *common_prefix(const struct pathspec *pathspec)
238 {
239 unsigned long len = common_prefix_len(pathspec);
240
241 return len ? xmemdupz(pathspec->items[0].match, len) : NULL;
242 }
243
244 int fill_directory(struct dir_struct *dir,
245 struct index_state *istate,
246 const struct pathspec *pathspec)
247 {
248 const char *prefix;
249 size_t prefix_len;
250
251 unsigned exclusive_flags = DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO;
252 if ((dir->flags & exclusive_flags) == exclusive_flags)
253 BUG("DIR_SHOW_IGNORED and DIR_SHOW_IGNORED_TOO are exclusive");
254
255 /*
256 * Calculate common prefix for the pathspec, and
257 * use that to optimize the directory walk
258 */
259 prefix_len = common_prefix_len(pathspec);
260 prefix = prefix_len ? pathspec->items[0].match : "";
261
262 /* Read the directory and prune it */
263 read_directory(dir, istate, prefix, prefix_len, pathspec);
264
265 return prefix_len;
266 }
267
268 int within_depth(const char *name, int namelen,
269 int depth, int max_depth)
270 {
271 const char *cp = name, *cpe = name + namelen;
272
273 while (cp < cpe) {
274 if (*cp++ != '/')
275 continue;
276 depth++;
277 if (depth > max_depth)
278 return 0;
279 }
280 return 1;
281 }
282
283 /*
284 * Read the contents of the blob with the given OID into a buffer.
285 * Append a trailing LF to the end if the last line doesn't have one.
286 *
287 * Returns:
288 * -1 when the OID is invalid or unknown or does not refer to a blob.
289 * 0 when the blob is empty.
290 * 1 along with { data, size } of the (possibly augmented) buffer
291 * when successful.
292 *
293 * Optionally updates the given oid_stat with the given OID (when valid).
294 */
295 static int do_read_blob(const struct object_id *oid, struct oid_stat *oid_stat,
296 size_t *size_out, char **data_out)
297 {
298 enum object_type type;
299 unsigned long sz;
300 char *data;
301
302 *size_out = 0;
303 *data_out = NULL;
304
305 data = repo_read_object_file(the_repository, oid, &type, &sz);
306 if (!data || type != OBJ_BLOB) {
307 free(data);
308 return -1;
309 }
310
311 if (oid_stat) {
312 memset(&oid_stat->stat, 0, sizeof(oid_stat->stat));
313 oidcpy(&oid_stat->oid, oid);
314 }
315
316 if (sz == 0) {
317 free(data);
318 return 0;
319 }
320
321 if (data[sz - 1] != '\n') {
322 data = xrealloc(data, st_add(sz, 1));
323 data[sz++] = '\n';
324 }
325
326 *size_out = xsize_t(sz);
327 *data_out = data;
328
329 return 1;
330 }
331
332 #define DO_MATCH_EXCLUDE (1<<0)
333 #define DO_MATCH_DIRECTORY (1<<1)
334 #define DO_MATCH_LEADING_PATHSPEC (1<<2)
335
336 /*
337 * Does the given pathspec match the given name? A match is found if
338 *
339 * (1) the pathspec string is leading directory of 'name' ("RECURSIVELY"), or
340 * (2) the pathspec string has a leading part matching 'name' ("LEADING"), or
341 * (3) the pathspec string is a wildcard and matches 'name' ("WILDCARD"), or
342 * (4) the pathspec string is exactly the same as 'name' ("EXACT").
343 *
344 * Return value tells which case it was (1-4), or 0 when there is no match.
345 *
346 * It may be instructive to look at a small table of concrete examples
347 * to understand the differences between 1, 2, and 4:
348 *
349 * Pathspecs
350 * | a/b | a/b/ | a/b/c
351 * ------+-----------+-----------+------------
352 * a/b | EXACT | EXACT[1] | LEADING[2]
353 * Names a/b/ | RECURSIVE | EXACT | LEADING[2]
354 * a/b/c | RECURSIVE | RECURSIVE | EXACT
355 *
356 * [1] Only if DO_MATCH_DIRECTORY is passed; otherwise, this is NOT a match.
357 * [2] Only if DO_MATCH_LEADING_PATHSPEC is passed; otherwise, not a match.
358 */
359 static int match_pathspec_item(struct index_state *istate,
360 const struct pathspec_item *item, int prefix,
361 const char *name, int namelen, unsigned flags)
362 {
363 /* name/namelen has prefix cut off by caller */
364 const char *match = item->match + prefix;
365 int matchlen = item->len - prefix;
366
367 /*
368 * The normal call pattern is:
369 * 1. prefix = common_prefix_len(ps);
370 * 2. prune something, or fill_directory
371 * 3. match_pathspec()
372 *
373 * 'prefix' at #1 may be shorter than the command's prefix and
374 * it's ok for #2 to match extra files. Those extras will be
375 * trimmed at #3.
376 *
377 * Suppose the pathspec is 'foo' and '../bar' running from
378 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
379 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
380 * user does not want XYZ/foo, only the "foo" part should be
381 * case-insensitive. We need to filter out XYZ/foo here. In
382 * other words, we do not trust the caller on comparing the
383 * prefix part when :(icase) is involved. We do exact
384 * comparison ourselves.
385 *
386 * Normally the caller (common_prefix_len() in fact) does
387 * _exact_ matching on name[-prefix+1..-1] and we do not need
388 * to check that part. Be defensive and check it anyway, in
389 * case common_prefix_len is changed, or a new caller is
390 * introduced that does not use common_prefix_len.
391 *
392 * If the penalty turns out too high when prefix is really
393 * long, maybe change it to
394 * strncmp(match, name, item->prefix - prefix)
395 */
396 if (item->prefix && (item->magic & PATHSPEC_ICASE) &&
397 strncmp(item->match, name - prefix, item->prefix))
398 return 0;
399
400 if (item->attr_match_nr) {
401 if (!istate)
402 BUG("magic PATHSPEC_ATTR requires an index");
403 if (!match_pathspec_attrs(istate, name - prefix, namelen + prefix, item))
404 return 0;
405 }
406
407 /* If the match was just the prefix, we matched */
408 if (!*match)
409 return MATCHED_RECURSIVELY;
410
411 if (matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) {
412 if (matchlen == namelen)
413 return MATCHED_EXACTLY;
414
415 if (match[matchlen-1] == '/' || name[matchlen] == '/')
416 return MATCHED_RECURSIVELY;
417 } else if ((flags & DO_MATCH_DIRECTORY) &&
418 match[matchlen - 1] == '/' &&
419 namelen == matchlen - 1 &&
420 !ps_strncmp(item, match, name, namelen))
421 return MATCHED_EXACTLY;
422
423 if (item->nowildcard_len < item->len &&
424 !git_fnmatch(item, match, name,
425 item->nowildcard_len - prefix))
426 return MATCHED_FNMATCH;
427
428 /* Perform checks to see if "name" is a leading string of the pathspec */
429 if ( (flags & DO_MATCH_LEADING_PATHSPEC) &&
430 !(flags & DO_MATCH_EXCLUDE)) {
431 /* name is a literal prefix of the pathspec */
432 int offset = name[namelen-1] == '/' ? 1 : 0;
433 if ((namelen < matchlen) &&
434 (match[namelen-offset] == '/') &&
435 !ps_strncmp(item, match, name, namelen))
436 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
437
438 /* name doesn't match up to the first wild character */
439 if (item->nowildcard_len < item->len &&
440 ps_strncmp(item, match, name,
441 item->nowildcard_len - prefix))
442 return 0;
443
444 /*
445 * name has no wildcard, and it didn't match as a leading
446 * pathspec so return.
447 */
448 if (item->nowildcard_len == item->len)
449 return 0;
450
451 /*
452 * Here is where we would perform a wildmatch to check if
453 * "name" can be matched as a directory (or a prefix) against
454 * the pathspec. Since wildmatch doesn't have this capability
455 * at the present we have to punt and say that it is a match,
456 * potentially returning a false positive
457 * The submodules themselves will be able to perform more
458 * accurate matching to determine if the pathspec matches.
459 */
460 return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
461 }
462
463 return 0;
464 }
465
466 /*
467 * do_match_pathspec() is meant to ONLY be called by
468 * match_pathspec_with_flags(); calling it directly risks pathspecs
469 * like ':!unwanted_path' being ignored.
470 *
471 * Given a name and a list of pathspecs, returns the nature of the
472 * closest (i.e. most specific) match of the name to any of the
473 * pathspecs.
474 *
475 * The caller typically calls this multiple times with the same
476 * pathspec and seen[] array but with different name/namelen
477 * (e.g. entries from the index) and is interested in seeing if and
478 * how each pathspec matches all the names it calls this function
479 * with. A mark is left in the seen[] array for each pathspec element
480 * indicating the closest type of match that element achieved, so if
481 * seen[n] remains zero after multiple invocations, that means the nth
482 * pathspec did not match any names, which could indicate that the
483 * user mistyped the nth pathspec.
484 */
485 static int do_match_pathspec(struct index_state *istate,
486 const struct pathspec *ps,
487 const char *name, int namelen,
488 int prefix, char *seen,
489 unsigned flags)
490 {
491 int i, retval = 0, exclude = flags & DO_MATCH_EXCLUDE;
492
493 GUARD_PATHSPEC(ps,
494 PATHSPEC_FROMTOP |
495 PATHSPEC_MAXDEPTH |
496 PATHSPEC_LITERAL |
497 PATHSPEC_GLOB |
498 PATHSPEC_ICASE |
499 PATHSPEC_EXCLUDE |
500 PATHSPEC_ATTR);
501
502 if (!ps->nr) {
503 if (!ps->recursive ||
504 !(ps->magic & PATHSPEC_MAXDEPTH) ||
505 ps->max_depth == -1)
506 return MATCHED_RECURSIVELY;
507
508 if (within_depth(name, namelen, 0, ps->max_depth))
509 return MATCHED_EXACTLY;
510 else
511 return 0;
512 }
513
514 name += prefix;
515 namelen -= prefix;
516
517 for (i = ps->nr - 1; i >= 0; i--) {
518 int how;
519
520 if ((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) ||
521 ( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE)))
522 continue;
523
524 if (seen && seen[i] == MATCHED_EXACTLY &&
525 ps->items[i].nowildcard_len == ps->items[i].len)
526 continue;
527 /*
528 * Make exclude patterns optional and never report
529 * "pathspec ':(exclude)foo' matches no files"
530 */
531 if (seen && ps->items[i].magic & PATHSPEC_EXCLUDE)
532 seen[i] = MATCHED_FNMATCH;
533 how = match_pathspec_item(istate, ps->items+i, prefix, name,
534 namelen, flags);
535 if (ps->recursive &&
536 (ps->magic & PATHSPEC_MAXDEPTH) &&
537 ps->max_depth != -1 &&
538 how && how != MATCHED_FNMATCH) {
539 int len = ps->items[i].len;
540 if (name[len] == '/')
541 len++;
542 if (within_depth(name+len, namelen-len, 0, ps->max_depth))
543 how = MATCHED_EXACTLY;
544 else
545 how = 0;
546 }
547 if (how) {
548 if (retval < how)
549 retval = how;
550 if (seen && seen[i] < how)
551 seen[i] = how;
552 }
553 }
554 return retval;
555 }
556
557 static int match_pathspec_with_flags(struct index_state *istate,
558 const struct pathspec *ps,
559 const char *name, int namelen,
560 int prefix, char *seen, unsigned flags)
561 {
562 int positive, negative;
563 positive = do_match_pathspec(istate, ps, name, namelen,
564 prefix, seen, flags);
565 if (!(ps->magic & PATHSPEC_EXCLUDE) || !positive)
566 return positive;
567 negative = do_match_pathspec(istate, ps, name, namelen,
568 prefix, seen,
569 flags | DO_MATCH_EXCLUDE);
570 return negative ? 0 : positive;
571 }
572
573 int match_pathspec(struct index_state *istate,
574 const struct pathspec *ps,
575 const char *name, int namelen,
576 int prefix, char *seen, int is_dir)
577 {
578 unsigned flags = is_dir ? DO_MATCH_DIRECTORY : 0;
579 return match_pathspec_with_flags(istate, ps, name, namelen,
580 prefix, seen, flags);
581 }
582
583 int match_leading_pathspec(struct index_state *istate,
584 const struct pathspec *ps,
585 const char *name, int namelen,
586 int prefix, char *seen, int is_dir)
587 {
588 unsigned flags = is_dir ? DO_MATCH_DIRECTORY | DO_MATCH_LEADING_PATHSPEC : 0;
589 return match_pathspec_with_flags(istate, ps, name, namelen,
590 prefix, seen, flags);
591 }
592
593 /**
594 * Check if a submodule is a superset of the pathspec
595 */
596 int submodule_path_match(struct index_state *istate,
597 const struct pathspec *ps,
598 const char *submodule_name,
599 char *seen)
600 {
601 int matched = match_pathspec_with_flags(istate, ps, submodule_name,
602 strlen(submodule_name),
603 0, seen,
604 DO_MATCH_DIRECTORY |
605 DO_MATCH_LEADING_PATHSPEC);
606 return matched;
607 }
608
609 int report_path_error(const char *ps_matched,
610 const struct pathspec *pathspec)
611 {
612 /*
613 * Make sure all pathspec matched; otherwise it is an error.
614 */
615 int num, errors = 0;
616 for (num = 0; num < pathspec->nr; num++) {
617 int other, found_dup;
618
619 if (ps_matched[num])
620 continue;
621 /*
622 * The caller might have fed identical pathspec
623 * twice. Do not barf on such a mistake.
624 * FIXME: parse_pathspec should have eliminated
625 * duplicate pathspec.
626 */
627 for (found_dup = other = 0;
628 !found_dup && other < pathspec->nr;
629 other++) {
630 if (other == num || !ps_matched[other])
631 continue;
632 if (!strcmp(pathspec->items[other].original,
633 pathspec->items[num].original))
634 /*
635 * Ok, we have a match already.
636 */
637 found_dup = 1;
638 }
639 if (found_dup)
640 continue;
641
642 error(_("pathspec '%s' did not match any file(s) known to git"),
643 pathspec->items[num].original);
644 errors++;
645 }
646 return errors;
647 }
648
649 /*
650 * Return the length of the "simple" part of a path match limiter.
651 */
652 int simple_length(const char *match)
653 {
654 int len = -1;
655
656 for (;;) {
657 unsigned char c = *match++;
658 len++;
659 if (c == '\0' || is_glob_special(c))
660 return len;
661 }
662 }
663
664 int no_wildcard(const char *string)
665 {
666 return string[simple_length(string)] == '\0';
667 }
668
669 void parse_path_pattern(const char **pattern,
670 int *patternlen,
671 unsigned *flags,
672 int *nowildcardlen)
673 {
674 const char *p = *pattern;
675 size_t i, len;
676
677 *flags = 0;
678 if (*p == '!') {
679 *flags |= PATTERN_FLAG_NEGATIVE;
680 p++;
681 }
682 len = strlen(p);
683 if (len && p[len - 1] == '/') {
684 len--;
685 *flags |= PATTERN_FLAG_MUSTBEDIR;
686 }
687 for (i = 0; i < len; i++) {
688 if (p[i] == '/')
689 break;
690 }
691 if (i == len)
692 *flags |= PATTERN_FLAG_NODIR;
693 *nowildcardlen = simple_length(p);
694 /*
695 * we should have excluded the trailing slash from 'p' too,
696 * but that's one more allocation. Instead just make sure
697 * nowildcardlen does not exceed real patternlen
698 */
699 if (*nowildcardlen > len)
700 *nowildcardlen = len;
701 if (*p == '*' && no_wildcard(p + 1))
702 *flags |= PATTERN_FLAG_ENDSWITH;
703 *pattern = p;
704 *patternlen = len;
705 }
706
707 int pl_hashmap_cmp(const void *cmp_data UNUSED,
708 const struct hashmap_entry *a,
709 const struct hashmap_entry *b,
710 const void *key UNUSED)
711 {
712 const struct pattern_entry *ee1 =
713 container_of(a, struct pattern_entry, ent);
714 const struct pattern_entry *ee2 =
715 container_of(b, struct pattern_entry, ent);
716
717 size_t min_len = ee1->patternlen <= ee2->patternlen
718 ? ee1->patternlen
719 : ee2->patternlen;
720
721 return fspathncmp(ee1->pattern, ee2->pattern, min_len);
722 }
723
724 static char *dup_and_filter_pattern(const char *pattern)
725 {
726 char *set, *read;
727 size_t count = 0;
728 char *result = xstrdup(pattern);
729
730 set = result;
731 read = result;
732
733 while (*read) {
734 /* skip escape characters (once) */
735 if (*read == '\\')
736 read++;
737
738 *set = *read;
739
740 set++;
741 read++;
742 count++;
743 }
744 *set = 0;
745
746 if (count > 2 &&
747 *(set - 1) == '*' &&
748 *(set - 2) == '/')
749 *(set - 2) = 0;
750
751 return result;
752 }
753
754 static void clear_pattern_entry_hashmap(struct hashmap *map)
755 {
756 struct hashmap_iter iter;
757 struct pattern_entry *entry;
758
759 hashmap_for_each_entry(map, &iter, entry, ent) {
760 free(entry->pattern);
761 }
762 hashmap_clear_and_free(map, struct pattern_entry, ent);
763 }
764
765 static void add_pattern_to_hashsets(struct pattern_list *pl, struct path_pattern *given)
766 {
767 struct pattern_entry *translated;
768 char *truncated;
769 char *data = NULL;
770 const char *prev, *cur, *next;
771
772 if (!pl->use_cone_patterns)
773 return;
774
775 if (given->flags & PATTERN_FLAG_NEGATIVE &&
776 given->flags & PATTERN_FLAG_MUSTBEDIR &&
777 !strcmp(given->pattern, "/*")) {
778 pl->full_cone = 0;
779 return;
780 }
781
782 if (!given->flags && !strcmp(given->pattern, "/*")) {
783 pl->full_cone = 1;
784 return;
785 }
786
787 if (given->patternlen < 2 ||
788 *given->pattern != '/' ||
789 strstr(given->pattern, "**")) {
790 /* Not a cone pattern. */
791 warning(_("unrecognized pattern: '%s'"), given->pattern);
792 goto clear_hashmaps;
793 }
794
795 if (!(given->flags & PATTERN_FLAG_MUSTBEDIR) &&
796 strcmp(given->pattern, "/*")) {
797 /* Not a cone pattern. */
798 warning(_("unrecognized pattern: '%s'"), given->pattern);
799 goto clear_hashmaps;
800 }
801
802 prev = given->pattern;
803 cur = given->pattern + 1;
804 next = given->pattern + 2;
805
806 while (*cur) {
807 /* Watch for glob characters '*', '\', '[', '?' */
808 if (!is_glob_special(*cur))
809 goto increment;
810
811 /* But only if *prev != '\\' */
812 if (*prev == '\\')
813 goto increment;
814
815 /* But allow the initial '\' */
816 if (*cur == '\\' &&
817 is_glob_special(*next))
818 goto increment;
819
820 /* But a trailing '/' then '*' is fine */
821 if (*prev == '/' &&
822 *cur == '*' &&
823 *next == 0)
824 goto increment;
825
826 /* Not a cone pattern. */
827 warning(_("unrecognized pattern: '%s'"), given->pattern);
828 goto clear_hashmaps;
829
830 increment:
831 prev++;
832 cur++;
833 next++;
834 }
835
836 if (given->patternlen > 2 &&
837 !strcmp(given->pattern + given->patternlen - 2, "/*")) {
838 struct pattern_entry *old;
839
840 if (!(given->flags & PATTERN_FLAG_NEGATIVE)) {
841 /* Not a cone pattern. */
842 warning(_("unrecognized pattern: '%s'"), given->pattern);
843 goto clear_hashmaps;
844 }
845
846 truncated = dup_and_filter_pattern(given->pattern);
847
848 translated = xmalloc(sizeof(struct pattern_entry));
849 translated->pattern = truncated;
850 translated->patternlen = given->patternlen - 2;
851 hashmap_entry_init(&translated->ent,
852 fspathhash(translated->pattern));
853
854 if (!hashmap_get_entry(&pl->recursive_hashmap,
855 translated, ent, NULL)) {
856 /* We did not see the "parent" included */
857 warning(_("unrecognized negative pattern: '%s'"),
858 given->pattern);
859 free(truncated);
860 free(translated);
861 goto clear_hashmaps;
862 }
863
864 hashmap_add(&pl->parent_hashmap, &translated->ent);
865 old = hashmap_remove_entry(&pl->recursive_hashmap, translated, ent, &data);
866 if (old) {
867 free(old->pattern);
868 free(old);
869 }
870 free(data);
871 return;
872 }
873
874 if (given->flags & PATTERN_FLAG_NEGATIVE) {
875 warning(_("unrecognized negative pattern: '%s'"),
876 given->pattern);
877 goto clear_hashmaps;
878 }
879
880 translated = xmalloc(sizeof(struct pattern_entry));
881
882 translated->pattern = dup_and_filter_pattern(given->pattern);
883 translated->patternlen = given->patternlen;
884 hashmap_entry_init(&translated->ent,
885 fspathhash(translated->pattern));
886
887 hashmap_add(&pl->recursive_hashmap, &translated->ent);
888
889 if (hashmap_get_entry(&pl->parent_hashmap, translated, ent, NULL)) {
890 /* we already included this at the parent level */
891 warning(_("your sparse-checkout file may have issues: pattern '%s' is repeated"),
892 given->pattern);
893 goto clear_hashmaps;
894 }
895
896 return;
897
898 clear_hashmaps:
899 warning(_("disabling cone pattern matching"));
900 clear_pattern_entry_hashmap(&pl->recursive_hashmap);
901 clear_pattern_entry_hashmap(&pl->parent_hashmap);
902 pl->use_cone_patterns = 0;
903 }
904
905 static int hashmap_contains_path(struct hashmap *map,
906 struct strbuf *pattern)
907 {
908 struct pattern_entry p;
909
910 /* Check straight mapping */
911 p.pattern = pattern->buf;
912 p.patternlen = pattern->len;
913 hashmap_entry_init(&p.ent, fspathhash(p.pattern));
914 return !!hashmap_get_entry(map, &p, ent, NULL);
915 }
916
917 int hashmap_contains_parent(struct hashmap *map,
918 const char *path,
919 struct strbuf *buffer)
920 {
921 char *slash_pos;
922
923 strbuf_setlen(buffer, 0);
924
925 if (path[0] != '/')
926 strbuf_addch(buffer, '/');
927
928 strbuf_addstr(buffer, path);
929
930 slash_pos = strrchr(buffer->buf, '/');
931
932 while (slash_pos > buffer->buf) {
933 strbuf_setlen(buffer, slash_pos - buffer->buf);
934
935 if (hashmap_contains_path(map, buffer))
936 return 1;
937
938 slash_pos = strrchr(buffer->buf, '/');
939 }
940
941 return 0;
942 }
943
944 void add_pattern(const char *string, const char *base,
945 int baselen, struct pattern_list *pl, int srcpos)
946 {
947 struct path_pattern *pattern;
948 int patternlen;
949 unsigned flags;
950 int nowildcardlen;
951
952 parse_path_pattern(&string, &patternlen, &flags, &nowildcardlen);
953 FLEX_ALLOC_MEM(pattern, pattern, string, patternlen);
954 pattern->patternlen = patternlen;
955 pattern->nowildcardlen = nowildcardlen;
956 pattern->base = base;
957 pattern->baselen = baselen;
958 pattern->flags = flags;
959 pattern->srcpos = srcpos;
960 ALLOC_GROW(pl->patterns, pl->nr + 1, pl->alloc);
961 pl->patterns[pl->nr++] = pattern;
962 pattern->pl = pl;
963
964 add_pattern_to_hashsets(pl, pattern);
965 }
966
967 static int read_skip_worktree_file_from_index(struct index_state *istate,
968 const char *path,
969 size_t *size_out, char **data_out,
970 struct oid_stat *oid_stat)
971 {
972 int pos, len;
973
974 len = strlen(path);
975 pos = index_name_pos(istate, path, len);
976 if (pos < 0)
977 return -1;
978 if (!ce_skip_worktree(istate->cache[pos]))
979 return -1;
980
981 return do_read_blob(&istate->cache[pos]->oid, oid_stat, size_out, data_out);
982 }
983
984 /*
985 * Frees memory within pl which was allocated for exclude patterns and
986 * the file buffer. Does not free pl itself.
987 */
988 void clear_pattern_list(struct pattern_list *pl)
989 {
990 int i;
991
992 for (i = 0; i < pl->nr; i++)
993 free(pl->patterns[i]);
994 free(pl->patterns);
995 clear_pattern_entry_hashmap(&pl->recursive_hashmap);
996 clear_pattern_entry_hashmap(&pl->parent_hashmap);
997
998 memset(pl, 0, sizeof(*pl));
999 }
1000
1001 static void trim_trailing_spaces(char *buf)
1002 {
1003 char *p, *last_space = NULL;
1004
1005 for (p = buf; *p; p++)
1006 switch (*p) {
1007 case ' ':
1008 if (!last_space)
1009 last_space = p;
1010 break;
1011 case '\\':
1012 p++;
1013 if (!*p)
1014 return;
1015 /* fallthrough */
1016 default:
1017 last_space = NULL;
1018 }
1019
1020 if (last_space)
1021 *last_space = '\0';
1022 }
1023
1024 /*
1025 * Given a subdirectory name and "dir" of the current directory,
1026 * search the subdir in "dir" and return it, or create a new one if it
1027 * does not exist in "dir".
1028 *
1029 * If "name" has the trailing slash, it'll be excluded in the search.
1030 */
1031 static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc,
1032 struct untracked_cache_dir *dir,
1033 const char *name, int len)
1034 {
1035 int first, last;
1036 struct untracked_cache_dir *d;
1037 if (!dir)
1038 return NULL;
1039 if (len && name[len - 1] == '/')
1040 len--;
1041 first = 0;
1042 last = dir->dirs_nr;
1043 while (last > first) {
1044 int cmp, next = first + ((last - first) >> 1);
1045 d = dir->dirs[next];
1046 cmp = strncmp(name, d->name, len);
1047 if (!cmp && strlen(d->name) > len)
1048 cmp = -1;
1049 if (!cmp)
1050 return d;
1051 if (cmp < 0) {
1052 last = next;
1053 continue;
1054 }
1055 first = next+1;
1056 }
1057
1058 uc->dir_created++;
1059 FLEX_ALLOC_MEM(d, name, name, len);
1060
1061 ALLOC_GROW(dir->dirs, dir->dirs_nr + 1, dir->dirs_alloc);
1062 MOVE_ARRAY(dir->dirs + first + 1, dir->dirs + first,
1063 dir->dirs_nr - first);
1064 dir->dirs_nr++;
1065 dir->dirs[first] = d;
1066 return d;
1067 }
1068
1069 static void do_invalidate_gitignore(struct untracked_cache_dir *dir)
1070 {
1071 int i;
1072 dir->valid = 0;
1073 for (size_t i = 0; i < dir->untracked_nr; i++)
1074 free(dir->untracked[i]);
1075 dir->untracked_nr = 0;
1076 for (i = 0; i < dir->dirs_nr; i++)
1077 do_invalidate_gitignore(dir->dirs[i]);
1078 }
1079
1080 static void invalidate_gitignore(struct untracked_cache *uc,
1081 struct untracked_cache_dir *dir)
1082 {
1083 uc->gitignore_invalidated++;
1084 do_invalidate_gitignore(dir);
1085 }
1086
1087 static void invalidate_directory(struct untracked_cache *uc,
1088 struct untracked_cache_dir *dir)
1089 {
1090 int i;
1091
1092 /*
1093 * Invalidation increment here is just roughly correct. If
1094 * untracked_nr or any of dirs[].recurse is non-zero, we
1095 * should increment dir_invalidated too. But that's more
1096 * expensive to do.
1097 */
1098 if (dir->valid)
1099 uc->dir_invalidated++;
1100
1101 dir->valid = 0;
1102 for (size_t i = 0; i < dir->untracked_nr; i++)
1103 free(dir->untracked[i]);
1104 dir->untracked_nr = 0;
1105 for (i = 0; i < dir->dirs_nr; i++)
1106 dir->dirs[i]->recurse = 0;
1107 }
1108
1109 /* Flags for add_patterns() */
1110 #define PATTERN_NOFOLLOW (1<<0)
1111
1112 /*
1113 * Given a file with name "fname", read it (either from disk, or from
1114 * an index if 'istate' is non-null), parse it and store the
1115 * exclude rules in "pl".
1116 *
1117 * If "oid_stat" is not NULL, compute oid of the exclude file and fill
1118 * stat data from disk (only valid if add_patterns returns zero). If
1119 * oid_stat.valid is non-zero, "oid_stat" must contain good value as input.
1120 */
1121 static int add_patterns(const char *fname, const char *base, int baselen,
1122 struct pattern_list *pl, struct index_state *istate,
1123 unsigned flags, struct oid_stat *oid_stat)
1124 {
1125 struct stat st;
1126 int r;
1127 int fd;
1128 size_t size = 0;
1129 char *buf;
1130
1131 if (flags & PATTERN_NOFOLLOW)
1132 fd = open_nofollow(fname, O_RDONLY);
1133 else
1134 fd = open(fname, O_RDONLY);
1135
1136 if (fd < 0 || fstat(fd, &st) < 0) {
1137 if (fd < 0)
1138 warn_on_fopen_errors(fname);
1139 else
1140 close(fd);
1141 if (!istate)
1142 return -1;
1143 r = read_skip_worktree_file_from_index(istate, fname,
1144 &size, &buf,
1145 oid_stat);
1146 if (r != 1)
1147 return r;
1148 } else {
1149 size = xsize_t(st.st_size);
1150 if (size == 0) {
1151 if (oid_stat) {
1152 fill_stat_data(&oid_stat->stat, &st);
1153 oidcpy(&oid_stat->oid, the_hash_algo->empty_blob);
1154 oid_stat->valid = 1;
1155 }
1156 close(fd);
1157 return 0;
1158 }
1159 buf = xmallocz(size);
1160 if (read_in_full(fd, buf, size) != size) {
1161 free(buf);
1162 close(fd);
1163 return -1;
1164 }
1165 buf[size++] = '\n';
1166 close(fd);
1167 if (oid_stat) {
1168 int pos;
1169 if (oid_stat->valid &&
1170 !match_stat_data_racy(istate, &oid_stat->stat, &st))
1171 ; /* no content change, oid_stat->oid still good */
1172 else if (istate &&
1173 (pos = index_name_pos(istate, fname, strlen(fname))) >= 0 &&
1174 !ce_stage(istate->cache[pos]) &&
1175 ce_uptodate(istate->cache[pos]) &&
1176 !would_convert_to_git(istate, fname))
1177 oidcpy(&oid_stat->oid,
1178 &istate->cache[pos]->oid);
1179 else
1180 hash_object_file(the_hash_algo, buf, size,
1181 OBJ_BLOB, &oid_stat->oid);
1182 fill_stat_data(&oid_stat->stat, &st);
1183 oid_stat->valid = 1;
1184 }
1185 }
1186
1187 if (size > PATTERN_MAX_FILE_SIZE) {
1188 warning("ignoring excessively large pattern file: %s", fname);
1189 free(buf);
1190 return -1;
1191 }
1192
1193 add_patterns_from_buffer(buf, size, base, baselen, pl);
1194 free(buf);
1195 return 0;
1196 }
1197
1198 int add_patterns_from_buffer(char *buf, size_t size,
1199 const char *base, int baselen,
1200 struct pattern_list *pl)
1201 {
1202 char *orig = buf;
1203 int i, lineno = 1;
1204 char *entry;
1205
1206 hashmap_init(&pl->recursive_hashmap, pl_hashmap_cmp, NULL, 0);
1207 hashmap_init(&pl->parent_hashmap, pl_hashmap_cmp, NULL, 0);
1208
1209 if (skip_utf8_bom(&buf, size))
1210 size -= buf - orig;
1211
1212 entry = buf;
1213
1214 for (i = 0; i < size; i++) {
1215 if (buf[i] == '\n') {
1216 if (entry != buf + i && entry[0] != '#') {
1217 buf[i - (i && buf[i-1] == '\r')] = 0;
1218 trim_trailing_spaces(entry);
1219 add_pattern(entry, base, baselen, pl, lineno);
1220 }
1221 lineno++;
1222 entry = buf + i + 1;
1223 }
1224 }
1225 return 0;
1226 }
1227
1228 int add_patterns_from_file_to_list(const char *fname, const char *base,
1229 int baselen, struct pattern_list *pl,
1230 struct index_state *istate,
1231 unsigned flags)
1232 {
1233 return add_patterns(fname, base, baselen, pl, istate, flags, NULL);
1234 }
1235
1236 int add_patterns_from_blob_to_list(
1237 struct object_id *oid,
1238 const char *base, int baselen,
1239 struct pattern_list *pl)
1240 {
1241 char *buf;
1242 size_t size;
1243 int r;
1244
1245 r = do_read_blob(oid, NULL, &size, &buf);
1246 if (r != 1)
1247 return r;
1248
1249 if (size > PATTERN_MAX_FILE_SIZE) {
1250 warning("ignoring excessively large pattern blob: %s",
1251 oid_to_hex(oid));
1252 free(buf);
1253 return -1;
1254 }
1255
1256 add_patterns_from_buffer(buf, size, base, baselen, pl);
1257 free(buf);
1258 return 0;
1259 }
1260
1261 struct pattern_list *add_pattern_list(struct dir_struct *dir,
1262 int group_type, const char *src)
1263 {
1264 struct pattern_list *pl;
1265 struct exclude_list_group *group;
1266
1267 group = &dir->internal.exclude_list_group[group_type];
1268 ALLOC_GROW(group->pl, group->nr + 1, group->alloc);
1269 pl = &group->pl[group->nr++];
1270 memset(pl, 0, sizeof(*pl));
1271 pl->src = src;
1272 return pl;
1273 }
1274
1275 /*
1276 * Used to set up core.excludesfile and .git/info/exclude lists.
1277 */
1278 static void add_patterns_from_file_1(struct dir_struct *dir, const char *fname,
1279 struct oid_stat *oid_stat)
1280 {
1281 struct pattern_list *pl;
1282 /*
1283 * catch setup_standard_excludes() that's called before
1284 * dir->untracked is assigned. That function behaves
1285 * differently when dir->untracked is non-NULL.
1286 */
1287 if (!dir->untracked)
1288 dir->internal.unmanaged_exclude_files++;
1289 pl = add_pattern_list(dir, EXC_FILE, fname);
1290 if (add_patterns(fname, "", 0, pl, NULL, 0, oid_stat) < 0)
1291 die(_("cannot use %s as an exclude file"), fname);
1292 }
1293
1294 void add_patterns_from_file(struct dir_struct *dir, const char *fname)
1295 {
1296 dir->internal.unmanaged_exclude_files++; /* see validate_untracked_cache() */
1297 add_patterns_from_file_1(dir, fname, NULL);
1298 }
1299
1300 int match_basename(const char *basename, int basenamelen,
1301 const char *pattern, int prefix, int patternlen,
1302 unsigned flags)
1303 {
1304 if (prefix == patternlen) {
1305 if (patternlen == basenamelen &&
1306 !fspathncmp(pattern, basename, basenamelen))
1307 return 1;
1308 } else if (flags & PATTERN_FLAG_ENDSWITH) {
1309 /* "*literal" matching against "fooliteral" */
1310 if (patternlen - 1 <= basenamelen &&
1311 !fspathncmp(pattern + 1,
1312 basename + basenamelen - (patternlen - 1),
1313 patternlen - 1))
1314 return 1;
1315 } else {
1316 if (fnmatch_icase_mem(pattern, patternlen,
1317 basename, basenamelen,
1318 0) == 0)
1319 return 1;
1320 }
1321 return 0;
1322 }
1323
1324 int match_pathname(const char *pathname, int pathlen,
1325 const char *base, int baselen,
1326 const char *pattern, int prefix, int patternlen)
1327 {
1328 const char *name;
1329 int namelen;
1330
1331 /*
1332 * match with FNM_PATHNAME; the pattern has base implicitly
1333 * in front of it.
1334 */
1335 if (*pattern == '/') {
1336 pattern++;
1337 patternlen--;
1338 prefix--;
1339 }
1340
1341 /*
1342 * baselen does not count the trailing slash. base[] may or
1343 * may not end with a trailing slash though.
1344 */
1345 if (pathlen < baselen + 1 ||
1346 (baselen && pathname[baselen] != '/') ||
1347 fspathncmp(pathname, base, baselen))
1348 return 0;
1349
1350 namelen = baselen ? pathlen - baselen - 1 : pathlen;
1351 name = pathname + pathlen - namelen;
1352
1353 if (prefix) {
1354 /*
1355 * if the non-wildcard part is longer than the
1356 * remaining pathname, surely it cannot match.
1357 */
1358 if (prefix > namelen)
1359 return 0;
1360
1361 if (fspathncmp(pattern, name, prefix))
1362 return 0;
1363 pattern += prefix;
1364 patternlen -= prefix;
1365 name += prefix;
1366 namelen -= prefix;
1367
1368 /*
1369 * If the whole pattern did not have a wildcard,
1370 * then our prefix match is all we need; we
1371 * do not need to call fnmatch at all.
1372 */
1373 if (!patternlen && !namelen)
1374 return 1;
1375 }
1376
1377 return fnmatch_icase_mem(pattern, patternlen,
1378 name, namelen,
1379 WM_PATHNAME) == 0;
1380 }
1381
1382 /*
1383 * Scan the given exclude list in reverse to see whether pathname
1384 * should be ignored. The first match (i.e. the last on the list), if
1385 * any, determines the fate. Returns the exclude_list element which
1386 * matched, or NULL for undecided.
1387 */
1388 static struct path_pattern *last_matching_pattern_from_list(const char *pathname,
1389 int pathlen,
1390 const char *basename,
1391 int *dtype,
1392 struct pattern_list *pl,
1393 struct index_state *istate)
1394 {
1395 struct path_pattern *res = NULL; /* undecided */
1396 int i;
1397
1398 if (!pl->nr)
1399 return NULL; /* undefined */
1400
1401 for (i = pl->nr - 1; 0 <= i; i--) {
1402 struct path_pattern *pattern = pl->patterns[i];
1403 const char *exclude = pattern->pattern;
1404 int prefix = pattern->nowildcardlen;
1405
1406 if (pattern->flags & PATTERN_FLAG_MUSTBEDIR) {
1407 *dtype = resolve_dtype(*dtype, istate, pathname, pathlen);
1408 if (*dtype != DT_DIR)
1409 continue;
1410 }
1411
1412 if (pattern->flags & PATTERN_FLAG_NODIR) {
1413 if (match_basename(basename,
1414 pathlen - (basename - pathname),
1415 exclude, prefix, pattern->patternlen,
1416 pattern->flags)) {
1417 res = pattern;
1418 break;
1419 }
1420 continue;
1421 }
1422
1423 assert(pattern->baselen == 0 ||
1424 pattern->base[pattern->baselen - 1] == '/');
1425 if (match_pathname(pathname, pathlen,
1426 pattern->base,
1427 pattern->baselen ? pattern->baselen - 1 : 0,
1428 exclude, prefix, pattern->patternlen)) {
1429 res = pattern;
1430 break;
1431 }
1432 }
1433 return res;
1434 }
1435
1436 /*
1437 * Scan the list of patterns to determine if the ordered list
1438 * of patterns matches on 'pathname'.
1439 *
1440 * Return 1 for a match, 0 for not matched and -1 for undecided.
1441 */
1442 enum pattern_match_result path_matches_pattern_list(
1443 const char *pathname, int pathlen,
1444 const char *basename, int *dtype,
1445 struct pattern_list *pl,
1446 struct index_state *istate)
1447 {
1448 struct path_pattern *pattern;
1449 struct strbuf parent_pathname = STRBUF_INIT;
1450 int result = NOT_MATCHED;
1451 size_t slash_pos;
1452
1453 if (!pl->use_cone_patterns) {
1454 pattern = last_matching_pattern_from_list(pathname, pathlen, basename,
1455 dtype, pl, istate);
1456 if (pattern) {
1457 if (pattern->flags & PATTERN_FLAG_NEGATIVE)
1458 return NOT_MATCHED;
1459 else
1460 return MATCHED;
1461 }
1462
1463 return UNDECIDED;
1464 }
1465
1466 if (pl->full_cone)
1467 return MATCHED;
1468
1469 strbuf_addch(&parent_pathname, '/');
1470 strbuf_add(&parent_pathname, pathname, pathlen);
1471
1472 /*
1473 * Directory entries are matched if and only if a file
1474 * contained immediately within them is matched. For the
1475 * case of a directory entry, modify the path to create
1476 * a fake filename within this directory, allowing us to
1477 * use the file-base matching logic in an equivalent way.
1478 */
1479 if (parent_pathname.len > 0 &&
1480 parent_pathname.buf[parent_pathname.len - 1] == '/') {
1481 slash_pos = parent_pathname.len - 1;
1482 strbuf_add(&parent_pathname, "-", 1);
1483 } else {
1484 const char *slash_ptr = strrchr(parent_pathname.buf, '/');
1485 slash_pos = slash_ptr ? slash_ptr - parent_pathname.buf : 0;
1486 }
1487
1488 if (hashmap_contains_path(&pl->recursive_hashmap,
1489 &parent_pathname)) {
1490 result = MATCHED_RECURSIVE;
1491 goto done;
1492 }
1493
1494 if (!slash_pos) {
1495 /* include every file in root */
1496 result = MATCHED;
1497 goto done;
1498 }
1499
1500 strbuf_setlen(&parent_pathname, slash_pos);
1501
1502 if (hashmap_contains_path(&pl->parent_hashmap, &parent_pathname)) {
1503 result = MATCHED;
1504 goto done;
1505 }
1506
1507 if (hashmap_contains_parent(&pl->recursive_hashmap,
1508 pathname,
1509 &parent_pathname))
1510 result = MATCHED_RECURSIVE;
1511
1512 done:
1513 strbuf_release(&parent_pathname);
1514 return result;
1515 }
1516
1517 int init_sparse_checkout_patterns(struct index_state *istate)
1518 {
1519 if (!core_apply_sparse_checkout)
1520 return 1;
1521 if (istate->sparse_checkout_patterns)
1522 return 0;
1523
1524 CALLOC_ARRAY(istate->sparse_checkout_patterns, 1);
1525
1526 if (get_sparse_checkout_patterns(istate->sparse_checkout_patterns) < 0) {
1527 FREE_AND_NULL(istate->sparse_checkout_patterns);
1528 return -1;
1529 }
1530
1531 return 0;
1532 }
1533
1534 static int path_in_sparse_checkout_1(const char *path,
1535 struct index_state *istate,
1536 int require_cone_mode)
1537 {
1538 int dtype = DT_REG;
1539 enum pattern_match_result match = UNDECIDED;
1540 const char *end, *slash;
1541
1542 /*
1543 * We default to accepting a path if the path is empty, there are no
1544 * patterns, or the patterns are of the wrong type.
1545 */
1546 if (!*path ||
1547 init_sparse_checkout_patterns(istate) ||
1548 (require_cone_mode &&
1549 !istate->sparse_checkout_patterns->use_cone_patterns))
1550 return 1;
1551
1552 /*
1553 * If UNDECIDED, use the match from the parent dir (recursively), or
1554 * fall back to NOT_MATCHED at the topmost level. Note that cone mode
1555 * never returns UNDECIDED, so we will execute only one iteration in
1556 * this case.
1557 */
1558 for (end = path + strlen(path);
1559 end > path && match == UNDECIDED;
1560 end = slash) {
1561
1562 for (slash = end - 1; slash > path && *slash != '/'; slash--)
1563 ; /* do nothing */
1564
1565 match = path_matches_pattern_list(path, end - path,
1566 slash > path ? slash + 1 : path, &dtype,
1567 istate->sparse_checkout_patterns, istate);
1568
1569 /* We are going to match the parent dir now */
1570 dtype = DT_DIR;
1571 }
1572 return match > 0;
1573 }
1574
1575 int path_in_sparse_checkout(const char *path,
1576 struct index_state *istate)
1577 {
1578 return path_in_sparse_checkout_1(path, istate, 0);
1579 }
1580
1581 int path_in_cone_mode_sparse_checkout(const char *path,
1582 struct index_state *istate)
1583 {
1584 return path_in_sparse_checkout_1(path, istate, 1);
1585 }
1586
1587 static struct path_pattern *last_matching_pattern_from_lists(
1588 struct dir_struct *dir, struct index_state *istate,
1589 const char *pathname, int pathlen,
1590 const char *basename, int *dtype_p)
1591 {
1592 int i, j;
1593 struct exclude_list_group *group;
1594 struct path_pattern *pattern;
1595 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
1596 group = &dir->internal.exclude_list_group[i];
1597 for (j = group->nr - 1; j >= 0; j--) {
1598 pattern = last_matching_pattern_from_list(
1599 pathname, pathlen, basename, dtype_p,
1600 &group->pl[j], istate);
1601 if (pattern)
1602 return pattern;
1603 }
1604 }
1605 return NULL;
1606 }
1607
1608 /*
1609 * Loads the per-directory exclude list for the substring of base
1610 * which has a char length of baselen.
1611 */
1612 static void prep_exclude(struct dir_struct *dir,
1613 struct index_state *istate,
1614 const char *base, int baselen)
1615 {
1616 struct exclude_list_group *group;
1617 struct pattern_list *pl;
1618 struct exclude_stack *stk = NULL;
1619 struct untracked_cache_dir *untracked;
1620 int current;
1621
1622 group = &dir->internal.exclude_list_group[EXC_DIRS];
1623
1624 /*
1625 * Pop the exclude lists from the EXCL_DIRS exclude_list_group
1626 * which originate from directories not in the prefix of the
1627 * path being checked.
1628 */
1629 while ((stk = dir->internal.exclude_stack) != NULL) {
1630 if (stk->baselen <= baselen &&
1631 !strncmp(dir->internal.basebuf.buf, base, stk->baselen))
1632 break;
1633 pl = &group->pl[dir->internal.exclude_stack->exclude_ix];
1634 dir->internal.exclude_stack = stk->prev;
1635 dir->internal.pattern = NULL;
1636 free((char *)pl->src); /* see strbuf_detach() below */
1637 clear_pattern_list(pl);
1638 free(stk);
1639 group->nr--;
1640 }
1641
1642 /* Skip traversing into sub directories if the parent is excluded */
1643 if (dir->internal.pattern)
1644 return;
1645
1646 /*
1647 * Lazy initialization. All call sites currently just
1648 * memset(dir, 0, sizeof(*dir)) before use. Changing all of
1649 * them seems lots of work for little benefit.
1650 */
1651 if (!dir->internal.basebuf.buf)
1652 strbuf_init(&dir->internal.basebuf, PATH_MAX);
1653
1654 /* Read from the parent directories and push them down. */
1655 current = stk ? stk->baselen : -1;
1656 strbuf_setlen(&dir->internal.basebuf, current < 0 ? 0 : current);
1657 if (dir->untracked)
1658 untracked = stk ? stk->ucd : dir->untracked->root;
1659 else
1660 untracked = NULL;
1661
1662 while (current < baselen) {
1663 const char *cp;
1664 struct oid_stat oid_stat;
1665
1666 CALLOC_ARRAY(stk, 1);
1667 if (current < 0) {
1668 cp = base;
1669 current = 0;
1670 } else {
1671 cp = strchr(base + current + 1, '/');
1672 if (!cp)
1673 die("oops in prep_exclude");
1674 cp++;
1675 untracked =
1676 lookup_untracked(dir->untracked,
1677 untracked,
1678 base + current,
1679 cp - base - current);
1680 }
1681 stk->prev = dir->internal.exclude_stack;
1682 stk->baselen = cp - base;
1683 stk->exclude_ix = group->nr;
1684 stk->ucd = untracked;
1685 pl = add_pattern_list(dir, EXC_DIRS, NULL);
1686 strbuf_add(&dir->internal.basebuf, base + current, stk->baselen - current);
1687 assert(stk->baselen == dir->internal.basebuf.len);
1688
1689 /* Abort if the directory is excluded */
1690 if (stk->baselen) {
1691 int dt = DT_DIR;
1692 dir->internal.basebuf.buf[stk->baselen - 1] = 0;
1693 dir->internal.pattern = last_matching_pattern_from_lists(dir,
1694 istate,
1695 dir->internal.basebuf.buf, stk->baselen - 1,
1696 dir->internal.basebuf.buf + current, &dt);
1697 dir->internal.basebuf.buf[stk->baselen - 1] = '/';
1698 if (dir->internal.pattern &&
1699 dir->internal.pattern->flags & PATTERN_FLAG_NEGATIVE)
1700 dir->internal.pattern = NULL;
1701 if (dir->internal.pattern) {
1702 dir->internal.exclude_stack = stk;
1703 return;
1704 }
1705 }
1706
1707 /* Try to read per-directory file */
1708 oidclr(&oid_stat.oid, the_repository->hash_algo);
1709 oid_stat.valid = 0;
1710 if (dir->exclude_per_dir &&
1711 /*
1712 * If we know that no files have been added in
1713 * this directory (i.e. valid_cached_dir() has
1714 * been executed and set untracked->valid) ..
1715 */
1716 (!untracked || !untracked->valid ||
1717 /*
1718 * .. and .gitignore does not exist before
1719 * (i.e. null exclude_oid). Then we can skip
1720 * loading .gitignore, which would result in
1721 * ENOENT anyway.
1722 */
1723 !is_null_oid(&untracked->exclude_oid))) {
1724 /*
1725 * dir->internal.basebuf gets reused by the traversal,
1726 * but we need fname to remain unchanged to ensure the
1727 * src member of each struct path_pattern correctly
1728 * back-references its source file. Other invocations
1729 * of add_pattern_list provide stable strings, so we
1730 * strbuf_detach() and free() here in the caller.
1731 */
1732 struct strbuf sb = STRBUF_INIT;
1733 strbuf_addbuf(&sb, &dir->internal.basebuf);
1734 strbuf_addstr(&sb, dir->exclude_per_dir);
1735 pl->src = strbuf_detach(&sb, NULL);
1736 add_patterns(pl->src, pl->src, stk->baselen, pl, istate,
1737 PATTERN_NOFOLLOW,
1738 untracked ? &oid_stat : NULL);
1739 }
1740 /*
1741 * NEEDSWORK: when untracked cache is enabled, prep_exclude()
1742 * will first be called in valid_cached_dir() then maybe many
1743 * times more in last_matching_pattern(). When the cache is
1744 * used, last_matching_pattern() will not be called and
1745 * reading .gitignore content will be a waste.
1746 *
1747 * So when it's called by valid_cached_dir() and we can get
1748 * .gitignore SHA-1 from the index (i.e. .gitignore is not
1749 * modified on work tree), we could delay reading the
1750 * .gitignore content until we absolutely need it in
1751 * last_matching_pattern(). Be careful about ignore rule
1752 * order, though, if you do that.
1753 */
1754 if (untracked &&
1755 !oideq(&oid_stat.oid, &untracked->exclude_oid)) {
1756 invalidate_gitignore(dir->untracked, untracked);
1757 oidcpy(&untracked->exclude_oid, &oid_stat.oid);
1758 }
1759 dir->internal.exclude_stack = stk;
1760 current = stk->baselen;
1761 }
1762 strbuf_setlen(&dir->internal.basebuf, baselen);
1763 }
1764
1765 /*
1766 * Loads the exclude lists for the directory containing pathname, then
1767 * scans all exclude lists to determine whether pathname is excluded.
1768 * Returns the exclude_list element which matched, or NULL for
1769 * undecided.
1770 */
1771 struct path_pattern *last_matching_pattern(struct dir_struct *dir,
1772 struct index_state *istate,
1773 const char *pathname,
1774 int *dtype_p)
1775 {
1776 int pathlen = strlen(pathname);
1777 const char *basename = strrchr(pathname, '/');
1778 basename = (basename) ? basename+1 : pathname;
1779
1780 prep_exclude(dir, istate, pathname, basename-pathname);
1781
1782 if (dir->internal.pattern)
1783 return dir->internal.pattern;
1784
1785 return last_matching_pattern_from_lists(dir, istate, pathname, pathlen,
1786 basename, dtype_p);
1787 }
1788
1789 /*
1790 * Loads the exclude lists for the directory containing pathname, then
1791 * scans all exclude lists to determine whether pathname is excluded.
1792 * Returns 1 if true, otherwise 0.
1793 */
1794 int is_excluded(struct dir_struct *dir, struct index_state *istate,
1795 const char *pathname, int *dtype_p)
1796 {
1797 struct path_pattern *pattern =
1798 last_matching_pattern(dir, istate, pathname, dtype_p);
1799 if (pattern)
1800 return pattern->flags & PATTERN_FLAG_NEGATIVE ? 0 : 1;
1801 return 0;
1802 }
1803
1804 static struct dir_entry *dir_entry_new(const char *pathname, int len)
1805 {
1806 struct dir_entry *ent;
1807
1808 FLEX_ALLOC_MEM(ent, name, pathname, len);
1809 ent->len = len;
1810 return ent;
1811 }
1812
1813 static struct dir_entry *dir_add_name(struct dir_struct *dir,
1814 struct index_state *istate,
1815 const char *pathname, int len)
1816 {
1817 if (index_file_exists(istate, pathname, len, ignore_case))
1818 return NULL;
1819
1820 ALLOC_GROW(dir->entries, dir->nr+1, dir->internal.alloc);
1821 return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
1822 }
1823
1824 struct dir_entry *dir_add_ignored(struct dir_struct *dir,
1825 struct index_state *istate,
1826 const char *pathname, int len)
1827 {
1828 if (!index_name_is_other(istate, pathname, len))
1829 return NULL;
1830
1831 ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->internal.ignored_alloc);
1832 return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
1833 }
1834
1835 enum exist_status {
1836 index_nonexistent = 0,
1837 index_directory,
1838 index_gitdir
1839 };
1840
1841 /*
1842 * Do not use the alphabetically sorted index to look up
1843 * the directory name; instead, use the case insensitive
1844 * directory hash.
1845 */
1846 static enum exist_status directory_exists_in_index_icase(struct index_state *istate,
1847 const char *dirname, int len)
1848 {
1849 struct cache_entry *ce;
1850
1851 if (index_dir_exists(istate, dirname, len))
1852 return index_directory;
1853
1854 ce = index_file_exists(istate, dirname, len, ignore_case);
1855 if (ce && S_ISGITLINK(ce->ce_mode))
1856 return index_gitdir;
1857
1858 return index_nonexistent;
1859 }
1860
1861 /*
1862 * The index sorts alphabetically by entry name, which
1863 * means that a gitlink sorts as '\0' at the end, while
1864 * a directory (which is defined not as an entry, but as
1865 * the files it contains) will sort with the '/' at the
1866 * end.
1867 */
1868 static enum exist_status directory_exists_in_index(struct index_state *istate,
1869 const char *dirname, int len)
1870 {
1871 int pos;
1872
1873 if (ignore_case)
1874 return directory_exists_in_index_icase(istate, dirname, len);
1875
1876 pos = index_name_pos(istate, dirname, len);
1877 if (pos < 0)
1878 pos = -pos-1;
1879 while (pos < istate->cache_nr) {
1880 const struct cache_entry *ce = istate->cache[pos++];
1881 unsigned char endchar;
1882
1883 if (strncmp(ce->name, dirname, len))
1884 break;
1885 endchar = ce->name[len];
1886 if (endchar > '/')
1887 break;
1888 if (endchar == '/')
1889 return index_directory;
1890 if (!endchar && S_ISGITLINK(ce->ce_mode))
1891 return index_gitdir;
1892 }
1893 return index_nonexistent;
1894 }
1895
1896 /*
1897 * When we find a directory when traversing the filesystem, we
1898 * have three distinct cases:
1899 *
1900 * - ignore it
1901 * - see it as a directory
1902 * - recurse into it
1903 *
1904 * and which one we choose depends on a combination of existing
1905 * git index contents and the flags passed into the directory
1906 * traversal routine.
1907 *
1908 * Case 1: If we *already* have entries in the index under that
1909 * directory name, we always recurse into the directory to see
1910 * all the files.
1911 *
1912 * Case 2: If we *already* have that directory name as a gitlink,
1913 * we always continue to see it as a gitlink, regardless of whether
1914 * there is an actual git directory there or not (it might not
1915 * be checked out as a subproject!)
1916 *
1917 * Case 3: if we didn't have it in the index previously, we
1918 * have a few sub-cases:
1919 *
1920 * (a) if DIR_SHOW_OTHER_DIRECTORIES flag is set, we show it as
1921 * just a directory, unless DIR_HIDE_EMPTY_DIRECTORIES is
1922 * also true, in which case we need to check if it contains any
1923 * untracked and / or ignored files.
1924 * (b) if it looks like a git directory and we don't have the
1925 * DIR_NO_GITLINKS flag, then we treat it as a gitlink, and
1926 * show it as a directory.
1927 * (c) otherwise, we recurse into it.
1928 */
1929 static enum path_treatment treat_directory(struct dir_struct *dir,
1930 struct index_state *istate,
1931 struct untracked_cache_dir *untracked,
1932 const char *dirname, int len, int baselen, int excluded,
1933 const struct pathspec *pathspec)
1934 {
1935 /*
1936 * WARNING: From this function, you can return path_recurse or you
1937 * can call read_directory_recursive() (or neither), but
1938 * you CAN'T DO BOTH.
1939 */
1940 enum path_treatment state;
1941 int matches_how = 0;
1942 int check_only, stop_early;
1943 int old_ignored_nr, old_untracked_nr;
1944 /* The "len-1" is to strip the final '/' */
1945 enum exist_status status = directory_exists_in_index(istate, dirname, len-1);
1946
1947 if (status == index_directory)
1948 return path_recurse;
1949 if (status == index_gitdir)
1950 return path_none;
1951 if (status != index_nonexistent)
1952 BUG("Unhandled value for directory_exists_in_index: %d\n", status);
1953
1954 /*
1955 * We don't want to descend into paths that don't match the necessary
1956 * patterns. Clearly, if we don't have a pathspec, then we can't check
1957 * for matching patterns. Also, if (excluded) then we know we matched
1958 * the exclusion patterns so as an optimization we can skip checking
1959 * for matching patterns.
1960 */
1961 if (pathspec && !excluded) {
1962 matches_how = match_pathspec_with_flags(istate, pathspec,
1963 dirname, len,
1964 0 /* prefix */,
1965 NULL /* seen */,
1966 DO_MATCH_LEADING_PATHSPEC);
1967 if (!matches_how)
1968 return path_none;
1969 }
1970
1971
1972 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
1973 !(dir->flags & DIR_NO_GITLINKS)) {
1974 /*
1975 * Determine if `dirname` is a nested repo by confirming that:
1976 * 1) we are in a nonbare repository, and
1977 * 2) `dirname` is not an immediate parent of `the_repository->gitdir`,
1978 * which could occur if the git_dir or worktree location was
1979 * manually configured by the user; see t2205 testcases 1-3 for
1980 * examples where this matters
1981 */
1982 int nested_repo;
1983 struct strbuf sb = STRBUF_INIT;
1984 strbuf_addstr(&sb, dirname);
1985 nested_repo = is_nonbare_repository_dir(&sb);
1986
1987 if (nested_repo) {
1988 char *real_dirname, *real_gitdir;
1989 strbuf_addstr(&sb, ".git");
1990 real_dirname = real_pathdup(sb.buf, 1);
1991 real_gitdir = real_pathdup(the_repository->gitdir, 1);
1992
1993 nested_repo = !!strcmp(real_dirname, real_gitdir);
1994 free(real_gitdir);
1995 free(real_dirname);
1996 }
1997 strbuf_release(&sb);
1998
1999 if (nested_repo) {
2000 if ((dir->flags & DIR_SKIP_NESTED_GIT) ||
2001 (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC))
2002 return path_none;
2003 return excluded ? path_excluded : path_untracked;
2004 }
2005 }
2006
2007 if (!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)) {
2008 if (excluded &&
2009 (dir->flags & DIR_SHOW_IGNORED_TOO) &&
2010 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING)) {
2011
2012 /*
2013 * This is an excluded directory and we are
2014 * showing ignored paths that match an exclude
2015 * pattern. (e.g. show directory as ignored
2016 * only if it matches an exclude pattern).
2017 * This path will either be 'path_excluded`
2018 * (if we are showing empty directories or if
2019 * the directory is not empty), or will be
2020 * 'path_none' (empty directory, and we are
2021 * not showing empty directories).
2022 */
2023 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
2024 return path_excluded;
2025
2026 if (read_directory_recursive(dir, istate, dirname, len,
2027 untracked, 1, 1, pathspec) == path_excluded)
2028 return path_excluded;
2029
2030 return path_none;
2031 }
2032 return path_recurse;
2033 }
2034
2035 assert(dir->flags & DIR_SHOW_OTHER_DIRECTORIES);
2036
2037 /*
2038 * If we have a pathspec which could match something _below_ this
2039 * directory (e.g. when checking 'subdir/' having a pathspec like
2040 * 'subdir/some/deep/path/file' or 'subdir/widget-*.c'), then we
2041 * need to recurse.
2042 */
2043 if (matches_how == MATCHED_RECURSIVELY_LEADING_PATHSPEC)
2044 return path_recurse;
2045
2046 /* Special cases for where this directory is excluded/ignored */
2047 if (excluded) {
2048 /*
2049 * If DIR_SHOW_OTHER_DIRECTORIES is set and we're not
2050 * hiding empty directories, there is no need to
2051 * recurse into an ignored directory.
2052 */
2053 if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
2054 return path_excluded;
2055
2056 /*
2057 * Even if we are hiding empty directories, we can still avoid
2058 * recursing into ignored directories for DIR_SHOW_IGNORED_TOO
2059 * if DIR_SHOW_IGNORED_TOO_MODE_MATCHING is also set.
2060 */
2061 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
2062 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING))
2063 return path_excluded;
2064 }
2065
2066 /*
2067 * Other than the path_recurse case above, we only need to
2068 * recurse into untracked directories if any of the following
2069 * bits is set:
2070 * - DIR_SHOW_IGNORED (because then we need to determine if
2071 * there are ignored entries below)
2072 * - DIR_SHOW_IGNORED_TOO (same as above)
2073 * - DIR_HIDE_EMPTY_DIRECTORIES (because we have to determine if
2074 * the directory is empty)
2075 */
2076 if (!excluded &&
2077 !(dir->flags & (DIR_SHOW_IGNORED |
2078 DIR_SHOW_IGNORED_TOO |
2079 DIR_HIDE_EMPTY_DIRECTORIES))) {
2080 return path_untracked;
2081 }
2082
2083 /*
2084 * Even if we don't want to know all the paths under an untracked or
2085 * ignored directory, we may still need to go into the directory to
2086 * determine if it is empty (because with DIR_HIDE_EMPTY_DIRECTORIES,
2087 * an empty directory should be path_none instead of path_excluded or
2088 * path_untracked).
2089 */
2090 check_only = ((dir->flags & DIR_HIDE_EMPTY_DIRECTORIES) &&
2091 !(dir->flags & DIR_SHOW_IGNORED_TOO));
2092
2093 /*
2094 * However, there's another optimization possible as a subset of
2095 * check_only, based on the cases we have to consider:
2096 * A) Directory matches no exclude patterns:
2097 * * Directory is empty => path_none
2098 * * Directory has an untracked file under it => path_untracked
2099 * * Directory has only ignored files under it => path_excluded
2100 * B) Directory matches an exclude pattern:
2101 * * Directory is empty => path_none
2102 * * Directory has an untracked file under it => path_excluded
2103 * * Directory has only ignored files under it => path_excluded
2104 * In case A, we can exit as soon as we've found an untracked
2105 * file but otherwise have to walk all files. In case B, though,
2106 * we can stop at the first file we find under the directory.
2107 */
2108 stop_early = check_only && excluded;
2109
2110 /*
2111 * If /every/ file within an untracked directory is ignored, then
2112 * we want to treat the directory as ignored (for e.g. status
2113 * --porcelain), without listing the individual ignored files
2114 * underneath. To do so, we'll save the current ignored_nr, and
2115 * pop all the ones added after it if it turns out the entire
2116 * directory is ignored. Also, when DIR_SHOW_IGNORED_TOO and
2117 * !DIR_KEEP_UNTRACKED_CONTENTS then we don't want to show
2118 * untracked paths so will need to pop all those off the last
2119 * after we traverse.
2120 */
2121 old_ignored_nr = dir->ignored_nr;
2122 old_untracked_nr = dir->nr;
2123
2124 /* Actually recurse into dirname now, we'll fixup the state later. */
2125 untracked = lookup_untracked(dir->untracked, untracked,
2126 dirname + baselen, len - baselen);
2127 state = read_directory_recursive(dir, istate, dirname, len, untracked,
2128 check_only, stop_early, pathspec);
2129
2130 /* There are a variety of reasons we may need to fixup the state... */
2131 if (state == path_excluded) {
2132 /* state == path_excluded implies all paths under
2133 * dirname were ignored...
2134 *
2135 * if running e.g. `git status --porcelain --ignored=matching`,
2136 * then we want to see the subpaths that are ignored.
2137 *
2138 * if running e.g. just `git status --porcelain`, then
2139 * we just want the directory itself to be listed as ignored
2140 * and not the individual paths underneath.
2141 */
2142 int want_ignored_subpaths =
2143 ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
2144 (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING));
2145
2146 if (want_ignored_subpaths) {
2147 /*
2148 * with --ignored=matching, we want the subpaths
2149 * INSTEAD of the directory itself.
2150 */
2151 state = path_none;
2152 } else {
2153 for (int i = old_ignored_nr; i < dir->ignored_nr; i++)
2154 FREE_AND_NULL(dir->ignored[i]);
2155 dir->ignored_nr = old_ignored_nr;
2156 }
2157 }
2158
2159 /*
2160 * We may need to ignore some of the untracked paths we found while
2161 * traversing subdirectories.
2162 */
2163 if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
2164 !(dir->flags & DIR_KEEP_UNTRACKED_CONTENTS)) {
2165 for (int i = old_untracked_nr; i < dir->nr; i++)
2166 FREE_AND_NULL(dir->entries[i]);
2167 dir->nr = old_untracked_nr;
2168 }
2169
2170 /*
2171 * If there is nothing under the current directory and we are not
2172 * hiding empty directories, then we need to report on the
2173 * untracked or ignored status of the directory itself.
2174 */
2175 if (state == path_none && !(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
2176 state = excluded ? path_excluded : path_untracked;
2177
2178 return state;
2179 }
2180
2181 /*
2182 * This is an inexact early pruning of any recursive directory
2183 * reading - if the path cannot possibly be in the pathspec,
2184 * return true, and we'll skip it early.
2185 */
2186 static int simplify_away(const char *path, int pathlen,
2187 const struct pathspec *pathspec)
2188 {
2189 int i;
2190
2191 if (!pathspec || !pathspec->nr)
2192 return 0;
2193
2194 GUARD_PATHSPEC(pathspec,
2195 PATHSPEC_FROMTOP |
2196 PATHSPEC_MAXDEPTH |
2197 PATHSPEC_LITERAL |
2198 PATHSPEC_GLOB |
2199 PATHSPEC_ICASE |
2200 PATHSPEC_EXCLUDE |
2201 PATHSPEC_ATTR);
2202
2203 for (i = 0; i < pathspec->nr; i++) {
2204 const struct pathspec_item *item = &pathspec->items[i];
2205 int len = item->nowildcard_len;
2206
2207 if (len > pathlen)
2208 len = pathlen;
2209 if (!ps_strncmp(item, item->match, path, len))
2210 return 0;
2211 }
2212
2213 return 1;
2214 }
2215
2216 /*
2217 * This function tells us whether an excluded path matches a
2218 * list of "interesting" pathspecs. That is, whether a path matched
2219 * by any of the pathspecs could possibly be ignored by excluding
2220 * the specified path. This can happen if:
2221 *
2222 * 1. the path is mentioned explicitly in the pathspec
2223 *
2224 * 2. the path is a directory prefix of some element in the
2225 * pathspec
2226 */
2227 static int exclude_matches_pathspec(const char *path, int pathlen,
2228 const struct pathspec *pathspec)
2229 {
2230 int i;
2231
2232 if (!pathspec || !pathspec->nr)
2233 return 0;
2234
2235 GUARD_PATHSPEC(pathspec,
2236 PATHSPEC_FROMTOP |
2237 PATHSPEC_MAXDEPTH |
2238 PATHSPEC_LITERAL |
2239 PATHSPEC_GLOB |
2240 PATHSPEC_ICASE |
2241 PATHSPEC_EXCLUDE |
2242 PATHSPEC_ATTR);
2243
2244 for (i = 0; i < pathspec->nr; i++) {
2245 const struct pathspec_item *item = &pathspec->items[i];
2246 int len = item->nowildcard_len;
2247
2248 if (len == pathlen &&
2249 !ps_strncmp(item, item->match, path, pathlen))
2250 return 1;
2251 if (len > pathlen &&
2252 item->match[pathlen] == '/' &&
2253 !ps_strncmp(item, item->match, path, pathlen))
2254 return 1;
2255 }
2256 return 0;
2257 }
2258
2259 static int get_index_dtype(struct index_state *istate,
2260 const char *path, int len)
2261 {
2262 int pos;
2263 const struct cache_entry *ce;
2264
2265 ce = index_file_exists(istate, path, len, 0);
2266 if (ce) {
2267 if (!ce_uptodate(ce))
2268 return DT_UNKNOWN;
2269 if (S_ISGITLINK(ce->ce_mode))
2270 return DT_DIR;
2271 /*
2272 * Nobody actually cares about the
2273 * difference between DT_LNK and DT_REG
2274 */
2275 return DT_REG;
2276 }
2277
2278 /* Try to look it up as a directory */
2279 pos = index_name_pos(istate, path, len);
2280 if (pos >= 0)
2281 return DT_UNKNOWN;
2282 pos = -pos-1;
2283 while (pos < istate->cache_nr) {
2284 ce = istate->cache[pos++];
2285 if (strncmp(ce->name, path, len))
2286 break;
2287 if (ce->name[len] > '/')
2288 break;
2289 if (ce->name[len] < '/')
2290 continue;
2291 if (!ce_uptodate(ce))
2292 break; /* continue? */
2293 return DT_DIR;
2294 }
2295 return DT_UNKNOWN;
2296 }
2297
2298 unsigned char get_dtype(struct dirent *e, struct strbuf *path,
2299 int follow_symlink)
2300 {
2301 struct stat st;
2302 unsigned char dtype = DTYPE(e);
2303 size_t base_path_len;
2304
2305 if (dtype != DT_UNKNOWN && !(follow_symlink && dtype == DT_LNK))
2306 return dtype;
2307
2308 /*
2309 * d_type unknown or unfollowed symlink, try to fall back on [l]stat
2310 * results. If [l]stat fails, explicitly set DT_UNKNOWN.
2311 */
2312 base_path_len = path->len;
2313 strbuf_addstr(path, e->d_name);
2314 if ((follow_symlink && stat(path->buf, &st)) ||
2315 (!follow_symlink && lstat(path->buf, &st)))
2316 goto cleanup;
2317
2318 /* determine d_type from st_mode */
2319 if (S_ISREG(st.st_mode))
2320 dtype = DT_REG;
2321 else if (S_ISDIR(st.st_mode))
2322 dtype = DT_DIR;
2323 else if (S_ISLNK(st.st_mode))
2324 dtype = DT_LNK;
2325
2326 cleanup:
2327 strbuf_setlen(path, base_path_len);
2328 return dtype;
2329 }
2330
2331 static int resolve_dtype(int dtype, struct index_state *istate,
2332 const char *path, int len)
2333 {
2334 struct stat st;
2335
2336 if (dtype != DT_UNKNOWN)
2337 return dtype;
2338 dtype = get_index_dtype(istate, path, len);
2339 if (dtype != DT_UNKNOWN)
2340 return dtype;
2341 if (lstat(path, &st))
2342 return dtype;
2343 if (S_ISREG(st.st_mode))
2344 return DT_REG;
2345 if (S_ISDIR(st.st_mode))
2346 return DT_DIR;
2347 if (S_ISLNK(st.st_mode))
2348 return DT_LNK;
2349 return dtype;
2350 }
2351
2352 static enum path_treatment treat_path_fast(struct dir_struct *dir,
2353 struct cached_dir *cdir,
2354 struct index_state *istate,
2355 struct strbuf *path,
2356 int baselen,
2357 const struct pathspec *pathspec)
2358 {
2359 /*
2360 * WARNING: From this function, you can return path_recurse or you
2361 * can call read_directory_recursive() (or neither), but
2362 * you CAN'T DO BOTH.
2363 */
2364 strbuf_setlen(path, baselen);
2365 if (!cdir->ucd) {
2366 strbuf_addstr(path, cdir->file);
2367 return path_untracked;
2368 }
2369 strbuf_addstr(path, cdir->ucd->name);
2370 /* treat_one_path() does this before it calls treat_directory() */
2371 strbuf_complete(path, '/');
2372 if (cdir->ucd->check_only)
2373 /*
2374 * check_only is set as a result of treat_directory() getting
2375 * to its bottom. Verify again the same set of directories
2376 * with check_only set.
2377 */
2378 return read_directory_recursive(dir, istate, path->buf, path->len,
2379 cdir->ucd, 1, 0, pathspec);
2380 /*
2381 * We get path_recurse in the first run when
2382 * directory_exists_in_index() returns index_nonexistent. We
2383 * are sure that new changes in the index does not impact the
2384 * outcome. Return now.
2385 */
2386 return path_recurse;
2387 }
2388
2389 static enum path_treatment treat_path(struct dir_struct *dir,
2390 struct untracked_cache_dir *untracked,
2391 struct cached_dir *cdir,
2392 struct index_state *istate,
2393 struct strbuf *path,
2394 int baselen,
2395 const struct pathspec *pathspec)
2396 {
2397 int has_path_in_index, dtype, excluded;
2398
2399 if (!cdir->d_name)
2400 return treat_path_fast(dir, cdir, istate, path,
2401 baselen, pathspec);
2402 if (is_dot_or_dotdot(cdir->d_name) || !fspathcmp(cdir->d_name, ".git"))
2403 return path_none;
2404 strbuf_setlen(path, baselen);
2405 strbuf_addstr(path, cdir->d_name);
2406 if (simplify_away(path->buf, path->len, pathspec))
2407 return path_none;
2408
2409 dtype = resolve_dtype(cdir->d_type, istate, path->buf, path->len);
2410
2411 /* Always exclude indexed files */
2412 has_path_in_index = !!index_file_exists(istate, path->buf, path->len,
2413 ignore_case);
2414 if (dtype != DT_DIR && has_path_in_index)
2415 return path_none;
2416
2417 /*
2418 * When we are looking at a directory P in the working tree,
2419 * there are three cases:
2420 *
2421 * (1) P exists in the index. Everything inside the directory P in
2422 * the working tree needs to go when P is checked out from the
2423 * index.
2424 *
2425 * (2) P does not exist in the index, but there is P/Q in the index.
2426 * We know P will stay a directory when we check out the contents
2427 * of the index, but we do not know yet if there is a directory
2428 * P/Q in the working tree to be killed, so we need to recurse.
2429 *
2430 * (3) P does not exist in the index, and there is no P/Q in the index
2431 * to require P to be a directory, either. Only in this case, we
2432 * know that everything inside P will not be killed without
2433 * recursing.
2434 */
2435 if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
2436 (dtype == DT_DIR) &&
2437 !has_path_in_index &&
2438 (directory_exists_in_index(istate, path->buf, path->len) == index_nonexistent))
2439 return path_none;
2440
2441 excluded = is_excluded(dir, istate, path->buf, &dtype);
2442
2443 /*
2444 * Excluded? If we don't explicitly want to show
2445 * ignored files, ignore it
2446 */
2447 if (excluded && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
2448 return path_excluded;
2449
2450 switch (dtype) {
2451 default:
2452 return path_none;
2453 case DT_DIR:
2454 /*
2455 * WARNING: Do not ignore/amend the return value from
2456 * treat_directory(), and especially do not change it to return
2457 * path_recurse as that can cause exponential slowdown.
2458 * Instead, modify treat_directory() to return the right value.
2459 */
2460 strbuf_addch(path, '/');
2461 return treat_directory(dir, istate, untracked,
2462 path->buf, path->len,
2463 baselen, excluded, pathspec);
2464 case DT_REG:
2465 case DT_LNK:
2466 if (pathspec &&
2467 !match_pathspec(istate, pathspec, path->buf, path->len,
2468 0 /* prefix */, NULL /* seen */,
2469 0 /* is_dir */))
2470 return path_none;
2471 if (excluded)
2472 return path_excluded;
2473 return path_untracked;
2474 }
2475 }
2476
2477 static void add_untracked(struct untracked_cache_dir *dir, const char *name)
2478 {
2479 if (!dir)
2480 return;
2481 ALLOC_GROW(dir->untracked, dir->untracked_nr + 1,
2482 dir->untracked_alloc);
2483 dir->untracked[dir->untracked_nr++] = xstrdup(name);
2484 }
2485
2486 static int valid_cached_dir(struct dir_struct *dir,
2487 struct untracked_cache_dir *untracked,
2488 struct index_state *istate,
2489 struct strbuf *path,
2490 int check_only)
2491 {
2492 struct stat st;
2493
2494 if (!untracked)
2495 return 0;
2496
2497 /*
2498 * With fsmonitor, we can trust the untracked cache's valid field.
2499 */
2500 refresh_fsmonitor(istate);
2501 if (!(dir->untracked->use_fsmonitor && untracked->valid)) {
2502 if (lstat(path->len ? path->buf : ".", &st)) {
2503 memset(&untracked->stat_data, 0, sizeof(untracked->stat_data));
2504 return 0;
2505 }
2506 if (!untracked->valid ||
2507 match_stat_data_racy(istate, &untracked->stat_data, &st)) {
2508 fill_stat_data(&untracked->stat_data, &st);
2509 return 0;
2510 }
2511 }
2512
2513 if (untracked->check_only != !!check_only)
2514 return 0;
2515
2516 /*
2517 * prep_exclude will be called eventually on this directory,
2518 * but it's called much later in last_matching_pattern(). We
2519 * need it now to determine the validity of the cache for this
2520 * path. The next calls will be nearly no-op, the way
2521 * prep_exclude() is designed.
2522 */
2523 if (path->len && path->buf[path->len - 1] != '/') {
2524 strbuf_addch(path, '/');
2525 prep_exclude(dir, istate, path->buf, path->len);
2526 strbuf_setlen(path, path->len - 1);
2527 } else
2528 prep_exclude(dir, istate, path->buf, path->len);
2529
2530 /* hopefully prep_exclude() haven't invalidated this entry... */
2531 return untracked->valid;
2532 }
2533
2534 static int open_cached_dir(struct cached_dir *cdir,
2535 struct dir_struct *dir,
2536 struct untracked_cache_dir *untracked,
2537 struct index_state *istate,
2538 struct strbuf *path,
2539 int check_only)
2540 {
2541 const char *c_path;
2542
2543 memset(cdir, 0, sizeof(*cdir));
2544 cdir->untracked = untracked;
2545 if (valid_cached_dir(dir, untracked, istate, path, check_only))
2546 return 0;
2547 c_path = path->len ? path->buf : ".";
2548 cdir->fdir = opendir(c_path);
2549 if (!cdir->fdir)
2550 warning_errno(_("could not open directory '%s'"), c_path);
2551 if (dir->untracked) {
2552 invalidate_directory(dir->untracked, untracked);
2553 dir->untracked->dir_opened++;
2554 }
2555 if (!cdir->fdir)
2556 return -1;
2557 return 0;
2558 }
2559
2560 static int read_cached_dir(struct cached_dir *cdir)
2561 {
2562 struct dirent *de;
2563
2564 if (cdir->fdir) {
2565 de = readdir_skip_dot_and_dotdot(cdir->fdir);
2566 if (!de) {
2567 cdir->d_name = NULL;
2568 cdir->d_type = DT_UNKNOWN;
2569 return -1;
2570 }
2571 cdir->d_name = de->d_name;
2572 cdir->d_type = DTYPE(de);
2573 return 0;
2574 }
2575 while (cdir->nr_dirs < cdir->untracked->dirs_nr) {
2576 struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];
2577 if (!d->recurse) {
2578 cdir->nr_dirs++;
2579 continue;
2580 }
2581 cdir->ucd = d;
2582 cdir->nr_dirs++;
2583 return 0;
2584 }
2585 cdir->ucd = NULL;
2586 if (cdir->nr_files < cdir->untracked->untracked_nr) {
2587 struct untracked_cache_dir *d = cdir->untracked;
2588 cdir->file = d->untracked[cdir->nr_files++];
2589 return 0;
2590 }
2591 return -1;
2592 }
2593
2594 static void close_cached_dir(struct cached_dir *cdir)
2595 {
2596 if (cdir->fdir)
2597 closedir(cdir->fdir);
2598 /*
2599 * We have gone through this directory and found no untracked
2600 * entries. Mark it valid.
2601 */
2602 if (cdir->untracked) {
2603 cdir->untracked->valid = 1;
2604 cdir->untracked->recurse = 1;
2605 }
2606 }
2607
2608 static void add_path_to_appropriate_result_list(struct dir_struct *dir,
2609 struct untracked_cache_dir *untracked,
2610 struct cached_dir *cdir,
2611 struct index_state *istate,
2612 struct strbuf *path,
2613 int baselen,
2614 const struct pathspec *pathspec,
2615 enum path_treatment state)
2616 {
2617 /* add the path to the appropriate result list */
2618 switch (state) {
2619 case path_excluded:
2620 if (dir->flags & DIR_SHOW_IGNORED)
2621 dir_add_name(dir, istate, path->buf, path->len);
2622 else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
2623 ((dir->flags & DIR_COLLECT_IGNORED) &&
2624 exclude_matches_pathspec(path->buf, path->len,
2625 pathspec)))
2626 dir_add_ignored(dir, istate, path->buf, path->len);
2627 break;
2628
2629 case path_untracked:
2630 if (dir->flags & DIR_SHOW_IGNORED)
2631 break;
2632 dir_add_name(dir, istate, path->buf, path->len);
2633 if (cdir->fdir)
2634 add_untracked(untracked, path->buf + baselen);
2635 break;
2636
2637 default:
2638 break;
2639 }
2640 }
2641
2642 /*
2643 * Read a directory tree. We currently ignore anything but
2644 * directories, regular files and symlinks. That's because git
2645 * doesn't handle them at all yet. Maybe that will change some
2646 * day.
2647 *
2648 * Also, we ignore the name ".git" (even if it is not a directory).
2649 * That likely will not change.
2650 *
2651 * If 'stop_at_first_file' is specified, 'path_excluded' is returned
2652 * to signal that a file was found. This is the least significant value that
2653 * indicates that a file was encountered that does not depend on the order of
2654 * whether an untracked or excluded path was encountered first.
2655 *
2656 * Returns the most significant path_treatment value encountered in the scan.
2657 * If 'stop_at_first_file' is specified, `path_excluded` is the most
2658 * significant path_treatment value that will be returned.
2659 */
2660
2661 static enum path_treatment read_directory_recursive(struct dir_struct *dir,
2662 struct index_state *istate, const char *base, int baselen,
2663 struct untracked_cache_dir *untracked, int check_only,
2664 int stop_at_first_file, const struct pathspec *pathspec)
2665 {
2666 /*
2667 * WARNING: Do NOT recurse unless path_recurse is returned from
2668 * treat_path(). Recursing on any other return value
2669 * can result in exponential slowdown.
2670 */
2671 struct cached_dir cdir;
2672 enum path_treatment state, subdir_state, dir_state = path_none;
2673 struct strbuf path = STRBUF_INIT;
2674
2675 strbuf_add(&path, base, baselen);
2676
2677 if (open_cached_dir(&cdir, dir, untracked, istate, &path, check_only))
2678 goto out;
2679 dir->internal.visited_directories++;
2680
2681 if (untracked)
2682 untracked->check_only = !!check_only;
2683
2684 while (!read_cached_dir(&cdir)) {
2685 /* check how the file or directory should be treated */
2686 state = treat_path(dir, untracked, &cdir, istate, &path,
2687 baselen, pathspec);
2688 dir->internal.visited_paths++;
2689
2690 if (state > dir_state)
2691 dir_state = state;
2692
2693 /* recurse into subdir if instructed by treat_path */
2694 if (state == path_recurse) {
2695 struct untracked_cache_dir *ud;
2696 ud = lookup_untracked(dir->untracked,
2697 untracked,
2698 path.buf + baselen,
2699 path.len - baselen);
2700 subdir_state =
2701 read_directory_recursive(dir, istate, path.buf,
2702 path.len, ud,
2703 check_only, stop_at_first_file, pathspec);
2704 if (subdir_state > dir_state)
2705 dir_state = subdir_state;
2706
2707 if (pathspec &&
2708 !match_pathspec(istate, pathspec, path.buf, path.len,
2709 0 /* prefix */, NULL,
2710 0 /* do NOT special case dirs */))
2711 state = path_none;
2712 }
2713
2714 if (check_only) {
2715 if (stop_at_first_file) {
2716 /*
2717 * If stopping at first file, then
2718 * signal that a file was found by
2719 * returning `path_excluded`. This is
2720 * to return a consistent value
2721 * regardless of whether an ignored or
2722 * excluded file happened to be
2723 * encountered 1st.
2724 *
2725 * In current usage, the
2726 * `stop_at_first_file` is passed when
2727 * an ancestor directory has matched
2728 * an exclude pattern, so any found
2729 * files will be excluded.
2730 */
2731 if (dir_state >= path_excluded) {
2732 dir_state = path_excluded;
2733 break;
2734 }
2735 }
2736
2737 /* abort early if maximum state has been reached */
2738 if (dir_state == path_untracked) {
2739 if (cdir.fdir)
2740 add_untracked(untracked, path.buf + baselen);
2741 break;
2742 }
2743 /* skip the add_path_to_appropriate_result_list() */
2744 continue;
2745 }
2746
2747 add_path_to_appropriate_result_list(dir, untracked, &cdir,
2748 istate, &path, baselen,
2749 pathspec, state);
2750 }
2751 close_cached_dir(&cdir);
2752 out:
2753 strbuf_release(&path);
2754
2755 return dir_state;
2756 }
2757
2758 int cmp_dir_entry(const void *p1, const void *p2)
2759 {
2760 const struct dir_entry *e1 = *(const struct dir_entry **)p1;
2761 const struct dir_entry *e2 = *(const struct dir_entry **)p2;
2762
2763 return name_compare(e1->name, e1->len, e2->name, e2->len);
2764 }
2765
2766 /* check if *out lexically strictly contains *in */
2767 int check_dir_entry_contains(const struct dir_entry *out, const struct dir_entry *in)
2768 {
2769 return (out->len < in->len) &&
2770 (out->name[out->len - 1] == '/') &&
2771 !memcmp(out->name, in->name, out->len);
2772 }
2773
2774 static int treat_leading_path(struct dir_struct *dir,
2775 struct index_state *istate,
2776 const char *path, int len,
2777 const struct pathspec *pathspec)
2778 {
2779 struct strbuf sb = STRBUF_INIT;
2780 struct strbuf subdir = STRBUF_INIT;
2781 int prevlen, baselen;
2782 const char *cp;
2783 struct cached_dir cdir;
2784 enum path_treatment state = path_none;
2785
2786 /*
2787 * For each directory component of path, we are going to check whether
2788 * that path is relevant given the pathspec. For example, if path is
2789 * foo/bar/baz/
2790 * then we will ask treat_path() whether we should go into foo, then
2791 * whether we should go into bar, then whether baz is relevant.
2792 * Checking each is important because e.g. if path is
2793 * .git/info/
2794 * then we need to check .git to know we shouldn't traverse it.
2795 * If the return from treat_path() is:
2796 * * path_none, for any path, we return false.
2797 * * path_recurse, for all path components, we return true
2798 * * <anything else> for some intermediate component, we make sure
2799 * to add that path to the relevant list but return false
2800 * signifying that we shouldn't recurse into it.
2801 */
2802
2803 while (len && path[len - 1] == '/')
2804 len--;
2805 if (!len)
2806 return 1;
2807
2808 memset(&cdir, 0, sizeof(cdir));
2809 cdir.d_type = DT_DIR;
2810 baselen = 0;
2811 prevlen = 0;
2812 while (1) {
2813 prevlen = baselen + !!baselen;
2814 cp = path + prevlen;
2815 cp = memchr(cp, '/', path + len - cp);
2816 if (!cp)
2817 baselen = len;
2818 else
2819 baselen = cp - path;
2820 strbuf_reset(&sb);
2821 strbuf_add(&sb, path, baselen);
2822 if (!is_directory(sb.buf))
2823 break;
2824 strbuf_reset(&sb);
2825 strbuf_add(&sb, path, prevlen);
2826 strbuf_reset(&subdir);
2827 strbuf_add(&subdir, path+prevlen, baselen-prevlen);
2828 cdir.d_name = subdir.buf;
2829 state = treat_path(dir, NULL, &cdir, istate, &sb, prevlen, pathspec);
2830
2831 if (state != path_recurse)
2832 break; /* do not recurse into it */
2833 if (len <= baselen)
2834 break; /* finished checking */
2835 }
2836 add_path_to_appropriate_result_list(dir, NULL, &cdir, istate,
2837 &sb, baselen, pathspec,
2838 state);
2839
2840 strbuf_release(&subdir);
2841 strbuf_release(&sb);
2842 return state == path_recurse;
2843 }
2844
2845 static const char *get_ident_string(void)
2846 {
2847 static struct strbuf sb = STRBUF_INIT;
2848 struct utsname uts;
2849
2850 if (sb.len)
2851 return sb.buf;
2852 if (uname(&uts) < 0)
2853 die_errno(_("failed to get kernel name and information"));
2854 strbuf_addf(&sb, "Location %s, system %s", repo_get_work_tree(the_repository),
2855 uts.sysname);
2856 return sb.buf;
2857 }
2858
2859 static int ident_in_untracked(const struct untracked_cache *uc)
2860 {
2861 /*
2862 * Previous git versions may have saved many NUL separated
2863 * strings in the "ident" field, but it is insane to manage
2864 * many locations, so just take care of the first one.
2865 */
2866
2867 return !strcmp(uc->ident.buf, get_ident_string());
2868 }
2869
2870 static void set_untracked_ident(struct untracked_cache *uc)
2871 {
2872 strbuf_reset(&uc->ident);
2873 strbuf_addstr(&uc->ident, get_ident_string());
2874
2875 /*
2876 * This strbuf used to contain a list of NUL separated
2877 * strings, so save NUL too for backward compatibility.
2878 */
2879 strbuf_addch(&uc->ident, 0);
2880 }
2881
2882 static unsigned new_untracked_cache_flags(struct index_state *istate)
2883 {
2884 struct repository *repo = istate->repo;
2885 const char *val;
2886
2887 /*
2888 * This logic is coordinated with the setting of these flags in
2889 * wt-status.c#wt_status_collect_untracked(), and the evaluation
2890 * of the config setting in commit.c#git_status_config()
2891 */
2892 if (!repo_config_get_string_tmp(repo, "status.showuntrackedfiles", &val) &&
2893 !strcmp(val, "all"))
2894 return 0;
2895
2896 /*
2897 * The default, if "all" is not set, is "normal" - leading us here.
2898 * If the value is "none" then it really doesn't matter.
2899 */
2900 return DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;
2901 }
2902
2903 static void new_untracked_cache(struct index_state *istate, int flags)
2904 {
2905 struct untracked_cache *uc = xcalloc(1, sizeof(*uc));
2906 strbuf_init(&uc->ident, 100);
2907 uc->exclude_per_dir = ".gitignore";
2908 uc->dir_flags = flags >= 0 ? flags : new_untracked_cache_flags(istate);
2909 set_untracked_ident(uc);
2910 istate->untracked = uc;
2911 istate->cache_changed |= UNTRACKED_CHANGED;
2912 }
2913
2914 void add_untracked_cache(struct index_state *istate)
2915 {
2916 if (!istate->untracked) {
2917 new_untracked_cache(istate, -1);
2918 } else {
2919 if (!ident_in_untracked(istate->untracked)) {
2920 free_untracked_cache(istate->untracked);
2921 new_untracked_cache(istate, -1);
2922 }
2923 }
2924 }
2925
2926 void remove_untracked_cache(struct index_state *istate)
2927 {
2928 if (istate->untracked) {
2929 free_untracked_cache(istate->untracked);
2930 istate->untracked = NULL;
2931 istate->cache_changed |= UNTRACKED_CHANGED;
2932 }
2933 }
2934
2935 static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,
2936 int base_len,
2937 const struct pathspec *pathspec,
2938 struct index_state *istate)
2939 {
2940 struct untracked_cache_dir *root;
2941 static int untracked_cache_disabled = -1;
2942
2943 if (!dir->untracked)
2944 return NULL;
2945 if (untracked_cache_disabled < 0)
2946 untracked_cache_disabled = git_env_bool("GIT_DISABLE_UNTRACKED_CACHE", 0);
2947 if (untracked_cache_disabled)
2948 return NULL;
2949
2950 /*
2951 * We only support $GIT_DIR/info/exclude and core.excludesfile
2952 * as the global ignore rule files. Any other additions
2953 * (e.g. from command line) invalidate the cache. This
2954 * condition also catches running setup_standard_excludes()
2955 * before setting dir->untracked!
2956 */
2957 if (dir->internal.unmanaged_exclude_files)
2958 return NULL;
2959
2960 /*
2961 * Optimize for the main use case only: whole-tree git
2962 * status. More work involved in treat_leading_path() if we
2963 * use cache on just a subset of the worktree. pathspec
2964 * support could make the matter even worse.
2965 */
2966 if (base_len || (pathspec && pathspec->nr))
2967 return NULL;
2968
2969 /* We don't support collecting ignore files */
2970 if (dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |
2971 DIR_COLLECT_IGNORED))
2972 return NULL;
2973
2974 /*
2975 * If we use .gitignore in the cache and now you change it to
2976 * .gitexclude, everything will go wrong.
2977 */
2978 if (dir->exclude_per_dir != dir->untracked->exclude_per_dir &&
2979 strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))
2980 return NULL;
2981
2982 /*
2983 * EXC_CMDL is not considered in the cache. If people set it,
2984 * skip the cache.
2985 */
2986 if (dir->internal.exclude_list_group[EXC_CMDL].nr)
2987 return NULL;
2988
2989 if (!ident_in_untracked(dir->untracked)) {
2990 warning(_("untracked cache is disabled on this system or location"));
2991 return NULL;
2992 }
2993
2994 /*
2995 * If the untracked structure we received does not have the same flags
2996 * as requested in this run, we're going to need to either discard the
2997 * existing structure (and potentially later recreate), or bypass the
2998 * untracked cache mechanism for this run.
2999 */
3000 if (dir->flags != dir->untracked->dir_flags) {
3001 /*
3002 * If the untracked structure we received does not have the same flags
3003 * as configured, then we need to reset / create a new "untracked"
3004 * structure to match the new config.
3005 *
3006 * Keeping the saved and used untracked cache consistent with the
3007 * configuration provides an opportunity for frequent users of
3008 * "git status -uall" to leverage the untracked cache by aligning their
3009 * configuration - setting "status.showuntrackedfiles" to "all" or
3010 * "normal" as appropriate.
3011 *
3012 * Previously using -uall (or setting "status.showuntrackedfiles" to
3013 * "all") was incompatible with untracked cache and *consistently*
3014 * caused surprisingly bad performance (with fscache and fsmonitor
3015 * enabled) on Windows.
3016 *
3017 * IMPROVEMENT OPPORTUNITY: If we reworked the untracked cache storage
3018 * to not be as bound up with the desired output in a given run,
3019 * and instead iterated through and stored enough information to
3020 * correctly serve both "modes", then users could get peak performance
3021 * with or without '-uall' regardless of their
3022 * "status.showuntrackedfiles" config.
3023 */
3024 if (dir->untracked->dir_flags != new_untracked_cache_flags(istate)) {
3025 free_untracked_cache(istate->untracked);
3026 new_untracked_cache(istate, dir->flags);
3027 dir->untracked = istate->untracked;
3028 }
3029 else {
3030 /*
3031 * Current untracked cache data is consistent with config, but not
3032 * usable in this request/run; just bypass untracked cache.
3033 */
3034 return NULL;
3035 }
3036 }
3037
3038 if (!dir->untracked->root) {
3039 /* Untracked cache existed but is not initialized; fix that */
3040 FLEX_ALLOC_STR(dir->untracked->root, name, "");
3041 istate->cache_changed |= UNTRACKED_CHANGED;
3042 }
3043
3044 /* Validate $GIT_DIR/info/exclude and core.excludesfile */
3045 root = dir->untracked->root;
3046 if (!oideq(&dir->internal.ss_info_exclude.oid,
3047 &dir->untracked->ss_info_exclude.oid)) {
3048 invalidate_gitignore(dir->untracked, root);
3049 dir->untracked->ss_info_exclude = dir->internal.ss_info_exclude;
3050 }
3051 if (!oideq(&dir->internal.ss_excludes_file.oid,
3052 &dir->untracked->ss_excludes_file.oid)) {
3053 invalidate_gitignore(dir->untracked, root);
3054 dir->untracked->ss_excludes_file = dir->internal.ss_excludes_file;
3055 }
3056
3057 /* Make sure this directory is not dropped out at saving phase */
3058 root->recurse = 1;
3059 return root;
3060 }
3061
3062 static void emit_traversal_statistics(struct dir_struct *dir,
3063 struct repository *repo,
3064 const char *path,
3065 int path_len)
3066 {
3067 if (!trace2_is_enabled())
3068 return;
3069
3070 if (!path_len) {
3071 trace2_data_string("read_directory", repo, "path", "");
3072 } else {
3073 struct strbuf tmp = STRBUF_INIT;
3074 strbuf_add(&tmp, path, path_len);
3075 trace2_data_string("read_directory", repo, "path", tmp.buf);
3076 strbuf_release(&tmp);
3077 }
3078
3079 trace2_data_intmax("read_directory", repo,
3080 "directories-visited", dir->internal.visited_directories);
3081 trace2_data_intmax("read_directory", repo,
3082 "paths-visited", dir->internal.visited_paths);
3083
3084 if (!dir->untracked)
3085 return;
3086 trace2_data_intmax("read_directory", repo,
3087 "node-creation", dir->untracked->dir_created);
3088 trace2_data_intmax("read_directory", repo,
3089 "gitignore-invalidation",
3090 dir->untracked->gitignore_invalidated);
3091 trace2_data_intmax("read_directory", repo,
3092 "directory-invalidation",
3093 dir->untracked->dir_invalidated);
3094 trace2_data_intmax("read_directory", repo,
3095 "opendir", dir->untracked->dir_opened);
3096 }
3097
3098 int read_directory(struct dir_struct *dir, struct index_state *istate,
3099 const char *path, int len, const struct pathspec *pathspec)
3100 {
3101 struct untracked_cache_dir *untracked;
3102
3103 trace2_region_enter("dir", "read_directory", istate->repo);
3104 dir->internal.visited_paths = 0;
3105 dir->internal.visited_directories = 0;
3106
3107 if (has_symlink_leading_path(path, len)) {
3108 trace2_region_leave("dir", "read_directory", istate->repo);
3109 return dir->nr;
3110 }
3111
3112 untracked = validate_untracked_cache(dir, len, pathspec, istate);
3113 if (!untracked)
3114 /*
3115 * make sure untracked cache code path is disabled,
3116 * e.g. prep_exclude()
3117 */
3118 dir->untracked = NULL;
3119 if (!len || treat_leading_path(dir, istate, path, len, pathspec))
3120 read_directory_recursive(dir, istate, path, len, untracked, 0, 0, pathspec);
3121 QSORT(dir->entries, dir->nr, cmp_dir_entry);
3122 QSORT(dir->ignored, dir->ignored_nr, cmp_dir_entry);
3123
3124 emit_traversal_statistics(dir, istate->repo, path, len);
3125
3126 trace2_region_leave("dir", "read_directory", istate->repo);
3127 if (dir->untracked) {
3128 static int force_untracked_cache = -1;
3129
3130 if (force_untracked_cache < 0)
3131 force_untracked_cache =
3132 git_env_bool("GIT_FORCE_UNTRACKED_CACHE", -1);
3133 if (force_untracked_cache < 0)
3134 force_untracked_cache = (istate->repo->settings.core_untracked_cache == UNTRACKED_CACHE_WRITE);
3135 if (force_untracked_cache &&
3136 dir->untracked == istate->untracked &&
3137 (dir->untracked->dir_opened ||
3138 dir->untracked->gitignore_invalidated ||
3139 dir->untracked->dir_invalidated))
3140 istate->cache_changed |= UNTRACKED_CHANGED;
3141 if (dir->untracked != istate->untracked) {
3142 FREE_AND_NULL(dir->untracked);
3143 }
3144 }
3145
3146 return dir->nr;
3147 }
3148
3149 int file_exists(const char *f)
3150 {
3151 struct stat sb;
3152 return lstat(f, &sb) == 0;
3153 }
3154
3155 int repo_file_exists(struct repository *repo, const char *path)
3156 {
3157 if (repo != the_repository)
3158 BUG("do not know how to check file existence in arbitrary repo");
3159
3160 return file_exists(path);
3161 }
3162
3163 static int cmp_icase(char a, char b)
3164 {
3165 if (a == b)
3166 return 0;
3167 if (ignore_case)
3168 return toupper(a) - toupper(b);
3169 return a - b;
3170 }
3171
3172 /*
3173 * Given two normalized paths (a trailing slash is ok), if subdir is
3174 * outside dir, return -1. Otherwise return the offset in subdir that
3175 * can be used as relative path to dir.
3176 */
3177 int dir_inside_of(const char *subdir, const char *dir)
3178 {
3179 int offset = 0;
3180
3181 assert(dir && subdir && *dir && *subdir);
3182
3183 while (*dir && *subdir && !cmp_icase(*dir, *subdir)) {
3184 dir++;
3185 subdir++;
3186 offset++;
3187 }
3188
3189 /* hel[p]/me vs hel[l]/yeah */
3190 if (*dir && *subdir)
3191 return -1;
3192
3193 if (!*subdir)
3194 return !*dir ? offset : -1; /* same dir */
3195
3196 /* foo/[b]ar vs foo/[] */
3197 if (is_dir_sep(dir[-1]))
3198 return is_dir_sep(subdir[-1]) ? offset : -1;
3199
3200 /* foo[/]bar vs foo[] */
3201 return is_dir_sep(*subdir) ? offset + 1 : -1;
3202 }
3203
3204 int is_inside_dir(const char *dir)
3205 {
3206 char *cwd;
3207 int rc;
3208
3209 if (!dir)
3210 return 0;
3211
3212 cwd = xgetcwd();
3213 rc = (dir_inside_of(cwd, dir) >= 0);
3214 free(cwd);
3215 return rc;
3216 }
3217
3218 int is_empty_dir(const char *path)
3219 {
3220 DIR *dir = opendir(path);
3221 struct dirent *e;
3222 int ret = 1;
3223
3224 if (!dir)
3225 return 0;
3226
3227 e = readdir_skip_dot_and_dotdot(dir);
3228 if (e)
3229 ret = 0;
3230
3231 closedir(dir);
3232 return ret;
3233 }
3234
3235 char *git_url_basename(const char *repo, int is_bundle, int is_bare)
3236 {
3237 const char *end = repo + strlen(repo), *start, *ptr;
3238 size_t len;
3239 char *dir;
3240
3241 /*
3242 * Skip scheme.
3243 */
3244 start = strstr(repo, "://");
3245 if (!start)
3246 start = repo;
3247 else
3248 start += 3;
3249
3250 /*
3251 * Skip authentication data. The stripping does happen
3252 * greedily, such that we strip up to the last '@' inside
3253 * the host part.
3254 */
3255 for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
3256 if (*ptr == '@')
3257 start = ptr + 1;
3258 }
3259
3260 /*
3261 * Strip trailing spaces, slashes and /.git
3262 */
3263 while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
3264 end--;
3265 if (end - start > 5 && is_dir_sep(end[-5]) &&
3266 !strncmp(end - 4, ".git", 4)) {
3267 end -= 5;
3268 while (start < end && is_dir_sep(end[-1]))
3269 end--;
3270 }
3271
3272 /*
3273 * It should not be possible to overflow `ptrdiff_t` by passing in an
3274 * insanely long URL, but GCC does not know that and will complain
3275 * without this check.
3276 */
3277 if (end - start < 0)
3278 die(_("No directory name could be guessed.\n"
3279 "Please specify a directory on the command line"));
3280
3281 /*
3282 * Strip trailing port number if we've got only a
3283 * hostname (that is, there is no dir separator but a
3284 * colon). This check is required such that we do not
3285 * strip URI's like '/foo/bar:2222.git', which should
3286 * result in a dir '2222' being guessed due to backwards
3287 * compatibility.
3288 */
3289 if (memchr(start, '/', end - start) == NULL
3290 && memchr(start, ':', end - start) != NULL) {
3291 ptr = end;
3292 while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
3293 ptr--;
3294 if (start < ptr && ptr[-1] == ':')
3295 end = ptr - 1;
3296 }
3297
3298 /*
3299 * Find last component. To remain backwards compatible we
3300 * also regard colons as path separators, such that
3301 * cloning a repository 'foo:bar.git' would result in a
3302 * directory 'bar' being guessed.
3303 */
3304 ptr = end;
3305 while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
3306 ptr--;
3307 start = ptr;
3308
3309 /*
3310 * Strip .{bundle,git}.
3311 */
3312 len = end - start;
3313 strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
3314
3315 if (!len || (len == 1 && *start == '/'))
3316 die(_("No directory name could be guessed.\n"
3317 "Please specify a directory on the command line"));
3318
3319 if (is_bare)
3320 dir = xstrfmt("%.*s.git", (int)len, start);
3321 else
3322 dir = xstrndup(start, len);
3323 /*
3324 * Replace sequences of 'control' characters and whitespace
3325 * with one ascii space, remove leading and trailing spaces.
3326 */
3327 if (*dir) {
3328 char *out = dir;
3329 int prev_space = 1 /* strip leading whitespace */;
3330 for (end = dir; *end; ++end) {
3331 char ch = *end;
3332 if ((unsigned char)ch < '\x20')
3333 ch = '\x20';
3334 if (isspace(ch)) {
3335 if (prev_space)
3336 continue;
3337 prev_space = 1;
3338 } else
3339 prev_space = 0;
3340 *out++ = ch;
3341 }
3342 *out = '\0';
3343 if (out > dir && prev_space)
3344 out[-1] = '\0';
3345 }
3346 return dir;
3347 }
3348
3349 void strip_dir_trailing_slashes(char *dir)
3350 {
3351 char *end = dir + strlen(dir);
3352
3353 while (dir < end - 1 && is_dir_sep(end[-1]))
3354 end--;
3355 *end = '\0';
3356 }
3357
3358 static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
3359 {
3360 DIR *dir;
3361 struct dirent *e;
3362 int ret = 0, original_len = path->len, len, kept_down = 0;
3363 int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
3364 int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
3365 int purge_original_cwd = (flag & REMOVE_DIR_PURGE_ORIGINAL_CWD);
3366 struct object_id submodule_head;
3367
3368 if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
3369 !repo_resolve_gitlink_ref(the_repository, path->buf,
3370 "HEAD", &submodule_head)) {
3371 /* Do not descend and nuke a nested git work tree. */
3372 if (kept_up)
3373 *kept_up = 1;
3374 return 0;
3375 }
3376
3377 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
3378 dir = opendir(path->buf);
3379 if (!dir) {
3380 if (errno == ENOENT)
3381 return keep_toplevel ? -1 : 0;
3382 else if (errno == EACCES && !keep_toplevel)
3383 /*
3384 * An empty dir could be removable even if it
3385 * is unreadable:
3386 */
3387 return rmdir(path->buf);
3388 else
3389 return -1;
3390 }
3391 strbuf_complete(path, '/');
3392
3393 len = path->len;
3394 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
3395 struct stat st;
3396
3397 strbuf_setlen(path, len);
3398 strbuf_addstr(path, e->d_name);
3399 if (lstat(path->buf, &st)) {
3400 if (errno == ENOENT)
3401 /*
3402 * file disappeared, which is what we
3403 * wanted anyway
3404 */
3405 continue;
3406 /* fall through */
3407 } else if (S_ISDIR(st.st_mode)) {
3408 if (!remove_dir_recurse(path, flag, &kept_down))
3409 continue; /* happy */
3410 } else if (!only_empty &&
3411 (!unlink(path->buf) || errno == ENOENT)) {
3412 continue; /* happy, too */
3413 }
3414
3415 /* path too long, stat fails, or non-directory still exists */
3416 ret = -1;
3417 break;
3418 }
3419 closedir(dir);
3420
3421 strbuf_setlen(path, original_len);
3422 if (!ret && !keep_toplevel && !kept_down) {
3423 if (!purge_original_cwd &&
3424 startup_info->original_cwd &&
3425 !strcmp(startup_info->original_cwd, path->buf))
3426 ret = -1; /* Do not remove current working directory */
3427 else
3428 ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1;
3429 } else if (kept_up)
3430 /*
3431 * report the uplevel that it is not an error that we
3432 * did not rmdir() our directory.
3433 */
3434 *kept_up = !ret;
3435 return ret;
3436 }
3437
3438 int remove_dir_recursively(struct strbuf *path, int flag)
3439 {
3440 return remove_dir_recurse(path, flag, NULL);
3441 }
3442
3443 static GIT_PATH_FUNC(git_path_info_exclude, "info/exclude")
3444
3445 void setup_standard_excludes(struct dir_struct *dir)
3446 {
3447 dir->exclude_per_dir = ".gitignore";
3448
3449 /* core.excludesfile defaulting to $XDG_CONFIG_HOME/git/ignore */
3450 if (!excludes_file)
3451 excludes_file = xdg_config_home("ignore");
3452 if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
3453 add_patterns_from_file_1(dir, excludes_file,
3454 dir->untracked ? &dir->internal.ss_excludes_file : NULL);
3455
3456 /* per repository user preference */
3457 if (startup_info->have_repository) {
3458 const char *path = git_path_info_exclude();
3459 if (!access_or_warn(path, R_OK, 0))
3460 add_patterns_from_file_1(dir, path,
3461 dir->untracked ? &dir->internal.ss_info_exclude : NULL);
3462 }
3463 }
3464
3465 char *get_sparse_checkout_filename(void)
3466 {
3467 return repo_git_path(the_repository, "info/sparse-checkout");
3468 }
3469
3470 int get_sparse_checkout_patterns(struct pattern_list *pl)
3471 {
3472 int res;
3473 char *sparse_filename = get_sparse_checkout_filename();
3474
3475 pl->use_cone_patterns = core_sparse_checkout_cone;
3476 res = add_patterns_from_file_to_list(sparse_filename, "", 0, pl, NULL, 0);
3477
3478 free(sparse_filename);
3479 return res;
3480 }
3481
3482 int remove_path(const char *name)
3483 {
3484 char *slash;
3485
3486 if (unlink(name) && !is_missing_file_error(errno))
3487 return -1;
3488
3489 slash = strrchr(name, '/');
3490 if (slash) {
3491 char *dirs = xstrdup(name);
3492 slash = dirs + (slash - name);
3493 do {
3494 *slash = '\0';
3495 if (startup_info->original_cwd &&
3496 !strcmp(startup_info->original_cwd, dirs))
3497 break;
3498 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
3499 free(dirs);
3500 }
3501 return 0;
3502 }
3503
3504 /*
3505 * Frees memory within dir which was allocated, and resets fields for further
3506 * use. Does not free dir itself.
3507 */
3508 void dir_clear(struct dir_struct *dir)
3509 {
3510 int i, j;
3511 struct exclude_list_group *group;
3512 struct pattern_list *pl;
3513 struct exclude_stack *stk;
3514 struct dir_struct new = DIR_INIT;
3515
3516 for (i = EXC_CMDL; i <= EXC_FILE; i++) {
3517 group = &dir->internal.exclude_list_group[i];
3518 for (j = 0; j < group->nr; j++) {
3519 pl = &group->pl[j];
3520 if (i == EXC_DIRS)
3521 free((char *)pl->src);
3522 clear_pattern_list(pl);
3523 }
3524 free(group->pl);
3525 }
3526
3527 for (i = 0; i < dir->ignored_nr; i++)
3528 free(dir->ignored[i]);
3529 for (i = 0; i < dir->nr; i++)
3530 free(dir->entries[i]);
3531 free(dir->ignored);
3532 free(dir->entries);
3533
3534 stk = dir->internal.exclude_stack;
3535 while (stk) {
3536 struct exclude_stack *prev = stk->prev;
3537 free(stk);
3538 stk = prev;
3539 }
3540 strbuf_release(&dir->internal.basebuf);
3541
3542 memcpy(dir, &new, sizeof(*dir));
3543 }
3544
3545 struct ondisk_untracked_cache {
3546 struct stat_data info_exclude_stat;
3547 struct stat_data excludes_file_stat;
3548 uint32_t dir_flags;
3549 };
3550
3551 #define ouc_offset(x) offsetof(struct ondisk_untracked_cache, x)
3552
3553 struct write_data {
3554 int index; /* number of written untracked_cache_dir */
3555 struct ewah_bitmap *check_only; /* from untracked_cache_dir */
3556 struct ewah_bitmap *valid; /* from untracked_cache_dir */
3557 struct ewah_bitmap *sha1_valid; /* set if exclude_sha1 is not null */
3558 struct strbuf out;
3559 struct strbuf sb_stat;
3560 struct strbuf sb_sha1;
3561 };
3562
3563 static void stat_data_to_disk(struct stat_data *to, const struct stat_data *from)
3564 {
3565 to->sd_ctime.sec = htonl(from->sd_ctime.sec);
3566 to->sd_ctime.nsec = htonl(from->sd_ctime.nsec);
3567 to->sd_mtime.sec = htonl(from->sd_mtime.sec);
3568 to->sd_mtime.nsec = htonl(from->sd_mtime.nsec);
3569 to->sd_dev = htonl(from->sd_dev);
3570 to->sd_ino = htonl(from->sd_ino);
3571 to->sd_uid = htonl(from->sd_uid);
3572 to->sd_gid = htonl(from->sd_gid);
3573 to->sd_size = htonl(from->sd_size);
3574 }
3575
3576 static void write_one_dir(struct untracked_cache_dir *untracked,
3577 struct write_data *wd)
3578 {
3579 struct stat_data stat_data;
3580 struct strbuf *out = &wd->out;
3581 unsigned char intbuf[16];
3582 unsigned int intlen, value;
3583 int i = wd->index++;
3584
3585 /*
3586 * untracked_nr should be reset whenever valid is clear, but
3587 * for safety..
3588 */
3589 if (!untracked->valid) {
3590 for (size_t i = 0; i < untracked->untracked_nr; i++)
3591 free(untracked->untracked[i]);
3592 untracked->untracked_nr = 0;
3593 untracked->check_only = 0;
3594 }
3595
3596 if (untracked->check_only)
3597 ewah_set(wd->check_only, i);
3598 if (untracked->valid) {
3599 ewah_set(wd->valid, i);
3600 stat_data_to_disk(&stat_data, &untracked->stat_data);
3601 strbuf_add(&wd->sb_stat, &stat_data, sizeof(stat_data));
3602 }
3603 if (!is_null_oid(&untracked->exclude_oid)) {
3604 ewah_set(wd->sha1_valid, i);
3605 strbuf_add(&wd->sb_sha1, untracked->exclude_oid.hash,
3606 the_hash_algo->rawsz);
3607 }
3608
3609 intlen = encode_varint(untracked->untracked_nr, intbuf);
3610 strbuf_add(out, intbuf, intlen);
3611
3612 /* skip non-recurse directories */
3613 for (i = 0, value = 0; i < untracked->dirs_nr; i++)
3614 if (untracked->dirs[i]->recurse)
3615 value++;
3616 intlen = encode_varint(value, intbuf);
3617 strbuf_add(out, intbuf, intlen);
3618
3619 strbuf_add(out, untracked->name, strlen(untracked->name) + 1);
3620
3621 for (i = 0; i < untracked->untracked_nr; i++)
3622 strbuf_add(out, untracked->untracked[i],
3623 strlen(untracked->untracked[i]) + 1);
3624
3625 for (i = 0; i < untracked->dirs_nr; i++)
3626 if (untracked->dirs[i]->recurse)
3627 write_one_dir(untracked->dirs[i], wd);
3628 }
3629
3630 void write_untracked_extension(struct strbuf *out, struct untracked_cache *untracked)
3631 {
3632 struct ondisk_untracked_cache *ouc;
3633 struct write_data wd;
3634 unsigned char varbuf[16];
3635 int varint_len;
3636 const unsigned hashsz = the_hash_algo->rawsz;
3637
3638 CALLOC_ARRAY(ouc, 1);
3639 stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);
3640 stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);
3641 ouc->dir_flags = htonl(untracked->dir_flags);
3642
3643 varint_len = encode_varint(untracked->ident.len, varbuf);
3644 strbuf_add(out, varbuf, varint_len);
3645 strbuf_addbuf(out, &untracked->ident);
3646
3647 strbuf_add(out, ouc, sizeof(*ouc));
3648 strbuf_add(out, untracked->ss_info_exclude.oid.hash, hashsz);
3649 strbuf_add(out, untracked->ss_excludes_file.oid.hash, hashsz);
3650 strbuf_add(out, untracked->exclude_per_dir, strlen(untracked->exclude_per_dir) + 1);
3651 FREE_AND_NULL(ouc);
3652
3653 if (!untracked->root) {
3654 varint_len = encode_varint(0, varbuf);
3655 strbuf_add(out, varbuf, varint_len);
3656 return;
3657 }
3658
3659 wd.index = 0;
3660 wd.check_only = ewah_new();
3661 wd.valid = ewah_new();
3662 wd.sha1_valid = ewah_new();
3663 strbuf_init(&wd.out, 1024);
3664 strbuf_init(&wd.sb_stat, 1024);
3665 strbuf_init(&wd.sb_sha1, 1024);
3666 write_one_dir(untracked->root, &wd);
3667
3668 varint_len = encode_varint(wd.index, varbuf);
3669 strbuf_add(out, varbuf, varint_len);
3670 strbuf_addbuf(out, &wd.out);
3671 ewah_serialize_strbuf(wd.valid, out);
3672 ewah_serialize_strbuf(wd.check_only, out);
3673 ewah_serialize_strbuf(wd.sha1_valid, out);
3674 strbuf_addbuf(out, &wd.sb_stat);
3675 strbuf_addbuf(out, &wd.sb_sha1);
3676 strbuf_addch(out, '\0'); /* safe guard for string lists */
3677
3678 ewah_free(wd.valid);
3679 ewah_free(wd.check_only);
3680 ewah_free(wd.sha1_valid);
3681 strbuf_release(&wd.out);
3682 strbuf_release(&wd.sb_stat);
3683 strbuf_release(&wd.sb_sha1);
3684 }
3685
3686 static void free_untracked(struct untracked_cache_dir *ucd)
3687 {
3688 int i;
3689 if (!ucd)
3690 return;
3691 for (i = 0; i < ucd->dirs_nr; i++)
3692 free_untracked(ucd->dirs[i]);
3693 for (i = 0; i < ucd->untracked_nr; i++)
3694 free(ucd->untracked[i]);
3695 free(ucd->untracked);
3696 free(ucd->dirs);
3697 free(ucd);
3698 }
3699
3700 void free_untracked_cache(struct untracked_cache *uc)
3701 {
3702 if (!uc)
3703 return;
3704
3705 free(uc->exclude_per_dir_to_free);
3706 strbuf_release(&uc->ident);
3707 free_untracked(uc->root);
3708 free(uc);
3709 }
3710
3711 struct read_data {
3712 int index;
3713 struct untracked_cache_dir **ucd;
3714 struct ewah_bitmap *check_only;
3715 struct ewah_bitmap *valid;
3716 struct ewah_bitmap *sha1_valid;
3717 const unsigned char *data;
3718 const unsigned char *end;
3719 };
3720
3721 static void stat_data_from_disk(struct stat_data *to, const unsigned char *data)
3722 {
3723 memcpy(to, data, sizeof(*to));
3724 to->sd_ctime.sec = ntohl(to->sd_ctime.sec);
3725 to->sd_ctime.nsec = ntohl(to->sd_ctime.nsec);
3726 to->sd_mtime.sec = ntohl(to->sd_mtime.sec);
3727 to->sd_mtime.nsec = ntohl(to->sd_mtime.nsec);
3728 to->sd_dev = ntohl(to->sd_dev);
3729 to->sd_ino = ntohl(to->sd_ino);
3730 to->sd_uid = ntohl(to->sd_uid);
3731 to->sd_gid = ntohl(to->sd_gid);
3732 to->sd_size = ntohl(to->sd_size);
3733 }
3734
3735 static int read_one_dir(struct untracked_cache_dir **untracked_,
3736 struct read_data *rd)
3737 {
3738 struct untracked_cache_dir ud, *untracked;
3739 const unsigned char *data = rd->data, *end = rd->end;
3740 const unsigned char *eos;
3741 unsigned int value;
3742 int i;
3743
3744 memset(&ud, 0, sizeof(ud));
3745
3746 value = decode_varint(&data);
3747 if (data > end)
3748 return -1;
3749 ud.recurse = 1;
3750 ud.untracked_alloc = value;
3751 ud.untracked_nr = value;
3752 if (ud.untracked_nr)
3753 ALLOC_ARRAY(ud.untracked, ud.untracked_nr);
3754
3755 ud.dirs_alloc = ud.dirs_nr = decode_varint(&data);
3756 if (data > end)
3757 return -1;
3758 ALLOC_ARRAY(ud.dirs, ud.dirs_nr);
3759
3760 eos = memchr(data, '\0', end - data);
3761 if (!eos || eos == end)
3762 return -1;
3763
3764 *untracked_ = untracked = xmalloc(st_add3(sizeof(*untracked), eos - data, 1));
3765 memcpy(untracked, &ud, sizeof(ud));
3766 memcpy(untracked->name, data, eos - data + 1);
3767 data = eos + 1;
3768
3769 for (i = 0; i < untracked->untracked_nr; i++) {
3770 eos = memchr(data, '\0', end - data);
3771 if (!eos || eos == end)
3772 return -1;
3773 untracked->untracked[i] = xmemdupz(data, eos - data);
3774 data = eos + 1;
3775 }
3776
3777 rd->ucd[rd->index++] = untracked;
3778 rd->data = data;
3779
3780 for (i = 0; i < untracked->dirs_nr; i++) {
3781 if (read_one_dir(untracked->dirs + i, rd) < 0)
3782 return -1;
3783 }
3784 return 0;
3785 }
3786
3787 static void set_check_only(size_t pos, void *cb)
3788 {
3789 struct read_data *rd = cb;
3790 struct untracked_cache_dir *ud = rd->ucd[pos];
3791 ud->check_only = 1;
3792 }
3793
3794 static void read_stat(size_t pos, void *cb)
3795 {
3796 struct read_data *rd = cb;
3797 struct untracked_cache_dir *ud = rd->ucd[pos];
3798 if (rd->data + sizeof(struct stat_data) > rd->end) {
3799 rd->data = rd->end + 1;
3800 return;
3801 }
3802 stat_data_from_disk(&ud->stat_data, rd->data);
3803 rd->data += sizeof(struct stat_data);
3804 ud->valid = 1;
3805 }
3806
3807 static void read_oid(size_t pos, void *cb)
3808 {
3809 struct read_data *rd = cb;
3810 struct untracked_cache_dir *ud = rd->ucd[pos];
3811 if (rd->data + the_hash_algo->rawsz > rd->end) {
3812 rd->data = rd->end + 1;
3813 return;
3814 }
3815 oidread(&ud->exclude_oid, rd->data, the_repository->hash_algo);
3816 rd->data += the_hash_algo->rawsz;
3817 }
3818
3819 static void load_oid_stat(struct oid_stat *oid_stat, const unsigned char *data,
3820 const unsigned char *sha1)
3821 {
3822 stat_data_from_disk(&oid_stat->stat, data);
3823 oidread(&oid_stat->oid, sha1, the_repository->hash_algo);
3824 oid_stat->valid = 1;
3825 }
3826
3827 struct untracked_cache *read_untracked_extension(const void *data, unsigned long sz)
3828 {
3829 struct untracked_cache *uc;
3830 struct read_data rd;
3831 const unsigned char *next = data, *end = (const unsigned char *)data + sz;
3832 const char *ident;
3833 int ident_len;
3834 ssize_t len;
3835 const char *exclude_per_dir;
3836 const unsigned hashsz = the_hash_algo->rawsz;
3837 const unsigned offset = sizeof(struct ondisk_untracked_cache);
3838 const unsigned exclude_per_dir_offset = offset + 2 * hashsz;
3839
3840 if (sz <= 1 || end[-1] != '\0')
3841 return NULL;
3842 end--;
3843
3844 ident_len = decode_varint(&next);
3845 if (next + ident_len > end)
3846 return NULL;
3847 ident = (const char *)next;
3848 next += ident_len;
3849
3850 if (next + exclude_per_dir_offset + 1 > end)
3851 return NULL;
3852
3853 CALLOC_ARRAY(uc, 1);
3854 strbuf_init(&uc->ident, ident_len);
3855 strbuf_add(&uc->ident, ident, ident_len);
3856 load_oid_stat(&uc->ss_info_exclude,
3857 next + ouc_offset(info_exclude_stat),
3858 next + offset);
3859 load_oid_stat(&uc->ss_excludes_file,
3860 next + ouc_offset(excludes_file_stat),
3861 next + offset + hashsz);
3862 uc->dir_flags = get_be32(next + ouc_offset(dir_flags));
3863 exclude_per_dir = (const char *)next + exclude_per_dir_offset;
3864 uc->exclude_per_dir = uc->exclude_per_dir_to_free = xstrdup(exclude_per_dir);
3865 /* NUL after exclude_per_dir is covered by sizeof(*ouc) */
3866 next += exclude_per_dir_offset + strlen(exclude_per_dir) + 1;
3867 if (next >= end)
3868 goto done2;
3869
3870 len = decode_varint(&next);
3871 if (next > end || len == 0)
3872 goto done2;
3873
3874 rd.valid = ewah_new();
3875 rd.check_only = ewah_new();
3876 rd.sha1_valid = ewah_new();
3877 rd.data = next;
3878 rd.end = end;
3879 rd.index = 0;
3880 ALLOC_ARRAY(rd.ucd, len);
3881
3882 if (read_one_dir(&uc->root, &rd) || rd.index != len)
3883 goto done;
3884
3885 next = rd.data;
3886 len = ewah_read_mmap(rd.valid, next, end - next);
3887 if (len < 0)
3888 goto done;
3889
3890 next += len;
3891 len = ewah_read_mmap(rd.check_only, next, end - next);
3892 if (len < 0)
3893 goto done;
3894
3895 next += len;
3896 len = ewah_read_mmap(rd.sha1_valid, next, end - next);
3897 if (len < 0)
3898 goto done;
3899
3900 ewah_each_bit(rd.check_only, set_check_only, &rd);
3901 rd.data = next + len;
3902 ewah_each_bit(rd.valid, read_stat, &rd);
3903 ewah_each_bit(rd.sha1_valid, read_oid, &rd);
3904 next = rd.data;
3905
3906 done:
3907 free(rd.ucd);
3908 ewah_free(rd.valid);
3909 ewah_free(rd.check_only);
3910 ewah_free(rd.sha1_valid);
3911 done2:
3912 if (next != end) {
3913 free_untracked_cache(uc);
3914 uc = NULL;
3915 }
3916 return uc;
3917 }
3918
3919 static void invalidate_one_directory(struct untracked_cache *uc,
3920 struct untracked_cache_dir *ucd)
3921 {
3922 uc->dir_invalidated++;
3923 ucd->valid = 0;
3924 for (size_t i = 0; i < ucd->untracked_nr; i++)
3925 free(ucd->untracked[i]);
3926 ucd->untracked_nr = 0;
3927 }
3928
3929 /*
3930 * Normally when an entry is added or removed from a directory,
3931 * invalidating that directory is enough. No need to touch its
3932 * ancestors. When a directory is shown as "foo/bar/" in git-status
3933 * however, deleting or adding an entry may have cascading effect.
3934 *
3935 * Say the "foo/bar/file" has become untracked, we need to tell the
3936 * untracked_cache_dir of "foo" that "bar/" is not an untracked
3937 * directory any more (because "bar" is managed by foo as an untracked
3938 * "file").
3939 *
3940 * Similarly, if "foo/bar/file" moves from untracked to tracked and it
3941 * was the last untracked entry in the entire "foo", we should show
3942 * "foo/" instead. Which means we have to invalidate past "bar" up to
3943 * "foo".
3944 *
3945 * This function traverses all directories from root to leaf. If there
3946 * is a chance of one of the above cases happening, we invalidate back
3947 * to root. Otherwise we just invalidate the leaf. There may be a more
3948 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to
3949 * detect these cases and avoid unnecessary invalidation, for example,
3950 * checking for the untracked entry named "bar/" in "foo", but for now
3951 * stick to something safe and simple.
3952 */
3953 static int invalidate_one_component(struct untracked_cache *uc,
3954 struct untracked_cache_dir *dir,
3955 const char *path, int len)
3956 {
3957 const char *rest = strchr(path, '/');
3958
3959 if (rest) {
3960 int component_len = rest - path;
3961 struct untracked_cache_dir *d =
3962 lookup_untracked(uc, dir, path, component_len);
3963 int ret =
3964 invalidate_one_component(uc, d, rest + 1,
3965 len - (component_len + 1));
3966 if (ret)
3967 invalidate_one_directory(uc, dir);
3968 return ret;
3969 }
3970
3971 invalidate_one_directory(uc, dir);
3972 return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;
3973 }
3974
3975 void untracked_cache_invalidate_path(struct index_state *istate,
3976 const char *path, int safe_path)
3977 {
3978 if (!istate->untracked || !istate->untracked->root)
3979 return;
3980 if (!safe_path && !verify_path(path, 0))
3981 return;
3982 invalidate_one_component(istate->untracked, istate->untracked->root,
3983 path, strlen(path));
3984 }
3985
3986 void untracked_cache_invalidate_trimmed_path(struct index_state *istate,
3987 const char *path,
3988 int safe_path)
3989 {
3990 size_t len = strlen(path);
3991
3992 if (!len)
3993 BUG("untracked_cache_invalidate_trimmed_path given zero length path");
3994
3995 if (path[len - 1] != '/') {
3996 untracked_cache_invalidate_path(istate, path, safe_path);
3997 } else {
3998 struct strbuf tmp = STRBUF_INIT;
3999
4000 strbuf_add(&tmp, path, len - 1);
4001 untracked_cache_invalidate_path(istate, tmp.buf, safe_path);
4002 strbuf_release(&tmp);
4003 }
4004 }
4005
4006 void untracked_cache_remove_from_index(struct index_state *istate,
4007 const char *path)
4008 {
4009 untracked_cache_invalidate_path(istate, path, 1);
4010 }
4011
4012 void untracked_cache_add_to_index(struct index_state *istate,
4013 const char *path)
4014 {
4015 untracked_cache_invalidate_path(istate, path, 1);
4016 }
4017
4018 static void connect_wt_gitdir_in_nested(const char *sub_worktree,
4019 const char *sub_gitdir)
4020 {
4021 int i;
4022 struct repository subrepo;
4023 struct strbuf sub_wt = STRBUF_INIT;
4024 struct strbuf sub_gd = STRBUF_INIT;
4025
4026 const struct submodule *sub;
4027
4028 /* If the submodule has no working tree, we can ignore it. */
4029 if (repo_init(&subrepo, sub_gitdir, sub_worktree))
4030 return;
4031
4032 if (repo_read_index(&subrepo) < 0)
4033 die(_("index file corrupt in repo %s"), subrepo.gitdir);
4034
4035 /* TODO: audit for interaction with sparse-index. */
4036 ensure_full_index(subrepo.index);
4037 for (i = 0; i < subrepo.index->cache_nr; i++) {
4038 const struct cache_entry *ce = subrepo.index->cache[i];
4039
4040 if (!S_ISGITLINK(ce->ce_mode))
4041 continue;
4042
4043 while (i + 1 < subrepo.index->cache_nr &&
4044 !strcmp(ce->name, subrepo.index->cache[i + 1]->name))
4045 /*
4046 * Skip entries with the same name in different stages
4047 * to make sure an entry is returned only once.
4048 */
4049 i++;
4050
4051 sub = submodule_from_path(&subrepo, null_oid(the_hash_algo), ce->name);
4052 if (!sub || !is_submodule_active(&subrepo, ce->name))
4053 /* .gitmodules broken or inactive sub */
4054 continue;
4055
4056 strbuf_reset(&sub_wt);
4057 strbuf_reset(&sub_gd);
4058 strbuf_addf(&sub_wt, "%s/%s", sub_worktree, sub->path);
4059 submodule_name_to_gitdir(&sub_gd, &subrepo, sub->name);
4060
4061 connect_work_tree_and_git_dir(sub_wt.buf, sub_gd.buf, 1);
4062 }
4063 strbuf_release(&sub_wt);
4064 strbuf_release(&sub_gd);
4065 repo_clear(&subrepo);
4066 }
4067
4068 void connect_work_tree_and_git_dir(const char *work_tree_,
4069 const char *git_dir_,
4070 int recurse_into_nested)
4071 {
4072 struct strbuf gitfile_sb = STRBUF_INIT;
4073 struct strbuf cfg_sb = STRBUF_INIT;
4074 struct strbuf rel_path = STRBUF_INIT;
4075 char *git_dir, *work_tree;
4076
4077 /* Prepare .git file */
4078 strbuf_addf(&gitfile_sb, "%s/.git", work_tree_);
4079 if (safe_create_leading_directories_const(the_repository, gitfile_sb.buf))
4080 die(_("could not create directories for %s"), gitfile_sb.buf);
4081
4082 /* Prepare config file */
4083 strbuf_addf(&cfg_sb, "%s/config", git_dir_);
4084 if (safe_create_leading_directories_const(the_repository, cfg_sb.buf))
4085 die(_("could not create directories for %s"), cfg_sb.buf);
4086
4087 git_dir = real_pathdup(git_dir_, 1);
4088 work_tree = real_pathdup(work_tree_, 1);
4089
4090 /* Write .git file */
4091 write_file(gitfile_sb.buf, "gitdir: %s",
4092 relative_path(git_dir, work_tree, &rel_path));
4093 /* Update core.worktree setting */
4094 git_config_set_in_file(cfg_sb.buf, "core.worktree",
4095 relative_path(work_tree, git_dir, &rel_path));
4096
4097 strbuf_release(&gitfile_sb);
4098 strbuf_release(&cfg_sb);
4099 strbuf_release(&rel_path);
4100
4101 if (recurse_into_nested)
4102 connect_wt_gitdir_in_nested(work_tree, git_dir);
4103
4104 free(work_tree);
4105 free(git_dir);
4106 }
4107
4108 /*
4109 * Migrate the git directory of the given path from old_git_dir to new_git_dir.
4110 */
4111 void relocate_gitdir(const char *path, const char *old_git_dir, const char *new_git_dir)
4112 {
4113 if (rename(old_git_dir, new_git_dir) < 0)
4114 die_errno(_("could not migrate git directory from '%s' to '%s'"),
4115 old_git_dir, new_git_dir);
4116
4117 connect_work_tree_and_git_dir(path, new_git_dir, 0);
4118 }
4119
4120 int path_match_flags(const char *const str, const enum path_match_flags flags)
4121 {
4122 const char *p = str;
4123
4124 if (flags & PATH_MATCH_NATIVE &&
4125 flags & PATH_MATCH_XPLATFORM)
4126 BUG("path_match_flags() must get one match kind, not multiple!");
4127 else if (!(flags & PATH_MATCH_KINDS_MASK))
4128 BUG("path_match_flags() must get at least one match kind!");
4129
4130 if (flags & PATH_MATCH_STARTS_WITH_DOT_SLASH &&
4131 flags & PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH)
4132 BUG("path_match_flags() must get one platform kind, not multiple!");
4133 else if (!(flags & PATH_MATCH_PLATFORM_MASK))
4134 BUG("path_match_flags() must get at least one platform kind!");
4135
4136 if (*p++ != '.')
4137 return 0;
4138 if (flags & PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH &&
4139 *p++ != '.')
4140 return 0;
4141
4142 if (flags & PATH_MATCH_NATIVE)
4143 return is_dir_sep(*p);
4144 else if (flags & PATH_MATCH_XPLATFORM)
4145 return is_xplatform_dir_sep(*p);
4146 BUG("unreachable");
4147 }