1/* 2 * This handles recursive filename detection with exclude 3 * files, index knowledge etc.. 4 * 5 * See Documentation/technical/api-directory-listing.txt 6 * 7 * Copyright (C) Linus Torvalds, 2005-2006 8 * Junio Hamano, 2005-2006 9 */ 10#include"cache.h" 11#include"dir.h" 12#include"refs.h" 13#include"wildmatch.h" 14#include"pathspec.h" 15 16struct path_simplify { 17int len; 18const char*path; 19}; 20 21/* 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. 26 */ 27enum path_treatment { 28 path_none =0, 29 path_recurse, 30 path_excluded, 31 path_untracked 32}; 33 34/* 35 * Support data structure for our opendir/readdir/closedir wrappers 36 */ 37struct cached_dir { 38DIR*fdir; 39struct untracked_cache_dir *untracked; 40int nr_files; 41int nr_dirs; 42 43struct dirent *de; 44const char*file; 45struct untracked_cache_dir *ucd; 46}; 47 48static enum path_treatment read_directory_recursive(struct dir_struct *dir, 49const char*path,int len,struct untracked_cache_dir *untracked, 50int check_only,const struct path_simplify *simplify); 51static intget_dtype(struct dirent *de,const char*path,int len); 52 53/* helper string functions with support for the ignore_case flag */ 54intstrcmp_icase(const char*a,const char*b) 55{ 56return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 57} 58 59intstrncmp_icase(const char*a,const char*b,size_t count) 60{ 61return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 62} 63 64intfnmatch_icase(const char*pattern,const char*string,int flags) 65{ 66returnwildmatch(pattern, string, 67 flags | (ignore_case ? WM_CASEFOLD :0), 68 NULL); 69} 70 71intgit_fnmatch(const struct pathspec_item *item, 72const char*pattern,const char*string, 73int prefix) 74{ 75if(prefix >0) { 76if(ps_strncmp(item, pattern, string, prefix)) 77return WM_NOMATCH; 78 pattern += prefix; 79 string += prefix; 80} 81if(item->flags & PATHSPEC_ONESTAR) { 82int pattern_len =strlen(++pattern); 83int string_len =strlen(string); 84return string_len < pattern_len || 85ps_strcmp(item, pattern, 86 string + string_len - pattern_len); 87} 88if(item->magic & PATHSPEC_GLOB) 89returnwildmatch(pattern, string, 90 WM_PATHNAME | 91(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 92 NULL); 93else 94/* wildmatch has not learned no FNM_PATHNAME mode yet */ 95returnwildmatch(pattern, string, 96 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 97 NULL); 98} 99 100static intfnmatch_icase_mem(const char*pattern,int patternlen, 101const char*string,int stringlen, 102int flags) 103{ 104int match_status; 105struct strbuf pat_buf = STRBUF_INIT; 106struct strbuf str_buf = STRBUF_INIT; 107const char*use_pat = pattern; 108const char*use_str = string; 109 110if(pattern[patternlen]) { 111strbuf_add(&pat_buf, pattern, patternlen); 112 use_pat = pat_buf.buf; 113} 114if(string[stringlen]) { 115strbuf_add(&str_buf, string, stringlen); 116 use_str = str_buf.buf; 117} 118 119if(ignore_case) 120 flags |= WM_CASEFOLD; 121 match_status =wildmatch(use_pat, use_str, flags, NULL); 122 123strbuf_release(&pat_buf); 124strbuf_release(&str_buf); 125 126return match_status; 127} 128 129static size_tcommon_prefix_len(const struct pathspec *pathspec) 130{ 131int n; 132size_t max =0; 133 134/* 135 * ":(icase)path" is treated as a pathspec full of 136 * wildcard. In other words, only prefix is considered common 137 * prefix. If the pathspec is abc/foo abc/bar, running in 138 * subdir xyz, the common prefix is still xyz, not xuz/abc as 139 * in non-:(icase). 140 */ 141GUARD_PATHSPEC(pathspec, 142 PATHSPEC_FROMTOP | 143 PATHSPEC_MAXDEPTH | 144 PATHSPEC_LITERAL | 145 PATHSPEC_GLOB | 146 PATHSPEC_ICASE | 147 PATHSPEC_EXCLUDE); 148 149for(n =0; n < pathspec->nr; n++) { 150size_t i =0, len =0, item_len; 151if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 152continue; 153if(pathspec->items[n].magic & PATHSPEC_ICASE) 154 item_len = pathspec->items[n].prefix; 155else 156 item_len = pathspec->items[n].nowildcard_len; 157while(i < item_len && (n ==0|| i < max)) { 158char c = pathspec->items[n].match[i]; 159if(c != pathspec->items[0].match[i]) 160break; 161if(c =='/') 162 len = i +1; 163 i++; 164} 165if(n ==0|| len < max) { 166 max = len; 167if(!max) 168break; 169} 170} 171return max; 172} 173 174/* 175 * Returns a copy of the longest leading path common among all 176 * pathspecs. 177 */ 178char*common_prefix(const struct pathspec *pathspec) 179{ 180unsigned long len =common_prefix_len(pathspec); 181 182return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 183} 184 185intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 186{ 187size_t len; 188 189/* 190 * Calculate common prefix for the pathspec, and 191 * use that to optimize the directory walk 192 */ 193 len =common_prefix_len(pathspec); 194 195/* Read the directory and prune it */ 196read_directory(dir, pathspec->nr ? pathspec->_raw[0] :"", len, pathspec); 197return len; 198} 199 200intwithin_depth(const char*name,int namelen, 201int depth,int max_depth) 202{ 203const char*cp = name, *cpe = name + namelen; 204 205while(cp < cpe) { 206if(*cp++ !='/') 207continue; 208 depth++; 209if(depth > max_depth) 210return0; 211} 212return1; 213} 214 215#define DO_MATCH_EXCLUDE 1 216#define DO_MATCH_DIRECTORY 2 217 218/* 219 * Does 'match' match the given name? 220 * A match is found if 221 * 222 * (1) the 'match' string is leading directory of 'name', or 223 * (2) the 'match' string is a wildcard and matches 'name', or 224 * (3) the 'match' string is exactly the same as 'name'. 225 * 226 * and the return value tells which case it was. 227 * 228 * It returns 0 when there is no match. 229 */ 230static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 231const char*name,int namelen,unsigned flags) 232{ 233/* name/namelen has prefix cut off by caller */ 234const char*match = item->match + prefix; 235int matchlen = item->len - prefix; 236 237/* 238 * The normal call pattern is: 239 * 1. prefix = common_prefix_len(ps); 240 * 2. prune something, or fill_directory 241 * 3. match_pathspec() 242 * 243 * 'prefix' at #1 may be shorter than the command's prefix and 244 * it's ok for #2 to match extra files. Those extras will be 245 * trimmed at #3. 246 * 247 * Suppose the pathspec is 'foo' and '../bar' running from 248 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 249 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 250 * user does not want XYZ/foo, only the "foo" part should be 251 * case-insensitive. We need to filter out XYZ/foo here. In 252 * other words, we do not trust the caller on comparing the 253 * prefix part when :(icase) is involved. We do exact 254 * comparison ourselves. 255 * 256 * Normally the caller (common_prefix_len() in fact) does 257 * _exact_ matching on name[-prefix+1..-1] and we do not need 258 * to check that part. Be defensive and check it anyway, in 259 * case common_prefix_len is changed, or a new caller is 260 * introduced that does not use common_prefix_len. 261 * 262 * If the penalty turns out too high when prefix is really 263 * long, maybe change it to 264 * strncmp(match, name, item->prefix - prefix) 265 */ 266if(item->prefix && (item->magic & PATHSPEC_ICASE) && 267strncmp(item->match, name - prefix, item->prefix)) 268return0; 269 270/* If the match was just the prefix, we matched */ 271if(!*match) 272return MATCHED_RECURSIVELY; 273 274if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 275if(matchlen == namelen) 276return MATCHED_EXACTLY; 277 278if(match[matchlen-1] =='/'|| name[matchlen] =='/') 279return MATCHED_RECURSIVELY; 280}else if((flags & DO_MATCH_DIRECTORY) && 281 match[matchlen -1] =='/'&& 282 namelen == matchlen -1&& 283!ps_strncmp(item, match, name, namelen)) 284return MATCHED_EXACTLY; 285 286if(item->nowildcard_len < item->len && 287!git_fnmatch(item, match, name, 288 item->nowildcard_len - prefix)) 289return MATCHED_FNMATCH; 290 291return0; 292} 293 294/* 295 * Given a name and a list of pathspecs, returns the nature of the 296 * closest (i.e. most specific) match of the name to any of the 297 * pathspecs. 298 * 299 * The caller typically calls this multiple times with the same 300 * pathspec and seen[] array but with different name/namelen 301 * (e.g. entries from the index) and is interested in seeing if and 302 * how each pathspec matches all the names it calls this function 303 * with. A mark is left in the seen[] array for each pathspec element 304 * indicating the closest type of match that element achieved, so if 305 * seen[n] remains zero after multiple invocations, that means the nth 306 * pathspec did not match any names, which could indicate that the 307 * user mistyped the nth pathspec. 308 */ 309static intdo_match_pathspec(const struct pathspec *ps, 310const char*name,int namelen, 311int prefix,char*seen, 312unsigned flags) 313{ 314int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 315 316GUARD_PATHSPEC(ps, 317 PATHSPEC_FROMTOP | 318 PATHSPEC_MAXDEPTH | 319 PATHSPEC_LITERAL | 320 PATHSPEC_GLOB | 321 PATHSPEC_ICASE | 322 PATHSPEC_EXCLUDE); 323 324if(!ps->nr) { 325if(!ps->recursive || 326!(ps->magic & PATHSPEC_MAXDEPTH) || 327 ps->max_depth == -1) 328return MATCHED_RECURSIVELY; 329 330if(within_depth(name, namelen,0, ps->max_depth)) 331return MATCHED_EXACTLY; 332else 333return0; 334} 335 336 name += prefix; 337 namelen -= prefix; 338 339for(i = ps->nr -1; i >=0; i--) { 340int how; 341 342if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 343( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 344continue; 345 346if(seen && seen[i] == MATCHED_EXACTLY) 347continue; 348/* 349 * Make exclude patterns optional and never report 350 * "pathspec ':(exclude)foo' matches no files" 351 */ 352if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 353 seen[i] = MATCHED_FNMATCH; 354 how =match_pathspec_item(ps->items+i, prefix, name, 355 namelen, flags); 356if(ps->recursive && 357(ps->magic & PATHSPEC_MAXDEPTH) && 358 ps->max_depth != -1&& 359 how && how != MATCHED_FNMATCH) { 360int len = ps->items[i].len; 361if(name[len] =='/') 362 len++; 363if(within_depth(name+len, namelen-len,0, ps->max_depth)) 364 how = MATCHED_EXACTLY; 365else 366 how =0; 367} 368if(how) { 369if(retval < how) 370 retval = how; 371if(seen && seen[i] < how) 372 seen[i] = how; 373} 374} 375return retval; 376} 377 378intmatch_pathspec(const struct pathspec *ps, 379const char*name,int namelen, 380int prefix,char*seen,int is_dir) 381{ 382int positive, negative; 383unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 384 positive =do_match_pathspec(ps, name, namelen, 385 prefix, seen, flags); 386if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 387return positive; 388 negative =do_match_pathspec(ps, name, namelen, 389 prefix, seen, 390 flags | DO_MATCH_EXCLUDE); 391return negative ?0: positive; 392} 393 394/* 395 * Return the length of the "simple" part of a path match limiter. 396 */ 397intsimple_length(const char*match) 398{ 399int len = -1; 400 401for(;;) { 402unsigned char c = *match++; 403 len++; 404if(c =='\0'||is_glob_special(c)) 405return len; 406} 407} 408 409intno_wildcard(const char*string) 410{ 411return string[simple_length(string)] =='\0'; 412} 413 414voidparse_exclude_pattern(const char**pattern, 415int*patternlen, 416int*flags, 417int*nowildcardlen) 418{ 419const char*p = *pattern; 420size_t i, len; 421 422*flags =0; 423if(*p =='!') { 424*flags |= EXC_FLAG_NEGATIVE; 425 p++; 426} 427 len =strlen(p); 428if(len && p[len -1] =='/') { 429 len--; 430*flags |= EXC_FLAG_MUSTBEDIR; 431} 432for(i =0; i < len; i++) { 433if(p[i] =='/') 434break; 435} 436if(i == len) 437*flags |= EXC_FLAG_NODIR; 438*nowildcardlen =simple_length(p); 439/* 440 * we should have excluded the trailing slash from 'p' too, 441 * but that's one more allocation. Instead just make sure 442 * nowildcardlen does not exceed real patternlen 443 */ 444if(*nowildcardlen > len) 445*nowildcardlen = len; 446if(*p =='*'&&no_wildcard(p +1)) 447*flags |= EXC_FLAG_ENDSWITH; 448*pattern = p; 449*patternlen = len; 450} 451 452voidadd_exclude(const char*string,const char*base, 453int baselen,struct exclude_list *el,int srcpos) 454{ 455struct exclude *x; 456int patternlen; 457int flags; 458int nowildcardlen; 459 460parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 461if(flags & EXC_FLAG_MUSTBEDIR) { 462char*s; 463 x =xmalloc(sizeof(*x) + patternlen +1); 464 s = (char*)(x+1); 465memcpy(s, string, patternlen); 466 s[patternlen] ='\0'; 467 x->pattern = s; 468}else{ 469 x =xmalloc(sizeof(*x)); 470 x->pattern = string; 471} 472 x->patternlen = patternlen; 473 x->nowildcardlen = nowildcardlen; 474 x->base = base; 475 x->baselen = baselen; 476 x->flags = flags; 477 x->srcpos = srcpos; 478ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 479 el->excludes[el->nr++] = x; 480 x->el = el; 481} 482 483static void*read_skip_worktree_file_from_index(const char*path,size_t*size, 484struct sha1_stat *sha1_stat) 485{ 486int pos, len; 487unsigned long sz; 488enum object_type type; 489void*data; 490 491 len =strlen(path); 492 pos =cache_name_pos(path, len); 493if(pos <0) 494return NULL; 495if(!ce_skip_worktree(active_cache[pos])) 496return NULL; 497 data =read_sha1_file(active_cache[pos]->sha1, &type, &sz); 498if(!data || type != OBJ_BLOB) { 499free(data); 500return NULL; 501} 502*size =xsize_t(sz); 503if(sha1_stat) { 504memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 505hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 506} 507return data; 508} 509 510/* 511 * Frees memory within el which was allocated for exclude patterns and 512 * the file buffer. Does not free el itself. 513 */ 514voidclear_exclude_list(struct exclude_list *el) 515{ 516int i; 517 518for(i =0; i < el->nr; i++) 519free(el->excludes[i]); 520free(el->excludes); 521free(el->filebuf); 522 523 el->nr =0; 524 el->excludes = NULL; 525 el->filebuf = NULL; 526} 527 528static voidtrim_trailing_spaces(char*buf) 529{ 530char*p, *last_space = NULL; 531 532for(p = buf; *p; p++) 533switch(*p) { 534case' ': 535if(!last_space) 536 last_space = p; 537break; 538case'\\': 539 p++; 540if(!*p) 541return; 542/* fallthrough */ 543default: 544 last_space = NULL; 545} 546 547if(last_space) 548*last_space ='\0'; 549} 550 551/* 552 * Given a subdirectory name and "dir" of the current directory, 553 * search the subdir in "dir" and return it, or create a new one if it 554 * does not exist in "dir". 555 * 556 * If "name" has the trailing slash, it'll be excluded in the search. 557 */ 558static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 559struct untracked_cache_dir *dir, 560const char*name,int len) 561{ 562int first, last; 563struct untracked_cache_dir *d; 564if(!dir) 565return NULL; 566if(len && name[len -1] =='/') 567 len--; 568 first =0; 569 last = dir->dirs_nr; 570while(last > first) { 571int cmp, next = (last + first) >>1; 572 d = dir->dirs[next]; 573 cmp =strncmp(name, d->name, len); 574if(!cmp &&strlen(d->name) > len) 575 cmp = -1; 576if(!cmp) 577return d; 578if(cmp <0) { 579 last = next; 580continue; 581} 582 first = next+1; 583} 584 585 uc->dir_created++; 586 d =xmalloc(sizeof(*d) + len +1); 587memset(d,0,sizeof(*d)); 588memcpy(d->name, name, len); 589 d->name[len] ='\0'; 590 591ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 592memmove(dir->dirs + first +1, dir->dirs + first, 593(dir->dirs_nr - first) *sizeof(*dir->dirs)); 594 dir->dirs_nr++; 595 dir->dirs[first] = d; 596return d; 597} 598 599static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 600{ 601int i; 602 dir->valid =0; 603 dir->untracked_nr =0; 604for(i =0; i < dir->dirs_nr; i++) 605do_invalidate_gitignore(dir->dirs[i]); 606} 607 608static voidinvalidate_gitignore(struct untracked_cache *uc, 609struct untracked_cache_dir *dir) 610{ 611 uc->gitignore_invalidated++; 612do_invalidate_gitignore(dir); 613} 614 615static voidinvalidate_directory(struct untracked_cache *uc, 616struct untracked_cache_dir *dir) 617{ 618 uc->dir_invalidated++; 619 dir->valid =0; 620 dir->untracked_nr =0; 621} 622 623/* 624 * Given a file with name "fname", read it (either from disk, or from 625 * the index if "check_index" is non-zero), parse it and store the 626 * exclude rules in "el". 627 * 628 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 629 * stat data from disk (only valid if add_excludes returns zero). If 630 * ss_valid is non-zero, "ss" must contain good value as input. 631 */ 632static intadd_excludes(const char*fname,const char*base,int baselen, 633struct exclude_list *el,int check_index, 634struct sha1_stat *sha1_stat) 635{ 636struct stat st; 637int fd, i, lineno =1; 638size_t size =0; 639char*buf, *entry; 640 641 fd =open(fname, O_RDONLY); 642if(fd <0||fstat(fd, &st) <0) { 643if(errno != ENOENT) 644warn_on_inaccessible(fname); 645if(0<= fd) 646close(fd); 647if(!check_index || 648(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 649return-1; 650if(size ==0) { 651free(buf); 652return0; 653} 654if(buf[size-1] !='\n') { 655 buf =xrealloc(buf, size+1); 656 buf[size++] ='\n'; 657} 658}else{ 659 size =xsize_t(st.st_size); 660if(size ==0) { 661if(sha1_stat) { 662fill_stat_data(&sha1_stat->stat, &st); 663hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 664 sha1_stat->valid =1; 665} 666close(fd); 667return0; 668} 669 buf =xmalloc(size+1); 670if(read_in_full(fd, buf, size) != size) { 671free(buf); 672close(fd); 673return-1; 674} 675 buf[size++] ='\n'; 676close(fd); 677if(sha1_stat) { 678int pos; 679if(sha1_stat->valid && 680!match_stat_data(&sha1_stat->stat, &st)) 681;/* no content change, ss->sha1 still good */ 682else if(check_index && 683(pos =cache_name_pos(fname,strlen(fname))) >=0&& 684!ce_stage(active_cache[pos]) && 685ce_uptodate(active_cache[pos]) && 686!would_convert_to_git(fname)) 687hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 688else 689hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 690fill_stat_data(&sha1_stat->stat, &st); 691 sha1_stat->valid =1; 692} 693} 694 695 el->filebuf = buf; 696 entry = buf; 697for(i =0; i < size; i++) { 698if(buf[i] =='\n') { 699if(entry != buf + i && entry[0] !='#') { 700 buf[i - (i && buf[i-1] =='\r')] =0; 701trim_trailing_spaces(entry); 702add_exclude(entry, base, baselen, el, lineno); 703} 704 lineno++; 705 entry = buf + i +1; 706} 707} 708return0; 709} 710 711intadd_excludes_from_file_to_list(const char*fname,const char*base, 712int baselen,struct exclude_list *el, 713int check_index) 714{ 715returnadd_excludes(fname, base, baselen, el, check_index, NULL); 716} 717 718struct exclude_list *add_exclude_list(struct dir_struct *dir, 719int group_type,const char*src) 720{ 721struct exclude_list *el; 722struct exclude_list_group *group; 723 724 group = &dir->exclude_list_group[group_type]; 725ALLOC_GROW(group->el, group->nr +1, group->alloc); 726 el = &group->el[group->nr++]; 727memset(el,0,sizeof(*el)); 728 el->src = src; 729return el; 730} 731 732/* 733 * Used to set up core.excludesfile and .git/info/exclude lists. 734 */ 735static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 736struct sha1_stat *sha1_stat) 737{ 738struct exclude_list *el; 739/* 740 * catch setup_standard_excludes() that's called before 741 * dir->untracked is assigned. That function behaves 742 * differently when dir->untracked is non-NULL. 743 */ 744if(!dir->untracked) 745 dir->unmanaged_exclude_files++; 746 el =add_exclude_list(dir, EXC_FILE, fname); 747if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 748die("cannot use%sas an exclude file", fname); 749} 750 751voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 752{ 753 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 754add_excludes_from_file_1(dir, fname, NULL); 755} 756 757intmatch_basename(const char*basename,int basenamelen, 758const char*pattern,int prefix,int patternlen, 759int flags) 760{ 761if(prefix == patternlen) { 762if(patternlen == basenamelen && 763!strncmp_icase(pattern, basename, basenamelen)) 764return1; 765}else if(flags & EXC_FLAG_ENDSWITH) { 766/* "*literal" matching against "fooliteral" */ 767if(patternlen -1<= basenamelen && 768!strncmp_icase(pattern +1, 769 basename + basenamelen - (patternlen -1), 770 patternlen -1)) 771return1; 772}else{ 773if(fnmatch_icase_mem(pattern, patternlen, 774 basename, basenamelen, 7750) ==0) 776return1; 777} 778return0; 779} 780 781intmatch_pathname(const char*pathname,int pathlen, 782const char*base,int baselen, 783const char*pattern,int prefix,int patternlen, 784int flags) 785{ 786const char*name; 787int namelen; 788 789/* 790 * match with FNM_PATHNAME; the pattern has base implicitly 791 * in front of it. 792 */ 793if(*pattern =='/') { 794 pattern++; 795 patternlen--; 796 prefix--; 797} 798 799/* 800 * baselen does not count the trailing slash. base[] may or 801 * may not end with a trailing slash though. 802 */ 803if(pathlen < baselen +1|| 804(baselen && pathname[baselen] !='/') || 805strncmp_icase(pathname, base, baselen)) 806return0; 807 808 namelen = baselen ? pathlen - baselen -1: pathlen; 809 name = pathname + pathlen - namelen; 810 811if(prefix) { 812/* 813 * if the non-wildcard part is longer than the 814 * remaining pathname, surely it cannot match. 815 */ 816if(prefix > namelen) 817return0; 818 819if(strncmp_icase(pattern, name, prefix)) 820return0; 821 pattern += prefix; 822 patternlen -= prefix; 823 name += prefix; 824 namelen -= prefix; 825 826/* 827 * If the whole pattern did not have a wildcard, 828 * then our prefix match is all we need; we 829 * do not need to call fnmatch at all. 830 */ 831if(!patternlen && !namelen) 832return1; 833} 834 835returnfnmatch_icase_mem(pattern, patternlen, 836 name, namelen, 837 WM_PATHNAME) ==0; 838} 839 840/* 841 * Scan the given exclude list in reverse to see whether pathname 842 * should be ignored. The first match (i.e. the last on the list), if 843 * any, determines the fate. Returns the exclude_list element which 844 * matched, or NULL for undecided. 845 */ 846static struct exclude *last_exclude_matching_from_list(const char*pathname, 847int pathlen, 848const char*basename, 849int*dtype, 850struct exclude_list *el) 851{ 852int i; 853 854if(!el->nr) 855return NULL;/* undefined */ 856 857for(i = el->nr -1;0<= i; i--) { 858struct exclude *x = el->excludes[i]; 859const char*exclude = x->pattern; 860int prefix = x->nowildcardlen; 861 862if(x->flags & EXC_FLAG_MUSTBEDIR) { 863if(*dtype == DT_UNKNOWN) 864*dtype =get_dtype(NULL, pathname, pathlen); 865if(*dtype != DT_DIR) 866continue; 867} 868 869if(x->flags & EXC_FLAG_NODIR) { 870if(match_basename(basename, 871 pathlen - (basename - pathname), 872 exclude, prefix, x->patternlen, 873 x->flags)) 874return x; 875continue; 876} 877 878assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 879if(match_pathname(pathname, pathlen, 880 x->base, x->baselen ? x->baselen -1:0, 881 exclude, prefix, x->patternlen, x->flags)) 882return x; 883} 884return NULL;/* undecided */ 885} 886 887/* 888 * Scan the list and let the last match determine the fate. 889 * Return 1 for exclude, 0 for include and -1 for undecided. 890 */ 891intis_excluded_from_list(const char*pathname, 892int pathlen,const char*basename,int*dtype, 893struct exclude_list *el) 894{ 895struct exclude *exclude; 896 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 897if(exclude) 898return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 899return-1;/* undecided */ 900} 901 902static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 903const char*pathname,int pathlen,const char*basename, 904int*dtype_p) 905{ 906int i, j; 907struct exclude_list_group *group; 908struct exclude *exclude; 909for(i = EXC_CMDL; i <= EXC_FILE; i++) { 910 group = &dir->exclude_list_group[i]; 911for(j = group->nr -1; j >=0; j--) { 912 exclude =last_exclude_matching_from_list( 913 pathname, pathlen, basename, dtype_p, 914&group->el[j]); 915if(exclude) 916return exclude; 917} 918} 919return NULL; 920} 921 922/* 923 * Loads the per-directory exclude list for the substring of base 924 * which has a char length of baselen. 925 */ 926static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen) 927{ 928struct exclude_list_group *group; 929struct exclude_list *el; 930struct exclude_stack *stk = NULL; 931struct untracked_cache_dir *untracked; 932int current; 933 934 group = &dir->exclude_list_group[EXC_DIRS]; 935 936/* 937 * Pop the exclude lists from the EXCL_DIRS exclude_list_group 938 * which originate from directories not in the prefix of the 939 * path being checked. 940 */ 941while((stk = dir->exclude_stack) != NULL) { 942if(stk->baselen <= baselen && 943!strncmp(dir->basebuf.buf, base, stk->baselen)) 944break; 945 el = &group->el[dir->exclude_stack->exclude_ix]; 946 dir->exclude_stack = stk->prev; 947 dir->exclude = NULL; 948free((char*)el->src);/* see strbuf_detach() below */ 949clear_exclude_list(el); 950free(stk); 951 group->nr--; 952} 953 954/* Skip traversing into sub directories if the parent is excluded */ 955if(dir->exclude) 956return; 957 958/* 959 * Lazy initialization. All call sites currently just 960 * memset(dir, 0, sizeof(*dir)) before use. Changing all of 961 * them seems lots of work for little benefit. 962 */ 963if(!dir->basebuf.buf) 964strbuf_init(&dir->basebuf, PATH_MAX); 965 966/* Read from the parent directories and push them down. */ 967 current = stk ? stk->baselen : -1; 968strbuf_setlen(&dir->basebuf, current <0?0: current); 969if(dir->untracked) 970 untracked = stk ? stk->ucd : dir->untracked->root; 971else 972 untracked = NULL; 973 974while(current < baselen) { 975const char*cp; 976struct sha1_stat sha1_stat; 977 978 stk =xcalloc(1,sizeof(*stk)); 979if(current <0) { 980 cp = base; 981 current =0; 982}else{ 983 cp =strchr(base + current +1,'/'); 984if(!cp) 985die("oops in prep_exclude"); 986 cp++; 987 untracked = 988lookup_untracked(dir->untracked, untracked, 989 base + current, 990 cp - base - current); 991} 992 stk->prev = dir->exclude_stack; 993 stk->baselen = cp - base; 994 stk->exclude_ix = group->nr; 995 stk->ucd = untracked; 996 el =add_exclude_list(dir, EXC_DIRS, NULL); 997strbuf_add(&dir->basebuf, base + current, stk->baselen - current); 998assert(stk->baselen == dir->basebuf.len); 9991000/* Abort if the directory is excluded */1001if(stk->baselen) {1002int dt = DT_DIR;1003 dir->basebuf.buf[stk->baselen -1] =0;1004 dir->exclude =last_exclude_matching_from_lists(dir,1005 dir->basebuf.buf, stk->baselen -1,1006 dir->basebuf.buf + current, &dt);1007 dir->basebuf.buf[stk->baselen -1] ='/';1008if(dir->exclude &&1009 dir->exclude->flags & EXC_FLAG_NEGATIVE)1010 dir->exclude = NULL;1011if(dir->exclude) {1012 dir->exclude_stack = stk;1013return;1014}1015}10161017/* Try to read per-directory file */1018hashclr(sha1_stat.sha1);1019 sha1_stat.valid =0;1020if(dir->exclude_per_dir) {1021/*1022 * dir->basebuf gets reused by the traversal, but we1023 * need fname to remain unchanged to ensure the src1024 * member of each struct exclude correctly1025 * back-references its source file. Other invocations1026 * of add_exclude_list provide stable strings, so we1027 * strbuf_detach() and free() here in the caller.1028 */1029struct strbuf sb = STRBUF_INIT;1030strbuf_addbuf(&sb, &dir->basebuf);1031strbuf_addstr(&sb, dir->exclude_per_dir);1032 el->src =strbuf_detach(&sb, NULL);1033add_excludes(el->src, el->src, stk->baselen, el,1,1034 untracked ? &sha1_stat : NULL);1035}1036/*1037 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1038 * will first be called in valid_cached_dir() then maybe many1039 * times more in last_exclude_matching(). When the cache is1040 * used, last_exclude_matching() will not be called and1041 * reading .gitignore content will be a waste.1042 *1043 * So when it's called by valid_cached_dir() and we can get1044 * .gitignore SHA-1 from the index (i.e. .gitignore is not1045 * modified on work tree), we could delay reading the1046 * .gitignore content until we absolutely need it in1047 * last_exclude_matching(). Be careful about ignore rule1048 * order, though, if you do that.1049 */1050if(untracked &&1051hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1052invalidate_gitignore(dir->untracked, untracked);1053hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1054}1055 dir->exclude_stack = stk;1056 current = stk->baselen;1057}1058strbuf_setlen(&dir->basebuf, baselen);1059}10601061/*1062 * Loads the exclude lists for the directory containing pathname, then1063 * scans all exclude lists to determine whether pathname is excluded.1064 * Returns the exclude_list element which matched, or NULL for1065 * undecided.1066 */1067struct exclude *last_exclude_matching(struct dir_struct *dir,1068const char*pathname,1069int*dtype_p)1070{1071int pathlen =strlen(pathname);1072const char*basename =strrchr(pathname,'/');1073 basename = (basename) ? basename+1: pathname;10741075prep_exclude(dir, pathname, basename-pathname);10761077if(dir->exclude)1078return dir->exclude;10791080returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1081 basename, dtype_p);1082}10831084/*1085 * Loads the exclude lists for the directory containing pathname, then1086 * scans all exclude lists to determine whether pathname is excluded.1087 * Returns 1 if true, otherwise 0.1088 */1089intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1090{1091struct exclude *exclude =1092last_exclude_matching(dir, pathname, dtype_p);1093if(exclude)1094return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1095return0;1096}10971098static struct dir_entry *dir_entry_new(const char*pathname,int len)1099{1100struct dir_entry *ent;11011102 ent =xmalloc(sizeof(*ent) + len +1);1103 ent->len = len;1104memcpy(ent->name, pathname, len);1105 ent->name[len] =0;1106return ent;1107}11081109static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1110{1111if(cache_file_exists(pathname, len, ignore_case))1112return NULL;11131114ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1115return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1116}11171118struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1119{1120if(!cache_name_is_other(pathname, len))1121return NULL;11221123ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1124return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1125}11261127enum exist_status {1128 index_nonexistent =0,1129 index_directory,1130 index_gitdir1131};11321133/*1134 * Do not use the alphabetically sorted index to look up1135 * the directory name; instead, use the case insensitive1136 * directory hash.1137 */1138static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1139{1140const struct cache_entry *ce =cache_dir_exists(dirname, len);1141unsigned char endchar;11421143if(!ce)1144return index_nonexistent;1145 endchar = ce->name[len];11461147/*1148 * The cache_entry structure returned will contain this dirname1149 * and possibly additional path components.1150 */1151if(endchar =='/')1152return index_directory;11531154/*1155 * If there are no additional path components, then this cache_entry1156 * represents a submodule. Submodules, despite being directories,1157 * are stored in the cache without a closing slash.1158 */1159if(!endchar &&S_ISGITLINK(ce->ce_mode))1160return index_gitdir;11611162/* This should never be hit, but it exists just in case. */1163return index_nonexistent;1164}11651166/*1167 * The index sorts alphabetically by entry name, which1168 * means that a gitlink sorts as '\0' at the end, while1169 * a directory (which is defined not as an entry, but as1170 * the files it contains) will sort with the '/' at the1171 * end.1172 */1173static enum exist_status directory_exists_in_index(const char*dirname,int len)1174{1175int pos;11761177if(ignore_case)1178returndirectory_exists_in_index_icase(dirname, len);11791180 pos =cache_name_pos(dirname, len);1181if(pos <0)1182 pos = -pos-1;1183while(pos < active_nr) {1184const struct cache_entry *ce = active_cache[pos++];1185unsigned char endchar;11861187if(strncmp(ce->name, dirname, len))1188break;1189 endchar = ce->name[len];1190if(endchar >'/')1191break;1192if(endchar =='/')1193return index_directory;1194if(!endchar &&S_ISGITLINK(ce->ce_mode))1195return index_gitdir;1196}1197return index_nonexistent;1198}11991200/*1201 * When we find a directory when traversing the filesystem, we1202 * have three distinct cases:1203 *1204 * - ignore it1205 * - see it as a directory1206 * - recurse into it1207 *1208 * and which one we choose depends on a combination of existing1209 * git index contents and the flags passed into the directory1210 * traversal routine.1211 *1212 * Case 1: If we *already* have entries in the index under that1213 * directory name, we always recurse into the directory to see1214 * all the files.1215 *1216 * Case 2: If we *already* have that directory name as a gitlink,1217 * we always continue to see it as a gitlink, regardless of whether1218 * there is an actual git directory there or not (it might not1219 * be checked out as a subproject!)1220 *1221 * Case 3: if we didn't have it in the index previously, we1222 * have a few sub-cases:1223 *1224 * (a) if "show_other_directories" is true, we show it as1225 * just a directory, unless "hide_empty_directories" is1226 * also true, in which case we need to check if it contains any1227 * untracked and / or ignored files.1228 * (b) if it looks like a git directory, and we don't have1229 * 'no_gitlinks' set we treat it as a gitlink, and show it1230 * as a directory.1231 * (c) otherwise, we recurse into it.1232 */1233static enum path_treatment treat_directory(struct dir_struct *dir,1234struct untracked_cache_dir *untracked,1235const char*dirname,int len,int exclude,1236const struct path_simplify *simplify)1237{1238/* The "len-1" is to strip the final '/' */1239switch(directory_exists_in_index(dirname, len-1)) {1240case index_directory:1241return path_recurse;12421243case index_gitdir:1244return path_none;12451246case index_nonexistent:1247if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1248break;1249if(!(dir->flags & DIR_NO_GITLINKS)) {1250unsigned char sha1[20];1251if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1252return path_untracked;1253}1254return path_recurse;1255}12561257/* This is the "show_other_directories" case */12581259if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1260return exclude ? path_excluded : path_untracked;12611262 untracked =lookup_untracked(dir->untracked, untracked, dirname, len);1263returnread_directory_recursive(dir, dirname, len,1264 untracked,1, simplify);1265}12661267/*1268 * This is an inexact early pruning of any recursive directory1269 * reading - if the path cannot possibly be in the pathspec,1270 * return true, and we'll skip it early.1271 */1272static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1273{1274if(simplify) {1275for(;;) {1276const char*match = simplify->path;1277int len = simplify->len;12781279if(!match)1280break;1281if(len > pathlen)1282 len = pathlen;1283if(!memcmp(path, match, len))1284return0;1285 simplify++;1286}1287return1;1288}1289return0;1290}12911292/*1293 * This function tells us whether an excluded path matches a1294 * list of "interesting" pathspecs. That is, whether a path matched1295 * by any of the pathspecs could possibly be ignored by excluding1296 * the specified path. This can happen if:1297 *1298 * 1. the path is mentioned explicitly in the pathspec1299 *1300 * 2. the path is a directory prefix of some element in the1301 * pathspec1302 */1303static intexclude_matches_pathspec(const char*path,int len,1304const struct path_simplify *simplify)1305{1306if(simplify) {1307for(; simplify->path; simplify++) {1308if(len == simplify->len1309&& !memcmp(path, simplify->path, len))1310return1;1311if(len < simplify->len1312&& simplify->path[len] =='/'1313&& !memcmp(path, simplify->path, len))1314return1;1315}1316}1317return0;1318}13191320static intget_index_dtype(const char*path,int len)1321{1322int pos;1323const struct cache_entry *ce;13241325 ce =cache_file_exists(path, len,0);1326if(ce) {1327if(!ce_uptodate(ce))1328return DT_UNKNOWN;1329if(S_ISGITLINK(ce->ce_mode))1330return DT_DIR;1331/*1332 * Nobody actually cares about the1333 * difference between DT_LNK and DT_REG1334 */1335return DT_REG;1336}13371338/* Try to look it up as a directory */1339 pos =cache_name_pos(path, len);1340if(pos >=0)1341return DT_UNKNOWN;1342 pos = -pos-1;1343while(pos < active_nr) {1344 ce = active_cache[pos++];1345if(strncmp(ce->name, path, len))1346break;1347if(ce->name[len] >'/')1348break;1349if(ce->name[len] <'/')1350continue;1351if(!ce_uptodate(ce))1352break;/* continue? */1353return DT_DIR;1354}1355return DT_UNKNOWN;1356}13571358static intget_dtype(struct dirent *de,const char*path,int len)1359{1360int dtype = de ?DTYPE(de) : DT_UNKNOWN;1361struct stat st;13621363if(dtype != DT_UNKNOWN)1364return dtype;1365 dtype =get_index_dtype(path, len);1366if(dtype != DT_UNKNOWN)1367return dtype;1368if(lstat(path, &st))1369return dtype;1370if(S_ISREG(st.st_mode))1371return DT_REG;1372if(S_ISDIR(st.st_mode))1373return DT_DIR;1374if(S_ISLNK(st.st_mode))1375return DT_LNK;1376return dtype;1377}13781379static enum path_treatment treat_one_path(struct dir_struct *dir,1380struct untracked_cache_dir *untracked,1381struct strbuf *path,1382const struct path_simplify *simplify,1383int dtype,struct dirent *de)1384{1385int exclude;1386int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);13871388if(dtype == DT_UNKNOWN)1389 dtype =get_dtype(de, path->buf, path->len);13901391/* Always exclude indexed files */1392if(dtype != DT_DIR && has_path_in_index)1393return path_none;13941395/*1396 * When we are looking at a directory P in the working tree,1397 * there are three cases:1398 *1399 * (1) P exists in the index. Everything inside the directory P in1400 * the working tree needs to go when P is checked out from the1401 * index.1402 *1403 * (2) P does not exist in the index, but there is P/Q in the index.1404 * We know P will stay a directory when we check out the contents1405 * of the index, but we do not know yet if there is a directory1406 * P/Q in the working tree to be killed, so we need to recurse.1407 *1408 * (3) P does not exist in the index, and there is no P/Q in the index1409 * to require P to be a directory, either. Only in this case, we1410 * know that everything inside P will not be killed without1411 * recursing.1412 */1413if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1414(dtype == DT_DIR) &&1415!has_path_in_index &&1416(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1417return path_none;14181419 exclude =is_excluded(dir, path->buf, &dtype);14201421/*1422 * Excluded? If we don't explicitly want to show1423 * ignored files, ignore it1424 */1425if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1426return path_excluded;14271428switch(dtype) {1429default:1430return path_none;1431case DT_DIR:1432strbuf_addch(path,'/');1433returntreat_directory(dir, untracked, path->buf, path->len, exclude,1434 simplify);1435case DT_REG:1436case DT_LNK:1437return exclude ? path_excluded : path_untracked;1438}1439}14401441static enum path_treatment treat_path_fast(struct dir_struct *dir,1442struct untracked_cache_dir *untracked,1443struct cached_dir *cdir,1444struct strbuf *path,1445int baselen,1446const struct path_simplify *simplify)1447{1448strbuf_setlen(path, baselen);1449if(!cdir->ucd) {1450strbuf_addstr(path, cdir->file);1451return path_untracked;1452}1453strbuf_addstr(path, cdir->ucd->name);1454/* treat_one_path() does this before it calls treat_directory() */1455if(path->buf[path->len -1] !='/')1456strbuf_addch(path,'/');1457if(cdir->ucd->check_only)1458/*1459 * check_only is set as a result of treat_directory() getting1460 * to its bottom. Verify again the same set of directories1461 * with check_only set.1462 */1463returnread_directory_recursive(dir, path->buf, path->len,1464 cdir->ucd,1, simplify);1465/*1466 * We get path_recurse in the first run when1467 * directory_exists_in_index() returns index_nonexistent. We1468 * are sure that new changes in the index does not impact the1469 * outcome. Return now.1470 */1471return path_recurse;1472}14731474static enum path_treatment treat_path(struct dir_struct *dir,1475struct untracked_cache_dir *untracked,1476struct cached_dir *cdir,1477struct strbuf *path,1478int baselen,1479const struct path_simplify *simplify)1480{1481int dtype;1482struct dirent *de = cdir->de;14831484if(!de)1485returntreat_path_fast(dir, untracked, cdir, path,1486 baselen, simplify);1487if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1488return path_none;1489strbuf_setlen(path, baselen);1490strbuf_addstr(path, de->d_name);1491if(simplify_away(path->buf, path->len, simplify))1492return path_none;14931494 dtype =DTYPE(de);1495returntreat_one_path(dir, untracked, path, simplify, dtype, de);1496}14971498static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1499{1500if(!dir)1501return;1502ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1503 dir->untracked_alloc);1504 dir->untracked[dir->untracked_nr++] =xstrdup(name);1505}15061507static intvalid_cached_dir(struct dir_struct *dir,1508struct untracked_cache_dir *untracked,1509struct strbuf *path,1510int check_only)1511{1512struct stat st;15131514if(!untracked)1515return0;15161517if(stat(path->len ? path->buf :".", &st)) {1518invalidate_directory(dir->untracked, untracked);1519memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1520return0;1521}1522if(!untracked->valid ||1523match_stat_data(&untracked->stat_data, &st)) {1524if(untracked->valid)1525invalidate_directory(dir->untracked, untracked);1526fill_stat_data(&untracked->stat_data, &st);1527return0;1528}15291530if(untracked->check_only != !!check_only) {1531invalidate_directory(dir->untracked, untracked);1532return0;1533}15341535/*1536 * prep_exclude will be called eventually on this directory,1537 * but it's called much later in last_exclude_matching(). We1538 * need it now to determine the validity of the cache for this1539 * path. The next calls will be nearly no-op, the way1540 * prep_exclude() is designed.1541 */1542if(path->len && path->buf[path->len -1] !='/') {1543strbuf_addch(path,'/');1544prep_exclude(dir, path->buf, path->len);1545strbuf_setlen(path, path->len -1);1546}else1547prep_exclude(dir, path->buf, path->len);15481549/* hopefully prep_exclude() haven't invalidated this entry... */1550return untracked->valid;1551}15521553static intopen_cached_dir(struct cached_dir *cdir,1554struct dir_struct *dir,1555struct untracked_cache_dir *untracked,1556struct strbuf *path,1557int check_only)1558{1559memset(cdir,0,sizeof(*cdir));1560 cdir->untracked = untracked;1561if(valid_cached_dir(dir, untracked, path, check_only))1562return0;1563 cdir->fdir =opendir(path->len ? path->buf :".");1564if(dir->untracked)1565 dir->untracked->dir_opened++;1566if(!cdir->fdir)1567return-1;1568return0;1569}15701571static intread_cached_dir(struct cached_dir *cdir)1572{1573if(cdir->fdir) {1574 cdir->de =readdir(cdir->fdir);1575if(!cdir->de)1576return-1;1577return0;1578}1579while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1580struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1581 cdir->ucd = d;1582 cdir->nr_dirs++;1583return0;1584}1585 cdir->ucd = NULL;1586if(cdir->nr_files < cdir->untracked->untracked_nr) {1587struct untracked_cache_dir *d = cdir->untracked;1588 cdir->file = d->untracked[cdir->nr_files++];1589return0;1590}1591return-1;1592}15931594static voidclose_cached_dir(struct cached_dir *cdir)1595{1596if(cdir->fdir)1597closedir(cdir->fdir);1598/*1599 * We have gone through this directory and found no untracked1600 * entries. Mark it valid.1601 */1602if(cdir->untracked)1603 cdir->untracked->valid =1;1604}16051606/*1607 * Read a directory tree. We currently ignore anything but1608 * directories, regular files and symlinks. That's because git1609 * doesn't handle them at all yet. Maybe that will change some1610 * day.1611 *1612 * Also, we ignore the name ".git" (even if it is not a directory).1613 * That likely will not change.1614 *1615 * Returns the most significant path_treatment value encountered in the scan.1616 */1617static enum path_treatment read_directory_recursive(struct dir_struct *dir,1618const char*base,int baselen,1619struct untracked_cache_dir *untracked,int check_only,1620const struct path_simplify *simplify)1621{1622struct cached_dir cdir;1623enum path_treatment state, subdir_state, dir_state = path_none;1624struct strbuf path = STRBUF_INIT;16251626strbuf_add(&path, base, baselen);16271628if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1629goto out;16301631if(untracked)1632 untracked->check_only = !!check_only;16331634while(!read_cached_dir(&cdir)) {1635/* check how the file or directory should be treated */1636 state =treat_path(dir, untracked, &cdir, &path, baselen, simplify);16371638if(state > dir_state)1639 dir_state = state;16401641/* recurse into subdir if instructed by treat_path */1642if(state == path_recurse) {1643struct untracked_cache_dir *ud;1644 ud =lookup_untracked(dir->untracked, untracked,1645 path.buf + baselen,1646 path.len - baselen);1647 subdir_state =1648read_directory_recursive(dir, path.buf, path.len,1649 ud, check_only, simplify);1650if(subdir_state > dir_state)1651 dir_state = subdir_state;1652}16531654if(check_only) {1655/* abort early if maximum state has been reached */1656if(dir_state == path_untracked) {1657if(cdir.fdir)1658add_untracked(untracked, path.buf + baselen);1659break;1660}1661/* skip the dir_add_* part */1662continue;1663}16641665/* add the path to the appropriate result list */1666switch(state) {1667case path_excluded:1668if(dir->flags & DIR_SHOW_IGNORED)1669dir_add_name(dir, path.buf, path.len);1670else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1671((dir->flags & DIR_COLLECT_IGNORED) &&1672exclude_matches_pathspec(path.buf, path.len,1673 simplify)))1674dir_add_ignored(dir, path.buf, path.len);1675break;16761677case path_untracked:1678if(dir->flags & DIR_SHOW_IGNORED)1679break;1680dir_add_name(dir, path.buf, path.len);1681if(cdir.fdir)1682add_untracked(untracked, path.buf + baselen);1683break;16841685default:1686break;1687}1688}1689close_cached_dir(&cdir);1690 out:1691strbuf_release(&path);16921693return dir_state;1694}16951696static intcmp_name(const void*p1,const void*p2)1697{1698const struct dir_entry *e1 = *(const struct dir_entry **)p1;1699const struct dir_entry *e2 = *(const struct dir_entry **)p2;17001701returnname_compare(e1->name, e1->len, e2->name, e2->len);1702}17031704static struct path_simplify *create_simplify(const char**pathspec)1705{1706int nr, alloc =0;1707struct path_simplify *simplify = NULL;17081709if(!pathspec)1710return NULL;17111712for(nr =0; ; nr++) {1713const char*match;1714ALLOC_GROW(simplify, nr +1, alloc);1715 match = *pathspec++;1716if(!match)1717break;1718 simplify[nr].path = match;1719 simplify[nr].len =simple_length(match);1720}1721 simplify[nr].path = NULL;1722 simplify[nr].len =0;1723return simplify;1724}17251726static voidfree_simplify(struct path_simplify *simplify)1727{1728free(simplify);1729}17301731static inttreat_leading_path(struct dir_struct *dir,1732const char*path,int len,1733const struct path_simplify *simplify)1734{1735struct strbuf sb = STRBUF_INIT;1736int baselen, rc =0;1737const char*cp;1738int old_flags = dir->flags;17391740while(len && path[len -1] =='/')1741 len--;1742if(!len)1743return1;1744 baselen =0;1745 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1746while(1) {1747 cp = path + baselen + !!baselen;1748 cp =memchr(cp,'/', path + len - cp);1749if(!cp)1750 baselen = len;1751else1752 baselen = cp - path;1753strbuf_setlen(&sb,0);1754strbuf_add(&sb, path, baselen);1755if(!is_directory(sb.buf))1756break;1757if(simplify_away(sb.buf, sb.len, simplify))1758break;1759if(treat_one_path(dir, NULL, &sb, simplify,1760 DT_DIR, NULL) == path_none)1761break;/* do not recurse into it */1762if(len <= baselen) {1763 rc =1;1764break;/* finished checking */1765}1766}1767strbuf_release(&sb);1768 dir->flags = old_flags;1769return rc;1770}17711772static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1773int base_len,1774const struct pathspec *pathspec)1775{1776struct untracked_cache_dir *root;17771778if(!dir->untracked)1779return NULL;17801781/*1782 * We only support $GIT_DIR/info/exclude and core.excludesfile1783 * as the global ignore rule files. Any other additions1784 * (e.g. from command line) invalidate the cache. This1785 * condition also catches running setup_standard_excludes()1786 * before setting dir->untracked!1787 */1788if(dir->unmanaged_exclude_files)1789return NULL;17901791/*1792 * Optimize for the main use case only: whole-tree git1793 * status. More work involved in treat_leading_path() if we1794 * use cache on just a subset of the worktree. pathspec1795 * support could make the matter even worse.1796 */1797if(base_len || (pathspec && pathspec->nr))1798return NULL;17991800/* Different set of flags may produce different results */1801if(dir->flags != dir->untracked->dir_flags ||1802/*1803 * See treat_directory(), case index_nonexistent. Without1804 * this flag, we may need to also cache .git file content1805 * for the resolve_gitlink_ref() call, which we don't.1806 */1807!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1808/* We don't support collecting ignore files */1809(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1810 DIR_COLLECT_IGNORED)))1811return NULL;18121813/*1814 * If we use .gitignore in the cache and now you change it to1815 * .gitexclude, everything will go wrong.1816 */1817if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1818strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1819return NULL;18201821/*1822 * EXC_CMDL is not considered in the cache. If people set it,1823 * skip the cache.1824 */1825if(dir->exclude_list_group[EXC_CMDL].nr)1826return NULL;18271828if(!dir->untracked->root) {1829const int len =sizeof(*dir->untracked->root);1830 dir->untracked->root =xmalloc(len);1831memset(dir->untracked->root,0, len);1832}18331834/* Validate $GIT_DIR/info/exclude and core.excludesfile */1835 root = dir->untracked->root;1836if(hashcmp(dir->ss_info_exclude.sha1,1837 dir->untracked->ss_info_exclude.sha1)) {1838invalidate_gitignore(dir->untracked, root);1839 dir->untracked->ss_info_exclude = dir->ss_info_exclude;1840}1841if(hashcmp(dir->ss_excludes_file.sha1,1842 dir->untracked->ss_excludes_file.sha1)) {1843invalidate_gitignore(dir->untracked, root);1844 dir->untracked->ss_excludes_file = dir->ss_excludes_file;1845}1846return root;1847}18481849intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)1850{1851struct path_simplify *simplify;1852struct untracked_cache_dir *untracked;18531854/*1855 * Check out create_simplify()1856 */1857if(pathspec)1858GUARD_PATHSPEC(pathspec,1859 PATHSPEC_FROMTOP |1860 PATHSPEC_MAXDEPTH |1861 PATHSPEC_LITERAL |1862 PATHSPEC_GLOB |1863 PATHSPEC_ICASE |1864 PATHSPEC_EXCLUDE);18651866if(has_symlink_leading_path(path, len))1867return dir->nr;18681869/*1870 * exclude patterns are treated like positive ones in1871 * create_simplify. Usually exclude patterns should be a1872 * subset of positive ones, which has no impacts on1873 * create_simplify().1874 */1875 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);1876 untracked =validate_untracked_cache(dir, len, pathspec);1877if(!untracked)1878/*1879 * make sure untracked cache code path is disabled,1880 * e.g. prep_exclude()1881 */1882 dir->untracked = NULL;1883if(!len ||treat_leading_path(dir, path, len, simplify))1884read_directory_recursive(dir, path, len, untracked,0, simplify);1885free_simplify(simplify);1886qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);1887qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);1888return dir->nr;1889}18901891intfile_exists(const char*f)1892{1893struct stat sb;1894returnlstat(f, &sb) ==0;1895}18961897/*1898 * Given two normalized paths (a trailing slash is ok), if subdir is1899 * outside dir, return -1. Otherwise return the offset in subdir that1900 * can be used as relative path to dir.1901 */1902intdir_inside_of(const char*subdir,const char*dir)1903{1904int offset =0;19051906assert(dir && subdir && *dir && *subdir);19071908while(*dir && *subdir && *dir == *subdir) {1909 dir++;1910 subdir++;1911 offset++;1912}19131914/* hel[p]/me vs hel[l]/yeah */1915if(*dir && *subdir)1916return-1;19171918if(!*subdir)1919return!*dir ? offset : -1;/* same dir */19201921/* foo/[b]ar vs foo/[] */1922if(is_dir_sep(dir[-1]))1923returnis_dir_sep(subdir[-1]) ? offset : -1;19241925/* foo[/]bar vs foo[] */1926returnis_dir_sep(*subdir) ? offset +1: -1;1927}19281929intis_inside_dir(const char*dir)1930{1931char*cwd;1932int rc;19331934if(!dir)1935return0;19361937 cwd =xgetcwd();1938 rc = (dir_inside_of(cwd, dir) >=0);1939free(cwd);1940return rc;1941}19421943intis_empty_dir(const char*path)1944{1945DIR*dir =opendir(path);1946struct dirent *e;1947int ret =1;19481949if(!dir)1950return0;19511952while((e =readdir(dir)) != NULL)1953if(!is_dot_or_dotdot(e->d_name)) {1954 ret =0;1955break;1956}19571958closedir(dir);1959return ret;1960}19611962static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)1963{1964DIR*dir;1965struct dirent *e;1966int ret =0, original_len = path->len, len, kept_down =0;1967int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);1968int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);1969unsigned char submodule_head[20];19701971if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&1972!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {1973/* Do not descend and nuke a nested git work tree. */1974if(kept_up)1975*kept_up =1;1976return0;1977}19781979 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;1980 dir =opendir(path->buf);1981if(!dir) {1982if(errno == ENOENT)1983return keep_toplevel ? -1:0;1984else if(errno == EACCES && !keep_toplevel)1985/*1986 * An empty dir could be removable even if it1987 * is unreadable:1988 */1989returnrmdir(path->buf);1990else1991return-1;1992}1993if(path->buf[original_len -1] !='/')1994strbuf_addch(path,'/');19951996 len = path->len;1997while((e =readdir(dir)) != NULL) {1998struct stat st;1999if(is_dot_or_dotdot(e->d_name))2000continue;20012002strbuf_setlen(path, len);2003strbuf_addstr(path, e->d_name);2004if(lstat(path->buf, &st)) {2005if(errno == ENOENT)2006/*2007 * file disappeared, which is what we2008 * wanted anyway2009 */2010continue;2011/* fall thru */2012}else if(S_ISDIR(st.st_mode)) {2013if(!remove_dir_recurse(path, flag, &kept_down))2014continue;/* happy */2015}else if(!only_empty &&2016(!unlink(path->buf) || errno == ENOENT)) {2017continue;/* happy, too */2018}20192020/* path too long, stat fails, or non-directory still exists */2021 ret = -1;2022break;2023}2024closedir(dir);20252026strbuf_setlen(path, original_len);2027if(!ret && !keep_toplevel && !kept_down)2028 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2029else if(kept_up)2030/*2031 * report the uplevel that it is not an error that we2032 * did not rmdir() our directory.2033 */2034*kept_up = !ret;2035return ret;2036}20372038intremove_dir_recursively(struct strbuf *path,int flag)2039{2040returnremove_dir_recurse(path, flag, NULL);2041}20422043voidsetup_standard_excludes(struct dir_struct *dir)2044{2045const char*path;2046char*xdg_path;20472048 dir->exclude_per_dir =".gitignore";2049 path =git_path("info/exclude");2050if(!excludes_file) {2051home_config_paths(NULL, &xdg_path,"ignore");2052 excludes_file = xdg_path;2053}2054if(!access_or_warn(path, R_OK,0))2055add_excludes_from_file_1(dir, path,2056 dir->untracked ? &dir->ss_info_exclude : NULL);2057if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2058add_excludes_from_file_1(dir, excludes_file,2059 dir->untracked ? &dir->ss_excludes_file : NULL);2060}20612062intremove_path(const char*name)2063{2064char*slash;20652066if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2067return-1;20682069 slash =strrchr(name,'/');2070if(slash) {2071char*dirs =xstrdup(name);2072 slash = dirs + (slash - name);2073do{2074*slash ='\0';2075}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2076free(dirs);2077}2078return0;2079}20802081/*2082 * Frees memory within dir which was allocated for exclude lists and2083 * the exclude_stack. Does not free dir itself.2084 */2085voidclear_directory(struct dir_struct *dir)2086{2087int i, j;2088struct exclude_list_group *group;2089struct exclude_list *el;2090struct exclude_stack *stk;20912092for(i = EXC_CMDL; i <= EXC_FILE; i++) {2093 group = &dir->exclude_list_group[i];2094for(j =0; j < group->nr; j++) {2095 el = &group->el[j];2096if(i == EXC_DIRS)2097free((char*)el->src);2098clear_exclude_list(el);2099}2100free(group->el);2101}21022103 stk = dir->exclude_stack;2104while(stk) {2105struct exclude_stack *prev = stk->prev;2106free(stk);2107 stk = prev;2108}2109strbuf_release(&dir->basebuf);2110}