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