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; 40struct dirent *de; 41}; 42 43static enum path_treatment read_directory_recursive(struct dir_struct *dir, 44const char*path,int len,struct untracked_cache_dir *untracked, 45int check_only,const struct path_simplify *simplify); 46static intget_dtype(struct dirent *de,const char*path,int len); 47 48/* helper string functions with support for the ignore_case flag */ 49intstrcmp_icase(const char*a,const char*b) 50{ 51return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 52} 53 54intstrncmp_icase(const char*a,const char*b,size_t count) 55{ 56return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 57} 58 59intfnmatch_icase(const char*pattern,const char*string,int flags) 60{ 61returnwildmatch(pattern, string, 62 flags | (ignore_case ? WM_CASEFOLD :0), 63 NULL); 64} 65 66intgit_fnmatch(const struct pathspec_item *item, 67const char*pattern,const char*string, 68int prefix) 69{ 70if(prefix >0) { 71if(ps_strncmp(item, pattern, string, prefix)) 72return WM_NOMATCH; 73 pattern += prefix; 74 string += prefix; 75} 76if(item->flags & PATHSPEC_ONESTAR) { 77int pattern_len =strlen(++pattern); 78int string_len =strlen(string); 79return string_len < pattern_len || 80ps_strcmp(item, pattern, 81 string + string_len - pattern_len); 82} 83if(item->magic & PATHSPEC_GLOB) 84returnwildmatch(pattern, string, 85 WM_PATHNAME | 86(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 87 NULL); 88else 89/* wildmatch has not learned no FNM_PATHNAME mode yet */ 90returnwildmatch(pattern, string, 91 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 92 NULL); 93} 94 95static intfnmatch_icase_mem(const char*pattern,int patternlen, 96const char*string,int stringlen, 97int flags) 98{ 99int match_status; 100struct strbuf pat_buf = STRBUF_INIT; 101struct strbuf str_buf = STRBUF_INIT; 102const char*use_pat = pattern; 103const char*use_str = string; 104 105if(pattern[patternlen]) { 106strbuf_add(&pat_buf, pattern, patternlen); 107 use_pat = pat_buf.buf; 108} 109if(string[stringlen]) { 110strbuf_add(&str_buf, string, stringlen); 111 use_str = str_buf.buf; 112} 113 114if(ignore_case) 115 flags |= WM_CASEFOLD; 116 match_status =wildmatch(use_pat, use_str, flags, NULL); 117 118strbuf_release(&pat_buf); 119strbuf_release(&str_buf); 120 121return match_status; 122} 123 124static size_tcommon_prefix_len(const struct pathspec *pathspec) 125{ 126int n; 127size_t max =0; 128 129/* 130 * ":(icase)path" is treated as a pathspec full of 131 * wildcard. In other words, only prefix is considered common 132 * prefix. If the pathspec is abc/foo abc/bar, running in 133 * subdir xyz, the common prefix is still xyz, not xuz/abc as 134 * in non-:(icase). 135 */ 136GUARD_PATHSPEC(pathspec, 137 PATHSPEC_FROMTOP | 138 PATHSPEC_MAXDEPTH | 139 PATHSPEC_LITERAL | 140 PATHSPEC_GLOB | 141 PATHSPEC_ICASE | 142 PATHSPEC_EXCLUDE); 143 144for(n =0; n < pathspec->nr; n++) { 145size_t i =0, len =0, item_len; 146if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 147continue; 148if(pathspec->items[n].magic & PATHSPEC_ICASE) 149 item_len = pathspec->items[n].prefix; 150else 151 item_len = pathspec->items[n].nowildcard_len; 152while(i < item_len && (n ==0|| i < max)) { 153char c = pathspec->items[n].match[i]; 154if(c != pathspec->items[0].match[i]) 155break; 156if(c =='/') 157 len = i +1; 158 i++; 159} 160if(n ==0|| len < max) { 161 max = len; 162if(!max) 163break; 164} 165} 166return max; 167} 168 169/* 170 * Returns a copy of the longest leading path common among all 171 * pathspecs. 172 */ 173char*common_prefix(const struct pathspec *pathspec) 174{ 175unsigned long len =common_prefix_len(pathspec); 176 177return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 178} 179 180intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 181{ 182size_t len; 183 184/* 185 * Calculate common prefix for the pathspec, and 186 * use that to optimize the directory walk 187 */ 188 len =common_prefix_len(pathspec); 189 190/* Read the directory and prune it */ 191read_directory(dir, pathspec->nr ? pathspec->_raw[0] :"", len, pathspec); 192return len; 193} 194 195intwithin_depth(const char*name,int namelen, 196int depth,int max_depth) 197{ 198const char*cp = name, *cpe = name + namelen; 199 200while(cp < cpe) { 201if(*cp++ !='/') 202continue; 203 depth++; 204if(depth > max_depth) 205return0; 206} 207return1; 208} 209 210#define DO_MATCH_EXCLUDE 1 211#define DO_MATCH_DIRECTORY 2 212 213/* 214 * Does 'match' match the given name? 215 * A match is found if 216 * 217 * (1) the 'match' string is leading directory of 'name', or 218 * (2) the 'match' string is a wildcard and matches 'name', or 219 * (3) the 'match' string is exactly the same as 'name'. 220 * 221 * and the return value tells which case it was. 222 * 223 * It returns 0 when there is no match. 224 */ 225static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 226const char*name,int namelen,unsigned flags) 227{ 228/* name/namelen has prefix cut off by caller */ 229const char*match = item->match + prefix; 230int matchlen = item->len - prefix; 231 232/* 233 * The normal call pattern is: 234 * 1. prefix = common_prefix_len(ps); 235 * 2. prune something, or fill_directory 236 * 3. match_pathspec() 237 * 238 * 'prefix' at #1 may be shorter than the command's prefix and 239 * it's ok for #2 to match extra files. Those extras will be 240 * trimmed at #3. 241 * 242 * Suppose the pathspec is 'foo' and '../bar' running from 243 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 244 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 245 * user does not want XYZ/foo, only the "foo" part should be 246 * case-insensitive. We need to filter out XYZ/foo here. In 247 * other words, we do not trust the caller on comparing the 248 * prefix part when :(icase) is involved. We do exact 249 * comparison ourselves. 250 * 251 * Normally the caller (common_prefix_len() in fact) does 252 * _exact_ matching on name[-prefix+1..-1] and we do not need 253 * to check that part. Be defensive and check it anyway, in 254 * case common_prefix_len is changed, or a new caller is 255 * introduced that does not use common_prefix_len. 256 * 257 * If the penalty turns out too high when prefix is really 258 * long, maybe change it to 259 * strncmp(match, name, item->prefix - prefix) 260 */ 261if(item->prefix && (item->magic & PATHSPEC_ICASE) && 262strncmp(item->match, name - prefix, item->prefix)) 263return0; 264 265/* If the match was just the prefix, we matched */ 266if(!*match) 267return MATCHED_RECURSIVELY; 268 269if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 270if(matchlen == namelen) 271return MATCHED_EXACTLY; 272 273if(match[matchlen-1] =='/'|| name[matchlen] =='/') 274return MATCHED_RECURSIVELY; 275}else if((flags & DO_MATCH_DIRECTORY) && 276 match[matchlen -1] =='/'&& 277 namelen == matchlen -1&& 278!ps_strncmp(item, match, name, namelen)) 279return MATCHED_EXACTLY; 280 281if(item->nowildcard_len < item->len && 282!git_fnmatch(item, match, name, 283 item->nowildcard_len - prefix)) 284return MATCHED_FNMATCH; 285 286return0; 287} 288 289/* 290 * Given a name and a list of pathspecs, returns the nature of the 291 * closest (i.e. most specific) match of the name to any of the 292 * pathspecs. 293 * 294 * The caller typically calls this multiple times with the same 295 * pathspec and seen[] array but with different name/namelen 296 * (e.g. entries from the index) and is interested in seeing if and 297 * how each pathspec matches all the names it calls this function 298 * with. A mark is left in the seen[] array for each pathspec element 299 * indicating the closest type of match that element achieved, so if 300 * seen[n] remains zero after multiple invocations, that means the nth 301 * pathspec did not match any names, which could indicate that the 302 * user mistyped the nth pathspec. 303 */ 304static intdo_match_pathspec(const struct pathspec *ps, 305const char*name,int namelen, 306int prefix,char*seen, 307unsigned flags) 308{ 309int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 310 311GUARD_PATHSPEC(ps, 312 PATHSPEC_FROMTOP | 313 PATHSPEC_MAXDEPTH | 314 PATHSPEC_LITERAL | 315 PATHSPEC_GLOB | 316 PATHSPEC_ICASE | 317 PATHSPEC_EXCLUDE); 318 319if(!ps->nr) { 320if(!ps->recursive || 321!(ps->magic & PATHSPEC_MAXDEPTH) || 322 ps->max_depth == -1) 323return MATCHED_RECURSIVELY; 324 325if(within_depth(name, namelen,0, ps->max_depth)) 326return MATCHED_EXACTLY; 327else 328return0; 329} 330 331 name += prefix; 332 namelen -= prefix; 333 334for(i = ps->nr -1; i >=0; i--) { 335int how; 336 337if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 338( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 339continue; 340 341if(seen && seen[i] == MATCHED_EXACTLY) 342continue; 343/* 344 * Make exclude patterns optional and never report 345 * "pathspec ':(exclude)foo' matches no files" 346 */ 347if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 348 seen[i] = MATCHED_FNMATCH; 349 how =match_pathspec_item(ps->items+i, prefix, name, 350 namelen, flags); 351if(ps->recursive && 352(ps->magic & PATHSPEC_MAXDEPTH) && 353 ps->max_depth != -1&& 354 how && how != MATCHED_FNMATCH) { 355int len = ps->items[i].len; 356if(name[len] =='/') 357 len++; 358if(within_depth(name+len, namelen-len,0, ps->max_depth)) 359 how = MATCHED_EXACTLY; 360else 361 how =0; 362} 363if(how) { 364if(retval < how) 365 retval = how; 366if(seen && seen[i] < how) 367 seen[i] = how; 368} 369} 370return retval; 371} 372 373intmatch_pathspec(const struct pathspec *ps, 374const char*name,int namelen, 375int prefix,char*seen,int is_dir) 376{ 377int positive, negative; 378unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 379 positive =do_match_pathspec(ps, name, namelen, 380 prefix, seen, flags); 381if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 382return positive; 383 negative =do_match_pathspec(ps, name, namelen, 384 prefix, seen, 385 flags | DO_MATCH_EXCLUDE); 386return negative ?0: positive; 387} 388 389/* 390 * Return the length of the "simple" part of a path match limiter. 391 */ 392intsimple_length(const char*match) 393{ 394int len = -1; 395 396for(;;) { 397unsigned char c = *match++; 398 len++; 399if(c =='\0'||is_glob_special(c)) 400return len; 401} 402} 403 404intno_wildcard(const char*string) 405{ 406return string[simple_length(string)] =='\0'; 407} 408 409voidparse_exclude_pattern(const char**pattern, 410int*patternlen, 411int*flags, 412int*nowildcardlen) 413{ 414const char*p = *pattern; 415size_t i, len; 416 417*flags =0; 418if(*p =='!') { 419*flags |= EXC_FLAG_NEGATIVE; 420 p++; 421} 422 len =strlen(p); 423if(len && p[len -1] =='/') { 424 len--; 425*flags |= EXC_FLAG_MUSTBEDIR; 426} 427for(i =0; i < len; i++) { 428if(p[i] =='/') 429break; 430} 431if(i == len) 432*flags |= EXC_FLAG_NODIR; 433*nowildcardlen =simple_length(p); 434/* 435 * we should have excluded the trailing slash from 'p' too, 436 * but that's one more allocation. Instead just make sure 437 * nowildcardlen does not exceed real patternlen 438 */ 439if(*nowildcardlen > len) 440*nowildcardlen = len; 441if(*p =='*'&&no_wildcard(p +1)) 442*flags |= EXC_FLAG_ENDSWITH; 443*pattern = p; 444*patternlen = len; 445} 446 447voidadd_exclude(const char*string,const char*base, 448int baselen,struct exclude_list *el,int srcpos) 449{ 450struct exclude *x; 451int patternlen; 452int flags; 453int nowildcardlen; 454 455parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 456if(flags & EXC_FLAG_MUSTBEDIR) { 457char*s; 458 x =xmalloc(sizeof(*x) + patternlen +1); 459 s = (char*)(x+1); 460memcpy(s, string, patternlen); 461 s[patternlen] ='\0'; 462 x->pattern = s; 463}else{ 464 x =xmalloc(sizeof(*x)); 465 x->pattern = string; 466} 467 x->patternlen = patternlen; 468 x->nowildcardlen = nowildcardlen; 469 x->base = base; 470 x->baselen = baselen; 471 x->flags = flags; 472 x->srcpos = srcpos; 473ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 474 el->excludes[el->nr++] = x; 475 x->el = el; 476} 477 478static void*read_skip_worktree_file_from_index(const char*path,size_t*size, 479struct sha1_stat *sha1_stat) 480{ 481int pos, len; 482unsigned long sz; 483enum object_type type; 484void*data; 485 486 len =strlen(path); 487 pos =cache_name_pos(path, len); 488if(pos <0) 489return NULL; 490if(!ce_skip_worktree(active_cache[pos])) 491return NULL; 492 data =read_sha1_file(active_cache[pos]->sha1, &type, &sz); 493if(!data || type != OBJ_BLOB) { 494free(data); 495return NULL; 496} 497*size =xsize_t(sz); 498if(sha1_stat) { 499memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 500hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 501} 502return data; 503} 504 505/* 506 * Frees memory within el which was allocated for exclude patterns and 507 * the file buffer. Does not free el itself. 508 */ 509voidclear_exclude_list(struct exclude_list *el) 510{ 511int i; 512 513for(i =0; i < el->nr; i++) 514free(el->excludes[i]); 515free(el->excludes); 516free(el->filebuf); 517 518 el->nr =0; 519 el->excludes = NULL; 520 el->filebuf = NULL; 521} 522 523static voidtrim_trailing_spaces(char*buf) 524{ 525char*p, *last_space = NULL; 526 527for(p = buf; *p; p++) 528switch(*p) { 529case' ': 530if(!last_space) 531 last_space = p; 532break; 533case'\\': 534 p++; 535if(!*p) 536return; 537/* fallthrough */ 538default: 539 last_space = NULL; 540} 541 542if(last_space) 543*last_space ='\0'; 544} 545 546/* 547 * Given a subdirectory name and "dir" of the current directory, 548 * search the subdir in "dir" and return it, or create a new one if it 549 * does not exist in "dir". 550 * 551 * If "name" has the trailing slash, it'll be excluded in the search. 552 */ 553static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 554struct untracked_cache_dir *dir, 555const char*name,int len) 556{ 557int first, last; 558struct untracked_cache_dir *d; 559if(!dir) 560return NULL; 561if(len && name[len -1] =='/') 562 len--; 563 first =0; 564 last = dir->dirs_nr; 565while(last > first) { 566int cmp, next = (last + first) >>1; 567 d = dir->dirs[next]; 568 cmp =strncmp(name, d->name, len); 569if(!cmp &&strlen(d->name) > len) 570 cmp = -1; 571if(!cmp) 572return d; 573if(cmp <0) { 574 last = next; 575continue; 576} 577 first = next+1; 578} 579 580 uc->dir_created++; 581 d =xmalloc(sizeof(*d) + len +1); 582memset(d,0,sizeof(*d)); 583memcpy(d->name, name, len); 584 d->name[len] ='\0'; 585 586ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 587memmove(dir->dirs + first +1, dir->dirs + first, 588(dir->dirs_nr - first) *sizeof(*dir->dirs)); 589 dir->dirs_nr++; 590 dir->dirs[first] = d; 591return d; 592} 593 594static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 595{ 596int i; 597 dir->valid =0; 598 dir->untracked_nr =0; 599for(i =0; i < dir->dirs_nr; i++) 600do_invalidate_gitignore(dir->dirs[i]); 601} 602 603static voidinvalidate_gitignore(struct untracked_cache *uc, 604struct untracked_cache_dir *dir) 605{ 606 uc->gitignore_invalidated++; 607do_invalidate_gitignore(dir); 608} 609 610/* 611 * Given a file with name "fname", read it (either from disk, or from 612 * the index if "check_index" is non-zero), parse it and store the 613 * exclude rules in "el". 614 * 615 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 616 * stat data from disk (only valid if add_excludes returns zero). If 617 * ss_valid is non-zero, "ss" must contain good value as input. 618 */ 619static intadd_excludes(const char*fname,const char*base,int baselen, 620struct exclude_list *el,int check_index, 621struct sha1_stat *sha1_stat) 622{ 623struct stat st; 624int fd, i, lineno =1; 625size_t size =0; 626char*buf, *entry; 627 628 fd =open(fname, O_RDONLY); 629if(fd <0||fstat(fd, &st) <0) { 630if(errno != ENOENT) 631warn_on_inaccessible(fname); 632if(0<= fd) 633close(fd); 634if(!check_index || 635(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 636return-1; 637if(size ==0) { 638free(buf); 639return0; 640} 641if(buf[size-1] !='\n') { 642 buf =xrealloc(buf, size+1); 643 buf[size++] ='\n'; 644} 645}else{ 646 size =xsize_t(st.st_size); 647if(size ==0) { 648if(sha1_stat) { 649fill_stat_data(&sha1_stat->stat, &st); 650hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 651 sha1_stat->valid =1; 652} 653close(fd); 654return0; 655} 656 buf =xmalloc(size+1); 657if(read_in_full(fd, buf, size) != size) { 658free(buf); 659close(fd); 660return-1; 661} 662 buf[size++] ='\n'; 663close(fd); 664if(sha1_stat) { 665int pos; 666if(sha1_stat->valid && 667!match_stat_data(&sha1_stat->stat, &st)) 668;/* no content change, ss->sha1 still good */ 669else if(check_index && 670(pos =cache_name_pos(fname,strlen(fname))) >=0&& 671!ce_stage(active_cache[pos]) && 672ce_uptodate(active_cache[pos]) && 673!would_convert_to_git(fname)) 674hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 675else 676hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 677fill_stat_data(&sha1_stat->stat, &st); 678 sha1_stat->valid =1; 679} 680} 681 682 el->filebuf = buf; 683 entry = buf; 684for(i =0; i < size; i++) { 685if(buf[i] =='\n') { 686if(entry != buf + i && entry[0] !='#') { 687 buf[i - (i && buf[i-1] =='\r')] =0; 688trim_trailing_spaces(entry); 689add_exclude(entry, base, baselen, el, lineno); 690} 691 lineno++; 692 entry = buf + i +1; 693} 694} 695return0; 696} 697 698intadd_excludes_from_file_to_list(const char*fname,const char*base, 699int baselen,struct exclude_list *el, 700int check_index) 701{ 702returnadd_excludes(fname, base, baselen, el, check_index, NULL); 703} 704 705struct exclude_list *add_exclude_list(struct dir_struct *dir, 706int group_type,const char*src) 707{ 708struct exclude_list *el; 709struct exclude_list_group *group; 710 711 group = &dir->exclude_list_group[group_type]; 712ALLOC_GROW(group->el, group->nr +1, group->alloc); 713 el = &group->el[group->nr++]; 714memset(el,0,sizeof(*el)); 715 el->src = src; 716return el; 717} 718 719/* 720 * Used to set up core.excludesfile and .git/info/exclude lists. 721 */ 722static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 723struct sha1_stat *sha1_stat) 724{ 725struct exclude_list *el; 726/* 727 * catch setup_standard_excludes() that's called before 728 * dir->untracked is assigned. That function behaves 729 * differently when dir->untracked is non-NULL. 730 */ 731if(!dir->untracked) 732 dir->unmanaged_exclude_files++; 733 el =add_exclude_list(dir, EXC_FILE, fname); 734if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 735die("cannot use%sas an exclude file", fname); 736} 737 738voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 739{ 740 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 741add_excludes_from_file_1(dir, fname, NULL); 742} 743 744intmatch_basename(const char*basename,int basenamelen, 745const char*pattern,int prefix,int patternlen, 746int flags) 747{ 748if(prefix == patternlen) { 749if(patternlen == basenamelen && 750!strncmp_icase(pattern, basename, basenamelen)) 751return1; 752}else if(flags & EXC_FLAG_ENDSWITH) { 753/* "*literal" matching against "fooliteral" */ 754if(patternlen -1<= basenamelen && 755!strncmp_icase(pattern +1, 756 basename + basenamelen - (patternlen -1), 757 patternlen -1)) 758return1; 759}else{ 760if(fnmatch_icase_mem(pattern, patternlen, 761 basename, basenamelen, 7620) ==0) 763return1; 764} 765return0; 766} 767 768intmatch_pathname(const char*pathname,int pathlen, 769const char*base,int baselen, 770const char*pattern,int prefix,int patternlen, 771int flags) 772{ 773const char*name; 774int namelen; 775 776/* 777 * match with FNM_PATHNAME; the pattern has base implicitly 778 * in front of it. 779 */ 780if(*pattern =='/') { 781 pattern++; 782 patternlen--; 783 prefix--; 784} 785 786/* 787 * baselen does not count the trailing slash. base[] may or 788 * may not end with a trailing slash though. 789 */ 790if(pathlen < baselen +1|| 791(baselen && pathname[baselen] !='/') || 792strncmp_icase(pathname, base, baselen)) 793return0; 794 795 namelen = baselen ? pathlen - baselen -1: pathlen; 796 name = pathname + pathlen - namelen; 797 798if(prefix) { 799/* 800 * if the non-wildcard part is longer than the 801 * remaining pathname, surely it cannot match. 802 */ 803if(prefix > namelen) 804return0; 805 806if(strncmp_icase(pattern, name, prefix)) 807return0; 808 pattern += prefix; 809 patternlen -= prefix; 810 name += prefix; 811 namelen -= prefix; 812 813/* 814 * If the whole pattern did not have a wildcard, 815 * then our prefix match is all we need; we 816 * do not need to call fnmatch at all. 817 */ 818if(!patternlen && !namelen) 819return1; 820} 821 822returnfnmatch_icase_mem(pattern, patternlen, 823 name, namelen, 824 WM_PATHNAME) ==0; 825} 826 827/* 828 * Scan the given exclude list in reverse to see whether pathname 829 * should be ignored. The first match (i.e. the last on the list), if 830 * any, determines the fate. Returns the exclude_list element which 831 * matched, or NULL for undecided. 832 */ 833static struct exclude *last_exclude_matching_from_list(const char*pathname, 834int pathlen, 835const char*basename, 836int*dtype, 837struct exclude_list *el) 838{ 839int i; 840 841if(!el->nr) 842return NULL;/* undefined */ 843 844for(i = el->nr -1;0<= i; i--) { 845struct exclude *x = el->excludes[i]; 846const char*exclude = x->pattern; 847int prefix = x->nowildcardlen; 848 849if(x->flags & EXC_FLAG_MUSTBEDIR) { 850if(*dtype == DT_UNKNOWN) 851*dtype =get_dtype(NULL, pathname, pathlen); 852if(*dtype != DT_DIR) 853continue; 854} 855 856if(x->flags & EXC_FLAG_NODIR) { 857if(match_basename(basename, 858 pathlen - (basename - pathname), 859 exclude, prefix, x->patternlen, 860 x->flags)) 861return x; 862continue; 863} 864 865assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 866if(match_pathname(pathname, pathlen, 867 x->base, x->baselen ? x->baselen -1:0, 868 exclude, prefix, x->patternlen, x->flags)) 869return x; 870} 871return NULL;/* undecided */ 872} 873 874/* 875 * Scan the list and let the last match determine the fate. 876 * Return 1 for exclude, 0 for include and -1 for undecided. 877 */ 878intis_excluded_from_list(const char*pathname, 879int pathlen,const char*basename,int*dtype, 880struct exclude_list *el) 881{ 882struct exclude *exclude; 883 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 884if(exclude) 885return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 886return-1;/* undecided */ 887} 888 889static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 890const char*pathname,int pathlen,const char*basename, 891int*dtype_p) 892{ 893int i, j; 894struct exclude_list_group *group; 895struct exclude *exclude; 896for(i = EXC_CMDL; i <= EXC_FILE; i++) { 897 group = &dir->exclude_list_group[i]; 898for(j = group->nr -1; j >=0; j--) { 899 exclude =last_exclude_matching_from_list( 900 pathname, pathlen, basename, dtype_p, 901&group->el[j]); 902if(exclude) 903return exclude; 904} 905} 906return NULL; 907} 908 909/* 910 * Loads the per-directory exclude list for the substring of base 911 * which has a char length of baselen. 912 */ 913static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen) 914{ 915struct exclude_list_group *group; 916struct exclude_list *el; 917struct exclude_stack *stk = NULL; 918struct untracked_cache_dir *untracked; 919int current; 920 921 group = &dir->exclude_list_group[EXC_DIRS]; 922 923/* 924 * Pop the exclude lists from the EXCL_DIRS exclude_list_group 925 * which originate from directories not in the prefix of the 926 * path being checked. 927 */ 928while((stk = dir->exclude_stack) != NULL) { 929if(stk->baselen <= baselen && 930!strncmp(dir->basebuf.buf, base, stk->baselen)) 931break; 932 el = &group->el[dir->exclude_stack->exclude_ix]; 933 dir->exclude_stack = stk->prev; 934 dir->exclude = NULL; 935free((char*)el->src);/* see strbuf_detach() below */ 936clear_exclude_list(el); 937free(stk); 938 group->nr--; 939} 940 941/* Skip traversing into sub directories if the parent is excluded */ 942if(dir->exclude) 943return; 944 945/* 946 * Lazy initialization. All call sites currently just 947 * memset(dir, 0, sizeof(*dir)) before use. Changing all of 948 * them seems lots of work for little benefit. 949 */ 950if(!dir->basebuf.buf) 951strbuf_init(&dir->basebuf, PATH_MAX); 952 953/* Read from the parent directories and push them down. */ 954 current = stk ? stk->baselen : -1; 955strbuf_setlen(&dir->basebuf, current <0?0: current); 956if(dir->untracked) 957 untracked = stk ? stk->ucd : dir->untracked->root; 958else 959 untracked = NULL; 960 961while(current < baselen) { 962const char*cp; 963struct sha1_stat sha1_stat; 964 965 stk =xcalloc(1,sizeof(*stk)); 966if(current <0) { 967 cp = base; 968 current =0; 969}else{ 970 cp =strchr(base + current +1,'/'); 971if(!cp) 972die("oops in prep_exclude"); 973 cp++; 974 untracked = 975lookup_untracked(dir->untracked, untracked, 976 base + current, 977 cp - base - current); 978} 979 stk->prev = dir->exclude_stack; 980 stk->baselen = cp - base; 981 stk->exclude_ix = group->nr; 982 stk->ucd = untracked; 983 el =add_exclude_list(dir, EXC_DIRS, NULL); 984strbuf_add(&dir->basebuf, base + current, stk->baselen - current); 985assert(stk->baselen == dir->basebuf.len); 986 987/* Abort if the directory is excluded */ 988if(stk->baselen) { 989int dt = DT_DIR; 990 dir->basebuf.buf[stk->baselen -1] =0; 991 dir->exclude =last_exclude_matching_from_lists(dir, 992 dir->basebuf.buf, stk->baselen -1, 993 dir->basebuf.buf + current, &dt); 994 dir->basebuf.buf[stk->baselen -1] ='/'; 995if(dir->exclude && 996 dir->exclude->flags & EXC_FLAG_NEGATIVE) 997 dir->exclude = NULL; 998if(dir->exclude) { 999 dir->exclude_stack = stk;1000return;1001}1002}10031004/* Try to read per-directory file */1005hashclr(sha1_stat.sha1);1006 sha1_stat.valid =0;1007if(dir->exclude_per_dir) {1008/*1009 * dir->basebuf gets reused by the traversal, but we1010 * need fname to remain unchanged to ensure the src1011 * member of each struct exclude correctly1012 * back-references its source file. Other invocations1013 * of add_exclude_list provide stable strings, so we1014 * strbuf_detach() and free() here in the caller.1015 */1016struct strbuf sb = STRBUF_INIT;1017strbuf_addbuf(&sb, &dir->basebuf);1018strbuf_addstr(&sb, dir->exclude_per_dir);1019 el->src =strbuf_detach(&sb, NULL);1020add_excludes(el->src, el->src, stk->baselen, el,1,1021 untracked ? &sha1_stat : NULL);1022}1023/*1024 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1025 * will first be called in valid_cached_dir() then maybe many1026 * times more in last_exclude_matching(). When the cache is1027 * used, last_exclude_matching() will not be called and1028 * reading .gitignore content will be a waste.1029 *1030 * So when it's called by valid_cached_dir() and we can get1031 * .gitignore SHA-1 from the index (i.e. .gitignore is not1032 * modified on work tree), we could delay reading the1033 * .gitignore content until we absolutely need it in1034 * last_exclude_matching(). Be careful about ignore rule1035 * order, though, if you do that.1036 */1037if(untracked &&1038hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1039invalidate_gitignore(dir->untracked, untracked);1040hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1041}1042 dir->exclude_stack = stk;1043 current = stk->baselen;1044}1045strbuf_setlen(&dir->basebuf, baselen);1046}10471048/*1049 * Loads the exclude lists for the directory containing pathname, then1050 * scans all exclude lists to determine whether pathname is excluded.1051 * Returns the exclude_list element which matched, or NULL for1052 * undecided.1053 */1054struct exclude *last_exclude_matching(struct dir_struct *dir,1055const char*pathname,1056int*dtype_p)1057{1058int pathlen =strlen(pathname);1059const char*basename =strrchr(pathname,'/');1060 basename = (basename) ? basename+1: pathname;10611062prep_exclude(dir, pathname, basename-pathname);10631064if(dir->exclude)1065return dir->exclude;10661067returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1068 basename, dtype_p);1069}10701071/*1072 * Loads the exclude lists for the directory containing pathname, then1073 * scans all exclude lists to determine whether pathname is excluded.1074 * Returns 1 if true, otherwise 0.1075 */1076intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1077{1078struct exclude *exclude =1079last_exclude_matching(dir, pathname, dtype_p);1080if(exclude)1081return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1082return0;1083}10841085static struct dir_entry *dir_entry_new(const char*pathname,int len)1086{1087struct dir_entry *ent;10881089 ent =xmalloc(sizeof(*ent) + len +1);1090 ent->len = len;1091memcpy(ent->name, pathname, len);1092 ent->name[len] =0;1093return ent;1094}10951096static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1097{1098if(cache_file_exists(pathname, len, ignore_case))1099return NULL;11001101ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1102return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1103}11041105struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1106{1107if(!cache_name_is_other(pathname, len))1108return NULL;11091110ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1111return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1112}11131114enum exist_status {1115 index_nonexistent =0,1116 index_directory,1117 index_gitdir1118};11191120/*1121 * Do not use the alphabetically sorted index to look up1122 * the directory name; instead, use the case insensitive1123 * directory hash.1124 */1125static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1126{1127const struct cache_entry *ce =cache_dir_exists(dirname, len);1128unsigned char endchar;11291130if(!ce)1131return index_nonexistent;1132 endchar = ce->name[len];11331134/*1135 * The cache_entry structure returned will contain this dirname1136 * and possibly additional path components.1137 */1138if(endchar =='/')1139return index_directory;11401141/*1142 * If there are no additional path components, then this cache_entry1143 * represents a submodule. Submodules, despite being directories,1144 * are stored in the cache without a closing slash.1145 */1146if(!endchar &&S_ISGITLINK(ce->ce_mode))1147return index_gitdir;11481149/* This should never be hit, but it exists just in case. */1150return index_nonexistent;1151}11521153/*1154 * The index sorts alphabetically by entry name, which1155 * means that a gitlink sorts as '\0' at the end, while1156 * a directory (which is defined not as an entry, but as1157 * the files it contains) will sort with the '/' at the1158 * end.1159 */1160static enum exist_status directory_exists_in_index(const char*dirname,int len)1161{1162int pos;11631164if(ignore_case)1165returndirectory_exists_in_index_icase(dirname, len);11661167 pos =cache_name_pos(dirname, len);1168if(pos <0)1169 pos = -pos-1;1170while(pos < active_nr) {1171const struct cache_entry *ce = active_cache[pos++];1172unsigned char endchar;11731174if(strncmp(ce->name, dirname, len))1175break;1176 endchar = ce->name[len];1177if(endchar >'/')1178break;1179if(endchar =='/')1180return index_directory;1181if(!endchar &&S_ISGITLINK(ce->ce_mode))1182return index_gitdir;1183}1184return index_nonexistent;1185}11861187/*1188 * When we find a directory when traversing the filesystem, we1189 * have three distinct cases:1190 *1191 * - ignore it1192 * - see it as a directory1193 * - recurse into it1194 *1195 * and which one we choose depends on a combination of existing1196 * git index contents and the flags passed into the directory1197 * traversal routine.1198 *1199 * Case 1: If we *already* have entries in the index under that1200 * directory name, we always recurse into the directory to see1201 * all the files.1202 *1203 * Case 2: If we *already* have that directory name as a gitlink,1204 * we always continue to see it as a gitlink, regardless of whether1205 * there is an actual git directory there or not (it might not1206 * be checked out as a subproject!)1207 *1208 * Case 3: if we didn't have it in the index previously, we1209 * have a few sub-cases:1210 *1211 * (a) if "show_other_directories" is true, we show it as1212 * just a directory, unless "hide_empty_directories" is1213 * also true, in which case we need to check if it contains any1214 * untracked and / or ignored files.1215 * (b) if it looks like a git directory, and we don't have1216 * 'no_gitlinks' set we treat it as a gitlink, and show it1217 * as a directory.1218 * (c) otherwise, we recurse into it.1219 */1220static enum path_treatment treat_directory(struct dir_struct *dir,1221struct untracked_cache_dir *untracked,1222const char*dirname,int len,int exclude,1223const struct path_simplify *simplify)1224{1225/* The "len-1" is to strip the final '/' */1226switch(directory_exists_in_index(dirname, len-1)) {1227case index_directory:1228return path_recurse;12291230case index_gitdir:1231return path_none;12321233case index_nonexistent:1234if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1235break;1236if(!(dir->flags & DIR_NO_GITLINKS)) {1237unsigned char sha1[20];1238if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1239return path_untracked;1240}1241return path_recurse;1242}12431244/* This is the "show_other_directories" case */12451246if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1247return exclude ? path_excluded : path_untracked;12481249 untracked =lookup_untracked(dir->untracked, untracked, dirname, len);1250returnread_directory_recursive(dir, dirname, len,1251 untracked,1, simplify);1252}12531254/*1255 * This is an inexact early pruning of any recursive directory1256 * reading - if the path cannot possibly be in the pathspec,1257 * return true, and we'll skip it early.1258 */1259static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1260{1261if(simplify) {1262for(;;) {1263const char*match = simplify->path;1264int len = simplify->len;12651266if(!match)1267break;1268if(len > pathlen)1269 len = pathlen;1270if(!memcmp(path, match, len))1271return0;1272 simplify++;1273}1274return1;1275}1276return0;1277}12781279/*1280 * This function tells us whether an excluded path matches a1281 * list of "interesting" pathspecs. That is, whether a path matched1282 * by any of the pathspecs could possibly be ignored by excluding1283 * the specified path. This can happen if:1284 *1285 * 1. the path is mentioned explicitly in the pathspec1286 *1287 * 2. the path is a directory prefix of some element in the1288 * pathspec1289 */1290static intexclude_matches_pathspec(const char*path,int len,1291const struct path_simplify *simplify)1292{1293if(simplify) {1294for(; simplify->path; simplify++) {1295if(len == simplify->len1296&& !memcmp(path, simplify->path, len))1297return1;1298if(len < simplify->len1299&& simplify->path[len] =='/'1300&& !memcmp(path, simplify->path, len))1301return1;1302}1303}1304return0;1305}13061307static intget_index_dtype(const char*path,int len)1308{1309int pos;1310const struct cache_entry *ce;13111312 ce =cache_file_exists(path, len,0);1313if(ce) {1314if(!ce_uptodate(ce))1315return DT_UNKNOWN;1316if(S_ISGITLINK(ce->ce_mode))1317return DT_DIR;1318/*1319 * Nobody actually cares about the1320 * difference between DT_LNK and DT_REG1321 */1322return DT_REG;1323}13241325/* Try to look it up as a directory */1326 pos =cache_name_pos(path, len);1327if(pos >=0)1328return DT_UNKNOWN;1329 pos = -pos-1;1330while(pos < active_nr) {1331 ce = active_cache[pos++];1332if(strncmp(ce->name, path, len))1333break;1334if(ce->name[len] >'/')1335break;1336if(ce->name[len] <'/')1337continue;1338if(!ce_uptodate(ce))1339break;/* continue? */1340return DT_DIR;1341}1342return DT_UNKNOWN;1343}13441345static intget_dtype(struct dirent *de,const char*path,int len)1346{1347int dtype = de ?DTYPE(de) : DT_UNKNOWN;1348struct stat st;13491350if(dtype != DT_UNKNOWN)1351return dtype;1352 dtype =get_index_dtype(path, len);1353if(dtype != DT_UNKNOWN)1354return dtype;1355if(lstat(path, &st))1356return dtype;1357if(S_ISREG(st.st_mode))1358return DT_REG;1359if(S_ISDIR(st.st_mode))1360return DT_DIR;1361if(S_ISLNK(st.st_mode))1362return DT_LNK;1363return dtype;1364}13651366static enum path_treatment treat_one_path(struct dir_struct *dir,1367struct untracked_cache_dir *untracked,1368struct strbuf *path,1369const struct path_simplify *simplify,1370int dtype,struct dirent *de)1371{1372int exclude;1373int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);13741375if(dtype == DT_UNKNOWN)1376 dtype =get_dtype(de, path->buf, path->len);13771378/* Always exclude indexed files */1379if(dtype != DT_DIR && has_path_in_index)1380return path_none;13811382/*1383 * When we are looking at a directory P in the working tree,1384 * there are three cases:1385 *1386 * (1) P exists in the index. Everything inside the directory P in1387 * the working tree needs to go when P is checked out from the1388 * index.1389 *1390 * (2) P does not exist in the index, but there is P/Q in the index.1391 * We know P will stay a directory when we check out the contents1392 * of the index, but we do not know yet if there is a directory1393 * P/Q in the working tree to be killed, so we need to recurse.1394 *1395 * (3) P does not exist in the index, and there is no P/Q in the index1396 * to require P to be a directory, either. Only in this case, we1397 * know that everything inside P will not be killed without1398 * recursing.1399 */1400if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1401(dtype == DT_DIR) &&1402!has_path_in_index &&1403(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1404return path_none;14051406 exclude =is_excluded(dir, path->buf, &dtype);14071408/*1409 * Excluded? If we don't explicitly want to show1410 * ignored files, ignore it1411 */1412if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1413return path_excluded;14141415switch(dtype) {1416default:1417return path_none;1418case DT_DIR:1419strbuf_addch(path,'/');1420returntreat_directory(dir, untracked, path->buf, path->len, exclude,1421 simplify);1422case DT_REG:1423case DT_LNK:1424return exclude ? path_excluded : path_untracked;1425}1426}14271428static enum path_treatment treat_path(struct dir_struct *dir,1429struct untracked_cache_dir *untracked,1430struct cached_dir *cdir,1431struct strbuf *path,1432int baselen,1433const struct path_simplify *simplify)1434{1435int dtype;1436struct dirent *de = cdir->de;14371438if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1439return path_none;1440strbuf_setlen(path, baselen);1441strbuf_addstr(path, de->d_name);1442if(simplify_away(path->buf, path->len, simplify))1443return path_none;14441445 dtype =DTYPE(de);1446returntreat_one_path(dir, untracked, path, simplify, dtype, de);1447}14481449static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1450{1451if(!dir)1452return;1453ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1454 dir->untracked_alloc);1455 dir->untracked[dir->untracked_nr++] =xstrdup(name);1456}14571458static intopen_cached_dir(struct cached_dir *cdir,1459struct dir_struct *dir,1460struct untracked_cache_dir *untracked,1461struct strbuf *path,1462int check_only)1463{1464memset(cdir,0,sizeof(*cdir));1465 cdir->untracked = untracked;1466 cdir->fdir =opendir(path->len ? path->buf :".");1467if(!cdir->fdir)1468return-1;1469return0;1470}14711472static intread_cached_dir(struct cached_dir *cdir)1473{1474if(cdir->fdir) {1475 cdir->de =readdir(cdir->fdir);1476if(!cdir->de)1477return-1;1478return0;1479}1480return-1;1481}14821483static voidclose_cached_dir(struct cached_dir *cdir)1484{1485if(cdir->fdir)1486closedir(cdir->fdir);1487}14881489/*1490 * Read a directory tree. We currently ignore anything but1491 * directories, regular files and symlinks. That's because git1492 * doesn't handle them at all yet. Maybe that will change some1493 * day.1494 *1495 * Also, we ignore the name ".git" (even if it is not a directory).1496 * That likely will not change.1497 *1498 * Returns the most significant path_treatment value encountered in the scan.1499 */1500static enum path_treatment read_directory_recursive(struct dir_struct *dir,1501const char*base,int baselen,1502struct untracked_cache_dir *untracked,int check_only,1503const struct path_simplify *simplify)1504{1505struct cached_dir cdir;1506enum path_treatment state, subdir_state, dir_state = path_none;1507struct strbuf path = STRBUF_INIT;15081509strbuf_add(&path, base, baselen);15101511if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1512goto out;15131514if(untracked)1515 untracked->check_only = !!check_only;15161517while(!read_cached_dir(&cdir)) {1518/* check how the file or directory should be treated */1519 state =treat_path(dir, untracked, &cdir, &path, baselen, simplify);15201521if(state > dir_state)1522 dir_state = state;15231524/* recurse into subdir if instructed by treat_path */1525if(state == path_recurse) {1526struct untracked_cache_dir *ud;1527 ud =lookup_untracked(dir->untracked, untracked,1528 path.buf + baselen,1529 path.len - baselen);1530 subdir_state =1531read_directory_recursive(dir, path.buf, path.len,1532 ud, check_only, simplify);1533if(subdir_state > dir_state)1534 dir_state = subdir_state;1535}15361537if(check_only) {1538/* abort early if maximum state has been reached */1539if(dir_state == path_untracked) {1540if(untracked)1541add_untracked(untracked, path.buf + baselen);1542break;1543}1544/* skip the dir_add_* part */1545continue;1546}15471548/* add the path to the appropriate result list */1549switch(state) {1550case path_excluded:1551if(dir->flags & DIR_SHOW_IGNORED)1552dir_add_name(dir, path.buf, path.len);1553else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1554((dir->flags & DIR_COLLECT_IGNORED) &&1555exclude_matches_pathspec(path.buf, path.len,1556 simplify)))1557dir_add_ignored(dir, path.buf, path.len);1558break;15591560case path_untracked:1561if(dir->flags & DIR_SHOW_IGNORED)1562break;1563dir_add_name(dir, path.buf, path.len);1564if(untracked)1565add_untracked(untracked, path.buf + baselen);1566break;15671568default:1569break;1570}1571}1572close_cached_dir(&cdir);1573 out:1574strbuf_release(&path);15751576return dir_state;1577}15781579static intcmp_name(const void*p1,const void*p2)1580{1581const struct dir_entry *e1 = *(const struct dir_entry **)p1;1582const struct dir_entry *e2 = *(const struct dir_entry **)p2;15831584returnname_compare(e1->name, e1->len, e2->name, e2->len);1585}15861587static struct path_simplify *create_simplify(const char**pathspec)1588{1589int nr, alloc =0;1590struct path_simplify *simplify = NULL;15911592if(!pathspec)1593return NULL;15941595for(nr =0; ; nr++) {1596const char*match;1597ALLOC_GROW(simplify, nr +1, alloc);1598 match = *pathspec++;1599if(!match)1600break;1601 simplify[nr].path = match;1602 simplify[nr].len =simple_length(match);1603}1604 simplify[nr].path = NULL;1605 simplify[nr].len =0;1606return simplify;1607}16081609static voidfree_simplify(struct path_simplify *simplify)1610{1611free(simplify);1612}16131614static inttreat_leading_path(struct dir_struct *dir,1615const char*path,int len,1616const struct path_simplify *simplify)1617{1618struct strbuf sb = STRBUF_INIT;1619int baselen, rc =0;1620const char*cp;1621int old_flags = dir->flags;16221623while(len && path[len -1] =='/')1624 len--;1625if(!len)1626return1;1627 baselen =0;1628 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1629while(1) {1630 cp = path + baselen + !!baselen;1631 cp =memchr(cp,'/', path + len - cp);1632if(!cp)1633 baselen = len;1634else1635 baselen = cp - path;1636strbuf_setlen(&sb,0);1637strbuf_add(&sb, path, baselen);1638if(!is_directory(sb.buf))1639break;1640if(simplify_away(sb.buf, sb.len, simplify))1641break;1642if(treat_one_path(dir, NULL, &sb, simplify,1643 DT_DIR, NULL) == path_none)1644break;/* do not recurse into it */1645if(len <= baselen) {1646 rc =1;1647break;/* finished checking */1648}1649}1650strbuf_release(&sb);1651 dir->flags = old_flags;1652return rc;1653}16541655static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1656int base_len,1657const struct pathspec *pathspec)1658{1659struct untracked_cache_dir *root;16601661if(!dir->untracked)1662return NULL;16631664/*1665 * We only support $GIT_DIR/info/exclude and core.excludesfile1666 * as the global ignore rule files. Any other additions1667 * (e.g. from command line) invalidate the cache. This1668 * condition also catches running setup_standard_excludes()1669 * before setting dir->untracked!1670 */1671if(dir->unmanaged_exclude_files)1672return NULL;16731674/*1675 * Optimize for the main use case only: whole-tree git1676 * status. More work involved in treat_leading_path() if we1677 * use cache on just a subset of the worktree. pathspec1678 * support could make the matter even worse.1679 */1680if(base_len || (pathspec && pathspec->nr))1681return NULL;16821683/* Different set of flags may produce different results */1684if(dir->flags != dir->untracked->dir_flags ||1685/*1686 * See treat_directory(), case index_nonexistent. Without1687 * this flag, we may need to also cache .git file content1688 * for the resolve_gitlink_ref() call, which we don't.1689 */1690!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1691/* We don't support collecting ignore files */1692(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1693 DIR_COLLECT_IGNORED)))1694return NULL;16951696/*1697 * If we use .gitignore in the cache and now you change it to1698 * .gitexclude, everything will go wrong.1699 */1700if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1701strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1702return NULL;17031704/*1705 * EXC_CMDL is not considered in the cache. If people set it,1706 * skip the cache.1707 */1708if(dir->exclude_list_group[EXC_CMDL].nr)1709return NULL;17101711if(!dir->untracked->root) {1712const int len =sizeof(*dir->untracked->root);1713 dir->untracked->root =xmalloc(len);1714memset(dir->untracked->root,0, len);1715}17161717/* Validate $GIT_DIR/info/exclude and core.excludesfile */1718 root = dir->untracked->root;1719if(hashcmp(dir->ss_info_exclude.sha1,1720 dir->untracked->ss_info_exclude.sha1)) {1721invalidate_gitignore(dir->untracked, root);1722 dir->untracked->ss_info_exclude = dir->ss_info_exclude;1723}1724if(hashcmp(dir->ss_excludes_file.sha1,1725 dir->untracked->ss_excludes_file.sha1)) {1726invalidate_gitignore(dir->untracked, root);1727 dir->untracked->ss_excludes_file = dir->ss_excludes_file;1728}1729return root;1730}17311732intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)1733{1734struct path_simplify *simplify;1735struct untracked_cache_dir *untracked;17361737/*1738 * Check out create_simplify()1739 */1740if(pathspec)1741GUARD_PATHSPEC(pathspec,1742 PATHSPEC_FROMTOP |1743 PATHSPEC_MAXDEPTH |1744 PATHSPEC_LITERAL |1745 PATHSPEC_GLOB |1746 PATHSPEC_ICASE |1747 PATHSPEC_EXCLUDE);17481749if(has_symlink_leading_path(path, len))1750return dir->nr;17511752/*1753 * exclude patterns are treated like positive ones in1754 * create_simplify. Usually exclude patterns should be a1755 * subset of positive ones, which has no impacts on1756 * create_simplify().1757 */1758 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);1759 untracked =validate_untracked_cache(dir, len, pathspec);1760if(!untracked)1761/*1762 * make sure untracked cache code path is disabled,1763 * e.g. prep_exclude()1764 */1765 dir->untracked = NULL;1766if(!len ||treat_leading_path(dir, path, len, simplify))1767read_directory_recursive(dir, path, len, untracked,0, simplify);1768free_simplify(simplify);1769qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);1770qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);1771return dir->nr;1772}17731774intfile_exists(const char*f)1775{1776struct stat sb;1777returnlstat(f, &sb) ==0;1778}17791780/*1781 * Given two normalized paths (a trailing slash is ok), if subdir is1782 * outside dir, return -1. Otherwise return the offset in subdir that1783 * can be used as relative path to dir.1784 */1785intdir_inside_of(const char*subdir,const char*dir)1786{1787int offset =0;17881789assert(dir && subdir && *dir && *subdir);17901791while(*dir && *subdir && *dir == *subdir) {1792 dir++;1793 subdir++;1794 offset++;1795}17961797/* hel[p]/me vs hel[l]/yeah */1798if(*dir && *subdir)1799return-1;18001801if(!*subdir)1802return!*dir ? offset : -1;/* same dir */18031804/* foo/[b]ar vs foo/[] */1805if(is_dir_sep(dir[-1]))1806returnis_dir_sep(subdir[-1]) ? offset : -1;18071808/* foo[/]bar vs foo[] */1809returnis_dir_sep(*subdir) ? offset +1: -1;1810}18111812intis_inside_dir(const char*dir)1813{1814char*cwd;1815int rc;18161817if(!dir)1818return0;18191820 cwd =xgetcwd();1821 rc = (dir_inside_of(cwd, dir) >=0);1822free(cwd);1823return rc;1824}18251826intis_empty_dir(const char*path)1827{1828DIR*dir =opendir(path);1829struct dirent *e;1830int ret =1;18311832if(!dir)1833return0;18341835while((e =readdir(dir)) != NULL)1836if(!is_dot_or_dotdot(e->d_name)) {1837 ret =0;1838break;1839}18401841closedir(dir);1842return ret;1843}18441845static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)1846{1847DIR*dir;1848struct dirent *e;1849int ret =0, original_len = path->len, len, kept_down =0;1850int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);1851int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);1852unsigned char submodule_head[20];18531854if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&1855!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {1856/* Do not descend and nuke a nested git work tree. */1857if(kept_up)1858*kept_up =1;1859return0;1860}18611862 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;1863 dir =opendir(path->buf);1864if(!dir) {1865if(errno == ENOENT)1866return keep_toplevel ? -1:0;1867else if(errno == EACCES && !keep_toplevel)1868/*1869 * An empty dir could be removable even if it1870 * is unreadable:1871 */1872returnrmdir(path->buf);1873else1874return-1;1875}1876if(path->buf[original_len -1] !='/')1877strbuf_addch(path,'/');18781879 len = path->len;1880while((e =readdir(dir)) != NULL) {1881struct stat st;1882if(is_dot_or_dotdot(e->d_name))1883continue;18841885strbuf_setlen(path, len);1886strbuf_addstr(path, e->d_name);1887if(lstat(path->buf, &st)) {1888if(errno == ENOENT)1889/*1890 * file disappeared, which is what we1891 * wanted anyway1892 */1893continue;1894/* fall thru */1895}else if(S_ISDIR(st.st_mode)) {1896if(!remove_dir_recurse(path, flag, &kept_down))1897continue;/* happy */1898}else if(!only_empty &&1899(!unlink(path->buf) || errno == ENOENT)) {1900continue;/* happy, too */1901}19021903/* path too long, stat fails, or non-directory still exists */1904 ret = -1;1905break;1906}1907closedir(dir);19081909strbuf_setlen(path, original_len);1910if(!ret && !keep_toplevel && !kept_down)1911 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;1912else if(kept_up)1913/*1914 * report the uplevel that it is not an error that we1915 * did not rmdir() our directory.1916 */1917*kept_up = !ret;1918return ret;1919}19201921intremove_dir_recursively(struct strbuf *path,int flag)1922{1923returnremove_dir_recurse(path, flag, NULL);1924}19251926voidsetup_standard_excludes(struct dir_struct *dir)1927{1928const char*path;1929char*xdg_path;19301931 dir->exclude_per_dir =".gitignore";1932 path =git_path("info/exclude");1933if(!excludes_file) {1934home_config_paths(NULL, &xdg_path,"ignore");1935 excludes_file = xdg_path;1936}1937if(!access_or_warn(path, R_OK,0))1938add_excludes_from_file_1(dir, path,1939 dir->untracked ? &dir->ss_info_exclude : NULL);1940if(excludes_file && !access_or_warn(excludes_file, R_OK,0))1941add_excludes_from_file_1(dir, excludes_file,1942 dir->untracked ? &dir->ss_excludes_file : NULL);1943}19441945intremove_path(const char*name)1946{1947char*slash;19481949if(unlink(name) && errno != ENOENT && errno != ENOTDIR)1950return-1;19511952 slash =strrchr(name,'/');1953if(slash) {1954char*dirs =xstrdup(name);1955 slash = dirs + (slash - name);1956do{1957*slash ='\0';1958}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));1959free(dirs);1960}1961return0;1962}19631964/*1965 * Frees memory within dir which was allocated for exclude lists and1966 * the exclude_stack. Does not free dir itself.1967 */1968voidclear_directory(struct dir_struct *dir)1969{1970int i, j;1971struct exclude_list_group *group;1972struct exclude_list *el;1973struct exclude_stack *stk;19741975for(i = EXC_CMDL; i <= EXC_FILE; i++) {1976 group = &dir->exclude_list_group[i];1977for(j =0; j < group->nr; j++) {1978 el = &group->el[j];1979if(i == EXC_DIRS)1980free((char*)el->src);1981clear_exclude_list(el);1982}1983free(group->el);1984}19851986 stk = dir->exclude_stack;1987while(stk) {1988struct exclude_stack *prev = stk->prev;1989free(stk);1990 stk = prev;1991}1992strbuf_release(&dir->basebuf);1993}