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"
13 #include "environment.h"
15 #include "object-store.h"
18 #include "wildmatch.h"
22 #include "ewah/ewok.h"
23 #include "fsmonitor.h"
25 #include "submodule-config.h"
29 * Tells read_directory_recursive how a file or directory should be treated.
30 * Values are ordered by significance, e.g. if a directory contains both
31 * excluded and untracked files, it is listed as untracked because
32 * path_untracked > path_excluded.
42 * Support data structure for our opendir/readdir/closedir wrappers
46 struct untracked_cache_dir
*untracked
;
53 struct untracked_cache_dir
*ucd
;
56 static enum path_treatment
read_directory_recursive(struct dir_struct
*dir
,
57 struct index_state
*istate
, const char *path
, int len
,
58 struct untracked_cache_dir
*untracked
,
59 int check_only
, int stop_at_first_file
, const struct pathspec
*pathspec
);
60 static int resolve_dtype(int dtype
, struct index_state
*istate
,
61 const char *path
, int len
);
62 struct dirent
*readdir_skip_dot_and_dotdot(DIR *dirp
)
66 while ((e
= readdir(dirp
)) != NULL
) {
67 if (!is_dot_or_dotdot(e
->d_name
))
73 int count_slashes(const char *s
)
82 int fspathcmp(const char *a
, const char *b
)
84 return ignore_case
? strcasecmp(a
, b
) : strcmp(a
, b
);
87 int fspatheq(const char *a
, const char *b
)
89 return !fspathcmp(a
, b
);
92 int fspathncmp(const char *a
, const char *b
, size_t count
)
94 return ignore_case
? strncasecmp(a
, b
, count
) : strncmp(a
, b
, count
);
97 unsigned int fspathhash(const char *str
)
99 return ignore_case
? strihash(str
) : strhash(str
);
102 int git_fnmatch(const struct pathspec_item
*item
,
103 const char *pattern
, const char *string
,
107 if (ps_strncmp(item
, pattern
, string
, prefix
))
112 if (item
->flags
& PATHSPEC_ONESTAR
) {
113 int pattern_len
= strlen(++pattern
);
114 int string_len
= strlen(string
);
115 return string_len
< pattern_len
||
116 ps_strcmp(item
, pattern
,
117 string
+ string_len
- pattern_len
);
119 if (item
->magic
& PATHSPEC_GLOB
)
120 return wildmatch(pattern
, string
,
122 (item
->magic
& PATHSPEC_ICASE
? WM_CASEFOLD
: 0));
124 /* wildmatch has not learned no FNM_PATHNAME mode yet */
125 return wildmatch(pattern
, string
,
126 item
->magic
& PATHSPEC_ICASE
? WM_CASEFOLD
: 0);
129 static int fnmatch_icase_mem(const char *pattern
, int patternlen
,
130 const char *string
, int stringlen
,
134 struct strbuf pat_buf
= STRBUF_INIT
;
135 struct strbuf str_buf
= STRBUF_INIT
;
136 const char *use_pat
= pattern
;
137 const char *use_str
= string
;
139 if (pattern
[patternlen
]) {
140 strbuf_add(&pat_buf
, pattern
, patternlen
);
141 use_pat
= pat_buf
.buf
;
143 if (string
[stringlen
]) {
144 strbuf_add(&str_buf
, string
, stringlen
);
145 use_str
= str_buf
.buf
;
149 flags
|= WM_CASEFOLD
;
150 match_status
= wildmatch(use_pat
, use_str
, flags
);
152 strbuf_release(&pat_buf
);
153 strbuf_release(&str_buf
);
158 static size_t common_prefix_len(const struct pathspec
*pathspec
)
164 * ":(icase)path" is treated as a pathspec full of
165 * wildcard. In other words, only prefix is considered common
166 * prefix. If the pathspec is abc/foo abc/bar, running in
167 * subdir xyz, the common prefix is still xyz, not xyz/abc as
170 GUARD_PATHSPEC(pathspec
,
179 for (n
= 0; n
< pathspec
->nr
; n
++) {
180 size_t i
= 0, len
= 0, item_len
;
181 if (pathspec
->items
[n
].magic
& PATHSPEC_EXCLUDE
)
183 if (pathspec
->items
[n
].magic
& PATHSPEC_ICASE
)
184 item_len
= pathspec
->items
[n
].prefix
;
186 item_len
= pathspec
->items
[n
].nowildcard_len
;
187 while (i
< item_len
&& (n
== 0 || i
< max
)) {
188 char c
= pathspec
->items
[n
].match
[i
];
189 if (c
!= pathspec
->items
[0].match
[i
])
195 if (n
== 0 || len
< max
) {
205 * Returns a copy of the longest leading path common among all
208 char *common_prefix(const struct pathspec
*pathspec
)
210 unsigned long len
= common_prefix_len(pathspec
);
212 return len
? xmemdupz(pathspec
->items
[0].match
, len
) : NULL
;
215 int fill_directory(struct dir_struct
*dir
,
216 struct index_state
*istate
,
217 const struct pathspec
*pathspec
)
222 unsigned exclusive_flags
= DIR_SHOW_IGNORED
| DIR_SHOW_IGNORED_TOO
;
223 if ((dir
->flags
& exclusive_flags
) == exclusive_flags
)
224 BUG("DIR_SHOW_IGNORED and DIR_SHOW_IGNORED_TOO are exclusive");
227 * Calculate common prefix for the pathspec, and
228 * use that to optimize the directory walk
230 prefix_len
= common_prefix_len(pathspec
);
231 prefix
= prefix_len
? pathspec
->items
[0].match
: "";
233 /* Read the directory and prune it */
234 read_directory(dir
, istate
, prefix
, prefix_len
, pathspec
);
239 int within_depth(const char *name
, int namelen
,
240 int depth
, int max_depth
)
242 const char *cp
= name
, *cpe
= name
+ namelen
;
248 if (depth
> max_depth
)
255 * Read the contents of the blob with the given OID into a buffer.
256 * Append a trailing LF to the end if the last line doesn't have one.
259 * -1 when the OID is invalid or unknown or does not refer to a blob.
260 * 0 when the blob is empty.
261 * 1 along with { data, size } of the (possibly augmented) buffer
264 * Optionally updates the given oid_stat with the given OID (when valid).
266 static int do_read_blob(const struct object_id
*oid
, struct oid_stat
*oid_stat
,
267 size_t *size_out
, char **data_out
)
269 enum object_type type
;
276 data
= read_object_file(oid
, &type
, &sz
);
277 if (!data
|| type
!= OBJ_BLOB
) {
283 memset(&oid_stat
->stat
, 0, sizeof(oid_stat
->stat
));
284 oidcpy(&oid_stat
->oid
, oid
);
292 if (data
[sz
- 1] != '\n') {
293 data
= xrealloc(data
, st_add(sz
, 1));
297 *size_out
= xsize_t(sz
);
303 #define DO_MATCH_EXCLUDE (1<<0)
304 #define DO_MATCH_DIRECTORY (1<<1)
305 #define DO_MATCH_LEADING_PATHSPEC (1<<2)
308 * Does the given pathspec match the given name? A match is found if
310 * (1) the pathspec string is leading directory of 'name' ("RECURSIVELY"), or
311 * (2) the pathspec string has a leading part matching 'name' ("LEADING"), or
312 * (3) the pathspec string is a wildcard and matches 'name' ("WILDCARD"), or
313 * (4) the pathspec string is exactly the same as 'name' ("EXACT").
315 * Return value tells which case it was (1-4), or 0 when there is no match.
317 * It may be instructive to look at a small table of concrete examples
318 * to understand the differences between 1, 2, and 4:
321 * | a/b | a/b/ | a/b/c
322 * ------+-----------+-----------+------------
323 * a/b | EXACT | EXACT[1] | LEADING[2]
324 * Names a/b/ | RECURSIVE | EXACT | LEADING[2]
325 * a/b/c | RECURSIVE | RECURSIVE | EXACT
327 * [1] Only if DO_MATCH_DIRECTORY is passed; otherwise, this is NOT a match.
328 * [2] Only if DO_MATCH_LEADING_PATHSPEC is passed; otherwise, not a match.
330 static int match_pathspec_item(struct index_state
*istate
,
331 const struct pathspec_item
*item
, int prefix
,
332 const char *name
, int namelen
, unsigned flags
)
334 /* name/namelen has prefix cut off by caller */
335 const char *match
= item
->match
+ prefix
;
336 int matchlen
= item
->len
- prefix
;
339 * The normal call pattern is:
340 * 1. prefix = common_prefix_len(ps);
341 * 2. prune something, or fill_directory
342 * 3. match_pathspec()
344 * 'prefix' at #1 may be shorter than the command's prefix and
345 * it's ok for #2 to match extra files. Those extras will be
348 * Suppose the pathspec is 'foo' and '../bar' running from
349 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
350 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
351 * user does not want XYZ/foo, only the "foo" part should be
352 * case-insensitive. We need to filter out XYZ/foo here. In
353 * other words, we do not trust the caller on comparing the
354 * prefix part when :(icase) is involved. We do exact
355 * comparison ourselves.
357 * Normally the caller (common_prefix_len() in fact) does
358 * _exact_ matching on name[-prefix+1..-1] and we do not need
359 * to check that part. Be defensive and check it anyway, in
360 * case common_prefix_len is changed, or a new caller is
361 * introduced that does not use common_prefix_len.
363 * If the penalty turns out too high when prefix is really
364 * long, maybe change it to
365 * strncmp(match, name, item->prefix - prefix)
367 if (item
->prefix
&& (item
->magic
& PATHSPEC_ICASE
) &&
368 strncmp(item
->match
, name
- prefix
, item
->prefix
))
371 if (item
->attr_match_nr
&&
372 !match_pathspec_attrs(istate
, name
, namelen
, item
))
375 /* If the match was just the prefix, we matched */
377 return MATCHED_RECURSIVELY
;
379 if (matchlen
<= namelen
&& !ps_strncmp(item
, match
, name
, matchlen
)) {
380 if (matchlen
== namelen
)
381 return MATCHED_EXACTLY
;
383 if (match
[matchlen
-1] == '/' || name
[matchlen
] == '/')
384 return MATCHED_RECURSIVELY
;
385 } else if ((flags
& DO_MATCH_DIRECTORY
) &&
386 match
[matchlen
- 1] == '/' &&
387 namelen
== matchlen
- 1 &&
388 !ps_strncmp(item
, match
, name
, namelen
))
389 return MATCHED_EXACTLY
;
391 if (item
->nowildcard_len
< item
->len
&&
392 !git_fnmatch(item
, match
, name
,
393 item
->nowildcard_len
- prefix
))
394 return MATCHED_FNMATCH
;
396 /* Perform checks to see if "name" is a leading string of the pathspec */
397 if ( (flags
& DO_MATCH_LEADING_PATHSPEC
) &&
398 !(flags
& DO_MATCH_EXCLUDE
)) {
399 /* name is a literal prefix of the pathspec */
400 int offset
= name
[namelen
-1] == '/' ? 1 : 0;
401 if ((namelen
< matchlen
) &&
402 (match
[namelen
-offset
] == '/') &&
403 !ps_strncmp(item
, match
, name
, namelen
))
404 return MATCHED_RECURSIVELY_LEADING_PATHSPEC
;
406 /* name doesn't match up to the first wild character */
407 if (item
->nowildcard_len
< item
->len
&&
408 ps_strncmp(item
, match
, name
,
409 item
->nowildcard_len
- prefix
))
413 * name has no wildcard, and it didn't match as a leading
414 * pathspec so return.
416 if (item
->nowildcard_len
== item
->len
)
420 * Here is where we would perform a wildmatch to check if
421 * "name" can be matched as a directory (or a prefix) against
422 * the pathspec. Since wildmatch doesn't have this capability
423 * at the present we have to punt and say that it is a match,
424 * potentially returning a false positive
425 * The submodules themselves will be able to perform more
426 * accurate matching to determine if the pathspec matches.
428 return MATCHED_RECURSIVELY_LEADING_PATHSPEC
;
435 * do_match_pathspec() is meant to ONLY be called by
436 * match_pathspec_with_flags(); calling it directly risks pathspecs
437 * like ':!unwanted_path' being ignored.
439 * Given a name and a list of pathspecs, returns the nature of the
440 * closest (i.e. most specific) match of the name to any of the
443 * The caller typically calls this multiple times with the same
444 * pathspec and seen[] array but with different name/namelen
445 * (e.g. entries from the index) and is interested in seeing if and
446 * how each pathspec matches all the names it calls this function
447 * with. A mark is left in the seen[] array for each pathspec element
448 * indicating the closest type of match that element achieved, so if
449 * seen[n] remains zero after multiple invocations, that means the nth
450 * pathspec did not match any names, which could indicate that the
451 * user mistyped the nth pathspec.
453 static int do_match_pathspec(struct index_state
*istate
,
454 const struct pathspec
*ps
,
455 const char *name
, int namelen
,
456 int prefix
, char *seen
,
459 int i
, retval
= 0, exclude
= flags
& DO_MATCH_EXCLUDE
;
471 if (!ps
->recursive
||
472 !(ps
->magic
& PATHSPEC_MAXDEPTH
) ||
474 return MATCHED_RECURSIVELY
;
476 if (within_depth(name
, namelen
, 0, ps
->max_depth
))
477 return MATCHED_EXACTLY
;
485 for (i
= ps
->nr
- 1; i
>= 0; i
--) {
488 if ((!exclude
&& ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
) ||
489 ( exclude
&& !(ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
)))
492 if (seen
&& seen
[i
] == MATCHED_EXACTLY
)
495 * Make exclude patterns optional and never report
496 * "pathspec ':(exclude)foo' matches no files"
498 if (seen
&& ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
)
499 seen
[i
] = MATCHED_FNMATCH
;
500 how
= match_pathspec_item(istate
, ps
->items
+i
, prefix
, name
,
503 (ps
->magic
& PATHSPEC_MAXDEPTH
) &&
504 ps
->max_depth
!= -1 &&
505 how
&& how
!= MATCHED_FNMATCH
) {
506 int len
= ps
->items
[i
].len
;
507 if (name
[len
] == '/')
509 if (within_depth(name
+len
, namelen
-len
, 0, ps
->max_depth
))
510 how
= MATCHED_EXACTLY
;
517 if (seen
&& seen
[i
] < how
)
524 static int match_pathspec_with_flags(struct index_state
*istate
,
525 const struct pathspec
*ps
,
526 const char *name
, int namelen
,
527 int prefix
, char *seen
, unsigned flags
)
529 int positive
, negative
;
530 positive
= do_match_pathspec(istate
, ps
, name
, namelen
,
531 prefix
, seen
, flags
);
532 if (!(ps
->magic
& PATHSPEC_EXCLUDE
) || !positive
)
534 negative
= do_match_pathspec(istate
, ps
, name
, namelen
,
536 flags
| DO_MATCH_EXCLUDE
);
537 return negative
? 0 : positive
;
540 int match_pathspec(struct index_state
*istate
,
541 const struct pathspec
*ps
,
542 const char *name
, int namelen
,
543 int prefix
, char *seen
, int is_dir
)
545 unsigned flags
= is_dir
? DO_MATCH_DIRECTORY
: 0;
546 return match_pathspec_with_flags(istate
, ps
, name
, namelen
,
547 prefix
, seen
, flags
);
551 * Check if a submodule is a superset of the pathspec
553 int submodule_path_match(struct index_state
*istate
,
554 const struct pathspec
*ps
,
555 const char *submodule_name
,
558 int matched
= match_pathspec_with_flags(istate
, ps
, submodule_name
,
559 strlen(submodule_name
),
562 DO_MATCH_LEADING_PATHSPEC
);
566 int report_path_error(const char *ps_matched
,
567 const struct pathspec
*pathspec
)
570 * Make sure all pathspec matched; otherwise it is an error.
573 for (num
= 0; num
< pathspec
->nr
; num
++) {
574 int other
, found_dup
;
579 * The caller might have fed identical pathspec
580 * twice. Do not barf on such a mistake.
581 * FIXME: parse_pathspec should have eliminated
582 * duplicate pathspec.
584 for (found_dup
= other
= 0;
585 !found_dup
&& other
< pathspec
->nr
;
587 if (other
== num
|| !ps_matched
[other
])
589 if (!strcmp(pathspec
->items
[other
].original
,
590 pathspec
->items
[num
].original
))
592 * Ok, we have a match already.
599 error(_("pathspec '%s' did not match any file(s) known to git"),
600 pathspec
->items
[num
].original
);
607 * Return the length of the "simple" part of a path match limiter.
609 int simple_length(const char *match
)
614 unsigned char c
= *match
++;
616 if (c
== '\0' || is_glob_special(c
))
621 int no_wildcard(const char *string
)
623 return string
[simple_length(string
)] == '\0';
626 void parse_path_pattern(const char **pattern
,
631 const char *p
= *pattern
;
636 *flags
|= PATTERN_FLAG_NEGATIVE
;
640 if (len
&& p
[len
- 1] == '/') {
642 *flags
|= PATTERN_FLAG_MUSTBEDIR
;
644 for (i
= 0; i
< len
; i
++) {
649 *flags
|= PATTERN_FLAG_NODIR
;
650 *nowildcardlen
= simple_length(p
);
652 * we should have excluded the trailing slash from 'p' too,
653 * but that's one more allocation. Instead just make sure
654 * nowildcardlen does not exceed real patternlen
656 if (*nowildcardlen
> len
)
657 *nowildcardlen
= len
;
658 if (*p
== '*' && no_wildcard(p
+ 1))
659 *flags
|= PATTERN_FLAG_ENDSWITH
;
664 int pl_hashmap_cmp(const void *cmp_data UNUSED
,
665 const struct hashmap_entry
*a
,
666 const struct hashmap_entry
*b
,
667 const void *key UNUSED
)
669 const struct pattern_entry
*ee1
=
670 container_of(a
, struct pattern_entry
, ent
);
671 const struct pattern_entry
*ee2
=
672 container_of(b
, struct pattern_entry
, ent
);
674 size_t min_len
= ee1
->patternlen
<= ee2
->patternlen
678 return fspathncmp(ee1
->pattern
, ee2
->pattern
, min_len
);
681 static char *dup_and_filter_pattern(const char *pattern
)
685 char *result
= xstrdup(pattern
);
691 /* skip escape characters (once) */
711 static void add_pattern_to_hashsets(struct pattern_list
*pl
, struct path_pattern
*given
)
713 struct pattern_entry
*translated
;
716 const char *prev
, *cur
, *next
;
718 if (!pl
->use_cone_patterns
)
721 if (given
->flags
& PATTERN_FLAG_NEGATIVE
&&
722 given
->flags
& PATTERN_FLAG_MUSTBEDIR
&&
723 !strcmp(given
->pattern
, "/*")) {
728 if (!given
->flags
&& !strcmp(given
->pattern
, "/*")) {
733 if (given
->patternlen
< 2 ||
734 *given
->pattern
!= '/' ||
735 strstr(given
->pattern
, "**")) {
736 /* Not a cone pattern. */
737 warning(_("unrecognized pattern: '%s'"), given
->pattern
);
741 if (!(given
->flags
& PATTERN_FLAG_MUSTBEDIR
) &&
742 strcmp(given
->pattern
, "/*")) {
743 /* Not a cone pattern. */
744 warning(_("unrecognized pattern: '%s'"), given
->pattern
);
748 prev
= given
->pattern
;
749 cur
= given
->pattern
+ 1;
750 next
= given
->pattern
+ 2;
753 /* Watch for glob characters '*', '\', '[', '?' */
754 if (!is_glob_special(*cur
))
757 /* But only if *prev != '\\' */
761 /* But allow the initial '\' */
763 is_glob_special(*next
))
766 /* But a trailing '/' then '*' is fine */
772 /* Not a cone pattern. */
773 warning(_("unrecognized pattern: '%s'"), given
->pattern
);
782 if (given
->patternlen
> 2 &&
783 !strcmp(given
->pattern
+ given
->patternlen
- 2, "/*")) {
784 if (!(given
->flags
& PATTERN_FLAG_NEGATIVE
)) {
785 /* Not a cone pattern. */
786 warning(_("unrecognized pattern: '%s'"), given
->pattern
);
790 truncated
= dup_and_filter_pattern(given
->pattern
);
792 translated
= xmalloc(sizeof(struct pattern_entry
));
793 translated
->pattern
= truncated
;
794 translated
->patternlen
= given
->patternlen
- 2;
795 hashmap_entry_init(&translated
->ent
,
796 fspathhash(translated
->pattern
));
798 if (!hashmap_get_entry(&pl
->recursive_hashmap
,
799 translated
, ent
, NULL
)) {
800 /* We did not see the "parent" included */
801 warning(_("unrecognized negative pattern: '%s'"),
808 hashmap_add(&pl
->parent_hashmap
, &translated
->ent
);
809 hashmap_remove(&pl
->recursive_hashmap
, &translated
->ent
, &data
);
814 if (given
->flags
& PATTERN_FLAG_NEGATIVE
) {
815 warning(_("unrecognized negative pattern: '%s'"),
820 translated
= xmalloc(sizeof(struct pattern_entry
));
822 translated
->pattern
= dup_and_filter_pattern(given
->pattern
);
823 translated
->patternlen
= given
->patternlen
;
824 hashmap_entry_init(&translated
->ent
,
825 fspathhash(translated
->pattern
));
827 hashmap_add(&pl
->recursive_hashmap
, &translated
->ent
);
829 if (hashmap_get_entry(&pl
->parent_hashmap
, translated
, ent
, NULL
)) {
830 /* we already included this at the parent level */
831 warning(_("your sparse-checkout file may have issues: pattern '%s' is repeated"),
839 warning(_("disabling cone pattern matching"));
840 hashmap_clear_and_free(&pl
->parent_hashmap
, struct pattern_entry
, ent
);
841 hashmap_clear_and_free(&pl
->recursive_hashmap
, struct pattern_entry
, ent
);
842 pl
->use_cone_patterns
= 0;
845 static int hashmap_contains_path(struct hashmap
*map
,
846 struct strbuf
*pattern
)
848 struct pattern_entry p
;
850 /* Check straight mapping */
851 p
.pattern
= pattern
->buf
;
852 p
.patternlen
= pattern
->len
;
853 hashmap_entry_init(&p
.ent
, fspathhash(p
.pattern
));
854 return !!hashmap_get_entry(map
, &p
, ent
, NULL
);
857 int hashmap_contains_parent(struct hashmap
*map
,
859 struct strbuf
*buffer
)
863 strbuf_setlen(buffer
, 0);
866 strbuf_addch(buffer
, '/');
868 strbuf_addstr(buffer
, path
);
870 slash_pos
= strrchr(buffer
->buf
, '/');
872 while (slash_pos
> buffer
->buf
) {
873 strbuf_setlen(buffer
, slash_pos
- buffer
->buf
);
875 if (hashmap_contains_path(map
, buffer
))
878 slash_pos
= strrchr(buffer
->buf
, '/');
884 void add_pattern(const char *string
, const char *base
,
885 int baselen
, struct pattern_list
*pl
, int srcpos
)
887 struct path_pattern
*pattern
;
892 parse_path_pattern(&string
, &patternlen
, &flags
, &nowildcardlen
);
893 if (flags
& PATTERN_FLAG_MUSTBEDIR
) {
894 FLEXPTR_ALLOC_MEM(pattern
, pattern
, string
, patternlen
);
896 pattern
= xmalloc(sizeof(*pattern
));
897 pattern
->pattern
= string
;
899 pattern
->patternlen
= patternlen
;
900 pattern
->nowildcardlen
= nowildcardlen
;
901 pattern
->base
= base
;
902 pattern
->baselen
= baselen
;
903 pattern
->flags
= flags
;
904 pattern
->srcpos
= srcpos
;
905 ALLOC_GROW(pl
->patterns
, pl
->nr
+ 1, pl
->alloc
);
906 pl
->patterns
[pl
->nr
++] = pattern
;
909 add_pattern_to_hashsets(pl
, pattern
);
912 static int read_skip_worktree_file_from_index(struct index_state
*istate
,
914 size_t *size_out
, char **data_out
,
915 struct oid_stat
*oid_stat
)
920 pos
= index_name_pos(istate
, path
, len
);
923 if (!ce_skip_worktree(istate
->cache
[pos
]))
926 return do_read_blob(&istate
->cache
[pos
]->oid
, oid_stat
, size_out
, data_out
);
930 * Frees memory within pl which was allocated for exclude patterns and
931 * the file buffer. Does not free pl itself.
933 void clear_pattern_list(struct pattern_list
*pl
)
937 for (i
= 0; i
< pl
->nr
; i
++)
938 free(pl
->patterns
[i
]);
941 hashmap_clear_and_free(&pl
->recursive_hashmap
, struct pattern_entry
, ent
);
942 hashmap_clear_and_free(&pl
->parent_hashmap
, struct pattern_entry
, ent
);
944 memset(pl
, 0, sizeof(*pl
));
947 static void trim_trailing_spaces(char *buf
)
949 char *p
, *last_space
= NULL
;
951 for (p
= buf
; *p
; p
++)
971 * Given a subdirectory name and "dir" of the current directory,
972 * search the subdir in "dir" and return it, or create a new one if it
973 * does not exist in "dir".
975 * If "name" has the trailing slash, it'll be excluded in the search.
977 static struct untracked_cache_dir
*lookup_untracked(struct untracked_cache
*uc
,
978 struct untracked_cache_dir
*dir
,
979 const char *name
, int len
)
982 struct untracked_cache_dir
*d
;
985 if (len
&& name
[len
- 1] == '/')
989 while (last
> first
) {
990 int cmp
, next
= first
+ ((last
- first
) >> 1);
992 cmp
= strncmp(name
, d
->name
, len
);
993 if (!cmp
&& strlen(d
->name
) > len
)
1005 FLEX_ALLOC_MEM(d
, name
, name
, len
);
1007 ALLOC_GROW(dir
->dirs
, dir
->dirs_nr
+ 1, dir
->dirs_alloc
);
1008 MOVE_ARRAY(dir
->dirs
+ first
+ 1, dir
->dirs
+ first
,
1009 dir
->dirs_nr
- first
);
1011 dir
->dirs
[first
] = d
;
1015 static void do_invalidate_gitignore(struct untracked_cache_dir
*dir
)
1019 dir
->untracked_nr
= 0;
1020 for (i
= 0; i
< dir
->dirs_nr
; i
++)
1021 do_invalidate_gitignore(dir
->dirs
[i
]);
1024 static void invalidate_gitignore(struct untracked_cache
*uc
,
1025 struct untracked_cache_dir
*dir
)
1027 uc
->gitignore_invalidated
++;
1028 do_invalidate_gitignore(dir
);
1031 static void invalidate_directory(struct untracked_cache
*uc
,
1032 struct untracked_cache_dir
*dir
)
1037 * Invalidation increment here is just roughly correct. If
1038 * untracked_nr or any of dirs[].recurse is non-zero, we
1039 * should increment dir_invalidated too. But that's more
1043 uc
->dir_invalidated
++;
1046 dir
->untracked_nr
= 0;
1047 for (i
= 0; i
< dir
->dirs_nr
; i
++)
1048 dir
->dirs
[i
]->recurse
= 0;
1051 static int add_patterns_from_buffer(char *buf
, size_t size
,
1052 const char *base
, int baselen
,
1053 struct pattern_list
*pl
);
1055 /* Flags for add_patterns() */
1056 #define PATTERN_NOFOLLOW (1<<0)
1059 * Given a file with name "fname", read it (either from disk, or from
1060 * an index if 'istate' is non-null), parse it and store the
1061 * exclude rules in "pl".
1063 * If "oid_stat" is not NULL, compute oid of the exclude file and fill
1064 * stat data from disk (only valid if add_patterns returns zero). If
1065 * oid_stat.valid is non-zero, "oid_stat" must contain good value as input.
1067 static int add_patterns(const char *fname
, const char *base
, int baselen
,
1068 struct pattern_list
*pl
, struct index_state
*istate
,
1069 unsigned flags
, struct oid_stat
*oid_stat
)
1077 if (flags
& PATTERN_NOFOLLOW
)
1078 fd
= open_nofollow(fname
, O_RDONLY
);
1080 fd
= open(fname
, O_RDONLY
);
1082 if (fd
< 0 || fstat(fd
, &st
) < 0) {
1084 warn_on_fopen_errors(fname
);
1089 r
= read_skip_worktree_file_from_index(istate
, fname
,
1095 size
= xsize_t(st
.st_size
);
1098 fill_stat_data(&oid_stat
->stat
, &st
);
1099 oidcpy(&oid_stat
->oid
, the_hash_algo
->empty_blob
);
1100 oid_stat
->valid
= 1;
1105 buf
= xmallocz(size
);
1106 if (read_in_full(fd
, buf
, size
) != size
) {
1115 if (oid_stat
->valid
&&
1116 !match_stat_data_racy(istate
, &oid_stat
->stat
, &st
))
1117 ; /* no content change, oid_stat->oid still good */
1119 (pos
= index_name_pos(istate
, fname
, strlen(fname
))) >= 0 &&
1120 !ce_stage(istate
->cache
[pos
]) &&
1121 ce_uptodate(istate
->cache
[pos
]) &&
1122 !would_convert_to_git(istate
, fname
))
1123 oidcpy(&oid_stat
->oid
,
1124 &istate
->cache
[pos
]->oid
);
1126 hash_object_file(the_hash_algo
, buf
, size
,
1127 OBJ_BLOB
, &oid_stat
->oid
);
1128 fill_stat_data(&oid_stat
->stat
, &st
);
1129 oid_stat
->valid
= 1;
1133 add_patterns_from_buffer(buf
, size
, base
, baselen
, pl
);
1137 static int add_patterns_from_buffer(char *buf
, size_t size
,
1138 const char *base
, int baselen
,
1139 struct pattern_list
*pl
)
1144 hashmap_init(&pl
->recursive_hashmap
, pl_hashmap_cmp
, NULL
, 0);
1145 hashmap_init(&pl
->parent_hashmap
, pl_hashmap_cmp
, NULL
, 0);
1149 if (skip_utf8_bom(&buf
, size
))
1150 size
-= buf
- pl
->filebuf
;
1154 for (i
= 0; i
< size
; i
++) {
1155 if (buf
[i
] == '\n') {
1156 if (entry
!= buf
+ i
&& entry
[0] != '#') {
1157 buf
[i
- (i
&& buf
[i
-1] == '\r')] = 0;
1158 trim_trailing_spaces(entry
);
1159 add_pattern(entry
, base
, baselen
, pl
, lineno
);
1162 entry
= buf
+ i
+ 1;
1168 int add_patterns_from_file_to_list(const char *fname
, const char *base
,
1169 int baselen
, struct pattern_list
*pl
,
1170 struct index_state
*istate
,
1173 return add_patterns(fname
, base
, baselen
, pl
, istate
, flags
, NULL
);
1176 int add_patterns_from_blob_to_list(
1177 struct object_id
*oid
,
1178 const char *base
, int baselen
,
1179 struct pattern_list
*pl
)
1185 r
= do_read_blob(oid
, NULL
, &size
, &buf
);
1189 add_patterns_from_buffer(buf
, size
, base
, baselen
, pl
);
1193 struct pattern_list
*add_pattern_list(struct dir_struct
*dir
,
1194 int group_type
, const char *src
)
1196 struct pattern_list
*pl
;
1197 struct exclude_list_group
*group
;
1199 group
= &dir
->internal
.exclude_list_group
[group_type
];
1200 ALLOC_GROW(group
->pl
, group
->nr
+ 1, group
->alloc
);
1201 pl
= &group
->pl
[group
->nr
++];
1202 memset(pl
, 0, sizeof(*pl
));
1208 * Used to set up core.excludesfile and .git/info/exclude lists.
1210 static void add_patterns_from_file_1(struct dir_struct
*dir
, const char *fname
,
1211 struct oid_stat
*oid_stat
)
1213 struct pattern_list
*pl
;
1215 * catch setup_standard_excludes() that's called before
1216 * dir->untracked is assigned. That function behaves
1217 * differently when dir->untracked is non-NULL.
1219 if (!dir
->untracked
)
1220 dir
->internal
.unmanaged_exclude_files
++;
1221 pl
= add_pattern_list(dir
, EXC_FILE
, fname
);
1222 if (add_patterns(fname
, "", 0, pl
, NULL
, 0, oid_stat
) < 0)
1223 die(_("cannot use %s as an exclude file"), fname
);
1226 void add_patterns_from_file(struct dir_struct
*dir
, const char *fname
)
1228 dir
->internal
.unmanaged_exclude_files
++; /* see validate_untracked_cache() */
1229 add_patterns_from_file_1(dir
, fname
, NULL
);
1232 int match_basename(const char *basename
, int basenamelen
,
1233 const char *pattern
, int prefix
, int patternlen
,
1236 if (prefix
== patternlen
) {
1237 if (patternlen
== basenamelen
&&
1238 !fspathncmp(pattern
, basename
, basenamelen
))
1240 } else if (flags
& PATTERN_FLAG_ENDSWITH
) {
1241 /* "*literal" matching against "fooliteral" */
1242 if (patternlen
- 1 <= basenamelen
&&
1243 !fspathncmp(pattern
+ 1,
1244 basename
+ basenamelen
- (patternlen
- 1),
1248 if (fnmatch_icase_mem(pattern
, patternlen
,
1249 basename
, basenamelen
,
1256 int match_pathname(const char *pathname
, int pathlen
,
1257 const char *base
, int baselen
,
1258 const char *pattern
, int prefix
, int patternlen
)
1264 * match with FNM_PATHNAME; the pattern has base implicitly
1267 if (*pattern
== '/') {
1274 * baselen does not count the trailing slash. base[] may or
1275 * may not end with a trailing slash though.
1277 if (pathlen
< baselen
+ 1 ||
1278 (baselen
&& pathname
[baselen
] != '/') ||
1279 fspathncmp(pathname
, base
, baselen
))
1282 namelen
= baselen
? pathlen
- baselen
- 1 : pathlen
;
1283 name
= pathname
+ pathlen
- namelen
;
1287 * if the non-wildcard part is longer than the
1288 * remaining pathname, surely it cannot match.
1290 if (prefix
> namelen
)
1293 if (fspathncmp(pattern
, name
, prefix
))
1296 patternlen
-= prefix
;
1301 * If the whole pattern did not have a wildcard,
1302 * then our prefix match is all we need; we
1303 * do not need to call fnmatch at all.
1305 if (!patternlen
&& !namelen
)
1309 return fnmatch_icase_mem(pattern
, patternlen
,
1315 * Scan the given exclude list in reverse to see whether pathname
1316 * should be ignored. The first match (i.e. the last on the list), if
1317 * any, determines the fate. Returns the exclude_list element which
1318 * matched, or NULL for undecided.
1320 static struct path_pattern
*last_matching_pattern_from_list(const char *pathname
,
1322 const char *basename
,
1324 struct pattern_list
*pl
,
1325 struct index_state
*istate
)
1327 struct path_pattern
*res
= NULL
; /* undecided */
1331 return NULL
; /* undefined */
1333 for (i
= pl
->nr
- 1; 0 <= i
; i
--) {
1334 struct path_pattern
*pattern
= pl
->patterns
[i
];
1335 const char *exclude
= pattern
->pattern
;
1336 int prefix
= pattern
->nowildcardlen
;
1338 if (pattern
->flags
& PATTERN_FLAG_MUSTBEDIR
) {
1339 *dtype
= resolve_dtype(*dtype
, istate
, pathname
, pathlen
);
1340 if (*dtype
!= DT_DIR
)
1344 if (pattern
->flags
& PATTERN_FLAG_NODIR
) {
1345 if (match_basename(basename
,
1346 pathlen
- (basename
- pathname
),
1347 exclude
, prefix
, pattern
->patternlen
,
1355 assert(pattern
->baselen
== 0 ||
1356 pattern
->base
[pattern
->baselen
- 1] == '/');
1357 if (match_pathname(pathname
, pathlen
,
1359 pattern
->baselen
? pattern
->baselen
- 1 : 0,
1360 exclude
, prefix
, pattern
->patternlen
)) {
1369 * Scan the list of patterns to determine if the ordered list
1370 * of patterns matches on 'pathname'.
1372 * Return 1 for a match, 0 for not matched and -1 for undecided.
1374 enum pattern_match_result
path_matches_pattern_list(
1375 const char *pathname
, int pathlen
,
1376 const char *basename
, int *dtype
,
1377 struct pattern_list
*pl
,
1378 struct index_state
*istate
)
1380 struct path_pattern
*pattern
;
1381 struct strbuf parent_pathname
= STRBUF_INIT
;
1382 int result
= NOT_MATCHED
;
1385 if (!pl
->use_cone_patterns
) {
1386 pattern
= last_matching_pattern_from_list(pathname
, pathlen
, basename
,
1389 if (pattern
->flags
& PATTERN_FLAG_NEGATIVE
)
1401 strbuf_addch(&parent_pathname
, '/');
1402 strbuf_add(&parent_pathname
, pathname
, pathlen
);
1405 * Directory entries are matched if and only if a file
1406 * contained immediately within them is matched. For the
1407 * case of a directory entry, modify the path to create
1408 * a fake filename within this directory, allowing us to
1409 * use the file-base matching logic in an equivalent way.
1411 if (parent_pathname
.len
> 0 &&
1412 parent_pathname
.buf
[parent_pathname
.len
- 1] == '/') {
1413 slash_pos
= parent_pathname
.len
- 1;
1414 strbuf_add(&parent_pathname
, "-", 1);
1416 const char *slash_ptr
= strrchr(parent_pathname
.buf
, '/');
1417 slash_pos
= slash_ptr
? slash_ptr
- parent_pathname
.buf
: 0;
1420 if (hashmap_contains_path(&pl
->recursive_hashmap
,
1421 &parent_pathname
)) {
1422 result
= MATCHED_RECURSIVE
;
1427 /* include every file in root */
1432 strbuf_setlen(&parent_pathname
, slash_pos
);
1434 if (hashmap_contains_path(&pl
->parent_hashmap
, &parent_pathname
)) {
1439 if (hashmap_contains_parent(&pl
->recursive_hashmap
,
1442 result
= MATCHED_RECURSIVE
;
1445 strbuf_release(&parent_pathname
);
1449 int init_sparse_checkout_patterns(struct index_state
*istate
)
1451 if (!core_apply_sparse_checkout
)
1453 if (istate
->sparse_checkout_patterns
)
1456 CALLOC_ARRAY(istate
->sparse_checkout_patterns
, 1);
1458 if (get_sparse_checkout_patterns(istate
->sparse_checkout_patterns
) < 0) {
1459 FREE_AND_NULL(istate
->sparse_checkout_patterns
);
1466 static int path_in_sparse_checkout_1(const char *path
,
1467 struct index_state
*istate
,
1468 int require_cone_mode
)
1471 enum pattern_match_result match
= UNDECIDED
;
1472 const char *end
, *slash
;
1475 * We default to accepting a path if the path is empty, there are no
1476 * patterns, or the patterns are of the wrong type.
1479 init_sparse_checkout_patterns(istate
) ||
1480 (require_cone_mode
&&
1481 !istate
->sparse_checkout_patterns
->use_cone_patterns
))
1485 * If UNDECIDED, use the match from the parent dir (recursively), or
1486 * fall back to NOT_MATCHED at the topmost level. Note that cone mode
1487 * never returns UNDECIDED, so we will execute only one iteration in
1490 for (end
= path
+ strlen(path
);
1491 end
> path
&& match
== UNDECIDED
;
1494 for (slash
= end
- 1; slash
> path
&& *slash
!= '/'; slash
--)
1497 match
= path_matches_pattern_list(path
, end
- path
,
1498 slash
> path
? slash
+ 1 : path
, &dtype
,
1499 istate
->sparse_checkout_patterns
, istate
);
1501 /* We are going to match the parent dir now */
1507 int path_in_sparse_checkout(const char *path
,
1508 struct index_state
*istate
)
1510 return path_in_sparse_checkout_1(path
, istate
, 0);
1513 int path_in_cone_mode_sparse_checkout(const char *path
,
1514 struct index_state
*istate
)
1516 return path_in_sparse_checkout_1(path
, istate
, 1);
1519 static struct path_pattern
*last_matching_pattern_from_lists(
1520 struct dir_struct
*dir
, struct index_state
*istate
,
1521 const char *pathname
, int pathlen
,
1522 const char *basename
, int *dtype_p
)
1525 struct exclude_list_group
*group
;
1526 struct path_pattern
*pattern
;
1527 for (i
= EXC_CMDL
; i
<= EXC_FILE
; i
++) {
1528 group
= &dir
->internal
.exclude_list_group
[i
];
1529 for (j
= group
->nr
- 1; j
>= 0; j
--) {
1530 pattern
= last_matching_pattern_from_list(
1531 pathname
, pathlen
, basename
, dtype_p
,
1532 &group
->pl
[j
], istate
);
1541 * Loads the per-directory exclude list for the substring of base
1542 * which has a char length of baselen.
1544 static void prep_exclude(struct dir_struct
*dir
,
1545 struct index_state
*istate
,
1546 const char *base
, int baselen
)
1548 struct exclude_list_group
*group
;
1549 struct pattern_list
*pl
;
1550 struct exclude_stack
*stk
= NULL
;
1551 struct untracked_cache_dir
*untracked
;
1554 group
= &dir
->internal
.exclude_list_group
[EXC_DIRS
];
1557 * Pop the exclude lists from the EXCL_DIRS exclude_list_group
1558 * which originate from directories not in the prefix of the
1559 * path being checked.
1561 while ((stk
= dir
->internal
.exclude_stack
) != NULL
) {
1562 if (stk
->baselen
<= baselen
&&
1563 !strncmp(dir
->internal
.basebuf
.buf
, base
, stk
->baselen
))
1565 pl
= &group
->pl
[dir
->internal
.exclude_stack
->exclude_ix
];
1566 dir
->internal
.exclude_stack
= stk
->prev
;
1567 dir
->internal
.pattern
= NULL
;
1568 free((char *)pl
->src
); /* see strbuf_detach() below */
1569 clear_pattern_list(pl
);
1574 /* Skip traversing into sub directories if the parent is excluded */
1575 if (dir
->internal
.pattern
)
1579 * Lazy initialization. All call sites currently just
1580 * memset(dir, 0, sizeof(*dir)) before use. Changing all of
1581 * them seems lots of work for little benefit.
1583 if (!dir
->internal
.basebuf
.buf
)
1584 strbuf_init(&dir
->internal
.basebuf
, PATH_MAX
);
1586 /* Read from the parent directories and push them down. */
1587 current
= stk
? stk
->baselen
: -1;
1588 strbuf_setlen(&dir
->internal
.basebuf
, current
< 0 ? 0 : current
);
1590 untracked
= stk
? stk
->ucd
: dir
->untracked
->root
;
1594 while (current
< baselen
) {
1596 struct oid_stat oid_stat
;
1598 CALLOC_ARRAY(stk
, 1);
1603 cp
= strchr(base
+ current
+ 1, '/');
1605 die("oops in prep_exclude");
1608 lookup_untracked(dir
->untracked
,
1611 cp
- base
- current
);
1613 stk
->prev
= dir
->internal
.exclude_stack
;
1614 stk
->baselen
= cp
- base
;
1615 stk
->exclude_ix
= group
->nr
;
1616 stk
->ucd
= untracked
;
1617 pl
= add_pattern_list(dir
, EXC_DIRS
, NULL
);
1618 strbuf_add(&dir
->internal
.basebuf
, base
+ current
, stk
->baselen
- current
);
1619 assert(stk
->baselen
== dir
->internal
.basebuf
.len
);
1621 /* Abort if the directory is excluded */
1624 dir
->internal
.basebuf
.buf
[stk
->baselen
- 1] = 0;
1625 dir
->internal
.pattern
= last_matching_pattern_from_lists(dir
,
1627 dir
->internal
.basebuf
.buf
, stk
->baselen
- 1,
1628 dir
->internal
.basebuf
.buf
+ current
, &dt
);
1629 dir
->internal
.basebuf
.buf
[stk
->baselen
- 1] = '/';
1630 if (dir
->internal
.pattern
&&
1631 dir
->internal
.pattern
->flags
& PATTERN_FLAG_NEGATIVE
)
1632 dir
->internal
.pattern
= NULL
;
1633 if (dir
->internal
.pattern
) {
1634 dir
->internal
.exclude_stack
= stk
;
1639 /* Try to read per-directory file */
1640 oidclr(&oid_stat
.oid
);
1642 if (dir
->exclude_per_dir
&&
1644 * If we know that no files have been added in
1645 * this directory (i.e. valid_cached_dir() has
1646 * been executed and set untracked->valid) ..
1648 (!untracked
|| !untracked
->valid
||
1650 * .. and .gitignore does not exist before
1651 * (i.e. null exclude_oid). Then we can skip
1652 * loading .gitignore, which would result in
1655 !is_null_oid(&untracked
->exclude_oid
))) {
1657 * dir->internal.basebuf gets reused by the traversal,
1658 * but we need fname to remain unchanged to ensure the
1659 * src member of each struct path_pattern correctly
1660 * back-references its source file. Other invocations
1661 * of add_pattern_list provide stable strings, so we
1662 * strbuf_detach() and free() here in the caller.
1664 struct strbuf sb
= STRBUF_INIT
;
1665 strbuf_addbuf(&sb
, &dir
->internal
.basebuf
);
1666 strbuf_addstr(&sb
, dir
->exclude_per_dir
);
1667 pl
->src
= strbuf_detach(&sb
, NULL
);
1668 add_patterns(pl
->src
, pl
->src
, stk
->baselen
, pl
, istate
,
1670 untracked
? &oid_stat
: NULL
);
1673 * NEEDSWORK: when untracked cache is enabled, prep_exclude()
1674 * will first be called in valid_cached_dir() then maybe many
1675 * times more in last_matching_pattern(). When the cache is
1676 * used, last_matching_pattern() will not be called and
1677 * reading .gitignore content will be a waste.
1679 * So when it's called by valid_cached_dir() and we can get
1680 * .gitignore SHA-1 from the index (i.e. .gitignore is not
1681 * modified on work tree), we could delay reading the
1682 * .gitignore content until we absolutely need it in
1683 * last_matching_pattern(). Be careful about ignore rule
1684 * order, though, if you do that.
1687 !oideq(&oid_stat
.oid
, &untracked
->exclude_oid
)) {
1688 invalidate_gitignore(dir
->untracked
, untracked
);
1689 oidcpy(&untracked
->exclude_oid
, &oid_stat
.oid
);
1691 dir
->internal
.exclude_stack
= stk
;
1692 current
= stk
->baselen
;
1694 strbuf_setlen(&dir
->internal
.basebuf
, baselen
);
1698 * Loads the exclude lists for the directory containing pathname, then
1699 * scans all exclude lists to determine whether pathname is excluded.
1700 * Returns the exclude_list element which matched, or NULL for
1703 struct path_pattern
*last_matching_pattern(struct dir_struct
*dir
,
1704 struct index_state
*istate
,
1705 const char *pathname
,
1708 int pathlen
= strlen(pathname
);
1709 const char *basename
= strrchr(pathname
, '/');
1710 basename
= (basename
) ? basename
+1 : pathname
;
1712 prep_exclude(dir
, istate
, pathname
, basename
-pathname
);
1714 if (dir
->internal
.pattern
)
1715 return dir
->internal
.pattern
;
1717 return last_matching_pattern_from_lists(dir
, istate
, pathname
, pathlen
,
1722 * Loads the exclude lists for the directory containing pathname, then
1723 * scans all exclude lists to determine whether pathname is excluded.
1724 * Returns 1 if true, otherwise 0.
1726 int is_excluded(struct dir_struct
*dir
, struct index_state
*istate
,
1727 const char *pathname
, int *dtype_p
)
1729 struct path_pattern
*pattern
=
1730 last_matching_pattern(dir
, istate
, pathname
, dtype_p
);
1732 return pattern
->flags
& PATTERN_FLAG_NEGATIVE
? 0 : 1;
1736 static struct dir_entry
*dir_entry_new(const char *pathname
, int len
)
1738 struct dir_entry
*ent
;
1740 FLEX_ALLOC_MEM(ent
, name
, pathname
, len
);
1745 static struct dir_entry
*dir_add_name(struct dir_struct
*dir
,
1746 struct index_state
*istate
,
1747 const char *pathname
, int len
)
1749 if (index_file_exists(istate
, pathname
, len
, ignore_case
))
1752 ALLOC_GROW(dir
->entries
, dir
->nr
+1, dir
->internal
.alloc
);
1753 return dir
->entries
[dir
->nr
++] = dir_entry_new(pathname
, len
);
1756 struct dir_entry
*dir_add_ignored(struct dir_struct
*dir
,
1757 struct index_state
*istate
,
1758 const char *pathname
, int len
)
1760 if (!index_name_is_other(istate
, pathname
, len
))
1763 ALLOC_GROW(dir
->ignored
, dir
->ignored_nr
+1, dir
->internal
.ignored_alloc
);
1764 return dir
->ignored
[dir
->ignored_nr
++] = dir_entry_new(pathname
, len
);
1768 index_nonexistent
= 0,
1774 * Do not use the alphabetically sorted index to look up
1775 * the directory name; instead, use the case insensitive
1778 static enum exist_status
directory_exists_in_index_icase(struct index_state
*istate
,
1779 const char *dirname
, int len
)
1781 struct cache_entry
*ce
;
1783 if (index_dir_exists(istate
, dirname
, len
))
1784 return index_directory
;
1786 ce
= index_file_exists(istate
, dirname
, len
, ignore_case
);
1787 if (ce
&& S_ISGITLINK(ce
->ce_mode
))
1788 return index_gitdir
;
1790 return index_nonexistent
;
1794 * The index sorts alphabetically by entry name, which
1795 * means that a gitlink sorts as '\0' at the end, while
1796 * a directory (which is defined not as an entry, but as
1797 * the files it contains) will sort with the '/' at the
1800 static enum exist_status
directory_exists_in_index(struct index_state
*istate
,
1801 const char *dirname
, int len
)
1806 return directory_exists_in_index_icase(istate
, dirname
, len
);
1808 pos
= index_name_pos(istate
, dirname
, len
);
1811 while (pos
< istate
->cache_nr
) {
1812 const struct cache_entry
*ce
= istate
->cache
[pos
++];
1813 unsigned char endchar
;
1815 if (strncmp(ce
->name
, dirname
, len
))
1817 endchar
= ce
->name
[len
];
1821 return index_directory
;
1822 if (!endchar
&& S_ISGITLINK(ce
->ce_mode
))
1823 return index_gitdir
;
1825 return index_nonexistent
;
1829 * When we find a directory when traversing the filesystem, we
1830 * have three distinct cases:
1833 * - see it as a directory
1836 * and which one we choose depends on a combination of existing
1837 * git index contents and the flags passed into the directory
1838 * traversal routine.
1840 * Case 1: If we *already* have entries in the index under that
1841 * directory name, we always recurse into the directory to see
1844 * Case 2: If we *already* have that directory name as a gitlink,
1845 * we always continue to see it as a gitlink, regardless of whether
1846 * there is an actual git directory there or not (it might not
1847 * be checked out as a subproject!)
1849 * Case 3: if we didn't have it in the index previously, we
1850 * have a few sub-cases:
1852 * (a) if DIR_SHOW_OTHER_DIRECTORIES flag is set, we show it as
1853 * just a directory, unless DIR_HIDE_EMPTY_DIRECTORIES is
1854 * also true, in which case we need to check if it contains any
1855 * untracked and / or ignored files.
1856 * (b) if it looks like a git directory and we don't have the
1857 * DIR_NO_GITLINKS flag, then we treat it as a gitlink, and
1858 * show it as a directory.
1859 * (c) otherwise, we recurse into it.
1861 static enum path_treatment
treat_directory(struct dir_struct
*dir
,
1862 struct index_state
*istate
,
1863 struct untracked_cache_dir
*untracked
,
1864 const char *dirname
, int len
, int baselen
, int excluded
,
1865 const struct pathspec
*pathspec
)
1868 * WARNING: From this function, you can return path_recurse or you
1869 * can call read_directory_recursive() (or neither), but
1870 * you CAN'T DO BOTH.
1872 enum path_treatment state
;
1873 int matches_how
= 0;
1874 int check_only
, stop_early
;
1875 int old_ignored_nr
, old_untracked_nr
;
1876 /* The "len-1" is to strip the final '/' */
1877 enum exist_status status
= directory_exists_in_index(istate
, dirname
, len
-1);
1879 if (status
== index_directory
)
1880 return path_recurse
;
1881 if (status
== index_gitdir
)
1883 if (status
!= index_nonexistent
)
1884 BUG("Unhandled value for directory_exists_in_index: %d\n", status
);
1887 * We don't want to descend into paths that don't match the necessary
1888 * patterns. Clearly, if we don't have a pathspec, then we can't check
1889 * for matching patterns. Also, if (excluded) then we know we matched
1890 * the exclusion patterns so as an optimization we can skip checking
1891 * for matching patterns.
1893 if (pathspec
&& !excluded
) {
1894 matches_how
= match_pathspec_with_flags(istate
, pathspec
,
1898 DO_MATCH_LEADING_PATHSPEC
);
1904 if ((dir
->flags
& DIR_SKIP_NESTED_GIT
) ||
1905 !(dir
->flags
& DIR_NO_GITLINKS
)) {
1907 * Determine if `dirname` is a nested repo by confirming that:
1908 * 1) we are in a nonbare repository, and
1909 * 2) `dirname` is not an immediate parent of `the_repository->gitdir`,
1910 * which could occur if the git_dir or worktree location was
1911 * manually configured by the user; see t2205 testcases 1-3 for
1912 * examples where this matters
1915 struct strbuf sb
= STRBUF_INIT
;
1916 strbuf_addstr(&sb
, dirname
);
1917 nested_repo
= is_nonbare_repository_dir(&sb
);
1920 char *real_dirname
, *real_gitdir
;
1921 strbuf_addstr(&sb
, ".git");
1922 real_dirname
= real_pathdup(sb
.buf
, 1);
1923 real_gitdir
= real_pathdup(the_repository
->gitdir
, 1);
1925 nested_repo
= !!strcmp(real_dirname
, real_gitdir
);
1929 strbuf_release(&sb
);
1932 if ((dir
->flags
& DIR_SKIP_NESTED_GIT
) ||
1933 (matches_how
== MATCHED_RECURSIVELY_LEADING_PATHSPEC
))
1935 return excluded
? path_excluded
: path_untracked
;
1939 if (!(dir
->flags
& DIR_SHOW_OTHER_DIRECTORIES
)) {
1941 (dir
->flags
& DIR_SHOW_IGNORED_TOO
) &&
1942 (dir
->flags
& DIR_SHOW_IGNORED_TOO_MODE_MATCHING
)) {
1945 * This is an excluded directory and we are
1946 * showing ignored paths that match an exclude
1947 * pattern. (e.g. show directory as ignored
1948 * only if it matches an exclude pattern).
1949 * This path will either be 'path_excluded`
1950 * (if we are showing empty directories or if
1951 * the directory is not empty), or will be
1952 * 'path_none' (empty directory, and we are
1953 * not showing empty directories).
1955 if (!(dir
->flags
& DIR_HIDE_EMPTY_DIRECTORIES
))
1956 return path_excluded
;
1958 if (read_directory_recursive(dir
, istate
, dirname
, len
,
1959 untracked
, 1, 1, pathspec
) == path_excluded
)
1960 return path_excluded
;
1964 return path_recurse
;
1967 assert(dir
->flags
& DIR_SHOW_OTHER_DIRECTORIES
);
1970 * If we have a pathspec which could match something _below_ this
1971 * directory (e.g. when checking 'subdir/' having a pathspec like
1972 * 'subdir/some/deep/path/file' or 'subdir/widget-*.c'), then we
1975 if (matches_how
== MATCHED_RECURSIVELY_LEADING_PATHSPEC
)
1976 return path_recurse
;
1978 /* Special cases for where this directory is excluded/ignored */
1981 * If DIR_SHOW_OTHER_DIRECTORIES is set and we're not
1982 * hiding empty directories, there is no need to
1983 * recurse into an ignored directory.
1985 if (!(dir
->flags
& DIR_HIDE_EMPTY_DIRECTORIES
))
1986 return path_excluded
;
1989 * Even if we are hiding empty directories, we can still avoid
1990 * recursing into ignored directories for DIR_SHOW_IGNORED_TOO
1991 * if DIR_SHOW_IGNORED_TOO_MODE_MATCHING is also set.
1993 if ((dir
->flags
& DIR_SHOW_IGNORED_TOO
) &&
1994 (dir
->flags
& DIR_SHOW_IGNORED_TOO_MODE_MATCHING
))
1995 return path_excluded
;
1999 * Other than the path_recurse case above, we only need to
2000 * recurse into untracked directories if any of the following
2002 * - DIR_SHOW_IGNORED (because then we need to determine if
2003 * there are ignored entries below)
2004 * - DIR_SHOW_IGNORED_TOO (same as above)
2005 * - DIR_HIDE_EMPTY_DIRECTORIES (because we have to determine if
2006 * the directory is empty)
2009 !(dir
->flags
& (DIR_SHOW_IGNORED
|
2010 DIR_SHOW_IGNORED_TOO
|
2011 DIR_HIDE_EMPTY_DIRECTORIES
))) {
2012 return path_untracked
;
2016 * Even if we don't want to know all the paths under an untracked or
2017 * ignored directory, we may still need to go into the directory to
2018 * determine if it is empty (because with DIR_HIDE_EMPTY_DIRECTORIES,
2019 * an empty directory should be path_none instead of path_excluded or
2022 check_only
= ((dir
->flags
& DIR_HIDE_EMPTY_DIRECTORIES
) &&
2023 !(dir
->flags
& DIR_SHOW_IGNORED_TOO
));
2026 * However, there's another optimization possible as a subset of
2027 * check_only, based on the cases we have to consider:
2028 * A) Directory matches no exclude patterns:
2029 * * Directory is empty => path_none
2030 * * Directory has an untracked file under it => path_untracked
2031 * * Directory has only ignored files under it => path_excluded
2032 * B) Directory matches an exclude pattern:
2033 * * Directory is empty => path_none
2034 * * Directory has an untracked file under it => path_excluded
2035 * * Directory has only ignored files under it => path_excluded
2036 * In case A, we can exit as soon as we've found an untracked
2037 * file but otherwise have to walk all files. In case B, though,
2038 * we can stop at the first file we find under the directory.
2040 stop_early
= check_only
&& excluded
;
2043 * If /every/ file within an untracked directory is ignored, then
2044 * we want to treat the directory as ignored (for e.g. status
2045 * --porcelain), without listing the individual ignored files
2046 * underneath. To do so, we'll save the current ignored_nr, and
2047 * pop all the ones added after it if it turns out the entire
2048 * directory is ignored. Also, when DIR_SHOW_IGNORED_TOO and
2049 * !DIR_KEEP_UNTRACKED_CONTENTS then we don't want to show
2050 * untracked paths so will need to pop all those off the last
2051 * after we traverse.
2053 old_ignored_nr
= dir
->ignored_nr
;
2054 old_untracked_nr
= dir
->nr
;
2056 /* Actually recurse into dirname now, we'll fixup the state later. */
2057 untracked
= lookup_untracked(dir
->untracked
, untracked
,
2058 dirname
+ baselen
, len
- baselen
);
2059 state
= read_directory_recursive(dir
, istate
, dirname
, len
, untracked
,
2060 check_only
, stop_early
, pathspec
);
2062 /* There are a variety of reasons we may need to fixup the state... */
2063 if (state
== path_excluded
) {
2064 /* state == path_excluded implies all paths under
2065 * dirname were ignored...
2067 * if running e.g. `git status --porcelain --ignored=matching`,
2068 * then we want to see the subpaths that are ignored.
2070 * if running e.g. just `git status --porcelain`, then
2071 * we just want the directory itself to be listed as ignored
2072 * and not the individual paths underneath.
2074 int want_ignored_subpaths
=
2075 ((dir
->flags
& DIR_SHOW_IGNORED_TOO
) &&
2076 (dir
->flags
& DIR_SHOW_IGNORED_TOO_MODE_MATCHING
));
2078 if (want_ignored_subpaths
) {
2080 * with --ignored=matching, we want the subpaths
2081 * INSTEAD of the directory itself.
2086 for (i
= old_ignored_nr
+ 1; i
<dir
->ignored_nr
; ++i
)
2087 FREE_AND_NULL(dir
->ignored
[i
]);
2088 dir
->ignored_nr
= old_ignored_nr
;
2093 * We may need to ignore some of the untracked paths we found while
2094 * traversing subdirectories.
2096 if ((dir
->flags
& DIR_SHOW_IGNORED_TOO
) &&
2097 !(dir
->flags
& DIR_KEEP_UNTRACKED_CONTENTS
)) {
2099 for (i
= old_untracked_nr
+ 1; i
<dir
->nr
; ++i
)
2100 FREE_AND_NULL(dir
->entries
[i
]);
2101 dir
->nr
= old_untracked_nr
;
2105 * If there is nothing under the current directory and we are not
2106 * hiding empty directories, then we need to report on the
2107 * untracked or ignored status of the directory itself.
2109 if (state
== path_none
&& !(dir
->flags
& DIR_HIDE_EMPTY_DIRECTORIES
))
2110 state
= excluded
? path_excluded
: path_untracked
;
2116 * This is an inexact early pruning of any recursive directory
2117 * reading - if the path cannot possibly be in the pathspec,
2118 * return true, and we'll skip it early.
2120 static int simplify_away(const char *path
, int pathlen
,
2121 const struct pathspec
*pathspec
)
2125 if (!pathspec
|| !pathspec
->nr
)
2128 GUARD_PATHSPEC(pathspec
,
2137 for (i
= 0; i
< pathspec
->nr
; i
++) {
2138 const struct pathspec_item
*item
= &pathspec
->items
[i
];
2139 int len
= item
->nowildcard_len
;
2143 if (!ps_strncmp(item
, item
->match
, path
, len
))
2151 * This function tells us whether an excluded path matches a
2152 * list of "interesting" pathspecs. That is, whether a path matched
2153 * by any of the pathspecs could possibly be ignored by excluding
2154 * the specified path. This can happen if:
2156 * 1. the path is mentioned explicitly in the pathspec
2158 * 2. the path is a directory prefix of some element in the
2161 static int exclude_matches_pathspec(const char *path
, int pathlen
,
2162 const struct pathspec
*pathspec
)
2166 if (!pathspec
|| !pathspec
->nr
)
2169 GUARD_PATHSPEC(pathspec
,
2177 for (i
= 0; i
< pathspec
->nr
; i
++) {
2178 const struct pathspec_item
*item
= &pathspec
->items
[i
];
2179 int len
= item
->nowildcard_len
;
2181 if (len
== pathlen
&&
2182 !ps_strncmp(item
, item
->match
, path
, pathlen
))
2184 if (len
> pathlen
&&
2185 item
->match
[pathlen
] == '/' &&
2186 !ps_strncmp(item
, item
->match
, path
, pathlen
))
2192 static int get_index_dtype(struct index_state
*istate
,
2193 const char *path
, int len
)
2196 const struct cache_entry
*ce
;
2198 ce
= index_file_exists(istate
, path
, len
, 0);
2200 if (!ce_uptodate(ce
))
2202 if (S_ISGITLINK(ce
->ce_mode
))
2205 * Nobody actually cares about the
2206 * difference between DT_LNK and DT_REG
2211 /* Try to look it up as a directory */
2212 pos
= index_name_pos(istate
, path
, len
);
2216 while (pos
< istate
->cache_nr
) {
2217 ce
= istate
->cache
[pos
++];
2218 if (strncmp(ce
->name
, path
, len
))
2220 if (ce
->name
[len
] > '/')
2222 if (ce
->name
[len
] < '/')
2224 if (!ce_uptodate(ce
))
2225 break; /* continue? */
2231 static int resolve_dtype(int dtype
, struct index_state
*istate
,
2232 const char *path
, int len
)
2236 if (dtype
!= DT_UNKNOWN
)
2238 dtype
= get_index_dtype(istate
, path
, len
);
2239 if (dtype
!= DT_UNKNOWN
)
2241 if (lstat(path
, &st
))
2243 if (S_ISREG(st
.st_mode
))
2245 if (S_ISDIR(st
.st_mode
))
2247 if (S_ISLNK(st
.st_mode
))
2252 static enum path_treatment
treat_path_fast(struct dir_struct
*dir
,
2253 struct cached_dir
*cdir
,
2254 struct index_state
*istate
,
2255 struct strbuf
*path
,
2257 const struct pathspec
*pathspec
)
2260 * WARNING: From this function, you can return path_recurse or you
2261 * can call read_directory_recursive() (or neither), but
2262 * you CAN'T DO BOTH.
2264 strbuf_setlen(path
, baselen
);
2266 strbuf_addstr(path
, cdir
->file
);
2267 return path_untracked
;
2269 strbuf_addstr(path
, cdir
->ucd
->name
);
2270 /* treat_one_path() does this before it calls treat_directory() */
2271 strbuf_complete(path
, '/');
2272 if (cdir
->ucd
->check_only
)
2274 * check_only is set as a result of treat_directory() getting
2275 * to its bottom. Verify again the same set of directories
2276 * with check_only set.
2278 return read_directory_recursive(dir
, istate
, path
->buf
, path
->len
,
2279 cdir
->ucd
, 1, 0, pathspec
);
2281 * We get path_recurse in the first run when
2282 * directory_exists_in_index() returns index_nonexistent. We
2283 * are sure that new changes in the index does not impact the
2284 * outcome. Return now.
2286 return path_recurse
;
2289 static enum path_treatment
treat_path(struct dir_struct
*dir
,
2290 struct untracked_cache_dir
*untracked
,
2291 struct cached_dir
*cdir
,
2292 struct index_state
*istate
,
2293 struct strbuf
*path
,
2295 const struct pathspec
*pathspec
)
2297 int has_path_in_index
, dtype
, excluded
;
2300 return treat_path_fast(dir
, cdir
, istate
, path
,
2302 if (is_dot_or_dotdot(cdir
->d_name
) || !fspathcmp(cdir
->d_name
, ".git"))
2304 strbuf_setlen(path
, baselen
);
2305 strbuf_addstr(path
, cdir
->d_name
);
2306 if (simplify_away(path
->buf
, path
->len
, pathspec
))
2309 dtype
= resolve_dtype(cdir
->d_type
, istate
, path
->buf
, path
->len
);
2311 /* Always exclude indexed files */
2312 has_path_in_index
= !!index_file_exists(istate
, path
->buf
, path
->len
,
2314 if (dtype
!= DT_DIR
&& has_path_in_index
)
2318 * When we are looking at a directory P in the working tree,
2319 * there are three cases:
2321 * (1) P exists in the index. Everything inside the directory P in
2322 * the working tree needs to go when P is checked out from the
2325 * (2) P does not exist in the index, but there is P/Q in the index.
2326 * We know P will stay a directory when we check out the contents
2327 * of the index, but we do not know yet if there is a directory
2328 * P/Q in the working tree to be killed, so we need to recurse.
2330 * (3) P does not exist in the index, and there is no P/Q in the index
2331 * to require P to be a directory, either. Only in this case, we
2332 * know that everything inside P will not be killed without
2335 if ((dir
->flags
& DIR_COLLECT_KILLED_ONLY
) &&
2336 (dtype
== DT_DIR
) &&
2337 !has_path_in_index
&&
2338 (directory_exists_in_index(istate
, path
->buf
, path
->len
) == index_nonexistent
))
2341 excluded
= is_excluded(dir
, istate
, path
->buf
, &dtype
);
2344 * Excluded? If we don't explicitly want to show
2345 * ignored files, ignore it
2347 if (excluded
&& !(dir
->flags
& (DIR_SHOW_IGNORED
|DIR_SHOW_IGNORED_TOO
)))
2348 return path_excluded
;
2355 * WARNING: Do not ignore/amend the return value from
2356 * treat_directory(), and especially do not change it to return
2357 * path_recurse as that can cause exponential slowdown.
2358 * Instead, modify treat_directory() to return the right value.
2360 strbuf_addch(path
, '/');
2361 return treat_directory(dir
, istate
, untracked
,
2362 path
->buf
, path
->len
,
2363 baselen
, excluded
, pathspec
);
2367 !match_pathspec(istate
, pathspec
, path
->buf
, path
->len
,
2368 0 /* prefix */, NULL
/* seen */,
2372 return path_excluded
;
2373 return path_untracked
;
2377 static void add_untracked(struct untracked_cache_dir
*dir
, const char *name
)
2381 ALLOC_GROW(dir
->untracked
, dir
->untracked_nr
+ 1,
2382 dir
->untracked_alloc
);
2383 dir
->untracked
[dir
->untracked_nr
++] = xstrdup(name
);
2386 static int valid_cached_dir(struct dir_struct
*dir
,
2387 struct untracked_cache_dir
*untracked
,
2388 struct index_state
*istate
,
2389 struct strbuf
*path
,
2398 * With fsmonitor, we can trust the untracked cache's valid field.
2400 refresh_fsmonitor(istate
);
2401 if (!(dir
->untracked
->use_fsmonitor
&& untracked
->valid
)) {
2402 if (lstat(path
->len
? path
->buf
: ".", &st
)) {
2403 memset(&untracked
->stat_data
, 0, sizeof(untracked
->stat_data
));
2406 if (!untracked
->valid
||
2407 match_stat_data_racy(istate
, &untracked
->stat_data
, &st
)) {
2408 fill_stat_data(&untracked
->stat_data
, &st
);
2413 if (untracked
->check_only
!= !!check_only
)
2417 * prep_exclude will be called eventually on this directory,
2418 * but it's called much later in last_matching_pattern(). We
2419 * need it now to determine the validity of the cache for this
2420 * path. The next calls will be nearly no-op, the way
2421 * prep_exclude() is designed.
2423 if (path
->len
&& path
->buf
[path
->len
- 1] != '/') {
2424 strbuf_addch(path
, '/');
2425 prep_exclude(dir
, istate
, path
->buf
, path
->len
);
2426 strbuf_setlen(path
, path
->len
- 1);
2428 prep_exclude(dir
, istate
, path
->buf
, path
->len
);
2430 /* hopefully prep_exclude() haven't invalidated this entry... */
2431 return untracked
->valid
;
2434 static int open_cached_dir(struct cached_dir
*cdir
,
2435 struct dir_struct
*dir
,
2436 struct untracked_cache_dir
*untracked
,
2437 struct index_state
*istate
,
2438 struct strbuf
*path
,
2443 memset(cdir
, 0, sizeof(*cdir
));
2444 cdir
->untracked
= untracked
;
2445 if (valid_cached_dir(dir
, untracked
, istate
, path
, check_only
))
2447 c_path
= path
->len
? path
->buf
: ".";
2448 cdir
->fdir
= opendir(c_path
);
2450 warning_errno(_("could not open directory '%s'"), c_path
);
2451 if (dir
->untracked
) {
2452 invalidate_directory(dir
->untracked
, untracked
);
2453 dir
->untracked
->dir_opened
++;
2460 static int read_cached_dir(struct cached_dir
*cdir
)
2465 de
= readdir_skip_dot_and_dotdot(cdir
->fdir
);
2467 cdir
->d_name
= NULL
;
2468 cdir
->d_type
= DT_UNKNOWN
;
2471 cdir
->d_name
= de
->d_name
;
2472 cdir
->d_type
= DTYPE(de
);
2475 while (cdir
->nr_dirs
< cdir
->untracked
->dirs_nr
) {
2476 struct untracked_cache_dir
*d
= cdir
->untracked
->dirs
[cdir
->nr_dirs
];
2486 if (cdir
->nr_files
< cdir
->untracked
->untracked_nr
) {
2487 struct untracked_cache_dir
*d
= cdir
->untracked
;
2488 cdir
->file
= d
->untracked
[cdir
->nr_files
++];
2494 static void close_cached_dir(struct cached_dir
*cdir
)
2497 closedir(cdir
->fdir
);
2499 * We have gone through this directory and found no untracked
2500 * entries. Mark it valid.
2502 if (cdir
->untracked
) {
2503 cdir
->untracked
->valid
= 1;
2504 cdir
->untracked
->recurse
= 1;
2508 static void add_path_to_appropriate_result_list(struct dir_struct
*dir
,
2509 struct untracked_cache_dir
*untracked
,
2510 struct cached_dir
*cdir
,
2511 struct index_state
*istate
,
2512 struct strbuf
*path
,
2514 const struct pathspec
*pathspec
,
2515 enum path_treatment state
)
2517 /* add the path to the appropriate result list */
2520 if (dir
->flags
& DIR_SHOW_IGNORED
)
2521 dir_add_name(dir
, istate
, path
->buf
, path
->len
);
2522 else if ((dir
->flags
& DIR_SHOW_IGNORED_TOO
) ||
2523 ((dir
->flags
& DIR_COLLECT_IGNORED
) &&
2524 exclude_matches_pathspec(path
->buf
, path
->len
,
2526 dir_add_ignored(dir
, istate
, path
->buf
, path
->len
);
2529 case path_untracked
:
2530 if (dir
->flags
& DIR_SHOW_IGNORED
)
2532 dir_add_name(dir
, istate
, path
->buf
, path
->len
);
2534 add_untracked(untracked
, path
->buf
+ baselen
);
2543 * Read a directory tree. We currently ignore anything but
2544 * directories, regular files and symlinks. That's because git
2545 * doesn't handle them at all yet. Maybe that will change some
2548 * Also, we ignore the name ".git" (even if it is not a directory).
2549 * That likely will not change.
2551 * If 'stop_at_first_file' is specified, 'path_excluded' is returned
2552 * to signal that a file was found. This is the least significant value that
2553 * indicates that a file was encountered that does not depend on the order of
2554 * whether an untracked or excluded path was encountered first.
2556 * Returns the most significant path_treatment value encountered in the scan.
2557 * If 'stop_at_first_file' is specified, `path_excluded` is the most
2558 * significant path_treatment value that will be returned.
2561 static enum path_treatment
read_directory_recursive(struct dir_struct
*dir
,
2562 struct index_state
*istate
, const char *base
, int baselen
,
2563 struct untracked_cache_dir
*untracked
, int check_only
,
2564 int stop_at_first_file
, const struct pathspec
*pathspec
)
2567 * WARNING: Do NOT recurse unless path_recurse is returned from
2568 * treat_path(). Recursing on any other return value
2569 * can result in exponential slowdown.
2571 struct cached_dir cdir
;
2572 enum path_treatment state
, subdir_state
, dir_state
= path_none
;
2573 struct strbuf path
= STRBUF_INIT
;
2575 strbuf_add(&path
, base
, baselen
);
2577 if (open_cached_dir(&cdir
, dir
, untracked
, istate
, &path
, check_only
))
2579 dir
->internal
.visited_directories
++;
2582 untracked
->check_only
= !!check_only
;
2584 while (!read_cached_dir(&cdir
)) {
2585 /* check how the file or directory should be treated */
2586 state
= treat_path(dir
, untracked
, &cdir
, istate
, &path
,
2588 dir
->internal
.visited_paths
++;
2590 if (state
> dir_state
)
2593 /* recurse into subdir if instructed by treat_path */
2594 if (state
== path_recurse
) {
2595 struct untracked_cache_dir
*ud
;
2596 ud
= lookup_untracked(dir
->untracked
,
2599 path
.len
- baselen
);
2601 read_directory_recursive(dir
, istate
, path
.buf
,
2603 check_only
, stop_at_first_file
, pathspec
);
2604 if (subdir_state
> dir_state
)
2605 dir_state
= subdir_state
;
2608 !match_pathspec(istate
, pathspec
, path
.buf
, path
.len
,
2609 0 /* prefix */, NULL
,
2610 0 /* do NOT special case dirs */))
2615 if (stop_at_first_file
) {
2617 * If stopping at first file, then
2618 * signal that a file was found by
2619 * returning `path_excluded`. This is
2620 * to return a consistent value
2621 * regardless of whether an ignored or
2622 * excluded file happened to be
2625 * In current usage, the
2626 * `stop_at_first_file` is passed when
2627 * an ancestor directory has matched
2628 * an exclude pattern, so any found
2629 * files will be excluded.
2631 if (dir_state
>= path_excluded
) {
2632 dir_state
= path_excluded
;
2637 /* abort early if maximum state has been reached */
2638 if (dir_state
== path_untracked
) {
2640 add_untracked(untracked
, path
.buf
+ baselen
);
2643 /* skip the add_path_to_appropriate_result_list() */
2647 add_path_to_appropriate_result_list(dir
, untracked
, &cdir
,
2648 istate
, &path
, baselen
,
2651 close_cached_dir(&cdir
);
2653 strbuf_release(&path
);
2658 int cmp_dir_entry(const void *p1
, const void *p2
)
2660 const struct dir_entry
*e1
= *(const struct dir_entry
**)p1
;
2661 const struct dir_entry
*e2
= *(const struct dir_entry
**)p2
;
2663 return name_compare(e1
->name
, e1
->len
, e2
->name
, e2
->len
);
2666 /* check if *out lexically strictly contains *in */
2667 int check_dir_entry_contains(const struct dir_entry
*out
, const struct dir_entry
*in
)
2669 return (out
->len
< in
->len
) &&
2670 (out
->name
[out
->len
- 1] == '/') &&
2671 !memcmp(out
->name
, in
->name
, out
->len
);
2674 static int treat_leading_path(struct dir_struct
*dir
,
2675 struct index_state
*istate
,
2676 const char *path
, int len
,
2677 const struct pathspec
*pathspec
)
2679 struct strbuf sb
= STRBUF_INIT
;
2680 struct strbuf subdir
= STRBUF_INIT
;
2681 int prevlen
, baselen
;
2683 struct cached_dir cdir
;
2684 enum path_treatment state
= path_none
;
2687 * For each directory component of path, we are going to check whether
2688 * that path is relevant given the pathspec. For example, if path is
2690 * then we will ask treat_path() whether we should go into foo, then
2691 * whether we should go into bar, then whether baz is relevant.
2692 * Checking each is important because e.g. if path is
2694 * then we need to check .git to know we shouldn't traverse it.
2695 * If the return from treat_path() is:
2696 * * path_none, for any path, we return false.
2697 * * path_recurse, for all path components, we return true
2698 * * <anything else> for some intermediate component, we make sure
2699 * to add that path to the relevant list but return false
2700 * signifying that we shouldn't recurse into it.
2703 while (len
&& path
[len
- 1] == '/')
2708 memset(&cdir
, 0, sizeof(cdir
));
2709 cdir
.d_type
= DT_DIR
;
2713 prevlen
= baselen
+ !!baselen
;
2714 cp
= path
+ prevlen
;
2715 cp
= memchr(cp
, '/', path
+ len
- cp
);
2719 baselen
= cp
- path
;
2721 strbuf_add(&sb
, path
, baselen
);
2722 if (!is_directory(sb
.buf
))
2725 strbuf_add(&sb
, path
, prevlen
);
2726 strbuf_reset(&subdir
);
2727 strbuf_add(&subdir
, path
+prevlen
, baselen
-prevlen
);
2728 cdir
.d_name
= subdir
.buf
;
2729 state
= treat_path(dir
, NULL
, &cdir
, istate
, &sb
, prevlen
, pathspec
);
2731 if (state
!= path_recurse
)
2732 break; /* do not recurse into it */
2734 break; /* finished checking */
2736 add_path_to_appropriate_result_list(dir
, NULL
, &cdir
, istate
,
2737 &sb
, baselen
, pathspec
,
2740 strbuf_release(&subdir
);
2741 strbuf_release(&sb
);
2742 return state
== path_recurse
;
2745 static const char *get_ident_string(void)
2747 static struct strbuf sb
= STRBUF_INIT
;
2752 if (uname(&uts
) < 0)
2753 die_errno(_("failed to get kernel name and information"));
2754 strbuf_addf(&sb
, "Location %s, system %s", get_git_work_tree(),
2759 static int ident_in_untracked(const struct untracked_cache
*uc
)
2762 * Previous git versions may have saved many NUL separated
2763 * strings in the "ident" field, but it is insane to manage
2764 * many locations, so just take care of the first one.
2767 return !strcmp(uc
->ident
.buf
, get_ident_string());
2770 static void set_untracked_ident(struct untracked_cache
*uc
)
2772 strbuf_reset(&uc
->ident
);
2773 strbuf_addstr(&uc
->ident
, get_ident_string());
2776 * This strbuf used to contain a list of NUL separated
2777 * strings, so save NUL too for backward compatibility.
2779 strbuf_addch(&uc
->ident
, 0);
2782 static unsigned new_untracked_cache_flags(struct index_state
*istate
)
2784 struct repository
*repo
= istate
->repo
;
2788 * This logic is coordinated with the setting of these flags in
2789 * wt-status.c#wt_status_collect_untracked(), and the evaluation
2790 * of the config setting in commit.c#git_status_config()
2792 if (!repo_config_get_string(repo
, "status.showuntrackedfiles", &val
) &&
2793 !strcmp(val
, "all"))
2797 * The default, if "all" is not set, is "normal" - leading us here.
2798 * If the value is "none" then it really doesn't matter.
2800 return DIR_SHOW_OTHER_DIRECTORIES
| DIR_HIDE_EMPTY_DIRECTORIES
;
2803 static void new_untracked_cache(struct index_state
*istate
, int flags
)
2805 struct untracked_cache
*uc
= xcalloc(1, sizeof(*uc
));
2806 strbuf_init(&uc
->ident
, 100);
2807 uc
->exclude_per_dir
= ".gitignore";
2808 uc
->dir_flags
= flags
>= 0 ? flags
: new_untracked_cache_flags(istate
);
2809 set_untracked_ident(uc
);
2810 istate
->untracked
= uc
;
2811 istate
->cache_changed
|= UNTRACKED_CHANGED
;
2814 void add_untracked_cache(struct index_state
*istate
)
2816 if (!istate
->untracked
) {
2817 new_untracked_cache(istate
, -1);
2819 if (!ident_in_untracked(istate
->untracked
)) {
2820 free_untracked_cache(istate
->untracked
);
2821 new_untracked_cache(istate
, -1);
2826 void remove_untracked_cache(struct index_state
*istate
)
2828 if (istate
->untracked
) {
2829 free_untracked_cache(istate
->untracked
);
2830 istate
->untracked
= NULL
;
2831 istate
->cache_changed
|= UNTRACKED_CHANGED
;
2835 static struct untracked_cache_dir
*validate_untracked_cache(struct dir_struct
*dir
,
2837 const struct pathspec
*pathspec
,
2838 struct index_state
*istate
)
2840 struct untracked_cache_dir
*root
;
2841 static int untracked_cache_disabled
= -1;
2843 if (!dir
->untracked
)
2845 if (untracked_cache_disabled
< 0)
2846 untracked_cache_disabled
= git_env_bool("GIT_DISABLE_UNTRACKED_CACHE", 0);
2847 if (untracked_cache_disabled
)
2851 * We only support $GIT_DIR/info/exclude and core.excludesfile
2852 * as the global ignore rule files. Any other additions
2853 * (e.g. from command line) invalidate the cache. This
2854 * condition also catches running setup_standard_excludes()
2855 * before setting dir->untracked!
2857 if (dir
->internal
.unmanaged_exclude_files
)
2861 * Optimize for the main use case only: whole-tree git
2862 * status. More work involved in treat_leading_path() if we
2863 * use cache on just a subset of the worktree. pathspec
2864 * support could make the matter even worse.
2866 if (base_len
|| (pathspec
&& pathspec
->nr
))
2869 /* We don't support collecting ignore files */
2870 if (dir
->flags
& (DIR_SHOW_IGNORED
| DIR_SHOW_IGNORED_TOO
|
2871 DIR_COLLECT_IGNORED
))
2875 * If we use .gitignore in the cache and now you change it to
2876 * .gitexclude, everything will go wrong.
2878 if (dir
->exclude_per_dir
!= dir
->untracked
->exclude_per_dir
&&
2879 strcmp(dir
->exclude_per_dir
, dir
->untracked
->exclude_per_dir
))
2883 * EXC_CMDL is not considered in the cache. If people set it,
2886 if (dir
->internal
.exclude_list_group
[EXC_CMDL
].nr
)
2889 if (!ident_in_untracked(dir
->untracked
)) {
2890 warning(_("untracked cache is disabled on this system or location"));
2895 * If the untracked structure we received does not have the same flags
2896 * as requested in this run, we're going to need to either discard the
2897 * existing structure (and potentially later recreate), or bypass the
2898 * untracked cache mechanism for this run.
2900 if (dir
->flags
!= dir
->untracked
->dir_flags
) {
2902 * If the untracked structure we received does not have the same flags
2903 * as configured, then we need to reset / create a new "untracked"
2904 * structure to match the new config.
2906 * Keeping the saved and used untracked cache consistent with the
2907 * configuration provides an opportunity for frequent users of
2908 * "git status -uall" to leverage the untracked cache by aligning their
2909 * configuration - setting "status.showuntrackedfiles" to "all" or
2910 * "normal" as appropriate.
2912 * Previously using -uall (or setting "status.showuntrackedfiles" to
2913 * "all") was incompatible with untracked cache and *consistently*
2914 * caused surprisingly bad performance (with fscache and fsmonitor
2915 * enabled) on Windows.
2917 * IMPROVEMENT OPPORTUNITY: If we reworked the untracked cache storage
2918 * to not be as bound up with the desired output in a given run,
2919 * and instead iterated through and stored enough information to
2920 * correctly serve both "modes", then users could get peak performance
2921 * with or without '-uall' regardless of their
2922 * "status.showuntrackedfiles" config.
2924 if (dir
->untracked
->dir_flags
!= new_untracked_cache_flags(istate
)) {
2925 free_untracked_cache(istate
->untracked
);
2926 new_untracked_cache(istate
, dir
->flags
);
2927 dir
->untracked
= istate
->untracked
;
2931 * Current untracked cache data is consistent with config, but not
2932 * usable in this request/run; just bypass untracked cache.
2938 if (!dir
->untracked
->root
) {
2939 /* Untracked cache existed but is not initialized; fix that */
2940 FLEX_ALLOC_STR(dir
->untracked
->root
, name
, "");
2941 istate
->cache_changed
|= UNTRACKED_CHANGED
;
2944 /* Validate $GIT_DIR/info/exclude and core.excludesfile */
2945 root
= dir
->untracked
->root
;
2946 if (!oideq(&dir
->internal
.ss_info_exclude
.oid
,
2947 &dir
->untracked
->ss_info_exclude
.oid
)) {
2948 invalidate_gitignore(dir
->untracked
, root
);
2949 dir
->untracked
->ss_info_exclude
= dir
->internal
.ss_info_exclude
;
2951 if (!oideq(&dir
->internal
.ss_excludes_file
.oid
,
2952 &dir
->untracked
->ss_excludes_file
.oid
)) {
2953 invalidate_gitignore(dir
->untracked
, root
);
2954 dir
->untracked
->ss_excludes_file
= dir
->internal
.ss_excludes_file
;
2957 /* Make sure this directory is not dropped out at saving phase */
2962 static void emit_traversal_statistics(struct dir_struct
*dir
,
2963 struct repository
*repo
,
2967 if (!trace2_is_enabled())
2971 trace2_data_string("read_directory", repo
, "path", "");
2973 struct strbuf tmp
= STRBUF_INIT
;
2974 strbuf_add(&tmp
, path
, path_len
);
2975 trace2_data_string("read_directory", repo
, "path", tmp
.buf
);
2976 strbuf_release(&tmp
);
2979 trace2_data_intmax("read_directory", repo
,
2980 "directories-visited", dir
->internal
.visited_directories
);
2981 trace2_data_intmax("read_directory", repo
,
2982 "paths-visited", dir
->internal
.visited_paths
);
2984 if (!dir
->untracked
)
2986 trace2_data_intmax("read_directory", repo
,
2987 "node-creation", dir
->untracked
->dir_created
);
2988 trace2_data_intmax("read_directory", repo
,
2989 "gitignore-invalidation",
2990 dir
->untracked
->gitignore_invalidated
);
2991 trace2_data_intmax("read_directory", repo
,
2992 "directory-invalidation",
2993 dir
->untracked
->dir_invalidated
);
2994 trace2_data_intmax("read_directory", repo
,
2995 "opendir", dir
->untracked
->dir_opened
);
2998 int read_directory(struct dir_struct
*dir
, struct index_state
*istate
,
2999 const char *path
, int len
, const struct pathspec
*pathspec
)
3001 struct untracked_cache_dir
*untracked
;
3003 trace2_region_enter("dir", "read_directory", istate
->repo
);
3004 dir
->internal
.visited_paths
= 0;
3005 dir
->internal
.visited_directories
= 0;
3007 if (has_symlink_leading_path(path
, len
)) {
3008 trace2_region_leave("dir", "read_directory", istate
->repo
);
3012 untracked
= validate_untracked_cache(dir
, len
, pathspec
, istate
);
3015 * make sure untracked cache code path is disabled,
3016 * e.g. prep_exclude()
3018 dir
->untracked
= NULL
;
3019 if (!len
|| treat_leading_path(dir
, istate
, path
, len
, pathspec
))
3020 read_directory_recursive(dir
, istate
, path
, len
, untracked
, 0, 0, pathspec
);
3021 QSORT(dir
->entries
, dir
->nr
, cmp_dir_entry
);
3022 QSORT(dir
->ignored
, dir
->ignored_nr
, cmp_dir_entry
);
3024 emit_traversal_statistics(dir
, istate
->repo
, path
, len
);
3026 trace2_region_leave("dir", "read_directory", istate
->repo
);
3027 if (dir
->untracked
) {
3028 static int force_untracked_cache
= -1;
3030 if (force_untracked_cache
< 0)
3031 force_untracked_cache
=
3032 git_env_bool("GIT_FORCE_UNTRACKED_CACHE", -1);
3033 if (force_untracked_cache
< 0)
3034 force_untracked_cache
= (istate
->repo
->settings
.core_untracked_cache
== UNTRACKED_CACHE_WRITE
);
3035 if (force_untracked_cache
&&
3036 dir
->untracked
== istate
->untracked
&&
3037 (dir
->untracked
->dir_opened
||
3038 dir
->untracked
->gitignore_invalidated
||
3039 dir
->untracked
->dir_invalidated
))
3040 istate
->cache_changed
|= UNTRACKED_CHANGED
;
3041 if (dir
->untracked
!= istate
->untracked
) {
3042 FREE_AND_NULL(dir
->untracked
);
3049 int file_exists(const char *f
)
3052 return lstat(f
, &sb
) == 0;
3055 int repo_file_exists(struct repository
*repo
, const char *path
)
3057 if (repo
!= the_repository
)
3058 BUG("do not know how to check file existence in arbitrary repo");
3060 return file_exists(path
);
3063 static int cmp_icase(char a
, char b
)
3068 return toupper(a
) - toupper(b
);
3073 * Given two normalized paths (a trailing slash is ok), if subdir is
3074 * outside dir, return -1. Otherwise return the offset in subdir that
3075 * can be used as relative path to dir.
3077 int dir_inside_of(const char *subdir
, const char *dir
)
3081 assert(dir
&& subdir
&& *dir
&& *subdir
);
3083 while (*dir
&& *subdir
&& !cmp_icase(*dir
, *subdir
)) {
3089 /* hel[p]/me vs hel[l]/yeah */
3090 if (*dir
&& *subdir
)
3094 return !*dir
? offset
: -1; /* same dir */
3096 /* foo/[b]ar vs foo/[] */
3097 if (is_dir_sep(dir
[-1]))
3098 return is_dir_sep(subdir
[-1]) ? offset
: -1;
3100 /* foo[/]bar vs foo[] */
3101 return is_dir_sep(*subdir
) ? offset
+ 1 : -1;
3104 int is_inside_dir(const char *dir
)
3113 rc
= (dir_inside_of(cwd
, dir
) >= 0);
3118 int is_empty_dir(const char *path
)
3120 DIR *dir
= opendir(path
);
3127 e
= readdir_skip_dot_and_dotdot(dir
);
3135 char *git_url_basename(const char *repo
, int is_bundle
, int is_bare
)
3137 const char *end
= repo
+ strlen(repo
), *start
, *ptr
;
3144 start
= strstr(repo
, "://");
3151 * Skip authentication data. The stripping does happen
3152 * greedily, such that we strip up to the last '@' inside
3155 for (ptr
= start
; ptr
< end
&& !is_dir_sep(*ptr
); ptr
++) {
3161 * Strip trailing spaces, slashes and /.git
3163 while (start
< end
&& (is_dir_sep(end
[-1]) || isspace(end
[-1])))
3165 if (end
- start
> 5 && is_dir_sep(end
[-5]) &&
3166 !strncmp(end
- 4, ".git", 4)) {
3168 while (start
< end
&& is_dir_sep(end
[-1]))
3173 * It should not be possible to overflow `ptrdiff_t` by passing in an
3174 * insanely long URL, but GCC does not know that and will complain
3175 * without this check.
3177 if (end
- start
< 0)
3178 die(_("No directory name could be guessed.\n"
3179 "Please specify a directory on the command line"));
3182 * Strip trailing port number if we've got only a
3183 * hostname (that is, there is no dir separator but a
3184 * colon). This check is required such that we do not
3185 * strip URI's like '/foo/bar:2222.git', which should
3186 * result in a dir '2222' being guessed due to backwards
3189 if (memchr(start
, '/', end
- start
) == NULL
3190 && memchr(start
, ':', end
- start
) != NULL
) {
3192 while (start
< ptr
&& isdigit(ptr
[-1]) && ptr
[-1] != ':')
3194 if (start
< ptr
&& ptr
[-1] == ':')
3199 * Find last component. To remain backwards compatible we
3200 * also regard colons as path separators, such that
3201 * cloning a repository 'foo:bar.git' would result in a
3202 * directory 'bar' being guessed.
3205 while (start
< ptr
&& !is_dir_sep(ptr
[-1]) && ptr
[-1] != ':')
3210 * Strip .{bundle,git}.
3213 strip_suffix_mem(start
, &len
, is_bundle
? ".bundle" : ".git");
3215 if (!len
|| (len
== 1 && *start
== '/'))
3216 die(_("No directory name could be guessed.\n"
3217 "Please specify a directory on the command line"));
3220 dir
= xstrfmt("%.*s.git", (int)len
, start
);
3222 dir
= xstrndup(start
, len
);
3224 * Replace sequences of 'control' characters and whitespace
3225 * with one ascii space, remove leading and trailing spaces.
3229 int prev_space
= 1 /* strip leading whitespace */;
3230 for (end
= dir
; *end
; ++end
) {
3232 if ((unsigned char)ch
< '\x20')
3243 if (out
> dir
&& prev_space
)
3249 void strip_dir_trailing_slashes(char *dir
)
3251 char *end
= dir
+ strlen(dir
);
3253 while (dir
< end
- 1 && is_dir_sep(end
[-1]))
3258 static int remove_dir_recurse(struct strbuf
*path
, int flag
, int *kept_up
)
3262 int ret
= 0, original_len
= path
->len
, len
, kept_down
= 0;
3263 int only_empty
= (flag
& REMOVE_DIR_EMPTY_ONLY
);
3264 int keep_toplevel
= (flag
& REMOVE_DIR_KEEP_TOPLEVEL
);
3265 int purge_original_cwd
= (flag
& REMOVE_DIR_PURGE_ORIGINAL_CWD
);
3266 struct object_id submodule_head
;
3268 if ((flag
& REMOVE_DIR_KEEP_NESTED_GIT
) &&
3269 !resolve_gitlink_ref(path
->buf
, "HEAD", &submodule_head
)) {
3270 /* Do not descend and nuke a nested git work tree. */
3276 flag
&= ~REMOVE_DIR_KEEP_TOPLEVEL
;
3277 dir
= opendir(path
->buf
);
3279 if (errno
== ENOENT
)
3280 return keep_toplevel
? -1 : 0;
3281 else if (errno
== EACCES
&& !keep_toplevel
)
3283 * An empty dir could be removable even if it
3286 return rmdir(path
->buf
);
3290 strbuf_complete(path
, '/');
3293 while ((e
= readdir_skip_dot_and_dotdot(dir
)) != NULL
) {
3296 strbuf_setlen(path
, len
);
3297 strbuf_addstr(path
, e
->d_name
);
3298 if (lstat(path
->buf
, &st
)) {
3299 if (errno
== ENOENT
)
3301 * file disappeared, which is what we
3306 } else if (S_ISDIR(st
.st_mode
)) {
3307 if (!remove_dir_recurse(path
, flag
, &kept_down
))
3308 continue; /* happy */
3309 } else if (!only_empty
&&
3310 (!unlink(path
->buf
) || errno
== ENOENT
)) {
3311 continue; /* happy, too */
3314 /* path too long, stat fails, or non-directory still exists */
3320 strbuf_setlen(path
, original_len
);
3321 if (!ret
&& !keep_toplevel
&& !kept_down
) {
3322 if (!purge_original_cwd
&&
3323 startup_info
->original_cwd
&&
3324 !strcmp(startup_info
->original_cwd
, path
->buf
))
3325 ret
= -1; /* Do not remove current working directory */
3327 ret
= (!rmdir(path
->buf
) || errno
== ENOENT
) ? 0 : -1;
3330 * report the uplevel that it is not an error that we
3331 * did not rmdir() our directory.
3337 int remove_dir_recursively(struct strbuf
*path
, int flag
)
3339 return remove_dir_recurse(path
, flag
, NULL
);
3342 static GIT_PATH_FUNC(git_path_info_exclude
, "info/exclude")
3344 void setup_standard_excludes(struct dir_struct
*dir
)
3346 dir
->exclude_per_dir
= ".gitignore";
3348 /* core.excludesfile defaulting to $XDG_CONFIG_HOME/git/ignore */
3350 excludes_file
= xdg_config_home("ignore");
3351 if (excludes_file
&& !access_or_warn(excludes_file
, R_OK
, 0))
3352 add_patterns_from_file_1(dir
, excludes_file
,
3353 dir
->untracked
? &dir
->internal
.ss_excludes_file
: NULL
);
3355 /* per repository user preference */
3356 if (startup_info
->have_repository
) {
3357 const char *path
= git_path_info_exclude();
3358 if (!access_or_warn(path
, R_OK
, 0))
3359 add_patterns_from_file_1(dir
, path
,
3360 dir
->untracked
? &dir
->internal
.ss_info_exclude
: NULL
);
3364 char *get_sparse_checkout_filename(void)
3366 return git_pathdup("info/sparse-checkout");
3369 int get_sparse_checkout_patterns(struct pattern_list
*pl
)
3372 char *sparse_filename
= get_sparse_checkout_filename();
3374 pl
->use_cone_patterns
= core_sparse_checkout_cone
;
3375 res
= add_patterns_from_file_to_list(sparse_filename
, "", 0, pl
, NULL
, 0);
3377 free(sparse_filename
);
3381 int remove_path(const char *name
)
3385 if (unlink(name
) && !is_missing_file_error(errno
))
3388 slash
= strrchr(name
, '/');
3390 char *dirs
= xstrdup(name
);
3391 slash
= dirs
+ (slash
- name
);
3394 if (startup_info
->original_cwd
&&
3395 !strcmp(startup_info
->original_cwd
, dirs
))
3397 } while (rmdir(dirs
) == 0 && (slash
= strrchr(dirs
, '/')));
3404 * Frees memory within dir which was allocated, and resets fields for further
3405 * use. Does not free dir itself.
3407 void dir_clear(struct dir_struct
*dir
)
3410 struct exclude_list_group
*group
;
3411 struct pattern_list
*pl
;
3412 struct exclude_stack
*stk
;
3413 struct dir_struct
new = DIR_INIT
;
3415 for (i
= EXC_CMDL
; i
<= EXC_FILE
; i
++) {
3416 group
= &dir
->internal
.exclude_list_group
[i
];
3417 for (j
= 0; j
< group
->nr
; j
++) {
3420 free((char *)pl
->src
);
3421 clear_pattern_list(pl
);
3426 for (i
= 0; i
< dir
->ignored_nr
; i
++)
3427 free(dir
->ignored
[i
]);
3428 for (i
= 0; i
< dir
->nr
; i
++)
3429 free(dir
->entries
[i
]);
3433 stk
= dir
->internal
.exclude_stack
;
3435 struct exclude_stack
*prev
= stk
->prev
;
3439 strbuf_release(&dir
->internal
.basebuf
);
3441 memcpy(dir
, &new, sizeof(*dir
));
3444 struct ondisk_untracked_cache
{
3445 struct stat_data info_exclude_stat
;
3446 struct stat_data excludes_file_stat
;
3450 #define ouc_offset(x) offsetof(struct ondisk_untracked_cache, x)
3453 int index
; /* number of written untracked_cache_dir */
3454 struct ewah_bitmap
*check_only
; /* from untracked_cache_dir */
3455 struct ewah_bitmap
*valid
; /* from untracked_cache_dir */
3456 struct ewah_bitmap
*sha1_valid
; /* set if exclude_sha1 is not null */
3458 struct strbuf sb_stat
;
3459 struct strbuf sb_sha1
;
3462 static void stat_data_to_disk(struct stat_data
*to
, const struct stat_data
*from
)
3464 to
->sd_ctime
.sec
= htonl(from
->sd_ctime
.sec
);
3465 to
->sd_ctime
.nsec
= htonl(from
->sd_ctime
.nsec
);
3466 to
->sd_mtime
.sec
= htonl(from
->sd_mtime
.sec
);
3467 to
->sd_mtime
.nsec
= htonl(from
->sd_mtime
.nsec
);
3468 to
->sd_dev
= htonl(from
->sd_dev
);
3469 to
->sd_ino
= htonl(from
->sd_ino
);
3470 to
->sd_uid
= htonl(from
->sd_uid
);
3471 to
->sd_gid
= htonl(from
->sd_gid
);
3472 to
->sd_size
= htonl(from
->sd_size
);
3475 static void write_one_dir(struct untracked_cache_dir
*untracked
,
3476 struct write_data
*wd
)
3478 struct stat_data stat_data
;
3479 struct strbuf
*out
= &wd
->out
;
3480 unsigned char intbuf
[16];
3481 unsigned int intlen
, value
;
3482 int i
= wd
->index
++;
3485 * untracked_nr should be reset whenever valid is clear, but
3488 if (!untracked
->valid
) {
3489 untracked
->untracked_nr
= 0;
3490 untracked
->check_only
= 0;
3493 if (untracked
->check_only
)
3494 ewah_set(wd
->check_only
, i
);
3495 if (untracked
->valid
) {
3496 ewah_set(wd
->valid
, i
);
3497 stat_data_to_disk(&stat_data
, &untracked
->stat_data
);
3498 strbuf_add(&wd
->sb_stat
, &stat_data
, sizeof(stat_data
));
3500 if (!is_null_oid(&untracked
->exclude_oid
)) {
3501 ewah_set(wd
->sha1_valid
, i
);
3502 strbuf_add(&wd
->sb_sha1
, untracked
->exclude_oid
.hash
,
3503 the_hash_algo
->rawsz
);
3506 intlen
= encode_varint(untracked
->untracked_nr
, intbuf
);
3507 strbuf_add(out
, intbuf
, intlen
);
3509 /* skip non-recurse directories */
3510 for (i
= 0, value
= 0; i
< untracked
->dirs_nr
; i
++)
3511 if (untracked
->dirs
[i
]->recurse
)
3513 intlen
= encode_varint(value
, intbuf
);
3514 strbuf_add(out
, intbuf
, intlen
);
3516 strbuf_add(out
, untracked
->name
, strlen(untracked
->name
) + 1);
3518 for (i
= 0; i
< untracked
->untracked_nr
; i
++)
3519 strbuf_add(out
, untracked
->untracked
[i
],
3520 strlen(untracked
->untracked
[i
]) + 1);
3522 for (i
= 0; i
< untracked
->dirs_nr
; i
++)
3523 if (untracked
->dirs
[i
]->recurse
)
3524 write_one_dir(untracked
->dirs
[i
], wd
);
3527 void write_untracked_extension(struct strbuf
*out
, struct untracked_cache
*untracked
)
3529 struct ondisk_untracked_cache
*ouc
;
3530 struct write_data wd
;
3531 unsigned char varbuf
[16];
3533 const unsigned hashsz
= the_hash_algo
->rawsz
;
3535 CALLOC_ARRAY(ouc
, 1);
3536 stat_data_to_disk(&ouc
->info_exclude_stat
, &untracked
->ss_info_exclude
.stat
);
3537 stat_data_to_disk(&ouc
->excludes_file_stat
, &untracked
->ss_excludes_file
.stat
);
3538 ouc
->dir_flags
= htonl(untracked
->dir_flags
);
3540 varint_len
= encode_varint(untracked
->ident
.len
, varbuf
);
3541 strbuf_add(out
, varbuf
, varint_len
);
3542 strbuf_addbuf(out
, &untracked
->ident
);
3544 strbuf_add(out
, ouc
, sizeof(*ouc
));
3545 strbuf_add(out
, untracked
->ss_info_exclude
.oid
.hash
, hashsz
);
3546 strbuf_add(out
, untracked
->ss_excludes_file
.oid
.hash
, hashsz
);
3547 strbuf_add(out
, untracked
->exclude_per_dir
, strlen(untracked
->exclude_per_dir
) + 1);
3550 if (!untracked
->root
) {
3551 varint_len
= encode_varint(0, varbuf
);
3552 strbuf_add(out
, varbuf
, varint_len
);
3557 wd
.check_only
= ewah_new();
3558 wd
.valid
= ewah_new();
3559 wd
.sha1_valid
= ewah_new();
3560 strbuf_init(&wd
.out
, 1024);
3561 strbuf_init(&wd
.sb_stat
, 1024);
3562 strbuf_init(&wd
.sb_sha1
, 1024);
3563 write_one_dir(untracked
->root
, &wd
);
3565 varint_len
= encode_varint(wd
.index
, varbuf
);
3566 strbuf_add(out
, varbuf
, varint_len
);
3567 strbuf_addbuf(out
, &wd
.out
);
3568 ewah_serialize_strbuf(wd
.valid
, out
);
3569 ewah_serialize_strbuf(wd
.check_only
, out
);
3570 ewah_serialize_strbuf(wd
.sha1_valid
, out
);
3571 strbuf_addbuf(out
, &wd
.sb_stat
);
3572 strbuf_addbuf(out
, &wd
.sb_sha1
);
3573 strbuf_addch(out
, '\0'); /* safe guard for string lists */
3575 ewah_free(wd
.valid
);
3576 ewah_free(wd
.check_only
);
3577 ewah_free(wd
.sha1_valid
);
3578 strbuf_release(&wd
.out
);
3579 strbuf_release(&wd
.sb_stat
);
3580 strbuf_release(&wd
.sb_sha1
);
3583 static void free_untracked(struct untracked_cache_dir
*ucd
)
3588 for (i
= 0; i
< ucd
->dirs_nr
; i
++)
3589 free_untracked(ucd
->dirs
[i
]);
3590 for (i
= 0; i
< ucd
->untracked_nr
; i
++)
3591 free(ucd
->untracked
[i
]);
3592 free(ucd
->untracked
);
3597 void free_untracked_cache(struct untracked_cache
*uc
)
3602 free(uc
->exclude_per_dir_to_free
);
3603 strbuf_release(&uc
->ident
);
3604 free_untracked(uc
->root
);
3610 struct untracked_cache_dir
**ucd
;
3611 struct ewah_bitmap
*check_only
;
3612 struct ewah_bitmap
*valid
;
3613 struct ewah_bitmap
*sha1_valid
;
3614 const unsigned char *data
;
3615 const unsigned char *end
;
3618 static void stat_data_from_disk(struct stat_data
*to
, const unsigned char *data
)
3620 memcpy(to
, data
, sizeof(*to
));
3621 to
->sd_ctime
.sec
= ntohl(to
->sd_ctime
.sec
);
3622 to
->sd_ctime
.nsec
= ntohl(to
->sd_ctime
.nsec
);
3623 to
->sd_mtime
.sec
= ntohl(to
->sd_mtime
.sec
);
3624 to
->sd_mtime
.nsec
= ntohl(to
->sd_mtime
.nsec
);
3625 to
->sd_dev
= ntohl(to
->sd_dev
);
3626 to
->sd_ino
= ntohl(to
->sd_ino
);
3627 to
->sd_uid
= ntohl(to
->sd_uid
);
3628 to
->sd_gid
= ntohl(to
->sd_gid
);
3629 to
->sd_size
= ntohl(to
->sd_size
);
3632 static int read_one_dir(struct untracked_cache_dir
**untracked_
,
3633 struct read_data
*rd
)
3635 struct untracked_cache_dir ud
, *untracked
;
3636 const unsigned char *data
= rd
->data
, *end
= rd
->end
;
3637 const unsigned char *eos
;
3641 memset(&ud
, 0, sizeof(ud
));
3643 value
= decode_varint(&data
);
3647 ud
.untracked_alloc
= value
;
3648 ud
.untracked_nr
= value
;
3649 if (ud
.untracked_nr
)
3650 ALLOC_ARRAY(ud
.untracked
, ud
.untracked_nr
);
3652 ud
.dirs_alloc
= ud
.dirs_nr
= decode_varint(&data
);
3655 ALLOC_ARRAY(ud
.dirs
, ud
.dirs_nr
);
3657 eos
= memchr(data
, '\0', end
- data
);
3658 if (!eos
|| eos
== end
)
3661 *untracked_
= untracked
= xmalloc(st_add3(sizeof(*untracked
), eos
- data
, 1));
3662 memcpy(untracked
, &ud
, sizeof(ud
));
3663 memcpy(untracked
->name
, data
, eos
- data
+ 1);
3666 for (i
= 0; i
< untracked
->untracked_nr
; i
++) {
3667 eos
= memchr(data
, '\0', end
- data
);
3668 if (!eos
|| eos
== end
)
3670 untracked
->untracked
[i
] = xmemdupz(data
, eos
- data
);
3674 rd
->ucd
[rd
->index
++] = untracked
;
3677 for (i
= 0; i
< untracked
->dirs_nr
; i
++) {
3678 if (read_one_dir(untracked
->dirs
+ i
, rd
) < 0)
3684 static void set_check_only(size_t pos
, void *cb
)
3686 struct read_data
*rd
= cb
;
3687 struct untracked_cache_dir
*ud
= rd
->ucd
[pos
];
3691 static void read_stat(size_t pos
, void *cb
)
3693 struct read_data
*rd
= cb
;
3694 struct untracked_cache_dir
*ud
= rd
->ucd
[pos
];
3695 if (rd
->data
+ sizeof(struct stat_data
) > rd
->end
) {
3696 rd
->data
= rd
->end
+ 1;
3699 stat_data_from_disk(&ud
->stat_data
, rd
->data
);
3700 rd
->data
+= sizeof(struct stat_data
);
3704 static void read_oid(size_t pos
, void *cb
)
3706 struct read_data
*rd
= cb
;
3707 struct untracked_cache_dir
*ud
= rd
->ucd
[pos
];
3708 if (rd
->data
+ the_hash_algo
->rawsz
> rd
->end
) {
3709 rd
->data
= rd
->end
+ 1;
3712 oidread(&ud
->exclude_oid
, rd
->data
);
3713 rd
->data
+= the_hash_algo
->rawsz
;
3716 static void load_oid_stat(struct oid_stat
*oid_stat
, const unsigned char *data
,
3717 const unsigned char *sha1
)
3719 stat_data_from_disk(&oid_stat
->stat
, data
);
3720 oidread(&oid_stat
->oid
, sha1
);
3721 oid_stat
->valid
= 1;
3724 struct untracked_cache
*read_untracked_extension(const void *data
, unsigned long sz
)
3726 struct untracked_cache
*uc
;
3727 struct read_data rd
;
3728 const unsigned char *next
= data
, *end
= (const unsigned char *)data
+ sz
;
3732 const char *exclude_per_dir
;
3733 const unsigned hashsz
= the_hash_algo
->rawsz
;
3734 const unsigned offset
= sizeof(struct ondisk_untracked_cache
);
3735 const unsigned exclude_per_dir_offset
= offset
+ 2 * hashsz
;
3737 if (sz
<= 1 || end
[-1] != '\0')
3741 ident_len
= decode_varint(&next
);
3742 if (next
+ ident_len
> end
)
3744 ident
= (const char *)next
;
3747 if (next
+ exclude_per_dir_offset
+ 1 > end
)
3750 CALLOC_ARRAY(uc
, 1);
3751 strbuf_init(&uc
->ident
, ident_len
);
3752 strbuf_add(&uc
->ident
, ident
, ident_len
);
3753 load_oid_stat(&uc
->ss_info_exclude
,
3754 next
+ ouc_offset(info_exclude_stat
),
3756 load_oid_stat(&uc
->ss_excludes_file
,
3757 next
+ ouc_offset(excludes_file_stat
),
3758 next
+ offset
+ hashsz
);
3759 uc
->dir_flags
= get_be32(next
+ ouc_offset(dir_flags
));
3760 exclude_per_dir
= (const char *)next
+ exclude_per_dir_offset
;
3761 uc
->exclude_per_dir
= uc
->exclude_per_dir_to_free
= xstrdup(exclude_per_dir
);
3762 /* NUL after exclude_per_dir is covered by sizeof(*ouc) */
3763 next
+= exclude_per_dir_offset
+ strlen(exclude_per_dir
) + 1;
3767 len
= decode_varint(&next
);
3768 if (next
> end
|| len
== 0)
3771 rd
.valid
= ewah_new();
3772 rd
.check_only
= ewah_new();
3773 rd
.sha1_valid
= ewah_new();
3777 ALLOC_ARRAY(rd
.ucd
, len
);
3779 if (read_one_dir(&uc
->root
, &rd
) || rd
.index
!= len
)
3783 len
= ewah_read_mmap(rd
.valid
, next
, end
- next
);
3788 len
= ewah_read_mmap(rd
.check_only
, next
, end
- next
);
3793 len
= ewah_read_mmap(rd
.sha1_valid
, next
, end
- next
);
3797 ewah_each_bit(rd
.check_only
, set_check_only
, &rd
);
3798 rd
.data
= next
+ len
;
3799 ewah_each_bit(rd
.valid
, read_stat
, &rd
);
3800 ewah_each_bit(rd
.sha1_valid
, read_oid
, &rd
);
3805 ewah_free(rd
.valid
);
3806 ewah_free(rd
.check_only
);
3807 ewah_free(rd
.sha1_valid
);
3810 free_untracked_cache(uc
);
3816 static void invalidate_one_directory(struct untracked_cache
*uc
,
3817 struct untracked_cache_dir
*ucd
)
3819 uc
->dir_invalidated
++;
3821 ucd
->untracked_nr
= 0;
3825 * Normally when an entry is added or removed from a directory,
3826 * invalidating that directory is enough. No need to touch its
3827 * ancestors. When a directory is shown as "foo/bar/" in git-status
3828 * however, deleting or adding an entry may have cascading effect.
3830 * Say the "foo/bar/file" has become untracked, we need to tell the
3831 * untracked_cache_dir of "foo" that "bar/" is not an untracked
3832 * directory any more (because "bar" is managed by foo as an untracked
3835 * Similarly, if "foo/bar/file" moves from untracked to tracked and it
3836 * was the last untracked entry in the entire "foo", we should show
3837 * "foo/" instead. Which means we have to invalidate past "bar" up to
3840 * This function traverses all directories from root to leaf. If there
3841 * is a chance of one of the above cases happening, we invalidate back
3842 * to root. Otherwise we just invalidate the leaf. There may be a more
3843 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to
3844 * detect these cases and avoid unnecessary invalidation, for example,
3845 * checking for the untracked entry named "bar/" in "foo", but for now
3846 * stick to something safe and simple.
3848 static int invalidate_one_component(struct untracked_cache
*uc
,
3849 struct untracked_cache_dir
*dir
,
3850 const char *path
, int len
)
3852 const char *rest
= strchr(path
, '/');
3855 int component_len
= rest
- path
;
3856 struct untracked_cache_dir
*d
=
3857 lookup_untracked(uc
, dir
, path
, component_len
);
3859 invalidate_one_component(uc
, d
, rest
+ 1,
3860 len
- (component_len
+ 1));
3862 invalidate_one_directory(uc
, dir
);
3866 invalidate_one_directory(uc
, dir
);
3867 return uc
->dir_flags
& DIR_SHOW_OTHER_DIRECTORIES
;
3870 void untracked_cache_invalidate_path(struct index_state
*istate
,
3871 const char *path
, int safe_path
)
3873 if (!istate
->untracked
|| !istate
->untracked
->root
)
3875 if (!safe_path
&& !verify_path(path
, 0))
3877 invalidate_one_component(istate
->untracked
, istate
->untracked
->root
,
3878 path
, strlen(path
));
3881 void untracked_cache_remove_from_index(struct index_state
*istate
,
3884 untracked_cache_invalidate_path(istate
, path
, 1);
3887 void untracked_cache_add_to_index(struct index_state
*istate
,
3890 untracked_cache_invalidate_path(istate
, path
, 1);
3893 static void connect_wt_gitdir_in_nested(const char *sub_worktree
,
3894 const char *sub_gitdir
)
3897 struct repository subrepo
;
3898 struct strbuf sub_wt
= STRBUF_INIT
;
3899 struct strbuf sub_gd
= STRBUF_INIT
;
3901 const struct submodule
*sub
;
3903 /* If the submodule has no working tree, we can ignore it. */
3904 if (repo_init(&subrepo
, sub_gitdir
, sub_worktree
))
3907 if (repo_read_index(&subrepo
) < 0)
3908 die(_("index file corrupt in repo %s"), subrepo
.gitdir
);
3910 /* TODO: audit for interaction with sparse-index. */
3911 ensure_full_index(subrepo
.index
);
3912 for (i
= 0; i
< subrepo
.index
->cache_nr
; i
++) {
3913 const struct cache_entry
*ce
= subrepo
.index
->cache
[i
];
3915 if (!S_ISGITLINK(ce
->ce_mode
))
3918 while (i
+ 1 < subrepo
.index
->cache_nr
&&
3919 !strcmp(ce
->name
, subrepo
.index
->cache
[i
+ 1]->name
))
3921 * Skip entries with the same name in different stages
3922 * to make sure an entry is returned only once.
3926 sub
= submodule_from_path(&subrepo
, null_oid(), ce
->name
);
3927 if (!sub
|| !is_submodule_active(&subrepo
, ce
->name
))
3928 /* .gitmodules broken or inactive sub */
3931 strbuf_reset(&sub_wt
);
3932 strbuf_reset(&sub_gd
);
3933 strbuf_addf(&sub_wt
, "%s/%s", sub_worktree
, sub
->path
);
3934 submodule_name_to_gitdir(&sub_gd
, &subrepo
, sub
->name
);
3936 connect_work_tree_and_git_dir(sub_wt
.buf
, sub_gd
.buf
, 1);
3938 strbuf_release(&sub_wt
);
3939 strbuf_release(&sub_gd
);
3940 repo_clear(&subrepo
);
3943 void connect_work_tree_and_git_dir(const char *work_tree_
,
3944 const char *git_dir_
,
3945 int recurse_into_nested
)
3947 struct strbuf gitfile_sb
= STRBUF_INIT
;
3948 struct strbuf cfg_sb
= STRBUF_INIT
;
3949 struct strbuf rel_path
= STRBUF_INIT
;
3950 char *git_dir
, *work_tree
;
3952 /* Prepare .git file */
3953 strbuf_addf(&gitfile_sb
, "%s/.git", work_tree_
);
3954 if (safe_create_leading_directories_const(gitfile_sb
.buf
))
3955 die(_("could not create directories for %s"), gitfile_sb
.buf
);
3957 /* Prepare config file */
3958 strbuf_addf(&cfg_sb
, "%s/config", git_dir_
);
3959 if (safe_create_leading_directories_const(cfg_sb
.buf
))
3960 die(_("could not create directories for %s"), cfg_sb
.buf
);
3962 git_dir
= real_pathdup(git_dir_
, 1);
3963 work_tree
= real_pathdup(work_tree_
, 1);
3965 /* Write .git file */
3966 write_file(gitfile_sb
.buf
, "gitdir: %s",
3967 relative_path(git_dir
, work_tree
, &rel_path
));
3968 /* Update core.worktree setting */
3969 git_config_set_in_file(cfg_sb
.buf
, "core.worktree",
3970 relative_path(work_tree
, git_dir
, &rel_path
));
3972 strbuf_release(&gitfile_sb
);
3973 strbuf_release(&cfg_sb
);
3974 strbuf_release(&rel_path
);
3976 if (recurse_into_nested
)
3977 connect_wt_gitdir_in_nested(work_tree
, git_dir
);
3984 * Migrate the git directory of the given path from old_git_dir to new_git_dir.
3986 void relocate_gitdir(const char *path
, const char *old_git_dir
, const char *new_git_dir
)
3988 if (rename(old_git_dir
, new_git_dir
) < 0)
3989 die_errno(_("could not migrate git directory from '%s' to '%s'"),
3990 old_git_dir
, new_git_dir
);
3992 connect_work_tree_and_git_dir(path
, new_git_dir
, 0);
3995 int path_match_flags(const char *const str
, const enum path_match_flags flags
)
3997 const char *p
= str
;
3999 if (flags
& PATH_MATCH_NATIVE
&&
4000 flags
& PATH_MATCH_XPLATFORM
)
4001 BUG("path_match_flags() must get one match kind, not multiple!");
4002 else if (!(flags
& PATH_MATCH_KINDS_MASK
))
4003 BUG("path_match_flags() must get at least one match kind!");
4005 if (flags
& PATH_MATCH_STARTS_WITH_DOT_SLASH
&&
4006 flags
& PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH
)
4007 BUG("path_match_flags() must get one platform kind, not multiple!");
4008 else if (!(flags
& PATH_MATCH_PLATFORM_MASK
))
4009 BUG("path_match_flags() must get at least one platform kind!");
4013 if (flags
& PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH
&&
4017 if (flags
& PATH_MATCH_NATIVE
)
4018 return is_dir_sep(*p
);
4019 else if (flags
& PATH_MATCH_XPLATFORM
)
4020 return is_xplatform_dir_sep(*p
);