1/* 2 * This handles recursive filename detection with exclude 3 * files, index knowledge etc.. 4 * 5 * See Documentation/technical/api-directory-listing.txt 6 * 7 * Copyright (C) Linus Torvalds, 2005-2006 8 * Junio Hamano, 2005-2006 9 */ 10#include"cache.h" 11#include"dir.h" 12#include"refs.h" 13#include"wildmatch.h" 14#include"pathspec.h" 15 16struct path_simplify { 17int len; 18const char*path; 19}; 20 21/* 22 * Tells read_directory_recursive how a file or directory should be treated. 23 * Values are ordered by significance, e.g. if a directory contains both 24 * excluded and untracked files, it is listed as untracked because 25 * path_untracked > path_excluded. 26 */ 27enum path_treatment { 28 path_none =0, 29 path_recurse, 30 path_excluded, 31 path_untracked 32}; 33 34/* 35 * Support data structure for our opendir/readdir/closedir wrappers 36 */ 37struct cached_dir { 38DIR*fdir; 39struct untracked_cache_dir *untracked; 40int nr_files; 41int nr_dirs; 42 43struct dirent *de; 44const char*file; 45struct untracked_cache_dir *ucd; 46}; 47 48static enum path_treatment read_directory_recursive(struct dir_struct *dir, 49const char*path,int len,struct untracked_cache_dir *untracked, 50int check_only,const struct path_simplify *simplify); 51static intget_dtype(struct dirent *de,const char*path,int len); 52 53/* helper string functions with support for the ignore_case flag */ 54intstrcmp_icase(const char*a,const char*b) 55{ 56return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 57} 58 59intstrncmp_icase(const char*a,const char*b,size_t count) 60{ 61return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 62} 63 64intfnmatch_icase(const char*pattern,const char*string,int flags) 65{ 66returnwildmatch(pattern, string, 67 flags | (ignore_case ? WM_CASEFOLD :0), 68 NULL); 69} 70 71intgit_fnmatch(const struct pathspec_item *item, 72const char*pattern,const char*string, 73int prefix) 74{ 75if(prefix >0) { 76if(ps_strncmp(item, pattern, string, prefix)) 77return WM_NOMATCH; 78 pattern += prefix; 79 string += prefix; 80} 81if(item->flags & PATHSPEC_ONESTAR) { 82int pattern_len =strlen(++pattern); 83int string_len =strlen(string); 84return string_len < pattern_len || 85ps_strcmp(item, pattern, 86 string + string_len - pattern_len); 87} 88if(item->magic & PATHSPEC_GLOB) 89returnwildmatch(pattern, string, 90 WM_PATHNAME | 91(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 92 NULL); 93else 94/* wildmatch has not learned no FNM_PATHNAME mode yet */ 95returnwildmatch(pattern, string, 96 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 97 NULL); 98} 99 100static intfnmatch_icase_mem(const char*pattern,int patternlen, 101const char*string,int stringlen, 102int flags) 103{ 104int match_status; 105struct strbuf pat_buf = STRBUF_INIT; 106struct strbuf str_buf = STRBUF_INIT; 107const char*use_pat = pattern; 108const char*use_str = string; 109 110if(pattern[patternlen]) { 111strbuf_add(&pat_buf, pattern, patternlen); 112 use_pat = pat_buf.buf; 113} 114if(string[stringlen]) { 115strbuf_add(&str_buf, string, stringlen); 116 use_str = str_buf.buf; 117} 118 119if(ignore_case) 120 flags |= WM_CASEFOLD; 121 match_status =wildmatch(use_pat, use_str, flags, NULL); 122 123strbuf_release(&pat_buf); 124strbuf_release(&str_buf); 125 126return match_status; 127} 128 129static size_tcommon_prefix_len(const struct pathspec *pathspec) 130{ 131int n; 132size_t max =0; 133 134/* 135 * ":(icase)path" is treated as a pathspec full of 136 * wildcard. In other words, only prefix is considered common 137 * prefix. If the pathspec is abc/foo abc/bar, running in 138 * subdir xyz, the common prefix is still xyz, not xuz/abc as 139 * in non-:(icase). 140 */ 141GUARD_PATHSPEC(pathspec, 142 PATHSPEC_FROMTOP | 143 PATHSPEC_MAXDEPTH | 144 PATHSPEC_LITERAL | 145 PATHSPEC_GLOB | 146 PATHSPEC_ICASE | 147 PATHSPEC_EXCLUDE); 148 149for(n =0; n < pathspec->nr; n++) { 150size_t i =0, len =0, item_len; 151if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 152continue; 153if(pathspec->items[n].magic & PATHSPEC_ICASE) 154 item_len = pathspec->items[n].prefix; 155else 156 item_len = pathspec->items[n].nowildcard_len; 157while(i < item_len && (n ==0|| i < max)) { 158char c = pathspec->items[n].match[i]; 159if(c != pathspec->items[0].match[i]) 160break; 161if(c =='/') 162 len = i +1; 163 i++; 164} 165if(n ==0|| len < max) { 166 max = len; 167if(!max) 168break; 169} 170} 171return max; 172} 173 174/* 175 * Returns a copy of the longest leading path common among all 176 * pathspecs. 177 */ 178char*common_prefix(const struct pathspec *pathspec) 179{ 180unsigned long len =common_prefix_len(pathspec); 181 182return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 183} 184 185intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 186{ 187size_t len; 188 189/* 190 * Calculate common prefix for the pathspec, and 191 * use that to optimize the directory walk 192 */ 193 len =common_prefix_len(pathspec); 194 195/* Read the directory and prune it */ 196read_directory(dir, pathspec->nr ? pathspec->_raw[0] :"", len, pathspec); 197return len; 198} 199 200intwithin_depth(const char*name,int namelen, 201int depth,int max_depth) 202{ 203const char*cp = name, *cpe = name + namelen; 204 205while(cp < cpe) { 206if(*cp++ !='/') 207continue; 208 depth++; 209if(depth > max_depth) 210return0; 211} 212return1; 213} 214 215#define DO_MATCH_EXCLUDE 1 216#define DO_MATCH_DIRECTORY 2 217 218/* 219 * Does 'match' match the given name? 220 * A match is found if 221 * 222 * (1) the 'match' string is leading directory of 'name', or 223 * (2) the 'match' string is a wildcard and matches 'name', or 224 * (3) the 'match' string is exactly the same as 'name'. 225 * 226 * and the return value tells which case it was. 227 * 228 * It returns 0 when there is no match. 229 */ 230static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 231const char*name,int namelen,unsigned flags) 232{ 233/* name/namelen has prefix cut off by caller */ 234const char*match = item->match + prefix; 235int matchlen = item->len - prefix; 236 237/* 238 * The normal call pattern is: 239 * 1. prefix = common_prefix_len(ps); 240 * 2. prune something, or fill_directory 241 * 3. match_pathspec() 242 * 243 * 'prefix' at #1 may be shorter than the command's prefix and 244 * it's ok for #2 to match extra files. Those extras will be 245 * trimmed at #3. 246 * 247 * Suppose the pathspec is 'foo' and '../bar' running from 248 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 249 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 250 * user does not want XYZ/foo, only the "foo" part should be 251 * case-insensitive. We need to filter out XYZ/foo here. In 252 * other words, we do not trust the caller on comparing the 253 * prefix part when :(icase) is involved. We do exact 254 * comparison ourselves. 255 * 256 * Normally the caller (common_prefix_len() in fact) does 257 * _exact_ matching on name[-prefix+1..-1] and we do not need 258 * to check that part. Be defensive and check it anyway, in 259 * case common_prefix_len is changed, or a new caller is 260 * introduced that does not use common_prefix_len. 261 * 262 * If the penalty turns out too high when prefix is really 263 * long, maybe change it to 264 * strncmp(match, name, item->prefix - prefix) 265 */ 266if(item->prefix && (item->magic & PATHSPEC_ICASE) && 267strncmp(item->match, name - prefix, item->prefix)) 268return0; 269 270/* If the match was just the prefix, we matched */ 271if(!*match) 272return MATCHED_RECURSIVELY; 273 274if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 275if(matchlen == namelen) 276return MATCHED_EXACTLY; 277 278if(match[matchlen-1] =='/'|| name[matchlen] =='/') 279return MATCHED_RECURSIVELY; 280}else if((flags & DO_MATCH_DIRECTORY) && 281 match[matchlen -1] =='/'&& 282 namelen == matchlen -1&& 283!ps_strncmp(item, match, name, namelen)) 284return MATCHED_EXACTLY; 285 286if(item->nowildcard_len < item->len && 287!git_fnmatch(item, match, name, 288 item->nowildcard_len - prefix)) 289return MATCHED_FNMATCH; 290 291return0; 292} 293 294/* 295 * Given a name and a list of pathspecs, returns the nature of the 296 * closest (i.e. most specific) match of the name to any of the 297 * pathspecs. 298 * 299 * The caller typically calls this multiple times with the same 300 * pathspec and seen[] array but with different name/namelen 301 * (e.g. entries from the index) and is interested in seeing if and 302 * how each pathspec matches all the names it calls this function 303 * with. A mark is left in the seen[] array for each pathspec element 304 * indicating the closest type of match that element achieved, so if 305 * seen[n] remains zero after multiple invocations, that means the nth 306 * pathspec did not match any names, which could indicate that the 307 * user mistyped the nth pathspec. 308 */ 309static intdo_match_pathspec(const struct pathspec *ps, 310const char*name,int namelen, 311int prefix,char*seen, 312unsigned flags) 313{ 314int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 315 316GUARD_PATHSPEC(ps, 317 PATHSPEC_FROMTOP | 318 PATHSPEC_MAXDEPTH | 319 PATHSPEC_LITERAL | 320 PATHSPEC_GLOB | 321 PATHSPEC_ICASE | 322 PATHSPEC_EXCLUDE); 323 324if(!ps->nr) { 325if(!ps->recursive || 326!(ps->magic & PATHSPEC_MAXDEPTH) || 327 ps->max_depth == -1) 328return MATCHED_RECURSIVELY; 329 330if(within_depth(name, namelen,0, ps->max_depth)) 331return MATCHED_EXACTLY; 332else 333return0; 334} 335 336 name += prefix; 337 namelen -= prefix; 338 339for(i = ps->nr -1; i >=0; i--) { 340int how; 341 342if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 343( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 344continue; 345 346if(seen && seen[i] == MATCHED_EXACTLY) 347continue; 348/* 349 * Make exclude patterns optional and never report 350 * "pathspec ':(exclude)foo' matches no files" 351 */ 352if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 353 seen[i] = MATCHED_FNMATCH; 354 how =match_pathspec_item(ps->items+i, prefix, name, 355 namelen, flags); 356if(ps->recursive && 357(ps->magic & PATHSPEC_MAXDEPTH) && 358 ps->max_depth != -1&& 359 how && how != MATCHED_FNMATCH) { 360int len = ps->items[i].len; 361if(name[len] =='/') 362 len++; 363if(within_depth(name+len, namelen-len,0, ps->max_depth)) 364 how = MATCHED_EXACTLY; 365else 366 how =0; 367} 368if(how) { 369if(retval < how) 370 retval = how; 371if(seen && seen[i] < how) 372 seen[i] = how; 373} 374} 375return retval; 376} 377 378intmatch_pathspec(const struct pathspec *ps, 379const char*name,int namelen, 380int prefix,char*seen,int is_dir) 381{ 382int positive, negative; 383unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 384 positive =do_match_pathspec(ps, name, namelen, 385 prefix, seen, flags); 386if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 387return positive; 388 negative =do_match_pathspec(ps, name, namelen, 389 prefix, seen, 390 flags | DO_MATCH_EXCLUDE); 391return negative ?0: positive; 392} 393 394/* 395 * Return the length of the "simple" part of a path match limiter. 396 */ 397intsimple_length(const char*match) 398{ 399int len = -1; 400 401for(;;) { 402unsigned char c = *match++; 403 len++; 404if(c =='\0'||is_glob_special(c)) 405return len; 406} 407} 408 409intno_wildcard(const char*string) 410{ 411return string[simple_length(string)] =='\0'; 412} 413 414voidparse_exclude_pattern(const char**pattern, 415int*patternlen, 416int*flags, 417int*nowildcardlen) 418{ 419const char*p = *pattern; 420size_t i, len; 421 422*flags =0; 423if(*p =='!') { 424*flags |= EXC_FLAG_NEGATIVE; 425 p++; 426} 427 len =strlen(p); 428if(len && p[len -1] =='/') { 429 len--; 430*flags |= EXC_FLAG_MUSTBEDIR; 431} 432for(i =0; i < len; i++) { 433if(p[i] =='/') 434break; 435} 436if(i == len) 437*flags |= EXC_FLAG_NODIR; 438*nowildcardlen =simple_length(p); 439/* 440 * we should have excluded the trailing slash from 'p' too, 441 * but that's one more allocation. Instead just make sure 442 * nowildcardlen does not exceed real patternlen 443 */ 444if(*nowildcardlen > len) 445*nowildcardlen = len; 446if(*p =='*'&&no_wildcard(p +1)) 447*flags |= EXC_FLAG_ENDSWITH; 448*pattern = p; 449*patternlen = len; 450} 451 452voidadd_exclude(const char*string,const char*base, 453int baselen,struct exclude_list *el,int srcpos) 454{ 455struct exclude *x; 456int patternlen; 457int flags; 458int nowildcardlen; 459 460parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 461if(flags & EXC_FLAG_MUSTBEDIR) { 462char*s; 463 x =xmalloc(sizeof(*x) + patternlen +1); 464 s = (char*)(x+1); 465memcpy(s, string, patternlen); 466 s[patternlen] ='\0'; 467 x->pattern = s; 468}else{ 469 x =xmalloc(sizeof(*x)); 470 x->pattern = string; 471} 472 x->patternlen = patternlen; 473 x->nowildcardlen = nowildcardlen; 474 x->base = base; 475 x->baselen = baselen; 476 x->flags = flags; 477 x->srcpos = srcpos; 478ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 479 el->excludes[el->nr++] = x; 480 x->el = el; 481} 482 483static void*read_skip_worktree_file_from_index(const char*path,size_t*size, 484struct sha1_stat *sha1_stat) 485{ 486int pos, len; 487unsigned long sz; 488enum object_type type; 489void*data; 490 491 len =strlen(path); 492 pos =cache_name_pos(path, len); 493if(pos <0) 494return NULL; 495if(!ce_skip_worktree(active_cache[pos])) 496return NULL; 497 data =read_sha1_file(active_cache[pos]->sha1, &type, &sz); 498if(!data || type != OBJ_BLOB) { 499free(data); 500return NULL; 501} 502*size =xsize_t(sz); 503if(sha1_stat) { 504memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 505hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 506} 507return data; 508} 509 510/* 511 * Frees memory within el which was allocated for exclude patterns and 512 * the file buffer. Does not free el itself. 513 */ 514voidclear_exclude_list(struct exclude_list *el) 515{ 516int i; 517 518for(i =0; i < el->nr; i++) 519free(el->excludes[i]); 520free(el->excludes); 521free(el->filebuf); 522 523 el->nr =0; 524 el->excludes = NULL; 525 el->filebuf = NULL; 526} 527 528static voidtrim_trailing_spaces(char*buf) 529{ 530char*p, *last_space = NULL; 531 532for(p = buf; *p; p++) 533switch(*p) { 534case' ': 535if(!last_space) 536 last_space = p; 537break; 538case'\\': 539 p++; 540if(!*p) 541return; 542/* fallthrough */ 543default: 544 last_space = NULL; 545} 546 547if(last_space) 548*last_space ='\0'; 549} 550 551/* 552 * Given a subdirectory name and "dir" of the current directory, 553 * search the subdir in "dir" and return it, or create a new one if it 554 * does not exist in "dir". 555 * 556 * If "name" has the trailing slash, it'll be excluded in the search. 557 */ 558static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 559struct untracked_cache_dir *dir, 560const char*name,int len) 561{ 562int first, last; 563struct untracked_cache_dir *d; 564if(!dir) 565return NULL; 566if(len && name[len -1] =='/') 567 len--; 568 first =0; 569 last = dir->dirs_nr; 570while(last > first) { 571int cmp, next = (last + first) >>1; 572 d = dir->dirs[next]; 573 cmp =strncmp(name, d->name, len); 574if(!cmp &&strlen(d->name) > len) 575 cmp = -1; 576if(!cmp) 577return d; 578if(cmp <0) { 579 last = next; 580continue; 581} 582 first = next+1; 583} 584 585 uc->dir_created++; 586 d =xmalloc(sizeof(*d) + len +1); 587memset(d,0,sizeof(*d)); 588memcpy(d->name, name, len); 589 d->name[len] ='\0'; 590 591ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 592memmove(dir->dirs + first +1, dir->dirs + first, 593(dir->dirs_nr - first) *sizeof(*dir->dirs)); 594 dir->dirs_nr++; 595 dir->dirs[first] = d; 596return d; 597} 598 599static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 600{ 601int i; 602 dir->valid =0; 603 dir->untracked_nr =0; 604for(i =0; i < dir->dirs_nr; i++) 605do_invalidate_gitignore(dir->dirs[i]); 606} 607 608static voidinvalidate_gitignore(struct untracked_cache *uc, 609struct untracked_cache_dir *dir) 610{ 611 uc->gitignore_invalidated++; 612do_invalidate_gitignore(dir); 613} 614 615static voidinvalidate_directory(struct untracked_cache *uc, 616struct untracked_cache_dir *dir) 617{ 618int i; 619 uc->dir_invalidated++; 620 dir->valid =0; 621 dir->untracked_nr =0; 622for(i =0; i < dir->dirs_nr; i++) 623 dir->dirs[i]->recurse =0; 624} 625 626/* 627 * Given a file with name "fname", read it (either from disk, or from 628 * the index if "check_index" is non-zero), parse it and store the 629 * exclude rules in "el". 630 * 631 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 632 * stat data from disk (only valid if add_excludes returns zero). If 633 * ss_valid is non-zero, "ss" must contain good value as input. 634 */ 635static intadd_excludes(const char*fname,const char*base,int baselen, 636struct exclude_list *el,int check_index, 637struct sha1_stat *sha1_stat) 638{ 639struct stat st; 640int fd, i, lineno =1; 641size_t size =0; 642char*buf, *entry; 643 644 fd =open(fname, O_RDONLY); 645if(fd <0||fstat(fd, &st) <0) { 646if(errno != ENOENT) 647warn_on_inaccessible(fname); 648if(0<= fd) 649close(fd); 650if(!check_index || 651(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 652return-1; 653if(size ==0) { 654free(buf); 655return0; 656} 657if(buf[size-1] !='\n') { 658 buf =xrealloc(buf, size+1); 659 buf[size++] ='\n'; 660} 661}else{ 662 size =xsize_t(st.st_size); 663if(size ==0) { 664if(sha1_stat) { 665fill_stat_data(&sha1_stat->stat, &st); 666hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 667 sha1_stat->valid =1; 668} 669close(fd); 670return0; 671} 672 buf =xmalloc(size+1); 673if(read_in_full(fd, buf, size) != size) { 674free(buf); 675close(fd); 676return-1; 677} 678 buf[size++] ='\n'; 679close(fd); 680if(sha1_stat) { 681int pos; 682if(sha1_stat->valid && 683!match_stat_data(&sha1_stat->stat, &st)) 684;/* no content change, ss->sha1 still good */ 685else if(check_index && 686(pos =cache_name_pos(fname,strlen(fname))) >=0&& 687!ce_stage(active_cache[pos]) && 688ce_uptodate(active_cache[pos]) && 689!would_convert_to_git(fname)) 690hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 691else 692hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 693fill_stat_data(&sha1_stat->stat, &st); 694 sha1_stat->valid =1; 695} 696} 697 698 el->filebuf = buf; 699 entry = buf; 700for(i =0; i < size; i++) { 701if(buf[i] =='\n') { 702if(entry != buf + i && entry[0] !='#') { 703 buf[i - (i && buf[i-1] =='\r')] =0; 704trim_trailing_spaces(entry); 705add_exclude(entry, base, baselen, el, lineno); 706} 707 lineno++; 708 entry = buf + i +1; 709} 710} 711return0; 712} 713 714intadd_excludes_from_file_to_list(const char*fname,const char*base, 715int baselen,struct exclude_list *el, 716int check_index) 717{ 718returnadd_excludes(fname, base, baselen, el, check_index, NULL); 719} 720 721struct exclude_list *add_exclude_list(struct dir_struct *dir, 722int group_type,const char*src) 723{ 724struct exclude_list *el; 725struct exclude_list_group *group; 726 727 group = &dir->exclude_list_group[group_type]; 728ALLOC_GROW(group->el, group->nr +1, group->alloc); 729 el = &group->el[group->nr++]; 730memset(el,0,sizeof(*el)); 731 el->src = src; 732return el; 733} 734 735/* 736 * Used to set up core.excludesfile and .git/info/exclude lists. 737 */ 738static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 739struct sha1_stat *sha1_stat) 740{ 741struct exclude_list *el; 742/* 743 * catch setup_standard_excludes() that's called before 744 * dir->untracked is assigned. That function behaves 745 * differently when dir->untracked is non-NULL. 746 */ 747if(!dir->untracked) 748 dir->unmanaged_exclude_files++; 749 el =add_exclude_list(dir, EXC_FILE, fname); 750if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 751die("cannot use%sas an exclude file", fname); 752} 753 754voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 755{ 756 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 757add_excludes_from_file_1(dir, fname, NULL); 758} 759 760intmatch_basename(const char*basename,int basenamelen, 761const char*pattern,int prefix,int patternlen, 762int flags) 763{ 764if(prefix == patternlen) { 765if(patternlen == basenamelen && 766!strncmp_icase(pattern, basename, basenamelen)) 767return1; 768}else if(flags & EXC_FLAG_ENDSWITH) { 769/* "*literal" matching against "fooliteral" */ 770if(patternlen -1<= basenamelen && 771!strncmp_icase(pattern +1, 772 basename + basenamelen - (patternlen -1), 773 patternlen -1)) 774return1; 775}else{ 776if(fnmatch_icase_mem(pattern, patternlen, 777 basename, basenamelen, 7780) ==0) 779return1; 780} 781return0; 782} 783 784intmatch_pathname(const char*pathname,int pathlen, 785const char*base,int baselen, 786const char*pattern,int prefix,int patternlen, 787int flags) 788{ 789const char*name; 790int namelen; 791 792/* 793 * match with FNM_PATHNAME; the pattern has base implicitly 794 * in front of it. 795 */ 796if(*pattern =='/') { 797 pattern++; 798 patternlen--; 799 prefix--; 800} 801 802/* 803 * baselen does not count the trailing slash. base[] may or 804 * may not end with a trailing slash though. 805 */ 806if(pathlen < baselen +1|| 807(baselen && pathname[baselen] !='/') || 808strncmp_icase(pathname, base, baselen)) 809return0; 810 811 namelen = baselen ? pathlen - baselen -1: pathlen; 812 name = pathname + pathlen - namelen; 813 814if(prefix) { 815/* 816 * if the non-wildcard part is longer than the 817 * remaining pathname, surely it cannot match. 818 */ 819if(prefix > namelen) 820return0; 821 822if(strncmp_icase(pattern, name, prefix)) 823return0; 824 pattern += prefix; 825 patternlen -= prefix; 826 name += prefix; 827 namelen -= prefix; 828 829/* 830 * If the whole pattern did not have a wildcard, 831 * then our prefix match is all we need; we 832 * do not need to call fnmatch at all. 833 */ 834if(!patternlen && !namelen) 835return1; 836} 837 838returnfnmatch_icase_mem(pattern, patternlen, 839 name, namelen, 840 WM_PATHNAME) ==0; 841} 842 843/* 844 * Scan the given exclude list in reverse to see whether pathname 845 * should be ignored. The first match (i.e. the last on the list), if 846 * any, determines the fate. Returns the exclude_list element which 847 * matched, or NULL for undecided. 848 */ 849static struct exclude *last_exclude_matching_from_list(const char*pathname, 850int pathlen, 851const char*basename, 852int*dtype, 853struct exclude_list *el) 854{ 855int i; 856 857if(!el->nr) 858return NULL;/* undefined */ 859 860for(i = el->nr -1;0<= i; i--) { 861struct exclude *x = el->excludes[i]; 862const char*exclude = x->pattern; 863int prefix = x->nowildcardlen; 864 865if(x->flags & EXC_FLAG_MUSTBEDIR) { 866if(*dtype == DT_UNKNOWN) 867*dtype =get_dtype(NULL, pathname, pathlen); 868if(*dtype != DT_DIR) 869continue; 870} 871 872if(x->flags & EXC_FLAG_NODIR) { 873if(match_basename(basename, 874 pathlen - (basename - pathname), 875 exclude, prefix, x->patternlen, 876 x->flags)) 877return x; 878continue; 879} 880 881assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 882if(match_pathname(pathname, pathlen, 883 x->base, x->baselen ? x->baselen -1:0, 884 exclude, prefix, x->patternlen, x->flags)) 885return x; 886} 887return NULL;/* undecided */ 888} 889 890/* 891 * Scan the list and let the last match determine the fate. 892 * Return 1 for exclude, 0 for include and -1 for undecided. 893 */ 894intis_excluded_from_list(const char*pathname, 895int pathlen,const char*basename,int*dtype, 896struct exclude_list *el) 897{ 898struct exclude *exclude; 899 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 900if(exclude) 901return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 902return-1;/* undecided */ 903} 904 905static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 906const char*pathname,int pathlen,const char*basename, 907int*dtype_p) 908{ 909int i, j; 910struct exclude_list_group *group; 911struct exclude *exclude; 912for(i = EXC_CMDL; i <= EXC_FILE; i++) { 913 group = &dir->exclude_list_group[i]; 914for(j = group->nr -1; j >=0; j--) { 915 exclude =last_exclude_matching_from_list( 916 pathname, pathlen, basename, dtype_p, 917&group->el[j]); 918if(exclude) 919return exclude; 920} 921} 922return NULL; 923} 924 925/* 926 * Loads the per-directory exclude list for the substring of base 927 * which has a char length of baselen. 928 */ 929static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen) 930{ 931struct exclude_list_group *group; 932struct exclude_list *el; 933struct exclude_stack *stk = NULL; 934struct untracked_cache_dir *untracked; 935int current; 936 937 group = &dir->exclude_list_group[EXC_DIRS]; 938 939/* 940 * Pop the exclude lists from the EXCL_DIRS exclude_list_group 941 * which originate from directories not in the prefix of the 942 * path being checked. 943 */ 944while((stk = dir->exclude_stack) != NULL) { 945if(stk->baselen <= baselen && 946!strncmp(dir->basebuf.buf, base, stk->baselen)) 947break; 948 el = &group->el[dir->exclude_stack->exclude_ix]; 949 dir->exclude_stack = stk->prev; 950 dir->exclude = NULL; 951free((char*)el->src);/* see strbuf_detach() below */ 952clear_exclude_list(el); 953free(stk); 954 group->nr--; 955} 956 957/* Skip traversing into sub directories if the parent is excluded */ 958if(dir->exclude) 959return; 960 961/* 962 * Lazy initialization. All call sites currently just 963 * memset(dir, 0, sizeof(*dir)) before use. Changing all of 964 * them seems lots of work for little benefit. 965 */ 966if(!dir->basebuf.buf) 967strbuf_init(&dir->basebuf, PATH_MAX); 968 969/* Read from the parent directories and push them down. */ 970 current = stk ? stk->baselen : -1; 971strbuf_setlen(&dir->basebuf, current <0?0: current); 972if(dir->untracked) 973 untracked = stk ? stk->ucd : dir->untracked->root; 974else 975 untracked = NULL; 976 977while(current < baselen) { 978const char*cp; 979struct sha1_stat sha1_stat; 980 981 stk =xcalloc(1,sizeof(*stk)); 982if(current <0) { 983 cp = base; 984 current =0; 985}else{ 986 cp =strchr(base + current +1,'/'); 987if(!cp) 988die("oops in prep_exclude"); 989 cp++; 990 untracked = 991lookup_untracked(dir->untracked, untracked, 992 base + current, 993 cp - base - current); 994} 995 stk->prev = dir->exclude_stack; 996 stk->baselen = cp - base; 997 stk->exclude_ix = group->nr; 998 stk->ucd = untracked; 999 el =add_exclude_list(dir, EXC_DIRS, NULL);1000strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1001assert(stk->baselen == dir->basebuf.len);10021003/* Abort if the directory is excluded */1004if(stk->baselen) {1005int dt = DT_DIR;1006 dir->basebuf.buf[stk->baselen -1] =0;1007 dir->exclude =last_exclude_matching_from_lists(dir,1008 dir->basebuf.buf, stk->baselen -1,1009 dir->basebuf.buf + current, &dt);1010 dir->basebuf.buf[stk->baselen -1] ='/';1011if(dir->exclude &&1012 dir->exclude->flags & EXC_FLAG_NEGATIVE)1013 dir->exclude = NULL;1014if(dir->exclude) {1015 dir->exclude_stack = stk;1016return;1017}1018}10191020/* Try to read per-directory file */1021hashclr(sha1_stat.sha1);1022 sha1_stat.valid =0;1023if(dir->exclude_per_dir) {1024/*1025 * dir->basebuf gets reused by the traversal, but we1026 * need fname to remain unchanged to ensure the src1027 * member of each struct exclude correctly1028 * back-references its source file. Other invocations1029 * of add_exclude_list provide stable strings, so we1030 * strbuf_detach() and free() here in the caller.1031 */1032struct strbuf sb = STRBUF_INIT;1033strbuf_addbuf(&sb, &dir->basebuf);1034strbuf_addstr(&sb, dir->exclude_per_dir);1035 el->src =strbuf_detach(&sb, NULL);1036add_excludes(el->src, el->src, stk->baselen, el,1,1037 untracked ? &sha1_stat : NULL);1038}1039/*1040 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1041 * will first be called in valid_cached_dir() then maybe many1042 * times more in last_exclude_matching(). When the cache is1043 * used, last_exclude_matching() will not be called and1044 * reading .gitignore content will be a waste.1045 *1046 * So when it's called by valid_cached_dir() and we can get1047 * .gitignore SHA-1 from the index (i.e. .gitignore is not1048 * modified on work tree), we could delay reading the1049 * .gitignore content until we absolutely need it in1050 * last_exclude_matching(). Be careful about ignore rule1051 * order, though, if you do that.1052 */1053if(untracked &&1054hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1055invalidate_gitignore(dir->untracked, untracked);1056hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1057}1058 dir->exclude_stack = stk;1059 current = stk->baselen;1060}1061strbuf_setlen(&dir->basebuf, baselen);1062}10631064/*1065 * Loads the exclude lists for the directory containing pathname, then1066 * scans all exclude lists to determine whether pathname is excluded.1067 * Returns the exclude_list element which matched, or NULL for1068 * undecided.1069 */1070struct exclude *last_exclude_matching(struct dir_struct *dir,1071const char*pathname,1072int*dtype_p)1073{1074int pathlen =strlen(pathname);1075const char*basename =strrchr(pathname,'/');1076 basename = (basename) ? basename+1: pathname;10771078prep_exclude(dir, pathname, basename-pathname);10791080if(dir->exclude)1081return dir->exclude;10821083returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1084 basename, dtype_p);1085}10861087/*1088 * Loads the exclude lists for the directory containing pathname, then1089 * scans all exclude lists to determine whether pathname is excluded.1090 * Returns 1 if true, otherwise 0.1091 */1092intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1093{1094struct exclude *exclude =1095last_exclude_matching(dir, pathname, dtype_p);1096if(exclude)1097return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1098return0;1099}11001101static struct dir_entry *dir_entry_new(const char*pathname,int len)1102{1103struct dir_entry *ent;11041105 ent =xmalloc(sizeof(*ent) + len +1);1106 ent->len = len;1107memcpy(ent->name, pathname, len);1108 ent->name[len] =0;1109return ent;1110}11111112static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1113{1114if(cache_file_exists(pathname, len, ignore_case))1115return NULL;11161117ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1118return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1119}11201121struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1122{1123if(!cache_name_is_other(pathname, len))1124return NULL;11251126ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1127return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1128}11291130enum exist_status {1131 index_nonexistent =0,1132 index_directory,1133 index_gitdir1134};11351136/*1137 * Do not use the alphabetically sorted index to look up1138 * the directory name; instead, use the case insensitive1139 * directory hash.1140 */1141static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1142{1143const struct cache_entry *ce =cache_dir_exists(dirname, len);1144unsigned char endchar;11451146if(!ce)1147return index_nonexistent;1148 endchar = ce->name[len];11491150/*1151 * The cache_entry structure returned will contain this dirname1152 * and possibly additional path components.1153 */1154if(endchar =='/')1155return index_directory;11561157/*1158 * If there are no additional path components, then this cache_entry1159 * represents a submodule. Submodules, despite being directories,1160 * are stored in the cache without a closing slash.1161 */1162if(!endchar &&S_ISGITLINK(ce->ce_mode))1163return index_gitdir;11641165/* This should never be hit, but it exists just in case. */1166return index_nonexistent;1167}11681169/*1170 * The index sorts alphabetically by entry name, which1171 * means that a gitlink sorts as '\0' at the end, while1172 * a directory (which is defined not as an entry, but as1173 * the files it contains) will sort with the '/' at the1174 * end.1175 */1176static enum exist_status directory_exists_in_index(const char*dirname,int len)1177{1178int pos;11791180if(ignore_case)1181returndirectory_exists_in_index_icase(dirname, len);11821183 pos =cache_name_pos(dirname, len);1184if(pos <0)1185 pos = -pos-1;1186while(pos < active_nr) {1187const struct cache_entry *ce = active_cache[pos++];1188unsigned char endchar;11891190if(strncmp(ce->name, dirname, len))1191break;1192 endchar = ce->name[len];1193if(endchar >'/')1194break;1195if(endchar =='/')1196return index_directory;1197if(!endchar &&S_ISGITLINK(ce->ce_mode))1198return index_gitdir;1199}1200return index_nonexistent;1201}12021203/*1204 * When we find a directory when traversing the filesystem, we1205 * have three distinct cases:1206 *1207 * - ignore it1208 * - see it as a directory1209 * - recurse into it1210 *1211 * and which one we choose depends on a combination of existing1212 * git index contents and the flags passed into the directory1213 * traversal routine.1214 *1215 * Case 1: If we *already* have entries in the index under that1216 * directory name, we always recurse into the directory to see1217 * all the files.1218 *1219 * Case 2: If we *already* have that directory name as a gitlink,1220 * we always continue to see it as a gitlink, regardless of whether1221 * there is an actual git directory there or not (it might not1222 * be checked out as a subproject!)1223 *1224 * Case 3: if we didn't have it in the index previously, we1225 * have a few sub-cases:1226 *1227 * (a) if "show_other_directories" is true, we show it as1228 * just a directory, unless "hide_empty_directories" is1229 * also true, in which case we need to check if it contains any1230 * untracked and / or ignored files.1231 * (b) if it looks like a git directory, and we don't have1232 * 'no_gitlinks' set we treat it as a gitlink, and show it1233 * as a directory.1234 * (c) otherwise, we recurse into it.1235 */1236static enum path_treatment treat_directory(struct dir_struct *dir,1237struct untracked_cache_dir *untracked,1238const char*dirname,int len,int exclude,1239const struct path_simplify *simplify)1240{1241/* The "len-1" is to strip the final '/' */1242switch(directory_exists_in_index(dirname, len-1)) {1243case index_directory:1244return path_recurse;12451246case index_gitdir:1247return path_none;12481249case index_nonexistent:1250if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1251break;1252if(!(dir->flags & DIR_NO_GITLINKS)) {1253unsigned char sha1[20];1254if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1255return path_untracked;1256}1257return path_recurse;1258}12591260/* This is the "show_other_directories" case */12611262if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1263return exclude ? path_excluded : path_untracked;12641265 untracked =lookup_untracked(dir->untracked, untracked, dirname, len);1266returnread_directory_recursive(dir, dirname, len,1267 untracked,1, simplify);1268}12691270/*1271 * This is an inexact early pruning of any recursive directory1272 * reading - if the path cannot possibly be in the pathspec,1273 * return true, and we'll skip it early.1274 */1275static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1276{1277if(simplify) {1278for(;;) {1279const char*match = simplify->path;1280int len = simplify->len;12811282if(!match)1283break;1284if(len > pathlen)1285 len = pathlen;1286if(!memcmp(path, match, len))1287return0;1288 simplify++;1289}1290return1;1291}1292return0;1293}12941295/*1296 * This function tells us whether an excluded path matches a1297 * list of "interesting" pathspecs. That is, whether a path matched1298 * by any of the pathspecs could possibly be ignored by excluding1299 * the specified path. This can happen if:1300 *1301 * 1. the path is mentioned explicitly in the pathspec1302 *1303 * 2. the path is a directory prefix of some element in the1304 * pathspec1305 */1306static intexclude_matches_pathspec(const char*path,int len,1307const struct path_simplify *simplify)1308{1309if(simplify) {1310for(; simplify->path; simplify++) {1311if(len == simplify->len1312&& !memcmp(path, simplify->path, len))1313return1;1314if(len < simplify->len1315&& simplify->path[len] =='/'1316&& !memcmp(path, simplify->path, len))1317return1;1318}1319}1320return0;1321}13221323static intget_index_dtype(const char*path,int len)1324{1325int pos;1326const struct cache_entry *ce;13271328 ce =cache_file_exists(path, len,0);1329if(ce) {1330if(!ce_uptodate(ce))1331return DT_UNKNOWN;1332if(S_ISGITLINK(ce->ce_mode))1333return DT_DIR;1334/*1335 * Nobody actually cares about the1336 * difference between DT_LNK and DT_REG1337 */1338return DT_REG;1339}13401341/* Try to look it up as a directory */1342 pos =cache_name_pos(path, len);1343if(pos >=0)1344return DT_UNKNOWN;1345 pos = -pos-1;1346while(pos < active_nr) {1347 ce = active_cache[pos++];1348if(strncmp(ce->name, path, len))1349break;1350if(ce->name[len] >'/')1351break;1352if(ce->name[len] <'/')1353continue;1354if(!ce_uptodate(ce))1355break;/* continue? */1356return DT_DIR;1357}1358return DT_UNKNOWN;1359}13601361static intget_dtype(struct dirent *de,const char*path,int len)1362{1363int dtype = de ?DTYPE(de) : DT_UNKNOWN;1364struct stat st;13651366if(dtype != DT_UNKNOWN)1367return dtype;1368 dtype =get_index_dtype(path, len);1369if(dtype != DT_UNKNOWN)1370return dtype;1371if(lstat(path, &st))1372return dtype;1373if(S_ISREG(st.st_mode))1374return DT_REG;1375if(S_ISDIR(st.st_mode))1376return DT_DIR;1377if(S_ISLNK(st.st_mode))1378return DT_LNK;1379return dtype;1380}13811382static enum path_treatment treat_one_path(struct dir_struct *dir,1383struct untracked_cache_dir *untracked,1384struct strbuf *path,1385const struct path_simplify *simplify,1386int dtype,struct dirent *de)1387{1388int exclude;1389int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);13901391if(dtype == DT_UNKNOWN)1392 dtype =get_dtype(de, path->buf, path->len);13931394/* Always exclude indexed files */1395if(dtype != DT_DIR && has_path_in_index)1396return path_none;13971398/*1399 * When we are looking at a directory P in the working tree,1400 * there are three cases:1401 *1402 * (1) P exists in the index. Everything inside the directory P in1403 * the working tree needs to go when P is checked out from the1404 * index.1405 *1406 * (2) P does not exist in the index, but there is P/Q in the index.1407 * We know P will stay a directory when we check out the contents1408 * of the index, but we do not know yet if there is a directory1409 * P/Q in the working tree to be killed, so we need to recurse.1410 *1411 * (3) P does not exist in the index, and there is no P/Q in the index1412 * to require P to be a directory, either. Only in this case, we1413 * know that everything inside P will not be killed without1414 * recursing.1415 */1416if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1417(dtype == DT_DIR) &&1418!has_path_in_index &&1419(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1420return path_none;14211422 exclude =is_excluded(dir, path->buf, &dtype);14231424/*1425 * Excluded? If we don't explicitly want to show1426 * ignored files, ignore it1427 */1428if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1429return path_excluded;14301431switch(dtype) {1432default:1433return path_none;1434case DT_DIR:1435strbuf_addch(path,'/');1436returntreat_directory(dir, untracked, path->buf, path->len, exclude,1437 simplify);1438case DT_REG:1439case DT_LNK:1440return exclude ? path_excluded : path_untracked;1441}1442}14431444static enum path_treatment treat_path_fast(struct dir_struct *dir,1445struct untracked_cache_dir *untracked,1446struct cached_dir *cdir,1447struct strbuf *path,1448int baselen,1449const struct path_simplify *simplify)1450{1451strbuf_setlen(path, baselen);1452if(!cdir->ucd) {1453strbuf_addstr(path, cdir->file);1454return path_untracked;1455}1456strbuf_addstr(path, cdir->ucd->name);1457/* treat_one_path() does this before it calls treat_directory() */1458if(path->buf[path->len -1] !='/')1459strbuf_addch(path,'/');1460if(cdir->ucd->check_only)1461/*1462 * check_only is set as a result of treat_directory() getting1463 * to its bottom. Verify again the same set of directories1464 * with check_only set.1465 */1466returnread_directory_recursive(dir, path->buf, path->len,1467 cdir->ucd,1, simplify);1468/*1469 * We get path_recurse in the first run when1470 * directory_exists_in_index() returns index_nonexistent. We1471 * are sure that new changes in the index does not impact the1472 * outcome. Return now.1473 */1474return path_recurse;1475}14761477static enum path_treatment treat_path(struct dir_struct *dir,1478struct untracked_cache_dir *untracked,1479struct cached_dir *cdir,1480struct strbuf *path,1481int baselen,1482const struct path_simplify *simplify)1483{1484int dtype;1485struct dirent *de = cdir->de;14861487if(!de)1488returntreat_path_fast(dir, untracked, cdir, path,1489 baselen, simplify);1490if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1491return path_none;1492strbuf_setlen(path, baselen);1493strbuf_addstr(path, de->d_name);1494if(simplify_away(path->buf, path->len, simplify))1495return path_none;14961497 dtype =DTYPE(de);1498returntreat_one_path(dir, untracked, path, simplify, dtype, de);1499}15001501static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1502{1503if(!dir)1504return;1505ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1506 dir->untracked_alloc);1507 dir->untracked[dir->untracked_nr++] =xstrdup(name);1508}15091510static intvalid_cached_dir(struct dir_struct *dir,1511struct untracked_cache_dir *untracked,1512struct strbuf *path,1513int check_only)1514{1515struct stat st;15161517if(!untracked)1518return0;15191520if(stat(path->len ? path->buf :".", &st)) {1521invalidate_directory(dir->untracked, untracked);1522memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1523return0;1524}1525if(!untracked->valid ||1526match_stat_data(&untracked->stat_data, &st)) {1527if(untracked->valid)1528invalidate_directory(dir->untracked, untracked);1529fill_stat_data(&untracked->stat_data, &st);1530return0;1531}15321533if(untracked->check_only != !!check_only) {1534invalidate_directory(dir->untracked, untracked);1535return0;1536}15371538/*1539 * prep_exclude will be called eventually on this directory,1540 * but it's called much later in last_exclude_matching(). We1541 * need it now to determine the validity of the cache for this1542 * path. The next calls will be nearly no-op, the way1543 * prep_exclude() is designed.1544 */1545if(path->len && path->buf[path->len -1] !='/') {1546strbuf_addch(path,'/');1547prep_exclude(dir, path->buf, path->len);1548strbuf_setlen(path, path->len -1);1549}else1550prep_exclude(dir, path->buf, path->len);15511552/* hopefully prep_exclude() haven't invalidated this entry... */1553return untracked->valid;1554}15551556static intopen_cached_dir(struct cached_dir *cdir,1557struct dir_struct *dir,1558struct untracked_cache_dir *untracked,1559struct strbuf *path,1560int check_only)1561{1562memset(cdir,0,sizeof(*cdir));1563 cdir->untracked = untracked;1564if(valid_cached_dir(dir, untracked, path, check_only))1565return0;1566 cdir->fdir =opendir(path->len ? path->buf :".");1567if(dir->untracked)1568 dir->untracked->dir_opened++;1569if(!cdir->fdir)1570return-1;1571return0;1572}15731574static intread_cached_dir(struct cached_dir *cdir)1575{1576if(cdir->fdir) {1577 cdir->de =readdir(cdir->fdir);1578if(!cdir->de)1579return-1;1580return0;1581}1582while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1583struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1584if(!d->recurse) {1585 cdir->nr_dirs++;1586continue;1587}1588 cdir->ucd = d;1589 cdir->nr_dirs++;1590return0;1591}1592 cdir->ucd = NULL;1593if(cdir->nr_files < cdir->untracked->untracked_nr) {1594struct untracked_cache_dir *d = cdir->untracked;1595 cdir->file = d->untracked[cdir->nr_files++];1596return0;1597}1598return-1;1599}16001601static voidclose_cached_dir(struct cached_dir *cdir)1602{1603if(cdir->fdir)1604closedir(cdir->fdir);1605/*1606 * We have gone through this directory and found no untracked1607 * entries. Mark it valid.1608 */1609if(cdir->untracked) {1610 cdir->untracked->valid =1;1611 cdir->untracked->recurse =1;1612}1613}16141615/*1616 * Read a directory tree. We currently ignore anything but1617 * directories, regular files and symlinks. That's because git1618 * doesn't handle them at all yet. Maybe that will change some1619 * day.1620 *1621 * Also, we ignore the name ".git" (even if it is not a directory).1622 * That likely will not change.1623 *1624 * Returns the most significant path_treatment value encountered in the scan.1625 */1626static enum path_treatment read_directory_recursive(struct dir_struct *dir,1627const char*base,int baselen,1628struct untracked_cache_dir *untracked,int check_only,1629const struct path_simplify *simplify)1630{1631struct cached_dir cdir;1632enum path_treatment state, subdir_state, dir_state = path_none;1633struct strbuf path = STRBUF_INIT;16341635strbuf_add(&path, base, baselen);16361637if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1638goto out;16391640if(untracked)1641 untracked->check_only = !!check_only;16421643while(!read_cached_dir(&cdir)) {1644/* check how the file or directory should be treated */1645 state =treat_path(dir, untracked, &cdir, &path, baselen, simplify);16461647if(state > dir_state)1648 dir_state = state;16491650/* recurse into subdir if instructed by treat_path */1651if(state == path_recurse) {1652struct untracked_cache_dir *ud;1653 ud =lookup_untracked(dir->untracked, untracked,1654 path.buf + baselen,1655 path.len - baselen);1656 subdir_state =1657read_directory_recursive(dir, path.buf, path.len,1658 ud, check_only, simplify);1659if(subdir_state > dir_state)1660 dir_state = subdir_state;1661}16621663if(check_only) {1664/* abort early if maximum state has been reached */1665if(dir_state == path_untracked) {1666if(cdir.fdir)1667add_untracked(untracked, path.buf + baselen);1668break;1669}1670/* skip the dir_add_* part */1671continue;1672}16731674/* add the path to the appropriate result list */1675switch(state) {1676case path_excluded:1677if(dir->flags & DIR_SHOW_IGNORED)1678dir_add_name(dir, path.buf, path.len);1679else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1680((dir->flags & DIR_COLLECT_IGNORED) &&1681exclude_matches_pathspec(path.buf, path.len,1682 simplify)))1683dir_add_ignored(dir, path.buf, path.len);1684break;16851686case path_untracked:1687if(dir->flags & DIR_SHOW_IGNORED)1688break;1689dir_add_name(dir, path.buf, path.len);1690if(cdir.fdir)1691add_untracked(untracked, path.buf + baselen);1692break;16931694default:1695break;1696}1697}1698close_cached_dir(&cdir);1699 out:1700strbuf_release(&path);17011702return dir_state;1703}17041705static intcmp_name(const void*p1,const void*p2)1706{1707const struct dir_entry *e1 = *(const struct dir_entry **)p1;1708const struct dir_entry *e2 = *(const struct dir_entry **)p2;17091710returnname_compare(e1->name, e1->len, e2->name, e2->len);1711}17121713static struct path_simplify *create_simplify(const char**pathspec)1714{1715int nr, alloc =0;1716struct path_simplify *simplify = NULL;17171718if(!pathspec)1719return NULL;17201721for(nr =0; ; nr++) {1722const char*match;1723ALLOC_GROW(simplify, nr +1, alloc);1724 match = *pathspec++;1725if(!match)1726break;1727 simplify[nr].path = match;1728 simplify[nr].len =simple_length(match);1729}1730 simplify[nr].path = NULL;1731 simplify[nr].len =0;1732return simplify;1733}17341735static voidfree_simplify(struct path_simplify *simplify)1736{1737free(simplify);1738}17391740static inttreat_leading_path(struct dir_struct *dir,1741const char*path,int len,1742const struct path_simplify *simplify)1743{1744struct strbuf sb = STRBUF_INIT;1745int baselen, rc =0;1746const char*cp;1747int old_flags = dir->flags;17481749while(len && path[len -1] =='/')1750 len--;1751if(!len)1752return1;1753 baselen =0;1754 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1755while(1) {1756 cp = path + baselen + !!baselen;1757 cp =memchr(cp,'/', path + len - cp);1758if(!cp)1759 baselen = len;1760else1761 baselen = cp - path;1762strbuf_setlen(&sb,0);1763strbuf_add(&sb, path, baselen);1764if(!is_directory(sb.buf))1765break;1766if(simplify_away(sb.buf, sb.len, simplify))1767break;1768if(treat_one_path(dir, NULL, &sb, simplify,1769 DT_DIR, NULL) == path_none)1770break;/* do not recurse into it */1771if(len <= baselen) {1772 rc =1;1773break;/* finished checking */1774}1775}1776strbuf_release(&sb);1777 dir->flags = old_flags;1778return rc;1779}17801781static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1782int base_len,1783const struct pathspec *pathspec)1784{1785struct untracked_cache_dir *root;17861787if(!dir->untracked)1788return NULL;17891790/*1791 * We only support $GIT_DIR/info/exclude and core.excludesfile1792 * as the global ignore rule files. Any other additions1793 * (e.g. from command line) invalidate the cache. This1794 * condition also catches running setup_standard_excludes()1795 * before setting dir->untracked!1796 */1797if(dir->unmanaged_exclude_files)1798return NULL;17991800/*1801 * Optimize for the main use case only: whole-tree git1802 * status. More work involved in treat_leading_path() if we1803 * use cache on just a subset of the worktree. pathspec1804 * support could make the matter even worse.1805 */1806if(base_len || (pathspec && pathspec->nr))1807return NULL;18081809/* Different set of flags may produce different results */1810if(dir->flags != dir->untracked->dir_flags ||1811/*1812 * See treat_directory(), case index_nonexistent. Without1813 * this flag, we may need to also cache .git file content1814 * for the resolve_gitlink_ref() call, which we don't.1815 */1816!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1817/* We don't support collecting ignore files */1818(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1819 DIR_COLLECT_IGNORED)))1820return NULL;18211822/*1823 * If we use .gitignore in the cache and now you change it to1824 * .gitexclude, everything will go wrong.1825 */1826if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1827strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1828return NULL;18291830/*1831 * EXC_CMDL is not considered in the cache. If people set it,1832 * skip the cache.1833 */1834if(dir->exclude_list_group[EXC_CMDL].nr)1835return NULL;18361837if(!dir->untracked->root) {1838const int len =sizeof(*dir->untracked->root);1839 dir->untracked->root =xmalloc(len);1840memset(dir->untracked->root,0, len);1841}18421843/* Validate $GIT_DIR/info/exclude and core.excludesfile */1844 root = dir->untracked->root;1845if(hashcmp(dir->ss_info_exclude.sha1,1846 dir->untracked->ss_info_exclude.sha1)) {1847invalidate_gitignore(dir->untracked, root);1848 dir->untracked->ss_info_exclude = dir->ss_info_exclude;1849}1850if(hashcmp(dir->ss_excludes_file.sha1,1851 dir->untracked->ss_excludes_file.sha1)) {1852invalidate_gitignore(dir->untracked, root);1853 dir->untracked->ss_excludes_file = dir->ss_excludes_file;1854}18551856/* Make sure this directory is not dropped out at saving phase */1857 root->recurse =1;1858return root;1859}18601861intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)1862{1863struct path_simplify *simplify;1864struct untracked_cache_dir *untracked;18651866/*1867 * Check out create_simplify()1868 */1869if(pathspec)1870GUARD_PATHSPEC(pathspec,1871 PATHSPEC_FROMTOP |1872 PATHSPEC_MAXDEPTH |1873 PATHSPEC_LITERAL |1874 PATHSPEC_GLOB |1875 PATHSPEC_ICASE |1876 PATHSPEC_EXCLUDE);18771878if(has_symlink_leading_path(path, len))1879return dir->nr;18801881/*1882 * exclude patterns are treated like positive ones in1883 * create_simplify. Usually exclude patterns should be a1884 * subset of positive ones, which has no impacts on1885 * create_simplify().1886 */1887 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);1888 untracked =validate_untracked_cache(dir, len, pathspec);1889if(!untracked)1890/*1891 * make sure untracked cache code path is disabled,1892 * e.g. prep_exclude()1893 */1894 dir->untracked = NULL;1895if(!len ||treat_leading_path(dir, path, len, simplify))1896read_directory_recursive(dir, path, len, untracked,0, simplify);1897free_simplify(simplify);1898qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);1899qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);1900return dir->nr;1901}19021903intfile_exists(const char*f)1904{1905struct stat sb;1906returnlstat(f, &sb) ==0;1907}19081909/*1910 * Given two normalized paths (a trailing slash is ok), if subdir is1911 * outside dir, return -1. Otherwise return the offset in subdir that1912 * can be used as relative path to dir.1913 */1914intdir_inside_of(const char*subdir,const char*dir)1915{1916int offset =0;19171918assert(dir && subdir && *dir && *subdir);19191920while(*dir && *subdir && *dir == *subdir) {1921 dir++;1922 subdir++;1923 offset++;1924}19251926/* hel[p]/me vs hel[l]/yeah */1927if(*dir && *subdir)1928return-1;19291930if(!*subdir)1931return!*dir ? offset : -1;/* same dir */19321933/* foo/[b]ar vs foo/[] */1934if(is_dir_sep(dir[-1]))1935returnis_dir_sep(subdir[-1]) ? offset : -1;19361937/* foo[/]bar vs foo[] */1938returnis_dir_sep(*subdir) ? offset +1: -1;1939}19401941intis_inside_dir(const char*dir)1942{1943char*cwd;1944int rc;19451946if(!dir)1947return0;19481949 cwd =xgetcwd();1950 rc = (dir_inside_of(cwd, dir) >=0);1951free(cwd);1952return rc;1953}19541955intis_empty_dir(const char*path)1956{1957DIR*dir =opendir(path);1958struct dirent *e;1959int ret =1;19601961if(!dir)1962return0;19631964while((e =readdir(dir)) != NULL)1965if(!is_dot_or_dotdot(e->d_name)) {1966 ret =0;1967break;1968}19691970closedir(dir);1971return ret;1972}19731974static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)1975{1976DIR*dir;1977struct dirent *e;1978int ret =0, original_len = path->len, len, kept_down =0;1979int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);1980int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);1981unsigned char submodule_head[20];19821983if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&1984!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {1985/* Do not descend and nuke a nested git work tree. */1986if(kept_up)1987*kept_up =1;1988return0;1989}19901991 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;1992 dir =opendir(path->buf);1993if(!dir) {1994if(errno == ENOENT)1995return keep_toplevel ? -1:0;1996else if(errno == EACCES && !keep_toplevel)1997/*1998 * An empty dir could be removable even if it1999 * is unreadable:2000 */2001returnrmdir(path->buf);2002else2003return-1;2004}2005if(path->buf[original_len -1] !='/')2006strbuf_addch(path,'/');20072008 len = path->len;2009while((e =readdir(dir)) != NULL) {2010struct stat st;2011if(is_dot_or_dotdot(e->d_name))2012continue;20132014strbuf_setlen(path, len);2015strbuf_addstr(path, e->d_name);2016if(lstat(path->buf, &st)) {2017if(errno == ENOENT)2018/*2019 * file disappeared, which is what we2020 * wanted anyway2021 */2022continue;2023/* fall thru */2024}else if(S_ISDIR(st.st_mode)) {2025if(!remove_dir_recurse(path, flag, &kept_down))2026continue;/* happy */2027}else if(!only_empty &&2028(!unlink(path->buf) || errno == ENOENT)) {2029continue;/* happy, too */2030}20312032/* path too long, stat fails, or non-directory still exists */2033 ret = -1;2034break;2035}2036closedir(dir);20372038strbuf_setlen(path, original_len);2039if(!ret && !keep_toplevel && !kept_down)2040 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2041else if(kept_up)2042/*2043 * report the uplevel that it is not an error that we2044 * did not rmdir() our directory.2045 */2046*kept_up = !ret;2047return ret;2048}20492050intremove_dir_recursively(struct strbuf *path,int flag)2051{2052returnremove_dir_recurse(path, flag, NULL);2053}20542055voidsetup_standard_excludes(struct dir_struct *dir)2056{2057const char*path;2058char*xdg_path;20592060 dir->exclude_per_dir =".gitignore";2061 path =git_path("info/exclude");2062if(!excludes_file) {2063home_config_paths(NULL, &xdg_path,"ignore");2064 excludes_file = xdg_path;2065}2066if(!access_or_warn(path, R_OK,0))2067add_excludes_from_file_1(dir, path,2068 dir->untracked ? &dir->ss_info_exclude : NULL);2069if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2070add_excludes_from_file_1(dir, excludes_file,2071 dir->untracked ? &dir->ss_excludes_file : NULL);2072}20732074intremove_path(const char*name)2075{2076char*slash;20772078if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2079return-1;20802081 slash =strrchr(name,'/');2082if(slash) {2083char*dirs =xstrdup(name);2084 slash = dirs + (slash - name);2085do{2086*slash ='\0';2087}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2088free(dirs);2089}2090return0;2091}20922093/*2094 * Frees memory within dir which was allocated for exclude lists and2095 * the exclude_stack. Does not free dir itself.2096 */2097voidclear_directory(struct dir_struct *dir)2098{2099int i, j;2100struct exclude_list_group *group;2101struct exclude_list *el;2102struct exclude_stack *stk;21032104for(i = EXC_CMDL; i <= EXC_FILE; i++) {2105 group = &dir->exclude_list_group[i];2106for(j =0; j < group->nr; j++) {2107 el = &group->el[j];2108if(i == EXC_DIRS)2109free((char*)el->src);2110clear_exclude_list(el);2111}2112free(group->el);2113}21142115 stk = dir->exclude_stack;2116while(stk) {2117struct exclude_stack *prev = stk->prev;2118free(stk);2119 stk = prev;2120}2121strbuf_release(&dir->basebuf);2122}