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 wildmatch(pattern
, string
,
53 flags
| (ignore_case
? WM_CASEFOLD
: 0),
57 inline int git_fnmatch(const struct pathspec_item
*item
,
58 const char *pattern
, const char *string
,
62 if (ps_strncmp(item
, pattern
, string
, prefix
))
67 if (item
->flags
& PATHSPEC_ONESTAR
) {
68 int pattern_len
= strlen(++pattern
);
69 int string_len
= strlen(string
);
70 return string_len
< pattern_len
||
71 ps_strcmp(item
, pattern
,
72 string
+ string_len
- pattern_len
);
74 if (item
->magic
& PATHSPEC_GLOB
)
75 return wildmatch(pattern
, string
,
77 (item
->magic
& PATHSPEC_ICASE
? WM_CASEFOLD
: 0),
80 /* wildmatch has not learned no FNM_PATHNAME mode yet */
81 return wildmatch(pattern
, string
,
82 item
->magic
& PATHSPEC_ICASE
? WM_CASEFOLD
: 0,
86 static int fnmatch_icase_mem(const char *pattern
, int patternlen
,
87 const char *string
, int stringlen
,
91 struct strbuf pat_buf
= STRBUF_INIT
;
92 struct strbuf str_buf
= STRBUF_INIT
;
93 const char *use_pat
= pattern
;
94 const char *use_str
= string
;
96 if (pattern
[patternlen
]) {
97 strbuf_add(&pat_buf
, pattern
, patternlen
);
98 use_pat
= pat_buf
.buf
;
100 if (string
[stringlen
]) {
101 strbuf_add(&str_buf
, string
, stringlen
);
102 use_str
= str_buf
.buf
;
106 flags
|= WM_CASEFOLD
;
107 match_status
= wildmatch(use_pat
, use_str
, flags
, NULL
);
109 strbuf_release(&pat_buf
);
110 strbuf_release(&str_buf
);
115 static size_t common_prefix_len(const struct pathspec
*pathspec
)
121 * ":(icase)path" is treated as a pathspec full of
122 * wildcard. In other words, only prefix is considered common
123 * prefix. If the pathspec is abc/foo abc/bar, running in
124 * subdir xyz, the common prefix is still xyz, not xuz/abc as
127 GUARD_PATHSPEC(pathspec
,
135 for (n
= 0; n
< pathspec
->nr
; n
++) {
136 size_t i
= 0, len
= 0, item_len
;
137 if (pathspec
->items
[n
].magic
& PATHSPEC_EXCLUDE
)
139 if (pathspec
->items
[n
].magic
& PATHSPEC_ICASE
)
140 item_len
= pathspec
->items
[n
].prefix
;
142 item_len
= pathspec
->items
[n
].nowildcard_len
;
143 while (i
< item_len
&& (n
== 0 || i
< max
)) {
144 char c
= pathspec
->items
[n
].match
[i
];
145 if (c
!= pathspec
->items
[0].match
[i
])
151 if (n
== 0 || len
< max
) {
161 * Returns a copy of the longest leading path common among all
164 char *common_prefix(const struct pathspec
*pathspec
)
166 unsigned long len
= common_prefix_len(pathspec
);
168 return len
? xmemdupz(pathspec
->items
[0].match
, len
) : NULL
;
171 int fill_directory(struct dir_struct
*dir
, const struct pathspec
*pathspec
)
176 * Calculate common prefix for the pathspec, and
177 * use that to optimize the directory walk
179 len
= common_prefix_len(pathspec
);
181 /* Read the directory and prune it */
182 read_directory(dir
, pathspec
->nr
? pathspec
->_raw
[0] : "", len
, pathspec
);
186 int within_depth(const char *name
, int namelen
,
187 int depth
, int max_depth
)
189 const char *cp
= name
, *cpe
= name
+ namelen
;
195 if (depth
> max_depth
)
202 * Does 'match' match the given name?
203 * A match is found if
205 * (1) the 'match' string is leading directory of 'name', or
206 * (2) the 'match' string is a wildcard and matches 'name', or
207 * (3) the 'match' string is exactly the same as 'name'.
209 * and the return value tells which case it was.
211 * It returns 0 when there is no match.
213 static int match_pathspec_item(const struct pathspec_item
*item
, int prefix
,
214 const char *name
, int namelen
)
216 /* name/namelen has prefix cut off by caller */
217 const char *match
= item
->match
+ prefix
;
218 int matchlen
= item
->len
- prefix
;
221 * The normal call pattern is:
222 * 1. prefix = common_prefix_len(ps);
223 * 2. prune something, or fill_directory
224 * 3. match_pathspec_depth()
226 * 'prefix' at #1 may be shorter than the command's prefix and
227 * it's ok for #2 to match extra files. Those extras will be
230 * Suppose the pathspec is 'foo' and '../bar' running from
231 * subdir 'xyz'. The common prefix at #1 will be empty, thanks
232 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
233 * user does not want XYZ/foo, only the "foo" part should be
234 * case-insensitive. We need to filter out XYZ/foo here. In
235 * other words, we do not trust the caller on comparing the
236 * prefix part when :(icase) is involved. We do exact
237 * comparison ourselves.
239 * Normally the caller (common_prefix_len() in fact) does
240 * _exact_ matching on name[-prefix+1..-1] and we do not need
241 * to check that part. Be defensive and check it anyway, in
242 * case common_prefix_len is changed, or a new caller is
243 * introduced that does not use common_prefix_len.
245 * If the penalty turns out too high when prefix is really
246 * long, maybe change it to
247 * strncmp(match, name, item->prefix - prefix)
249 if (item
->prefix
&& (item
->magic
& PATHSPEC_ICASE
) &&
250 strncmp(item
->match
, name
- prefix
, item
->prefix
))
253 /* If the match was just the prefix, we matched */
255 return MATCHED_RECURSIVELY
;
257 if (matchlen
<= namelen
&& !ps_strncmp(item
, match
, name
, matchlen
)) {
258 if (matchlen
== namelen
)
259 return MATCHED_EXACTLY
;
261 if (match
[matchlen
-1] == '/' || name
[matchlen
] == '/')
262 return MATCHED_RECURSIVELY
;
265 if (item
->nowildcard_len
< item
->len
&&
266 !git_fnmatch(item
, match
, name
,
267 item
->nowildcard_len
- prefix
))
268 return MATCHED_FNMATCH
;
274 * Given a name and a list of pathspecs, returns the nature of the
275 * closest (i.e. most specific) match of the name to any of the
278 * The caller typically calls this multiple times with the same
279 * pathspec and seen[] array but with different name/namelen
280 * (e.g. entries from the index) and is interested in seeing if and
281 * how each pathspec matches all the names it calls this function
282 * with. A mark is left in the seen[] array for each pathspec element
283 * indicating the closest type of match that element achieved, so if
284 * seen[n] remains zero after multiple invocations, that means the nth
285 * pathspec did not match any names, which could indicate that the
286 * user mistyped the nth pathspec.
288 static int match_pathspec_depth_1(const struct pathspec
*ps
,
289 const char *name
, int namelen
,
290 int prefix
, char *seen
,
304 if (!ps
->recursive
||
305 !(ps
->magic
& PATHSPEC_MAXDEPTH
) ||
307 return MATCHED_RECURSIVELY
;
309 if (within_depth(name
, namelen
, 0, ps
->max_depth
))
310 return MATCHED_EXACTLY
;
318 for (i
= ps
->nr
- 1; i
>= 0; i
--) {
321 if ((!exclude
&& ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
) ||
322 ( exclude
&& !(ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
)))
325 if (seen
&& seen
[i
] == MATCHED_EXACTLY
)
328 * Make exclude patterns optional and never report
329 * "pathspec ':(exclude)foo' matches no files"
331 if (seen
&& ps
->items
[i
].magic
& PATHSPEC_EXCLUDE
)
332 seen
[i
] = MATCHED_FNMATCH
;
333 how
= match_pathspec_item(ps
->items
+i
, prefix
, name
, namelen
);
335 (ps
->magic
& PATHSPEC_MAXDEPTH
) &&
336 ps
->max_depth
!= -1 &&
337 how
&& how
!= MATCHED_FNMATCH
) {
338 int len
= ps
->items
[i
].len
;
339 if (name
[len
] == '/')
341 if (within_depth(name
+len
, namelen
-len
, 0, ps
->max_depth
))
342 how
= MATCHED_EXACTLY
;
349 if (seen
&& seen
[i
] < how
)
356 int match_pathspec_depth(const struct pathspec
*ps
,
357 const char *name
, int namelen
,
358 int prefix
, char *seen
)
360 int positive
, negative
;
361 positive
= match_pathspec_depth_1(ps
, name
, namelen
, prefix
, seen
, 0);
362 if (!(ps
->magic
& PATHSPEC_EXCLUDE
) || !positive
)
364 negative
= match_pathspec_depth_1(ps
, name
, namelen
, prefix
, seen
, 1);
365 return negative
? 0 : positive
;
369 * Return the length of the "simple" part of a path match limiter.
371 int simple_length(const char *match
)
376 unsigned char c
= *match
++;
378 if (c
== '\0' || is_glob_special(c
))
383 int no_wildcard(const char *string
)
385 return string
[simple_length(string
)] == '\0';
388 void parse_exclude_pattern(const char **pattern
,
393 const char *p
= *pattern
;
398 *flags
|= EXC_FLAG_NEGATIVE
;
402 if (len
&& p
[len
- 1] == '/') {
404 *flags
|= EXC_FLAG_MUSTBEDIR
;
406 for (i
= 0; i
< len
; i
++) {
411 *flags
|= EXC_FLAG_NODIR
;
412 *nowildcardlen
= simple_length(p
);
414 * we should have excluded the trailing slash from 'p' too,
415 * but that's one more allocation. Instead just make sure
416 * nowildcardlen does not exceed real patternlen
418 if (*nowildcardlen
> len
)
419 *nowildcardlen
= len
;
420 if (*p
== '*' && no_wildcard(p
+ 1))
421 *flags
|= EXC_FLAG_ENDSWITH
;
426 void add_exclude(const char *string
, const char *base
,
427 int baselen
, struct exclude_list
*el
, int srcpos
)
434 parse_exclude_pattern(&string
, &patternlen
, &flags
, &nowildcardlen
);
435 if (flags
& EXC_FLAG_MUSTBEDIR
) {
437 x
= xmalloc(sizeof(*x
) + patternlen
+ 1);
439 memcpy(s
, string
, patternlen
);
440 s
[patternlen
] = '\0';
443 x
= xmalloc(sizeof(*x
));
446 x
->patternlen
= patternlen
;
447 x
->nowildcardlen
= nowildcardlen
;
449 x
->baselen
= baselen
;
452 ALLOC_GROW(el
->excludes
, el
->nr
+ 1, el
->alloc
);
453 el
->excludes
[el
->nr
++] = x
;
457 static void *read_skip_worktree_file_from_index(const char *path
, size_t *size
)
461 enum object_type type
;
465 pos
= cache_name_pos(path
, len
);
468 if (!ce_skip_worktree(active_cache
[pos
]))
470 data
= read_sha1_file(active_cache
[pos
]->sha1
, &type
, &sz
);
471 if (!data
|| type
!= OBJ_BLOB
) {
480 * Frees memory within el which was allocated for exclude patterns and
481 * the file buffer. Does not free el itself.
483 void clear_exclude_list(struct exclude_list
*el
)
487 for (i
= 0; i
< el
->nr
; i
++)
488 free(el
->excludes
[i
]);
497 int add_excludes_from_file_to_list(const char *fname
,
500 struct exclude_list
*el
,
504 int fd
, i
, lineno
= 1;
508 fd
= open(fname
, O_RDONLY
);
509 if (fd
< 0 || fstat(fd
, &st
) < 0) {
511 warn_on_inaccessible(fname
);
515 (buf
= read_skip_worktree_file_from_index(fname
, &size
)) == NULL
)
521 if (buf
[size
-1] != '\n') {
522 buf
= xrealloc(buf
, size
+1);
527 size
= xsize_t(st
.st_size
);
532 buf
= xmalloc(size
+1);
533 if (read_in_full(fd
, buf
, size
) != size
) {
544 for (i
= 0; i
< size
; i
++) {
545 if (buf
[i
] == '\n') {
546 if (entry
!= buf
+ i
&& entry
[0] != '#') {
547 buf
[i
- (i
&& buf
[i
-1] == '\r')] = 0;
548 add_exclude(entry
, base
, baselen
, el
, lineno
);
557 struct exclude_list
*add_exclude_list(struct dir_struct
*dir
,
558 int group_type
, const char *src
)
560 struct exclude_list
*el
;
561 struct exclude_list_group
*group
;
563 group
= &dir
->exclude_list_group
[group_type
];
564 ALLOC_GROW(group
->el
, group
->nr
+ 1, group
->alloc
);
565 el
= &group
->el
[group
->nr
++];
566 memset(el
, 0, sizeof(*el
));
572 * Used to set up core.excludesfile and .git/info/exclude lists.
574 void add_excludes_from_file(struct dir_struct
*dir
, const char *fname
)
576 struct exclude_list
*el
;
577 el
= add_exclude_list(dir
, EXC_FILE
, fname
);
578 if (add_excludes_from_file_to_list(fname
, "", 0, el
, 0) < 0)
579 die("cannot use %s as an exclude file", fname
);
582 int match_basename(const char *basename
, int basenamelen
,
583 const char *pattern
, int prefix
, int patternlen
,
586 if (prefix
== patternlen
) {
587 if (patternlen
== basenamelen
&&
588 !strncmp_icase(pattern
, basename
, basenamelen
))
590 } else if (flags
& EXC_FLAG_ENDSWITH
) {
591 /* "*literal" matching against "fooliteral" */
592 if (patternlen
- 1 <= basenamelen
&&
593 !strncmp_icase(pattern
+ 1,
594 basename
+ basenamelen
- (patternlen
- 1),
598 if (fnmatch_icase_mem(pattern
, patternlen
,
599 basename
, basenamelen
,
606 int match_pathname(const char *pathname
, int pathlen
,
607 const char *base
, int baselen
,
608 const char *pattern
, int prefix
, int patternlen
,
615 * match with FNM_PATHNAME; the pattern has base implicitly
618 if (*pattern
== '/') {
625 * baselen does not count the trailing slash. base[] may or
626 * may not end with a trailing slash though.
628 if (pathlen
< baselen
+ 1 ||
629 (baselen
&& pathname
[baselen
] != '/') ||
630 strncmp_icase(pathname
, base
, baselen
))
633 namelen
= baselen
? pathlen
- baselen
- 1 : pathlen
;
634 name
= pathname
+ pathlen
- namelen
;
638 * if the non-wildcard part is longer than the
639 * remaining pathname, surely it cannot match.
641 if (prefix
> namelen
)
644 if (strncmp_icase(pattern
, name
, prefix
))
647 patternlen
-= prefix
;
652 * If the whole pattern did not have a wildcard,
653 * then our prefix match is all we need; we
654 * do not need to call fnmatch at all.
656 if (!patternlen
&& !namelen
)
660 return fnmatch_icase_mem(pattern
, patternlen
,
666 * Scan the given exclude list in reverse to see whether pathname
667 * should be ignored. The first match (i.e. the last on the list), if
668 * any, determines the fate. Returns the exclude_list element which
669 * matched, or NULL for undecided.
671 static struct exclude
*last_exclude_matching_from_list(const char *pathname
,
673 const char *basename
,
675 struct exclude_list
*el
)
680 return NULL
; /* undefined */
682 for (i
= el
->nr
- 1; 0 <= i
; i
--) {
683 struct exclude
*x
= el
->excludes
[i
];
684 const char *exclude
= x
->pattern
;
685 int prefix
= x
->nowildcardlen
;
687 if (x
->flags
& EXC_FLAG_MUSTBEDIR
) {
688 if (*dtype
== DT_UNKNOWN
)
689 *dtype
= get_dtype(NULL
, pathname
, pathlen
);
690 if (*dtype
!= DT_DIR
)
694 if (x
->flags
& EXC_FLAG_NODIR
) {
695 if (match_basename(basename
,
696 pathlen
- (basename
- pathname
),
697 exclude
, prefix
, x
->patternlen
,
703 assert(x
->baselen
== 0 || x
->base
[x
->baselen
- 1] == '/');
704 if (match_pathname(pathname
, pathlen
,
705 x
->base
, x
->baselen
? x
->baselen
- 1 : 0,
706 exclude
, prefix
, x
->patternlen
, x
->flags
))
709 return NULL
; /* undecided */
713 * Scan the list and let the last match determine the fate.
714 * Return 1 for exclude, 0 for include and -1 for undecided.
716 int is_excluded_from_list(const char *pathname
,
717 int pathlen
, const char *basename
, int *dtype
,
718 struct exclude_list
*el
)
720 struct exclude
*exclude
;
721 exclude
= last_exclude_matching_from_list(pathname
, pathlen
, basename
, dtype
, el
);
723 return exclude
->flags
& EXC_FLAG_NEGATIVE
? 0 : 1;
724 return -1; /* undecided */
727 static struct exclude
*last_exclude_matching_from_lists(struct dir_struct
*dir
,
728 const char *pathname
, int pathlen
, const char *basename
,
732 struct exclude_list_group
*group
;
733 struct exclude
*exclude
;
734 for (i
= EXC_CMDL
; i
<= EXC_FILE
; i
++) {
735 group
= &dir
->exclude_list_group
[i
];
736 for (j
= group
->nr
- 1; j
>= 0; j
--) {
737 exclude
= last_exclude_matching_from_list(
738 pathname
, pathlen
, basename
, dtype_p
,
748 * Loads the per-directory exclude list for the substring of base
749 * which has a char length of baselen.
751 static void prep_exclude(struct dir_struct
*dir
, const char *base
, int baselen
)
753 struct exclude_list_group
*group
;
754 struct exclude_list
*el
;
755 struct exclude_stack
*stk
= NULL
;
758 group
= &dir
->exclude_list_group
[EXC_DIRS
];
760 /* Pop the exclude lists from the EXCL_DIRS exclude_list_group
761 * which originate from directories not in the prefix of the
762 * path being checked. */
763 while ((stk
= dir
->exclude_stack
) != NULL
) {
764 if (stk
->baselen
<= baselen
&&
765 !strncmp(dir
->basebuf
, base
, stk
->baselen
))
767 el
= &group
->el
[dir
->exclude_stack
->exclude_ix
];
768 dir
->exclude_stack
= stk
->prev
;
770 free((char *)el
->src
); /* see strdup() below */
771 clear_exclude_list(el
);
776 /* Skip traversing into sub directories if the parent is excluded */
780 /* Read from the parent directories and push them down. */
781 current
= stk
? stk
->baselen
: -1;
782 while (current
< baselen
) {
783 struct exclude_stack
*stk
= xcalloc(1, sizeof(*stk
));
791 cp
= strchr(base
+ current
+ 1, '/');
793 die("oops in prep_exclude");
796 stk
->prev
= dir
->exclude_stack
;
797 stk
->baselen
= cp
- base
;
798 stk
->exclude_ix
= group
->nr
;
799 el
= add_exclude_list(dir
, EXC_DIRS
, NULL
);
800 memcpy(dir
->basebuf
+ current
, base
+ current
,
801 stk
->baselen
- current
);
803 /* Abort if the directory is excluded */
806 dir
->basebuf
[stk
->baselen
- 1] = 0;
807 dir
->exclude
= last_exclude_matching_from_lists(dir
,
808 dir
->basebuf
, stk
->baselen
- 1,
809 dir
->basebuf
+ current
, &dt
);
810 dir
->basebuf
[stk
->baselen
- 1] = '/';
812 dir
->exclude
->flags
& EXC_FLAG_NEGATIVE
)
815 dir
->basebuf
[stk
->baselen
] = 0;
816 dir
->exclude_stack
= stk
;
821 /* Try to read per-directory file unless path is too long */
822 if (dir
->exclude_per_dir
&&
823 stk
->baselen
+ strlen(dir
->exclude_per_dir
) < PATH_MAX
) {
824 strcpy(dir
->basebuf
+ stk
->baselen
,
825 dir
->exclude_per_dir
);
827 * dir->basebuf gets reused by the traversal, but we
828 * need fname to remain unchanged to ensure the src
829 * member of each struct exclude correctly
830 * back-references its source file. Other invocations
831 * of add_exclude_list provide stable strings, so we
832 * strdup() and free() here in the caller.
834 el
->src
= strdup(dir
->basebuf
);
835 add_excludes_from_file_to_list(dir
->basebuf
,
836 dir
->basebuf
, stk
->baselen
, el
, 1);
838 dir
->exclude_stack
= stk
;
839 current
= stk
->baselen
;
841 dir
->basebuf
[baselen
] = '\0';
845 * Loads the exclude lists for the directory containing pathname, then
846 * scans all exclude lists to determine whether pathname is excluded.
847 * Returns the exclude_list element which matched, or NULL for
850 struct exclude
*last_exclude_matching(struct dir_struct
*dir
,
851 const char *pathname
,
854 int pathlen
= strlen(pathname
);
855 const char *basename
= strrchr(pathname
, '/');
856 basename
= (basename
) ? basename
+1 : pathname
;
858 prep_exclude(dir
, pathname
, basename
-pathname
);
863 return last_exclude_matching_from_lists(dir
, pathname
, pathlen
,
868 * Loads the exclude lists for the directory containing pathname, then
869 * scans all exclude lists to determine whether pathname is excluded.
870 * Returns 1 if true, otherwise 0.
872 int is_excluded(struct dir_struct
*dir
, const char *pathname
, int *dtype_p
)
874 struct exclude
*exclude
=
875 last_exclude_matching(dir
, pathname
, dtype_p
);
877 return exclude
->flags
& EXC_FLAG_NEGATIVE
? 0 : 1;
881 static struct dir_entry
*dir_entry_new(const char *pathname
, int len
)
883 struct dir_entry
*ent
;
885 ent
= xmalloc(sizeof(*ent
) + len
+ 1);
887 memcpy(ent
->name
, pathname
, len
);
892 static struct dir_entry
*dir_add_name(struct dir_struct
*dir
, const char *pathname
, int len
)
894 if (cache_file_exists(pathname
, len
, ignore_case
))
897 ALLOC_GROW(dir
->entries
, dir
->nr
+1, dir
->alloc
);
898 return dir
->entries
[dir
->nr
++] = dir_entry_new(pathname
, len
);
901 struct dir_entry
*dir_add_ignored(struct dir_struct
*dir
, const char *pathname
, int len
)
903 if (!cache_name_is_other(pathname
, len
))
906 ALLOC_GROW(dir
->ignored
, dir
->ignored_nr
+1, dir
->ignored_alloc
);
907 return dir
->ignored
[dir
->ignored_nr
++] = dir_entry_new(pathname
, len
);
911 index_nonexistent
= 0,
917 * Do not use the alphabetically sorted index to look up
918 * the directory name; instead, use the case insensitive
921 static enum exist_status
directory_exists_in_index_icase(const char *dirname
, int len
)
923 const struct cache_entry
*ce
= cache_dir_exists(dirname
, len
);
924 unsigned char endchar
;
927 return index_nonexistent
;
928 endchar
= ce
->name
[len
];
931 * The cache_entry structure returned will contain this dirname
932 * and possibly additional path components.
935 return index_directory
;
938 * If there are no additional path components, then this cache_entry
939 * represents a submodule. Submodules, despite being directories,
940 * are stored in the cache without a closing slash.
942 if (!endchar
&& S_ISGITLINK(ce
->ce_mode
))
945 /* This should never be hit, but it exists just in case. */
946 return index_nonexistent
;
950 * The index sorts alphabetically by entry name, which
951 * means that a gitlink sorts as '\0' at the end, while
952 * a directory (which is defined not as an entry, but as
953 * the files it contains) will sort with the '/' at the
956 static enum exist_status
directory_exists_in_index(const char *dirname
, int len
)
961 return directory_exists_in_index_icase(dirname
, len
);
963 pos
= cache_name_pos(dirname
, len
);
966 while (pos
< active_nr
) {
967 const struct cache_entry
*ce
= active_cache
[pos
++];
968 unsigned char endchar
;
970 if (strncmp(ce
->name
, dirname
, len
))
972 endchar
= ce
->name
[len
];
976 return index_directory
;
977 if (!endchar
&& S_ISGITLINK(ce
->ce_mode
))
980 return index_nonexistent
;
984 * When we find a directory when traversing the filesystem, we
985 * have three distinct cases:
988 * - see it as a directory
991 * and which one we choose depends on a combination of existing
992 * git index contents and the flags passed into the directory
995 * Case 1: If we *already* have entries in the index under that
996 * directory name, we always recurse into the directory to see
999 * Case 2: If we *already* have that directory name as a gitlink,
1000 * we always continue to see it as a gitlink, regardless of whether
1001 * there is an actual git directory there or not (it might not
1002 * be checked out as a subproject!)
1004 * Case 3: if we didn't have it in the index previously, we
1005 * have a few sub-cases:
1007 * (a) if "show_other_directories" is true, we show it as
1008 * just a directory, unless "hide_empty_directories" is
1009 * also true, in which case we need to check if it contains any
1010 * untracked and / or ignored files.
1011 * (b) if it looks like a git directory, and we don't have
1012 * 'no_gitlinks' set we treat it as a gitlink, and show it
1014 * (c) otherwise, we recurse into it.
1016 static enum path_treatment
treat_directory(struct dir_struct
*dir
,
1017 const char *dirname
, int len
, int exclude
,
1018 const struct path_simplify
*simplify
)
1020 /* The "len-1" is to strip the final '/' */
1021 switch (directory_exists_in_index(dirname
, len
-1)) {
1022 case index_directory
:
1023 return path_recurse
;
1028 case index_nonexistent
:
1029 if (dir
->flags
& DIR_SHOW_OTHER_DIRECTORIES
)
1031 if (!(dir
->flags
& DIR_NO_GITLINKS
)) {
1032 unsigned char sha1
[20];
1033 if (resolve_gitlink_ref(dirname
, "HEAD", sha1
) == 0)
1034 return path_untracked
;
1036 return path_recurse
;
1039 /* This is the "show_other_directories" case */
1041 if (!(dir
->flags
& DIR_HIDE_EMPTY_DIRECTORIES
))
1042 return exclude
? path_excluded
: path_untracked
;
1044 return read_directory_recursive(dir
, dirname
, len
, 1, simplify
);
1048 * This is an inexact early pruning of any recursive directory
1049 * reading - if the path cannot possibly be in the pathspec,
1050 * return true, and we'll skip it early.
1052 static int simplify_away(const char *path
, int pathlen
, const struct path_simplify
*simplify
)
1056 const char *match
= simplify
->path
;
1057 int len
= simplify
->len
;
1063 if (!memcmp(path
, match
, len
))
1073 * This function tells us whether an excluded path matches a
1074 * list of "interesting" pathspecs. That is, whether a path matched
1075 * by any of the pathspecs could possibly be ignored by excluding
1076 * the specified path. This can happen if:
1078 * 1. the path is mentioned explicitly in the pathspec
1080 * 2. the path is a directory prefix of some element in the
1083 static int exclude_matches_pathspec(const char *path
, int len
,
1084 const struct path_simplify
*simplify
)
1087 for (; simplify
->path
; simplify
++) {
1088 if (len
== simplify
->len
1089 && !memcmp(path
, simplify
->path
, len
))
1091 if (len
< simplify
->len
1092 && simplify
->path
[len
] == '/'
1093 && !memcmp(path
, simplify
->path
, len
))
1100 static int get_index_dtype(const char *path
, int len
)
1103 const struct cache_entry
*ce
;
1105 ce
= cache_file_exists(path
, len
, 0);
1107 if (!ce_uptodate(ce
))
1109 if (S_ISGITLINK(ce
->ce_mode
))
1112 * Nobody actually cares about the
1113 * difference between DT_LNK and DT_REG
1118 /* Try to look it up as a directory */
1119 pos
= cache_name_pos(path
, len
);
1123 while (pos
< active_nr
) {
1124 ce
= active_cache
[pos
++];
1125 if (strncmp(ce
->name
, path
, len
))
1127 if (ce
->name
[len
] > '/')
1129 if (ce
->name
[len
] < '/')
1131 if (!ce_uptodate(ce
))
1132 break; /* continue? */
1138 static int get_dtype(struct dirent
*de
, const char *path
, int len
)
1140 int dtype
= de
? DTYPE(de
) : DT_UNKNOWN
;
1143 if (dtype
!= DT_UNKNOWN
)
1145 dtype
= get_index_dtype(path
, len
);
1146 if (dtype
!= DT_UNKNOWN
)
1148 if (lstat(path
, &st
))
1150 if (S_ISREG(st
.st_mode
))
1152 if (S_ISDIR(st
.st_mode
))
1154 if (S_ISLNK(st
.st_mode
))
1159 static enum path_treatment
treat_one_path(struct dir_struct
*dir
,
1160 struct strbuf
*path
,
1161 const struct path_simplify
*simplify
,
1162 int dtype
, struct dirent
*de
)
1165 int has_path_in_index
= !!cache_file_exists(path
->buf
, path
->len
, ignore_case
);
1167 if (dtype
== DT_UNKNOWN
)
1168 dtype
= get_dtype(de
, path
->buf
, path
->len
);
1170 /* Always exclude indexed files */
1171 if (dtype
!= DT_DIR
&& has_path_in_index
)
1175 * When we are looking at a directory P in the working tree,
1176 * there are three cases:
1178 * (1) P exists in the index. Everything inside the directory P in
1179 * the working tree needs to go when P is checked out from the
1182 * (2) P does not exist in the index, but there is P/Q in the index.
1183 * We know P will stay a directory when we check out the contents
1184 * of the index, but we do not know yet if there is a directory
1185 * P/Q in the working tree to be killed, so we need to recurse.
1187 * (3) P does not exist in the index, and there is no P/Q in the index
1188 * to require P to be a directory, either. Only in this case, we
1189 * know that everything inside P will not be killed without
1192 if ((dir
->flags
& DIR_COLLECT_KILLED_ONLY
) &&
1193 (dtype
== DT_DIR
) &&
1194 !has_path_in_index
&&
1195 (directory_exists_in_index(path
->buf
, path
->len
) == index_nonexistent
))
1198 exclude
= is_excluded(dir
, path
->buf
, &dtype
);
1201 * Excluded? If we don't explicitly want to show
1202 * ignored files, ignore it
1204 if (exclude
&& !(dir
->flags
& (DIR_SHOW_IGNORED
|DIR_SHOW_IGNORED_TOO
)))
1205 return path_excluded
;
1211 strbuf_addch(path
, '/');
1212 return treat_directory(dir
, path
->buf
, path
->len
, exclude
,
1216 return exclude
? path_excluded
: path_untracked
;
1220 static enum path_treatment
treat_path(struct dir_struct
*dir
,
1222 struct strbuf
*path
,
1224 const struct path_simplify
*simplify
)
1228 if (is_dot_or_dotdot(de
->d_name
) || !strcmp(de
->d_name
, ".git"))
1230 strbuf_setlen(path
, baselen
);
1231 strbuf_addstr(path
, de
->d_name
);
1232 if (simplify_away(path
->buf
, path
->len
, simplify
))
1236 return treat_one_path(dir
, path
, simplify
, dtype
, de
);
1240 * Read a directory tree. We currently ignore anything but
1241 * directories, regular files and symlinks. That's because git
1242 * doesn't handle them at all yet. Maybe that will change some
1245 * Also, we ignore the name ".git" (even if it is not a directory).
1246 * That likely will not change.
1248 * Returns the most significant path_treatment value encountered in the scan.
1250 static enum path_treatment
read_directory_recursive(struct dir_struct
*dir
,
1251 const char *base
, int baselen
,
1253 const struct path_simplify
*simplify
)
1256 enum path_treatment state
, subdir_state
, dir_state
= path_none
;
1258 struct strbuf path
= STRBUF_INIT
;
1260 strbuf_add(&path
, base
, baselen
);
1262 fdir
= opendir(path
.len
? path
.buf
: ".");
1266 while ((de
= readdir(fdir
)) != NULL
) {
1267 /* check how the file or directory should be treated */
1268 state
= treat_path(dir
, de
, &path
, baselen
, simplify
);
1269 if (state
> dir_state
)
1272 /* recurse into subdir if instructed by treat_path */
1273 if (state
== path_recurse
) {
1274 subdir_state
= read_directory_recursive(dir
, path
.buf
,
1275 path
.len
, check_only
, simplify
);
1276 if (subdir_state
> dir_state
)
1277 dir_state
= subdir_state
;
1281 /* abort early if maximum state has been reached */
1282 if (dir_state
== path_untracked
)
1284 /* skip the dir_add_* part */
1288 /* add the path to the appropriate result list */
1291 if (dir
->flags
& DIR_SHOW_IGNORED
)
1292 dir_add_name(dir
, path
.buf
, path
.len
);
1293 else if ((dir
->flags
& DIR_SHOW_IGNORED_TOO
) ||
1294 ((dir
->flags
& DIR_COLLECT_IGNORED
) &&
1295 exclude_matches_pathspec(path
.buf
, path
.len
,
1297 dir_add_ignored(dir
, path
.buf
, path
.len
);
1300 case path_untracked
:
1301 if (!(dir
->flags
& DIR_SHOW_IGNORED
))
1302 dir_add_name(dir
, path
.buf
, path
.len
);
1311 strbuf_release(&path
);
1316 static int cmp_name(const void *p1
, const void *p2
)
1318 const struct dir_entry
*e1
= *(const struct dir_entry
**)p1
;
1319 const struct dir_entry
*e2
= *(const struct dir_entry
**)p2
;
1321 return cache_name_compare(e1
->name
, e1
->len
,
1325 static struct path_simplify
*create_simplify(const char **pathspec
)
1328 struct path_simplify
*simplify
= NULL
;
1333 for (nr
= 0 ; ; nr
++) {
1336 alloc
= alloc_nr(alloc
);
1337 simplify
= xrealloc(simplify
, alloc
* sizeof(*simplify
));
1339 match
= *pathspec
++;
1342 simplify
[nr
].path
= match
;
1343 simplify
[nr
].len
= simple_length(match
);
1345 simplify
[nr
].path
= NULL
;
1346 simplify
[nr
].len
= 0;
1350 static void free_simplify(struct path_simplify
*simplify
)
1355 static int treat_leading_path(struct dir_struct
*dir
,
1356 const char *path
, int len
,
1357 const struct path_simplify
*simplify
)
1359 struct strbuf sb
= STRBUF_INIT
;
1360 int baselen
, rc
= 0;
1362 int old_flags
= dir
->flags
;
1364 while (len
&& path
[len
- 1] == '/')
1369 dir
->flags
&= ~DIR_SHOW_OTHER_DIRECTORIES
;
1371 cp
= path
+ baselen
+ !!baselen
;
1372 cp
= memchr(cp
, '/', path
+ len
- cp
);
1376 baselen
= cp
- path
;
1377 strbuf_setlen(&sb
, 0);
1378 strbuf_add(&sb
, path
, baselen
);
1379 if (!is_directory(sb
.buf
))
1381 if (simplify_away(sb
.buf
, sb
.len
, simplify
))
1383 if (treat_one_path(dir
, &sb
, simplify
,
1384 DT_DIR
, NULL
) == path_none
)
1385 break; /* do not recurse into it */
1386 if (len
<= baselen
) {
1388 break; /* finished checking */
1391 strbuf_release(&sb
);
1392 dir
->flags
= old_flags
;
1396 int read_directory(struct dir_struct
*dir
, const char *path
, int len
, const struct pathspec
*pathspec
)
1398 struct path_simplify
*simplify
;
1401 * Check out create_simplify()
1404 GUARD_PATHSPEC(pathspec
,
1412 if (has_symlink_leading_path(path
, len
))
1416 * exclude patterns are treated like positive ones in
1417 * create_simplify. Usually exclude patterns should be a
1418 * subset of positive ones, which has no impacts on
1419 * create_simplify().
1421 simplify
= create_simplify(pathspec
? pathspec
->_raw
: NULL
);
1422 if (!len
|| treat_leading_path(dir
, path
, len
, simplify
))
1423 read_directory_recursive(dir
, path
, len
, 0, simplify
);
1424 free_simplify(simplify
);
1425 qsort(dir
->entries
, dir
->nr
, sizeof(struct dir_entry
*), cmp_name
);
1426 qsort(dir
->ignored
, dir
->ignored_nr
, sizeof(struct dir_entry
*), cmp_name
);
1430 int file_exists(const char *f
)
1433 return lstat(f
, &sb
) == 0;
1437 * Given two normalized paths (a trailing slash is ok), if subdir is
1438 * outside dir, return -1. Otherwise return the offset in subdir that
1439 * can be used as relative path to dir.
1441 int dir_inside_of(const char *subdir
, const char *dir
)
1445 assert(dir
&& subdir
&& *dir
&& *subdir
);
1447 while (*dir
&& *subdir
&& *dir
== *subdir
) {
1453 /* hel[p]/me vs hel[l]/yeah */
1454 if (*dir
&& *subdir
)
1458 return !*dir
? offset
: -1; /* same dir */
1460 /* foo/[b]ar vs foo/[] */
1461 if (is_dir_sep(dir
[-1]))
1462 return is_dir_sep(subdir
[-1]) ? offset
: -1;
1464 /* foo[/]bar vs foo[] */
1465 return is_dir_sep(*subdir
) ? offset
+ 1 : -1;
1468 int is_inside_dir(const char *dir
)
1473 if (!getcwd(cwd
, sizeof(cwd
)))
1474 die_errno("can't find the current directory");
1475 return dir_inside_of(cwd
, dir
) >= 0;
1478 int is_empty_dir(const char *path
)
1480 DIR *dir
= opendir(path
);
1487 while ((e
= readdir(dir
)) != NULL
)
1488 if (!is_dot_or_dotdot(e
->d_name
)) {
1497 static int remove_dir_recurse(struct strbuf
*path
, int flag
, int *kept_up
)
1501 int ret
= 0, original_len
= path
->len
, len
, kept_down
= 0;
1502 int only_empty
= (flag
& REMOVE_DIR_EMPTY_ONLY
);
1503 int keep_toplevel
= (flag
& REMOVE_DIR_KEEP_TOPLEVEL
);
1504 unsigned char submodule_head
[20];
1506 if ((flag
& REMOVE_DIR_KEEP_NESTED_GIT
) &&
1507 !resolve_gitlink_ref(path
->buf
, "HEAD", submodule_head
)) {
1508 /* Do not descend and nuke a nested git work tree. */
1514 flag
&= ~REMOVE_DIR_KEEP_TOPLEVEL
;
1515 dir
= opendir(path
->buf
);
1517 if (errno
== ENOENT
)
1518 return keep_toplevel
? -1 : 0;
1519 else if (errno
== EACCES
&& !keep_toplevel
)
1521 * An empty dir could be removable even if it
1524 return rmdir(path
->buf
);
1528 if (path
->buf
[original_len
- 1] != '/')
1529 strbuf_addch(path
, '/');
1532 while ((e
= readdir(dir
)) != NULL
) {
1534 if (is_dot_or_dotdot(e
->d_name
))
1537 strbuf_setlen(path
, len
);
1538 strbuf_addstr(path
, e
->d_name
);
1539 if (lstat(path
->buf
, &st
)) {
1540 if (errno
== ENOENT
)
1542 * file disappeared, which is what we
1547 } else if (S_ISDIR(st
.st_mode
)) {
1548 if (!remove_dir_recurse(path
, flag
, &kept_down
))
1549 continue; /* happy */
1550 } else if (!only_empty
&&
1551 (!unlink(path
->buf
) || errno
== ENOENT
)) {
1552 continue; /* happy, too */
1555 /* path too long, stat fails, or non-directory still exists */
1561 strbuf_setlen(path
, original_len
);
1562 if (!ret
&& !keep_toplevel
&& !kept_down
)
1563 ret
= (!rmdir(path
->buf
) || errno
== ENOENT
) ? 0 : -1;
1566 * report the uplevel that it is not an error that we
1567 * did not rmdir() our directory.
1573 int remove_dir_recursively(struct strbuf
*path
, int flag
)
1575 return remove_dir_recurse(path
, flag
, NULL
);
1578 void setup_standard_excludes(struct dir_struct
*dir
)
1583 dir
->exclude_per_dir
= ".gitignore";
1584 path
= git_path("info/exclude");
1585 if (!excludes_file
) {
1586 home_config_paths(NULL
, &xdg_path
, "ignore");
1587 excludes_file
= xdg_path
;
1589 if (!access_or_warn(path
, R_OK
, 0))
1590 add_excludes_from_file(dir
, path
);
1591 if (excludes_file
&& !access_or_warn(excludes_file
, R_OK
, 0))
1592 add_excludes_from_file(dir
, excludes_file
);
1595 int remove_path(const char *name
)
1599 if (unlink(name
) && errno
!= ENOENT
&& errno
!= ENOTDIR
)
1602 slash
= strrchr(name
, '/');
1604 char *dirs
= xstrdup(name
);
1605 slash
= dirs
+ (slash
- name
);
1608 } while (rmdir(dirs
) == 0 && (slash
= strrchr(dirs
, '/')));
1615 * Frees memory within dir which was allocated for exclude lists and
1616 * the exclude_stack. Does not free dir itself.
1618 void clear_directory(struct dir_struct
*dir
)
1621 struct exclude_list_group
*group
;
1622 struct exclude_list
*el
;
1623 struct exclude_stack
*stk
;
1625 for (i
= EXC_CMDL
; i
<= EXC_FILE
; i
++) {
1626 group
= &dir
->exclude_list_group
[i
];
1627 for (j
= 0; j
< group
->nr
; j
++) {
1630 free((char *)el
->src
);
1631 clear_exclude_list(el
);
1636 stk
= dir
->exclude_stack
;
1638 struct exclude_stack
*prev
= stk
->prev
;