2 * This handles recursive filename detection with exclude
3 * files, index knowledge etc..
5 * Copyright (C) Linus Torvalds, 2005-2006
6 * Junio Hamano, 2005-2006
8 #include "git-compat-util.h"
12 #include "object-store.h"
15 #include "wildmatch.h"
19 #include "ewah/ewok.h"
20 #include "fsmonitor.h"
21 #include "submodule-config.h"
24 * Tells read_directory_recursive how a file or directory should be treated.
25 * Values are ordered by significance, e.g. if a directory contains both
26 * excluded and untracked files, it is listed as untracked because
27 * path_untracked > path_excluded.
37 * Support data structure for our opendir/readdir/closedir wrappers
41 struct untracked_cache_dir
*untracked
;
48 struct untracked_cache_dir
*ucd
;
51 static enum path_treatment
read_directory_recursive(struct dir_struct
*dir
,
52 struct index_state
*istate
, const char *path
, int len
,
53 struct untracked_cache_dir
*untracked
,
54 int check_only
, int stop_at_first_file
, const struct pathspec
*pathspec
);
55 static int resolve_dtype(int dtype
, struct index_state
*istate
,
56 const char *path
, int len
);
57 struct dirent
*readdir_skip_dot_and_dotdot(DIR *dirp
)
61 while ((e
= readdir(dirp
)) != NULL
) {
62 if (!is_dot_or_dotdot(e
->d_name
))
68 int count_slashes(const char *s
)
77 int fspathcmp(const char *a
, const char *b
)
79 return ignore_case
? strcasecmp(a
, b
) : strcmp(a
, b
);
82 int fspatheq(const char *a
, const char *b
)
84 return !fspathcmp(a
, b
);
87 int fspathncmp(const char *a
, const char *b
, size_t count
)
89 return ignore_case
? strncasecmp(a
, b
, count
) : strncmp(a
, b
, count
);
92 unsigned int fspathhash(const char *str
)
94 return ignore_case
? strihash(str
) : strhash(str
);
97 int git_fnmatch(const struct pathspec_item
*item
,
98 const char *pattern
, const char *string
,
102 if (ps_strncmp(item
, pattern
, string
, prefix
))
107 if (item
->flags
& PATHSPEC_ONESTAR
) {
108 int pattern_len
= strlen(++pattern
);
109 int string_len
= strlen(string
);
110 return string_len
< pattern_len
||
111 ps_strcmp(item
, pattern
,
112 string
+ string_len
- pattern_len
);
114 if (item
->magic
& PATHSPEC_GLOB
)
115 return wildmatch(pattern
, string
,
117 (item
->magic
& PATHSPEC_ICASE
? WM_CASEFOLD
: 0));
119 /* wildmatch has not learned no FNM_PATHNAME mode yet */
120 return wildmatch(pattern
, string
,
121 item
->magic
& PATHSPEC_ICASE
? WM_CASEFOLD
: 0);
124 static int fnmatch_icase_mem(const char *pattern
, int patternlen
,
125 const char *string
, int stringlen
,
129 struct strbuf pat_buf
= STRBUF_INIT
;
130 struct strbuf str_buf
= STRBUF_INIT
;
131 const char *use_pat
= pattern
;
132 const char *use_str
= string
;
134 if (pattern
[patternlen
]) {
135 strbuf_add(&pat_buf
, pattern
, patternlen
);
136 use_pat
= pat_buf
.buf
;
138 if (string
[stringlen
]) {
139 strbuf_add(&str_buf
, string
, stringlen
);
140 use_str
= str_buf
.buf
;
144 flags
|= WM_CASEFOLD
;
145 match_status
= wildmatch(use_pat
, use_str
, flags
);
147 strbuf_release(&pat_buf
);
148 strbuf_release(&str_buf
);
153 static size_t common_prefix_len(const struct pathspec
*pathspec
)
159 * ":(icase)path" is treated as a pathspec full of
160 * wildcard. In other words, only prefix is considered common
161 * prefix. If the pathspec is abc/foo abc/bar, running in
162 * subdir xyz, the common prefix is still xyz, not xyz/abc as
165 GUARD_PATHSPEC(pathspec
,
174 for (n
= 0; n
< pathspec
->nr
; n
++) {
175 size_t i
= 0, len
= 0, item_len
;
176 if (pathspec
->items
[n
].magic
& PATHSPEC_EXCLUDE
)
178 if (pathspec
->items
[n
].magic
& PATHSPEC_ICASE
)
179 item_len
= pathspec
->items
[n
].prefix
;
181 item_len
= pathspec
->items
[n
].nowildcard_len
;
182 while (i
< item_len
&& (n
== 0 || i
< max
)) {
183 char c
= pathspec
->items
[n
].match
[i
];
184 if (c
!= pathspec
->items
[0].match
[i
])
190 if (n
== 0 || len
< max
) {
200 * Returns a copy of the longest leading path common among all
203 char *common_prefix(const struct pathspec
*pathspec
)
205 unsigned long len
= common_prefix_len(pathspec
);
207 return len
? xmemdupz(pathspec
->items
[0].match
, len
) : NULL
;
210 int fill_directory(struct dir_struct
*dir
,
211 struct index_state
*istate
,
212 const struct pathspec
*pathspec
)
217 unsigned exclusive_flags
= DIR_SHOW_IGNORED
| DIR_SHOW_IGNORED_TOO
;
218 if ((dir
->flags
& exclusive_flags
) == exclusive_flags
)
219 BUG("DIR_SHOW_IGNORED and DIR_SHOW_IGNORED_TOO are exclusive");
222 * Calculate common prefix for the pathspec, and
223 * use that to optimize the directory walk
225 prefix_len
= common_prefix_len(pathspec
);
226 prefix
= prefix_len
? pathspec
->items
[0].match
: "";
228 /* Read the directory and prune it */
229 read_directory(dir
, istate
, prefix
, prefix_len
, pathspec
);
234 int within_depth(const char *name
, int namelen
,
235 int depth
, int max_depth
)
237 const char *cp
= name
, *cpe
= name
+ namelen
;
243 if (depth
> max_depth
)
250 * Read the contents of the blob with the given OID into a buffer.
251 * Append a trailing LF to the end if the last line doesn't have one.
254 * -1 when the OID is invalid or unknown or does not refer to a blob.
255 * 0 when the blob is empty.
256 * 1 along with { data, size } of the (possibly augmented) buffer
259 * Optionally updates the given oid_stat with the given OID (when valid).
261 static int do_read_blob(const struct object_id
*oid
, struct oid_stat
*oid_stat
,
262 size_t *size_out
, char **data_out
)
264 enum object_type type
;
271 data
= read_object_file(oid
, &type
, &sz
);
272 if (!data
|| type
!= OBJ_BLOB
) {
278 memset(&oid_stat
->stat
, 0, sizeof(oid_stat
->stat
));
279 oidcpy(&oid_stat
->oid
, oid
);
287 if (data
[sz
- 1] != '\n') {
288 data
= xrealloc(data
, st_add(sz
, 1));
292 *size_out
= xsize_t(sz
);
298 #define DO_MATCH_EXCLUDE (1<<0)
299 #define DO_MATCH_DIRECTORY (1<<1)
300 #define DO_MATCH_LEADING_PATHSPEC (1<<2)
303 * Does the given pathspec match the given name? A match is found if
305 * (1) the pathspec string is leading directory of 'name' ("RECURSIVELY"), or
306 * (2) the pathspec string has a leading part matching 'name' ("LEADING"), or
307 * (3) the pathspec string is a wildcard and matches 'name' ("WILDCARD"), or
308 * (4) the pathspec string is exactly the same as 'name' ("EXACT").
310 * Return value tells which case it was (1-4), or 0 when there is no match.
312 * It may be instructive to look at a small table of concrete examples
313 * to understand the differences between 1, 2, and 4:
316 * | a/b | a/b/ | a/b/c
317 * ------+-----------+-----------+------------
318 * a/b | EXACT | EXACT[1] | LEADING[2]
319 * Names a/b/ | RECURSIVE | EXACT | LEADING[2]
320 * a/b/c | RECURSIVE | RECURSIVE | EXACT
322 * [1] Only if DO_MATCH_DIRECTORY is passed; otherwise, this is NOT a match.
323 * [2] Only if DO_MATCH_LEADING_PATHSPEC is passed; otherwise, not a match.
325 static int match_pathspec_item(struct index_state
*istate
,
326 const struct pathspec_item
*item
, int prefix
,
327 const char *name
, int namelen
, unsigned flags
)
329 /* name/namelen has prefix cut off by caller */
330 const char *match
= item
->match
+ prefix
;
331 int matchlen
= item
->len
- prefix
;
334 * The normal call pattern is:
335 * 1. prefix = common_prefix_len(ps);
336 * 2. prune something, or fill_directory
337 * 3. match_pathspec()
339 * 'prefix' at #1 may be shorter than the command's prefix and
340 * it's ok for #2 to match extra files. Those extras will be
343 * Suppose the pathspec is 'foo' and '../bar' running from
344 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
345 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
346 * user does not want XYZ/foo, only the "foo" part should be
347 * case-insensitive. We need to filter out XYZ/foo here. In
348 * other words, we do not trust the caller on comparing the
349 * prefix part when :(icase) is involved. We do exact
350 * comparison ourselves.
352 * Normally the caller (common_prefix_len() in fact) does
353 * _exact_ matching on name[-prefix+1..-1] and we do not need
354 * to check that part. Be defensive and check it anyway, in
355 * case common_prefix_len is changed, or a new caller is
356 * introduced that does not use common_prefix_len.
358 * If the penalty turns out too high when prefix is really
359 * long, maybe change it to
360 * strncmp(match, name, item->prefix - prefix)
362 if (item
->prefix
&& (item
->magic
& PATHSPEC_ICASE
) &&
363 strncmp(item
->match
, name
- prefix
, item
->prefix
))
366 if (item
->attr_match_nr
&&
367 !match_pathspec_attrs(istate
, name
, namelen
, item
))
370 /* If the match was just the prefix, we matched */
372 return MATCHED_RECURSIVELY
;
374 if (matchlen
<= namelen
&& !ps_strncmp(item
, match
, name
, matchlen
)) {
375 if (matchlen
== namelen
)
376 return MATCHED_EXACTLY
;
378 if (match
[matchlen
-1] == '/' || name
[matchlen
] == '/')
379 return MATCHED_RECURSIVELY
;
380 } else if ((flags
& DO_MATCH_DIRECTORY
) &&
381 match
[matchlen
- 1] == '/' &&
382 namelen
== matchlen
- 1 &&
383 !ps_strncmp(item
, match
, name
, namelen
))
384 return MATCHED_EXACTLY
;
386 if (item
->nowildcard_len
< item
->len
&&
387 !git_fnmatch(item
, match
, name
,
388 item
->nowildcard_len
- prefix
))
389 return MATCHED_FNMATCH
;
391 /* Perform checks to see if "name" is a leading string of the pathspec */
392 if ( (flags
& DO_MATCH_LEADING_PATHSPEC
) &&
393 !(flags
& DO_MATCH_EXCLUDE
)) {
394 /* name is a literal prefix of the pathspec */
395 int offset
= name
[namelen
-1] == '/' ? 1 : 0;
396 if ((namelen
< matchlen
) &&
397 (match
[namelen
-offset
] == '/') &&
398 !ps_strncmp(item
, match
, name
, namelen
))
399 return MATCHED_RECURSIVELY_LEADING_PATHSPEC
;
401 /* name doesn't match up to the first wild character */
402 if (item
->nowildcard_len
< item
->len
&&
403 ps_strncmp(item
, match
, name
,
404 item
->nowildcard_len
- prefix
))
408 * name has no wildcard, and it didn't match as a leading
409 * pathspec so return.
411 if (item
->nowildcard_len
== item
->len
)
415 * Here is where we would perform a wildmatch to check if
416 * "name" can be matched as a directory (or a prefix) against
417 * the pathspec. Since wildmatch doesn't have this capability
418 * at the present we have to punt and say that it is a match,
419 * potentially returning a false positive
420 * The submodules themselves will be able to perform more
421 * accurate matching to determine if the pathspec matches.
423 return MATCHED_RECURSIVELY_LEADING_PATHSPEC
;
430 * do_match_pathspec() is meant to ONLY be called by
431 * match_pathspec_with_flags(); calling it directly risks pathspecs
432 * like ':!unwanted_path' being ignored.
434 * Given a name and a list of pathspecs, returns the nature of the
435 * closest (i.e. most specific) match of the name to any of the
438 * The caller typically calls this multiple times with the same
439 * pathspec and seen[] array but with different name/namelen
440 * (e.g. entries from the index) and is interested in seeing if and
441 * how each pathspec matches all the names it calls this function
442 * with. A mark is left in the seen[] array for each pathspec element
443 * indicating the closest type of match that element achieved, so if
444 * seen[n] remains zero after multiple invocations, that means the nth
445 * pathspec did not match any names, which could indicate that the
446 * user mistyped the nth pathspec.
448 static int do_match_pathspec(struct index_state
*istate
,
449 const struct pathspec
*ps
,
450 const char *name
, int namelen
,
451 int prefix
, char *seen
,
454 int i
, retval
= 0, exclude
= flags
& DO_MATCH_EXCLUDE
;
466 if (!ps
->recursive
||
467 !(ps
->magic
& PATHSPEC_MAXDEPTH
) ||
469 return MATCHED_RECURSIVELY
;
471 if (within_depth(name
, namelen
, 0, ps
->max_depth
))
472 return MATCHED_EXACTLY
;
480 for (i
= ps
->nr
- 1; i
>= 0; i
--) {
483 if ((!exclude
&& ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
) ||
484 ( exclude
&& !(ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
)))
487 if (seen
&& seen
[i
] == MATCHED_EXACTLY
)
490 * Make exclude patterns optional and never report
491 * "pathspec ':(exclude)foo' matches no files"
493 if (seen
&& ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
)
494 seen
[i
] = MATCHED_FNMATCH
;
495 how
= match_pathspec_item(istate
, ps
->items
+i
, prefix
, name
,
498 (ps
->magic
& PATHSPEC_MAXDEPTH
) &&
499 ps
->max_depth
!= -1 &&
500 how
&& how
!= MATCHED_FNMATCH
) {
501 int len
= ps
->items
[i
].len
;
502 if (name
[len
] == '/')
504 if (within_depth(name
+len
, namelen
-len
, 0, ps
->max_depth
))
505 how
= MATCHED_EXACTLY
;
512 if (seen
&& seen
[i
] < how
)
519 static int match_pathspec_with_flags(struct index_state
*istate
,
520 const struct pathspec
*ps
,
521 const char *name
, int namelen
,
522 int prefix
, char *seen
, unsigned flags
)
524 int positive
, negative
;
525 positive
= do_match_pathspec(istate
, ps
, name
, namelen
,
526 prefix
, seen
, flags
);
527 if (!(ps
->magic
& PATHSPEC_EXCLUDE
) || !positive
)
529 negative
= do_match_pathspec(istate
, ps
, name
, namelen
,
531 flags
| DO_MATCH_EXCLUDE
);
532 return negative
? 0 : positive
;
535 int match_pathspec(struct index_state
*istate
,
536 const struct pathspec
*ps
,
537 const char *name
, int namelen
,
538 int prefix
, char *seen
, int is_dir
)
540 unsigned flags
= is_dir
? DO_MATCH_DIRECTORY
: 0;
541 return match_pathspec_with_flags(istate
, ps
, name
, namelen
,
542 prefix
, seen
, flags
);
546 * Check if a submodule is a superset of the pathspec
548 int submodule_path_match(struct index_state
*istate
,
549 const struct pathspec
*ps
,
550 const char *submodule_name
,
553 int matched
= match_pathspec_with_flags(istate
, ps
, submodule_name
,
554 strlen(submodule_name
),
557 DO_MATCH_LEADING_PATHSPEC
);
561 int report_path_error(const char *ps_matched
,
562 const struct pathspec
*pathspec
)
565 * Make sure all pathspec matched; otherwise it is an error.
568 for (num
= 0; num
< pathspec
->nr
; num
++) {
569 int other
, found_dup
;
574 * The caller might have fed identical pathspec
575 * twice. Do not barf on such a mistake.
576 * FIXME: parse_pathspec should have eliminated
577 * duplicate pathspec.
579 for (found_dup
= other
= 0;
580 !found_dup
&& other
< pathspec
->nr
;
582 if (other
== num
|| !ps_matched
[other
])
584 if (!strcmp(pathspec
->items
[other
].original
,
585 pathspec
->items
[num
].original
))
587 * Ok, we have a match already.
594 error(_("pathspec '%s' did not match any file(s) known to git"),
595 pathspec
->items
[num
].original
);
602 * Return the length of the "simple" part of a path match limiter.
604 int simple_length(const char *match
)
609 unsigned char c
= *match
++;
611 if (c
== '\0' || is_glob_special(c
))
616 int no_wildcard(const char *string
)
618 return string
[simple_length(string
)] == '\0';
621 void parse_path_pattern(const char **pattern
,
626 const char *p
= *pattern
;
631 *flags
|= PATTERN_FLAG_NEGATIVE
;
635 if (len
&& p
[len
- 1] == '/') {
637 *flags
|= PATTERN_FLAG_MUSTBEDIR
;
639 for (i
= 0; i
< len
; i
++) {
644 *flags
|= PATTERN_FLAG_NODIR
;
645 *nowildcardlen
= simple_length(p
);
647 * we should have excluded the trailing slash from 'p' too,
648 * but that's one more allocation. Instead just make sure
649 * nowildcardlen does not exceed real patternlen
651 if (*nowildcardlen
> len
)
652 *nowildcardlen
= len
;
653 if (*p
== '*' && no_wildcard(p
+ 1))
654 *flags
|= PATTERN_FLAG_ENDSWITH
;
659 int pl_hashmap_cmp(const void *cmp_data UNUSED
,
660 const struct hashmap_entry
*a
,
661 const struct hashmap_entry
*b
,
662 const void *key UNUSED
)
664 const struct pattern_entry
*ee1
=
665 container_of(a
, struct pattern_entry
, ent
);
666 const struct pattern_entry
*ee2
=
667 container_of(b
, struct pattern_entry
, ent
);
669 size_t min_len
= ee1
->patternlen
<= ee2
->patternlen
673 return fspathncmp(ee1
->pattern
, ee2
->pattern
, min_len
);
676 static char *dup_and_filter_pattern(const char *pattern
)
680 char *result
= xstrdup(pattern
);
686 /* skip escape characters (once) */
706 static void add_pattern_to_hashsets(struct pattern_list
*pl
, struct path_pattern
*given
)
708 struct pattern_entry
*translated
;
711 const char *prev
, *cur
, *next
;
713 if (!pl
->use_cone_patterns
)
716 if (given
->flags
& PATTERN_FLAG_NEGATIVE
&&
717 given
->flags
& PATTERN_FLAG_MUSTBEDIR
&&
718 !strcmp(given
->pattern
, "/*")) {
723 if (!given
->flags
&& !strcmp(given
->pattern
, "/*")) {
728 if (given
->patternlen
< 2 ||
729 *given
->pattern
!= '/' ||
730 strstr(given
->pattern
, "**")) {
731 /* Not a cone pattern. */
732 warning(_("unrecognized pattern: '%s'"), given
->pattern
);
736 if (!(given
->flags
& PATTERN_FLAG_MUSTBEDIR
) &&
737 strcmp(given
->pattern
, "/*")) {
738 /* Not a cone pattern. */
739 warning(_("unrecognized pattern: '%s'"), given
->pattern
);
743 prev
= given
->pattern
;
744 cur
= given
->pattern
+ 1;
745 next
= given
->pattern
+ 2;
748 /* Watch for glob characters '*', '\', '[', '?' */
749 if (!is_glob_special(*cur
))
752 /* But only if *prev != '\\' */
756 /* But allow the initial '\' */
758 is_glob_special(*next
))
761 /* But a trailing '/' then '*' is fine */
767 /* Not a cone pattern. */
768 warning(_("unrecognized pattern: '%s'"), given
->pattern
);
777 if (given
->patternlen
> 2 &&
778 !strcmp(given
->pattern
+ given
->patternlen
- 2, "/*")) {
779 if (!(given
->flags
& PATTERN_FLAG_NEGATIVE
)) {
780 /* Not a cone pattern. */
781 warning(_("unrecognized pattern: '%s'"), given
->pattern
);
785 truncated
= dup_and_filter_pattern(given
->pattern
);
787 translated
= xmalloc(sizeof(struct pattern_entry
));
788 translated
->pattern
= truncated
;
789 translated
->patternlen
= given
->patternlen
- 2;
790 hashmap_entry_init(&translated
->ent
,
791 fspathhash(translated
->pattern
));
793 if (!hashmap_get_entry(&pl
->recursive_hashmap
,
794 translated
, ent
, NULL
)) {
795 /* We did not see the "parent" included */
796 warning(_("unrecognized negative pattern: '%s'"),
803 hashmap_add(&pl
->parent_hashmap
, &translated
->ent
);
804 hashmap_remove(&pl
->recursive_hashmap
, &translated
->ent
, &data
);
809 if (given
->flags
& PATTERN_FLAG_NEGATIVE
) {
810 warning(_("unrecognized negative pattern: '%s'"),
815 translated
= xmalloc(sizeof(struct pattern_entry
));
817 translated
->pattern
= dup_and_filter_pattern(given
->pattern
);
818 translated
->patternlen
= given
->patternlen
;
819 hashmap_entry_init(&translated
->ent
,
820 fspathhash(translated
->pattern
));
822 hashmap_add(&pl
->recursive_hashmap
, &translated
->ent
);
824 if (hashmap_get_entry(&pl
->parent_hashmap
, translated
, ent
, NULL
)) {
825 /* we already included this at the parent level */
826 warning(_("your sparse-checkout file may have issues: pattern '%s' is repeated"),
834 warning(_("disabling cone pattern matching"));
835 hashmap_clear_and_free(&pl
->parent_hashmap
, struct pattern_entry
, ent
);
836 hashmap_clear_and_free(&pl
->recursive_hashmap
, struct pattern_entry
, ent
);
837 pl
->use_cone_patterns
= 0;
840 static int hashmap_contains_path(struct hashmap
*map
,
841 struct strbuf
*pattern
)
843 struct pattern_entry p
;
845 /* Check straight mapping */
846 p
.pattern
= pattern
->buf
;
847 p
.patternlen
= pattern
->len
;
848 hashmap_entry_init(&p
.ent
, fspathhash(p
.pattern
));
849 return !!hashmap_get_entry(map
, &p
, ent
, NULL
);
852 int hashmap_contains_parent(struct hashmap
*map
,
854 struct strbuf
*buffer
)
858 strbuf_setlen(buffer
, 0);
861 strbuf_addch(buffer
, '/');
863 strbuf_addstr(buffer
, path
);
865 slash_pos
= strrchr(buffer
->buf
, '/');
867 while (slash_pos
> buffer
->buf
) {
868 strbuf_setlen(buffer
, slash_pos
- buffer
->buf
);
870 if (hashmap_contains_path(map
, buffer
))
873 slash_pos
= strrchr(buffer
->buf
, '/');
879 void add_pattern(const char *string
, const char *base
,
880 int baselen
, struct pattern_list
*pl
, int srcpos
)
882 struct path_pattern
*pattern
;
887 parse_path_pattern(&string
, &patternlen
, &flags
, &nowildcardlen
);
888 if (flags
& PATTERN_FLAG_MUSTBEDIR
) {
889 FLEXPTR_ALLOC_MEM(pattern
, pattern
, string
, patternlen
);
891 pattern
= xmalloc(sizeof(*pattern
));
892 pattern
->pattern
= string
;
894 pattern
->patternlen
= patternlen
;
895 pattern
->nowildcardlen
= nowildcardlen
;
896 pattern
->base
= base
;
897 pattern
->baselen
= baselen
;
898 pattern
->flags
= flags
;
899 pattern
->srcpos
= srcpos
;
900 ALLOC_GROW(pl
->patterns
, pl
->nr
+ 1, pl
->alloc
);
901 pl
->patterns
[pl
->nr
++] = pattern
;
904 add_pattern_to_hashsets(pl
, pattern
);
907 static int read_skip_worktree_file_from_index(struct index_state
*istate
,
909 size_t *size_out
, char **data_out
,
910 struct oid_stat
*oid_stat
)
915 pos
= index_name_pos(istate
, path
, len
);
918 if (!ce_skip_worktree(istate
->cache
[pos
]))
921 return do_read_blob(&istate
->cache
[pos
]->oid
, oid_stat
, size_out
, data_out
);
925 * Frees memory within pl which was allocated for exclude patterns and
926 * the file buffer. Does not free pl itself.
928 void clear_pattern_list(struct pattern_list
*pl
)
932 for (i
= 0; i
< pl
->nr
; i
++)
933 free(pl
->patterns
[i
]);
936 hashmap_clear_and_free(&pl
->recursive_hashmap
, struct pattern_entry
, ent
);
937 hashmap_clear_and_free(&pl
->parent_hashmap
, struct pattern_entry
, ent
);
939 memset(pl
, 0, sizeof(*pl
));
942 static void trim_trailing_spaces(char *buf
)
944 char *p
, *last_space
= NULL
;
946 for (p
= buf
; *p
; p
++)
966 * Given a subdirectory name and "dir" of the current directory,
967 * search the subdir in "dir" and return it, or create a new one if it
968 * does not exist in "dir".
970 * If "name" has the trailing slash, it'll be excluded in the search.
972 static struct untracked_cache_dir
*lookup_untracked(struct untracked_cache
*uc
,
973 struct untracked_cache_dir
*dir
,
974 const char *name
, int len
)
977 struct untracked_cache_dir
*d
;
980 if (len
&& name
[len
- 1] == '/')
984 while (last
> first
) {
985 int cmp
, next
= first
+ ((last
- first
) >> 1);
987 cmp
= strncmp(name
, d
->name
, len
);
988 if (!cmp
&& strlen(d
->name
) > len
)
1000 FLEX_ALLOC_MEM(d
, name
, name
, len
);
1002 ALLOC_GROW(dir
->dirs
, dir
->dirs_nr
+ 1, dir
->dirs_alloc
);
1003 MOVE_ARRAY(dir
->dirs
+ first
+ 1, dir
->dirs
+ first
,
1004 dir
->dirs_nr
- first
);
1006 dir
->dirs
[first
] = d
;
1010 static void do_invalidate_gitignore(struct untracked_cache_dir
*dir
)
1014 dir
->untracked_nr
= 0;
1015 for (i
= 0; i
< dir
->dirs_nr
; i
++)
1016 do_invalidate_gitignore(dir
->dirs
[i
]);
1019 static void invalidate_gitignore(struct untracked_cache
*uc
,
1020 struct untracked_cache_dir
*dir
)
1022 uc
->gitignore_invalidated
++;
1023 do_invalidate_gitignore(dir
);
1026 static void invalidate_directory(struct untracked_cache
*uc
,
1027 struct untracked_cache_dir
*dir
)
1032 * Invalidation increment here is just roughly correct. If
1033 * untracked_nr or any of dirs[].recurse is non-zero, we
1034 * should increment dir_invalidated too. But that's more
1038 uc
->dir_invalidated
++;
1041 dir
->untracked_nr
= 0;
1042 for (i
= 0; i
< dir
->dirs_nr
; i
++)
1043 dir
->dirs
[i
]->recurse
= 0;
1046 static int add_patterns_from_buffer(char *buf
, size_t size
,
1047 const char *base
, int baselen
,
1048 struct pattern_list
*pl
);
1050 /* Flags for add_patterns() */
1051 #define PATTERN_NOFOLLOW (1<<0)
1054 * Given a file with name "fname", read it (either from disk, or from
1055 * an index if 'istate' is non-null), parse it and store the
1056 * exclude rules in "pl".
1058 * If "oid_stat" is not NULL, compute oid of the exclude file and fill
1059 * stat data from disk (only valid if add_patterns returns zero). If
1060 * oid_stat.valid is non-zero, "oid_stat" must contain good value as input.
1062 static int add_patterns(const char *fname
, const char *base
, int baselen
,
1063 struct pattern_list
*pl
, struct index_state
*istate
,
1064 unsigned flags
, struct oid_stat
*oid_stat
)
1072 if (flags
& PATTERN_NOFOLLOW
)
1073 fd
= open_nofollow(fname
, O_RDONLY
);
1075 fd
= open(fname
, O_RDONLY
);
1077 if (fd
< 0 || fstat(fd
, &st
) < 0) {
1079 warn_on_fopen_errors(fname
);
1084 r
= read_skip_worktree_file_from_index(istate
, fname
,
1090 size
= xsize_t(st
.st_size
);
1093 fill_stat_data(&oid_stat
->stat
, &st
);
1094 oidcpy(&oid_stat
->oid
, the_hash_algo
->empty_blob
);
1095 oid_stat
->valid
= 1;
1100 buf
= xmallocz(size
);
1101 if (read_in_full(fd
, buf
, size
) != size
) {
1110 if (oid_stat
->valid
&&
1111 !match_stat_data_racy(istate
, &oid_stat
->stat
, &st
))
1112 ; /* no content change, oid_stat->oid still good */
1114 (pos
= index_name_pos(istate
, fname
, strlen(fname
))) >= 0 &&
1115 !ce_stage(istate
->cache
[pos
]) &&
1116 ce_uptodate(istate
->cache
[pos
]) &&
1117 !would_convert_to_git(istate
, fname
))
1118 oidcpy(&oid_stat
->oid
,
1119 &istate
->cache
[pos
]->oid
);
1121 hash_object_file(the_hash_algo
, buf
, size
,
1122 OBJ_BLOB
, &oid_stat
->oid
);
1123 fill_stat_data(&oid_stat
->stat
, &st
);
1124 oid_stat
->valid
= 1;
1128 add_patterns_from_buffer(buf
, size
, base
, baselen
, pl
);
1132 static int add_patterns_from_buffer(char *buf
, size_t size
,
1133 const char *base
, int baselen
,
1134 struct pattern_list
*pl
)
1139 hashmap_init(&pl
->recursive_hashmap
, pl_hashmap_cmp
, NULL
, 0);
1140 hashmap_init(&pl
->parent_hashmap
, pl_hashmap_cmp
, NULL
, 0);
1144 if (skip_utf8_bom(&buf
, size
))
1145 size
-= buf
- pl
->filebuf
;
1149 for (i
= 0; i
< size
; i
++) {
1150 if (buf
[i
] == '\n') {
1151 if (entry
!= buf
+ i
&& entry
[0] != '#') {
1152 buf
[i
- (i
&& buf
[i
-1] == '\r')] = 0;
1153 trim_trailing_spaces(entry
);
1154 add_pattern(entry
, base
, baselen
, pl
, lineno
);
1157 entry
= buf
+ i
+ 1;
1163 int add_patterns_from_file_to_list(const char *fname
, const char *base
,
1164 int baselen
, struct pattern_list
*pl
,
1165 struct index_state
*istate
,
1168 return add_patterns(fname
, base
, baselen
, pl
, istate
, flags
, NULL
);
1171 int add_patterns_from_blob_to_list(
1172 struct object_id
*oid
,
1173 const char *base
, int baselen
,
1174 struct pattern_list
*pl
)
1180 r
= do_read_blob(oid
, NULL
, &size
, &buf
);
1184 add_patterns_from_buffer(buf
, size
, base
, baselen
, pl
);
1188 struct pattern_list
*add_pattern_list(struct dir_struct
*dir
,
1189 int group_type
, const char *src
)
1191 struct pattern_list
*pl
;
1192 struct exclude_list_group
*group
;
1194 group
= &dir
->internal
.exclude_list_group
[group_type
];
1195 ALLOC_GROW(group
->pl
, group
->nr
+ 1, group
->alloc
);
1196 pl
= &group
->pl
[group
->nr
++];
1197 memset(pl
, 0, sizeof(*pl
));
1203 * Used to set up core.excludesfile and .git/info/exclude lists.
1205 static void add_patterns_from_file_1(struct dir_struct
*dir
, const char *fname
,
1206 struct oid_stat
*oid_stat
)
1208 struct pattern_list
*pl
;
1210 * catch setup_standard_excludes() that's called before
1211 * dir->untracked is assigned. That function behaves
1212 * differently when dir->untracked is non-NULL.
1214 if (!dir
->untracked
)
1215 dir
->internal
.unmanaged_exclude_files
++;
1216 pl
= add_pattern_list(dir
, EXC_FILE
, fname
);
1217 if (add_patterns(fname
, "", 0, pl
, NULL
, 0, oid_stat
) < 0)
1218 die(_("cannot use %s as an exclude file"), fname
);
1221 void add_patterns_from_file(struct dir_struct
*dir
, const char *fname
)
1223 dir
->internal
.unmanaged_exclude_files
++; /* see validate_untracked_cache() */
1224 add_patterns_from_file_1(dir
, fname
, NULL
);
1227 int match_basename(const char *basename
, int basenamelen
,
1228 const char *pattern
, int prefix
, int patternlen
,
1231 if (prefix
== patternlen
) {
1232 if (patternlen
== basenamelen
&&
1233 !fspathncmp(pattern
, basename
, basenamelen
))
1235 } else if (flags
& PATTERN_FLAG_ENDSWITH
) {
1236 /* "*literal" matching against "fooliteral" */
1237 if (patternlen
- 1 <= basenamelen
&&
1238 !fspathncmp(pattern
+ 1,
1239 basename
+ basenamelen
- (patternlen
- 1),
1243 if (fnmatch_icase_mem(pattern
, patternlen
,
1244 basename
, basenamelen
,
1251 int match_pathname(const char *pathname
, int pathlen
,
1252 const char *base
, int baselen
,
1253 const char *pattern
, int prefix
, int patternlen
)
1259 * match with FNM_PATHNAME; the pattern has base implicitly
1262 if (*pattern
== '/') {
1269 * baselen does not count the trailing slash. base[] may or
1270 * may not end with a trailing slash though.
1272 if (pathlen
< baselen
+ 1 ||
1273 (baselen
&& pathname
[baselen
] != '/') ||
1274 fspathncmp(pathname
, base
, baselen
))
1277 namelen
= baselen
? pathlen
- baselen
- 1 : pathlen
;
1278 name
= pathname
+ pathlen
- namelen
;
1282 * if the non-wildcard part is longer than the
1283 * remaining pathname, surely it cannot match.
1285 if (prefix
> namelen
)
1288 if (fspathncmp(pattern
, name
, prefix
))
1291 patternlen
-= prefix
;
1296 * If the whole pattern did not have a wildcard,
1297 * then our prefix match is all we need; we
1298 * do not need to call fnmatch at all.
1300 if (!patternlen
&& !namelen
)
1304 return fnmatch_icase_mem(pattern
, patternlen
,
1310 * Scan the given exclude list in reverse to see whether pathname
1311 * should be ignored. The first match (i.e. the last on the list), if
1312 * any, determines the fate. Returns the exclude_list element which
1313 * matched, or NULL for undecided.
1315 static struct path_pattern
*last_matching_pattern_from_list(const char *pathname
,
1317 const char *basename
,
1319 struct pattern_list
*pl
,
1320 struct index_state
*istate
)
1322 struct path_pattern
*res
= NULL
; /* undecided */
1326 return NULL
; /* undefined */
1328 for (i
= pl
->nr
- 1; 0 <= i
; i
--) {
1329 struct path_pattern
*pattern
= pl
->patterns
[i
];
1330 const char *exclude
= pattern
->pattern
;
1331 int prefix
= pattern
->nowildcardlen
;
1333 if (pattern
->flags
& PATTERN_FLAG_MUSTBEDIR
) {
1334 *dtype
= resolve_dtype(*dtype
, istate
, pathname
, pathlen
);
1335 if (*dtype
!= DT_DIR
)
1339 if (pattern
->flags
& PATTERN_FLAG_NODIR
) {
1340 if (match_basename(basename
,
1341 pathlen
- (basename
- pathname
),
1342 exclude
, prefix
, pattern
->patternlen
,
1350 assert(pattern
->baselen
== 0 ||
1351 pattern
->base
[pattern
->baselen
- 1] == '/');
1352 if (match_pathname(pathname
, pathlen
,
1354 pattern
->baselen
? pattern
->baselen
- 1 : 0,
1355 exclude
, prefix
, pattern
->patternlen
)) {
1364 * Scan the list of patterns to determine if the ordered list
1365 * of patterns matches on 'pathname'.
1367 * Return 1 for a match, 0 for not matched and -1 for undecided.
1369 enum pattern_match_result
path_matches_pattern_list(
1370 const char *pathname
, int pathlen
,
1371 const char *basename
, int *dtype
,
1372 struct pattern_list
*pl
,
1373 struct index_state
*istate
)
1375 struct path_pattern
*pattern
;
1376 struct strbuf parent_pathname
= STRBUF_INIT
;
1377 int result
= NOT_MATCHED
;
1380 if (!pl
->use_cone_patterns
) {
1381 pattern
= last_matching_pattern_from_list(pathname
, pathlen
, basename
,
1384 if (pattern
->flags
& PATTERN_FLAG_NEGATIVE
)
1396 strbuf_addch(&parent_pathname
, '/');
1397 strbuf_add(&parent_pathname
, pathname
, pathlen
);
1400 * Directory entries are matched if and only if a file
1401 * contained immediately within them is matched. For the
1402 * case of a directory entry, modify the path to create
1403 * a fake filename within this directory, allowing us to
1404 * use the file-base matching logic in an equivalent way.
1406 if (parent_pathname
.len
> 0 &&
1407 parent_pathname
.buf
[parent_pathname
.len
- 1] == '/') {
1408 slash_pos
= parent_pathname
.len
- 1;
1409 strbuf_add(&parent_pathname
, "-", 1);
1411 const char *slash_ptr
= strrchr(parent_pathname
.buf
, '/');
1412 slash_pos
= slash_ptr
? slash_ptr
- parent_pathname
.buf
: 0;
1415 if (hashmap_contains_path(&pl
->recursive_hashmap
,
1416 &parent_pathname
)) {
1417 result
= MATCHED_RECURSIVE
;
1422 /* include every file in root */
1427 strbuf_setlen(&parent_pathname
, slash_pos
);
1429 if (hashmap_contains_path(&pl
->parent_hashmap
, &parent_pathname
)) {
1434 if (hashmap_contains_parent(&pl
->recursive_hashmap
,
1437 result
= MATCHED_RECURSIVE
;
1440 strbuf_release(&parent_pathname
);
1444 int init_sparse_checkout_patterns(struct index_state
*istate
)
1446 if (!core_apply_sparse_checkout
)
1448 if (istate
->sparse_checkout_patterns
)
1451 CALLOC_ARRAY(istate
->sparse_checkout_patterns
, 1);
1453 if (get_sparse_checkout_patterns(istate
->sparse_checkout_patterns
) < 0) {
1454 FREE_AND_NULL(istate
->sparse_checkout_patterns
);
1461 static int path_in_sparse_checkout_1(const char *path
,
1462 struct index_state
*istate
,
1463 int require_cone_mode
)
1466 enum pattern_match_result match
= UNDECIDED
;
1467 const char *end
, *slash
;
1470 * We default to accepting a path if the path is empty, there are no
1471 * patterns, or the patterns are of the wrong type.
1474 init_sparse_checkout_patterns(istate
) ||
1475 (require_cone_mode
&&
1476 !istate
->sparse_checkout_patterns
->use_cone_patterns
))
1480 * If UNDECIDED, use the match from the parent dir (recursively), or
1481 * fall back to NOT_MATCHED at the topmost level. Note that cone mode
1482 * never returns UNDECIDED, so we will execute only one iteration in
1485 for (end
= path
+ strlen(path
);
1486 end
> path
&& match
== UNDECIDED
;
1489 for (slash
= end
- 1; slash
> path
&& *slash
!= '/'; slash
--)
1492 match
= path_matches_pattern_list(path
, end
- path
,
1493 slash
> path
? slash
+ 1 : path
, &dtype
,
1494 istate
->sparse_checkout_patterns
, istate
);
1496 /* We are going to match the parent dir now */
1502 int path_in_sparse_checkout(const char *path
,
1503 struct index_state
*istate
)
1505 return path_in_sparse_checkout_1(path
, istate
, 0);
1508 int path_in_cone_mode_sparse_checkout(const char *path
,
1509 struct index_state
*istate
)
1511 return path_in_sparse_checkout_1(path
, istate
, 1);
1514 static struct path_pattern
*last_matching_pattern_from_lists(
1515 struct dir_struct
*dir
, struct index_state
*istate
,
1516 const char *pathname
, int pathlen
,
1517 const char *basename
, int *dtype_p
)
1520 struct exclude_list_group
*group
;
1521 struct path_pattern
*pattern
;
1522 for (i
= EXC_CMDL
; i
<= EXC_FILE
; i
++) {
1523 group
= &dir
->internal
.exclude_list_group
[i
];
1524 for (j
= group
->nr
- 1; j
>= 0; j
--) {
1525 pattern
= last_matching_pattern_from_list(
1526 pathname
, pathlen
, basename
, dtype_p
,
1527 &group
->pl
[j
], istate
);
1536 * Loads the per-directory exclude list for the substring of base
1537 * which has a char length of baselen.
1539 static void prep_exclude(struct dir_struct
*dir
,
1540 struct index_state
*istate
,
1541 const char *base
, int baselen
)
1543 struct exclude_list_group
*group
;
1544 struct pattern_list
*pl
;
1545 struct exclude_stack
*stk
= NULL
;
1546 struct untracked_cache_dir
*untracked
;
1549 group
= &dir
->internal
.exclude_list_group
[EXC_DIRS
];
1552 * Pop the exclude lists from the EXCL_DIRS exclude_list_group
1553 * which originate from directories not in the prefix of the
1554 * path being checked.
1556 while ((stk
= dir
->internal
.exclude_stack
) != NULL
) {
1557 if (stk
->baselen
<= baselen
&&
1558 !strncmp(dir
->internal
.basebuf
.buf
, base
, stk
->baselen
))
1560 pl
= &group
->pl
[dir
->internal
.exclude_stack
->exclude_ix
];
1561 dir
->internal
.exclude_stack
= stk
->prev
;
1562 dir
->internal
.pattern
= NULL
;
1563 free((char *)pl
->src
); /* see strbuf_detach() below */
1564 clear_pattern_list(pl
);
1569 /* Skip traversing into sub directories if the parent is excluded */
1570 if (dir
->internal
.pattern
)
1574 * Lazy initialization. All call sites currently just
1575 * memset(dir, 0, sizeof(*dir)) before use. Changing all of
1576 * them seems lots of work for little benefit.
1578 if (!dir
->internal
.basebuf
.buf
)
1579 strbuf_init(&dir
->internal
.basebuf
, PATH_MAX
);
1581 /* Read from the parent directories and push them down. */
1582 current
= stk
? stk
->baselen
: -1;
1583 strbuf_setlen(&dir
->internal
.basebuf
, current
< 0 ? 0 : current
);
1585 untracked
= stk
? stk
->ucd
: dir
->untracked
->root
;
1589 while (current
< baselen
) {
1591 struct oid_stat oid_stat
;
1593 CALLOC_ARRAY(stk
, 1);
1598 cp
= strchr(base
+ current
+ 1, '/');
1600 die("oops in prep_exclude");
1603 lookup_untracked(dir
->untracked
,
1606 cp
- base
- current
);
1608 stk
->prev
= dir
->internal
.exclude_stack
;
1609 stk
->baselen
= cp
- base
;
1610 stk
->exclude_ix
= group
->nr
;
1611 stk
->ucd
= untracked
;
1612 pl
= add_pattern_list(dir
, EXC_DIRS
, NULL
);
1613 strbuf_add(&dir
->internal
.basebuf
, base
+ current
, stk
->baselen
- current
);
1614 assert(stk
->baselen
== dir
->internal
.basebuf
.len
);
1616 /* Abort if the directory is excluded */
1619 dir
->internal
.basebuf
.buf
[stk
->baselen
- 1] = 0;
1620 dir
->internal
.pattern
= last_matching_pattern_from_lists(dir
,
1622 dir
->internal
.basebuf
.buf
, stk
->baselen
- 1,
1623 dir
->internal
.basebuf
.buf
+ current
, &dt
);
1624 dir
->internal
.basebuf
.buf
[stk
->baselen
- 1] = '/';
1625 if (dir
->internal
.pattern
&&
1626 dir
->internal
.pattern
->flags
& PATTERN_FLAG_NEGATIVE
)
1627 dir
->internal
.pattern
= NULL
;
1628 if (dir
->internal
.pattern
) {
1629 dir
->internal
.exclude_stack
= stk
;
1634 /* Try to read per-directory file */
1635 oidclr(&oid_stat
.oid
);
1637 if (dir
->exclude_per_dir
&&
1639 * If we know that no files have been added in
1640 * this directory (i.e. valid_cached_dir() has
1641 * been executed and set untracked->valid) ..
1643 (!untracked
|| !untracked
->valid
||
1645 * .. and .gitignore does not exist before
1646 * (i.e. null exclude_oid). Then we can skip
1647 * loading .gitignore, which would result in
1650 !is_null_oid(&untracked
->exclude_oid
))) {
1652 * dir->internal.basebuf gets reused by the traversal,
1653 * but we need fname to remain unchanged to ensure the
1654 * src member of each struct path_pattern correctly
1655 * back-references its source file. Other invocations
1656 * of add_pattern_list provide stable strings, so we
1657 * strbuf_detach() and free() here in the caller.
1659 struct strbuf sb
= STRBUF_INIT
;
1660 strbuf_addbuf(&sb
, &dir
->internal
.basebuf
);
1661 strbuf_addstr(&sb
, dir
->exclude_per_dir
);
1662 pl
->src
= strbuf_detach(&sb
, NULL
);
1663 add_patterns(pl
->src
, pl
->src
, stk
->baselen
, pl
, istate
,
1665 untracked
? &oid_stat
: NULL
);
1668 * NEEDSWORK: when untracked cache is enabled, prep_exclude()
1669 * will first be called in valid_cached_dir() then maybe many
1670 * times more in last_matching_pattern(). When the cache is
1671 * used, last_matching_pattern() will not be called and
1672 * reading .gitignore content will be a waste.
1674 * So when it's called by valid_cached_dir() and we can get
1675 * .gitignore SHA-1 from the index (i.e. .gitignore is not
1676 * modified on work tree), we could delay reading the
1677 * .gitignore content until we absolutely need it in
1678 * last_matching_pattern(). Be careful about ignore rule
1679 * order, though, if you do that.
1682 !oideq(&oid_stat
.oid
, &untracked
->exclude_oid
)) {
1683 invalidate_gitignore(dir
->untracked
, untracked
);
1684 oidcpy(&untracked
->exclude_oid
, &oid_stat
.oid
);
1686 dir
->internal
.exclude_stack
= stk
;
1687 current
= stk
->baselen
;
1689 strbuf_setlen(&dir
->internal
.basebuf
, baselen
);
1693 * Loads the exclude lists for the directory containing pathname, then
1694 * scans all exclude lists to determine whether pathname is excluded.
1695 * Returns the exclude_list element which matched, or NULL for
1698 struct path_pattern
*last_matching_pattern(struct dir_struct
*dir
,
1699 struct index_state
*istate
,
1700 const char *pathname
,
1703 int pathlen
= strlen(pathname
);
1704 const char *basename
= strrchr(pathname
, '/');
1705 basename
= (basename
) ? basename
+1 : pathname
;
1707 prep_exclude(dir
, istate
, pathname
, basename
-pathname
);
1709 if (dir
->internal
.pattern
)
1710 return dir
->internal
.pattern
;
1712 return last_matching_pattern_from_lists(dir
, istate
, pathname
, pathlen
,
1717 * Loads the exclude lists for the directory containing pathname, then
1718 * scans all exclude lists to determine whether pathname is excluded.
1719 * Returns 1 if true, otherwise 0.
1721 int is_excluded(struct dir_struct
*dir
, struct index_state
*istate
,
1722 const char *pathname
, int *dtype_p
)
1724 struct path_pattern
*pattern
=
1725 last_matching_pattern(dir
, istate
, pathname
, dtype_p
);
1727 return pattern
->flags
& PATTERN_FLAG_NEGATIVE
? 0 : 1;
1731 static struct dir_entry
*dir_entry_new(const char *pathname
, int len
)
1733 struct dir_entry
*ent
;
1735 FLEX_ALLOC_MEM(ent
, name
, pathname
, len
);
1740 static struct dir_entry
*dir_add_name(struct dir_struct
*dir
,
1741 struct index_state
*istate
,
1742 const char *pathname
, int len
)
1744 if (index_file_exists(istate
, pathname
, len
, ignore_case
))
1747 ALLOC_GROW(dir
->entries
, dir
->nr
+1, dir
->internal
.alloc
);
1748 return dir
->entries
[dir
->nr
++] = dir_entry_new(pathname
, len
);
1751 struct dir_entry
*dir_add_ignored(struct dir_struct
*dir
,
1752 struct index_state
*istate
,
1753 const char *pathname
, int len
)
1755 if (!index_name_is_other(istate
, pathname
, len
))
1758 ALLOC_GROW(dir
->ignored
, dir
->ignored_nr
+1, dir
->internal
.ignored_alloc
);
1759 return dir
->ignored
[dir
->ignored_nr
++] = dir_entry_new(pathname
, len
);
1763 index_nonexistent
= 0,
1769 * Do not use the alphabetically sorted index to look up
1770 * the directory name; instead, use the case insensitive
1773 static enum exist_status
directory_exists_in_index_icase(struct index_state
*istate
,
1774 const char *dirname
, int len
)
1776 struct cache_entry
*ce
;
1778 if (index_dir_exists(istate
, dirname
, len
))
1779 return index_directory
;
1781 ce
= index_file_exists(istate
, dirname
, len
, ignore_case
);
1782 if (ce
&& S_ISGITLINK(ce
->ce_mode
))
1783 return index_gitdir
;
1785 return index_nonexistent
;
1789 * The index sorts alphabetically by entry name, which
1790 * means that a gitlink sorts as '\0' at the end, while
1791 * a directory (which is defined not as an entry, but as
1792 * the files it contains) will sort with the '/' at the
1795 static enum exist_status
directory_exists_in_index(struct index_state
*istate
,
1796 const char *dirname
, int len
)
1801 return directory_exists_in_index_icase(istate
, dirname
, len
);
1803 pos
= index_name_pos(istate
, dirname
, len
);
1806 while (pos
< istate
->cache_nr
) {
1807 const struct cache_entry
*ce
= istate
->cache
[pos
++];
1808 unsigned char endchar
;
1810 if (strncmp(ce
->name
, dirname
, len
))
1812 endchar
= ce
->name
[len
];
1816 return index_directory
;
1817 if (!endchar
&& S_ISGITLINK(ce
->ce_mode
))
1818 return index_gitdir
;
1820 return index_nonexistent
;
1824 * When we find a directory when traversing the filesystem, we
1825 * have three distinct cases:
1828 * - see it as a directory
1831 * and which one we choose depends on a combination of existing
1832 * git index contents and the flags passed into the directory
1833 * traversal routine.
1835 * Case 1: If we *already* have entries in the index under that
1836 * directory name, we always recurse into the directory to see
1839 * Case 2: If we *already* have that directory name as a gitlink,
1840 * we always continue to see it as a gitlink, regardless of whether
1841 * there is an actual git directory there or not (it might not
1842 * be checked out as a subproject!)
1844 * Case 3: if we didn't have it in the index previously, we
1845 * have a few sub-cases:
1847 * (a) if DIR_SHOW_OTHER_DIRECTORIES flag is set, we show it as
1848 * just a directory, unless DIR_HIDE_EMPTY_DIRECTORIES is
1849 * also true, in which case we need to check if it contains any
1850 * untracked and / or ignored files.
1851 * (b) if it looks like a git directory and we don't have the
1852 * DIR_NO_GITLINKS flag, then we treat it as a gitlink, and
1853 * show it as a directory.
1854 * (c) otherwise, we recurse into it.
1856 static enum path_treatment
treat_directory(struct dir_struct
*dir
,
1857 struct index_state
*istate
,
1858 struct untracked_cache_dir
*untracked
,
1859 const char *dirname
, int len
, int baselen
, int excluded
,
1860 const struct pathspec
*pathspec
)
1863 * WARNING: From this function, you can return path_recurse or you
1864 * can call read_directory_recursive() (or neither), but
1865 * you CAN'T DO BOTH.
1867 enum path_treatment state
;
1868 int matches_how
= 0;
1869 int check_only
, stop_early
;
1870 int old_ignored_nr
, old_untracked_nr
;
1871 /* The "len-1" is to strip the final '/' */
1872 enum exist_status status
= directory_exists_in_index(istate
, dirname
, len
-1);
1874 if (status
== index_directory
)
1875 return path_recurse
;
1876 if (status
== index_gitdir
)
1878 if (status
!= index_nonexistent
)
1879 BUG("Unhandled value for directory_exists_in_index: %d\n", status
);
1882 * We don't want to descend into paths that don't match the necessary
1883 * patterns. Clearly, if we don't have a pathspec, then we can't check
1884 * for matching patterns. Also, if (excluded) then we know we matched
1885 * the exclusion patterns so as an optimization we can skip checking
1886 * for matching patterns.
1888 if (pathspec
&& !excluded
) {
1889 matches_how
= match_pathspec_with_flags(istate
, pathspec
,
1893 DO_MATCH_LEADING_PATHSPEC
);
1899 if ((dir
->flags
& DIR_SKIP_NESTED_GIT
) ||
1900 !(dir
->flags
& DIR_NO_GITLINKS
)) {
1902 * Determine if `dirname` is a nested repo by confirming that:
1903 * 1) we are in a nonbare repository, and
1904 * 2) `dirname` is not an immediate parent of `the_repository->gitdir`,
1905 * which could occur if the git_dir or worktree location was
1906 * manually configured by the user; see t2205 testcases 1-3 for
1907 * examples where this matters
1910 struct strbuf sb
= STRBUF_INIT
;
1911 strbuf_addstr(&sb
, dirname
);
1912 nested_repo
= is_nonbare_repository_dir(&sb
);
1915 char *real_dirname
, *real_gitdir
;
1916 strbuf_addstr(&sb
, ".git");
1917 real_dirname
= real_pathdup(sb
.buf
, 1);
1918 real_gitdir
= real_pathdup(the_repository
->gitdir
, 1);
1920 nested_repo
= !!strcmp(real_dirname
, real_gitdir
);
1924 strbuf_release(&sb
);
1927 if ((dir
->flags
& DIR_SKIP_NESTED_GIT
) ||
1928 (matches_how
== MATCHED_RECURSIVELY_LEADING_PATHSPEC
))
1930 return excluded
? path_excluded
: path_untracked
;
1934 if (!(dir
->flags
& DIR_SHOW_OTHER_DIRECTORIES
)) {
1936 (dir
->flags
& DIR_SHOW_IGNORED_TOO
) &&
1937 (dir
->flags
& DIR_SHOW_IGNORED_TOO_MODE_MATCHING
)) {
1940 * This is an excluded directory and we are
1941 * showing ignored paths that match an exclude
1942 * pattern. (e.g. show directory as ignored
1943 * only if it matches an exclude pattern).
1944 * This path will either be 'path_excluded`
1945 * (if we are showing empty directories or if
1946 * the directory is not empty), or will be
1947 * 'path_none' (empty directory, and we are
1948 * not showing empty directories).
1950 if (!(dir
->flags
& DIR_HIDE_EMPTY_DIRECTORIES
))
1951 return path_excluded
;
1953 if (read_directory_recursive(dir
, istate
, dirname
, len
,
1954 untracked
, 1, 1, pathspec
) == path_excluded
)
1955 return path_excluded
;
1959 return path_recurse
;
1962 assert(dir
->flags
& DIR_SHOW_OTHER_DIRECTORIES
);
1965 * If we have a pathspec which could match something _below_ this
1966 * directory (e.g. when checking 'subdir/' having a pathspec like
1967 * 'subdir/some/deep/path/file' or 'subdir/widget-*.c'), then we
1970 if (matches_how
== MATCHED_RECURSIVELY_LEADING_PATHSPEC
)
1971 return path_recurse
;
1973 /* Special cases for where this directory is excluded/ignored */
1976 * If DIR_SHOW_OTHER_DIRECTORIES is set and we're not
1977 * hiding empty directories, there is no need to
1978 * recurse into an ignored directory.
1980 if (!(dir
->flags
& DIR_HIDE_EMPTY_DIRECTORIES
))
1981 return path_excluded
;
1984 * Even if we are hiding empty directories, we can still avoid
1985 * recursing into ignored directories for DIR_SHOW_IGNORED_TOO
1986 * if DIR_SHOW_IGNORED_TOO_MODE_MATCHING is also set.
1988 if ((dir
->flags
& DIR_SHOW_IGNORED_TOO
) &&
1989 (dir
->flags
& DIR_SHOW_IGNORED_TOO_MODE_MATCHING
))
1990 return path_excluded
;
1994 * Other than the path_recurse case above, we only need to
1995 * recurse into untracked directories if any of the following
1997 * - DIR_SHOW_IGNORED (because then we need to determine if
1998 * there are ignored entries below)
1999 * - DIR_SHOW_IGNORED_TOO (same as above)
2000 * - DIR_HIDE_EMPTY_DIRECTORIES (because we have to determine if
2001 * the directory is empty)
2004 !(dir
->flags
& (DIR_SHOW_IGNORED
|
2005 DIR_SHOW_IGNORED_TOO
|
2006 DIR_HIDE_EMPTY_DIRECTORIES
))) {
2007 return path_untracked
;
2011 * Even if we don't want to know all the paths under an untracked or
2012 * ignored directory, we may still need to go into the directory to
2013 * determine if it is empty (because with DIR_HIDE_EMPTY_DIRECTORIES,
2014 * an empty directory should be path_none instead of path_excluded or
2017 check_only
= ((dir
->flags
& DIR_HIDE_EMPTY_DIRECTORIES
) &&
2018 !(dir
->flags
& DIR_SHOW_IGNORED_TOO
));
2021 * However, there's another optimization possible as a subset of
2022 * check_only, based on the cases we have to consider:
2023 * A) Directory matches no exclude patterns:
2024 * * Directory is empty => path_none
2025 * * Directory has an untracked file under it => path_untracked
2026 * * Directory has only ignored files under it => path_excluded
2027 * B) Directory matches an exclude pattern:
2028 * * Directory is empty => path_none
2029 * * Directory has an untracked file under it => path_excluded
2030 * * Directory has only ignored files under it => path_excluded
2031 * In case A, we can exit as soon as we've found an untracked
2032 * file but otherwise have to walk all files. In case B, though,
2033 * we can stop at the first file we find under the directory.
2035 stop_early
= check_only
&& excluded
;
2038 * If /every/ file within an untracked directory is ignored, then
2039 * we want to treat the directory as ignored (for e.g. status
2040 * --porcelain), without listing the individual ignored files
2041 * underneath. To do so, we'll save the current ignored_nr, and
2042 * pop all the ones added after it if it turns out the entire
2043 * directory is ignored. Also, when DIR_SHOW_IGNORED_TOO and
2044 * !DIR_KEEP_UNTRACKED_CONTENTS then we don't want to show
2045 * untracked paths so will need to pop all those off the last
2046 * after we traverse.
2048 old_ignored_nr
= dir
->ignored_nr
;
2049 old_untracked_nr
= dir
->nr
;
2051 /* Actually recurse into dirname now, we'll fixup the state later. */
2052 untracked
= lookup_untracked(dir
->untracked
, untracked
,
2053 dirname
+ baselen
, len
- baselen
);
2054 state
= read_directory_recursive(dir
, istate
, dirname
, len
, untracked
,
2055 check_only
, stop_early
, pathspec
);
2057 /* There are a variety of reasons we may need to fixup the state... */
2058 if (state
== path_excluded
) {
2059 /* state == path_excluded implies all paths under
2060 * dirname were ignored...
2062 * if running e.g. `git status --porcelain --ignored=matching`,
2063 * then we want to see the subpaths that are ignored.
2065 * if running e.g. just `git status --porcelain`, then
2066 * we just want the directory itself to be listed as ignored
2067 * and not the individual paths underneath.
2069 int want_ignored_subpaths
=
2070 ((dir
->flags
& DIR_SHOW_IGNORED_TOO
) &&
2071 (dir
->flags
& DIR_SHOW_IGNORED_TOO_MODE_MATCHING
));
2073 if (want_ignored_subpaths
) {
2075 * with --ignored=matching, we want the subpaths
2076 * INSTEAD of the directory itself.
2081 for (i
= old_ignored_nr
+ 1; i
<dir
->ignored_nr
; ++i
)
2082 FREE_AND_NULL(dir
->ignored
[i
]);
2083 dir
->ignored_nr
= old_ignored_nr
;
2088 * We may need to ignore some of the untracked paths we found while
2089 * traversing subdirectories.
2091 if ((dir
->flags
& DIR_SHOW_IGNORED_TOO
) &&
2092 !(dir
->flags
& DIR_KEEP_UNTRACKED_CONTENTS
)) {
2094 for (i
= old_untracked_nr
+ 1; i
<dir
->nr
; ++i
)
2095 FREE_AND_NULL(dir
->entries
[i
]);
2096 dir
->nr
= old_untracked_nr
;
2100 * If there is nothing under the current directory and we are not
2101 * hiding empty directories, then we need to report on the
2102 * untracked or ignored status of the directory itself.
2104 if (state
== path_none
&& !(dir
->flags
& DIR_HIDE_EMPTY_DIRECTORIES
))
2105 state
= excluded
? path_excluded
: path_untracked
;
2111 * This is an inexact early pruning of any recursive directory
2112 * reading - if the path cannot possibly be in the pathspec,
2113 * return true, and we'll skip it early.
2115 static int simplify_away(const char *path
, int pathlen
,
2116 const struct pathspec
*pathspec
)
2120 if (!pathspec
|| !pathspec
->nr
)
2123 GUARD_PATHSPEC(pathspec
,
2132 for (i
= 0; i
< pathspec
->nr
; i
++) {
2133 const struct pathspec_item
*item
= &pathspec
->items
[i
];
2134 int len
= item
->nowildcard_len
;
2138 if (!ps_strncmp(item
, item
->match
, path
, len
))
2146 * This function tells us whether an excluded path matches a
2147 * list of "interesting" pathspecs. That is, whether a path matched
2148 * by any of the pathspecs could possibly be ignored by excluding
2149 * the specified path. This can happen if:
2151 * 1. the path is mentioned explicitly in the pathspec
2153 * 2. the path is a directory prefix of some element in the
2156 static int exclude_matches_pathspec(const char *path
, int pathlen
,
2157 const struct pathspec
*pathspec
)
2161 if (!pathspec
|| !pathspec
->nr
)
2164 GUARD_PATHSPEC(pathspec
,
2172 for (i
= 0; i
< pathspec
->nr
; i
++) {
2173 const struct pathspec_item
*item
= &pathspec
->items
[i
];
2174 int len
= item
->nowildcard_len
;
2176 if (len
== pathlen
&&
2177 !ps_strncmp(item
, item
->match
, path
, pathlen
))
2179 if (len
> pathlen
&&
2180 item
->match
[pathlen
] == '/' &&
2181 !ps_strncmp(item
, item
->match
, path
, pathlen
))
2187 static int get_index_dtype(struct index_state
*istate
,
2188 const char *path
, int len
)
2191 const struct cache_entry
*ce
;
2193 ce
= index_file_exists(istate
, path
, len
, 0);
2195 if (!ce_uptodate(ce
))
2197 if (S_ISGITLINK(ce
->ce_mode
))
2200 * Nobody actually cares about the
2201 * difference between DT_LNK and DT_REG
2206 /* Try to look it up as a directory */
2207 pos
= index_name_pos(istate
, path
, len
);
2211 while (pos
< istate
->cache_nr
) {
2212 ce
= istate
->cache
[pos
++];
2213 if (strncmp(ce
->name
, path
, len
))
2215 if (ce
->name
[len
] > '/')
2217 if (ce
->name
[len
] < '/')
2219 if (!ce_uptodate(ce
))
2220 break; /* continue? */
2226 static int resolve_dtype(int dtype
, struct index_state
*istate
,
2227 const char *path
, int len
)
2231 if (dtype
!= DT_UNKNOWN
)
2233 dtype
= get_index_dtype(istate
, path
, len
);
2234 if (dtype
!= DT_UNKNOWN
)
2236 if (lstat(path
, &st
))
2238 if (S_ISREG(st
.st_mode
))
2240 if (S_ISDIR(st
.st_mode
))
2242 if (S_ISLNK(st
.st_mode
))
2247 static enum path_treatment
treat_path_fast(struct dir_struct
*dir
,
2248 struct cached_dir
*cdir
,
2249 struct index_state
*istate
,
2250 struct strbuf
*path
,
2252 const struct pathspec
*pathspec
)
2255 * WARNING: From this function, you can return path_recurse or you
2256 * can call read_directory_recursive() (or neither), but
2257 * you CAN'T DO BOTH.
2259 strbuf_setlen(path
, baselen
);
2261 strbuf_addstr(path
, cdir
->file
);
2262 return path_untracked
;
2264 strbuf_addstr(path
, cdir
->ucd
->name
);
2265 /* treat_one_path() does this before it calls treat_directory() */
2266 strbuf_complete(path
, '/');
2267 if (cdir
->ucd
->check_only
)
2269 * check_only is set as a result of treat_directory() getting
2270 * to its bottom. Verify again the same set of directories
2271 * with check_only set.
2273 return read_directory_recursive(dir
, istate
, path
->buf
, path
->len
,
2274 cdir
->ucd
, 1, 0, pathspec
);
2276 * We get path_recurse in the first run when
2277 * directory_exists_in_index() returns index_nonexistent. We
2278 * are sure that new changes in the index does not impact the
2279 * outcome. Return now.
2281 return path_recurse
;
2284 static enum path_treatment
treat_path(struct dir_struct
*dir
,
2285 struct untracked_cache_dir
*untracked
,
2286 struct cached_dir
*cdir
,
2287 struct index_state
*istate
,
2288 struct strbuf
*path
,
2290 const struct pathspec
*pathspec
)
2292 int has_path_in_index
, dtype
, excluded
;
2295 return treat_path_fast(dir
, cdir
, istate
, path
,
2297 if (is_dot_or_dotdot(cdir
->d_name
) || !fspathcmp(cdir
->d_name
, ".git"))
2299 strbuf_setlen(path
, baselen
);
2300 strbuf_addstr(path
, cdir
->d_name
);
2301 if (simplify_away(path
->buf
, path
->len
, pathspec
))
2304 dtype
= resolve_dtype(cdir
->d_type
, istate
, path
->buf
, path
->len
);
2306 /* Always exclude indexed files */
2307 has_path_in_index
= !!index_file_exists(istate
, path
->buf
, path
->len
,
2309 if (dtype
!= DT_DIR
&& has_path_in_index
)
2313 * When we are looking at a directory P in the working tree,
2314 * there are three cases:
2316 * (1) P exists in the index. Everything inside the directory P in
2317 * the working tree needs to go when P is checked out from the
2320 * (2) P does not exist in the index, but there is P/Q in the index.
2321 * We know P will stay a directory when we check out the contents
2322 * of the index, but we do not know yet if there is a directory
2323 * P/Q in the working tree to be killed, so we need to recurse.
2325 * (3) P does not exist in the index, and there is no P/Q in the index
2326 * to require P to be a directory, either. Only in this case, we
2327 * know that everything inside P will not be killed without
2330 if ((dir
->flags
& DIR_COLLECT_KILLED_ONLY
) &&
2331 (dtype
== DT_DIR
) &&
2332 !has_path_in_index
&&
2333 (directory_exists_in_index(istate
, path
->buf
, path
->len
) == index_nonexistent
))
2336 excluded
= is_excluded(dir
, istate
, path
->buf
, &dtype
);
2339 * Excluded? If we don't explicitly want to show
2340 * ignored files, ignore it
2342 if (excluded
&& !(dir
->flags
& (DIR_SHOW_IGNORED
|DIR_SHOW_IGNORED_TOO
)))
2343 return path_excluded
;
2350 * WARNING: Do not ignore/amend the return value from
2351 * treat_directory(), and especially do not change it to return
2352 * path_recurse as that can cause exponential slowdown.
2353 * Instead, modify treat_directory() to return the right value.
2355 strbuf_addch(path
, '/');
2356 return treat_directory(dir
, istate
, untracked
,
2357 path
->buf
, path
->len
,
2358 baselen
, excluded
, pathspec
);
2362 !match_pathspec(istate
, pathspec
, path
->buf
, path
->len
,
2363 0 /* prefix */, NULL
/* seen */,
2367 return path_excluded
;
2368 return path_untracked
;
2372 static void add_untracked(struct untracked_cache_dir
*dir
, const char *name
)
2376 ALLOC_GROW(dir
->untracked
, dir
->untracked_nr
+ 1,
2377 dir
->untracked_alloc
);
2378 dir
->untracked
[dir
->untracked_nr
++] = xstrdup(name
);
2381 static int valid_cached_dir(struct dir_struct
*dir
,
2382 struct untracked_cache_dir
*untracked
,
2383 struct index_state
*istate
,
2384 struct strbuf
*path
,
2393 * With fsmonitor, we can trust the untracked cache's valid field.
2395 refresh_fsmonitor(istate
);
2396 if (!(dir
->untracked
->use_fsmonitor
&& untracked
->valid
)) {
2397 if (lstat(path
->len
? path
->buf
: ".", &st
)) {
2398 memset(&untracked
->stat_data
, 0, sizeof(untracked
->stat_data
));
2401 if (!untracked
->valid
||
2402 match_stat_data_racy(istate
, &untracked
->stat_data
, &st
)) {
2403 fill_stat_data(&untracked
->stat_data
, &st
);
2408 if (untracked
->check_only
!= !!check_only
)
2412 * prep_exclude will be called eventually on this directory,
2413 * but it's called much later in last_matching_pattern(). We
2414 * need it now to determine the validity of the cache for this
2415 * path. The next calls will be nearly no-op, the way
2416 * prep_exclude() is designed.
2418 if (path
->len
&& path
->buf
[path
->len
- 1] != '/') {
2419 strbuf_addch(path
, '/');
2420 prep_exclude(dir
, istate
, path
->buf
, path
->len
);
2421 strbuf_setlen(path
, path
->len
- 1);
2423 prep_exclude(dir
, istate
, path
->buf
, path
->len
);
2425 /* hopefully prep_exclude() haven't invalidated this entry... */
2426 return untracked
->valid
;
2429 static int open_cached_dir(struct cached_dir
*cdir
,
2430 struct dir_struct
*dir
,
2431 struct untracked_cache_dir
*untracked
,
2432 struct index_state
*istate
,
2433 struct strbuf
*path
,
2438 memset(cdir
, 0, sizeof(*cdir
));
2439 cdir
->untracked
= untracked
;
2440 if (valid_cached_dir(dir
, untracked
, istate
, path
, check_only
))
2442 c_path
= path
->len
? path
->buf
: ".";
2443 cdir
->fdir
= opendir(c_path
);
2445 warning_errno(_("could not open directory '%s'"), c_path
);
2446 if (dir
->untracked
) {
2447 invalidate_directory(dir
->untracked
, untracked
);
2448 dir
->untracked
->dir_opened
++;
2455 static int read_cached_dir(struct cached_dir
*cdir
)
2460 de
= readdir_skip_dot_and_dotdot(cdir
->fdir
);
2462 cdir
->d_name
= NULL
;
2463 cdir
->d_type
= DT_UNKNOWN
;
2466 cdir
->d_name
= de
->d_name
;
2467 cdir
->d_type
= DTYPE(de
);
2470 while (cdir
->nr_dirs
< cdir
->untracked
->dirs_nr
) {
2471 struct untracked_cache_dir
*d
= cdir
->untracked
->dirs
[cdir
->nr_dirs
];
2481 if (cdir
->nr_files
< cdir
->untracked
->untracked_nr
) {
2482 struct untracked_cache_dir
*d
= cdir
->untracked
;
2483 cdir
->file
= d
->untracked
[cdir
->nr_files
++];
2489 static void close_cached_dir(struct cached_dir
*cdir
)
2492 closedir(cdir
->fdir
);
2494 * We have gone through this directory and found no untracked
2495 * entries. Mark it valid.
2497 if (cdir
->untracked
) {
2498 cdir
->untracked
->valid
= 1;
2499 cdir
->untracked
->recurse
= 1;
2503 static void add_path_to_appropriate_result_list(struct dir_struct
*dir
,
2504 struct untracked_cache_dir
*untracked
,
2505 struct cached_dir
*cdir
,
2506 struct index_state
*istate
,
2507 struct strbuf
*path
,
2509 const struct pathspec
*pathspec
,
2510 enum path_treatment state
)
2512 /* add the path to the appropriate result list */
2515 if (dir
->flags
& DIR_SHOW_IGNORED
)
2516 dir_add_name(dir
, istate
, path
->buf
, path
->len
);
2517 else if ((dir
->flags
& DIR_SHOW_IGNORED_TOO
) ||
2518 ((dir
->flags
& DIR_COLLECT_IGNORED
) &&
2519 exclude_matches_pathspec(path
->buf
, path
->len
,
2521 dir_add_ignored(dir
, istate
, path
->buf
, path
->len
);
2524 case path_untracked
:
2525 if (dir
->flags
& DIR_SHOW_IGNORED
)
2527 dir_add_name(dir
, istate
, path
->buf
, path
->len
);
2529 add_untracked(untracked
, path
->buf
+ baselen
);
2538 * Read a directory tree. We currently ignore anything but
2539 * directories, regular files and symlinks. That's because git
2540 * doesn't handle them at all yet. Maybe that will change some
2543 * Also, we ignore the name ".git" (even if it is not a directory).
2544 * That likely will not change.
2546 * If 'stop_at_first_file' is specified, 'path_excluded' is returned
2547 * to signal that a file was found. This is the least significant value that
2548 * indicates that a file was encountered that does not depend on the order of
2549 * whether an untracked or excluded path was encountered first.
2551 * Returns the most significant path_treatment value encountered in the scan.
2552 * If 'stop_at_first_file' is specified, `path_excluded` is the most
2553 * significant path_treatment value that will be returned.
2556 static enum path_treatment
read_directory_recursive(struct dir_struct
*dir
,
2557 struct index_state
*istate
, const char *base
, int baselen
,
2558 struct untracked_cache_dir
*untracked
, int check_only
,
2559 int stop_at_first_file
, const struct pathspec
*pathspec
)
2562 * WARNING: Do NOT recurse unless path_recurse is returned from
2563 * treat_path(). Recursing on any other return value
2564 * can result in exponential slowdown.
2566 struct cached_dir cdir
;
2567 enum path_treatment state
, subdir_state
, dir_state
= path_none
;
2568 struct strbuf path
= STRBUF_INIT
;
2570 strbuf_add(&path
, base
, baselen
);
2572 if (open_cached_dir(&cdir
, dir
, untracked
, istate
, &path
, check_only
))
2574 dir
->internal
.visited_directories
++;
2577 untracked
->check_only
= !!check_only
;
2579 while (!read_cached_dir(&cdir
)) {
2580 /* check how the file or directory should be treated */
2581 state
= treat_path(dir
, untracked
, &cdir
, istate
, &path
,
2583 dir
->internal
.visited_paths
++;
2585 if (state
> dir_state
)
2588 /* recurse into subdir if instructed by treat_path */
2589 if (state
== path_recurse
) {
2590 struct untracked_cache_dir
*ud
;
2591 ud
= lookup_untracked(dir
->untracked
,
2594 path
.len
- baselen
);
2596 read_directory_recursive(dir
, istate
, path
.buf
,
2598 check_only
, stop_at_first_file
, pathspec
);
2599 if (subdir_state
> dir_state
)
2600 dir_state
= subdir_state
;
2603 !match_pathspec(istate
, pathspec
, path
.buf
, path
.len
,
2604 0 /* prefix */, NULL
,
2605 0 /* do NOT special case dirs */))
2610 if (stop_at_first_file
) {
2612 * If stopping at first file, then
2613 * signal that a file was found by
2614 * returning `path_excluded`. This is
2615 * to return a consistent value
2616 * regardless of whether an ignored or
2617 * excluded file happened to be
2620 * In current usage, the
2621 * `stop_at_first_file` is passed when
2622 * an ancestor directory has matched
2623 * an exclude pattern, so any found
2624 * files will be excluded.
2626 if (dir_state
>= path_excluded
) {
2627 dir_state
= path_excluded
;
2632 /* abort early if maximum state has been reached */
2633 if (dir_state
== path_untracked
) {
2635 add_untracked(untracked
, path
.buf
+ baselen
);
2638 /* skip the add_path_to_appropriate_result_list() */
2642 add_path_to_appropriate_result_list(dir
, untracked
, &cdir
,
2643 istate
, &path
, baselen
,
2646 close_cached_dir(&cdir
);
2648 strbuf_release(&path
);
2653 int cmp_dir_entry(const void *p1
, const void *p2
)
2655 const struct dir_entry
*e1
= *(const struct dir_entry
**)p1
;
2656 const struct dir_entry
*e2
= *(const struct dir_entry
**)p2
;
2658 return name_compare(e1
->name
, e1
->len
, e2
->name
, e2
->len
);
2661 /* check if *out lexically strictly contains *in */
2662 int check_dir_entry_contains(const struct dir_entry
*out
, const struct dir_entry
*in
)
2664 return (out
->len
< in
->len
) &&
2665 (out
->name
[out
->len
- 1] == '/') &&
2666 !memcmp(out
->name
, in
->name
, out
->len
);
2669 static int treat_leading_path(struct dir_struct
*dir
,
2670 struct index_state
*istate
,
2671 const char *path
, int len
,
2672 const struct pathspec
*pathspec
)
2674 struct strbuf sb
= STRBUF_INIT
;
2675 struct strbuf subdir
= STRBUF_INIT
;
2676 int prevlen
, baselen
;
2678 struct cached_dir cdir
;
2679 enum path_treatment state
= path_none
;
2682 * For each directory component of path, we are going to check whether
2683 * that path is relevant given the pathspec. For example, if path is
2685 * then we will ask treat_path() whether we should go into foo, then
2686 * whether we should go into bar, then whether baz is relevant.
2687 * Checking each is important because e.g. if path is
2689 * then we need to check .git to know we shouldn't traverse it.
2690 * If the return from treat_path() is:
2691 * * path_none, for any path, we return false.
2692 * * path_recurse, for all path components, we return true
2693 * * <anything else> for some intermediate component, we make sure
2694 * to add that path to the relevant list but return false
2695 * signifying that we shouldn't recurse into it.
2698 while (len
&& path
[len
- 1] == '/')
2703 memset(&cdir
, 0, sizeof(cdir
));
2704 cdir
.d_type
= DT_DIR
;
2708 prevlen
= baselen
+ !!baselen
;
2709 cp
= path
+ prevlen
;
2710 cp
= memchr(cp
, '/', path
+ len
- cp
);
2714 baselen
= cp
- path
;
2716 strbuf_add(&sb
, path
, baselen
);
2717 if (!is_directory(sb
.buf
))
2720 strbuf_add(&sb
, path
, prevlen
);
2721 strbuf_reset(&subdir
);
2722 strbuf_add(&subdir
, path
+prevlen
, baselen
-prevlen
);
2723 cdir
.d_name
= subdir
.buf
;
2724 state
= treat_path(dir
, NULL
, &cdir
, istate
, &sb
, prevlen
, pathspec
);
2726 if (state
!= path_recurse
)
2727 break; /* do not recurse into it */
2729 break; /* finished checking */
2731 add_path_to_appropriate_result_list(dir
, NULL
, &cdir
, istate
,
2732 &sb
, baselen
, pathspec
,
2735 strbuf_release(&subdir
);
2736 strbuf_release(&sb
);
2737 return state
== path_recurse
;
2740 static const char *get_ident_string(void)
2742 static struct strbuf sb
= STRBUF_INIT
;
2747 if (uname(&uts
) < 0)
2748 die_errno(_("failed to get kernel name and information"));
2749 strbuf_addf(&sb
, "Location %s, system %s", get_git_work_tree(),
2754 static int ident_in_untracked(const struct untracked_cache
*uc
)
2757 * Previous git versions may have saved many NUL separated
2758 * strings in the "ident" field, but it is insane to manage
2759 * many locations, so just take care of the first one.
2762 return !strcmp(uc
->ident
.buf
, get_ident_string());
2765 static void set_untracked_ident(struct untracked_cache
*uc
)
2767 strbuf_reset(&uc
->ident
);
2768 strbuf_addstr(&uc
->ident
, get_ident_string());
2771 * This strbuf used to contain a list of NUL separated
2772 * strings, so save NUL too for backward compatibility.
2774 strbuf_addch(&uc
->ident
, 0);
2777 static unsigned new_untracked_cache_flags(struct index_state
*istate
)
2779 struct repository
*repo
= istate
->repo
;
2783 * This logic is coordinated with the setting of these flags in
2784 * wt-status.c#wt_status_collect_untracked(), and the evaluation
2785 * of the config setting in commit.c#git_status_config()
2787 if (!repo_config_get_string(repo
, "status.showuntrackedfiles", &val
) &&
2788 !strcmp(val
, "all"))
2792 * The default, if "all" is not set, is "normal" - leading us here.
2793 * If the value is "none" then it really doesn't matter.
2795 return DIR_SHOW_OTHER_DIRECTORIES
| DIR_HIDE_EMPTY_DIRECTORIES
;
2798 static void new_untracked_cache(struct index_state
*istate
, int flags
)
2800 struct untracked_cache
*uc
= xcalloc(1, sizeof(*uc
));
2801 strbuf_init(&uc
->ident
, 100);
2802 uc
->exclude_per_dir
= ".gitignore";
2803 uc
->dir_flags
= flags
>= 0 ? flags
: new_untracked_cache_flags(istate
);
2804 set_untracked_ident(uc
);
2805 istate
->untracked
= uc
;
2806 istate
->cache_changed
|= UNTRACKED_CHANGED
;
2809 void add_untracked_cache(struct index_state
*istate
)
2811 if (!istate
->untracked
) {
2812 new_untracked_cache(istate
, -1);
2814 if (!ident_in_untracked(istate
->untracked
)) {
2815 free_untracked_cache(istate
->untracked
);
2816 new_untracked_cache(istate
, -1);
2821 void remove_untracked_cache(struct index_state
*istate
)
2823 if (istate
->untracked
) {
2824 free_untracked_cache(istate
->untracked
);
2825 istate
->untracked
= NULL
;
2826 istate
->cache_changed
|= UNTRACKED_CHANGED
;
2830 static struct untracked_cache_dir
*validate_untracked_cache(struct dir_struct
*dir
,
2832 const struct pathspec
*pathspec
,
2833 struct index_state
*istate
)
2835 struct untracked_cache_dir
*root
;
2836 static int untracked_cache_disabled
= -1;
2838 if (!dir
->untracked
)
2840 if (untracked_cache_disabled
< 0)
2841 untracked_cache_disabled
= git_env_bool("GIT_DISABLE_UNTRACKED_CACHE", 0);
2842 if (untracked_cache_disabled
)
2846 * We only support $GIT_DIR/info/exclude and core.excludesfile
2847 * as the global ignore rule files. Any other additions
2848 * (e.g. from command line) invalidate the cache. This
2849 * condition also catches running setup_standard_excludes()
2850 * before setting dir->untracked!
2852 if (dir
->internal
.unmanaged_exclude_files
)
2856 * Optimize for the main use case only: whole-tree git
2857 * status. More work involved in treat_leading_path() if we
2858 * use cache on just a subset of the worktree. pathspec
2859 * support could make the matter even worse.
2861 if (base_len
|| (pathspec
&& pathspec
->nr
))
2864 /* We don't support collecting ignore files */
2865 if (dir
->flags
& (DIR_SHOW_IGNORED
| DIR_SHOW_IGNORED_TOO
|
2866 DIR_COLLECT_IGNORED
))
2870 * If we use .gitignore in the cache and now you change it to
2871 * .gitexclude, everything will go wrong.
2873 if (dir
->exclude_per_dir
!= dir
->untracked
->exclude_per_dir
&&
2874 strcmp(dir
->exclude_per_dir
, dir
->untracked
->exclude_per_dir
))
2878 * EXC_CMDL is not considered in the cache. If people set it,
2881 if (dir
->internal
.exclude_list_group
[EXC_CMDL
].nr
)
2884 if (!ident_in_untracked(dir
->untracked
)) {
2885 warning(_("untracked cache is disabled on this system or location"));
2890 * If the untracked structure we received does not have the same flags
2891 * as requested in this run, we're going to need to either discard the
2892 * existing structure (and potentially later recreate), or bypass the
2893 * untracked cache mechanism for this run.
2895 if (dir
->flags
!= dir
->untracked
->dir_flags
) {
2897 * If the untracked structure we received does not have the same flags
2898 * as configured, then we need to reset / create a new "untracked"
2899 * structure to match the new config.
2901 * Keeping the saved and used untracked cache consistent with the
2902 * configuration provides an opportunity for frequent users of
2903 * "git status -uall" to leverage the untracked cache by aligning their
2904 * configuration - setting "status.showuntrackedfiles" to "all" or
2905 * "normal" as appropriate.
2907 * Previously using -uall (or setting "status.showuntrackedfiles" to
2908 * "all") was incompatible with untracked cache and *consistently*
2909 * caused surprisingly bad performance (with fscache and fsmonitor
2910 * enabled) on Windows.
2912 * IMPROVEMENT OPPORTUNITY: If we reworked the untracked cache storage
2913 * to not be as bound up with the desired output in a given run,
2914 * and instead iterated through and stored enough information to
2915 * correctly serve both "modes", then users could get peak performance
2916 * with or without '-uall' regardless of their
2917 * "status.showuntrackedfiles" config.
2919 if (dir
->untracked
->dir_flags
!= new_untracked_cache_flags(istate
)) {
2920 free_untracked_cache(istate
->untracked
);
2921 new_untracked_cache(istate
, dir
->flags
);
2922 dir
->untracked
= istate
->untracked
;
2926 * Current untracked cache data is consistent with config, but not
2927 * usable in this request/run; just bypass untracked cache.
2933 if (!dir
->untracked
->root
) {
2934 /* Untracked cache existed but is not initialized; fix that */
2935 FLEX_ALLOC_STR(dir
->untracked
->root
, name
, "");
2936 istate
->cache_changed
|= UNTRACKED_CHANGED
;
2939 /* Validate $GIT_DIR/info/exclude and core.excludesfile */
2940 root
= dir
->untracked
->root
;
2941 if (!oideq(&dir
->internal
.ss_info_exclude
.oid
,
2942 &dir
->untracked
->ss_info_exclude
.oid
)) {
2943 invalidate_gitignore(dir
->untracked
, root
);
2944 dir
->untracked
->ss_info_exclude
= dir
->internal
.ss_info_exclude
;
2946 if (!oideq(&dir
->internal
.ss_excludes_file
.oid
,
2947 &dir
->untracked
->ss_excludes_file
.oid
)) {
2948 invalidate_gitignore(dir
->untracked
, root
);
2949 dir
->untracked
->ss_excludes_file
= dir
->internal
.ss_excludes_file
;
2952 /* Make sure this directory is not dropped out at saving phase */
2957 static void emit_traversal_statistics(struct dir_struct
*dir
,
2958 struct repository
*repo
,
2962 if (!trace2_is_enabled())
2966 trace2_data_string("read_directory", repo
, "path", "");
2968 struct strbuf tmp
= STRBUF_INIT
;
2969 strbuf_add(&tmp
, path
, path_len
);
2970 trace2_data_string("read_directory", repo
, "path", tmp
.buf
);
2971 strbuf_release(&tmp
);
2974 trace2_data_intmax("read_directory", repo
,
2975 "directories-visited", dir
->internal
.visited_directories
);
2976 trace2_data_intmax("read_directory", repo
,
2977 "paths-visited", dir
->internal
.visited_paths
);
2979 if (!dir
->untracked
)
2981 trace2_data_intmax("read_directory", repo
,
2982 "node-creation", dir
->untracked
->dir_created
);
2983 trace2_data_intmax("read_directory", repo
,
2984 "gitignore-invalidation",
2985 dir
->untracked
->gitignore_invalidated
);
2986 trace2_data_intmax("read_directory", repo
,
2987 "directory-invalidation",
2988 dir
->untracked
->dir_invalidated
);
2989 trace2_data_intmax("read_directory", repo
,
2990 "opendir", dir
->untracked
->dir_opened
);
2993 int read_directory(struct dir_struct
*dir
, struct index_state
*istate
,
2994 const char *path
, int len
, const struct pathspec
*pathspec
)
2996 struct untracked_cache_dir
*untracked
;
2998 trace2_region_enter("dir", "read_directory", istate
->repo
);
2999 dir
->internal
.visited_paths
= 0;
3000 dir
->internal
.visited_directories
= 0;
3002 if (has_symlink_leading_path(path
, len
)) {
3003 trace2_region_leave("dir", "read_directory", istate
->repo
);
3007 untracked
= validate_untracked_cache(dir
, len
, pathspec
, istate
);
3010 * make sure untracked cache code path is disabled,
3011 * e.g. prep_exclude()
3013 dir
->untracked
= NULL
;
3014 if (!len
|| treat_leading_path(dir
, istate
, path
, len
, pathspec
))
3015 read_directory_recursive(dir
, istate
, path
, len
, untracked
, 0, 0, pathspec
);
3016 QSORT(dir
->entries
, dir
->nr
, cmp_dir_entry
);
3017 QSORT(dir
->ignored
, dir
->ignored_nr
, cmp_dir_entry
);
3019 emit_traversal_statistics(dir
, istate
->repo
, path
, len
);
3021 trace2_region_leave("dir", "read_directory", istate
->repo
);
3022 if (dir
->untracked
) {
3023 static int force_untracked_cache
= -1;
3025 if (force_untracked_cache
< 0)
3026 force_untracked_cache
=
3027 git_env_bool("GIT_FORCE_UNTRACKED_CACHE", -1);
3028 if (force_untracked_cache
< 0)
3029 force_untracked_cache
= (istate
->repo
->settings
.core_untracked_cache
== UNTRACKED_CACHE_WRITE
);
3030 if (force_untracked_cache
&&
3031 dir
->untracked
== istate
->untracked
&&
3032 (dir
->untracked
->dir_opened
||
3033 dir
->untracked
->gitignore_invalidated
||
3034 dir
->untracked
->dir_invalidated
))
3035 istate
->cache_changed
|= UNTRACKED_CHANGED
;
3036 if (dir
->untracked
!= istate
->untracked
) {
3037 FREE_AND_NULL(dir
->untracked
);
3044 int file_exists(const char *f
)
3047 return lstat(f
, &sb
) == 0;
3050 int repo_file_exists(struct repository
*repo
, const char *path
)
3052 if (repo
!= the_repository
)
3053 BUG("do not know how to check file existence in arbitrary repo");
3055 return file_exists(path
);
3058 static int cmp_icase(char a
, char b
)
3063 return toupper(a
) - toupper(b
);
3068 * Given two normalized paths (a trailing slash is ok), if subdir is
3069 * outside dir, return -1. Otherwise return the offset in subdir that
3070 * can be used as relative path to dir.
3072 int dir_inside_of(const char *subdir
, const char *dir
)
3076 assert(dir
&& subdir
&& *dir
&& *subdir
);
3078 while (*dir
&& *subdir
&& !cmp_icase(*dir
, *subdir
)) {
3084 /* hel[p]/me vs hel[l]/yeah */
3085 if (*dir
&& *subdir
)
3089 return !*dir
? offset
: -1; /* same dir */
3091 /* foo/[b]ar vs foo/[] */
3092 if (is_dir_sep(dir
[-1]))
3093 return is_dir_sep(subdir
[-1]) ? offset
: -1;
3095 /* foo[/]bar vs foo[] */
3096 return is_dir_sep(*subdir
) ? offset
+ 1 : -1;
3099 int is_inside_dir(const char *dir
)
3108 rc
= (dir_inside_of(cwd
, dir
) >= 0);
3113 int is_empty_dir(const char *path
)
3115 DIR *dir
= opendir(path
);
3122 e
= readdir_skip_dot_and_dotdot(dir
);
3130 char *git_url_basename(const char *repo
, int is_bundle
, int is_bare
)
3132 const char *end
= repo
+ strlen(repo
), *start
, *ptr
;
3139 start
= strstr(repo
, "://");
3146 * Skip authentication data. The stripping does happen
3147 * greedily, such that we strip up to the last '@' inside
3150 for (ptr
= start
; ptr
< end
&& !is_dir_sep(*ptr
); ptr
++) {
3156 * Strip trailing spaces, slashes and /.git
3158 while (start
< end
&& (is_dir_sep(end
[-1]) || isspace(end
[-1])))
3160 if (end
- start
> 5 && is_dir_sep(end
[-5]) &&
3161 !strncmp(end
- 4, ".git", 4)) {
3163 while (start
< end
&& is_dir_sep(end
[-1]))
3168 * It should not be possible to overflow `ptrdiff_t` by passing in an
3169 * insanely long URL, but GCC does not know that and will complain
3170 * without this check.
3172 if (end
- start
< 0)
3173 die(_("No directory name could be guessed.\n"
3174 "Please specify a directory on the command line"));
3177 * Strip trailing port number if we've got only a
3178 * hostname (that is, there is no dir separator but a
3179 * colon). This check is required such that we do not
3180 * strip URI's like '/foo/bar:2222.git', which should
3181 * result in a dir '2222' being guessed due to backwards
3184 if (memchr(start
, '/', end
- start
) == NULL
3185 && memchr(start
, ':', end
- start
) != NULL
) {
3187 while (start
< ptr
&& isdigit(ptr
[-1]) && ptr
[-1] != ':')
3189 if (start
< ptr
&& ptr
[-1] == ':')
3194 * Find last component. To remain backwards compatible we
3195 * also regard colons as path separators, such that
3196 * cloning a repository 'foo:bar.git' would result in a
3197 * directory 'bar' being guessed.
3200 while (start
< ptr
&& !is_dir_sep(ptr
[-1]) && ptr
[-1] != ':')
3205 * Strip .{bundle,git}.
3208 strip_suffix_mem(start
, &len
, is_bundle
? ".bundle" : ".git");
3210 if (!len
|| (len
== 1 && *start
== '/'))
3211 die(_("No directory name could be guessed.\n"
3212 "Please specify a directory on the command line"));
3215 dir
= xstrfmt("%.*s.git", (int)len
, start
);
3217 dir
= xstrndup(start
, len
);
3219 * Replace sequences of 'control' characters and whitespace
3220 * with one ascii space, remove leading and trailing spaces.
3224 int prev_space
= 1 /* strip leading whitespace */;
3225 for (end
= dir
; *end
; ++end
) {
3227 if ((unsigned char)ch
< '\x20')
3238 if (out
> dir
&& prev_space
)
3244 void strip_dir_trailing_slashes(char *dir
)
3246 char *end
= dir
+ strlen(dir
);
3248 while (dir
< end
- 1 && is_dir_sep(end
[-1]))
3253 static int remove_dir_recurse(struct strbuf
*path
, int flag
, int *kept_up
)
3257 int ret
= 0, original_len
= path
->len
, len
, kept_down
= 0;
3258 int only_empty
= (flag
& REMOVE_DIR_EMPTY_ONLY
);
3259 int keep_toplevel
= (flag
& REMOVE_DIR_KEEP_TOPLEVEL
);
3260 int purge_original_cwd
= (flag
& REMOVE_DIR_PURGE_ORIGINAL_CWD
);
3261 struct object_id submodule_head
;
3263 if ((flag
& REMOVE_DIR_KEEP_NESTED_GIT
) &&
3264 !resolve_gitlink_ref(path
->buf
, "HEAD", &submodule_head
)) {
3265 /* Do not descend and nuke a nested git work tree. */
3271 flag
&= ~REMOVE_DIR_KEEP_TOPLEVEL
;
3272 dir
= opendir(path
->buf
);
3274 if (errno
== ENOENT
)
3275 return keep_toplevel
? -1 : 0;
3276 else if (errno
== EACCES
&& !keep_toplevel
)
3278 * An empty dir could be removable even if it
3281 return rmdir(path
->buf
);
3285 strbuf_complete(path
, '/');
3288 while ((e
= readdir_skip_dot_and_dotdot(dir
)) != NULL
) {
3291 strbuf_setlen(path
, len
);
3292 strbuf_addstr(path
, e
->d_name
);
3293 if (lstat(path
->buf
, &st
)) {
3294 if (errno
== ENOENT
)
3296 * file disappeared, which is what we
3301 } else if (S_ISDIR(st
.st_mode
)) {
3302 if (!remove_dir_recurse(path
, flag
, &kept_down
))
3303 continue; /* happy */
3304 } else if (!only_empty
&&
3305 (!unlink(path
->buf
) || errno
== ENOENT
)) {
3306 continue; /* happy, too */
3309 /* path too long, stat fails, or non-directory still exists */
3315 strbuf_setlen(path
, original_len
);
3316 if (!ret
&& !keep_toplevel
&& !kept_down
) {
3317 if (!purge_original_cwd
&&
3318 startup_info
->original_cwd
&&
3319 !strcmp(startup_info
->original_cwd
, path
->buf
))
3320 ret
= -1; /* Do not remove current working directory */
3322 ret
= (!rmdir(path
->buf
) || errno
== ENOENT
) ? 0 : -1;
3325 * report the uplevel that it is not an error that we
3326 * did not rmdir() our directory.
3332 int remove_dir_recursively(struct strbuf
*path
, int flag
)
3334 return remove_dir_recurse(path
, flag
, NULL
);
3337 static GIT_PATH_FUNC(git_path_info_exclude
, "info/exclude")
3339 void setup_standard_excludes(struct dir_struct
*dir
)
3341 dir
->exclude_per_dir
= ".gitignore";
3343 /* core.excludesfile defaulting to $XDG_CONFIG_HOME/git/ignore */
3345 excludes_file
= xdg_config_home("ignore");
3346 if (excludes_file
&& !access_or_warn(excludes_file
, R_OK
, 0))
3347 add_patterns_from_file_1(dir
, excludes_file
,
3348 dir
->untracked
? &dir
->internal
.ss_excludes_file
: NULL
);
3350 /* per repository user preference */
3351 if (startup_info
->have_repository
) {
3352 const char *path
= git_path_info_exclude();
3353 if (!access_or_warn(path
, R_OK
, 0))
3354 add_patterns_from_file_1(dir
, path
,
3355 dir
->untracked
? &dir
->internal
.ss_info_exclude
: NULL
);
3359 char *get_sparse_checkout_filename(void)
3361 return git_pathdup("info/sparse-checkout");
3364 int get_sparse_checkout_patterns(struct pattern_list
*pl
)
3367 char *sparse_filename
= get_sparse_checkout_filename();
3369 pl
->use_cone_patterns
= core_sparse_checkout_cone
;
3370 res
= add_patterns_from_file_to_list(sparse_filename
, "", 0, pl
, NULL
, 0);
3372 free(sparse_filename
);
3376 int remove_path(const char *name
)
3380 if (unlink(name
) && !is_missing_file_error(errno
))
3383 slash
= strrchr(name
, '/');
3385 char *dirs
= xstrdup(name
);
3386 slash
= dirs
+ (slash
- name
);
3389 if (startup_info
->original_cwd
&&
3390 !strcmp(startup_info
->original_cwd
, dirs
))
3392 } while (rmdir(dirs
) == 0 && (slash
= strrchr(dirs
, '/')));
3399 * Frees memory within dir which was allocated, and resets fields for further
3400 * use. Does not free dir itself.
3402 void dir_clear(struct dir_struct
*dir
)
3405 struct exclude_list_group
*group
;
3406 struct pattern_list
*pl
;
3407 struct exclude_stack
*stk
;
3408 struct dir_struct
new = DIR_INIT
;
3410 for (i
= EXC_CMDL
; i
<= EXC_FILE
; i
++) {
3411 group
= &dir
->internal
.exclude_list_group
[i
];
3412 for (j
= 0; j
< group
->nr
; j
++) {
3415 free((char *)pl
->src
);
3416 clear_pattern_list(pl
);
3421 for (i
= 0; i
< dir
->ignored_nr
; i
++)
3422 free(dir
->ignored
[i
]);
3423 for (i
= 0; i
< dir
->nr
; i
++)
3424 free(dir
->entries
[i
]);
3428 stk
= dir
->internal
.exclude_stack
;
3430 struct exclude_stack
*prev
= stk
->prev
;
3434 strbuf_release(&dir
->internal
.basebuf
);
3436 memcpy(dir
, &new, sizeof(*dir
));
3439 struct ondisk_untracked_cache
{
3440 struct stat_data info_exclude_stat
;
3441 struct stat_data excludes_file_stat
;
3445 #define ouc_offset(x) offsetof(struct ondisk_untracked_cache, x)
3448 int index
; /* number of written untracked_cache_dir */
3449 struct ewah_bitmap
*check_only
; /* from untracked_cache_dir */
3450 struct ewah_bitmap
*valid
; /* from untracked_cache_dir */
3451 struct ewah_bitmap
*sha1_valid
; /* set if exclude_sha1 is not null */
3453 struct strbuf sb_stat
;
3454 struct strbuf sb_sha1
;
3457 static void stat_data_to_disk(struct stat_data
*to
, const struct stat_data
*from
)
3459 to
->sd_ctime
.sec
= htonl(from
->sd_ctime
.sec
);
3460 to
->sd_ctime
.nsec
= htonl(from
->sd_ctime
.nsec
);
3461 to
->sd_mtime
.sec
= htonl(from
->sd_mtime
.sec
);
3462 to
->sd_mtime
.nsec
= htonl(from
->sd_mtime
.nsec
);
3463 to
->sd_dev
= htonl(from
->sd_dev
);
3464 to
->sd_ino
= htonl(from
->sd_ino
);
3465 to
->sd_uid
= htonl(from
->sd_uid
);
3466 to
->sd_gid
= htonl(from
->sd_gid
);
3467 to
->sd_size
= htonl(from
->sd_size
);
3470 static void write_one_dir(struct untracked_cache_dir
*untracked
,
3471 struct write_data
*wd
)
3473 struct stat_data stat_data
;
3474 struct strbuf
*out
= &wd
->out
;
3475 unsigned char intbuf
[16];
3476 unsigned int intlen
, value
;
3477 int i
= wd
->index
++;
3480 * untracked_nr should be reset whenever valid is clear, but
3483 if (!untracked
->valid
) {
3484 untracked
->untracked_nr
= 0;
3485 untracked
->check_only
= 0;
3488 if (untracked
->check_only
)
3489 ewah_set(wd
->check_only
, i
);
3490 if (untracked
->valid
) {
3491 ewah_set(wd
->valid
, i
);
3492 stat_data_to_disk(&stat_data
, &untracked
->stat_data
);
3493 strbuf_add(&wd
->sb_stat
, &stat_data
, sizeof(stat_data
));
3495 if (!is_null_oid(&untracked
->exclude_oid
)) {
3496 ewah_set(wd
->sha1_valid
, i
);
3497 strbuf_add(&wd
->sb_sha1
, untracked
->exclude_oid
.hash
,
3498 the_hash_algo
->rawsz
);
3501 intlen
= encode_varint(untracked
->untracked_nr
, intbuf
);
3502 strbuf_add(out
, intbuf
, intlen
);
3504 /* skip non-recurse directories */
3505 for (i
= 0, value
= 0; i
< untracked
->dirs_nr
; i
++)
3506 if (untracked
->dirs
[i
]->recurse
)
3508 intlen
= encode_varint(value
, intbuf
);
3509 strbuf_add(out
, intbuf
, intlen
);
3511 strbuf_add(out
, untracked
->name
, strlen(untracked
->name
) + 1);
3513 for (i
= 0; i
< untracked
->untracked_nr
; i
++)
3514 strbuf_add(out
, untracked
->untracked
[i
],
3515 strlen(untracked
->untracked
[i
]) + 1);
3517 for (i
= 0; i
< untracked
->dirs_nr
; i
++)
3518 if (untracked
->dirs
[i
]->recurse
)
3519 write_one_dir(untracked
->dirs
[i
], wd
);
3522 void write_untracked_extension(struct strbuf
*out
, struct untracked_cache
*untracked
)
3524 struct ondisk_untracked_cache
*ouc
;
3525 struct write_data wd
;
3526 unsigned char varbuf
[16];
3528 const unsigned hashsz
= the_hash_algo
->rawsz
;
3530 CALLOC_ARRAY(ouc
, 1);
3531 stat_data_to_disk(&ouc
->info_exclude_stat
, &untracked
->ss_info_exclude
.stat
);
3532 stat_data_to_disk(&ouc
->excludes_file_stat
, &untracked
->ss_excludes_file
.stat
);
3533 ouc
->dir_flags
= htonl(untracked
->dir_flags
);
3535 varint_len
= encode_varint(untracked
->ident
.len
, varbuf
);
3536 strbuf_add(out
, varbuf
, varint_len
);
3537 strbuf_addbuf(out
, &untracked
->ident
);
3539 strbuf_add(out
, ouc
, sizeof(*ouc
));
3540 strbuf_add(out
, untracked
->ss_info_exclude
.oid
.hash
, hashsz
);
3541 strbuf_add(out
, untracked
->ss_excludes_file
.oid
.hash
, hashsz
);
3542 strbuf_add(out
, untracked
->exclude_per_dir
, strlen(untracked
->exclude_per_dir
) + 1);
3545 if (!untracked
->root
) {
3546 varint_len
= encode_varint(0, varbuf
);
3547 strbuf_add(out
, varbuf
, varint_len
);
3552 wd
.check_only
= ewah_new();
3553 wd
.valid
= ewah_new();
3554 wd
.sha1_valid
= ewah_new();
3555 strbuf_init(&wd
.out
, 1024);
3556 strbuf_init(&wd
.sb_stat
, 1024);
3557 strbuf_init(&wd
.sb_sha1
, 1024);
3558 write_one_dir(untracked
->root
, &wd
);
3560 varint_len
= encode_varint(wd
.index
, varbuf
);
3561 strbuf_add(out
, varbuf
, varint_len
);
3562 strbuf_addbuf(out
, &wd
.out
);
3563 ewah_serialize_strbuf(wd
.valid
, out
);
3564 ewah_serialize_strbuf(wd
.check_only
, out
);
3565 ewah_serialize_strbuf(wd
.sha1_valid
, out
);
3566 strbuf_addbuf(out
, &wd
.sb_stat
);
3567 strbuf_addbuf(out
, &wd
.sb_sha1
);
3568 strbuf_addch(out
, '\0'); /* safe guard for string lists */
3570 ewah_free(wd
.valid
);
3571 ewah_free(wd
.check_only
);
3572 ewah_free(wd
.sha1_valid
);
3573 strbuf_release(&wd
.out
);
3574 strbuf_release(&wd
.sb_stat
);
3575 strbuf_release(&wd
.sb_sha1
);
3578 static void free_untracked(struct untracked_cache_dir
*ucd
)
3583 for (i
= 0; i
< ucd
->dirs_nr
; i
++)
3584 free_untracked(ucd
->dirs
[i
]);
3585 for (i
= 0; i
< ucd
->untracked_nr
; i
++)
3586 free(ucd
->untracked
[i
]);
3587 free(ucd
->untracked
);
3592 void free_untracked_cache(struct untracked_cache
*uc
)
3597 free(uc
->exclude_per_dir_to_free
);
3598 strbuf_release(&uc
->ident
);
3599 free_untracked(uc
->root
);
3605 struct untracked_cache_dir
**ucd
;
3606 struct ewah_bitmap
*check_only
;
3607 struct ewah_bitmap
*valid
;
3608 struct ewah_bitmap
*sha1_valid
;
3609 const unsigned char *data
;
3610 const unsigned char *end
;
3613 static void stat_data_from_disk(struct stat_data
*to
, const unsigned char *data
)
3615 memcpy(to
, data
, sizeof(*to
));
3616 to
->sd_ctime
.sec
= ntohl(to
->sd_ctime
.sec
);
3617 to
->sd_ctime
.nsec
= ntohl(to
->sd_ctime
.nsec
);
3618 to
->sd_mtime
.sec
= ntohl(to
->sd_mtime
.sec
);
3619 to
->sd_mtime
.nsec
= ntohl(to
->sd_mtime
.nsec
);
3620 to
->sd_dev
= ntohl(to
->sd_dev
);
3621 to
->sd_ino
= ntohl(to
->sd_ino
);
3622 to
->sd_uid
= ntohl(to
->sd_uid
);
3623 to
->sd_gid
= ntohl(to
->sd_gid
);
3624 to
->sd_size
= ntohl(to
->sd_size
);
3627 static int read_one_dir(struct untracked_cache_dir
**untracked_
,
3628 struct read_data
*rd
)
3630 struct untracked_cache_dir ud
, *untracked
;
3631 const unsigned char *data
= rd
->data
, *end
= rd
->end
;
3632 const unsigned char *eos
;
3636 memset(&ud
, 0, sizeof(ud
));
3638 value
= decode_varint(&data
);
3642 ud
.untracked_alloc
= value
;
3643 ud
.untracked_nr
= value
;
3644 if (ud
.untracked_nr
)
3645 ALLOC_ARRAY(ud
.untracked
, ud
.untracked_nr
);
3647 ud
.dirs_alloc
= ud
.dirs_nr
= decode_varint(&data
);
3650 ALLOC_ARRAY(ud
.dirs
, ud
.dirs_nr
);
3652 eos
= memchr(data
, '\0', end
- data
);
3653 if (!eos
|| eos
== end
)
3656 *untracked_
= untracked
= xmalloc(st_add3(sizeof(*untracked
), eos
- data
, 1));
3657 memcpy(untracked
, &ud
, sizeof(ud
));
3658 memcpy(untracked
->name
, data
, eos
- data
+ 1);
3661 for (i
= 0; i
< untracked
->untracked_nr
; i
++) {
3662 eos
= memchr(data
, '\0', end
- data
);
3663 if (!eos
|| eos
== end
)
3665 untracked
->untracked
[i
] = xmemdupz(data
, eos
- data
);
3669 rd
->ucd
[rd
->index
++] = untracked
;
3672 for (i
= 0; i
< untracked
->dirs_nr
; i
++) {
3673 if (read_one_dir(untracked
->dirs
+ i
, rd
) < 0)
3679 static void set_check_only(size_t pos
, void *cb
)
3681 struct read_data
*rd
= cb
;
3682 struct untracked_cache_dir
*ud
= rd
->ucd
[pos
];
3686 static void read_stat(size_t pos
, void *cb
)
3688 struct read_data
*rd
= cb
;
3689 struct untracked_cache_dir
*ud
= rd
->ucd
[pos
];
3690 if (rd
->data
+ sizeof(struct stat_data
) > rd
->end
) {
3691 rd
->data
= rd
->end
+ 1;
3694 stat_data_from_disk(&ud
->stat_data
, rd
->data
);
3695 rd
->data
+= sizeof(struct stat_data
);
3699 static void read_oid(size_t pos
, void *cb
)
3701 struct read_data
*rd
= cb
;
3702 struct untracked_cache_dir
*ud
= rd
->ucd
[pos
];
3703 if (rd
->data
+ the_hash_algo
->rawsz
> rd
->end
) {
3704 rd
->data
= rd
->end
+ 1;
3707 oidread(&ud
->exclude_oid
, rd
->data
);
3708 rd
->data
+= the_hash_algo
->rawsz
;
3711 static void load_oid_stat(struct oid_stat
*oid_stat
, const unsigned char *data
,
3712 const unsigned char *sha1
)
3714 stat_data_from_disk(&oid_stat
->stat
, data
);
3715 oidread(&oid_stat
->oid
, sha1
);
3716 oid_stat
->valid
= 1;
3719 struct untracked_cache
*read_untracked_extension(const void *data
, unsigned long sz
)
3721 struct untracked_cache
*uc
;
3722 struct read_data rd
;
3723 const unsigned char *next
= data
, *end
= (const unsigned char *)data
+ sz
;
3727 const char *exclude_per_dir
;
3728 const unsigned hashsz
= the_hash_algo
->rawsz
;
3729 const unsigned offset
= sizeof(struct ondisk_untracked_cache
);
3730 const unsigned exclude_per_dir_offset
= offset
+ 2 * hashsz
;
3732 if (sz
<= 1 || end
[-1] != '\0')
3736 ident_len
= decode_varint(&next
);
3737 if (next
+ ident_len
> end
)
3739 ident
= (const char *)next
;
3742 if (next
+ exclude_per_dir_offset
+ 1 > end
)
3745 CALLOC_ARRAY(uc
, 1);
3746 strbuf_init(&uc
->ident
, ident_len
);
3747 strbuf_add(&uc
->ident
, ident
, ident_len
);
3748 load_oid_stat(&uc
->ss_info_exclude
,
3749 next
+ ouc_offset(info_exclude_stat
),
3751 load_oid_stat(&uc
->ss_excludes_file
,
3752 next
+ ouc_offset(excludes_file_stat
),
3753 next
+ offset
+ hashsz
);
3754 uc
->dir_flags
= get_be32(next
+ ouc_offset(dir_flags
));
3755 exclude_per_dir
= (const char *)next
+ exclude_per_dir_offset
;
3756 uc
->exclude_per_dir
= uc
->exclude_per_dir_to_free
= xstrdup(exclude_per_dir
);
3757 /* NUL after exclude_per_dir is covered by sizeof(*ouc) */
3758 next
+= exclude_per_dir_offset
+ strlen(exclude_per_dir
) + 1;
3762 len
= decode_varint(&next
);
3763 if (next
> end
|| len
== 0)
3766 rd
.valid
= ewah_new();
3767 rd
.check_only
= ewah_new();
3768 rd
.sha1_valid
= ewah_new();
3772 ALLOC_ARRAY(rd
.ucd
, len
);
3774 if (read_one_dir(&uc
->root
, &rd
) || rd
.index
!= len
)
3778 len
= ewah_read_mmap(rd
.valid
, next
, end
- next
);
3783 len
= ewah_read_mmap(rd
.check_only
, next
, end
- next
);
3788 len
= ewah_read_mmap(rd
.sha1_valid
, next
, end
- next
);
3792 ewah_each_bit(rd
.check_only
, set_check_only
, &rd
);
3793 rd
.data
= next
+ len
;
3794 ewah_each_bit(rd
.valid
, read_stat
, &rd
);
3795 ewah_each_bit(rd
.sha1_valid
, read_oid
, &rd
);
3800 ewah_free(rd
.valid
);
3801 ewah_free(rd
.check_only
);
3802 ewah_free(rd
.sha1_valid
);
3805 free_untracked_cache(uc
);
3811 static void invalidate_one_directory(struct untracked_cache
*uc
,
3812 struct untracked_cache_dir
*ucd
)
3814 uc
->dir_invalidated
++;
3816 ucd
->untracked_nr
= 0;
3820 * Normally when an entry is added or removed from a directory,
3821 * invalidating that directory is enough. No need to touch its
3822 * ancestors. When a directory is shown as "foo/bar/" in git-status
3823 * however, deleting or adding an entry may have cascading effect.
3825 * Say the "foo/bar/file" has become untracked, we need to tell the
3826 * untracked_cache_dir of "foo" that "bar/" is not an untracked
3827 * directory any more (because "bar" is managed by foo as an untracked
3830 * Similarly, if "foo/bar/file" moves from untracked to tracked and it
3831 * was the last untracked entry in the entire "foo", we should show
3832 * "foo/" instead. Which means we have to invalidate past "bar" up to
3835 * This function traverses all directories from root to leaf. If there
3836 * is a chance of one of the above cases happening, we invalidate back
3837 * to root. Otherwise we just invalidate the leaf. There may be a more
3838 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to
3839 * detect these cases and avoid unnecessary invalidation, for example,
3840 * checking for the untracked entry named "bar/" in "foo", but for now
3841 * stick to something safe and simple.
3843 static int invalidate_one_component(struct untracked_cache
*uc
,
3844 struct untracked_cache_dir
*dir
,
3845 const char *path
, int len
)
3847 const char *rest
= strchr(path
, '/');
3850 int component_len
= rest
- path
;
3851 struct untracked_cache_dir
*d
=
3852 lookup_untracked(uc
, dir
, path
, component_len
);
3854 invalidate_one_component(uc
, d
, rest
+ 1,
3855 len
- (component_len
+ 1));
3857 invalidate_one_directory(uc
, dir
);
3861 invalidate_one_directory(uc
, dir
);
3862 return uc
->dir_flags
& DIR_SHOW_OTHER_DIRECTORIES
;
3865 void untracked_cache_invalidate_path(struct index_state
*istate
,
3866 const char *path
, int safe_path
)
3868 if (!istate
->untracked
|| !istate
->untracked
->root
)
3870 if (!safe_path
&& !verify_path(path
, 0))
3872 invalidate_one_component(istate
->untracked
, istate
->untracked
->root
,
3873 path
, strlen(path
));
3876 void untracked_cache_remove_from_index(struct index_state
*istate
,
3879 untracked_cache_invalidate_path(istate
, path
, 1);
3882 void untracked_cache_add_to_index(struct index_state
*istate
,
3885 untracked_cache_invalidate_path(istate
, path
, 1);
3888 static void connect_wt_gitdir_in_nested(const char *sub_worktree
,
3889 const char *sub_gitdir
)
3892 struct repository subrepo
;
3893 struct strbuf sub_wt
= STRBUF_INIT
;
3894 struct strbuf sub_gd
= STRBUF_INIT
;
3896 const struct submodule
*sub
;
3898 /* If the submodule has no working tree, we can ignore it. */
3899 if (repo_init(&subrepo
, sub_gitdir
, sub_worktree
))
3902 if (repo_read_index(&subrepo
) < 0)
3903 die(_("index file corrupt in repo %s"), subrepo
.gitdir
);
3905 /* TODO: audit for interaction with sparse-index. */
3906 ensure_full_index(subrepo
.index
);
3907 for (i
= 0; i
< subrepo
.index
->cache_nr
; i
++) {
3908 const struct cache_entry
*ce
= subrepo
.index
->cache
[i
];
3910 if (!S_ISGITLINK(ce
->ce_mode
))
3913 while (i
+ 1 < subrepo
.index
->cache_nr
&&
3914 !strcmp(ce
->name
, subrepo
.index
->cache
[i
+ 1]->name
))
3916 * Skip entries with the same name in different stages
3917 * to make sure an entry is returned only once.
3921 sub
= submodule_from_path(&subrepo
, null_oid(), ce
->name
);
3922 if (!sub
|| !is_submodule_active(&subrepo
, ce
->name
))
3923 /* .gitmodules broken or inactive sub */
3926 strbuf_reset(&sub_wt
);
3927 strbuf_reset(&sub_gd
);
3928 strbuf_addf(&sub_wt
, "%s/%s", sub_worktree
, sub
->path
);
3929 submodule_name_to_gitdir(&sub_gd
, &subrepo
, sub
->name
);
3931 connect_work_tree_and_git_dir(sub_wt
.buf
, sub_gd
.buf
, 1);
3933 strbuf_release(&sub_wt
);
3934 strbuf_release(&sub_gd
);
3935 repo_clear(&subrepo
);
3938 void connect_work_tree_and_git_dir(const char *work_tree_
,
3939 const char *git_dir_
,
3940 int recurse_into_nested
)
3942 struct strbuf gitfile_sb
= STRBUF_INIT
;
3943 struct strbuf cfg_sb
= STRBUF_INIT
;
3944 struct strbuf rel_path
= STRBUF_INIT
;
3945 char *git_dir
, *work_tree
;
3947 /* Prepare .git file */
3948 strbuf_addf(&gitfile_sb
, "%s/.git", work_tree_
);
3949 if (safe_create_leading_directories_const(gitfile_sb
.buf
))
3950 die(_("could not create directories for %s"), gitfile_sb
.buf
);
3952 /* Prepare config file */
3953 strbuf_addf(&cfg_sb
, "%s/config", git_dir_
);
3954 if (safe_create_leading_directories_const(cfg_sb
.buf
))
3955 die(_("could not create directories for %s"), cfg_sb
.buf
);
3957 git_dir
= real_pathdup(git_dir_
, 1);
3958 work_tree
= real_pathdup(work_tree_
, 1);
3960 /* Write .git file */
3961 write_file(gitfile_sb
.buf
, "gitdir: %s",
3962 relative_path(git_dir
, work_tree
, &rel_path
));
3963 /* Update core.worktree setting */
3964 git_config_set_in_file(cfg_sb
.buf
, "core.worktree",
3965 relative_path(work_tree
, git_dir
, &rel_path
));
3967 strbuf_release(&gitfile_sb
);
3968 strbuf_release(&cfg_sb
);
3969 strbuf_release(&rel_path
);
3971 if (recurse_into_nested
)
3972 connect_wt_gitdir_in_nested(work_tree
, git_dir
);
3979 * Migrate the git directory of the given path from old_git_dir to new_git_dir.
3981 void relocate_gitdir(const char *path
, const char *old_git_dir
, const char *new_git_dir
)
3983 if (rename(old_git_dir
, new_git_dir
) < 0)
3984 die_errno(_("could not migrate git directory from '%s' to '%s'"),
3985 old_git_dir
, new_git_dir
);
3987 connect_work_tree_and_git_dir(path
, new_git_dir
, 0);
3990 int path_match_flags(const char *const str
, const enum path_match_flags flags
)
3992 const char *p
= str
;
3994 if (flags
& PATH_MATCH_NATIVE
&&
3995 flags
& PATH_MATCH_XPLATFORM
)
3996 BUG("path_match_flags() must get one match kind, not multiple!");
3997 else if (!(flags
& PATH_MATCH_KINDS_MASK
))
3998 BUG("path_match_flags() must get at least one match kind!");
4000 if (flags
& PATH_MATCH_STARTS_WITH_DOT_SLASH
&&
4001 flags
& PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH
)
4002 BUG("path_match_flags() must get one platform kind, not multiple!");
4003 else if (!(flags
& PATH_MATCH_PLATFORM_MASK
))
4004 BUG("path_match_flags() must get at least one platform kind!");
4008 if (flags
& PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH
&&
4012 if (flags
& PATH_MATCH_NATIVE
)
4013 return is_dir_sep(*p
);
4014 else if (flags
& PATH_MATCH_XPLATFORM
)
4015 return is_xplatform_dir_sep(*p
);