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"
16 struct path_simplify
{
22 * Tells read_directory_recursive how a file or directory should be treated.
23 * Values are ordered by significance, e.g. if a directory contains both
24 * excluded and untracked files, it is listed as untracked because
25 * path_untracked > path_excluded.
34 static enum path_treatment
read_directory_recursive(struct dir_struct
*dir
,
35 const char *path
, int len
,
36 int check_only
, const struct path_simplify
*simplify
);
37 static int get_dtype(struct dirent
*de
, const char *path
, int len
);
39 /* helper string functions with support for the ignore_case flag */
40 int strcmp_icase(const char *a
, const char *b
)
42 return ignore_case
? strcasecmp(a
, b
) : strcmp(a
, b
);
45 int strncmp_icase(const char *a
, const char *b
, size_t count
)
47 return ignore_case
? strncasecmp(a
, b
, count
) : strncmp(a
, b
, count
);
50 int fnmatch_icase(const char *pattern
, const char *string
, int flags
)
52 return fnmatch(pattern
, string
, flags
| (ignore_case
? FNM_CASEFOLD
: 0));
55 inline int git_fnmatch(const struct pathspec_item
*item
,
56 const char *pattern
, const char *string
,
60 if (ps_strncmp(item
, pattern
, string
, prefix
))
65 if (item
->flags
& PATHSPEC_ONESTAR
) {
66 int pattern_len
= strlen(++pattern
);
67 int string_len
= strlen(string
);
68 return string_len
< pattern_len
||
69 ps_strcmp(item
, pattern
,
70 string
+ string_len
- pattern_len
);
72 if (item
->magic
& PATHSPEC_GLOB
)
73 return wildmatch(pattern
, string
,
75 (item
->magic
& PATHSPEC_ICASE
? WM_CASEFOLD
: 0),
78 /* wildmatch has not learned no FNM_PATHNAME mode yet */
79 return fnmatch(pattern
, string
,
80 item
->magic
& PATHSPEC_ICASE
? FNM_CASEFOLD
: 0);
83 static int fnmatch_icase_mem(const char *pattern
, int patternlen
,
84 const char *string
, int stringlen
,
88 struct strbuf pat_buf
= STRBUF_INIT
;
89 struct strbuf str_buf
= STRBUF_INIT
;
90 const char *use_pat
= pattern
;
91 const char *use_str
= string
;
93 if (pattern
[patternlen
]) {
94 strbuf_add(&pat_buf
, pattern
, patternlen
);
95 use_pat
= pat_buf
.buf
;
97 if (string
[stringlen
]) {
98 strbuf_add(&str_buf
, string
, stringlen
);
99 use_str
= str_buf
.buf
;
103 flags
|= WM_CASEFOLD
;
104 match_status
= wildmatch(use_pat
, use_str
, flags
, NULL
);
106 strbuf_release(&pat_buf
);
107 strbuf_release(&str_buf
);
112 static size_t common_prefix_len(const struct pathspec
*pathspec
)
118 * ":(icase)path" is treated as a pathspec full of
119 * wildcard. In other words, only prefix is considered common
120 * prefix. If the pathspec is abc/foo abc/bar, running in
121 * subdir xyz, the common prefix is still xyz, not xuz/abc as
124 GUARD_PATHSPEC(pathspec
,
132 for (n
= 0; n
< pathspec
->nr
; n
++) {
133 size_t i
= 0, len
= 0, item_len
;
134 if (pathspec
->items
[n
].magic
& PATHSPEC_EXCLUDE
)
136 if (pathspec
->items
[n
].magic
& PATHSPEC_ICASE
)
137 item_len
= pathspec
->items
[n
].prefix
;
139 item_len
= pathspec
->items
[n
].nowildcard_len
;
140 while (i
< item_len
&& (n
== 0 || i
< max
)) {
141 char c
= pathspec
->items
[n
].match
[i
];
142 if (c
!= pathspec
->items
[0].match
[i
])
148 if (n
== 0 || len
< max
) {
158 * Returns a copy of the longest leading path common among all
161 char *common_prefix(const struct pathspec
*pathspec
)
163 unsigned long len
= common_prefix_len(pathspec
);
165 return len
? xmemdupz(pathspec
->items
[0].match
, len
) : NULL
;
168 int fill_directory(struct dir_struct
*dir
, const struct pathspec
*pathspec
)
173 * Calculate common prefix for the pathspec, and
174 * use that to optimize the directory walk
176 len
= common_prefix_len(pathspec
);
178 /* Read the directory and prune it */
179 read_directory(dir
, pathspec
->nr
? pathspec
->_raw
[0] : "", len
, pathspec
);
183 int within_depth(const char *name
, int namelen
,
184 int depth
, int max_depth
)
186 const char *cp
= name
, *cpe
= name
+ namelen
;
192 if (depth
> max_depth
)
199 * Does 'match' match the given name?
200 * A match is found if
202 * (1) the 'match' string is leading directory of 'name', or
203 * (2) the 'match' string is a wildcard and matches 'name', or
204 * (3) the 'match' string is exactly the same as 'name'.
206 * and the return value tells which case it was.
208 * It returns 0 when there is no match.
210 static int match_pathspec_item(const struct pathspec_item
*item
, int prefix
,
211 const char *name
, int namelen
)
213 /* name/namelen has prefix cut off by caller */
214 const char *match
= item
->match
+ prefix
;
215 int matchlen
= item
->len
- prefix
;
218 * The normal call pattern is:
219 * 1. prefix = common_prefix_len(ps);
220 * 2. prune something, or fill_directory
221 * 3. match_pathspec_depth()
223 * 'prefix' at #1 may be shorter than the command's prefix and
224 * it's ok for #2 to match extra files. Those extras will be
227 * Suppose the pathspec is 'foo' and '../bar' running from
228 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
229 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
230 * user does not want XYZ/foo, only the "foo" part should be
231 * case-insensitive. We need to filter out XYZ/foo here. In
232 * other words, we do not trust the caller on comparing the
233 * prefix part when :(icase) is involved. We do exact
234 * comparison ourselves.
236 * Normally the caller (common_prefix_len() in fact) does
237 * _exact_ matching on name[-prefix+1..-1] and we do not need
238 * to check that part. Be defensive and check it anyway, in
239 * case common_prefix_len is changed, or a new caller is
240 * introduced that does not use common_prefix_len.
242 * If the penalty turns out too high when prefix is really
243 * long, maybe change it to
244 * strncmp(match, name, item->prefix - prefix)
246 if (item
->prefix
&& (item
->magic
& PATHSPEC_ICASE
) &&
247 strncmp(item
->match
, name
- prefix
, item
->prefix
))
250 /* If the match was just the prefix, we matched */
252 return MATCHED_RECURSIVELY
;
254 if (matchlen
<= namelen
&& !ps_strncmp(item
, match
, name
, matchlen
)) {
255 if (matchlen
== namelen
)
256 return MATCHED_EXACTLY
;
258 if (match
[matchlen
-1] == '/' || name
[matchlen
] == '/')
259 return MATCHED_RECURSIVELY
;
262 if (item
->nowildcard_len
< item
->len
&&
263 !git_fnmatch(item
, match
, name
,
264 item
->nowildcard_len
- prefix
))
265 return MATCHED_FNMATCH
;
271 * Given a name and a list of pathspecs, returns the nature of the
272 * closest (i.e. most specific) match of the name to any of the
275 * The caller typically calls this multiple times with the same
276 * pathspec and seen[] array but with different name/namelen
277 * (e.g. entries from the index) and is interested in seeing if and
278 * how each pathspec matches all the names it calls this function
279 * with. A mark is left in the seen[] array for each pathspec element
280 * indicating the closest type of match that element achieved, so if
281 * seen[n] remains zero after multiple invocations, that means the nth
282 * pathspec did not match any names, which could indicate that the
283 * user mistyped the nth pathspec.
285 static int match_pathspec_depth_1(const struct pathspec
*ps
,
286 const char *name
, int namelen
,
287 int prefix
, char *seen
,
301 if (!ps
->recursive
||
302 !(ps
->magic
& PATHSPEC_MAXDEPTH
) ||
304 return MATCHED_RECURSIVELY
;
306 if (within_depth(name
, namelen
, 0, ps
->max_depth
))
307 return MATCHED_EXACTLY
;
315 for (i
= ps
->nr
- 1; i
>= 0; i
--) {
318 if ((!exclude
&& ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
) ||
319 ( exclude
&& !(ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
)))
322 if (seen
&& seen
[i
] == MATCHED_EXACTLY
)
325 * Make exclude patterns optional and never report
326 * "pathspec ':(exclude)foo' matches no files"
328 if (seen
&& ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
)
329 seen
[i
] = MATCHED_FNMATCH
;
330 how
= match_pathspec_item(ps
->items
+i
, prefix
, name
, namelen
);
332 (ps
->magic
& PATHSPEC_MAXDEPTH
) &&
333 ps
->max_depth
!= -1 &&
334 how
&& how
!= MATCHED_FNMATCH
) {
335 int len
= ps
->items
[i
].len
;
336 if (name
[len
] == '/')
338 if (within_depth(name
+len
, namelen
-len
, 0, ps
->max_depth
))
339 how
= MATCHED_EXACTLY
;
346 if (seen
&& seen
[i
] < how
)
353 int match_pathspec_depth(const struct pathspec
*ps
,
354 const char *name
, int namelen
,
355 int prefix
, char *seen
)
357 int positive
, negative
;
358 positive
= match_pathspec_depth_1(ps
, name
, namelen
, prefix
, seen
, 0);
359 if (!(ps
->magic
& PATHSPEC_EXCLUDE
) || !positive
)
361 negative
= match_pathspec_depth_1(ps
, name
, namelen
, prefix
, seen
, 1);
362 return negative
? 0 : positive
;
366 * Return the length of the "simple" part of a path match limiter.
368 int simple_length(const char *match
)
373 unsigned char c
= *match
++;
375 if (c
== '\0' || is_glob_special(c
))
380 int no_wildcard(const char *string
)
382 return string
[simple_length(string
)] == '\0';
385 void parse_exclude_pattern(const char **pattern
,
390 const char *p
= *pattern
;
395 *flags
|= EXC_FLAG_NEGATIVE
;
399 if (len
&& p
[len
- 1] == '/') {
401 *flags
|= EXC_FLAG_MUSTBEDIR
;
403 for (i
= 0; i
< len
; i
++) {
408 *flags
|= EXC_FLAG_NODIR
;
409 *nowildcardlen
= simple_length(p
);
411 * we should have excluded the trailing slash from 'p' too,
412 * but that's one more allocation. Instead just make sure
413 * nowildcardlen does not exceed real patternlen
415 if (*nowildcardlen
> len
)
416 *nowildcardlen
= len
;
417 if (*p
== '*' && no_wildcard(p
+ 1))
418 *flags
|= EXC_FLAG_ENDSWITH
;
423 void add_exclude(const char *string
, const char *base
,
424 int baselen
, struct exclude_list
*el
, int srcpos
)
431 parse_exclude_pattern(&string
, &patternlen
, &flags
, &nowildcardlen
);
432 if (flags
& EXC_FLAG_MUSTBEDIR
) {
434 x
= xmalloc(sizeof(*x
) + patternlen
+ 1);
436 memcpy(s
, string
, patternlen
);
437 s
[patternlen
] = '\0';
440 x
= xmalloc(sizeof(*x
));
443 x
->patternlen
= patternlen
;
444 x
->nowildcardlen
= nowildcardlen
;
446 x
->baselen
= baselen
;
449 ALLOC_GROW(el
->excludes
, el
->nr
+ 1, el
->alloc
);
450 el
->excludes
[el
->nr
++] = x
;
454 static void *read_skip_worktree_file_from_index(const char *path
, size_t *size
)
458 enum object_type type
;
462 pos
= cache_name_pos(path
, len
);
465 if (!ce_skip_worktree(active_cache
[pos
]))
467 data
= read_sha1_file(active_cache
[pos
]->sha1
, &type
, &sz
);
468 if (!data
|| type
!= OBJ_BLOB
) {
477 * Frees memory within el which was allocated for exclude patterns and
478 * the file buffer. Does not free el itself.
480 void clear_exclude_list(struct exclude_list
*el
)
484 for (i
= 0; i
< el
->nr
; i
++)
485 free(el
->excludes
[i
]);
494 int add_excludes_from_file_to_list(const char *fname
,
497 struct exclude_list
*el
,
501 int fd
, i
, lineno
= 1;
505 fd
= open(fname
, O_RDONLY
);
506 if (fd
< 0 || fstat(fd
, &st
) < 0) {
508 warn_on_inaccessible(fname
);
512 (buf
= read_skip_worktree_file_from_index(fname
, &size
)) == NULL
)
518 if (buf
[size
-1] != '\n') {
519 buf
= xrealloc(buf
, size
+1);
524 size
= xsize_t(st
.st_size
);
529 buf
= xmalloc(size
+1);
530 if (read_in_full(fd
, buf
, size
) != size
) {
541 for (i
= 0; i
< size
; i
++) {
542 if (buf
[i
] == '\n') {
543 if (entry
!= buf
+ i
&& entry
[0] != '#') {
544 buf
[i
- (i
&& buf
[i
-1] == '\r')] = 0;
545 add_exclude(entry
, base
, baselen
, el
, lineno
);
554 struct exclude_list
*add_exclude_list(struct dir_struct
*dir
,
555 int group_type
, const char *src
)
557 struct exclude_list
*el
;
558 struct exclude_list_group
*group
;
560 group
= &dir
->exclude_list_group
[group_type
];
561 ALLOC_GROW(group
->el
, group
->nr
+ 1, group
->alloc
);
562 el
= &group
->el
[group
->nr
++];
563 memset(el
, 0, sizeof(*el
));
569 * Used to set up core.excludesfile and .git/info/exclude lists.
571 void add_excludes_from_file(struct dir_struct
*dir
, const char *fname
)
573 struct exclude_list
*el
;
574 el
= add_exclude_list(dir
, EXC_FILE
, fname
);
575 if (add_excludes_from_file_to_list(fname
, "", 0, el
, 0) < 0)
576 die("cannot use %s as an exclude file", fname
);
579 int match_basename(const char *basename
, int basenamelen
,
580 const char *pattern
, int prefix
, int patternlen
,
583 if (prefix
== patternlen
) {
584 if (patternlen
== basenamelen
&&
585 !strncmp_icase(pattern
, basename
, basenamelen
))
587 } else if (flags
& EXC_FLAG_ENDSWITH
) {
588 /* "*literal" matching against "fooliteral" */
589 if (patternlen
- 1 <= basenamelen
&&
590 !strncmp_icase(pattern
+ 1,
591 basename
+ basenamelen
- (patternlen
- 1),
595 if (fnmatch_icase_mem(pattern
, patternlen
,
596 basename
, basenamelen
,
603 int match_pathname(const char *pathname
, int pathlen
,
604 const char *base
, int baselen
,
605 const char *pattern
, int prefix
, int patternlen
,
612 * match with FNM_PATHNAME; the pattern has base implicitly
615 if (*pattern
== '/') {
622 * baselen does not count the trailing slash. base[] may or
623 * may not end with a trailing slash though.
625 if (pathlen
< baselen
+ 1 ||
626 (baselen
&& pathname
[baselen
] != '/') ||
627 strncmp_icase(pathname
, base
, baselen
))
630 namelen
= baselen
? pathlen
- baselen
- 1 : pathlen
;
631 name
= pathname
+ pathlen
- namelen
;
635 * if the non-wildcard part is longer than the
636 * remaining pathname, surely it cannot match.
638 if (prefix
> namelen
)
641 if (strncmp_icase(pattern
, name
, prefix
))
644 patternlen
-= prefix
;
649 * If the whole pattern did not have a wildcard,
650 * then our prefix match is all we need; we
651 * do not need to call fnmatch at all.
653 if (!patternlen
&& !namelen
)
657 return fnmatch_icase_mem(pattern
, patternlen
,
663 * Scan the given exclude list in reverse to see whether pathname
664 * should be ignored. The first match (i.e. the last on the list), if
665 * any, determines the fate. Returns the exclude_list element which
666 * matched, or NULL for undecided.
668 static struct exclude
*last_exclude_matching_from_list(const char *pathname
,
670 const char *basename
,
672 struct exclude_list
*el
)
677 return NULL
; /* undefined */
679 for (i
= el
->nr
- 1; 0 <= i
; i
--) {
680 struct exclude
*x
= el
->excludes
[i
];
681 const char *exclude
= x
->pattern
;
682 int prefix
= x
->nowildcardlen
;
684 if (x
->flags
& EXC_FLAG_MUSTBEDIR
) {
685 if (*dtype
== DT_UNKNOWN
)
686 *dtype
= get_dtype(NULL
, pathname
, pathlen
);
687 if (*dtype
!= DT_DIR
)
691 if (x
->flags
& EXC_FLAG_NODIR
) {
692 if (match_basename(basename
,
693 pathlen
- (basename
- pathname
),
694 exclude
, prefix
, x
->patternlen
,
700 assert(x
->baselen
== 0 || x
->base
[x
->baselen
- 1] == '/');
701 if (match_pathname(pathname
, pathlen
,
702 x
->base
, x
->baselen
? x
->baselen
- 1 : 0,
703 exclude
, prefix
, x
->patternlen
, x
->flags
))
706 return NULL
; /* undecided */
710 * Scan the list and let the last match determine the fate.
711 * Return 1 for exclude, 0 for include and -1 for undecided.
713 int is_excluded_from_list(const char *pathname
,
714 int pathlen
, const char *basename
, int *dtype
,
715 struct exclude_list
*el
)
717 struct exclude
*exclude
;
718 exclude
= last_exclude_matching_from_list(pathname
, pathlen
, basename
, dtype
, el
);
720 return exclude
->flags
& EXC_FLAG_NEGATIVE
? 0 : 1;
721 return -1; /* undecided */
724 static struct exclude
*last_exclude_matching_from_lists(struct dir_struct
*dir
,
725 const char *pathname
, int pathlen
, const char *basename
,
729 struct exclude_list_group
*group
;
730 struct exclude
*exclude
;
731 for (i
= EXC_CMDL
; i
<= EXC_FILE
; i
++) {
732 group
= &dir
->exclude_list_group
[i
];
733 for (j
= group
->nr
- 1; j
>= 0; j
--) {
734 exclude
= last_exclude_matching_from_list(
735 pathname
, pathlen
, basename
, dtype_p
,
745 * Loads the per-directory exclude list for the substring of base
746 * which has a char length of baselen.
748 static void prep_exclude(struct dir_struct
*dir
, const char *base
, int baselen
)
750 struct exclude_list_group
*group
;
751 struct exclude_list
*el
;
752 struct exclude_stack
*stk
= NULL
;
755 group
= &dir
->exclude_list_group
[EXC_DIRS
];
757 /* Pop the exclude lists from the EXCL_DIRS exclude_list_group
758 * which originate from directories not in the prefix of the
759 * path being checked. */
760 while ((stk
= dir
->exclude_stack
) != NULL
) {
761 if (stk
->baselen
<= baselen
&&
762 !strncmp(dir
->basebuf
, base
, stk
->baselen
))
764 el
= &group
->el
[dir
->exclude_stack
->exclude_ix
];
765 dir
->exclude_stack
= stk
->prev
;
767 free((char *)el
->src
); /* see strdup() below */
768 clear_exclude_list(el
);
773 /* Skip traversing into sub directories if the parent is excluded */
777 /* Read from the parent directories and push them down. */
778 current
= stk
? stk
->baselen
: -1;
779 while (current
< baselen
) {
780 struct exclude_stack
*stk
= xcalloc(1, sizeof(*stk
));
788 cp
= strchr(base
+ current
+ 1, '/');
790 die("oops in prep_exclude");
793 stk
->prev
= dir
->exclude_stack
;
794 stk
->baselen
= cp
- base
;
795 stk
->exclude_ix
= group
->nr
;
796 el
= add_exclude_list(dir
, EXC_DIRS
, NULL
);
797 memcpy(dir
->basebuf
+ current
, base
+ current
,
798 stk
->baselen
- current
);
800 /* Abort if the directory is excluded */
803 dir
->basebuf
[stk
->baselen
- 1] = 0;
804 dir
->exclude
= last_exclude_matching_from_lists(dir
,
805 dir
->basebuf
, stk
->baselen
- 1,
806 dir
->basebuf
+ current
, &dt
);
807 dir
->basebuf
[stk
->baselen
- 1] = '/';
809 dir
->exclude
->flags
& EXC_FLAG_NEGATIVE
)
812 dir
->basebuf
[stk
->baselen
] = 0;
813 dir
->exclude_stack
= stk
;
818 /* Try to read per-directory file unless path is too long */
819 if (dir
->exclude_per_dir
&&
820 stk
->baselen
+ strlen(dir
->exclude_per_dir
) < PATH_MAX
) {
821 strcpy(dir
->basebuf
+ stk
->baselen
,
822 dir
->exclude_per_dir
);
824 * dir->basebuf gets reused by the traversal, but we
825 * need fname to remain unchanged to ensure the src
826 * member of each struct exclude correctly
827 * back-references its source file. Other invocations
828 * of add_exclude_list provide stable strings, so we
829 * strdup() and free() here in the caller.
831 el
->src
= strdup(dir
->basebuf
);
832 add_excludes_from_file_to_list(dir
->basebuf
,
833 dir
->basebuf
, stk
->baselen
, el
, 1);
835 dir
->exclude_stack
= stk
;
836 current
= stk
->baselen
;
838 dir
->basebuf
[baselen
] = '\0';
842 * Loads the exclude lists for the directory containing pathname, then
843 * scans all exclude lists to determine whether pathname is excluded.
844 * Returns the exclude_list element which matched, or NULL for
847 struct exclude
*last_exclude_matching(struct dir_struct
*dir
,
848 const char *pathname
,
851 int pathlen
= strlen(pathname
);
852 const char *basename
= strrchr(pathname
, '/');
853 basename
= (basename
) ? basename
+1 : pathname
;
855 prep_exclude(dir
, pathname
, basename
-pathname
);
860 return last_exclude_matching_from_lists(dir
, pathname
, pathlen
,
865 * Loads the exclude lists for the directory containing pathname, then
866 * scans all exclude lists to determine whether pathname is excluded.
867 * Returns 1 if true, otherwise 0.
869 int is_excluded(struct dir_struct
*dir
, const char *pathname
, int *dtype_p
)
871 struct exclude
*exclude
=
872 last_exclude_matching(dir
, pathname
, dtype_p
);
874 return exclude
->flags
& EXC_FLAG_NEGATIVE
? 0 : 1;
878 static struct dir_entry
*dir_entry_new(const char *pathname
, int len
)
880 struct dir_entry
*ent
;
882 ent
= xmalloc(sizeof(*ent
) + len
+ 1);
884 memcpy(ent
->name
, pathname
, len
);
889 static struct dir_entry
*dir_add_name(struct dir_struct
*dir
, const char *pathname
, int len
)
891 if (cache_file_exists(pathname
, len
, ignore_case
))
894 ALLOC_GROW(dir
->entries
, dir
->nr
+1, dir
->alloc
);
895 return dir
->entries
[dir
->nr
++] = dir_entry_new(pathname
, len
);
898 struct dir_entry
*dir_add_ignored(struct dir_struct
*dir
, const char *pathname
, int len
)
900 if (!cache_name_is_other(pathname
, len
))
903 ALLOC_GROW(dir
->ignored
, dir
->ignored_nr
+1, dir
->ignored_alloc
);
904 return dir
->ignored
[dir
->ignored_nr
++] = dir_entry_new(pathname
, len
);
908 index_nonexistent
= 0,
914 * Do not use the alphabetically sorted index to look up
915 * the directory name; instead, use the case insensitive
918 static enum exist_status
directory_exists_in_index_icase(const char *dirname
, int len
)
920 const struct cache_entry
*ce
= cache_dir_exists(dirname
, len
);
921 unsigned char endchar
;
924 return index_nonexistent
;
925 endchar
= ce
->name
[len
];
928 * The cache_entry structure returned will contain this dirname
929 * and possibly additional path components.
932 return index_directory
;
935 * If there are no additional path components, then this cache_entry
936 * represents a submodule. Submodules, despite being directories,
937 * are stored in the cache without a closing slash.
939 if (!endchar
&& S_ISGITLINK(ce
->ce_mode
))
942 /* This should never be hit, but it exists just in case. */
943 return index_nonexistent
;
947 * The index sorts alphabetically by entry name, which
948 * means that a gitlink sorts as '\0' at the end, while
949 * a directory (which is defined not as an entry, but as
950 * the files it contains) will sort with the '/' at the
953 static enum exist_status
directory_exists_in_index(const char *dirname
, int len
)
958 return directory_exists_in_index_icase(dirname
, len
);
960 pos
= cache_name_pos(dirname
, len
);
963 while (pos
< active_nr
) {
964 const struct cache_entry
*ce
= active_cache
[pos
++];
965 unsigned char endchar
;
967 if (strncmp(ce
->name
, dirname
, len
))
969 endchar
= ce
->name
[len
];
973 return index_directory
;
974 if (!endchar
&& S_ISGITLINK(ce
->ce_mode
))
977 return index_nonexistent
;
981 * When we find a directory when traversing the filesystem, we
982 * have three distinct cases:
985 * - see it as a directory
988 * and which one we choose depends on a combination of existing
989 * git index contents and the flags passed into the directory
992 * Case 1: If we *already* have entries in the index under that
993 * directory name, we always recurse into the directory to see
996 * Case 2: If we *already* have that directory name as a gitlink,
997 * we always continue to see it as a gitlink, regardless of whether
998 * there is an actual git directory there or not (it might not
999 * be checked out as a subproject!)
1001 * Case 3: if we didn't have it in the index previously, we
1002 * have a few sub-cases:
1004 * (a) if "show_other_directories" is true, we show it as
1005 * just a directory, unless "hide_empty_directories" is
1006 * also true, in which case we need to check if it contains any
1007 * untracked and / or ignored files.
1008 * (b) if it looks like a git directory, and we don't have
1009 * 'no_gitlinks' set we treat it as a gitlink, and show it
1011 * (c) otherwise, we recurse into it.
1013 static enum path_treatment
treat_directory(struct dir_struct
*dir
,
1014 const char *dirname
, int len
, int exclude
,
1015 const struct path_simplify
*simplify
)
1017 /* The "len-1" is to strip the final '/' */
1018 switch (directory_exists_in_index(dirname
, len
-1)) {
1019 case index_directory
:
1020 return path_recurse
;
1025 case index_nonexistent
:
1026 if (dir
->flags
& DIR_SHOW_OTHER_DIRECTORIES
)
1028 if (!(dir
->flags
& DIR_NO_GITLINKS
)) {
1029 unsigned char sha1
[20];
1030 if (resolve_gitlink_ref(dirname
, "HEAD", sha1
) == 0)
1031 return path_untracked
;
1033 return path_recurse
;
1036 /* This is the "show_other_directories" case */
1038 if (!(dir
->flags
& DIR_HIDE_EMPTY_DIRECTORIES
))
1039 return exclude
? path_excluded
: path_untracked
;
1041 return read_directory_recursive(dir
, dirname
, len
, 1, simplify
);
1045 * This is an inexact early pruning of any recursive directory
1046 * reading - if the path cannot possibly be in the pathspec,
1047 * return true, and we'll skip it early.
1049 static int simplify_away(const char *path
, int pathlen
, const struct path_simplify
*simplify
)
1053 const char *match
= simplify
->path
;
1054 int len
= simplify
->len
;
1060 if (!memcmp(path
, match
, len
))
1070 * This function tells us whether an excluded path matches a
1071 * list of "interesting" pathspecs. That is, whether a path matched
1072 * by any of the pathspecs could possibly be ignored by excluding
1073 * the specified path. This can happen if:
1075 * 1. the path is mentioned explicitly in the pathspec
1077 * 2. the path is a directory prefix of some element in the
1080 static int exclude_matches_pathspec(const char *path
, int len
,
1081 const struct path_simplify
*simplify
)
1084 for (; simplify
->path
; simplify
++) {
1085 if (len
== simplify
->len
1086 && !memcmp(path
, simplify
->path
, len
))
1088 if (len
< simplify
->len
1089 && simplify
->path
[len
] == '/'
1090 && !memcmp(path
, simplify
->path
, len
))
1097 static int get_index_dtype(const char *path
, int len
)
1100 const struct cache_entry
*ce
;
1102 ce
= cache_file_exists(path
, len
, 0);
1104 if (!ce_uptodate(ce
))
1106 if (S_ISGITLINK(ce
->ce_mode
))
1109 * Nobody actually cares about the
1110 * difference between DT_LNK and DT_REG
1115 /* Try to look it up as a directory */
1116 pos
= cache_name_pos(path
, len
);
1120 while (pos
< active_nr
) {
1121 ce
= active_cache
[pos
++];
1122 if (strncmp(ce
->name
, path
, len
))
1124 if (ce
->name
[len
] > '/')
1126 if (ce
->name
[len
] < '/')
1128 if (!ce_uptodate(ce
))
1129 break; /* continue? */
1135 static int get_dtype(struct dirent
*de
, const char *path
, int len
)
1137 int dtype
= de
? DTYPE(de
) : DT_UNKNOWN
;
1140 if (dtype
!= DT_UNKNOWN
)
1142 dtype
= get_index_dtype(path
, len
);
1143 if (dtype
!= DT_UNKNOWN
)
1145 if (lstat(path
, &st
))
1147 if (S_ISREG(st
.st_mode
))
1149 if (S_ISDIR(st
.st_mode
))
1151 if (S_ISLNK(st
.st_mode
))
1156 static enum path_treatment
treat_one_path(struct dir_struct
*dir
,
1157 struct strbuf
*path
,
1158 const struct path_simplify
*simplify
,
1159 int dtype
, struct dirent
*de
)
1162 int has_path_in_index
= !!cache_file_exists(path
->buf
, path
->len
, ignore_case
);
1164 if (dtype
== DT_UNKNOWN
)
1165 dtype
= get_dtype(de
, path
->buf
, path
->len
);
1167 /* Always exclude indexed files */
1168 if (dtype
!= DT_DIR
&& has_path_in_index
)
1172 * When we are looking at a directory P in the working tree,
1173 * there are three cases:
1175 * (1) P exists in the index. Everything inside the directory P in
1176 * the working tree needs to go when P is checked out from the
1179 * (2) P does not exist in the index, but there is P/Q in the index.
1180 * We know P will stay a directory when we check out the contents
1181 * of the index, but we do not know yet if there is a directory
1182 * P/Q in the working tree to be killed, so we need to recurse.
1184 * (3) P does not exist in the index, and there is no P/Q in the index
1185 * to require P to be a directory, either. Only in this case, we
1186 * know that everything inside P will not be killed without
1189 if ((dir
->flags
& DIR_COLLECT_KILLED_ONLY
) &&
1190 (dtype
== DT_DIR
) &&
1191 !has_path_in_index
&&
1192 (directory_exists_in_index(path
->buf
, path
->len
) == index_nonexistent
))
1195 exclude
= is_excluded(dir
, path
->buf
, &dtype
);
1198 * Excluded? If we don't explicitly want to show
1199 * ignored files, ignore it
1201 if (exclude
&& !(dir
->flags
& (DIR_SHOW_IGNORED
|DIR_SHOW_IGNORED_TOO
)))
1202 return path_excluded
;
1208 strbuf_addch(path
, '/');
1209 return treat_directory(dir
, path
->buf
, path
->len
, exclude
,
1213 return exclude
? path_excluded
: path_untracked
;
1217 static enum path_treatment
treat_path(struct dir_struct
*dir
,
1219 struct strbuf
*path
,
1221 const struct path_simplify
*simplify
)
1225 if (is_dot_or_dotdot(de
->d_name
) || !strcmp(de
->d_name
, ".git"))
1227 strbuf_setlen(path
, baselen
);
1228 strbuf_addstr(path
, de
->d_name
);
1229 if (simplify_away(path
->buf
, path
->len
, simplify
))
1233 return treat_one_path(dir
, path
, simplify
, dtype
, de
);
1237 * Read a directory tree. We currently ignore anything but
1238 * directories, regular files and symlinks. That's because git
1239 * doesn't handle them at all yet. Maybe that will change some
1242 * Also, we ignore the name ".git" (even if it is not a directory).
1243 * That likely will not change.
1245 * Returns the most significant path_treatment value encountered in the scan.
1247 static enum path_treatment
read_directory_recursive(struct dir_struct
*dir
,
1248 const char *base
, int baselen
,
1250 const struct path_simplify
*simplify
)
1253 enum path_treatment state
, subdir_state
, dir_state
= path_none
;
1255 struct strbuf path
= STRBUF_INIT
;
1257 strbuf_add(&path
, base
, baselen
);
1259 fdir
= opendir(path
.len
? path
.buf
: ".");
1263 while ((de
= readdir(fdir
)) != NULL
) {
1264 /* check how the file or directory should be treated */
1265 state
= treat_path(dir
, de
, &path
, baselen
, simplify
);
1266 if (state
> dir_state
)
1269 /* recurse into subdir if instructed by treat_path */
1270 if (state
== path_recurse
) {
1271 subdir_state
= read_directory_recursive(dir
, path
.buf
,
1272 path
.len
, check_only
, simplify
);
1273 if (subdir_state
> dir_state
)
1274 dir_state
= subdir_state
;
1278 /* abort early if maximum state has been reached */
1279 if (dir_state
== path_untracked
)
1281 /* skip the dir_add_* part */
1285 /* add the path to the appropriate result list */
1288 if (dir
->flags
& DIR_SHOW_IGNORED
)
1289 dir_add_name(dir
, path
.buf
, path
.len
);
1290 else if ((dir
->flags
& DIR_SHOW_IGNORED_TOO
) ||
1291 ((dir
->flags
& DIR_COLLECT_IGNORED
) &&
1292 exclude_matches_pathspec(path
.buf
, path
.len
,
1294 dir_add_ignored(dir
, path
.buf
, path
.len
);
1297 case path_untracked
:
1298 if (!(dir
->flags
& DIR_SHOW_IGNORED
))
1299 dir_add_name(dir
, path
.buf
, path
.len
);
1308 strbuf_release(&path
);
1313 static int cmp_name(const void *p1
, const void *p2
)
1315 const struct dir_entry
*e1
= *(const struct dir_entry
**)p1
;
1316 const struct dir_entry
*e2
= *(const struct dir_entry
**)p2
;
1318 return cache_name_compare(e1
->name
, e1
->len
,
1322 static struct path_simplify
*create_simplify(const char **pathspec
)
1325 struct path_simplify
*simplify
= NULL
;
1330 for (nr
= 0 ; ; nr
++) {
1332 ALLOC_GROW(simplify
, nr
+ 1, alloc
);
1333 match
= *pathspec
++;
1336 simplify
[nr
].path
= match
;
1337 simplify
[nr
].len
= simple_length(match
);
1339 simplify
[nr
].path
= NULL
;
1340 simplify
[nr
].len
= 0;
1344 static void free_simplify(struct path_simplify
*simplify
)
1349 static int treat_leading_path(struct dir_struct
*dir
,
1350 const char *path
, int len
,
1351 const struct path_simplify
*simplify
)
1353 struct strbuf sb
= STRBUF_INIT
;
1354 int baselen
, rc
= 0;
1356 int old_flags
= dir
->flags
;
1358 while (len
&& path
[len
- 1] == '/')
1363 dir
->flags
&= ~DIR_SHOW_OTHER_DIRECTORIES
;
1365 cp
= path
+ baselen
+ !!baselen
;
1366 cp
= memchr(cp
, '/', path
+ len
- cp
);
1370 baselen
= cp
- path
;
1371 strbuf_setlen(&sb
, 0);
1372 strbuf_add(&sb
, path
, baselen
);
1373 if (!is_directory(sb
.buf
))
1375 if (simplify_away(sb
.buf
, sb
.len
, simplify
))
1377 if (treat_one_path(dir
, &sb
, simplify
,
1378 DT_DIR
, NULL
) == path_none
)
1379 break; /* do not recurse into it */
1380 if (len
<= baselen
) {
1382 break; /* finished checking */
1385 strbuf_release(&sb
);
1386 dir
->flags
= old_flags
;
1390 int read_directory(struct dir_struct
*dir
, const char *path
, int len
, const struct pathspec
*pathspec
)
1392 struct path_simplify
*simplify
;
1395 * Check out create_simplify()
1398 GUARD_PATHSPEC(pathspec
,
1406 if (has_symlink_leading_path(path
, len
))
1410 * exclude patterns are treated like positive ones in
1411 * create_simplify. Usually exclude patterns should be a
1412 * subset of positive ones, which has no impacts on
1413 * create_simplify().
1415 simplify
= create_simplify(pathspec
? pathspec
->_raw
: NULL
);
1416 if (!len
|| treat_leading_path(dir
, path
, len
, simplify
))
1417 read_directory_recursive(dir
, path
, len
, 0, simplify
);
1418 free_simplify(simplify
);
1419 qsort(dir
->entries
, dir
->nr
, sizeof(struct dir_entry
*), cmp_name
);
1420 qsort(dir
->ignored
, dir
->ignored_nr
, sizeof(struct dir_entry
*), cmp_name
);
1424 int file_exists(const char *f
)
1427 return lstat(f
, &sb
) == 0;
1431 * Given two normalized paths (a trailing slash is ok), if subdir is
1432 * outside dir, return -1. Otherwise return the offset in subdir that
1433 * can be used as relative path to dir.
1435 int dir_inside_of(const char *subdir
, const char *dir
)
1439 assert(dir
&& subdir
&& *dir
&& *subdir
);
1441 while (*dir
&& *subdir
&& *dir
== *subdir
) {
1447 /* hel[p]/me vs hel[l]/yeah */
1448 if (*dir
&& *subdir
)
1452 return !*dir
? offset
: -1; /* same dir */
1454 /* foo/[b]ar vs foo/[] */
1455 if (is_dir_sep(dir
[-1]))
1456 return is_dir_sep(subdir
[-1]) ? offset
: -1;
1458 /* foo[/]bar vs foo[] */
1459 return is_dir_sep(*subdir
) ? offset
+ 1 : -1;
1462 int is_inside_dir(const char *dir
)
1467 if (!getcwd(cwd
, sizeof(cwd
)))
1468 die_errno("can't find the current directory");
1469 return dir_inside_of(cwd
, dir
) >= 0;
1472 int is_empty_dir(const char *path
)
1474 DIR *dir
= opendir(path
);
1481 while ((e
= readdir(dir
)) != NULL
)
1482 if (!is_dot_or_dotdot(e
->d_name
)) {
1491 static int remove_dir_recurse(struct strbuf
*path
, int flag
, int *kept_up
)
1495 int ret
= 0, original_len
= path
->len
, len
, kept_down
= 0;
1496 int only_empty
= (flag
& REMOVE_DIR_EMPTY_ONLY
);
1497 int keep_toplevel
= (flag
& REMOVE_DIR_KEEP_TOPLEVEL
);
1498 unsigned char submodule_head
[20];
1500 if ((flag
& REMOVE_DIR_KEEP_NESTED_GIT
) &&
1501 !resolve_gitlink_ref(path
->buf
, "HEAD", submodule_head
)) {
1502 /* Do not descend and nuke a nested git work tree. */
1508 flag
&= ~REMOVE_DIR_KEEP_TOPLEVEL
;
1509 dir
= opendir(path
->buf
);
1511 if (errno
== ENOENT
)
1512 return keep_toplevel
? -1 : 0;
1513 else if (errno
== EACCES
&& !keep_toplevel
)
1515 * An empty dir could be removable even if it
1518 return rmdir(path
->buf
);
1522 if (path
->buf
[original_len
- 1] != '/')
1523 strbuf_addch(path
, '/');
1526 while ((e
= readdir(dir
)) != NULL
) {
1528 if (is_dot_or_dotdot(e
->d_name
))
1531 strbuf_setlen(path
, len
);
1532 strbuf_addstr(path
, e
->d_name
);
1533 if (lstat(path
->buf
, &st
)) {
1534 if (errno
== ENOENT
)
1536 * file disappeared, which is what we
1541 } else if (S_ISDIR(st
.st_mode
)) {
1542 if (!remove_dir_recurse(path
, flag
, &kept_down
))
1543 continue; /* happy */
1544 } else if (!only_empty
&&
1545 (!unlink(path
->buf
) || errno
== ENOENT
)) {
1546 continue; /* happy, too */
1549 /* path too long, stat fails, or non-directory still exists */
1555 strbuf_setlen(path
, original_len
);
1556 if (!ret
&& !keep_toplevel
&& !kept_down
)
1557 ret
= (!rmdir(path
->buf
) || errno
== ENOENT
) ? 0 : -1;
1560 * report the uplevel that it is not an error that we
1561 * did not rmdir() our directory.
1567 int remove_dir_recursively(struct strbuf
*path
, int flag
)
1569 return remove_dir_recurse(path
, flag
, NULL
);
1572 void setup_standard_excludes(struct dir_struct
*dir
)
1577 dir
->exclude_per_dir
= ".gitignore";
1578 path
= git_path("info/exclude");
1579 if (!excludes_file
) {
1580 home_config_paths(NULL
, &xdg_path
, "ignore");
1581 excludes_file
= xdg_path
;
1583 if (!access_or_warn(path
, R_OK
, 0))
1584 add_excludes_from_file(dir
, path
);
1585 if (excludes_file
&& !access_or_warn(excludes_file
, R_OK
, 0))
1586 add_excludes_from_file(dir
, excludes_file
);
1589 int remove_path(const char *name
)
1593 if (unlink(name
) && errno
!= ENOENT
&& errno
!= ENOTDIR
)
1596 slash
= strrchr(name
, '/');
1598 char *dirs
= xstrdup(name
);
1599 slash
= dirs
+ (slash
- name
);
1602 } while (rmdir(dirs
) == 0 && (slash
= strrchr(dirs
, '/')));
1609 * Frees memory within dir which was allocated for exclude lists and
1610 * the exclude_stack. Does not free dir itself.
1612 void clear_directory(struct dir_struct
*dir
)
1615 struct exclude_list_group
*group
;
1616 struct exclude_list
*el
;
1617 struct exclude_stack
*stk
;
1619 for (i
= EXC_CMDL
; i
<= EXC_FILE
; i
++) {
1620 group
= &dir
->exclude_list_group
[i
];
1621 for (j
= 0; j
< group
->nr
; j
++) {
1624 free((char *)el
->src
);
1625 clear_exclude_list(el
);
1630 stk
= dir
->exclude_stack
;
1632 struct exclude_stack
*prev
= stk
->prev
;