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{ 618int i; 619 uc->dir_invalidated++; 620 dir->valid =0; 621 dir->untracked_nr =0; 622for(i =0; i < dir->dirs_nr; i++) 623 dir->dirs[i]->recurse =0; 624} 625 626/* 627 * Given a file with name "fname", read it (either from disk, or from 628 * the index if "check_index" is non-zero), parse it and store the 629 * exclude rules in "el". 630 * 631 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 632 * stat data from disk (only valid if add_excludes returns zero). If 633 * ss_valid is non-zero, "ss" must contain good value as input. 634 */ 635static intadd_excludes(const char*fname,const char*base,int baselen, 636struct exclude_list *el,int check_index, 637struct sha1_stat *sha1_stat) 638{ 639struct stat st; 640int fd, i, lineno =1; 641size_t size =0; 642char*buf, *entry; 643 644 fd =open(fname, O_RDONLY); 645if(fd <0||fstat(fd, &st) <0) { 646if(errno != ENOENT) 647warn_on_inaccessible(fname); 648if(0<= fd) 649close(fd); 650if(!check_index || 651(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 652return-1; 653if(size ==0) { 654free(buf); 655return0; 656} 657if(buf[size-1] !='\n') { 658 buf =xrealloc(buf, size+1); 659 buf[size++] ='\n'; 660} 661}else{ 662 size =xsize_t(st.st_size); 663if(size ==0) { 664if(sha1_stat) { 665fill_stat_data(&sha1_stat->stat, &st); 666hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 667 sha1_stat->valid =1; 668} 669close(fd); 670return0; 671} 672 buf =xmalloc(size+1); 673if(read_in_full(fd, buf, size) != size) { 674free(buf); 675close(fd); 676return-1; 677} 678 buf[size++] ='\n'; 679close(fd); 680if(sha1_stat) { 681int pos; 682if(sha1_stat->valid && 683!match_stat_data(&sha1_stat->stat, &st)) 684;/* no content change, ss->sha1 still good */ 685else if(check_index && 686(pos =cache_name_pos(fname,strlen(fname))) >=0&& 687!ce_stage(active_cache[pos]) && 688ce_uptodate(active_cache[pos]) && 689!would_convert_to_git(fname)) 690hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 691else 692hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 693fill_stat_data(&sha1_stat->stat, &st); 694 sha1_stat->valid =1; 695} 696} 697 698 el->filebuf = buf; 699 entry = buf; 700for(i =0; i < size; i++) { 701if(buf[i] =='\n') { 702if(entry != buf + i && entry[0] !='#') { 703 buf[i - (i && buf[i-1] =='\r')] =0; 704trim_trailing_spaces(entry); 705add_exclude(entry, base, baselen, el, lineno); 706} 707 lineno++; 708 entry = buf + i +1; 709} 710} 711return0; 712} 713 714intadd_excludes_from_file_to_list(const char*fname,const char*base, 715int baselen,struct exclude_list *el, 716int check_index) 717{ 718returnadd_excludes(fname, base, baselen, el, check_index, NULL); 719} 720 721struct exclude_list *add_exclude_list(struct dir_struct *dir, 722int group_type,const char*src) 723{ 724struct exclude_list *el; 725struct exclude_list_group *group; 726 727 group = &dir->exclude_list_group[group_type]; 728ALLOC_GROW(group->el, group->nr +1, group->alloc); 729 el = &group->el[group->nr++]; 730memset(el,0,sizeof(*el)); 731 el->src = src; 732return el; 733} 734 735/* 736 * Used to set up core.excludesfile and .git/info/exclude lists. 737 */ 738static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 739struct sha1_stat *sha1_stat) 740{ 741struct exclude_list *el; 742/* 743 * catch setup_standard_excludes() that's called before 744 * dir->untracked is assigned. That function behaves 745 * differently when dir->untracked is non-NULL. 746 */ 747if(!dir->untracked) 748 dir->unmanaged_exclude_files++; 749 el =add_exclude_list(dir, EXC_FILE, fname); 750if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 751die("cannot use%sas an exclude file", fname); 752} 753 754voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 755{ 756 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 757add_excludes_from_file_1(dir, fname, NULL); 758} 759 760intmatch_basename(const char*basename,int basenamelen, 761const char*pattern,int prefix,int patternlen, 762int flags) 763{ 764if(prefix == patternlen) { 765if(patternlen == basenamelen && 766!strncmp_icase(pattern, basename, basenamelen)) 767return1; 768}else if(flags & EXC_FLAG_ENDSWITH) { 769/* "*literal" matching against "fooliteral" */ 770if(patternlen -1<= basenamelen && 771!strncmp_icase(pattern +1, 772 basename + basenamelen - (patternlen -1), 773 patternlen -1)) 774return1; 775}else{ 776if(fnmatch_icase_mem(pattern, patternlen, 777 basename, basenamelen, 7780) ==0) 779return1; 780} 781return0; 782} 783 784intmatch_pathname(const char*pathname,int pathlen, 785const char*base,int baselen, 786const char*pattern,int prefix,int patternlen, 787int flags) 788{ 789const char*name; 790int namelen; 791 792/* 793 * match with FNM_PATHNAME; the pattern has base implicitly 794 * in front of it. 795 */ 796if(*pattern =='/') { 797 pattern++; 798 patternlen--; 799 prefix--; 800} 801 802/* 803 * baselen does not count the trailing slash. base[] may or 804 * may not end with a trailing slash though. 805 */ 806if(pathlen < baselen +1|| 807(baselen && pathname[baselen] !='/') || 808strncmp_icase(pathname, base, baselen)) 809return0; 810 811 namelen = baselen ? pathlen - baselen -1: pathlen; 812 name = pathname + pathlen - namelen; 813 814if(prefix) { 815/* 816 * if the non-wildcard part is longer than the 817 * remaining pathname, surely it cannot match. 818 */ 819if(prefix > namelen) 820return0; 821 822if(strncmp_icase(pattern, name, prefix)) 823return0; 824 pattern += prefix; 825 patternlen -= prefix; 826 name += prefix; 827 namelen -= prefix; 828 829/* 830 * If the whole pattern did not have a wildcard, 831 * then our prefix match is all we need; we 832 * do not need to call fnmatch at all. 833 */ 834if(!patternlen && !namelen) 835return1; 836} 837 838returnfnmatch_icase_mem(pattern, patternlen, 839 name, namelen, 840 WM_PATHNAME) ==0; 841} 842 843/* 844 * Scan the given exclude list in reverse to see whether pathname 845 * should be ignored. The first match (i.e. the last on the list), if 846 * any, determines the fate. Returns the exclude_list element which 847 * matched, or NULL for undecided. 848 */ 849static struct exclude *last_exclude_matching_from_list(const char*pathname, 850int pathlen, 851const char*basename, 852int*dtype, 853struct exclude_list *el) 854{ 855int i; 856 857if(!el->nr) 858return NULL;/* undefined */ 859 860for(i = el->nr -1;0<= i; i--) { 861struct exclude *x = el->excludes[i]; 862const char*exclude = x->pattern; 863int prefix = x->nowildcardlen; 864 865if(x->flags & EXC_FLAG_MUSTBEDIR) { 866if(*dtype == DT_UNKNOWN) 867*dtype =get_dtype(NULL, pathname, pathlen); 868if(*dtype != DT_DIR) 869continue; 870} 871 872if(x->flags & EXC_FLAG_NODIR) { 873if(match_basename(basename, 874 pathlen - (basename - pathname), 875 exclude, prefix, x->patternlen, 876 x->flags)) 877return x; 878continue; 879} 880 881assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 882if(match_pathname(pathname, pathlen, 883 x->base, x->baselen ? x->baselen -1:0, 884 exclude, prefix, x->patternlen, x->flags)) 885return x; 886} 887return NULL;/* undecided */ 888} 889 890/* 891 * Scan the list and let the last match determine the fate. 892 * Return 1 for exclude, 0 for include and -1 for undecided. 893 */ 894intis_excluded_from_list(const char*pathname, 895int pathlen,const char*basename,int*dtype, 896struct exclude_list *el) 897{ 898struct exclude *exclude; 899 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 900if(exclude) 901return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 902return-1;/* undecided */ 903} 904 905static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 906const char*pathname,int pathlen,const char*basename, 907int*dtype_p) 908{ 909int i, j; 910struct exclude_list_group *group; 911struct exclude *exclude; 912for(i = EXC_CMDL; i <= EXC_FILE; i++) { 913 group = &dir->exclude_list_group[i]; 914for(j = group->nr -1; j >=0; j--) { 915 exclude =last_exclude_matching_from_list( 916 pathname, pathlen, basename, dtype_p, 917&group->el[j]); 918if(exclude) 919return exclude; 920} 921} 922return NULL; 923} 924 925/* 926 * Loads the per-directory exclude list for the substring of base 927 * which has a char length of baselen. 928 */ 929static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen) 930{ 931struct exclude_list_group *group; 932struct exclude_list *el; 933struct exclude_stack *stk = NULL; 934struct untracked_cache_dir *untracked; 935int current; 936 937 group = &dir->exclude_list_group[EXC_DIRS]; 938 939/* 940 * Pop the exclude lists from the EXCL_DIRS exclude_list_group 941 * which originate from directories not in the prefix of the 942 * path being checked. 943 */ 944while((stk = dir->exclude_stack) != NULL) { 945if(stk->baselen <= baselen && 946!strncmp(dir->basebuf.buf, base, stk->baselen)) 947break; 948 el = &group->el[dir->exclude_stack->exclude_ix]; 949 dir->exclude_stack = stk->prev; 950 dir->exclude = NULL; 951free((char*)el->src);/* see strbuf_detach() below */ 952clear_exclude_list(el); 953free(stk); 954 group->nr--; 955} 956 957/* Skip traversing into sub directories if the parent is excluded */ 958if(dir->exclude) 959return; 960 961/* 962 * Lazy initialization. All call sites currently just 963 * memset(dir, 0, sizeof(*dir)) before use. Changing all of 964 * them seems lots of work for little benefit. 965 */ 966if(!dir->basebuf.buf) 967strbuf_init(&dir->basebuf, PATH_MAX); 968 969/* Read from the parent directories and push them down. */ 970 current = stk ? stk->baselen : -1; 971strbuf_setlen(&dir->basebuf, current <0?0: current); 972if(dir->untracked) 973 untracked = stk ? stk->ucd : dir->untracked->root; 974else 975 untracked = NULL; 976 977while(current < baselen) { 978const char*cp; 979struct sha1_stat sha1_stat; 980 981 stk =xcalloc(1,sizeof(*stk)); 982if(current <0) { 983 cp = base; 984 current =0; 985}else{ 986 cp =strchr(base + current +1,'/'); 987if(!cp) 988die("oops in prep_exclude"); 989 cp++; 990 untracked = 991lookup_untracked(dir->untracked, untracked, 992 base + current, 993 cp - base - current); 994} 995 stk->prev = dir->exclude_stack; 996 stk->baselen = cp - base; 997 stk->exclude_ix = group->nr; 998 stk->ucd = untracked; 999 el =add_exclude_list(dir, EXC_DIRS, NULL);1000strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1001assert(stk->baselen == dir->basebuf.len);10021003/* Abort if the directory is excluded */1004if(stk->baselen) {1005int dt = DT_DIR;1006 dir->basebuf.buf[stk->baselen -1] =0;1007 dir->exclude =last_exclude_matching_from_lists(dir,1008 dir->basebuf.buf, stk->baselen -1,1009 dir->basebuf.buf + current, &dt);1010 dir->basebuf.buf[stk->baselen -1] ='/';1011if(dir->exclude &&1012 dir->exclude->flags & EXC_FLAG_NEGATIVE)1013 dir->exclude = NULL;1014if(dir->exclude) {1015 dir->exclude_stack = stk;1016return;1017}1018}10191020/* Try to read per-directory file */1021hashclr(sha1_stat.sha1);1022 sha1_stat.valid =0;1023if(dir->exclude_per_dir &&1024/*1025 * If we know that no files have been added in1026 * this directory (i.e. valid_cached_dir() has1027 * been executed and set untracked->valid) ..1028 */1029(!untracked || !untracked->valid ||1030/*1031 * .. and .gitignore does not exist before1032 * (i.e. null exclude_sha1 and skip_worktree is1033 * not set). Then we can skip loading .gitignore,1034 * which would result in ENOENT anyway.1035 * skip_worktree is taken care in read_directory()1036 */1037!is_null_sha1(untracked->exclude_sha1))) {1038/*1039 * dir->basebuf gets reused by the traversal, but we1040 * need fname to remain unchanged to ensure the src1041 * member of each struct exclude correctly1042 * back-references its source file. Other invocations1043 * of add_exclude_list provide stable strings, so we1044 * strbuf_detach() and free() here in the caller.1045 */1046struct strbuf sb = STRBUF_INIT;1047strbuf_addbuf(&sb, &dir->basebuf);1048strbuf_addstr(&sb, dir->exclude_per_dir);1049 el->src =strbuf_detach(&sb, NULL);1050add_excludes(el->src, el->src, stk->baselen, el,1,1051 untracked ? &sha1_stat : NULL);1052}1053/*1054 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1055 * will first be called in valid_cached_dir() then maybe many1056 * times more in last_exclude_matching(). When the cache is1057 * used, last_exclude_matching() will not be called and1058 * reading .gitignore content will be a waste.1059 *1060 * So when it's called by valid_cached_dir() and we can get1061 * .gitignore SHA-1 from the index (i.e. .gitignore is not1062 * modified on work tree), we could delay reading the1063 * .gitignore content until we absolutely need it in1064 * last_exclude_matching(). Be careful about ignore rule1065 * order, though, if you do that.1066 */1067if(untracked &&1068hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1069invalidate_gitignore(dir->untracked, untracked);1070hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1071}1072 dir->exclude_stack = stk;1073 current = stk->baselen;1074}1075strbuf_setlen(&dir->basebuf, baselen);1076}10771078/*1079 * Loads the exclude lists for the directory containing pathname, then1080 * scans all exclude lists to determine whether pathname is excluded.1081 * Returns the exclude_list element which matched, or NULL for1082 * undecided.1083 */1084struct exclude *last_exclude_matching(struct dir_struct *dir,1085const char*pathname,1086int*dtype_p)1087{1088int pathlen =strlen(pathname);1089const char*basename =strrchr(pathname,'/');1090 basename = (basename) ? basename+1: pathname;10911092prep_exclude(dir, pathname, basename-pathname);10931094if(dir->exclude)1095return dir->exclude;10961097returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1098 basename, dtype_p);1099}11001101/*1102 * Loads the exclude lists for the directory containing pathname, then1103 * scans all exclude lists to determine whether pathname is excluded.1104 * Returns 1 if true, otherwise 0.1105 */1106intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1107{1108struct exclude *exclude =1109last_exclude_matching(dir, pathname, dtype_p);1110if(exclude)1111return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1112return0;1113}11141115static struct dir_entry *dir_entry_new(const char*pathname,int len)1116{1117struct dir_entry *ent;11181119 ent =xmalloc(sizeof(*ent) + len +1);1120 ent->len = len;1121memcpy(ent->name, pathname, len);1122 ent->name[len] =0;1123return ent;1124}11251126static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1127{1128if(cache_file_exists(pathname, len, ignore_case))1129return NULL;11301131ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1132return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1133}11341135struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1136{1137if(!cache_name_is_other(pathname, len))1138return NULL;11391140ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1141return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1142}11431144enum exist_status {1145 index_nonexistent =0,1146 index_directory,1147 index_gitdir1148};11491150/*1151 * Do not use the alphabetically sorted index to look up1152 * the directory name; instead, use the case insensitive1153 * directory hash.1154 */1155static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1156{1157const struct cache_entry *ce =cache_dir_exists(dirname, len);1158unsigned char endchar;11591160if(!ce)1161return index_nonexistent;1162 endchar = ce->name[len];11631164/*1165 * The cache_entry structure returned will contain this dirname1166 * and possibly additional path components.1167 */1168if(endchar =='/')1169return index_directory;11701171/*1172 * If there are no additional path components, then this cache_entry1173 * represents a submodule. Submodules, despite being directories,1174 * are stored in the cache without a closing slash.1175 */1176if(!endchar &&S_ISGITLINK(ce->ce_mode))1177return index_gitdir;11781179/* This should never be hit, but it exists just in case. */1180return index_nonexistent;1181}11821183/*1184 * The index sorts alphabetically by entry name, which1185 * means that a gitlink sorts as '\0' at the end, while1186 * a directory (which is defined not as an entry, but as1187 * the files it contains) will sort with the '/' at the1188 * end.1189 */1190static enum exist_status directory_exists_in_index(const char*dirname,int len)1191{1192int pos;11931194if(ignore_case)1195returndirectory_exists_in_index_icase(dirname, len);11961197 pos =cache_name_pos(dirname, len);1198if(pos <0)1199 pos = -pos-1;1200while(pos < active_nr) {1201const struct cache_entry *ce = active_cache[pos++];1202unsigned char endchar;12031204if(strncmp(ce->name, dirname, len))1205break;1206 endchar = ce->name[len];1207if(endchar >'/')1208break;1209if(endchar =='/')1210return index_directory;1211if(!endchar &&S_ISGITLINK(ce->ce_mode))1212return index_gitdir;1213}1214return index_nonexistent;1215}12161217/*1218 * When we find a directory when traversing the filesystem, we1219 * have three distinct cases:1220 *1221 * - ignore it1222 * - see it as a directory1223 * - recurse into it1224 *1225 * and which one we choose depends on a combination of existing1226 * git index contents and the flags passed into the directory1227 * traversal routine.1228 *1229 * Case 1: If we *already* have entries in the index under that1230 * directory name, we always recurse into the directory to see1231 * all the files.1232 *1233 * Case 2: If we *already* have that directory name as a gitlink,1234 * we always continue to see it as a gitlink, regardless of whether1235 * there is an actual git directory there or not (it might not1236 * be checked out as a subproject!)1237 *1238 * Case 3: if we didn't have it in the index previously, we1239 * have a few sub-cases:1240 *1241 * (a) if "show_other_directories" is true, we show it as1242 * just a directory, unless "hide_empty_directories" is1243 * also true, in which case we need to check if it contains any1244 * untracked and / or ignored files.1245 * (b) if it looks like a git directory, and we don't have1246 * 'no_gitlinks' set we treat it as a gitlink, and show it1247 * as a directory.1248 * (c) otherwise, we recurse into it.1249 */1250static enum path_treatment treat_directory(struct dir_struct *dir,1251struct untracked_cache_dir *untracked,1252const char*dirname,int len,int exclude,1253const struct path_simplify *simplify)1254{1255/* The "len-1" is to strip the final '/' */1256switch(directory_exists_in_index(dirname, len-1)) {1257case index_directory:1258return path_recurse;12591260case index_gitdir:1261return path_none;12621263case index_nonexistent:1264if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1265break;1266if(!(dir->flags & DIR_NO_GITLINKS)) {1267unsigned char sha1[20];1268if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1269return path_untracked;1270}1271return path_recurse;1272}12731274/* This is the "show_other_directories" case */12751276if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1277return exclude ? path_excluded : path_untracked;12781279 untracked =lookup_untracked(dir->untracked, untracked, dirname, len);1280returnread_directory_recursive(dir, dirname, len,1281 untracked,1, simplify);1282}12831284/*1285 * This is an inexact early pruning of any recursive directory1286 * reading - if the path cannot possibly be in the pathspec,1287 * return true, and we'll skip it early.1288 */1289static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1290{1291if(simplify) {1292for(;;) {1293const char*match = simplify->path;1294int len = simplify->len;12951296if(!match)1297break;1298if(len > pathlen)1299 len = pathlen;1300if(!memcmp(path, match, len))1301return0;1302 simplify++;1303}1304return1;1305}1306return0;1307}13081309/*1310 * This function tells us whether an excluded path matches a1311 * list of "interesting" pathspecs. That is, whether a path matched1312 * by any of the pathspecs could possibly be ignored by excluding1313 * the specified path. This can happen if:1314 *1315 * 1. the path is mentioned explicitly in the pathspec1316 *1317 * 2. the path is a directory prefix of some element in the1318 * pathspec1319 */1320static intexclude_matches_pathspec(const char*path,int len,1321const struct path_simplify *simplify)1322{1323if(simplify) {1324for(; simplify->path; simplify++) {1325if(len == simplify->len1326&& !memcmp(path, simplify->path, len))1327return1;1328if(len < simplify->len1329&& simplify->path[len] =='/'1330&& !memcmp(path, simplify->path, len))1331return1;1332}1333}1334return0;1335}13361337static intget_index_dtype(const char*path,int len)1338{1339int pos;1340const struct cache_entry *ce;13411342 ce =cache_file_exists(path, len,0);1343if(ce) {1344if(!ce_uptodate(ce))1345return DT_UNKNOWN;1346if(S_ISGITLINK(ce->ce_mode))1347return DT_DIR;1348/*1349 * Nobody actually cares about the1350 * difference between DT_LNK and DT_REG1351 */1352return DT_REG;1353}13541355/* Try to look it up as a directory */1356 pos =cache_name_pos(path, len);1357if(pos >=0)1358return DT_UNKNOWN;1359 pos = -pos-1;1360while(pos < active_nr) {1361 ce = active_cache[pos++];1362if(strncmp(ce->name, path, len))1363break;1364if(ce->name[len] >'/')1365break;1366if(ce->name[len] <'/')1367continue;1368if(!ce_uptodate(ce))1369break;/* continue? */1370return DT_DIR;1371}1372return DT_UNKNOWN;1373}13741375static intget_dtype(struct dirent *de,const char*path,int len)1376{1377int dtype = de ?DTYPE(de) : DT_UNKNOWN;1378struct stat st;13791380if(dtype != DT_UNKNOWN)1381return dtype;1382 dtype =get_index_dtype(path, len);1383if(dtype != DT_UNKNOWN)1384return dtype;1385if(lstat(path, &st))1386return dtype;1387if(S_ISREG(st.st_mode))1388return DT_REG;1389if(S_ISDIR(st.st_mode))1390return DT_DIR;1391if(S_ISLNK(st.st_mode))1392return DT_LNK;1393return dtype;1394}13951396static enum path_treatment treat_one_path(struct dir_struct *dir,1397struct untracked_cache_dir *untracked,1398struct strbuf *path,1399const struct path_simplify *simplify,1400int dtype,struct dirent *de)1401{1402int exclude;1403int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);14041405if(dtype == DT_UNKNOWN)1406 dtype =get_dtype(de, path->buf, path->len);14071408/* Always exclude indexed files */1409if(dtype != DT_DIR && has_path_in_index)1410return path_none;14111412/*1413 * When we are looking at a directory P in the working tree,1414 * there are three cases:1415 *1416 * (1) P exists in the index. Everything inside the directory P in1417 * the working tree needs to go when P is checked out from the1418 * index.1419 *1420 * (2) P does not exist in the index, but there is P/Q in the index.1421 * We know P will stay a directory when we check out the contents1422 * of the index, but we do not know yet if there is a directory1423 * P/Q in the working tree to be killed, so we need to recurse.1424 *1425 * (3) P does not exist in the index, and there is no P/Q in the index1426 * to require P to be a directory, either. Only in this case, we1427 * know that everything inside P will not be killed without1428 * recursing.1429 */1430if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1431(dtype == DT_DIR) &&1432!has_path_in_index &&1433(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1434return path_none;14351436 exclude =is_excluded(dir, path->buf, &dtype);14371438/*1439 * Excluded? If we don't explicitly want to show1440 * ignored files, ignore it1441 */1442if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1443return path_excluded;14441445switch(dtype) {1446default:1447return path_none;1448case DT_DIR:1449strbuf_addch(path,'/');1450returntreat_directory(dir, untracked, path->buf, path->len, exclude,1451 simplify);1452case DT_REG:1453case DT_LNK:1454return exclude ? path_excluded : path_untracked;1455}1456}14571458static enum path_treatment treat_path_fast(struct dir_struct *dir,1459struct untracked_cache_dir *untracked,1460struct cached_dir *cdir,1461struct strbuf *path,1462int baselen,1463const struct path_simplify *simplify)1464{1465strbuf_setlen(path, baselen);1466if(!cdir->ucd) {1467strbuf_addstr(path, cdir->file);1468return path_untracked;1469}1470strbuf_addstr(path, cdir->ucd->name);1471/* treat_one_path() does this before it calls treat_directory() */1472if(path->buf[path->len -1] !='/')1473strbuf_addch(path,'/');1474if(cdir->ucd->check_only)1475/*1476 * check_only is set as a result of treat_directory() getting1477 * to its bottom. Verify again the same set of directories1478 * with check_only set.1479 */1480returnread_directory_recursive(dir, path->buf, path->len,1481 cdir->ucd,1, simplify);1482/*1483 * We get path_recurse in the first run when1484 * directory_exists_in_index() returns index_nonexistent. We1485 * are sure that new changes in the index does not impact the1486 * outcome. Return now.1487 */1488return path_recurse;1489}14901491static enum path_treatment treat_path(struct dir_struct *dir,1492struct untracked_cache_dir *untracked,1493struct cached_dir *cdir,1494struct strbuf *path,1495int baselen,1496const struct path_simplify *simplify)1497{1498int dtype;1499struct dirent *de = cdir->de;15001501if(!de)1502returntreat_path_fast(dir, untracked, cdir, path,1503 baselen, simplify);1504if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1505return path_none;1506strbuf_setlen(path, baselen);1507strbuf_addstr(path, de->d_name);1508if(simplify_away(path->buf, path->len, simplify))1509return path_none;15101511 dtype =DTYPE(de);1512returntreat_one_path(dir, untracked, path, simplify, dtype, de);1513}15141515static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1516{1517if(!dir)1518return;1519ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1520 dir->untracked_alloc);1521 dir->untracked[dir->untracked_nr++] =xstrdup(name);1522}15231524static intvalid_cached_dir(struct dir_struct *dir,1525struct untracked_cache_dir *untracked,1526struct strbuf *path,1527int check_only)1528{1529struct stat st;15301531if(!untracked)1532return0;15331534if(stat(path->len ? path->buf :".", &st)) {1535invalidate_directory(dir->untracked, untracked);1536memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1537return0;1538}1539if(!untracked->valid ||1540match_stat_data(&untracked->stat_data, &st)) {1541if(untracked->valid)1542invalidate_directory(dir->untracked, untracked);1543fill_stat_data(&untracked->stat_data, &st);1544return0;1545}15461547if(untracked->check_only != !!check_only) {1548invalidate_directory(dir->untracked, untracked);1549return0;1550}15511552/*1553 * prep_exclude will be called eventually on this directory,1554 * but it's called much later in last_exclude_matching(). We1555 * need it now to determine the validity of the cache for this1556 * path. The next calls will be nearly no-op, the way1557 * prep_exclude() is designed.1558 */1559if(path->len && path->buf[path->len -1] !='/') {1560strbuf_addch(path,'/');1561prep_exclude(dir, path->buf, path->len);1562strbuf_setlen(path, path->len -1);1563}else1564prep_exclude(dir, path->buf, path->len);15651566/* hopefully prep_exclude() haven't invalidated this entry... */1567return untracked->valid;1568}15691570static intopen_cached_dir(struct cached_dir *cdir,1571struct dir_struct *dir,1572struct untracked_cache_dir *untracked,1573struct strbuf *path,1574int check_only)1575{1576memset(cdir,0,sizeof(*cdir));1577 cdir->untracked = untracked;1578if(valid_cached_dir(dir, untracked, path, check_only))1579return0;1580 cdir->fdir =opendir(path->len ? path->buf :".");1581if(dir->untracked)1582 dir->untracked->dir_opened++;1583if(!cdir->fdir)1584return-1;1585return0;1586}15871588static intread_cached_dir(struct cached_dir *cdir)1589{1590if(cdir->fdir) {1591 cdir->de =readdir(cdir->fdir);1592if(!cdir->de)1593return-1;1594return0;1595}1596while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1597struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1598if(!d->recurse) {1599 cdir->nr_dirs++;1600continue;1601}1602 cdir->ucd = d;1603 cdir->nr_dirs++;1604return0;1605}1606 cdir->ucd = NULL;1607if(cdir->nr_files < cdir->untracked->untracked_nr) {1608struct untracked_cache_dir *d = cdir->untracked;1609 cdir->file = d->untracked[cdir->nr_files++];1610return0;1611}1612return-1;1613}16141615static voidclose_cached_dir(struct cached_dir *cdir)1616{1617if(cdir->fdir)1618closedir(cdir->fdir);1619/*1620 * We have gone through this directory and found no untracked1621 * entries. Mark it valid.1622 */1623if(cdir->untracked) {1624 cdir->untracked->valid =1;1625 cdir->untracked->recurse =1;1626}1627}16281629/*1630 * Read a directory tree. We currently ignore anything but1631 * directories, regular files and symlinks. That's because git1632 * doesn't handle them at all yet. Maybe that will change some1633 * day.1634 *1635 * Also, we ignore the name ".git" (even if it is not a directory).1636 * That likely will not change.1637 *1638 * Returns the most significant path_treatment value encountered in the scan.1639 */1640static enum path_treatment read_directory_recursive(struct dir_struct *dir,1641const char*base,int baselen,1642struct untracked_cache_dir *untracked,int check_only,1643const struct path_simplify *simplify)1644{1645struct cached_dir cdir;1646enum path_treatment state, subdir_state, dir_state = path_none;1647struct strbuf path = STRBUF_INIT;16481649strbuf_add(&path, base, baselen);16501651if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1652goto out;16531654if(untracked)1655 untracked->check_only = !!check_only;16561657while(!read_cached_dir(&cdir)) {1658/* check how the file or directory should be treated */1659 state =treat_path(dir, untracked, &cdir, &path, baselen, simplify);16601661if(state > dir_state)1662 dir_state = state;16631664/* recurse into subdir if instructed by treat_path */1665if(state == path_recurse) {1666struct untracked_cache_dir *ud;1667 ud =lookup_untracked(dir->untracked, untracked,1668 path.buf + baselen,1669 path.len - baselen);1670 subdir_state =1671read_directory_recursive(dir, path.buf, path.len,1672 ud, check_only, simplify);1673if(subdir_state > dir_state)1674 dir_state = subdir_state;1675}16761677if(check_only) {1678/* abort early if maximum state has been reached */1679if(dir_state == path_untracked) {1680if(cdir.fdir)1681add_untracked(untracked, path.buf + baselen);1682break;1683}1684/* skip the dir_add_* part */1685continue;1686}16871688/* add the path to the appropriate result list */1689switch(state) {1690case path_excluded:1691if(dir->flags & DIR_SHOW_IGNORED)1692dir_add_name(dir, path.buf, path.len);1693else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1694((dir->flags & DIR_COLLECT_IGNORED) &&1695exclude_matches_pathspec(path.buf, path.len,1696 simplify)))1697dir_add_ignored(dir, path.buf, path.len);1698break;16991700case path_untracked:1701if(dir->flags & DIR_SHOW_IGNORED)1702break;1703dir_add_name(dir, path.buf, path.len);1704if(cdir.fdir)1705add_untracked(untracked, path.buf + baselen);1706break;17071708default:1709break;1710}1711}1712close_cached_dir(&cdir);1713 out:1714strbuf_release(&path);17151716return dir_state;1717}17181719static intcmp_name(const void*p1,const void*p2)1720{1721const struct dir_entry *e1 = *(const struct dir_entry **)p1;1722const struct dir_entry *e2 = *(const struct dir_entry **)p2;17231724returnname_compare(e1->name, e1->len, e2->name, e2->len);1725}17261727static struct path_simplify *create_simplify(const char**pathspec)1728{1729int nr, alloc =0;1730struct path_simplify *simplify = NULL;17311732if(!pathspec)1733return NULL;17341735for(nr =0; ; nr++) {1736const char*match;1737ALLOC_GROW(simplify, nr +1, alloc);1738 match = *pathspec++;1739if(!match)1740break;1741 simplify[nr].path = match;1742 simplify[nr].len =simple_length(match);1743}1744 simplify[nr].path = NULL;1745 simplify[nr].len =0;1746return simplify;1747}17481749static voidfree_simplify(struct path_simplify *simplify)1750{1751free(simplify);1752}17531754static inttreat_leading_path(struct dir_struct *dir,1755const char*path,int len,1756const struct path_simplify *simplify)1757{1758struct strbuf sb = STRBUF_INIT;1759int baselen, rc =0;1760const char*cp;1761int old_flags = dir->flags;17621763while(len && path[len -1] =='/')1764 len--;1765if(!len)1766return1;1767 baselen =0;1768 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1769while(1) {1770 cp = path + baselen + !!baselen;1771 cp =memchr(cp,'/', path + len - cp);1772if(!cp)1773 baselen = len;1774else1775 baselen = cp - path;1776strbuf_setlen(&sb,0);1777strbuf_add(&sb, path, baselen);1778if(!is_directory(sb.buf))1779break;1780if(simplify_away(sb.buf, sb.len, simplify))1781break;1782if(treat_one_path(dir, NULL, &sb, simplify,1783 DT_DIR, NULL) == path_none)1784break;/* do not recurse into it */1785if(len <= baselen) {1786 rc =1;1787break;/* finished checking */1788}1789}1790strbuf_release(&sb);1791 dir->flags = old_flags;1792return rc;1793}17941795static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1796int base_len,1797const struct pathspec *pathspec)1798{1799struct untracked_cache_dir *root;1800int i;18011802if(!dir->untracked)1803return NULL;18041805/*1806 * We only support $GIT_DIR/info/exclude and core.excludesfile1807 * as the global ignore rule files. Any other additions1808 * (e.g. from command line) invalidate the cache. This1809 * condition also catches running setup_standard_excludes()1810 * before setting dir->untracked!1811 */1812if(dir->unmanaged_exclude_files)1813return NULL;18141815/*1816 * Optimize for the main use case only: whole-tree git1817 * status. More work involved in treat_leading_path() if we1818 * use cache on just a subset of the worktree. pathspec1819 * support could make the matter even worse.1820 */1821if(base_len || (pathspec && pathspec->nr))1822return NULL;18231824/* Different set of flags may produce different results */1825if(dir->flags != dir->untracked->dir_flags ||1826/*1827 * See treat_directory(), case index_nonexistent. Without1828 * this flag, we may need to also cache .git file content1829 * for the resolve_gitlink_ref() call, which we don't.1830 */1831!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1832/* We don't support collecting ignore files */1833(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1834 DIR_COLLECT_IGNORED)))1835return NULL;18361837/*1838 * If we use .gitignore in the cache and now you change it to1839 * .gitexclude, everything will go wrong.1840 */1841if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1842strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1843return NULL;18441845/*1846 * EXC_CMDL is not considered in the cache. If people set it,1847 * skip the cache.1848 */1849if(dir->exclude_list_group[EXC_CMDL].nr)1850return NULL;18511852/*1853 * An optimization in prep_exclude() does not play well with1854 * CE_SKIP_WORKTREE. It's a rare case anyway, if a single1855 * entry has that bit set, disable the whole untracked cache.1856 */1857for(i =0; i < active_nr; i++)1858if(ce_skip_worktree(active_cache[i]))1859return NULL;18601861if(!dir->untracked->root) {1862const int len =sizeof(*dir->untracked->root);1863 dir->untracked->root =xmalloc(len);1864memset(dir->untracked->root,0, len);1865}18661867/* Validate $GIT_DIR/info/exclude and core.excludesfile */1868 root = dir->untracked->root;1869if(hashcmp(dir->ss_info_exclude.sha1,1870 dir->untracked->ss_info_exclude.sha1)) {1871invalidate_gitignore(dir->untracked, root);1872 dir->untracked->ss_info_exclude = dir->ss_info_exclude;1873}1874if(hashcmp(dir->ss_excludes_file.sha1,1875 dir->untracked->ss_excludes_file.sha1)) {1876invalidate_gitignore(dir->untracked, root);1877 dir->untracked->ss_excludes_file = dir->ss_excludes_file;1878}18791880/* Make sure this directory is not dropped out at saving phase */1881 root->recurse =1;1882return root;1883}18841885intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)1886{1887struct path_simplify *simplify;1888struct untracked_cache_dir *untracked;18891890/*1891 * Check out create_simplify()1892 */1893if(pathspec)1894GUARD_PATHSPEC(pathspec,1895 PATHSPEC_FROMTOP |1896 PATHSPEC_MAXDEPTH |1897 PATHSPEC_LITERAL |1898 PATHSPEC_GLOB |1899 PATHSPEC_ICASE |1900 PATHSPEC_EXCLUDE);19011902if(has_symlink_leading_path(path, len))1903return dir->nr;19041905/*1906 * exclude patterns are treated like positive ones in1907 * create_simplify. Usually exclude patterns should be a1908 * subset of positive ones, which has no impacts on1909 * create_simplify().1910 */1911 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);1912 untracked =validate_untracked_cache(dir, len, pathspec);1913if(!untracked)1914/*1915 * make sure untracked cache code path is disabled,1916 * e.g. prep_exclude()1917 */1918 dir->untracked = NULL;1919if(!len ||treat_leading_path(dir, path, len, simplify))1920read_directory_recursive(dir, path, len, untracked,0, simplify);1921free_simplify(simplify);1922qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);1923qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);1924return dir->nr;1925}19261927intfile_exists(const char*f)1928{1929struct stat sb;1930returnlstat(f, &sb) ==0;1931}19321933/*1934 * Given two normalized paths (a trailing slash is ok), if subdir is1935 * outside dir, return -1. Otherwise return the offset in subdir that1936 * can be used as relative path to dir.1937 */1938intdir_inside_of(const char*subdir,const char*dir)1939{1940int offset =0;19411942assert(dir && subdir && *dir && *subdir);19431944while(*dir && *subdir && *dir == *subdir) {1945 dir++;1946 subdir++;1947 offset++;1948}19491950/* hel[p]/me vs hel[l]/yeah */1951if(*dir && *subdir)1952return-1;19531954if(!*subdir)1955return!*dir ? offset : -1;/* same dir */19561957/* foo/[b]ar vs foo/[] */1958if(is_dir_sep(dir[-1]))1959returnis_dir_sep(subdir[-1]) ? offset : -1;19601961/* foo[/]bar vs foo[] */1962returnis_dir_sep(*subdir) ? offset +1: -1;1963}19641965intis_inside_dir(const char*dir)1966{1967char*cwd;1968int rc;19691970if(!dir)1971return0;19721973 cwd =xgetcwd();1974 rc = (dir_inside_of(cwd, dir) >=0);1975free(cwd);1976return rc;1977}19781979intis_empty_dir(const char*path)1980{1981DIR*dir =opendir(path);1982struct dirent *e;1983int ret =1;19841985if(!dir)1986return0;19871988while((e =readdir(dir)) != NULL)1989if(!is_dot_or_dotdot(e->d_name)) {1990 ret =0;1991break;1992}19931994closedir(dir);1995return ret;1996}19971998static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)1999{2000DIR*dir;2001struct dirent *e;2002int ret =0, original_len = path->len, len, kept_down =0;2003int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2004int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2005unsigned char submodule_head[20];20062007if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2008!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2009/* Do not descend and nuke a nested git work tree. */2010if(kept_up)2011*kept_up =1;2012return0;2013}20142015 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2016 dir =opendir(path->buf);2017if(!dir) {2018if(errno == ENOENT)2019return keep_toplevel ? -1:0;2020else if(errno == EACCES && !keep_toplevel)2021/*2022 * An empty dir could be removable even if it2023 * is unreadable:2024 */2025returnrmdir(path->buf);2026else2027return-1;2028}2029if(path->buf[original_len -1] !='/')2030strbuf_addch(path,'/');20312032 len = path->len;2033while((e =readdir(dir)) != NULL) {2034struct stat st;2035if(is_dot_or_dotdot(e->d_name))2036continue;20372038strbuf_setlen(path, len);2039strbuf_addstr(path, e->d_name);2040if(lstat(path->buf, &st)) {2041if(errno == ENOENT)2042/*2043 * file disappeared, which is what we2044 * wanted anyway2045 */2046continue;2047/* fall thru */2048}else if(S_ISDIR(st.st_mode)) {2049if(!remove_dir_recurse(path, flag, &kept_down))2050continue;/* happy */2051}else if(!only_empty &&2052(!unlink(path->buf) || errno == ENOENT)) {2053continue;/* happy, too */2054}20552056/* path too long, stat fails, or non-directory still exists */2057 ret = -1;2058break;2059}2060closedir(dir);20612062strbuf_setlen(path, original_len);2063if(!ret && !keep_toplevel && !kept_down)2064 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2065else if(kept_up)2066/*2067 * report the uplevel that it is not an error that we2068 * did not rmdir() our directory.2069 */2070*kept_up = !ret;2071return ret;2072}20732074intremove_dir_recursively(struct strbuf *path,int flag)2075{2076returnremove_dir_recurse(path, flag, NULL);2077}20782079voidsetup_standard_excludes(struct dir_struct *dir)2080{2081const char*path;2082char*xdg_path;20832084 dir->exclude_per_dir =".gitignore";2085 path =git_path("info/exclude");2086if(!excludes_file) {2087home_config_paths(NULL, &xdg_path,"ignore");2088 excludes_file = xdg_path;2089}2090if(!access_or_warn(path, R_OK,0))2091add_excludes_from_file_1(dir, path,2092 dir->untracked ? &dir->ss_info_exclude : NULL);2093if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2094add_excludes_from_file_1(dir, excludes_file,2095 dir->untracked ? &dir->ss_excludes_file : NULL);2096}20972098intremove_path(const char*name)2099{2100char*slash;21012102if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2103return-1;21042105 slash =strrchr(name,'/');2106if(slash) {2107char*dirs =xstrdup(name);2108 slash = dirs + (slash - name);2109do{2110*slash ='\0';2111}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2112free(dirs);2113}2114return0;2115}21162117/*2118 * Frees memory within dir which was allocated for exclude lists and2119 * the exclude_stack. Does not free dir itself.2120 */2121voidclear_directory(struct dir_struct *dir)2122{2123int i, j;2124struct exclude_list_group *group;2125struct exclude_list *el;2126struct exclude_stack *stk;21272128for(i = EXC_CMDL; i <= EXC_FILE; i++) {2129 group = &dir->exclude_list_group[i];2130for(j =0; j < group->nr; j++) {2131 el = &group->el[j];2132if(i == EXC_DIRS)2133free((char*)el->src);2134clear_exclude_list(el);2135}2136free(group->el);2137}21382139 stk = dir->exclude_stack;2140while(stk) {2141struct exclude_stack *prev = stk->prev;2142free(stk);2143 stk = prev;2144}2145strbuf_release(&dir->basebuf);2146}