2 * This handles recursive filename detection with exclude
3 * files, index knowledge etc..
5 * See Documentation/technical/api-directory-listing.txt
7 * Copyright (C) Linus Torvalds, 2005-2006
8 * Junio Hamano, 2005-2006
13 #include "wildmatch.h"
17 struct path_simplify
{
23 * Tells read_directory_recursive how a file or directory should be treated.
24 * Values are ordered by significance, e.g. if a directory contains both
25 * excluded and untracked files, it is listed as untracked because
26 * path_untracked > path_excluded.
35 static enum path_treatment
read_directory_recursive(struct dir_struct
*dir
,
36 const char *path
, int len
,
37 int check_only
, const struct path_simplify
*simplify
);
38 static int get_dtype(struct dirent
*de
, const char *path
, int len
);
40 /* helper string functions with support for the ignore_case flag */
41 int strcmp_icase(const char *a
, const char *b
)
43 return ignore_case
? strcasecmp(a
, b
) : strcmp(a
, b
);
46 int strncmp_icase(const char *a
, const char *b
, size_t count
)
48 return ignore_case
? strncasecmp(a
, b
, count
) : strncmp(a
, b
, count
);
51 int fnmatch_icase(const char *pattern
, const char *string
, int flags
)
53 return wildmatch(pattern
, string
,
54 flags
| (ignore_case
? WM_CASEFOLD
: 0),
58 int git_fnmatch(const struct pathspec_item
*item
,
59 const char *pattern
, const char *string
,
63 if (ps_strncmp(item
, pattern
, string
, prefix
))
68 if (item
->flags
& PATHSPEC_ONESTAR
) {
69 int pattern_len
= strlen(++pattern
);
70 int string_len
= strlen(string
);
71 return string_len
< pattern_len
||
72 ps_strcmp(item
, pattern
,
73 string
+ string_len
- pattern_len
);
75 if (item
->magic
& PATHSPEC_GLOB
)
76 return wildmatch(pattern
, string
,
78 (item
->magic
& PATHSPEC_ICASE
? WM_CASEFOLD
: 0),
81 /* wildmatch has not learned no FNM_PATHNAME mode yet */
82 return wildmatch(pattern
, string
,
83 item
->magic
& PATHSPEC_ICASE
? WM_CASEFOLD
: 0,
87 static int fnmatch_icase_mem(const char *pattern
, int patternlen
,
88 const char *string
, int stringlen
,
92 struct strbuf pat_buf
= STRBUF_INIT
;
93 struct strbuf str_buf
= STRBUF_INIT
;
94 const char *use_pat
= pattern
;
95 const char *use_str
= string
;
97 if (pattern
[patternlen
]) {
98 strbuf_add(&pat_buf
, pattern
, patternlen
);
99 use_pat
= pat_buf
.buf
;
101 if (string
[stringlen
]) {
102 strbuf_add(&str_buf
, string
, stringlen
);
103 use_str
= str_buf
.buf
;
107 flags
|= WM_CASEFOLD
;
108 match_status
= wildmatch(use_pat
, use_str
, flags
, NULL
);
110 strbuf_release(&pat_buf
);
111 strbuf_release(&str_buf
);
116 static size_t common_prefix_len(const struct pathspec
*pathspec
)
122 * ":(icase)path" is treated as a pathspec full of
123 * wildcard. In other words, only prefix is considered common
124 * prefix. If the pathspec is abc/foo abc/bar, running in
125 * subdir xyz, the common prefix is still xyz, not xuz/abc as
128 GUARD_PATHSPEC(pathspec
,
136 for (n
= 0; n
< pathspec
->nr
; n
++) {
137 size_t i
= 0, len
= 0, item_len
;
138 if (pathspec
->items
[n
].magic
& PATHSPEC_EXCLUDE
)
140 if (pathspec
->items
[n
].magic
& PATHSPEC_ICASE
)
141 item_len
= pathspec
->items
[n
].prefix
;
143 item_len
= pathspec
->items
[n
].nowildcard_len
;
144 while (i
< item_len
&& (n
== 0 || i
< max
)) {
145 char c
= pathspec
->items
[n
].match
[i
];
146 if (c
!= pathspec
->items
[0].match
[i
])
152 if (n
== 0 || len
< max
) {
162 * Returns a copy of the longest leading path common among all
165 char *common_prefix(const struct pathspec
*pathspec
)
167 unsigned long len
= common_prefix_len(pathspec
);
169 return len
? xmemdupz(pathspec
->items
[0].match
, len
) : NULL
;
172 int fill_directory(struct dir_struct
*dir
, const struct pathspec
*pathspec
)
177 * Calculate common prefix for the pathspec, and
178 * use that to optimize the directory walk
180 len
= common_prefix_len(pathspec
);
182 /* Read the directory and prune it */
183 read_directory(dir
, pathspec
->nr
? pathspec
->_raw
[0] : "", len
, pathspec
);
187 int within_depth(const char *name
, int namelen
,
188 int depth
, int max_depth
)
190 const char *cp
= name
, *cpe
= name
+ namelen
;
196 if (depth
> max_depth
)
202 #define DO_MATCH_EXCLUDE 1
203 #define DO_MATCH_DIRECTORY 2
206 * Does 'match' match the given name?
207 * A match is found if
209 * (1) the 'match' string is leading directory of 'name', or
210 * (2) the 'match' string is a wildcard and matches 'name', or
211 * (3) the 'match' string is exactly the same as 'name'.
213 * and the return value tells which case it was.
215 * It returns 0 when there is no match.
217 static int match_pathspec_item(const struct pathspec_item
*item
, int prefix
,
218 const char *name
, int namelen
, unsigned flags
)
220 /* name/namelen has prefix cut off by caller */
221 const char *match
= item
->match
+ prefix
;
222 int matchlen
= item
->len
- prefix
;
225 * The normal call pattern is:
226 * 1. prefix = common_prefix_len(ps);
227 * 2. prune something, or fill_directory
228 * 3. match_pathspec()
230 * 'prefix' at #1 may be shorter than the command's prefix and
231 * it's ok for #2 to match extra files. Those extras will be
234 * Suppose the pathspec is 'foo' and '../bar' running from
235 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
236 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
237 * user does not want XYZ/foo, only the "foo" part should be
238 * case-insensitive. We need to filter out XYZ/foo here. In
239 * other words, we do not trust the caller on comparing the
240 * prefix part when :(icase) is involved. We do exact
241 * comparison ourselves.
243 * Normally the caller (common_prefix_len() in fact) does
244 * _exact_ matching on name[-prefix+1..-1] and we do not need
245 * to check that part. Be defensive and check it anyway, in
246 * case common_prefix_len is changed, or a new caller is
247 * introduced that does not use common_prefix_len.
249 * If the penalty turns out too high when prefix is really
250 * long, maybe change it to
251 * strncmp(match, name, item->prefix - prefix)
253 if (item
->prefix
&& (item
->magic
& PATHSPEC_ICASE
) &&
254 strncmp(item
->match
, name
- prefix
, item
->prefix
))
257 /* If the match was just the prefix, we matched */
259 return MATCHED_RECURSIVELY
;
261 if (matchlen
<= namelen
&& !ps_strncmp(item
, match
, name
, matchlen
)) {
262 if (matchlen
== namelen
)
263 return MATCHED_EXACTLY
;
265 if (match
[matchlen
-1] == '/' || name
[matchlen
] == '/')
266 return MATCHED_RECURSIVELY
;
267 } else if ((flags
& DO_MATCH_DIRECTORY
) &&
268 match
[matchlen
- 1] == '/' &&
269 namelen
== matchlen
- 1 &&
270 !ps_strncmp(item
, match
, name
, namelen
))
271 return MATCHED_EXACTLY
;
273 if (item
->nowildcard_len
< item
->len
&&
274 !git_fnmatch(item
, match
, name
,
275 item
->nowildcard_len
- prefix
))
276 return MATCHED_FNMATCH
;
282 * Given a name and a list of pathspecs, returns the nature of the
283 * closest (i.e. most specific) match of the name to any of the
286 * The caller typically calls this multiple times with the same
287 * pathspec and seen[] array but with different name/namelen
288 * (e.g. entries from the index) and is interested in seeing if and
289 * how each pathspec matches all the names it calls this function
290 * with. A mark is left in the seen[] array for each pathspec element
291 * indicating the closest type of match that element achieved, so if
292 * seen[n] remains zero after multiple invocations, that means the nth
293 * pathspec did not match any names, which could indicate that the
294 * user mistyped the nth pathspec.
296 static int do_match_pathspec(const struct pathspec
*ps
,
297 const char *name
, int namelen
,
298 int prefix
, char *seen
,
301 int i
, retval
= 0, exclude
= flags
& DO_MATCH_EXCLUDE
;
312 if (!ps
->recursive
||
313 !(ps
->magic
& PATHSPEC_MAXDEPTH
) ||
315 return MATCHED_RECURSIVELY
;
317 if (within_depth(name
, namelen
, 0, ps
->max_depth
))
318 return MATCHED_EXACTLY
;
326 for (i
= ps
->nr
- 1; i
>= 0; i
--) {
329 if ((!exclude
&& ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
) ||
330 ( exclude
&& !(ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
)))
333 if (seen
&& seen
[i
] == MATCHED_EXACTLY
)
336 * Make exclude patterns optional and never report
337 * "pathspec ':(exclude)foo' matches no files"
339 if (seen
&& ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
)
340 seen
[i
] = MATCHED_FNMATCH
;
341 how
= match_pathspec_item(ps
->items
+i
, prefix
, name
,
344 (ps
->magic
& PATHSPEC_MAXDEPTH
) &&
345 ps
->max_depth
!= -1 &&
346 how
&& how
!= MATCHED_FNMATCH
) {
347 int len
= ps
->items
[i
].len
;
348 if (name
[len
] == '/')
350 if (within_depth(name
+len
, namelen
-len
, 0, ps
->max_depth
))
351 how
= MATCHED_EXACTLY
;
358 if (seen
&& seen
[i
] < how
)
365 int match_pathspec(const struct pathspec
*ps
,
366 const char *name
, int namelen
,
367 int prefix
, char *seen
, int is_dir
)
369 int positive
, negative
;
370 unsigned flags
= is_dir
? DO_MATCH_DIRECTORY
: 0;
371 positive
= do_match_pathspec(ps
, name
, namelen
,
372 prefix
, seen
, flags
);
373 if (!(ps
->magic
& PATHSPEC_EXCLUDE
) || !positive
)
375 negative
= do_match_pathspec(ps
, name
, namelen
,
377 flags
| DO_MATCH_EXCLUDE
);
378 return negative
? 0 : positive
;
382 * Return the length of the "simple" part of a path match limiter.
384 int simple_length(const char *match
)
389 unsigned char c
= *match
++;
391 if (c
== '\0' || is_glob_special(c
))
396 int no_wildcard(const char *string
)
398 return string
[simple_length(string
)] == '\0';
401 void parse_exclude_pattern(const char **pattern
,
406 const char *p
= *pattern
;
411 *flags
|= EXC_FLAG_NEGATIVE
;
415 if (len
&& p
[len
- 1] == '/') {
417 *flags
|= EXC_FLAG_MUSTBEDIR
;
419 for (i
= 0; i
< len
; i
++) {
424 *flags
|= EXC_FLAG_NODIR
;
425 *nowildcardlen
= simple_length(p
);
427 * we should have excluded the trailing slash from 'p' too,
428 * but that's one more allocation. Instead just make sure
429 * nowildcardlen does not exceed real patternlen
431 if (*nowildcardlen
> len
)
432 *nowildcardlen
= len
;
433 if (*p
== '*' && no_wildcard(p
+ 1))
434 *flags
|= EXC_FLAG_ENDSWITH
;
439 void add_exclude(const char *string
, const char *base
,
440 int baselen
, struct exclude_list
*el
, int srcpos
)
447 parse_exclude_pattern(&string
, &patternlen
, &flags
, &nowildcardlen
);
448 if (flags
& EXC_FLAG_MUSTBEDIR
) {
450 x
= xmalloc(sizeof(*x
) + patternlen
+ 1);
452 memcpy(s
, string
, patternlen
);
453 s
[patternlen
] = '\0';
456 x
= xmalloc(sizeof(*x
));
459 x
->patternlen
= patternlen
;
460 x
->nowildcardlen
= nowildcardlen
;
462 x
->baselen
= baselen
;
465 ALLOC_GROW(el
->excludes
, el
->nr
+ 1, el
->alloc
);
466 el
->excludes
[el
->nr
++] = x
;
470 static void *read_skip_worktree_file_from_index(const char *path
, size_t *size
)
474 enum object_type type
;
478 pos
= cache_name_pos(path
, len
);
481 if (!ce_skip_worktree(active_cache
[pos
]))
483 data
= read_sha1_file(active_cache
[pos
]->sha1
, &type
, &sz
);
484 if (!data
|| type
!= OBJ_BLOB
) {
493 * Frees memory within el which was allocated for exclude patterns and
494 * the file buffer. Does not free el itself.
496 void clear_exclude_list(struct exclude_list
*el
)
500 for (i
= 0; i
< el
->nr
; i
++)
501 free(el
->excludes
[i
]);
510 static void trim_trailing_spaces(char *buf
)
512 char *p
, *last_space
= NULL
;
514 for (p
= buf
; *p
; p
++)
533 int add_excludes_from_file_to_list(const char *fname
,
536 struct exclude_list
*el
,
540 int fd
, i
, lineno
= 1;
544 fd
= open(fname
, O_RDONLY
);
545 if (fd
< 0 || fstat(fd
, &st
) < 0) {
547 warn_on_inaccessible(fname
);
551 (buf
= read_skip_worktree_file_from_index(fname
, &size
)) == NULL
)
557 if (buf
[size
-1] != '\n') {
558 buf
= xrealloc(buf
, size
+1);
562 size
= xsize_t(st
.st_size
);
567 buf
= xmalloc(size
+1);
568 if (read_in_full(fd
, buf
, size
) != size
) {
579 if (skip_utf8_bom(&buf
, size
))
580 size
-= buf
- el
->filebuf
;
584 for (i
= 0; i
< size
; i
++) {
585 if (buf
[i
] == '\n') {
586 if (entry
!= buf
+ i
&& entry
[0] != '#') {
587 buf
[i
- (i
&& buf
[i
-1] == '\r')] = 0;
588 trim_trailing_spaces(entry
);
589 add_exclude(entry
, base
, baselen
, el
, lineno
);
598 struct exclude_list
*add_exclude_list(struct dir_struct
*dir
,
599 int group_type
, const char *src
)
601 struct exclude_list
*el
;
602 struct exclude_list_group
*group
;
604 group
= &dir
->exclude_list_group
[group_type
];
605 ALLOC_GROW(group
->el
, group
->nr
+ 1, group
->alloc
);
606 el
= &group
->el
[group
->nr
++];
607 memset(el
, 0, sizeof(*el
));
613 * Used to set up core.excludesfile and .git/info/exclude lists.
615 void add_excludes_from_file(struct dir_struct
*dir
, const char *fname
)
617 struct exclude_list
*el
;
618 el
= add_exclude_list(dir
, EXC_FILE
, fname
);
619 if (add_excludes_from_file_to_list(fname
, "", 0, el
, 0) < 0)
620 die("cannot use %s as an exclude file", fname
);
623 int match_basename(const char *basename
, int basenamelen
,
624 const char *pattern
, int prefix
, int patternlen
,
627 if (prefix
== patternlen
) {
628 if (patternlen
== basenamelen
&&
629 !strncmp_icase(pattern
, basename
, basenamelen
))
631 } else if (flags
& EXC_FLAG_ENDSWITH
) {
632 /* "*literal" matching against "fooliteral" */
633 if (patternlen
- 1 <= basenamelen
&&
634 !strncmp_icase(pattern
+ 1,
635 basename
+ basenamelen
- (patternlen
- 1),
639 if (fnmatch_icase_mem(pattern
, patternlen
,
640 basename
, basenamelen
,
647 int match_pathname(const char *pathname
, int pathlen
,
648 const char *base
, int baselen
,
649 const char *pattern
, int prefix
, int patternlen
,
656 * match with FNM_PATHNAME; the pattern has base implicitly
659 if (*pattern
== '/') {
666 * baselen does not count the trailing slash. base[] may or
667 * may not end with a trailing slash though.
669 if (pathlen
< baselen
+ 1 ||
670 (baselen
&& pathname
[baselen
] != '/') ||
671 strncmp_icase(pathname
, base
, baselen
))
674 namelen
= baselen
? pathlen
- baselen
- 1 : pathlen
;
675 name
= pathname
+ pathlen
- namelen
;
679 * if the non-wildcard part is longer than the
680 * remaining pathname, surely it cannot match.
682 if (prefix
> namelen
)
685 if (strncmp_icase(pattern
, name
, prefix
))
688 patternlen
-= prefix
;
693 * If the whole pattern did not have a wildcard,
694 * then our prefix match is all we need; we
695 * do not need to call fnmatch at all.
697 if (!patternlen
&& !namelen
)
701 return fnmatch_icase_mem(pattern
, patternlen
,
707 * Scan the given exclude list in reverse to see whether pathname
708 * should be ignored. The first match (i.e. the last on the list), if
709 * any, determines the fate. Returns the exclude_list element which
710 * matched, or NULL for undecided.
712 static struct exclude
*last_exclude_matching_from_list(const char *pathname
,
714 const char *basename
,
716 struct exclude_list
*el
)
721 return NULL
; /* undefined */
723 for (i
= el
->nr
- 1; 0 <= i
; i
--) {
724 struct exclude
*x
= el
->excludes
[i
];
725 const char *exclude
= x
->pattern
;
726 int prefix
= x
->nowildcardlen
;
728 if (x
->flags
& EXC_FLAG_MUSTBEDIR
) {
729 if (*dtype
== DT_UNKNOWN
)
730 *dtype
= get_dtype(NULL
, pathname
, pathlen
);
731 if (*dtype
!= DT_DIR
)
735 if (x
->flags
& EXC_FLAG_NODIR
) {
736 if (match_basename(basename
,
737 pathlen
- (basename
- pathname
),
738 exclude
, prefix
, x
->patternlen
,
744 assert(x
->baselen
== 0 || x
->base
[x
->baselen
- 1] == '/');
745 if (match_pathname(pathname
, pathlen
,
746 x
->base
, x
->baselen
? x
->baselen
- 1 : 0,
747 exclude
, prefix
, x
->patternlen
, x
->flags
))
750 return NULL
; /* undecided */
754 * Scan the list and let the last match determine the fate.
755 * Return 1 for exclude, 0 for include and -1 for undecided.
757 int is_excluded_from_list(const char *pathname
,
758 int pathlen
, const char *basename
, int *dtype
,
759 struct exclude_list
*el
)
761 struct exclude
*exclude
;
762 exclude
= last_exclude_matching_from_list(pathname
, pathlen
, basename
, dtype
, el
);
764 return exclude
->flags
& EXC_FLAG_NEGATIVE
? 0 : 1;
765 return -1; /* undecided */
768 static struct exclude
*last_exclude_matching_from_lists(struct dir_struct
*dir
,
769 const char *pathname
, int pathlen
, const char *basename
,
773 struct exclude_list_group
*group
;
774 struct exclude
*exclude
;
775 for (i
= EXC_CMDL
; i
<= EXC_FILE
; i
++) {
776 group
= &dir
->exclude_list_group
[i
];
777 for (j
= group
->nr
- 1; j
>= 0; j
--) {
778 exclude
= last_exclude_matching_from_list(
779 pathname
, pathlen
, basename
, dtype_p
,
789 * Loads the per-directory exclude list for the substring of base
790 * which has a char length of baselen.
792 static void prep_exclude(struct dir_struct
*dir
, const char *base
, int baselen
)
794 struct exclude_list_group
*group
;
795 struct exclude_list
*el
;
796 struct exclude_stack
*stk
= NULL
;
799 group
= &dir
->exclude_list_group
[EXC_DIRS
];
802 * Pop the exclude lists from the EXCL_DIRS exclude_list_group
803 * which originate from directories not in the prefix of the
804 * path being checked.
806 while ((stk
= dir
->exclude_stack
) != NULL
) {
807 if (stk
->baselen
<= baselen
&&
808 !strncmp(dir
->basebuf
.buf
, base
, stk
->baselen
))
810 el
= &group
->el
[dir
->exclude_stack
->exclude_ix
];
811 dir
->exclude_stack
= stk
->prev
;
813 free((char *)el
->src
); /* see strbuf_detach() below */
814 clear_exclude_list(el
);
819 /* Skip traversing into sub directories if the parent is excluded */
824 * Lazy initialization. All call sites currently just
825 * memset(dir, 0, sizeof(*dir)) before use. Changing all of
826 * them seems lots of work for little benefit.
828 if (!dir
->basebuf
.buf
)
829 strbuf_init(&dir
->basebuf
, PATH_MAX
);
831 /* Read from the parent directories and push them down. */
832 current
= stk
? stk
->baselen
: -1;
833 strbuf_setlen(&dir
->basebuf
, current
< 0 ? 0 : current
);
834 while (current
< baselen
) {
837 stk
= xcalloc(1, sizeof(*stk
));
842 cp
= strchr(base
+ current
+ 1, '/');
844 die("oops in prep_exclude");
847 stk
->prev
= dir
->exclude_stack
;
848 stk
->baselen
= cp
- base
;
849 stk
->exclude_ix
= group
->nr
;
850 el
= add_exclude_list(dir
, EXC_DIRS
, NULL
);
851 strbuf_add(&dir
->basebuf
, base
+ current
, stk
->baselen
- current
);
852 assert(stk
->baselen
== dir
->basebuf
.len
);
854 /* Abort if the directory is excluded */
857 dir
->basebuf
.buf
[stk
->baselen
- 1] = 0;
858 dir
->exclude
= last_exclude_matching_from_lists(dir
,
859 dir
->basebuf
.buf
, stk
->baselen
- 1,
860 dir
->basebuf
.buf
+ current
, &dt
);
861 dir
->basebuf
.buf
[stk
->baselen
- 1] = '/';
863 dir
->exclude
->flags
& EXC_FLAG_NEGATIVE
)
866 dir
->exclude_stack
= stk
;
871 /* Try to read per-directory file */
872 if (dir
->exclude_per_dir
) {
874 * dir->basebuf gets reused by the traversal, but we
875 * need fname to remain unchanged to ensure the src
876 * member of each struct exclude correctly
877 * back-references its source file. Other invocations
878 * of add_exclude_list provide stable strings, so we
879 * strbuf_detach() and free() here in the caller.
881 struct strbuf sb
= STRBUF_INIT
;
882 strbuf_addbuf(&sb
, &dir
->basebuf
);
883 strbuf_addstr(&sb
, dir
->exclude_per_dir
);
884 el
->src
= strbuf_detach(&sb
, NULL
);
885 add_excludes_from_file_to_list(el
->src
, el
->src
,
886 stk
->baselen
, el
, 1);
888 dir
->exclude_stack
= stk
;
889 current
= stk
->baselen
;
891 strbuf_setlen(&dir
->basebuf
, baselen
);
895 * Loads the exclude lists for the directory containing pathname, then
896 * scans all exclude lists to determine whether pathname is excluded.
897 * Returns the exclude_list element which matched, or NULL for
900 struct exclude
*last_exclude_matching(struct dir_struct
*dir
,
901 const char *pathname
,
904 int pathlen
= strlen(pathname
);
905 const char *basename
= strrchr(pathname
, '/');
906 basename
= (basename
) ? basename
+1 : pathname
;
908 prep_exclude(dir
, pathname
, basename
-pathname
);
913 return last_exclude_matching_from_lists(dir
, pathname
, pathlen
,
918 * Loads the exclude lists for the directory containing pathname, then
919 * scans all exclude lists to determine whether pathname is excluded.
920 * Returns 1 if true, otherwise 0.
922 int is_excluded(struct dir_struct
*dir
, const char *pathname
, int *dtype_p
)
924 struct exclude
*exclude
=
925 last_exclude_matching(dir
, pathname
, dtype_p
);
927 return exclude
->flags
& EXC_FLAG_NEGATIVE
? 0 : 1;
931 static struct dir_entry
*dir_entry_new(const char *pathname
, int len
)
933 struct dir_entry
*ent
;
935 ent
= xmalloc(sizeof(*ent
) + len
+ 1);
937 memcpy(ent
->name
, pathname
, len
);
942 static struct dir_entry
*dir_add_name(struct dir_struct
*dir
, const char *pathname
, int len
)
944 if (cache_file_exists(pathname
, len
, ignore_case
))
947 ALLOC_GROW(dir
->entries
, dir
->nr
+1, dir
->alloc
);
948 return dir
->entries
[dir
->nr
++] = dir_entry_new(pathname
, len
);
951 struct dir_entry
*dir_add_ignored(struct dir_struct
*dir
, const char *pathname
, int len
)
953 if (!cache_name_is_other(pathname
, len
))
956 ALLOC_GROW(dir
->ignored
, dir
->ignored_nr
+1, dir
->ignored_alloc
);
957 return dir
->ignored
[dir
->ignored_nr
++] = dir_entry_new(pathname
, len
);
961 index_nonexistent
= 0,
967 * Do not use the alphabetically sorted index to look up
968 * the directory name; instead, use the case insensitive
971 static enum exist_status
directory_exists_in_index_icase(const char *dirname
, int len
)
973 const struct cache_entry
*ce
= cache_dir_exists(dirname
, len
);
974 unsigned char endchar
;
977 return index_nonexistent
;
978 endchar
= ce
->name
[len
];
981 * The cache_entry structure returned will contain this dirname
982 * and possibly additional path components.
985 return index_directory
;
988 * If there are no additional path components, then this cache_entry
989 * represents a submodule. Submodules, despite being directories,
990 * are stored in the cache without a closing slash.
992 if (!endchar
&& S_ISGITLINK(ce
->ce_mode
))
995 /* This should never be hit, but it exists just in case. */
996 return index_nonexistent
;
1000 * The index sorts alphabetically by entry name, which
1001 * means that a gitlink sorts as '\0' at the end, while
1002 * a directory (which is defined not as an entry, but as
1003 * the files it contains) will sort with the '/' at the
1006 static enum exist_status
directory_exists_in_index(const char *dirname
, int len
)
1011 return directory_exists_in_index_icase(dirname
, len
);
1013 pos
= cache_name_pos(dirname
, len
);
1016 while (pos
< active_nr
) {
1017 const struct cache_entry
*ce
= active_cache
[pos
++];
1018 unsigned char endchar
;
1020 if (strncmp(ce
->name
, dirname
, len
))
1022 endchar
= ce
->name
[len
];
1026 return index_directory
;
1027 if (!endchar
&& S_ISGITLINK(ce
->ce_mode
))
1028 return index_gitdir
;
1030 return index_nonexistent
;
1034 * When we find a directory when traversing the filesystem, we
1035 * have three distinct cases:
1038 * - see it as a directory
1041 * and which one we choose depends on a combination of existing
1042 * git index contents and the flags passed into the directory
1043 * traversal routine.
1045 * Case 1: If we *already* have entries in the index under that
1046 * directory name, we always recurse into the directory to see
1049 * Case 2: If we *already* have that directory name as a gitlink,
1050 * we always continue to see it as a gitlink, regardless of whether
1051 * there is an actual git directory there or not (it might not
1052 * be checked out as a subproject!)
1054 * Case 3: if we didn't have it in the index previously, we
1055 * have a few sub-cases:
1057 * (a) if "show_other_directories" is true, we show it as
1058 * just a directory, unless "hide_empty_directories" is
1059 * also true, in which case we need to check if it contains any
1060 * untracked and / or ignored files.
1061 * (b) if it looks like a git directory, and we don't have
1062 * 'no_gitlinks' set we treat it as a gitlink, and show it
1064 * (c) otherwise, we recurse into it.
1066 static enum path_treatment
treat_directory(struct dir_struct
*dir
,
1067 const char *dirname
, int len
, int exclude
,
1068 const struct path_simplify
*simplify
)
1070 /* The "len-1" is to strip the final '/' */
1071 switch (directory_exists_in_index(dirname
, len
-1)) {
1072 case index_directory
:
1073 return path_recurse
;
1078 case index_nonexistent
:
1079 if (dir
->flags
& DIR_SHOW_OTHER_DIRECTORIES
)
1081 if (!(dir
->flags
& DIR_NO_GITLINKS
)) {
1082 unsigned char sha1
[20];
1083 if (resolve_gitlink_ref(dirname
, "HEAD", sha1
) == 0)
1084 return path_untracked
;
1086 return path_recurse
;
1089 /* This is the "show_other_directories" case */
1091 if (!(dir
->flags
& DIR_HIDE_EMPTY_DIRECTORIES
))
1092 return exclude
? path_excluded
: path_untracked
;
1094 return read_directory_recursive(dir
, dirname
, len
, 1, simplify
);
1098 * This is an inexact early pruning of any recursive directory
1099 * reading - if the path cannot possibly be in the pathspec,
1100 * return true, and we'll skip it early.
1102 static int simplify_away(const char *path
, int pathlen
, const struct path_simplify
*simplify
)
1106 const char *match
= simplify
->path
;
1107 int len
= simplify
->len
;
1113 if (!memcmp(path
, match
, len
))
1123 * This function tells us whether an excluded path matches a
1124 * list of "interesting" pathspecs. That is, whether a path matched
1125 * by any of the pathspecs could possibly be ignored by excluding
1126 * the specified path. This can happen if:
1128 * 1. the path is mentioned explicitly in the pathspec
1130 * 2. the path is a directory prefix of some element in the
1133 static int exclude_matches_pathspec(const char *path
, int len
,
1134 const struct path_simplify
*simplify
)
1137 for (; simplify
->path
; simplify
++) {
1138 if (len
== simplify
->len
1139 && !memcmp(path
, simplify
->path
, len
))
1141 if (len
< simplify
->len
1142 && simplify
->path
[len
] == '/'
1143 && !memcmp(path
, simplify
->path
, len
))
1150 static int get_index_dtype(const char *path
, int len
)
1153 const struct cache_entry
*ce
;
1155 ce
= cache_file_exists(path
, len
, 0);
1157 if (!ce_uptodate(ce
))
1159 if (S_ISGITLINK(ce
->ce_mode
))
1162 * Nobody actually cares about the
1163 * difference between DT_LNK and DT_REG
1168 /* Try to look it up as a directory */
1169 pos
= cache_name_pos(path
, len
);
1173 while (pos
< active_nr
) {
1174 ce
= active_cache
[pos
++];
1175 if (strncmp(ce
->name
, path
, len
))
1177 if (ce
->name
[len
] > '/')
1179 if (ce
->name
[len
] < '/')
1181 if (!ce_uptodate(ce
))
1182 break; /* continue? */
1188 static int get_dtype(struct dirent
*de
, const char *path
, int len
)
1190 int dtype
= de
? DTYPE(de
) : DT_UNKNOWN
;
1193 if (dtype
!= DT_UNKNOWN
)
1195 dtype
= get_index_dtype(path
, len
);
1196 if (dtype
!= DT_UNKNOWN
)
1198 if (lstat(path
, &st
))
1200 if (S_ISREG(st
.st_mode
))
1202 if (S_ISDIR(st
.st_mode
))
1204 if (S_ISLNK(st
.st_mode
))
1209 static enum path_treatment
treat_one_path(struct dir_struct
*dir
,
1210 struct strbuf
*path
,
1211 const struct path_simplify
*simplify
,
1212 int dtype
, struct dirent
*de
)
1215 int has_path_in_index
= !!cache_file_exists(path
->buf
, path
->len
, ignore_case
);
1217 if (dtype
== DT_UNKNOWN
)
1218 dtype
= get_dtype(de
, path
->buf
, path
->len
);
1220 /* Always exclude indexed files */
1221 if (dtype
!= DT_DIR
&& has_path_in_index
)
1225 * When we are looking at a directory P in the working tree,
1226 * there are three cases:
1228 * (1) P exists in the index. Everything inside the directory P in
1229 * the working tree needs to go when P is checked out from the
1232 * (2) P does not exist in the index, but there is P/Q in the index.
1233 * We know P will stay a directory when we check out the contents
1234 * of the index, but we do not know yet if there is a directory
1235 * P/Q in the working tree to be killed, so we need to recurse.
1237 * (3) P does not exist in the index, and there is no P/Q in the index
1238 * to require P to be a directory, either. Only in this case, we
1239 * know that everything inside P will not be killed without
1242 if ((dir
->flags
& DIR_COLLECT_KILLED_ONLY
) &&
1243 (dtype
== DT_DIR
) &&
1244 !has_path_in_index
&&
1245 (directory_exists_in_index(path
->buf
, path
->len
) == index_nonexistent
))
1248 exclude
= is_excluded(dir
, path
->buf
, &dtype
);
1251 * Excluded? If we don't explicitly want to show
1252 * ignored files, ignore it
1254 if (exclude
&& !(dir
->flags
& (DIR_SHOW_IGNORED
|DIR_SHOW_IGNORED_TOO
)))
1255 return path_excluded
;
1261 strbuf_addch(path
, '/');
1262 return treat_directory(dir
, path
->buf
, path
->len
, exclude
,
1266 return exclude
? path_excluded
: path_untracked
;
1270 static enum path_treatment
treat_path(struct dir_struct
*dir
,
1272 struct strbuf
*path
,
1274 const struct path_simplify
*simplify
)
1278 if (is_dot_or_dotdot(de
->d_name
) || !strcmp(de
->d_name
, ".git"))
1280 strbuf_setlen(path
, baselen
);
1281 strbuf_addstr(path
, de
->d_name
);
1282 if (simplify_away(path
->buf
, path
->len
, simplify
))
1286 return treat_one_path(dir
, path
, simplify
, dtype
, de
);
1290 * Read a directory tree. We currently ignore anything but
1291 * directories, regular files and symlinks. That's because git
1292 * doesn't handle them at all yet. Maybe that will change some
1295 * Also, we ignore the name ".git" (even if it is not a directory).
1296 * That likely will not change.
1298 * Returns the most significant path_treatment value encountered in the scan.
1300 static enum path_treatment
read_directory_recursive(struct dir_struct
*dir
,
1301 const char *base
, int baselen
,
1303 const struct path_simplify
*simplify
)
1306 enum path_treatment state
, subdir_state
, dir_state
= path_none
;
1308 struct strbuf path
= STRBUF_INIT
;
1310 strbuf_add(&path
, base
, baselen
);
1312 fdir
= opendir(path
.len
? path
.buf
: ".");
1316 while ((de
= readdir(fdir
)) != NULL
) {
1317 /* check how the file or directory should be treated */
1318 state
= treat_path(dir
, de
, &path
, baselen
, simplify
);
1319 if (state
> dir_state
)
1322 /* recurse into subdir if instructed by treat_path */
1323 if (state
== path_recurse
) {
1324 subdir_state
= read_directory_recursive(dir
, path
.buf
,
1325 path
.len
, check_only
, simplify
);
1326 if (subdir_state
> dir_state
)
1327 dir_state
= subdir_state
;
1331 /* abort early if maximum state has been reached */
1332 if (dir_state
== path_untracked
)
1334 /* skip the dir_add_* part */
1338 /* add the path to the appropriate result list */
1341 if (dir
->flags
& DIR_SHOW_IGNORED
)
1342 dir_add_name(dir
, path
.buf
, path
.len
);
1343 else if ((dir
->flags
& DIR_SHOW_IGNORED_TOO
) ||
1344 ((dir
->flags
& DIR_COLLECT_IGNORED
) &&
1345 exclude_matches_pathspec(path
.buf
, path
.len
,
1347 dir_add_ignored(dir
, path
.buf
, path
.len
);
1350 case path_untracked
:
1351 if (!(dir
->flags
& DIR_SHOW_IGNORED
))
1352 dir_add_name(dir
, path
.buf
, path
.len
);
1361 strbuf_release(&path
);
1366 static int cmp_name(const void *p1
, const void *p2
)
1368 const struct dir_entry
*e1
= *(const struct dir_entry
**)p1
;
1369 const struct dir_entry
*e2
= *(const struct dir_entry
**)p2
;
1371 return name_compare(e1
->name
, e1
->len
, e2
->name
, e2
->len
);
1374 static struct path_simplify
*create_simplify(const char **pathspec
)
1377 struct path_simplify
*simplify
= NULL
;
1382 for (nr
= 0 ; ; nr
++) {
1384 ALLOC_GROW(simplify
, nr
+ 1, alloc
);
1385 match
= *pathspec
++;
1388 simplify
[nr
].path
= match
;
1389 simplify
[nr
].len
= simple_length(match
);
1391 simplify
[nr
].path
= NULL
;
1392 simplify
[nr
].len
= 0;
1396 static void free_simplify(struct path_simplify
*simplify
)
1401 static int treat_leading_path(struct dir_struct
*dir
,
1402 const char *path
, int len
,
1403 const struct path_simplify
*simplify
)
1405 struct strbuf sb
= STRBUF_INIT
;
1406 int baselen
, rc
= 0;
1408 int old_flags
= dir
->flags
;
1410 while (len
&& path
[len
- 1] == '/')
1415 dir
->flags
&= ~DIR_SHOW_OTHER_DIRECTORIES
;
1417 cp
= path
+ baselen
+ !!baselen
;
1418 cp
= memchr(cp
, '/', path
+ len
- cp
);
1422 baselen
= cp
- path
;
1423 strbuf_setlen(&sb
, 0);
1424 strbuf_add(&sb
, path
, baselen
);
1425 if (!is_directory(sb
.buf
))
1427 if (simplify_away(sb
.buf
, sb
.len
, simplify
))
1429 if (treat_one_path(dir
, &sb
, simplify
,
1430 DT_DIR
, NULL
) == path_none
)
1431 break; /* do not recurse into it */
1432 if (len
<= baselen
) {
1434 break; /* finished checking */
1437 strbuf_release(&sb
);
1438 dir
->flags
= old_flags
;
1442 int read_directory(struct dir_struct
*dir
, const char *path
, int len
, const struct pathspec
*pathspec
)
1444 struct path_simplify
*simplify
;
1447 * Check out create_simplify()
1450 GUARD_PATHSPEC(pathspec
,
1458 if (has_symlink_leading_path(path
, len
))
1462 * exclude patterns are treated like positive ones in
1463 * create_simplify. Usually exclude patterns should be a
1464 * subset of positive ones, which has no impacts on
1465 * create_simplify().
1467 simplify
= create_simplify(pathspec
? pathspec
->_raw
: NULL
);
1468 if (!len
|| treat_leading_path(dir
, path
, len
, simplify
))
1469 read_directory_recursive(dir
, path
, len
, 0, simplify
);
1470 free_simplify(simplify
);
1471 qsort(dir
->entries
, dir
->nr
, sizeof(struct dir_entry
*), cmp_name
);
1472 qsort(dir
->ignored
, dir
->ignored_nr
, sizeof(struct dir_entry
*), cmp_name
);
1476 int file_exists(const char *f
)
1479 return lstat(f
, &sb
) == 0;
1483 * Given two normalized paths (a trailing slash is ok), if subdir is
1484 * outside dir, return -1. Otherwise return the offset in subdir that
1485 * can be used as relative path to dir.
1487 int dir_inside_of(const char *subdir
, const char *dir
)
1491 assert(dir
&& subdir
&& *dir
&& *subdir
);
1493 while (*dir
&& *subdir
&& *dir
== *subdir
) {
1499 /* hel[p]/me vs hel[l]/yeah */
1500 if (*dir
&& *subdir
)
1504 return !*dir
? offset
: -1; /* same dir */
1506 /* foo/[b]ar vs foo/[] */
1507 if (is_dir_sep(dir
[-1]))
1508 return is_dir_sep(subdir
[-1]) ? offset
: -1;
1510 /* foo[/]bar vs foo[] */
1511 return is_dir_sep(*subdir
) ? offset
+ 1 : -1;
1514 int is_inside_dir(const char *dir
)
1523 rc
= (dir_inside_of(cwd
, dir
) >= 0);
1528 int is_empty_dir(const char *path
)
1530 DIR *dir
= opendir(path
);
1537 while ((e
= readdir(dir
)) != NULL
)
1538 if (!is_dot_or_dotdot(e
->d_name
)) {
1547 static int remove_dir_recurse(struct strbuf
*path
, int flag
, int *kept_up
)
1551 int ret
= 0, original_len
= path
->len
, len
, kept_down
= 0;
1552 int only_empty
= (flag
& REMOVE_DIR_EMPTY_ONLY
);
1553 int keep_toplevel
= (flag
& REMOVE_DIR_KEEP_TOPLEVEL
);
1554 unsigned char submodule_head
[20];
1556 if ((flag
& REMOVE_DIR_KEEP_NESTED_GIT
) &&
1557 !resolve_gitlink_ref(path
->buf
, "HEAD", submodule_head
)) {
1558 /* Do not descend and nuke a nested git work tree. */
1564 flag
&= ~REMOVE_DIR_KEEP_TOPLEVEL
;
1565 dir
= opendir(path
->buf
);
1567 if (errno
== ENOENT
)
1568 return keep_toplevel
? -1 : 0;
1569 else if (errno
== EACCES
&& !keep_toplevel
)
1571 * An empty dir could be removable even if it
1574 return rmdir(path
->buf
);
1578 if (path
->buf
[original_len
- 1] != '/')
1579 strbuf_addch(path
, '/');
1582 while ((e
= readdir(dir
)) != NULL
) {
1584 if (is_dot_or_dotdot(e
->d_name
))
1587 strbuf_setlen(path
, len
);
1588 strbuf_addstr(path
, e
->d_name
);
1589 if (lstat(path
->buf
, &st
)) {
1590 if (errno
== ENOENT
)
1592 * file disappeared, which is what we
1597 } else if (S_ISDIR(st
.st_mode
)) {
1598 if (!remove_dir_recurse(path
, flag
, &kept_down
))
1599 continue; /* happy */
1600 } else if (!only_empty
&&
1601 (!unlink(path
->buf
) || errno
== ENOENT
)) {
1602 continue; /* happy, too */
1605 /* path too long, stat fails, or non-directory still exists */
1611 strbuf_setlen(path
, original_len
);
1612 if (!ret
&& !keep_toplevel
&& !kept_down
)
1613 ret
= (!rmdir(path
->buf
) || errno
== ENOENT
) ? 0 : -1;
1616 * report the uplevel that it is not an error that we
1617 * did not rmdir() our directory.
1623 int remove_dir_recursively(struct strbuf
*path
, int flag
)
1625 return remove_dir_recurse(path
, flag
, NULL
);
1628 void setup_standard_excludes(struct dir_struct
*dir
)
1633 dir
->exclude_per_dir
= ".gitignore";
1634 path
= git_path("info/exclude");
1635 if (!excludes_file
) {
1636 home_config_paths(NULL
, &xdg_path
, "ignore");
1637 excludes_file
= xdg_path
;
1639 if (!access_or_warn(path
, R_OK
, 0))
1640 add_excludes_from_file(dir
, path
);
1641 if (excludes_file
&& !access_or_warn(excludes_file
, R_OK
, 0))
1642 add_excludes_from_file(dir
, excludes_file
);
1645 int remove_path(const char *name
)
1649 if (unlink(name
) && errno
!= ENOENT
&& errno
!= ENOTDIR
)
1652 slash
= strrchr(name
, '/');
1654 char *dirs
= xstrdup(name
);
1655 slash
= dirs
+ (slash
- name
);
1658 } while (rmdir(dirs
) == 0 && (slash
= strrchr(dirs
, '/')));
1665 * Frees memory within dir which was allocated for exclude lists and
1666 * the exclude_stack. Does not free dir itself.
1668 void clear_directory(struct dir_struct
*dir
)
1671 struct exclude_list_group
*group
;
1672 struct exclude_list
*el
;
1673 struct exclude_stack
*stk
;
1675 for (i
= EXC_CMDL
; i
<= EXC_FILE
; i
++) {
1676 group
= &dir
->exclude_list_group
[i
];
1677 for (j
= 0; j
< group
->nr
; j
++) {
1680 free((char *)el
->src
);
1681 clear_exclude_list(el
);
1686 stk
= dir
->exclude_stack
;
1688 struct exclude_stack
*prev
= stk
->prev
;
1692 strbuf_release(&dir
->basebuf
);