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 34static enum path_treatment read_directory_recursive(struct dir_struct *dir, 35const char*path,int len,struct untracked_cache_dir *untracked, 36int check_only,const struct path_simplify *simplify); 37static intget_dtype(struct dirent *de,const char*path,int len); 38 39/* helper string functions with support for the ignore_case flag */ 40intstrcmp_icase(const char*a,const char*b) 41{ 42return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 43} 44 45intstrncmp_icase(const char*a,const char*b,size_t count) 46{ 47return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 48} 49 50intfnmatch_icase(const char*pattern,const char*string,int flags) 51{ 52returnwildmatch(pattern, string, 53 flags | (ignore_case ? WM_CASEFOLD :0), 54 NULL); 55} 56 57intgit_fnmatch(const struct pathspec_item *item, 58const char*pattern,const char*string, 59int prefix) 60{ 61if(prefix >0) { 62if(ps_strncmp(item, pattern, string, prefix)) 63return WM_NOMATCH; 64 pattern += prefix; 65 string += prefix; 66} 67if(item->flags & PATHSPEC_ONESTAR) { 68int pattern_len =strlen(++pattern); 69int string_len =strlen(string); 70return string_len < pattern_len || 71ps_strcmp(item, pattern, 72 string + string_len - pattern_len); 73} 74if(item->magic & PATHSPEC_GLOB) 75returnwildmatch(pattern, string, 76 WM_PATHNAME | 77(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 78 NULL); 79else 80/* wildmatch has not learned no FNM_PATHNAME mode yet */ 81returnwildmatch(pattern, string, 82 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 83 NULL); 84} 85 86static intfnmatch_icase_mem(const char*pattern,int patternlen, 87const char*string,int stringlen, 88int flags) 89{ 90int match_status; 91struct strbuf pat_buf = STRBUF_INIT; 92struct strbuf str_buf = STRBUF_INIT; 93const char*use_pat = pattern; 94const char*use_str = string; 95 96if(pattern[patternlen]) { 97strbuf_add(&pat_buf, pattern, patternlen); 98 use_pat = pat_buf.buf; 99} 100if(string[stringlen]) { 101strbuf_add(&str_buf, string, stringlen); 102 use_str = str_buf.buf; 103} 104 105if(ignore_case) 106 flags |= WM_CASEFOLD; 107 match_status =wildmatch(use_pat, use_str, flags, NULL); 108 109strbuf_release(&pat_buf); 110strbuf_release(&str_buf); 111 112return match_status; 113} 114 115static size_tcommon_prefix_len(const struct pathspec *pathspec) 116{ 117int n; 118size_t max =0; 119 120/* 121 * ":(icase)path" is treated as a pathspec full of 122 * wildcard. In other words, only prefix is considered common 123 * prefix. If the pathspec is abc/foo abc/bar, running in 124 * subdir xyz, the common prefix is still xyz, not xuz/abc as 125 * in non-:(icase). 126 */ 127GUARD_PATHSPEC(pathspec, 128 PATHSPEC_FROMTOP | 129 PATHSPEC_MAXDEPTH | 130 PATHSPEC_LITERAL | 131 PATHSPEC_GLOB | 132 PATHSPEC_ICASE | 133 PATHSPEC_EXCLUDE); 134 135for(n =0; n < pathspec->nr; n++) { 136size_t i =0, len =0, item_len; 137if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 138continue; 139if(pathspec->items[n].magic & PATHSPEC_ICASE) 140 item_len = pathspec->items[n].prefix; 141else 142 item_len = pathspec->items[n].nowildcard_len; 143while(i < item_len && (n ==0|| i < max)) { 144char c = pathspec->items[n].match[i]; 145if(c != pathspec->items[0].match[i]) 146break; 147if(c =='/') 148 len = i +1; 149 i++; 150} 151if(n ==0|| len < max) { 152 max = len; 153if(!max) 154break; 155} 156} 157return max; 158} 159 160/* 161 * Returns a copy of the longest leading path common among all 162 * pathspecs. 163 */ 164char*common_prefix(const struct pathspec *pathspec) 165{ 166unsigned long len =common_prefix_len(pathspec); 167 168return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 169} 170 171intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 172{ 173size_t len; 174 175/* 176 * Calculate common prefix for the pathspec, and 177 * use that to optimize the directory walk 178 */ 179 len =common_prefix_len(pathspec); 180 181/* Read the directory and prune it */ 182read_directory(dir, pathspec->nr ? pathspec->_raw[0] :"", len, pathspec); 183return len; 184} 185 186intwithin_depth(const char*name,int namelen, 187int depth,int max_depth) 188{ 189const char*cp = name, *cpe = name + namelen; 190 191while(cp < cpe) { 192if(*cp++ !='/') 193continue; 194 depth++; 195if(depth > max_depth) 196return0; 197} 198return1; 199} 200 201#define DO_MATCH_EXCLUDE 1 202#define DO_MATCH_DIRECTORY 2 203 204/* 205 * Does 'match' match the given name? 206 * A match is found if 207 * 208 * (1) the 'match' string is leading directory of 'name', or 209 * (2) the 'match' string is a wildcard and matches 'name', or 210 * (3) the 'match' string is exactly the same as 'name'. 211 * 212 * and the return value tells which case it was. 213 * 214 * It returns 0 when there is no match. 215 */ 216static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 217const char*name,int namelen,unsigned flags) 218{ 219/* name/namelen has prefix cut off by caller */ 220const char*match = item->match + prefix; 221int matchlen = item->len - prefix; 222 223/* 224 * The normal call pattern is: 225 * 1. prefix = common_prefix_len(ps); 226 * 2. prune something, or fill_directory 227 * 3. match_pathspec() 228 * 229 * 'prefix' at #1 may be shorter than the command's prefix and 230 * it's ok for #2 to match extra files. Those extras will be 231 * trimmed at #3. 232 * 233 * Suppose the pathspec is 'foo' and '../bar' running from 234 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 235 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 236 * user does not want XYZ/foo, only the "foo" part should be 237 * case-insensitive. We need to filter out XYZ/foo here. In 238 * other words, we do not trust the caller on comparing the 239 * prefix part when :(icase) is involved. We do exact 240 * comparison ourselves. 241 * 242 * Normally the caller (common_prefix_len() in fact) does 243 * _exact_ matching on name[-prefix+1..-1] and we do not need 244 * to check that part. Be defensive and check it anyway, in 245 * case common_prefix_len is changed, or a new caller is 246 * introduced that does not use common_prefix_len. 247 * 248 * If the penalty turns out too high when prefix is really 249 * long, maybe change it to 250 * strncmp(match, name, item->prefix - prefix) 251 */ 252if(item->prefix && (item->magic & PATHSPEC_ICASE) && 253strncmp(item->match, name - prefix, item->prefix)) 254return0; 255 256/* If the match was just the prefix, we matched */ 257if(!*match) 258return MATCHED_RECURSIVELY; 259 260if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 261if(matchlen == namelen) 262return MATCHED_EXACTLY; 263 264if(match[matchlen-1] =='/'|| name[matchlen] =='/') 265return MATCHED_RECURSIVELY; 266}else if((flags & DO_MATCH_DIRECTORY) && 267 match[matchlen -1] =='/'&& 268 namelen == matchlen -1&& 269!ps_strncmp(item, match, name, namelen)) 270return MATCHED_EXACTLY; 271 272if(item->nowildcard_len < item->len && 273!git_fnmatch(item, match, name, 274 item->nowildcard_len - prefix)) 275return MATCHED_FNMATCH; 276 277return0; 278} 279 280/* 281 * Given a name and a list of pathspecs, returns the nature of the 282 * closest (i.e. most specific) match of the name to any of the 283 * pathspecs. 284 * 285 * The caller typically calls this multiple times with the same 286 * pathspec and seen[] array but with different name/namelen 287 * (e.g. entries from the index) and is interested in seeing if and 288 * how each pathspec matches all the names it calls this function 289 * with. A mark is left in the seen[] array for each pathspec element 290 * indicating the closest type of match that element achieved, so if 291 * seen[n] remains zero after multiple invocations, that means the nth 292 * pathspec did not match any names, which could indicate that the 293 * user mistyped the nth pathspec. 294 */ 295static intdo_match_pathspec(const struct pathspec *ps, 296const char*name,int namelen, 297int prefix,char*seen, 298unsigned flags) 299{ 300int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 301 302GUARD_PATHSPEC(ps, 303 PATHSPEC_FROMTOP | 304 PATHSPEC_MAXDEPTH | 305 PATHSPEC_LITERAL | 306 PATHSPEC_GLOB | 307 PATHSPEC_ICASE | 308 PATHSPEC_EXCLUDE); 309 310if(!ps->nr) { 311if(!ps->recursive || 312!(ps->magic & PATHSPEC_MAXDEPTH) || 313 ps->max_depth == -1) 314return MATCHED_RECURSIVELY; 315 316if(within_depth(name, namelen,0, ps->max_depth)) 317return MATCHED_EXACTLY; 318else 319return0; 320} 321 322 name += prefix; 323 namelen -= prefix; 324 325for(i = ps->nr -1; i >=0; i--) { 326int how; 327 328if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 329( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 330continue; 331 332if(seen && seen[i] == MATCHED_EXACTLY) 333continue; 334/* 335 * Make exclude patterns optional and never report 336 * "pathspec ':(exclude)foo' matches no files" 337 */ 338if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 339 seen[i] = MATCHED_FNMATCH; 340 how =match_pathspec_item(ps->items+i, prefix, name, 341 namelen, flags); 342if(ps->recursive && 343(ps->magic & PATHSPEC_MAXDEPTH) && 344 ps->max_depth != -1&& 345 how && how != MATCHED_FNMATCH) { 346int len = ps->items[i].len; 347if(name[len] =='/') 348 len++; 349if(within_depth(name+len, namelen-len,0, ps->max_depth)) 350 how = MATCHED_EXACTLY; 351else 352 how =0; 353} 354if(how) { 355if(retval < how) 356 retval = how; 357if(seen && seen[i] < how) 358 seen[i] = how; 359} 360} 361return retval; 362} 363 364intmatch_pathspec(const struct pathspec *ps, 365const char*name,int namelen, 366int prefix,char*seen,int is_dir) 367{ 368int positive, negative; 369unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 370 positive =do_match_pathspec(ps, name, namelen, 371 prefix, seen, flags); 372if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 373return positive; 374 negative =do_match_pathspec(ps, name, namelen, 375 prefix, seen, 376 flags | DO_MATCH_EXCLUDE); 377return negative ?0: positive; 378} 379 380/* 381 * Return the length of the "simple" part of a path match limiter. 382 */ 383intsimple_length(const char*match) 384{ 385int len = -1; 386 387for(;;) { 388unsigned char c = *match++; 389 len++; 390if(c =='\0'||is_glob_special(c)) 391return len; 392} 393} 394 395intno_wildcard(const char*string) 396{ 397return string[simple_length(string)] =='\0'; 398} 399 400voidparse_exclude_pattern(const char**pattern, 401int*patternlen, 402int*flags, 403int*nowildcardlen) 404{ 405const char*p = *pattern; 406size_t i, len; 407 408*flags =0; 409if(*p =='!') { 410*flags |= EXC_FLAG_NEGATIVE; 411 p++; 412} 413 len =strlen(p); 414if(len && p[len -1] =='/') { 415 len--; 416*flags |= EXC_FLAG_MUSTBEDIR; 417} 418for(i =0; i < len; i++) { 419if(p[i] =='/') 420break; 421} 422if(i == len) 423*flags |= EXC_FLAG_NODIR; 424*nowildcardlen =simple_length(p); 425/* 426 * we should have excluded the trailing slash from 'p' too, 427 * but that's one more allocation. Instead just make sure 428 * nowildcardlen does not exceed real patternlen 429 */ 430if(*nowildcardlen > len) 431*nowildcardlen = len; 432if(*p =='*'&&no_wildcard(p +1)) 433*flags |= EXC_FLAG_ENDSWITH; 434*pattern = p; 435*patternlen = len; 436} 437 438voidadd_exclude(const char*string,const char*base, 439int baselen,struct exclude_list *el,int srcpos) 440{ 441struct exclude *x; 442int patternlen; 443int flags; 444int nowildcardlen; 445 446parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 447if(flags & EXC_FLAG_MUSTBEDIR) { 448char*s; 449 x =xmalloc(sizeof(*x) + patternlen +1); 450 s = (char*)(x+1); 451memcpy(s, string, patternlen); 452 s[patternlen] ='\0'; 453 x->pattern = s; 454}else{ 455 x =xmalloc(sizeof(*x)); 456 x->pattern = string; 457} 458 x->patternlen = patternlen; 459 x->nowildcardlen = nowildcardlen; 460 x->base = base; 461 x->baselen = baselen; 462 x->flags = flags; 463 x->srcpos = srcpos; 464ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 465 el->excludes[el->nr++] = x; 466 x->el = el; 467} 468 469static void*read_skip_worktree_file_from_index(const char*path,size_t*size, 470struct sha1_stat *sha1_stat) 471{ 472int pos, len; 473unsigned long sz; 474enum object_type type; 475void*data; 476 477 len =strlen(path); 478 pos =cache_name_pos(path, len); 479if(pos <0) 480return NULL; 481if(!ce_skip_worktree(active_cache[pos])) 482return NULL; 483 data =read_sha1_file(active_cache[pos]->sha1, &type, &sz); 484if(!data || type != OBJ_BLOB) { 485free(data); 486return NULL; 487} 488*size =xsize_t(sz); 489if(sha1_stat) { 490memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 491hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 492} 493return data; 494} 495 496/* 497 * Frees memory within el which was allocated for exclude patterns and 498 * the file buffer. Does not free el itself. 499 */ 500voidclear_exclude_list(struct exclude_list *el) 501{ 502int i; 503 504for(i =0; i < el->nr; i++) 505free(el->excludes[i]); 506free(el->excludes); 507free(el->filebuf); 508 509 el->nr =0; 510 el->excludes = NULL; 511 el->filebuf = NULL; 512} 513 514static voidtrim_trailing_spaces(char*buf) 515{ 516char*p, *last_space = NULL; 517 518for(p = buf; *p; p++) 519switch(*p) { 520case' ': 521if(!last_space) 522 last_space = p; 523break; 524case'\\': 525 p++; 526if(!*p) 527return; 528/* fallthrough */ 529default: 530 last_space = NULL; 531} 532 533if(last_space) 534*last_space ='\0'; 535} 536 537/* 538 * Given a subdirectory name and "dir" of the current directory, 539 * search the subdir in "dir" and return it, or create a new one if it 540 * does not exist in "dir". 541 * 542 * If "name" has the trailing slash, it'll be excluded in the search. 543 */ 544static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 545struct untracked_cache_dir *dir, 546const char*name,int len) 547{ 548int first, last; 549struct untracked_cache_dir *d; 550if(!dir) 551return NULL; 552if(len && name[len -1] =='/') 553 len--; 554 first =0; 555 last = dir->dirs_nr; 556while(last > first) { 557int cmp, next = (last + first) >>1; 558 d = dir->dirs[next]; 559 cmp =strncmp(name, d->name, len); 560if(!cmp &&strlen(d->name) > len) 561 cmp = -1; 562if(!cmp) 563return d; 564if(cmp <0) { 565 last = next; 566continue; 567} 568 first = next+1; 569} 570 571 uc->dir_created++; 572 d =xmalloc(sizeof(*d) + len +1); 573memset(d,0,sizeof(*d)); 574memcpy(d->name, name, len); 575 d->name[len] ='\0'; 576 577ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 578memmove(dir->dirs + first +1, dir->dirs + first, 579(dir->dirs_nr - first) *sizeof(*dir->dirs)); 580 dir->dirs_nr++; 581 dir->dirs[first] = d; 582return d; 583} 584 585static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 586{ 587int i; 588 dir->valid =0; 589 dir->untracked_nr =0; 590for(i =0; i < dir->dirs_nr; i++) 591do_invalidate_gitignore(dir->dirs[i]); 592} 593 594static voidinvalidate_gitignore(struct untracked_cache *uc, 595struct untracked_cache_dir *dir) 596{ 597 uc->gitignore_invalidated++; 598do_invalidate_gitignore(dir); 599} 600 601/* 602 * Given a file with name "fname", read it (either from disk, or from 603 * the index if "check_index" is non-zero), parse it and store the 604 * exclude rules in "el". 605 * 606 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 607 * stat data from disk (only valid if add_excludes returns zero). If 608 * ss_valid is non-zero, "ss" must contain good value as input. 609 */ 610static intadd_excludes(const char*fname,const char*base,int baselen, 611struct exclude_list *el,int check_index, 612struct sha1_stat *sha1_stat) 613{ 614struct stat st; 615int fd, i, lineno =1; 616size_t size =0; 617char*buf, *entry; 618 619 fd =open(fname, O_RDONLY); 620if(fd <0||fstat(fd, &st) <0) { 621if(errno != ENOENT) 622warn_on_inaccessible(fname); 623if(0<= fd) 624close(fd); 625if(!check_index || 626(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 627return-1; 628if(size ==0) { 629free(buf); 630return0; 631} 632if(buf[size-1] !='\n') { 633 buf =xrealloc(buf, size+1); 634 buf[size++] ='\n'; 635} 636}else{ 637 size =xsize_t(st.st_size); 638if(size ==0) { 639if(sha1_stat) { 640fill_stat_data(&sha1_stat->stat, &st); 641hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 642 sha1_stat->valid =1; 643} 644close(fd); 645return0; 646} 647 buf =xmalloc(size+1); 648if(read_in_full(fd, buf, size) != size) { 649free(buf); 650close(fd); 651return-1; 652} 653 buf[size++] ='\n'; 654close(fd); 655if(sha1_stat) { 656int pos; 657if(sha1_stat->valid && 658!match_stat_data(&sha1_stat->stat, &st)) 659;/* no content change, ss->sha1 still good */ 660else if(check_index && 661(pos =cache_name_pos(fname,strlen(fname))) >=0&& 662!ce_stage(active_cache[pos]) && 663ce_uptodate(active_cache[pos]) && 664!would_convert_to_git(fname)) 665hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 666else 667hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 668fill_stat_data(&sha1_stat->stat, &st); 669 sha1_stat->valid =1; 670} 671} 672 673 el->filebuf = buf; 674 entry = buf; 675for(i =0; i < size; i++) { 676if(buf[i] =='\n') { 677if(entry != buf + i && entry[0] !='#') { 678 buf[i - (i && buf[i-1] =='\r')] =0; 679trim_trailing_spaces(entry); 680add_exclude(entry, base, baselen, el, lineno); 681} 682 lineno++; 683 entry = buf + i +1; 684} 685} 686return0; 687} 688 689intadd_excludes_from_file_to_list(const char*fname,const char*base, 690int baselen,struct exclude_list *el, 691int check_index) 692{ 693returnadd_excludes(fname, base, baselen, el, check_index, NULL); 694} 695 696struct exclude_list *add_exclude_list(struct dir_struct *dir, 697int group_type,const char*src) 698{ 699struct exclude_list *el; 700struct exclude_list_group *group; 701 702 group = &dir->exclude_list_group[group_type]; 703ALLOC_GROW(group->el, group->nr +1, group->alloc); 704 el = &group->el[group->nr++]; 705memset(el,0,sizeof(*el)); 706 el->src = src; 707return el; 708} 709 710/* 711 * Used to set up core.excludesfile and .git/info/exclude lists. 712 */ 713static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 714struct sha1_stat *sha1_stat) 715{ 716struct exclude_list *el; 717/* 718 * catch setup_standard_excludes() that's called before 719 * dir->untracked is assigned. That function behaves 720 * differently when dir->untracked is non-NULL. 721 */ 722if(!dir->untracked) 723 dir->unmanaged_exclude_files++; 724 el =add_exclude_list(dir, EXC_FILE, fname); 725if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 726die("cannot use%sas an exclude file", fname); 727} 728 729voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 730{ 731 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 732add_excludes_from_file_1(dir, fname, NULL); 733} 734 735intmatch_basename(const char*basename,int basenamelen, 736const char*pattern,int prefix,int patternlen, 737int flags) 738{ 739if(prefix == patternlen) { 740if(patternlen == basenamelen && 741!strncmp_icase(pattern, basename, basenamelen)) 742return1; 743}else if(flags & EXC_FLAG_ENDSWITH) { 744/* "*literal" matching against "fooliteral" */ 745if(patternlen -1<= basenamelen && 746!strncmp_icase(pattern +1, 747 basename + basenamelen - (patternlen -1), 748 patternlen -1)) 749return1; 750}else{ 751if(fnmatch_icase_mem(pattern, patternlen, 752 basename, basenamelen, 7530) ==0) 754return1; 755} 756return0; 757} 758 759intmatch_pathname(const char*pathname,int pathlen, 760const char*base,int baselen, 761const char*pattern,int prefix,int patternlen, 762int flags) 763{ 764const char*name; 765int namelen; 766 767/* 768 * match with FNM_PATHNAME; the pattern has base implicitly 769 * in front of it. 770 */ 771if(*pattern =='/') { 772 pattern++; 773 patternlen--; 774 prefix--; 775} 776 777/* 778 * baselen does not count the trailing slash. base[] may or 779 * may not end with a trailing slash though. 780 */ 781if(pathlen < baselen +1|| 782(baselen && pathname[baselen] !='/') || 783strncmp_icase(pathname, base, baselen)) 784return0; 785 786 namelen = baselen ? pathlen - baselen -1: pathlen; 787 name = pathname + pathlen - namelen; 788 789if(prefix) { 790/* 791 * if the non-wildcard part is longer than the 792 * remaining pathname, surely it cannot match. 793 */ 794if(prefix > namelen) 795return0; 796 797if(strncmp_icase(pattern, name, prefix)) 798return0; 799 pattern += prefix; 800 patternlen -= prefix; 801 name += prefix; 802 namelen -= prefix; 803 804/* 805 * If the whole pattern did not have a wildcard, 806 * then our prefix match is all we need; we 807 * do not need to call fnmatch at all. 808 */ 809if(!patternlen && !namelen) 810return1; 811} 812 813returnfnmatch_icase_mem(pattern, patternlen, 814 name, namelen, 815 WM_PATHNAME) ==0; 816} 817 818/* 819 * Scan the given exclude list in reverse to see whether pathname 820 * should be ignored. The first match (i.e. the last on the list), if 821 * any, determines the fate. Returns the exclude_list element which 822 * matched, or NULL for undecided. 823 */ 824static struct exclude *last_exclude_matching_from_list(const char*pathname, 825int pathlen, 826const char*basename, 827int*dtype, 828struct exclude_list *el) 829{ 830int i; 831 832if(!el->nr) 833return NULL;/* undefined */ 834 835for(i = el->nr -1;0<= i; i--) { 836struct exclude *x = el->excludes[i]; 837const char*exclude = x->pattern; 838int prefix = x->nowildcardlen; 839 840if(x->flags & EXC_FLAG_MUSTBEDIR) { 841if(*dtype == DT_UNKNOWN) 842*dtype =get_dtype(NULL, pathname, pathlen); 843if(*dtype != DT_DIR) 844continue; 845} 846 847if(x->flags & EXC_FLAG_NODIR) { 848if(match_basename(basename, 849 pathlen - (basename - pathname), 850 exclude, prefix, x->patternlen, 851 x->flags)) 852return x; 853continue; 854} 855 856assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 857if(match_pathname(pathname, pathlen, 858 x->base, x->baselen ? x->baselen -1:0, 859 exclude, prefix, x->patternlen, x->flags)) 860return x; 861} 862return NULL;/* undecided */ 863} 864 865/* 866 * Scan the list and let the last match determine the fate. 867 * Return 1 for exclude, 0 for include and -1 for undecided. 868 */ 869intis_excluded_from_list(const char*pathname, 870int pathlen,const char*basename,int*dtype, 871struct exclude_list *el) 872{ 873struct exclude *exclude; 874 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 875if(exclude) 876return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 877return-1;/* undecided */ 878} 879 880static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 881const char*pathname,int pathlen,const char*basename, 882int*dtype_p) 883{ 884int i, j; 885struct exclude_list_group *group; 886struct exclude *exclude; 887for(i = EXC_CMDL; i <= EXC_FILE; i++) { 888 group = &dir->exclude_list_group[i]; 889for(j = group->nr -1; j >=0; j--) { 890 exclude =last_exclude_matching_from_list( 891 pathname, pathlen, basename, dtype_p, 892&group->el[j]); 893if(exclude) 894return exclude; 895} 896} 897return NULL; 898} 899 900/* 901 * Loads the per-directory exclude list for the substring of base 902 * which has a char length of baselen. 903 */ 904static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen) 905{ 906struct exclude_list_group *group; 907struct exclude_list *el; 908struct exclude_stack *stk = NULL; 909struct untracked_cache_dir *untracked; 910int current; 911 912 group = &dir->exclude_list_group[EXC_DIRS]; 913 914/* 915 * Pop the exclude lists from the EXCL_DIRS exclude_list_group 916 * which originate from directories not in the prefix of the 917 * path being checked. 918 */ 919while((stk = dir->exclude_stack) != NULL) { 920if(stk->baselen <= baselen && 921!strncmp(dir->basebuf.buf, base, stk->baselen)) 922break; 923 el = &group->el[dir->exclude_stack->exclude_ix]; 924 dir->exclude_stack = stk->prev; 925 dir->exclude = NULL; 926free((char*)el->src);/* see strbuf_detach() below */ 927clear_exclude_list(el); 928free(stk); 929 group->nr--; 930} 931 932/* Skip traversing into sub directories if the parent is excluded */ 933if(dir->exclude) 934return; 935 936/* 937 * Lazy initialization. All call sites currently just 938 * memset(dir, 0, sizeof(*dir)) before use. Changing all of 939 * them seems lots of work for little benefit. 940 */ 941if(!dir->basebuf.buf) 942strbuf_init(&dir->basebuf, PATH_MAX); 943 944/* Read from the parent directories and push them down. */ 945 current = stk ? stk->baselen : -1; 946strbuf_setlen(&dir->basebuf, current <0?0: current); 947if(dir->untracked) 948 untracked = stk ? stk->ucd : dir->untracked->root; 949else 950 untracked = NULL; 951 952while(current < baselen) { 953const char*cp; 954struct sha1_stat sha1_stat; 955 956 stk =xcalloc(1,sizeof(*stk)); 957if(current <0) { 958 cp = base; 959 current =0; 960}else{ 961 cp =strchr(base + current +1,'/'); 962if(!cp) 963die("oops in prep_exclude"); 964 cp++; 965 untracked = 966lookup_untracked(dir->untracked, untracked, 967 base + current, 968 cp - base - current); 969} 970 stk->prev = dir->exclude_stack; 971 stk->baselen = cp - base; 972 stk->exclude_ix = group->nr; 973 stk->ucd = untracked; 974 el =add_exclude_list(dir, EXC_DIRS, NULL); 975strbuf_add(&dir->basebuf, base + current, stk->baselen - current); 976assert(stk->baselen == dir->basebuf.len); 977 978/* Abort if the directory is excluded */ 979if(stk->baselen) { 980int dt = DT_DIR; 981 dir->basebuf.buf[stk->baselen -1] =0; 982 dir->exclude =last_exclude_matching_from_lists(dir, 983 dir->basebuf.buf, stk->baselen -1, 984 dir->basebuf.buf + current, &dt); 985 dir->basebuf.buf[stk->baselen -1] ='/'; 986if(dir->exclude && 987 dir->exclude->flags & EXC_FLAG_NEGATIVE) 988 dir->exclude = NULL; 989if(dir->exclude) { 990 dir->exclude_stack = stk; 991return; 992} 993} 994 995/* Try to read per-directory file */ 996hashclr(sha1_stat.sha1); 997 sha1_stat.valid =0; 998if(dir->exclude_per_dir) { 999/*1000 * dir->basebuf gets reused by the traversal, but we1001 * need fname to remain unchanged to ensure the src1002 * member of each struct exclude correctly1003 * back-references its source file. Other invocations1004 * of add_exclude_list provide stable strings, so we1005 * strbuf_detach() and free() here in the caller.1006 */1007struct strbuf sb = STRBUF_INIT;1008strbuf_addbuf(&sb, &dir->basebuf);1009strbuf_addstr(&sb, dir->exclude_per_dir);1010 el->src =strbuf_detach(&sb, NULL);1011add_excludes(el->src, el->src, stk->baselen, el,1,1012 untracked ? &sha1_stat : NULL);1013}1014/*1015 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1016 * will first be called in valid_cached_dir() then maybe many1017 * times more in last_exclude_matching(). When the cache is1018 * used, last_exclude_matching() will not be called and1019 * reading .gitignore content will be a waste.1020 *1021 * So when it's called by valid_cached_dir() and we can get1022 * .gitignore SHA-1 from the index (i.e. .gitignore is not1023 * modified on work tree), we could delay reading the1024 * .gitignore content until we absolutely need it in1025 * last_exclude_matching(). Be careful about ignore rule1026 * order, though, if you do that.1027 */1028if(untracked &&1029hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1030invalidate_gitignore(dir->untracked, untracked);1031hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1032}1033 dir->exclude_stack = stk;1034 current = stk->baselen;1035}1036strbuf_setlen(&dir->basebuf, baselen);1037}10381039/*1040 * Loads the exclude lists for the directory containing pathname, then1041 * scans all exclude lists to determine whether pathname is excluded.1042 * Returns the exclude_list element which matched, or NULL for1043 * undecided.1044 */1045struct exclude *last_exclude_matching(struct dir_struct *dir,1046const char*pathname,1047int*dtype_p)1048{1049int pathlen =strlen(pathname);1050const char*basename =strrchr(pathname,'/');1051 basename = (basename) ? basename+1: pathname;10521053prep_exclude(dir, pathname, basename-pathname);10541055if(dir->exclude)1056return dir->exclude;10571058returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1059 basename, dtype_p);1060}10611062/*1063 * Loads the exclude lists for the directory containing pathname, then1064 * scans all exclude lists to determine whether pathname is excluded.1065 * Returns 1 if true, otherwise 0.1066 */1067intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1068{1069struct exclude *exclude =1070last_exclude_matching(dir, pathname, dtype_p);1071if(exclude)1072return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1073return0;1074}10751076static struct dir_entry *dir_entry_new(const char*pathname,int len)1077{1078struct dir_entry *ent;10791080 ent =xmalloc(sizeof(*ent) + len +1);1081 ent->len = len;1082memcpy(ent->name, pathname, len);1083 ent->name[len] =0;1084return ent;1085}10861087static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1088{1089if(cache_file_exists(pathname, len, ignore_case))1090return NULL;10911092ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1093return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1094}10951096struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1097{1098if(!cache_name_is_other(pathname, len))1099return NULL;11001101ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1102return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1103}11041105enum exist_status {1106 index_nonexistent =0,1107 index_directory,1108 index_gitdir1109};11101111/*1112 * Do not use the alphabetically sorted index to look up1113 * the directory name; instead, use the case insensitive1114 * directory hash.1115 */1116static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1117{1118const struct cache_entry *ce =cache_dir_exists(dirname, len);1119unsigned char endchar;11201121if(!ce)1122return index_nonexistent;1123 endchar = ce->name[len];11241125/*1126 * The cache_entry structure returned will contain this dirname1127 * and possibly additional path components.1128 */1129if(endchar =='/')1130return index_directory;11311132/*1133 * If there are no additional path components, then this cache_entry1134 * represents a submodule. Submodules, despite being directories,1135 * are stored in the cache without a closing slash.1136 */1137if(!endchar &&S_ISGITLINK(ce->ce_mode))1138return index_gitdir;11391140/* This should never be hit, but it exists just in case. */1141return index_nonexistent;1142}11431144/*1145 * The index sorts alphabetically by entry name, which1146 * means that a gitlink sorts as '\0' at the end, while1147 * a directory (which is defined not as an entry, but as1148 * the files it contains) will sort with the '/' at the1149 * end.1150 */1151static enum exist_status directory_exists_in_index(const char*dirname,int len)1152{1153int pos;11541155if(ignore_case)1156returndirectory_exists_in_index_icase(dirname, len);11571158 pos =cache_name_pos(dirname, len);1159if(pos <0)1160 pos = -pos-1;1161while(pos < active_nr) {1162const struct cache_entry *ce = active_cache[pos++];1163unsigned char endchar;11641165if(strncmp(ce->name, dirname, len))1166break;1167 endchar = ce->name[len];1168if(endchar >'/')1169break;1170if(endchar =='/')1171return index_directory;1172if(!endchar &&S_ISGITLINK(ce->ce_mode))1173return index_gitdir;1174}1175return index_nonexistent;1176}11771178/*1179 * When we find a directory when traversing the filesystem, we1180 * have three distinct cases:1181 *1182 * - ignore it1183 * - see it as a directory1184 * - recurse into it1185 *1186 * and which one we choose depends on a combination of existing1187 * git index contents and the flags passed into the directory1188 * traversal routine.1189 *1190 * Case 1: If we *already* have entries in the index under that1191 * directory name, we always recurse into the directory to see1192 * all the files.1193 *1194 * Case 2: If we *already* have that directory name as a gitlink,1195 * we always continue to see it as a gitlink, regardless of whether1196 * there is an actual git directory there or not (it might not1197 * be checked out as a subproject!)1198 *1199 * Case 3: if we didn't have it in the index previously, we1200 * have a few sub-cases:1201 *1202 * (a) if "show_other_directories" is true, we show it as1203 * just a directory, unless "hide_empty_directories" is1204 * also true, in which case we need to check if it contains any1205 * untracked and / or ignored files.1206 * (b) if it looks like a git directory, and we don't have1207 * 'no_gitlinks' set we treat it as a gitlink, and show it1208 * as a directory.1209 * (c) otherwise, we recurse into it.1210 */1211static enum path_treatment treat_directory(struct dir_struct *dir,1212struct untracked_cache_dir *untracked,1213const char*dirname,int len,int exclude,1214const struct path_simplify *simplify)1215{1216/* The "len-1" is to strip the final '/' */1217switch(directory_exists_in_index(dirname, len-1)) {1218case index_directory:1219return path_recurse;12201221case index_gitdir:1222return path_none;12231224case index_nonexistent:1225if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1226break;1227if(!(dir->flags & DIR_NO_GITLINKS)) {1228unsigned char sha1[20];1229if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1230return path_untracked;1231}1232return path_recurse;1233}12341235/* This is the "show_other_directories" case */12361237if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1238return exclude ? path_excluded : path_untracked;12391240 untracked =lookup_untracked(dir->untracked, untracked, dirname, len);1241returnread_directory_recursive(dir, dirname, len,1242 untracked,1, simplify);1243}12441245/*1246 * This is an inexact early pruning of any recursive directory1247 * reading - if the path cannot possibly be in the pathspec,1248 * return true, and we'll skip it early.1249 */1250static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1251{1252if(simplify) {1253for(;;) {1254const char*match = simplify->path;1255int len = simplify->len;12561257if(!match)1258break;1259if(len > pathlen)1260 len = pathlen;1261if(!memcmp(path, match, len))1262return0;1263 simplify++;1264}1265return1;1266}1267return0;1268}12691270/*1271 * This function tells us whether an excluded path matches a1272 * list of "interesting" pathspecs. That is, whether a path matched1273 * by any of the pathspecs could possibly be ignored by excluding1274 * the specified path. This can happen if:1275 *1276 * 1. the path is mentioned explicitly in the pathspec1277 *1278 * 2. the path is a directory prefix of some element in the1279 * pathspec1280 */1281static intexclude_matches_pathspec(const char*path,int len,1282const struct path_simplify *simplify)1283{1284if(simplify) {1285for(; simplify->path; simplify++) {1286if(len == simplify->len1287&& !memcmp(path, simplify->path, len))1288return1;1289if(len < simplify->len1290&& simplify->path[len] =='/'1291&& !memcmp(path, simplify->path, len))1292return1;1293}1294}1295return0;1296}12971298static intget_index_dtype(const char*path,int len)1299{1300int pos;1301const struct cache_entry *ce;13021303 ce =cache_file_exists(path, len,0);1304if(ce) {1305if(!ce_uptodate(ce))1306return DT_UNKNOWN;1307if(S_ISGITLINK(ce->ce_mode))1308return DT_DIR;1309/*1310 * Nobody actually cares about the1311 * difference between DT_LNK and DT_REG1312 */1313return DT_REG;1314}13151316/* Try to look it up as a directory */1317 pos =cache_name_pos(path, len);1318if(pos >=0)1319return DT_UNKNOWN;1320 pos = -pos-1;1321while(pos < active_nr) {1322 ce = active_cache[pos++];1323if(strncmp(ce->name, path, len))1324break;1325if(ce->name[len] >'/')1326break;1327if(ce->name[len] <'/')1328continue;1329if(!ce_uptodate(ce))1330break;/* continue? */1331return DT_DIR;1332}1333return DT_UNKNOWN;1334}13351336static intget_dtype(struct dirent *de,const char*path,int len)1337{1338int dtype = de ?DTYPE(de) : DT_UNKNOWN;1339struct stat st;13401341if(dtype != DT_UNKNOWN)1342return dtype;1343 dtype =get_index_dtype(path, len);1344if(dtype != DT_UNKNOWN)1345return dtype;1346if(lstat(path, &st))1347return dtype;1348if(S_ISREG(st.st_mode))1349return DT_REG;1350if(S_ISDIR(st.st_mode))1351return DT_DIR;1352if(S_ISLNK(st.st_mode))1353return DT_LNK;1354return dtype;1355}13561357static enum path_treatment treat_one_path(struct dir_struct *dir,1358struct untracked_cache_dir *untracked,1359struct strbuf *path,1360const struct path_simplify *simplify,1361int dtype,struct dirent *de)1362{1363int exclude;1364int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);13651366if(dtype == DT_UNKNOWN)1367 dtype =get_dtype(de, path->buf, path->len);13681369/* Always exclude indexed files */1370if(dtype != DT_DIR && has_path_in_index)1371return path_none;13721373/*1374 * When we are looking at a directory P in the working tree,1375 * there are three cases:1376 *1377 * (1) P exists in the index. Everything inside the directory P in1378 * the working tree needs to go when P is checked out from the1379 * index.1380 *1381 * (2) P does not exist in the index, but there is P/Q in the index.1382 * We know P will stay a directory when we check out the contents1383 * of the index, but we do not know yet if there is a directory1384 * P/Q in the working tree to be killed, so we need to recurse.1385 *1386 * (3) P does not exist in the index, and there is no P/Q in the index1387 * to require P to be a directory, either. Only in this case, we1388 * know that everything inside P will not be killed without1389 * recursing.1390 */1391if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1392(dtype == DT_DIR) &&1393!has_path_in_index &&1394(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1395return path_none;13961397 exclude =is_excluded(dir, path->buf, &dtype);13981399/*1400 * Excluded? If we don't explicitly want to show1401 * ignored files, ignore it1402 */1403if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1404return path_excluded;14051406switch(dtype) {1407default:1408return path_none;1409case DT_DIR:1410strbuf_addch(path,'/');1411returntreat_directory(dir, untracked, path->buf, path->len, exclude,1412 simplify);1413case DT_REG:1414case DT_LNK:1415return exclude ? path_excluded : path_untracked;1416}1417}14181419static enum path_treatment treat_path(struct dir_struct *dir,1420struct untracked_cache_dir *untracked,1421struct dirent *de,1422struct strbuf *path,1423int baselen,1424const struct path_simplify *simplify)1425{1426int dtype;14271428if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1429return path_none;1430strbuf_setlen(path, baselen);1431strbuf_addstr(path, de->d_name);1432if(simplify_away(path->buf, path->len, simplify))1433return path_none;14341435 dtype =DTYPE(de);1436returntreat_one_path(dir, untracked, path, simplify, dtype, de);1437}14381439static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1440{1441if(!dir)1442return;1443ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1444 dir->untracked_alloc);1445 dir->untracked[dir->untracked_nr++] =xstrdup(name);1446}14471448/*1449 * Read a directory tree. We currently ignore anything but1450 * directories, regular files and symlinks. That's because git1451 * doesn't handle them at all yet. Maybe that will change some1452 * day.1453 *1454 * Also, we ignore the name ".git" (even if it is not a directory).1455 * That likely will not change.1456 *1457 * Returns the most significant path_treatment value encountered in the scan.1458 */1459static enum path_treatment read_directory_recursive(struct dir_struct *dir,1460const char*base,int baselen,1461struct untracked_cache_dir *untracked,int check_only,1462const struct path_simplify *simplify)1463{1464DIR*fdir;1465enum path_treatment state, subdir_state, dir_state = path_none;1466struct dirent *de;1467struct strbuf path = STRBUF_INIT;14681469strbuf_add(&path, base, baselen);14701471 fdir =opendir(path.len ? path.buf :".");1472if(!fdir)1473goto out;14741475if(untracked)1476 untracked->check_only = !!check_only;14771478while((de =readdir(fdir)) != NULL) {1479/* check how the file or directory should be treated */1480 state =treat_path(dir, untracked, de, &path, baselen, simplify);14811482if(state > dir_state)1483 dir_state = state;14841485/* recurse into subdir if instructed by treat_path */1486if(state == path_recurse) {1487struct untracked_cache_dir *ud;1488 ud =lookup_untracked(dir->untracked, untracked,1489 path.buf + baselen,1490 path.len - baselen);1491 subdir_state =1492read_directory_recursive(dir, path.buf, path.len,1493 ud, check_only, simplify);1494if(subdir_state > dir_state)1495 dir_state = subdir_state;1496}14971498if(check_only) {1499/* abort early if maximum state has been reached */1500if(dir_state == path_untracked) {1501if(untracked)1502add_untracked(untracked, path.buf + baselen);1503break;1504}1505/* skip the dir_add_* part */1506continue;1507}15081509/* add the path to the appropriate result list */1510switch(state) {1511case path_excluded:1512if(dir->flags & DIR_SHOW_IGNORED)1513dir_add_name(dir, path.buf, path.len);1514else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1515((dir->flags & DIR_COLLECT_IGNORED) &&1516exclude_matches_pathspec(path.buf, path.len,1517 simplify)))1518dir_add_ignored(dir, path.buf, path.len);1519break;15201521case path_untracked:1522if(dir->flags & DIR_SHOW_IGNORED)1523break;1524dir_add_name(dir, path.buf, path.len);1525if(untracked)1526add_untracked(untracked, path.buf + baselen);1527break;15281529default:1530break;1531}1532}1533closedir(fdir);1534 out:1535strbuf_release(&path);15361537return dir_state;1538}15391540static intcmp_name(const void*p1,const void*p2)1541{1542const struct dir_entry *e1 = *(const struct dir_entry **)p1;1543const struct dir_entry *e2 = *(const struct dir_entry **)p2;15441545returnname_compare(e1->name, e1->len, e2->name, e2->len);1546}15471548static struct path_simplify *create_simplify(const char**pathspec)1549{1550int nr, alloc =0;1551struct path_simplify *simplify = NULL;15521553if(!pathspec)1554return NULL;15551556for(nr =0; ; nr++) {1557const char*match;1558ALLOC_GROW(simplify, nr +1, alloc);1559 match = *pathspec++;1560if(!match)1561break;1562 simplify[nr].path = match;1563 simplify[nr].len =simple_length(match);1564}1565 simplify[nr].path = NULL;1566 simplify[nr].len =0;1567return simplify;1568}15691570static voidfree_simplify(struct path_simplify *simplify)1571{1572free(simplify);1573}15741575static inttreat_leading_path(struct dir_struct *dir,1576const char*path,int len,1577const struct path_simplify *simplify)1578{1579struct strbuf sb = STRBUF_INIT;1580int baselen, rc =0;1581const char*cp;1582int old_flags = dir->flags;15831584while(len && path[len -1] =='/')1585 len--;1586if(!len)1587return1;1588 baselen =0;1589 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1590while(1) {1591 cp = path + baselen + !!baselen;1592 cp =memchr(cp,'/', path + len - cp);1593if(!cp)1594 baselen = len;1595else1596 baselen = cp - path;1597strbuf_setlen(&sb,0);1598strbuf_add(&sb, path, baselen);1599if(!is_directory(sb.buf))1600break;1601if(simplify_away(sb.buf, sb.len, simplify))1602break;1603if(treat_one_path(dir, NULL, &sb, simplify,1604 DT_DIR, NULL) == path_none)1605break;/* do not recurse into it */1606if(len <= baselen) {1607 rc =1;1608break;/* finished checking */1609}1610}1611strbuf_release(&sb);1612 dir->flags = old_flags;1613return rc;1614}16151616static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1617int base_len,1618const struct pathspec *pathspec)1619{1620struct untracked_cache_dir *root;16211622if(!dir->untracked)1623return NULL;16241625/*1626 * We only support $GIT_DIR/info/exclude and core.excludesfile1627 * as the global ignore rule files. Any other additions1628 * (e.g. from command line) invalidate the cache. This1629 * condition also catches running setup_standard_excludes()1630 * before setting dir->untracked!1631 */1632if(dir->unmanaged_exclude_files)1633return NULL;16341635/*1636 * Optimize for the main use case only: whole-tree git1637 * status. More work involved in treat_leading_path() if we1638 * use cache on just a subset of the worktree. pathspec1639 * support could make the matter even worse.1640 */1641if(base_len || (pathspec && pathspec->nr))1642return NULL;16431644/* Different set of flags may produce different results */1645if(dir->flags != dir->untracked->dir_flags ||1646/*1647 * See treat_directory(), case index_nonexistent. Without1648 * this flag, we may need to also cache .git file content1649 * for the resolve_gitlink_ref() call, which we don't.1650 */1651!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1652/* We don't support collecting ignore files */1653(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1654 DIR_COLLECT_IGNORED)))1655return NULL;16561657/*1658 * If we use .gitignore in the cache and now you change it to1659 * .gitexclude, everything will go wrong.1660 */1661if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1662strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1663return NULL;16641665/*1666 * EXC_CMDL is not considered in the cache. If people set it,1667 * skip the cache.1668 */1669if(dir->exclude_list_group[EXC_CMDL].nr)1670return NULL;16711672if(!dir->untracked->root) {1673const int len =sizeof(*dir->untracked->root);1674 dir->untracked->root =xmalloc(len);1675memset(dir->untracked->root,0, len);1676}16771678/* Validate $GIT_DIR/info/exclude and core.excludesfile */1679 root = dir->untracked->root;1680if(hashcmp(dir->ss_info_exclude.sha1,1681 dir->untracked->ss_info_exclude.sha1)) {1682invalidate_gitignore(dir->untracked, root);1683 dir->untracked->ss_info_exclude = dir->ss_info_exclude;1684}1685if(hashcmp(dir->ss_excludes_file.sha1,1686 dir->untracked->ss_excludes_file.sha1)) {1687invalidate_gitignore(dir->untracked, root);1688 dir->untracked->ss_excludes_file = dir->ss_excludes_file;1689}1690return root;1691}16921693intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)1694{1695struct path_simplify *simplify;1696struct untracked_cache_dir *untracked;16971698/*1699 * Check out create_simplify()1700 */1701if(pathspec)1702GUARD_PATHSPEC(pathspec,1703 PATHSPEC_FROMTOP |1704 PATHSPEC_MAXDEPTH |1705 PATHSPEC_LITERAL |1706 PATHSPEC_GLOB |1707 PATHSPEC_ICASE |1708 PATHSPEC_EXCLUDE);17091710if(has_symlink_leading_path(path, len))1711return dir->nr;17121713/*1714 * exclude patterns are treated like positive ones in1715 * create_simplify. Usually exclude patterns should be a1716 * subset of positive ones, which has no impacts on1717 * create_simplify().1718 */1719 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);1720 untracked =validate_untracked_cache(dir, len, pathspec);1721if(!untracked)1722/*1723 * make sure untracked cache code path is disabled,1724 * e.g. prep_exclude()1725 */1726 dir->untracked = NULL;1727if(!len ||treat_leading_path(dir, path, len, simplify))1728read_directory_recursive(dir, path, len, untracked,0, simplify);1729free_simplify(simplify);1730qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);1731qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);1732return dir->nr;1733}17341735intfile_exists(const char*f)1736{1737struct stat sb;1738returnlstat(f, &sb) ==0;1739}17401741/*1742 * Given two normalized paths (a trailing slash is ok), if subdir is1743 * outside dir, return -1. Otherwise return the offset in subdir that1744 * can be used as relative path to dir.1745 */1746intdir_inside_of(const char*subdir,const char*dir)1747{1748int offset =0;17491750assert(dir && subdir && *dir && *subdir);17511752while(*dir && *subdir && *dir == *subdir) {1753 dir++;1754 subdir++;1755 offset++;1756}17571758/* hel[p]/me vs hel[l]/yeah */1759if(*dir && *subdir)1760return-1;17611762if(!*subdir)1763return!*dir ? offset : -1;/* same dir */17641765/* foo/[b]ar vs foo/[] */1766if(is_dir_sep(dir[-1]))1767returnis_dir_sep(subdir[-1]) ? offset : -1;17681769/* foo[/]bar vs foo[] */1770returnis_dir_sep(*subdir) ? offset +1: -1;1771}17721773intis_inside_dir(const char*dir)1774{1775char*cwd;1776int rc;17771778if(!dir)1779return0;17801781 cwd =xgetcwd();1782 rc = (dir_inside_of(cwd, dir) >=0);1783free(cwd);1784return rc;1785}17861787intis_empty_dir(const char*path)1788{1789DIR*dir =opendir(path);1790struct dirent *e;1791int ret =1;17921793if(!dir)1794return0;17951796while((e =readdir(dir)) != NULL)1797if(!is_dot_or_dotdot(e->d_name)) {1798 ret =0;1799break;1800}18011802closedir(dir);1803return ret;1804}18051806static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)1807{1808DIR*dir;1809struct dirent *e;1810int ret =0, original_len = path->len, len, kept_down =0;1811int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);1812int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);1813unsigned char submodule_head[20];18141815if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&1816!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {1817/* Do not descend and nuke a nested git work tree. */1818if(kept_up)1819*kept_up =1;1820return0;1821}18221823 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;1824 dir =opendir(path->buf);1825if(!dir) {1826if(errno == ENOENT)1827return keep_toplevel ? -1:0;1828else if(errno == EACCES && !keep_toplevel)1829/*1830 * An empty dir could be removable even if it1831 * is unreadable:1832 */1833returnrmdir(path->buf);1834else1835return-1;1836}1837if(path->buf[original_len -1] !='/')1838strbuf_addch(path,'/');18391840 len = path->len;1841while((e =readdir(dir)) != NULL) {1842struct stat st;1843if(is_dot_or_dotdot(e->d_name))1844continue;18451846strbuf_setlen(path, len);1847strbuf_addstr(path, e->d_name);1848if(lstat(path->buf, &st)) {1849if(errno == ENOENT)1850/*1851 * file disappeared, which is what we1852 * wanted anyway1853 */1854continue;1855/* fall thru */1856}else if(S_ISDIR(st.st_mode)) {1857if(!remove_dir_recurse(path, flag, &kept_down))1858continue;/* happy */1859}else if(!only_empty &&1860(!unlink(path->buf) || errno == ENOENT)) {1861continue;/* happy, too */1862}18631864/* path too long, stat fails, or non-directory still exists */1865 ret = -1;1866break;1867}1868closedir(dir);18691870strbuf_setlen(path, original_len);1871if(!ret && !keep_toplevel && !kept_down)1872 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;1873else if(kept_up)1874/*1875 * report the uplevel that it is not an error that we1876 * did not rmdir() our directory.1877 */1878*kept_up = !ret;1879return ret;1880}18811882intremove_dir_recursively(struct strbuf *path,int flag)1883{1884returnremove_dir_recurse(path, flag, NULL);1885}18861887voidsetup_standard_excludes(struct dir_struct *dir)1888{1889const char*path;1890char*xdg_path;18911892 dir->exclude_per_dir =".gitignore";1893 path =git_path("info/exclude");1894if(!excludes_file) {1895home_config_paths(NULL, &xdg_path,"ignore");1896 excludes_file = xdg_path;1897}1898if(!access_or_warn(path, R_OK,0))1899add_excludes_from_file_1(dir, path,1900 dir->untracked ? &dir->ss_info_exclude : NULL);1901if(excludes_file && !access_or_warn(excludes_file, R_OK,0))1902add_excludes_from_file_1(dir, excludes_file,1903 dir->untracked ? &dir->ss_excludes_file : NULL);1904}19051906intremove_path(const char*name)1907{1908char*slash;19091910if(unlink(name) && errno != ENOENT && errno != ENOTDIR)1911return-1;19121913 slash =strrchr(name,'/');1914if(slash) {1915char*dirs =xstrdup(name);1916 slash = dirs + (slash - name);1917do{1918*slash ='\0';1919}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));1920free(dirs);1921}1922return0;1923}19241925/*1926 * Frees memory within dir which was allocated for exclude lists and1927 * the exclude_stack. Does not free dir itself.1928 */1929voidclear_directory(struct dir_struct *dir)1930{1931int i, j;1932struct exclude_list_group *group;1933struct exclude_list *el;1934struct exclude_stack *stk;19351936for(i = EXC_CMDL; i <= EXC_FILE; i++) {1937 group = &dir->exclude_list_group[i];1938for(j =0; j < group->nr; j++) {1939 el = &group->el[j];1940if(i == EXC_DIRS)1941free((char*)el->src);1942clear_exclude_list(el);1943}1944free(group->el);1945}19461947 stk = dir->exclude_stack;1948while(stk) {1949struct exclude_stack *prev = stk->prev;1950free(stk);1951 stk = prev;1952}1953strbuf_release(&dir->basebuf);1954}