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#include"utf8.h" 16#include"varint.h" 17#include"ewah/ewok.h" 18 19struct path_simplify { 20int len; 21const char*path; 22}; 23 24/* 25 * Tells read_directory_recursive how a file or directory should be treated. 26 * Values are ordered by significance, e.g. if a directory contains both 27 * excluded and untracked files, it is listed as untracked because 28 * path_untracked > path_excluded. 29 */ 30enum path_treatment { 31 path_none =0, 32 path_recurse, 33 path_excluded, 34 path_untracked 35}; 36 37/* 38 * Support data structure for our opendir/readdir/closedir wrappers 39 */ 40struct cached_dir { 41DIR*fdir; 42struct untracked_cache_dir *untracked; 43int nr_files; 44int nr_dirs; 45 46struct dirent *de; 47const char*file; 48struct untracked_cache_dir *ucd; 49}; 50 51static enum path_treatment read_directory_recursive(struct dir_struct *dir, 52const char*path,int len,struct untracked_cache_dir *untracked, 53int check_only,const struct path_simplify *simplify); 54static intget_dtype(struct dirent *de,const char*path,int len); 55 56static struct trace_key trace_exclude =TRACE_KEY_INIT(EXCLUDE); 57 58/* helper string functions with support for the ignore_case flag */ 59intstrcmp_icase(const char*a,const char*b) 60{ 61return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 62} 63 64intstrncmp_icase(const char*a,const char*b,size_t count) 65{ 66return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 67} 68 69intfnmatch_icase(const char*pattern,const char*string,int flags) 70{ 71returnwildmatch(pattern, string, 72 flags | (ignore_case ? WM_CASEFOLD :0), 73 NULL); 74} 75 76intgit_fnmatch(const struct pathspec_item *item, 77const char*pattern,const char*string, 78int prefix) 79{ 80if(prefix >0) { 81if(ps_strncmp(item, pattern, string, prefix)) 82return WM_NOMATCH; 83 pattern += prefix; 84 string += prefix; 85} 86if(item->flags & PATHSPEC_ONESTAR) { 87int pattern_len =strlen(++pattern); 88int string_len =strlen(string); 89return string_len < pattern_len || 90ps_strcmp(item, pattern, 91 string + string_len - pattern_len); 92} 93if(item->magic & PATHSPEC_GLOB) 94returnwildmatch(pattern, string, 95 WM_PATHNAME | 96(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 97 NULL); 98else 99/* wildmatch has not learned no FNM_PATHNAME mode yet */ 100returnwildmatch(pattern, string, 101 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 102 NULL); 103} 104 105static intfnmatch_icase_mem(const char*pattern,int patternlen, 106const char*string,int stringlen, 107int flags) 108{ 109int match_status; 110struct strbuf pat_buf = STRBUF_INIT; 111struct strbuf str_buf = STRBUF_INIT; 112const char*use_pat = pattern; 113const char*use_str = string; 114 115if(pattern[patternlen]) { 116strbuf_add(&pat_buf, pattern, patternlen); 117 use_pat = pat_buf.buf; 118} 119if(string[stringlen]) { 120strbuf_add(&str_buf, string, stringlen); 121 use_str = str_buf.buf; 122} 123 124if(ignore_case) 125 flags |= WM_CASEFOLD; 126 match_status =wildmatch(use_pat, use_str, flags, NULL); 127 128strbuf_release(&pat_buf); 129strbuf_release(&str_buf); 130 131return match_status; 132} 133 134static size_tcommon_prefix_len(const struct pathspec *pathspec) 135{ 136int n; 137size_t max =0; 138 139/* 140 * ":(icase)path" is treated as a pathspec full of 141 * wildcard. In other words, only prefix is considered common 142 * prefix. If the pathspec is abc/foo abc/bar, running in 143 * subdir xyz, the common prefix is still xyz, not xuz/abc as 144 * in non-:(icase). 145 */ 146GUARD_PATHSPEC(pathspec, 147 PATHSPEC_FROMTOP | 148 PATHSPEC_MAXDEPTH | 149 PATHSPEC_LITERAL | 150 PATHSPEC_GLOB | 151 PATHSPEC_ICASE | 152 PATHSPEC_EXCLUDE); 153 154for(n =0; n < pathspec->nr; n++) { 155size_t i =0, len =0, item_len; 156if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 157continue; 158if(pathspec->items[n].magic & PATHSPEC_ICASE) 159 item_len = pathspec->items[n].prefix; 160else 161 item_len = pathspec->items[n].nowildcard_len; 162while(i < item_len && (n ==0|| i < max)) { 163char c = pathspec->items[n].match[i]; 164if(c != pathspec->items[0].match[i]) 165break; 166if(c =='/') 167 len = i +1; 168 i++; 169} 170if(n ==0|| len < max) { 171 max = len; 172if(!max) 173break; 174} 175} 176return max; 177} 178 179/* 180 * Returns a copy of the longest leading path common among all 181 * pathspecs. 182 */ 183char*common_prefix(const struct pathspec *pathspec) 184{ 185unsigned long len =common_prefix_len(pathspec); 186 187return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 188} 189 190intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 191{ 192size_t len; 193 194/* 195 * Calculate common prefix for the pathspec, and 196 * use that to optimize the directory walk 197 */ 198 len =common_prefix_len(pathspec); 199 200/* Read the directory and prune it */ 201read_directory(dir, pathspec->nr ? pathspec->_raw[0] :"", len, pathspec); 202return len; 203} 204 205intwithin_depth(const char*name,int namelen, 206int depth,int max_depth) 207{ 208const char*cp = name, *cpe = name + namelen; 209 210while(cp < cpe) { 211if(*cp++ !='/') 212continue; 213 depth++; 214if(depth > max_depth) 215return0; 216} 217return1; 218} 219 220#define DO_MATCH_EXCLUDE 1 221#define DO_MATCH_DIRECTORY 2 222 223/* 224 * Does 'match' match the given name? 225 * A match is found if 226 * 227 * (1) the 'match' string is leading directory of 'name', or 228 * (2) the 'match' string is a wildcard and matches 'name', or 229 * (3) the 'match' string is exactly the same as 'name'. 230 * 231 * and the return value tells which case it was. 232 * 233 * It returns 0 when there is no match. 234 */ 235static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 236const char*name,int namelen,unsigned flags) 237{ 238/* name/namelen has prefix cut off by caller */ 239const char*match = item->match + prefix; 240int matchlen = item->len - prefix; 241 242/* 243 * The normal call pattern is: 244 * 1. prefix = common_prefix_len(ps); 245 * 2. prune something, or fill_directory 246 * 3. match_pathspec() 247 * 248 * 'prefix' at #1 may be shorter than the command's prefix and 249 * it's ok for #2 to match extra files. Those extras will be 250 * trimmed at #3. 251 * 252 * Suppose the pathspec is 'foo' and '../bar' running from 253 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 254 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 255 * user does not want XYZ/foo, only the "foo" part should be 256 * case-insensitive. We need to filter out XYZ/foo here. In 257 * other words, we do not trust the caller on comparing the 258 * prefix part when :(icase) is involved. We do exact 259 * comparison ourselves. 260 * 261 * Normally the caller (common_prefix_len() in fact) does 262 * _exact_ matching on name[-prefix+1..-1] and we do not need 263 * to check that part. Be defensive and check it anyway, in 264 * case common_prefix_len is changed, or a new caller is 265 * introduced that does not use common_prefix_len. 266 * 267 * If the penalty turns out too high when prefix is really 268 * long, maybe change it to 269 * strncmp(match, name, item->prefix - prefix) 270 */ 271if(item->prefix && (item->magic & PATHSPEC_ICASE) && 272strncmp(item->match, name - prefix, item->prefix)) 273return0; 274 275/* If the match was just the prefix, we matched */ 276if(!*match) 277return MATCHED_RECURSIVELY; 278 279if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 280if(matchlen == namelen) 281return MATCHED_EXACTLY; 282 283if(match[matchlen-1] =='/'|| name[matchlen] =='/') 284return MATCHED_RECURSIVELY; 285}else if((flags & DO_MATCH_DIRECTORY) && 286 match[matchlen -1] =='/'&& 287 namelen == matchlen -1&& 288!ps_strncmp(item, match, name, namelen)) 289return MATCHED_EXACTLY; 290 291if(item->nowildcard_len < item->len && 292!git_fnmatch(item, match, name, 293 item->nowildcard_len - prefix)) 294return MATCHED_FNMATCH; 295 296return0; 297} 298 299/* 300 * Given a name and a list of pathspecs, returns the nature of the 301 * closest (i.e. most specific) match of the name to any of the 302 * pathspecs. 303 * 304 * The caller typically calls this multiple times with the same 305 * pathspec and seen[] array but with different name/namelen 306 * (e.g. entries from the index) and is interested in seeing if and 307 * how each pathspec matches all the names it calls this function 308 * with. A mark is left in the seen[] array for each pathspec element 309 * indicating the closest type of match that element achieved, so if 310 * seen[n] remains zero after multiple invocations, that means the nth 311 * pathspec did not match any names, which could indicate that the 312 * user mistyped the nth pathspec. 313 */ 314static intdo_match_pathspec(const struct pathspec *ps, 315const char*name,int namelen, 316int prefix,char*seen, 317unsigned flags) 318{ 319int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 320 321GUARD_PATHSPEC(ps, 322 PATHSPEC_FROMTOP | 323 PATHSPEC_MAXDEPTH | 324 PATHSPEC_LITERAL | 325 PATHSPEC_GLOB | 326 PATHSPEC_ICASE | 327 PATHSPEC_EXCLUDE); 328 329if(!ps->nr) { 330if(!ps->recursive || 331!(ps->magic & PATHSPEC_MAXDEPTH) || 332 ps->max_depth == -1) 333return MATCHED_RECURSIVELY; 334 335if(within_depth(name, namelen,0, ps->max_depth)) 336return MATCHED_EXACTLY; 337else 338return0; 339} 340 341 name += prefix; 342 namelen -= prefix; 343 344for(i = ps->nr -1; i >=0; i--) { 345int how; 346 347if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 348( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 349continue; 350 351if(seen && seen[i] == MATCHED_EXACTLY) 352continue; 353/* 354 * Make exclude patterns optional and never report 355 * "pathspec ':(exclude)foo' matches no files" 356 */ 357if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 358 seen[i] = MATCHED_FNMATCH; 359 how =match_pathspec_item(ps->items+i, prefix, name, 360 namelen, flags); 361if(ps->recursive && 362(ps->magic & PATHSPEC_MAXDEPTH) && 363 ps->max_depth != -1&& 364 how && how != MATCHED_FNMATCH) { 365int len = ps->items[i].len; 366if(name[len] =='/') 367 len++; 368if(within_depth(name+len, namelen-len,0, ps->max_depth)) 369 how = MATCHED_EXACTLY; 370else 371 how =0; 372} 373if(how) { 374if(retval < how) 375 retval = how; 376if(seen && seen[i] < how) 377 seen[i] = how; 378} 379} 380return retval; 381} 382 383intmatch_pathspec(const struct pathspec *ps, 384const char*name,int namelen, 385int prefix,char*seen,int is_dir) 386{ 387int positive, negative; 388unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 389 positive =do_match_pathspec(ps, name, namelen, 390 prefix, seen, flags); 391if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 392return positive; 393 negative =do_match_pathspec(ps, name, namelen, 394 prefix, seen, 395 flags | DO_MATCH_EXCLUDE); 396return negative ?0: positive; 397} 398 399intreport_path_error(const char*ps_matched, 400const struct pathspec *pathspec, 401const char*prefix) 402{ 403/* 404 * Make sure all pathspec matched; otherwise it is an error. 405 */ 406int num, errors =0; 407for(num =0; num < pathspec->nr; num++) { 408int other, found_dup; 409 410if(ps_matched[num]) 411continue; 412/* 413 * The caller might have fed identical pathspec 414 * twice. Do not barf on such a mistake. 415 * FIXME: parse_pathspec should have eliminated 416 * duplicate pathspec. 417 */ 418for(found_dup = other =0; 419!found_dup && other < pathspec->nr; 420 other++) { 421if(other == num || !ps_matched[other]) 422continue; 423if(!strcmp(pathspec->items[other].original, 424 pathspec->items[num].original)) 425/* 426 * Ok, we have a match already. 427 */ 428 found_dup =1; 429} 430if(found_dup) 431continue; 432 433error("pathspec '%s' did not match any file(s) known to git.", 434 pathspec->items[num].original); 435 errors++; 436} 437return errors; 438} 439 440/* 441 * Return the length of the "simple" part of a path match limiter. 442 */ 443intsimple_length(const char*match) 444{ 445int len = -1; 446 447for(;;) { 448unsigned char c = *match++; 449 len++; 450if(c =='\0'||is_glob_special(c)) 451return len; 452} 453} 454 455intno_wildcard(const char*string) 456{ 457return string[simple_length(string)] =='\0'; 458} 459 460voidparse_exclude_pattern(const char**pattern, 461int*patternlen, 462int*flags, 463int*nowildcardlen) 464{ 465const char*p = *pattern; 466size_t i, len; 467 468*flags =0; 469if(*p =='!') { 470*flags |= EXC_FLAG_NEGATIVE; 471 p++; 472} 473 len =strlen(p); 474if(len && p[len -1] =='/') { 475 len--; 476*flags |= EXC_FLAG_MUSTBEDIR; 477} 478for(i =0; i < len; i++) { 479if(p[i] =='/') 480break; 481} 482if(i == len) 483*flags |= EXC_FLAG_NODIR; 484*nowildcardlen =simple_length(p); 485/* 486 * we should have excluded the trailing slash from 'p' too, 487 * but that's one more allocation. Instead just make sure 488 * nowildcardlen does not exceed real patternlen 489 */ 490if(*nowildcardlen > len) 491*nowildcardlen = len; 492if(*p =='*'&&no_wildcard(p +1)) 493*flags |= EXC_FLAG_ENDSWITH; 494*pattern = p; 495*patternlen = len; 496} 497 498voidadd_exclude(const char*string,const char*base, 499int baselen,struct exclude_list *el,int srcpos) 500{ 501struct exclude *x; 502int patternlen; 503int flags; 504int nowildcardlen; 505 506parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 507if(flags & EXC_FLAG_MUSTBEDIR) { 508char*s; 509 x =xmalloc(sizeof(*x) + patternlen +1); 510 s = (char*)(x+1); 511memcpy(s, string, patternlen); 512 s[patternlen] ='\0'; 513 x->pattern = s; 514}else{ 515 x =xmalloc(sizeof(*x)); 516 x->pattern = string; 517} 518 x->patternlen = patternlen; 519 x->nowildcardlen = nowildcardlen; 520 x->base = base; 521 x->baselen = baselen; 522 x->flags = flags; 523 x->srcpos = srcpos; 524string_list_init(&x->sticky_paths,1); 525ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 526 el->excludes[el->nr++] = x; 527 x->el = el; 528} 529 530static void*read_skip_worktree_file_from_index(const char*path,size_t*size, 531struct sha1_stat *sha1_stat) 532{ 533int pos, len; 534unsigned long sz; 535enum object_type type; 536void*data; 537 538 len =strlen(path); 539 pos =cache_name_pos(path, len); 540if(pos <0) 541return NULL; 542if(!ce_skip_worktree(active_cache[pos])) 543return NULL; 544 data =read_sha1_file(active_cache[pos]->sha1, &type, &sz); 545if(!data || type != OBJ_BLOB) { 546free(data); 547return NULL; 548} 549*size =xsize_t(sz); 550if(sha1_stat) { 551memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 552hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 553} 554return data; 555} 556 557/* 558 * Frees memory within el which was allocated for exclude patterns and 559 * the file buffer. Does not free el itself. 560 */ 561voidclear_exclude_list(struct exclude_list *el) 562{ 563int i; 564 565for(i =0; i < el->nr; i++) { 566string_list_clear(&el->excludes[i]->sticky_paths,0); 567free(el->excludes[i]); 568} 569free(el->excludes); 570free(el->filebuf); 571 572memset(el,0,sizeof(*el)); 573} 574 575static voidtrim_trailing_spaces(char*buf) 576{ 577char*p, *last_space = NULL; 578 579for(p = buf; *p; p++) 580switch(*p) { 581case' ': 582if(!last_space) 583 last_space = p; 584break; 585case'\\': 586 p++; 587if(!*p) 588return; 589/* fallthrough */ 590default: 591 last_space = NULL; 592} 593 594if(last_space) 595*last_space ='\0'; 596} 597 598/* 599 * Given a subdirectory name and "dir" of the current directory, 600 * search the subdir in "dir" and return it, or create a new one if it 601 * does not exist in "dir". 602 * 603 * If "name" has the trailing slash, it'll be excluded in the search. 604 */ 605static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 606struct untracked_cache_dir *dir, 607const char*name,int len) 608{ 609int first, last; 610struct untracked_cache_dir *d; 611if(!dir) 612return NULL; 613if(len && name[len -1] =='/') 614 len--; 615 first =0; 616 last = dir->dirs_nr; 617while(last > first) { 618int cmp, next = (last + first) >>1; 619 d = dir->dirs[next]; 620 cmp =strncmp(name, d->name, len); 621if(!cmp &&strlen(d->name) > len) 622 cmp = -1; 623if(!cmp) 624return d; 625if(cmp <0) { 626 last = next; 627continue; 628} 629 first = next+1; 630} 631 632 uc->dir_created++; 633 d =xmalloc(sizeof(*d) + len +1); 634memset(d,0,sizeof(*d)); 635memcpy(d->name, name, len); 636 d->name[len] ='\0'; 637 638ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 639memmove(dir->dirs + first +1, dir->dirs + first, 640(dir->dirs_nr - first) *sizeof(*dir->dirs)); 641 dir->dirs_nr++; 642 dir->dirs[first] = d; 643return d; 644} 645 646static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 647{ 648int i; 649 dir->valid =0; 650 dir->untracked_nr =0; 651for(i =0; i < dir->dirs_nr; i++) 652do_invalidate_gitignore(dir->dirs[i]); 653} 654 655static voidinvalidate_gitignore(struct untracked_cache *uc, 656struct untracked_cache_dir *dir) 657{ 658 uc->gitignore_invalidated++; 659do_invalidate_gitignore(dir); 660} 661 662static voidinvalidate_directory(struct untracked_cache *uc, 663struct untracked_cache_dir *dir) 664{ 665int i; 666 uc->dir_invalidated++; 667 dir->valid =0; 668 dir->untracked_nr =0; 669for(i =0; i < dir->dirs_nr; i++) 670 dir->dirs[i]->recurse =0; 671} 672 673/* 674 * Given a file with name "fname", read it (either from disk, or from 675 * the index if "check_index" is non-zero), parse it and store the 676 * exclude rules in "el". 677 * 678 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 679 * stat data from disk (only valid if add_excludes returns zero). If 680 * ss_valid is non-zero, "ss" must contain good value as input. 681 */ 682static intadd_excludes(const char*fname,const char*base,int baselen, 683struct exclude_list *el,int check_index, 684struct sha1_stat *sha1_stat) 685{ 686struct stat st; 687int fd, i, lineno =1; 688size_t size =0; 689char*buf, *entry; 690 691 fd =open(fname, O_RDONLY); 692if(fd <0||fstat(fd, &st) <0) { 693if(errno != ENOENT) 694warn_on_inaccessible(fname); 695if(0<= fd) 696close(fd); 697if(!check_index || 698(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 699return-1; 700if(size ==0) { 701free(buf); 702return0; 703} 704if(buf[size-1] !='\n') { 705 buf =xrealloc(buf, size+1); 706 buf[size++] ='\n'; 707} 708}else{ 709 size =xsize_t(st.st_size); 710if(size ==0) { 711if(sha1_stat) { 712fill_stat_data(&sha1_stat->stat, &st); 713hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 714 sha1_stat->valid =1; 715} 716close(fd); 717return0; 718} 719 buf =xmalloc(size+1); 720if(read_in_full(fd, buf, size) != size) { 721free(buf); 722close(fd); 723return-1; 724} 725 buf[size++] ='\n'; 726close(fd); 727if(sha1_stat) { 728int pos; 729if(sha1_stat->valid && 730!match_stat_data_racy(&the_index, &sha1_stat->stat, &st)) 731;/* no content change, ss->sha1 still good */ 732else if(check_index && 733(pos =cache_name_pos(fname,strlen(fname))) >=0&& 734!ce_stage(active_cache[pos]) && 735ce_uptodate(active_cache[pos]) && 736!would_convert_to_git(fname)) 737hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 738else 739hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 740fill_stat_data(&sha1_stat->stat, &st); 741 sha1_stat->valid =1; 742} 743} 744 745 el->filebuf = buf; 746 747if(skip_utf8_bom(&buf, size)) 748 size -= buf - el->filebuf; 749 750 entry = buf; 751 752for(i =0; i < size; i++) { 753if(buf[i] =='\n') { 754if(entry != buf + i && entry[0] !='#') { 755 buf[i - (i && buf[i-1] =='\r')] =0; 756trim_trailing_spaces(entry); 757add_exclude(entry, base, baselen, el, lineno); 758} 759 lineno++; 760 entry = buf + i +1; 761} 762} 763return0; 764} 765 766intadd_excludes_from_file_to_list(const char*fname,const char*base, 767int baselen,struct exclude_list *el, 768int check_index) 769{ 770returnadd_excludes(fname, base, baselen, el, check_index, NULL); 771} 772 773struct exclude_list *add_exclude_list(struct dir_struct *dir, 774int group_type,const char*src) 775{ 776struct exclude_list *el; 777struct exclude_list_group *group; 778 779 group = &dir->exclude_list_group[group_type]; 780ALLOC_GROW(group->el, group->nr +1, group->alloc); 781 el = &group->el[group->nr++]; 782memset(el,0,sizeof(*el)); 783 el->src = src; 784return el; 785} 786 787/* 788 * Used to set up core.excludesfile and .git/info/exclude lists. 789 */ 790static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 791struct sha1_stat *sha1_stat) 792{ 793struct exclude_list *el; 794/* 795 * catch setup_standard_excludes() that's called before 796 * dir->untracked is assigned. That function behaves 797 * differently when dir->untracked is non-NULL. 798 */ 799if(!dir->untracked) 800 dir->unmanaged_exclude_files++; 801 el =add_exclude_list(dir, EXC_FILE, fname); 802if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 803die("cannot use%sas an exclude file", fname); 804} 805 806voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 807{ 808 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 809add_excludes_from_file_1(dir, fname, NULL); 810} 811 812intmatch_basename(const char*basename,int basenamelen, 813const char*pattern,int prefix,int patternlen, 814int flags) 815{ 816if(prefix == patternlen) { 817if(patternlen == basenamelen && 818!strncmp_icase(pattern, basename, basenamelen)) 819return1; 820}else if(flags & EXC_FLAG_ENDSWITH) { 821/* "*literal" matching against "fooliteral" */ 822if(patternlen -1<= basenamelen && 823!strncmp_icase(pattern +1, 824 basename + basenamelen - (patternlen -1), 825 patternlen -1)) 826return1; 827}else{ 828if(fnmatch_icase_mem(pattern, patternlen, 829 basename, basenamelen, 8300) ==0) 831return1; 832} 833return0; 834} 835 836intmatch_pathname(const char*pathname,int pathlen, 837const char*base,int baselen, 838const char*pattern,int prefix,int patternlen, 839int flags) 840{ 841const char*name; 842int namelen; 843 844/* 845 * match with FNM_PATHNAME; the pattern has base implicitly 846 * in front of it. 847 */ 848if(*pattern =='/') { 849 pattern++; 850 patternlen--; 851 prefix--; 852} 853 854/* 855 * baselen does not count the trailing slash. base[] may or 856 * may not end with a trailing slash though. 857 */ 858if(pathlen < baselen +1|| 859(baselen && pathname[baselen] !='/') || 860strncmp_icase(pathname, base, baselen)) 861return0; 862 863 namelen = baselen ? pathlen - baselen -1: pathlen; 864 name = pathname + pathlen - namelen; 865 866if(prefix) { 867/* 868 * if the non-wildcard part is longer than the 869 * remaining pathname, surely it cannot match. 870 */ 871if(prefix > namelen) 872return0; 873 874if(strncmp_icase(pattern, name, prefix)) 875return0; 876 pattern += prefix; 877 patternlen -= prefix; 878 name += prefix; 879 namelen -= prefix; 880 881/* 882 * If the whole pattern did not have a wildcard, 883 * then our prefix match is all we need; we 884 * do not need to call fnmatch at all. 885 */ 886if(!patternlen && (!namelen || *name =='/')) 887return1; 888} 889 890returnfnmatch_icase_mem(pattern, patternlen, 891 name, namelen, 892 WM_PATHNAME) ==0; 893} 894 895static voidadd_sticky(struct exclude *exc,const char*pathname,int pathlen) 896{ 897struct strbuf sb = STRBUF_INIT; 898int i; 899 900for(i = exc->sticky_paths.nr -1; i >=0; i--) { 901const char*sticky = exc->sticky_paths.items[i].string; 902int len =strlen(sticky); 903 904if(pathlen < len && sticky[pathlen] =='/'&& 905!strncmp(pathname, sticky, pathlen)) 906return; 907} 908 909strbuf_add(&sb, pathname, pathlen); 910string_list_append_nodup(&exc->sticky_paths,strbuf_detach(&sb, NULL)); 911} 912 913static intmatch_sticky(struct exclude *exc,const char*pathname,int pathlen,int dtype) 914{ 915int i; 916 917for(i = exc->sticky_paths.nr -1; i >=0; i--) { 918const char*sticky = exc->sticky_paths.items[i].string; 919int len =strlen(sticky); 920 921if(pathlen == len && dtype == DT_DIR && 922!strncmp(pathname, sticky, len)) 923return1; 924 925if(pathlen > len && pathname[len] =='/'&& 926!strncmp(pathname, sticky, len)) 927return1; 928} 929 930return0; 931} 932 933staticinlineintdifferent_decisions(const struct exclude *a, 934const struct exclude *b) 935{ 936return(a->flags & EXC_FLAG_NEGATIVE) != (b->flags & EXC_FLAG_NEGATIVE); 937} 938 939/* 940 * Return non-zero if pathname is a directory and an ancestor of the 941 * literal path in a pattern. 942 */ 943static intmatch_directory_part(const char*pathname,int pathlen, 944int*dtype,struct exclude *x) 945{ 946const char*base = x->base; 947int baselen = x->baselen ? x->baselen -1:0; 948const char*pattern = x->pattern; 949int prefix = x->nowildcardlen; 950int patternlen = x->patternlen; 951 952if(*dtype == DT_UNKNOWN) 953*dtype =get_dtype(NULL, pathname, pathlen); 954if(*dtype != DT_DIR) 955return0; 956 957if(*pattern =='/') { 958 pattern++; 959 patternlen--; 960 prefix--; 961} 962 963if(baselen) { 964if(((pathlen < baselen && base[pathlen] =='/') || 965 pathlen == baselen) && 966!strncmp_icase(pathname, base, pathlen)) 967return1; 968 pathname += baselen +1; 969 pathlen -= baselen +1; 970} 971 972 973if(prefix && 974(((pathlen < prefix && pattern[pathlen] =='/') || 975 pathlen == prefix) && 976!strncmp_icase(pathname, pattern, pathlen))) 977return1; 978 979return0; 980} 981 982static struct exclude *should_descend(const char*pathname,int pathlen, 983int*dtype,struct exclude_list *el, 984struct exclude *exc) 985{ 986int i; 987 988for(i = el->nr -1;0<= i; i--) { 989struct exclude *x = el->excludes[i]; 990 991if(x == exc) 992break; 993 994if(!(x->flags & EXC_FLAG_NODIR) && 995different_decisions(x, exc) && 996match_directory_part(pathname, pathlen, dtype, x)) 997return x; 998} 999return NULL;1000}10011002/*1003 * Scan the given exclude list in reverse to see whether pathname1004 * should be ignored. The first match (i.e. the last on the list), if1005 * any, determines the fate. Returns the exclude_list element which1006 * matched, or NULL for undecided.1007 */1008static struct exclude *last_exclude_matching_from_list(const char*pathname,1009int pathlen,1010const char*basename,1011int*dtype,1012struct exclude_list *el)1013{1014struct exclude *exc = NULL;/* undecided */1015int i, maybe_descend =0;10161017if(!el->nr)1018return NULL;/* undefined */10191020trace_printf_key(&trace_exclude,"exclude: from%s\n", el->src);10211022for(i = el->nr -1;0<= i; i--) {1023struct exclude *x = el->excludes[i];1024const char*exclude = x->pattern;1025int prefix = x->nowildcardlen;10261027if(!maybe_descend && i < el->nr -1&&1028different_decisions(x, el->excludes[i+1]))1029 maybe_descend =1;10301031if(x->sticky_paths.nr) {1032if(*dtype == DT_UNKNOWN)1033*dtype =get_dtype(NULL, pathname, pathlen);1034if(match_sticky(x, pathname, pathlen, *dtype)) {1035 exc = x;1036break;1037}1038continue;1039}10401041if(x->flags & EXC_FLAG_MUSTBEDIR) {1042if(*dtype == DT_UNKNOWN)1043*dtype =get_dtype(NULL, pathname, pathlen);1044if(*dtype != DT_DIR)1045continue;1046}10471048if(x->flags & EXC_FLAG_NODIR) {1049if(match_basename(basename,1050 pathlen - (basename - pathname),1051 exclude, prefix, x->patternlen,1052 x->flags)) {1053 exc = x;1054break;1055}1056continue;1057}10581059assert(x->baselen ==0|| x->base[x->baselen -1] =='/');1060if(match_pathname(pathname, pathlen,1061 x->base, x->baselen ? x->baselen -1:0,1062 exclude, prefix, x->patternlen, x->flags)) {1063 exc = x;1064break;1065}1066}10671068if(!exc) {1069trace_printf_key(&trace_exclude,"exclude: %.*s => n/a\n",1070 pathlen, pathname);1071return NULL;1072}10731074/*1075 * We have found a matching pattern "exc" that may exclude whole1076 * directory. We also found that there may be a pattern that matches1077 * something inside the directory and reincludes stuff.1078 *1079 * Go through the patterns again, find that pattern and double check.1080 * If it's true, return "undecided" and keep descending in. "exc" is1081 * marked sticky so that it continues to match inside the directory.1082 */1083if(!(exc->flags & EXC_FLAG_NEGATIVE) && maybe_descend) {1084struct exclude *x;10851086if(*dtype == DT_UNKNOWN)1087*dtype =get_dtype(NULL, pathname, pathlen);10881089if(*dtype == DT_DIR &&1090(x =should_descend(pathname, pathlen, dtype, el, exc))) {1091add_sticky(exc, pathname, pathlen);1092trace_printf_key(&trace_exclude,1093"exclude: %.*s vs%sat line%d=>%s,"1094" forced open by%sat line%d=> n/a\n",1095 pathlen, pathname, exc->pattern, exc->srcpos,1096 exc->flags & EXC_FLAG_NEGATIVE ?"no":"yes",1097 x->pattern, x->srcpos);1098return NULL;1099}1100}11011102trace_printf_key(&trace_exclude,"exclude: %.*s vs%sat line%d=>%s%s\n",1103 pathlen, pathname, exc->pattern, exc->srcpos,1104 exc->flags & EXC_FLAG_NEGATIVE ?"no":"yes",1105 exc->sticky_paths.nr ?" (stuck)":"");1106return exc;1107}11081109/*1110 * Scan the list and let the last match determine the fate.1111 * Return 1 for exclude, 0 for include and -1 for undecided.1112 */1113intis_excluded_from_list(const char*pathname,1114int pathlen,const char*basename,int*dtype,1115struct exclude_list *el)1116{1117struct exclude *exclude;1118 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el);1119if(exclude)1120return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1121return-1;/* undecided */1122}11231124static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir,1125const char*pathname,int pathlen,const char*basename,1126int*dtype_p)1127{1128int i, j;1129struct exclude_list_group *group;1130struct exclude *exclude;1131for(i = EXC_CMDL; i <= EXC_FILE; i++) {1132 group = &dir->exclude_list_group[i];1133for(j = group->nr -1; j >=0; j--) {1134 exclude =last_exclude_matching_from_list(1135 pathname, pathlen, basename, dtype_p,1136&group->el[j]);1137if(exclude)1138return exclude;1139}1140}1141return NULL;1142}11431144/*1145 * Loads the per-directory exclude list for the substring of base1146 * which has a char length of baselen.1147 */1148static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen)1149{1150struct exclude_list_group *group;1151struct exclude_list *el;1152struct exclude_stack *stk = NULL;1153struct untracked_cache_dir *untracked;1154int current;11551156 group = &dir->exclude_list_group[EXC_DIRS];11571158/*1159 * Pop the exclude lists from the EXCL_DIRS exclude_list_group1160 * which originate from directories not in the prefix of the1161 * path being checked.1162 */1163while((stk = dir->exclude_stack) != NULL) {1164if(stk->baselen <= baselen &&1165!strncmp(dir->basebuf.buf, base, stk->baselen))1166break;1167 el = &group->el[dir->exclude_stack->exclude_ix];1168 dir->exclude_stack = stk->prev;1169 dir->exclude = NULL;1170free((char*)el->src);/* see strbuf_detach() below */1171clear_exclude_list(el);1172free(stk);1173 group->nr--;1174}11751176/* Skip traversing into sub directories if the parent is excluded */1177if(dir->exclude)1178return;11791180/*1181 * Lazy initialization. All call sites currently just1182 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1183 * them seems lots of work for little benefit.1184 */1185if(!dir->basebuf.buf)1186strbuf_init(&dir->basebuf, PATH_MAX);11871188/* Read from the parent directories and push them down. */1189 current = stk ? stk->baselen : -1;1190strbuf_setlen(&dir->basebuf, current <0?0: current);1191if(dir->untracked)1192 untracked = stk ? stk->ucd : dir->untracked->root;1193else1194 untracked = NULL;11951196while(current < baselen) {1197const char*cp;1198struct sha1_stat sha1_stat;11991200 stk =xcalloc(1,sizeof(*stk));1201if(current <0) {1202 cp = base;1203 current =0;1204}else{1205 cp =strchr(base + current +1,'/');1206if(!cp)1207die("oops in prep_exclude");1208 cp++;1209 untracked =1210lookup_untracked(dir->untracked, untracked,1211 base + current,1212 cp - base - current);1213}1214 stk->prev = dir->exclude_stack;1215 stk->baselen = cp - base;1216 stk->exclude_ix = group->nr;1217 stk->ucd = untracked;1218 el =add_exclude_list(dir, EXC_DIRS, NULL);1219strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1220assert(stk->baselen == dir->basebuf.len);12211222/* Abort if the directory is excluded */1223if(stk->baselen) {1224int dt = DT_DIR;1225 dir->basebuf.buf[stk->baselen -1] =0;1226 dir->exclude =last_exclude_matching_from_lists(dir,1227 dir->basebuf.buf, stk->baselen -1,1228 dir->basebuf.buf + current, &dt);1229 dir->basebuf.buf[stk->baselen -1] ='/';1230if(dir->exclude &&1231 dir->exclude->flags & EXC_FLAG_NEGATIVE)1232 dir->exclude = NULL;1233if(dir->exclude) {1234 dir->exclude_stack = stk;1235return;1236}1237}12381239/* Try to read per-directory file */1240hashclr(sha1_stat.sha1);1241 sha1_stat.valid =0;1242if(dir->exclude_per_dir &&1243/*1244 * If we know that no files have been added in1245 * this directory (i.e. valid_cached_dir() has1246 * been executed and set untracked->valid) ..1247 */1248(!untracked || !untracked->valid ||1249/*1250 * .. and .gitignore does not exist before1251 * (i.e. null exclude_sha1). Then we can skip1252 * loading .gitignore, which would result in1253 * ENOENT anyway.1254 */1255!is_null_sha1(untracked->exclude_sha1))) {1256/*1257 * dir->basebuf gets reused by the traversal, but we1258 * need fname to remain unchanged to ensure the src1259 * member of each struct exclude correctly1260 * back-references its source file. Other invocations1261 * of add_exclude_list provide stable strings, so we1262 * strbuf_detach() and free() here in the caller.1263 */1264struct strbuf sb = STRBUF_INIT;1265strbuf_addbuf(&sb, &dir->basebuf);1266strbuf_addstr(&sb, dir->exclude_per_dir);1267 el->src =strbuf_detach(&sb, NULL);1268add_excludes(el->src, el->src, stk->baselen, el,1,1269 untracked ? &sha1_stat : NULL);1270}1271/*1272 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1273 * will first be called in valid_cached_dir() then maybe many1274 * times more in last_exclude_matching(). When the cache is1275 * used, last_exclude_matching() will not be called and1276 * reading .gitignore content will be a waste.1277 *1278 * So when it's called by valid_cached_dir() and we can get1279 * .gitignore SHA-1 from the index (i.e. .gitignore is not1280 * modified on work tree), we could delay reading the1281 * .gitignore content until we absolutely need it in1282 * last_exclude_matching(). Be careful about ignore rule1283 * order, though, if you do that.1284 */1285if(untracked &&1286hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1287invalidate_gitignore(dir->untracked, untracked);1288hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1289}1290 dir->exclude_stack = stk;1291 current = stk->baselen;1292}1293strbuf_setlen(&dir->basebuf, baselen);1294}12951296/*1297 * Loads the exclude lists for the directory containing pathname, then1298 * scans all exclude lists to determine whether pathname is excluded.1299 * Returns the exclude_list element which matched, or NULL for1300 * undecided.1301 */1302struct exclude *last_exclude_matching(struct dir_struct *dir,1303const char*pathname,1304int*dtype_p)1305{1306int pathlen =strlen(pathname);1307const char*basename =strrchr(pathname,'/');1308 basename = (basename) ? basename+1: pathname;13091310prep_exclude(dir, pathname, basename-pathname);13111312if(dir->exclude)1313return dir->exclude;13141315returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1316 basename, dtype_p);1317}13181319/*1320 * Loads the exclude lists for the directory containing pathname, then1321 * scans all exclude lists to determine whether pathname is excluded.1322 * Returns 1 if true, otherwise 0.1323 */1324intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1325{1326struct exclude *exclude =1327last_exclude_matching(dir, pathname, dtype_p);1328if(exclude)1329return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1330return0;1331}13321333static struct dir_entry *dir_entry_new(const char*pathname,int len)1334{1335struct dir_entry *ent;13361337 ent =xmalloc(sizeof(*ent) + len +1);1338 ent->len = len;1339memcpy(ent->name, pathname, len);1340 ent->name[len] =0;1341return ent;1342}13431344static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1345{1346if(cache_file_exists(pathname, len, ignore_case))1347return NULL;13481349ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1350return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1351}13521353struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1354{1355if(!cache_name_is_other(pathname, len))1356return NULL;13571358ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1359return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1360}13611362enum exist_status {1363 index_nonexistent =0,1364 index_directory,1365 index_gitdir1366};13671368/*1369 * Do not use the alphabetically sorted index to look up1370 * the directory name; instead, use the case insensitive1371 * directory hash.1372 */1373static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1374{1375struct cache_entry *ce;13761377if(cache_dir_exists(dirname, len))1378return index_directory;13791380 ce =cache_file_exists(dirname, len, ignore_case);1381if(ce &&S_ISGITLINK(ce->ce_mode))1382return index_gitdir;13831384return index_nonexistent;1385}13861387/*1388 * The index sorts alphabetically by entry name, which1389 * means that a gitlink sorts as '\0' at the end, while1390 * a directory (which is defined not as an entry, but as1391 * the files it contains) will sort with the '/' at the1392 * end.1393 */1394static enum exist_status directory_exists_in_index(const char*dirname,int len)1395{1396int pos;13971398if(ignore_case)1399returndirectory_exists_in_index_icase(dirname, len);14001401 pos =cache_name_pos(dirname, len);1402if(pos <0)1403 pos = -pos-1;1404while(pos < active_nr) {1405const struct cache_entry *ce = active_cache[pos++];1406unsigned char endchar;14071408if(strncmp(ce->name, dirname, len))1409break;1410 endchar = ce->name[len];1411if(endchar >'/')1412break;1413if(endchar =='/')1414return index_directory;1415if(!endchar &&S_ISGITLINK(ce->ce_mode))1416return index_gitdir;1417}1418return index_nonexistent;1419}14201421/*1422 * When we find a directory when traversing the filesystem, we1423 * have three distinct cases:1424 *1425 * - ignore it1426 * - see it as a directory1427 * - recurse into it1428 *1429 * and which one we choose depends on a combination of existing1430 * git index contents and the flags passed into the directory1431 * traversal routine.1432 *1433 * Case 1: If we *already* have entries in the index under that1434 * directory name, we always recurse into the directory to see1435 * all the files.1436 *1437 * Case 2: If we *already* have that directory name as a gitlink,1438 * we always continue to see it as a gitlink, regardless of whether1439 * there is an actual git directory there or not (it might not1440 * be checked out as a subproject!)1441 *1442 * Case 3: if we didn't have it in the index previously, we1443 * have a few sub-cases:1444 *1445 * (a) if "show_other_directories" is true, we show it as1446 * just a directory, unless "hide_empty_directories" is1447 * also true, in which case we need to check if it contains any1448 * untracked and / or ignored files.1449 * (b) if it looks like a git directory, and we don't have1450 * 'no_gitlinks' set we treat it as a gitlink, and show it1451 * as a directory.1452 * (c) otherwise, we recurse into it.1453 */1454static enum path_treatment treat_directory(struct dir_struct *dir,1455struct untracked_cache_dir *untracked,1456const char*dirname,int len,int baselen,int exclude,1457const struct path_simplify *simplify)1458{1459/* The "len-1" is to strip the final '/' */1460switch(directory_exists_in_index(dirname, len-1)) {1461case index_directory:1462return path_recurse;14631464case index_gitdir:1465return path_none;14661467case index_nonexistent:1468if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1469break;1470if(!(dir->flags & DIR_NO_GITLINKS)) {1471unsigned char sha1[20];1472if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1473return path_untracked;1474}1475return path_recurse;1476}14771478/* This is the "show_other_directories" case */14791480if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1481return exclude ? path_excluded : path_untracked;14821483 untracked =lookup_untracked(dir->untracked, untracked,1484 dirname + baselen, len - baselen);1485returnread_directory_recursive(dir, dirname, len,1486 untracked,1, simplify);1487}14881489/*1490 * This is an inexact early pruning of any recursive directory1491 * reading - if the path cannot possibly be in the pathspec,1492 * return true, and we'll skip it early.1493 */1494static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1495{1496if(simplify) {1497for(;;) {1498const char*match = simplify->path;1499int len = simplify->len;15001501if(!match)1502break;1503if(len > pathlen)1504 len = pathlen;1505if(!memcmp(path, match, len))1506return0;1507 simplify++;1508}1509return1;1510}1511return0;1512}15131514/*1515 * This function tells us whether an excluded path matches a1516 * list of "interesting" pathspecs. That is, whether a path matched1517 * by any of the pathspecs could possibly be ignored by excluding1518 * the specified path. This can happen if:1519 *1520 * 1. the path is mentioned explicitly in the pathspec1521 *1522 * 2. the path is a directory prefix of some element in the1523 * pathspec1524 */1525static intexclude_matches_pathspec(const char*path,int len,1526const struct path_simplify *simplify)1527{1528if(simplify) {1529for(; simplify->path; simplify++) {1530if(len == simplify->len1531&& !memcmp(path, simplify->path, len))1532return1;1533if(len < simplify->len1534&& simplify->path[len] =='/'1535&& !memcmp(path, simplify->path, len))1536return1;1537}1538}1539return0;1540}15411542static intget_index_dtype(const char*path,int len)1543{1544int pos;1545const struct cache_entry *ce;15461547 ce =cache_file_exists(path, len,0);1548if(ce) {1549if(!ce_uptodate(ce))1550return DT_UNKNOWN;1551if(S_ISGITLINK(ce->ce_mode))1552return DT_DIR;1553/*1554 * Nobody actually cares about the1555 * difference between DT_LNK and DT_REG1556 */1557return DT_REG;1558}15591560/* Try to look it up as a directory */1561 pos =cache_name_pos(path, len);1562if(pos >=0)1563return DT_UNKNOWN;1564 pos = -pos-1;1565while(pos < active_nr) {1566 ce = active_cache[pos++];1567if(strncmp(ce->name, path, len))1568break;1569if(ce->name[len] >'/')1570break;1571if(ce->name[len] <'/')1572continue;1573if(!ce_uptodate(ce))1574break;/* continue? */1575return DT_DIR;1576}1577return DT_UNKNOWN;1578}15791580static intget_dtype(struct dirent *de,const char*path,int len)1581{1582int dtype = de ?DTYPE(de) : DT_UNKNOWN;1583struct stat st;15841585if(dtype != DT_UNKNOWN)1586return dtype;1587 dtype =get_index_dtype(path, len);1588if(dtype != DT_UNKNOWN)1589return dtype;1590if(lstat(path, &st))1591return dtype;1592if(S_ISREG(st.st_mode))1593return DT_REG;1594if(S_ISDIR(st.st_mode))1595return DT_DIR;1596if(S_ISLNK(st.st_mode))1597return DT_LNK;1598return dtype;1599}16001601static enum path_treatment treat_one_path(struct dir_struct *dir,1602struct untracked_cache_dir *untracked,1603struct strbuf *path,1604int baselen,1605const struct path_simplify *simplify,1606int dtype,struct dirent *de)1607{1608int exclude;1609int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);16101611if(dtype == DT_UNKNOWN)1612 dtype =get_dtype(de, path->buf, path->len);16131614/* Always exclude indexed files */1615if(dtype != DT_DIR && has_path_in_index)1616return path_none;16171618/*1619 * When we are looking at a directory P in the working tree,1620 * there are three cases:1621 *1622 * (1) P exists in the index. Everything inside the directory P in1623 * the working tree needs to go when P is checked out from the1624 * index.1625 *1626 * (2) P does not exist in the index, but there is P/Q in the index.1627 * We know P will stay a directory when we check out the contents1628 * of the index, but we do not know yet if there is a directory1629 * P/Q in the working tree to be killed, so we need to recurse.1630 *1631 * (3) P does not exist in the index, and there is no P/Q in the index1632 * to require P to be a directory, either. Only in this case, we1633 * know that everything inside P will not be killed without1634 * recursing.1635 */1636if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1637(dtype == DT_DIR) &&1638!has_path_in_index &&1639(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1640return path_none;16411642 exclude =is_excluded(dir, path->buf, &dtype);16431644/*1645 * Excluded? If we don't explicitly want to show1646 * ignored files, ignore it1647 */1648if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1649return path_excluded;16501651switch(dtype) {1652default:1653return path_none;1654case DT_DIR:1655strbuf_addch(path,'/');1656returntreat_directory(dir, untracked, path->buf, path->len,1657 baselen, exclude, simplify);1658case DT_REG:1659case DT_LNK:1660return exclude ? path_excluded : path_untracked;1661}1662}16631664static enum path_treatment treat_path_fast(struct dir_struct *dir,1665struct untracked_cache_dir *untracked,1666struct cached_dir *cdir,1667struct strbuf *path,1668int baselen,1669const struct path_simplify *simplify)1670{1671strbuf_setlen(path, baselen);1672if(!cdir->ucd) {1673strbuf_addstr(path, cdir->file);1674return path_untracked;1675}1676strbuf_addstr(path, cdir->ucd->name);1677/* treat_one_path() does this before it calls treat_directory() */1678strbuf_complete(path,'/');1679if(cdir->ucd->check_only)1680/*1681 * check_only is set as a result of treat_directory() getting1682 * to its bottom. Verify again the same set of directories1683 * with check_only set.1684 */1685returnread_directory_recursive(dir, path->buf, path->len,1686 cdir->ucd,1, simplify);1687/*1688 * We get path_recurse in the first run when1689 * directory_exists_in_index() returns index_nonexistent. We1690 * are sure that new changes in the index does not impact the1691 * outcome. Return now.1692 */1693return path_recurse;1694}16951696static enum path_treatment treat_path(struct dir_struct *dir,1697struct untracked_cache_dir *untracked,1698struct cached_dir *cdir,1699struct strbuf *path,1700int baselen,1701const struct path_simplify *simplify)1702{1703int dtype;1704struct dirent *de = cdir->de;17051706if(!de)1707returntreat_path_fast(dir, untracked, cdir, path,1708 baselen, simplify);1709if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1710return path_none;1711strbuf_setlen(path, baselen);1712strbuf_addstr(path, de->d_name);1713if(simplify_away(path->buf, path->len, simplify))1714return path_none;17151716 dtype =DTYPE(de);1717returntreat_one_path(dir, untracked, path, baselen, simplify, dtype, de);1718}17191720static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1721{1722if(!dir)1723return;1724ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1725 dir->untracked_alloc);1726 dir->untracked[dir->untracked_nr++] =xstrdup(name);1727}17281729static intvalid_cached_dir(struct dir_struct *dir,1730struct untracked_cache_dir *untracked,1731struct strbuf *path,1732int check_only)1733{1734struct stat st;17351736if(!untracked)1737return0;17381739if(stat(path->len ? path->buf :".", &st)) {1740invalidate_directory(dir->untracked, untracked);1741memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1742return0;1743}1744if(!untracked->valid ||1745match_stat_data_racy(&the_index, &untracked->stat_data, &st)) {1746if(untracked->valid)1747invalidate_directory(dir->untracked, untracked);1748fill_stat_data(&untracked->stat_data, &st);1749return0;1750}17511752if(untracked->check_only != !!check_only) {1753invalidate_directory(dir->untracked, untracked);1754return0;1755}17561757/*1758 * prep_exclude will be called eventually on this directory,1759 * but it's called much later in last_exclude_matching(). We1760 * need it now to determine the validity of the cache for this1761 * path. The next calls will be nearly no-op, the way1762 * prep_exclude() is designed.1763 */1764if(path->len && path->buf[path->len -1] !='/') {1765strbuf_addch(path,'/');1766prep_exclude(dir, path->buf, path->len);1767strbuf_setlen(path, path->len -1);1768}else1769prep_exclude(dir, path->buf, path->len);17701771/* hopefully prep_exclude() haven't invalidated this entry... */1772return untracked->valid;1773}17741775static intopen_cached_dir(struct cached_dir *cdir,1776struct dir_struct *dir,1777struct untracked_cache_dir *untracked,1778struct strbuf *path,1779int check_only)1780{1781memset(cdir,0,sizeof(*cdir));1782 cdir->untracked = untracked;1783if(valid_cached_dir(dir, untracked, path, check_only))1784return0;1785 cdir->fdir =opendir(path->len ? path->buf :".");1786if(dir->untracked)1787 dir->untracked->dir_opened++;1788if(!cdir->fdir)1789return-1;1790return0;1791}17921793static intread_cached_dir(struct cached_dir *cdir)1794{1795if(cdir->fdir) {1796 cdir->de =readdir(cdir->fdir);1797if(!cdir->de)1798return-1;1799return0;1800}1801while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1802struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1803if(!d->recurse) {1804 cdir->nr_dirs++;1805continue;1806}1807 cdir->ucd = d;1808 cdir->nr_dirs++;1809return0;1810}1811 cdir->ucd = NULL;1812if(cdir->nr_files < cdir->untracked->untracked_nr) {1813struct untracked_cache_dir *d = cdir->untracked;1814 cdir->file = d->untracked[cdir->nr_files++];1815return0;1816}1817return-1;1818}18191820static voidclose_cached_dir(struct cached_dir *cdir)1821{1822if(cdir->fdir)1823closedir(cdir->fdir);1824/*1825 * We have gone through this directory and found no untracked1826 * entries. Mark it valid.1827 */1828if(cdir->untracked) {1829 cdir->untracked->valid =1;1830 cdir->untracked->recurse =1;1831}1832}18331834/*1835 * Read a directory tree. We currently ignore anything but1836 * directories, regular files and symlinks. That's because git1837 * doesn't handle them at all yet. Maybe that will change some1838 * day.1839 *1840 * Also, we ignore the name ".git" (even if it is not a directory).1841 * That likely will not change.1842 *1843 * Returns the most significant path_treatment value encountered in the scan.1844 */1845static enum path_treatment read_directory_recursive(struct dir_struct *dir,1846const char*base,int baselen,1847struct untracked_cache_dir *untracked,int check_only,1848const struct path_simplify *simplify)1849{1850struct cached_dir cdir;1851enum path_treatment state, subdir_state, dir_state = path_none;1852struct strbuf path = STRBUF_INIT;1853static int level =0;18541855strbuf_add(&path, base, baselen);18561857trace_printf_key(&trace_exclude,"exclude: [%d] enter '%.*s'\n",1858 level++, baselen, base);18591860if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1861goto out;18621863if(untracked)1864 untracked->check_only = !!check_only;18651866while(!read_cached_dir(&cdir)) {1867/* check how the file or directory should be treated */1868 state =treat_path(dir, untracked, &cdir, &path, baselen, simplify);18691870if(state > dir_state)1871 dir_state = state;18721873/* recurse into subdir if instructed by treat_path */1874if(state == path_recurse) {1875struct untracked_cache_dir *ud;1876 ud =lookup_untracked(dir->untracked, untracked,1877 path.buf + baselen,1878 path.len - baselen);1879 subdir_state =1880read_directory_recursive(dir, path.buf, path.len,1881 ud, check_only, simplify);1882if(subdir_state > dir_state)1883 dir_state = subdir_state;1884}18851886if(check_only) {1887/* abort early if maximum state has been reached */1888if(dir_state == path_untracked) {1889if(cdir.fdir)1890add_untracked(untracked, path.buf + baselen);1891break;1892}1893/* skip the dir_add_* part */1894continue;1895}18961897/* add the path to the appropriate result list */1898switch(state) {1899case path_excluded:1900if(dir->flags & DIR_SHOW_IGNORED)1901dir_add_name(dir, path.buf, path.len);1902else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1903((dir->flags & DIR_COLLECT_IGNORED) &&1904exclude_matches_pathspec(path.buf, path.len,1905 simplify)))1906dir_add_ignored(dir, path.buf, path.len);1907break;19081909case path_untracked:1910if(dir->flags & DIR_SHOW_IGNORED)1911break;1912dir_add_name(dir, path.buf, path.len);1913if(cdir.fdir)1914add_untracked(untracked, path.buf + baselen);1915break;19161917default:1918break;1919}1920}1921close_cached_dir(&cdir);1922 out:1923trace_printf_key(&trace_exclude,"exclude: [%d] leave '%.*s'\n",1924--level, baselen, base);1925strbuf_release(&path);19261927return dir_state;1928}19291930static intcmp_name(const void*p1,const void*p2)1931{1932const struct dir_entry *e1 = *(const struct dir_entry **)p1;1933const struct dir_entry *e2 = *(const struct dir_entry **)p2;19341935returnname_compare(e1->name, e1->len, e2->name, e2->len);1936}19371938static struct path_simplify *create_simplify(const char**pathspec)1939{1940int nr, alloc =0;1941struct path_simplify *simplify = NULL;19421943if(!pathspec)1944return NULL;19451946for(nr =0; ; nr++) {1947const char*match;1948ALLOC_GROW(simplify, nr +1, alloc);1949 match = *pathspec++;1950if(!match)1951break;1952 simplify[nr].path = match;1953 simplify[nr].len =simple_length(match);1954}1955 simplify[nr].path = NULL;1956 simplify[nr].len =0;1957return simplify;1958}19591960static voidfree_simplify(struct path_simplify *simplify)1961{1962free(simplify);1963}19641965static inttreat_leading_path(struct dir_struct *dir,1966const char*path,int len,1967const struct path_simplify *simplify)1968{1969struct strbuf sb = STRBUF_INIT;1970int baselen, rc =0;1971const char*cp;1972int old_flags = dir->flags;19731974while(len && path[len -1] =='/')1975 len--;1976if(!len)1977return1;1978 baselen =0;1979 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1980while(1) {1981 cp = path + baselen + !!baselen;1982 cp =memchr(cp,'/', path + len - cp);1983if(!cp)1984 baselen = len;1985else1986 baselen = cp - path;1987strbuf_setlen(&sb,0);1988strbuf_add(&sb, path, baselen);1989if(!is_directory(sb.buf))1990break;1991if(simplify_away(sb.buf, sb.len, simplify))1992break;1993if(treat_one_path(dir, NULL, &sb, baselen, simplify,1994 DT_DIR, NULL) == path_none)1995break;/* do not recurse into it */1996if(len <= baselen) {1997 rc =1;1998break;/* finished checking */1999}2000}2001strbuf_release(&sb);2002 dir->flags = old_flags;2003return rc;2004}20052006static const char*get_ident_string(void)2007{2008static struct strbuf sb = STRBUF_INIT;2009struct utsname uts;20102011if(sb.len)2012return sb.buf;2013if(uname(&uts) <0)2014die_errno(_("failed to get kernel name and information"));2015strbuf_addf(&sb,"Location%s, system%s",get_git_work_tree(),2016 uts.sysname);2017return sb.buf;2018}20192020static intident_in_untracked(const struct untracked_cache *uc)2021{2022/*2023 * Previous git versions may have saved many NUL separated2024 * strings in the "ident" field, but it is insane to manage2025 * many locations, so just take care of the first one.2026 */20272028return!strcmp(uc->ident.buf,get_ident_string());2029}20302031static voidset_untracked_ident(struct untracked_cache *uc)2032{2033strbuf_reset(&uc->ident);2034strbuf_addstr(&uc->ident,get_ident_string());20352036/*2037 * This strbuf used to contain a list of NUL separated2038 * strings, so save NUL too for backward compatibility.2039 */2040strbuf_addch(&uc->ident,0);2041}20422043static voidnew_untracked_cache(struct index_state *istate)2044{2045struct untracked_cache *uc =xcalloc(1,sizeof(*uc));2046strbuf_init(&uc->ident,100);2047 uc->exclude_per_dir =".gitignore";2048/* should be the same flags used by git-status */2049 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;2050set_untracked_ident(uc);2051 istate->untracked = uc;2052 istate->cache_changed |= UNTRACKED_CHANGED;2053}20542055voidadd_untracked_cache(struct index_state *istate)2056{2057if(!istate->untracked) {2058new_untracked_cache(istate);2059}else{2060if(!ident_in_untracked(istate->untracked)) {2061free_untracked_cache(istate->untracked);2062new_untracked_cache(istate);2063}2064}2065}20662067voidremove_untracked_cache(struct index_state *istate)2068{2069if(istate->untracked) {2070free_untracked_cache(istate->untracked);2071 istate->untracked = NULL;2072 istate->cache_changed |= UNTRACKED_CHANGED;2073}2074}20752076static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,2077int base_len,2078const struct pathspec *pathspec)2079{2080struct untracked_cache_dir *root;20812082if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))2083return NULL;20842085/*2086 * We only support $GIT_DIR/info/exclude and core.excludesfile2087 * as the global ignore rule files. Any other additions2088 * (e.g. from command line) invalidate the cache. This2089 * condition also catches running setup_standard_excludes()2090 * before setting dir->untracked!2091 */2092if(dir->unmanaged_exclude_files)2093return NULL;20942095/*2096 * Optimize for the main use case only: whole-tree git2097 * status. More work involved in treat_leading_path() if we2098 * use cache on just a subset of the worktree. pathspec2099 * support could make the matter even worse.2100 */2101if(base_len || (pathspec && pathspec->nr))2102return NULL;21032104/* Different set of flags may produce different results */2105if(dir->flags != dir->untracked->dir_flags ||2106/*2107 * See treat_directory(), case index_nonexistent. Without2108 * this flag, we may need to also cache .git file content2109 * for the resolve_gitlink_ref() call, which we don't.2110 */2111!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||2112/* We don't support collecting ignore files */2113(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |2114 DIR_COLLECT_IGNORED)))2115return NULL;21162117/*2118 * If we use .gitignore in the cache and now you change it to2119 * .gitexclude, everything will go wrong.2120 */2121if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&2122strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))2123return NULL;21242125/*2126 * EXC_CMDL is not considered in the cache. If people set it,2127 * skip the cache.2128 */2129if(dir->exclude_list_group[EXC_CMDL].nr)2130return NULL;21312132if(!ident_in_untracked(dir->untracked)) {2133warning(_("Untracked cache is disabled on this system or location."));2134return NULL;2135}21362137if(!dir->untracked->root) {2138const int len =sizeof(*dir->untracked->root);2139 dir->untracked->root =xmalloc(len);2140memset(dir->untracked->root,0, len);2141}21422143/* Validate $GIT_DIR/info/exclude and core.excludesfile */2144 root = dir->untracked->root;2145if(hashcmp(dir->ss_info_exclude.sha1,2146 dir->untracked->ss_info_exclude.sha1)) {2147invalidate_gitignore(dir->untracked, root);2148 dir->untracked->ss_info_exclude = dir->ss_info_exclude;2149}2150if(hashcmp(dir->ss_excludes_file.sha1,2151 dir->untracked->ss_excludes_file.sha1)) {2152invalidate_gitignore(dir->untracked, root);2153 dir->untracked->ss_excludes_file = dir->ss_excludes_file;2154}21552156/* Make sure this directory is not dropped out at saving phase */2157 root->recurse =1;2158return root;2159}21602161static voidclear_sticky(struct dir_struct *dir)2162{2163struct exclude_list_group *g;2164struct exclude_list *el;2165struct exclude *x;2166int i, j, k;21672168for(i = EXC_CMDL; i <= EXC_FILE; i++) {2169 g = &dir->exclude_list_group[i];2170for(j = g->nr -1; j >=0; j--) {2171 el = &g->el[j];2172for(k = el->nr -1;0<= k; k--) {2173 x = el->excludes[k];2174string_list_clear(&x->sticky_paths,0);2175}2176}2177}2178}21792180intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)2181{2182struct path_simplify *simplify;2183struct untracked_cache_dir *untracked;21842185/*2186 * Check out create_simplify()2187 */2188if(pathspec)2189GUARD_PATHSPEC(pathspec,2190 PATHSPEC_FROMTOP |2191 PATHSPEC_MAXDEPTH |2192 PATHSPEC_LITERAL |2193 PATHSPEC_GLOB |2194 PATHSPEC_ICASE |2195 PATHSPEC_EXCLUDE);21962197if(has_symlink_leading_path(path, len))2198return dir->nr;21992200/*2201 * Stay on the safe side. if read_directory() has run once on2202 * "dir", some sticky flag may have been left. Clear them all.2203 */2204clear_sticky(dir);22052206/*2207 * exclude patterns are treated like positive ones in2208 * create_simplify. Usually exclude patterns should be a2209 * subset of positive ones, which has no impacts on2210 * create_simplify().2211 */2212 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);2213 untracked =validate_untracked_cache(dir, len, pathspec);2214if(!untracked)2215/*2216 * make sure untracked cache code path is disabled,2217 * e.g. prep_exclude()2218 */2219 dir->untracked = NULL;2220if(!len ||treat_leading_path(dir, path, len, simplify))2221read_directory_recursive(dir, path, len, untracked,0, simplify);2222free_simplify(simplify);2223qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);2224qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);2225if(dir->untracked) {2226static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);2227trace_printf_key(&trace_untracked_stats,2228"node creation:%u\n"2229"gitignore invalidation:%u\n"2230"directory invalidation:%u\n"2231"opendir:%u\n",2232 dir->untracked->dir_created,2233 dir->untracked->gitignore_invalidated,2234 dir->untracked->dir_invalidated,2235 dir->untracked->dir_opened);2236if(dir->untracked == the_index.untracked &&2237(dir->untracked->dir_opened ||2238 dir->untracked->gitignore_invalidated ||2239 dir->untracked->dir_invalidated))2240 the_index.cache_changed |= UNTRACKED_CHANGED;2241if(dir->untracked != the_index.untracked) {2242free(dir->untracked);2243 dir->untracked = NULL;2244}2245}2246return dir->nr;2247}22482249intfile_exists(const char*f)2250{2251struct stat sb;2252returnlstat(f, &sb) ==0;2253}22542255static intcmp_icase(char a,char b)2256{2257if(a == b)2258return0;2259if(ignore_case)2260returntoupper(a) -toupper(b);2261return a - b;2262}22632264/*2265 * Given two normalized paths (a trailing slash is ok), if subdir is2266 * outside dir, return -1. Otherwise return the offset in subdir that2267 * can be used as relative path to dir.2268 */2269intdir_inside_of(const char*subdir,const char*dir)2270{2271int offset =0;22722273assert(dir && subdir && *dir && *subdir);22742275while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2276 dir++;2277 subdir++;2278 offset++;2279}22802281/* hel[p]/me vs hel[l]/yeah */2282if(*dir && *subdir)2283return-1;22842285if(!*subdir)2286return!*dir ? offset : -1;/* same dir */22872288/* foo/[b]ar vs foo/[] */2289if(is_dir_sep(dir[-1]))2290returnis_dir_sep(subdir[-1]) ? offset : -1;22912292/* foo[/]bar vs foo[] */2293returnis_dir_sep(*subdir) ? offset +1: -1;2294}22952296intis_inside_dir(const char*dir)2297{2298char*cwd;2299int rc;23002301if(!dir)2302return0;23032304 cwd =xgetcwd();2305 rc = (dir_inside_of(cwd, dir) >=0);2306free(cwd);2307return rc;2308}23092310intis_empty_dir(const char*path)2311{2312DIR*dir =opendir(path);2313struct dirent *e;2314int ret =1;23152316if(!dir)2317return0;23182319while((e =readdir(dir)) != NULL)2320if(!is_dot_or_dotdot(e->d_name)) {2321 ret =0;2322break;2323}23242325closedir(dir);2326return ret;2327}23282329static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2330{2331DIR*dir;2332struct dirent *e;2333int ret =0, original_len = path->len, len, kept_down =0;2334int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2335int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2336unsigned char submodule_head[20];23372338if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2339!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2340/* Do not descend and nuke a nested git work tree. */2341if(kept_up)2342*kept_up =1;2343return0;2344}23452346 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2347 dir =opendir(path->buf);2348if(!dir) {2349if(errno == ENOENT)2350return keep_toplevel ? -1:0;2351else if(errno == EACCES && !keep_toplevel)2352/*2353 * An empty dir could be removable even if it2354 * is unreadable:2355 */2356returnrmdir(path->buf);2357else2358return-1;2359}2360strbuf_complete(path,'/');23612362 len = path->len;2363while((e =readdir(dir)) != NULL) {2364struct stat st;2365if(is_dot_or_dotdot(e->d_name))2366continue;23672368strbuf_setlen(path, len);2369strbuf_addstr(path, e->d_name);2370if(lstat(path->buf, &st)) {2371if(errno == ENOENT)2372/*2373 * file disappeared, which is what we2374 * wanted anyway2375 */2376continue;2377/* fall thru */2378}else if(S_ISDIR(st.st_mode)) {2379if(!remove_dir_recurse(path, flag, &kept_down))2380continue;/* happy */2381}else if(!only_empty &&2382(!unlink(path->buf) || errno == ENOENT)) {2383continue;/* happy, too */2384}23852386/* path too long, stat fails, or non-directory still exists */2387 ret = -1;2388break;2389}2390closedir(dir);23912392strbuf_setlen(path, original_len);2393if(!ret && !keep_toplevel && !kept_down)2394 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2395else if(kept_up)2396/*2397 * report the uplevel that it is not an error that we2398 * did not rmdir() our directory.2399 */2400*kept_up = !ret;2401return ret;2402}24032404intremove_dir_recursively(struct strbuf *path,int flag)2405{2406returnremove_dir_recurse(path, flag, NULL);2407}24082409staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")24102411voidsetup_standard_excludes(struct dir_struct *dir)2412{2413const char*path;24142415 dir->exclude_per_dir =".gitignore";24162417/* core.excludefile defaulting to $XDG_HOME/git/ignore */2418if(!excludes_file)2419 excludes_file =xdg_config_home("ignore");2420if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2421add_excludes_from_file_1(dir, excludes_file,2422 dir->untracked ? &dir->ss_excludes_file : NULL);24232424/* per repository user preference */2425 path =git_path_info_exclude();2426if(!access_or_warn(path, R_OK,0))2427add_excludes_from_file_1(dir, path,2428 dir->untracked ? &dir->ss_info_exclude : NULL);2429}24302431intremove_path(const char*name)2432{2433char*slash;24342435if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2436return-1;24372438 slash =strrchr(name,'/');2439if(slash) {2440char*dirs =xstrdup(name);2441 slash = dirs + (slash - name);2442do{2443*slash ='\0';2444}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2445free(dirs);2446}2447return0;2448}24492450/*2451 * Frees memory within dir which was allocated for exclude lists and2452 * the exclude_stack. Does not free dir itself.2453 */2454voidclear_directory(struct dir_struct *dir)2455{2456int i, j;2457struct exclude_list_group *group;2458struct exclude_list *el;2459struct exclude_stack *stk;24602461for(i = EXC_CMDL; i <= EXC_FILE; i++) {2462 group = &dir->exclude_list_group[i];2463for(j =0; j < group->nr; j++) {2464 el = &group->el[j];2465if(i == EXC_DIRS)2466free((char*)el->src);2467clear_exclude_list(el);2468}2469free(group->el);2470}24712472 stk = dir->exclude_stack;2473while(stk) {2474struct exclude_stack *prev = stk->prev;2475free(stk);2476 stk = prev;2477}2478strbuf_release(&dir->basebuf);2479}24802481struct ondisk_untracked_cache {2482struct stat_data info_exclude_stat;2483struct stat_data excludes_file_stat;2484uint32_t dir_flags;2485unsigned char info_exclude_sha1[20];2486unsigned char excludes_file_sha1[20];2487char exclude_per_dir[FLEX_ARRAY];2488};24892490#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)24912492struct write_data {2493int index;/* number of written untracked_cache_dir */2494struct ewah_bitmap *check_only;/* from untracked_cache_dir */2495struct ewah_bitmap *valid;/* from untracked_cache_dir */2496struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2497struct strbuf out;2498struct strbuf sb_stat;2499struct strbuf sb_sha1;2500};25012502static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2503{2504 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2505 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2506 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2507 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2508 to->sd_dev =htonl(from->sd_dev);2509 to->sd_ino =htonl(from->sd_ino);2510 to->sd_uid =htonl(from->sd_uid);2511 to->sd_gid =htonl(from->sd_gid);2512 to->sd_size =htonl(from->sd_size);2513}25142515static voidwrite_one_dir(struct untracked_cache_dir *untracked,2516struct write_data *wd)2517{2518struct stat_data stat_data;2519struct strbuf *out = &wd->out;2520unsigned char intbuf[16];2521unsigned int intlen, value;2522int i = wd->index++;25232524/*2525 * untracked_nr should be reset whenever valid is clear, but2526 * for safety..2527 */2528if(!untracked->valid) {2529 untracked->untracked_nr =0;2530 untracked->check_only =0;2531}25322533if(untracked->check_only)2534ewah_set(wd->check_only, i);2535if(untracked->valid) {2536ewah_set(wd->valid, i);2537stat_data_to_disk(&stat_data, &untracked->stat_data);2538strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2539}2540if(!is_null_sha1(untracked->exclude_sha1)) {2541ewah_set(wd->sha1_valid, i);2542strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2543}25442545 intlen =encode_varint(untracked->untracked_nr, intbuf);2546strbuf_add(out, intbuf, intlen);25472548/* skip non-recurse directories */2549for(i =0, value =0; i < untracked->dirs_nr; i++)2550if(untracked->dirs[i]->recurse)2551 value++;2552 intlen =encode_varint(value, intbuf);2553strbuf_add(out, intbuf, intlen);25542555strbuf_add(out, untracked->name,strlen(untracked->name) +1);25562557for(i =0; i < untracked->untracked_nr; i++)2558strbuf_add(out, untracked->untracked[i],2559strlen(untracked->untracked[i]) +1);25602561for(i =0; i < untracked->dirs_nr; i++)2562if(untracked->dirs[i]->recurse)2563write_one_dir(untracked->dirs[i], wd);2564}25652566voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2567{2568struct ondisk_untracked_cache *ouc;2569struct write_data wd;2570unsigned char varbuf[16];2571int len =0, varint_len;2572if(untracked->exclude_per_dir)2573 len =strlen(untracked->exclude_per_dir);2574 ouc =xmalloc(sizeof(*ouc) + len +1);2575stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2576stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2577hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2578hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2579 ouc->dir_flags =htonl(untracked->dir_flags);2580memcpy(ouc->exclude_per_dir, untracked->exclude_per_dir, len +1);25812582 varint_len =encode_varint(untracked->ident.len, varbuf);2583strbuf_add(out, varbuf, varint_len);2584strbuf_add(out, untracked->ident.buf, untracked->ident.len);25852586strbuf_add(out, ouc,ouc_size(len));2587free(ouc);2588 ouc = NULL;25892590if(!untracked->root) {2591 varint_len =encode_varint(0, varbuf);2592strbuf_add(out, varbuf, varint_len);2593return;2594}25952596 wd.index =0;2597 wd.check_only =ewah_new();2598 wd.valid =ewah_new();2599 wd.sha1_valid =ewah_new();2600strbuf_init(&wd.out,1024);2601strbuf_init(&wd.sb_stat,1024);2602strbuf_init(&wd.sb_sha1,1024);2603write_one_dir(untracked->root, &wd);26042605 varint_len =encode_varint(wd.index, varbuf);2606strbuf_add(out, varbuf, varint_len);2607strbuf_addbuf(out, &wd.out);2608ewah_serialize_strbuf(wd.valid, out);2609ewah_serialize_strbuf(wd.check_only, out);2610ewah_serialize_strbuf(wd.sha1_valid, out);2611strbuf_addbuf(out, &wd.sb_stat);2612strbuf_addbuf(out, &wd.sb_sha1);2613strbuf_addch(out,'\0');/* safe guard for string lists */26142615ewah_free(wd.valid);2616ewah_free(wd.check_only);2617ewah_free(wd.sha1_valid);2618strbuf_release(&wd.out);2619strbuf_release(&wd.sb_stat);2620strbuf_release(&wd.sb_sha1);2621}26222623static voidfree_untracked(struct untracked_cache_dir *ucd)2624{2625int i;2626if(!ucd)2627return;2628for(i =0; i < ucd->dirs_nr; i++)2629free_untracked(ucd->dirs[i]);2630for(i =0; i < ucd->untracked_nr; i++)2631free(ucd->untracked[i]);2632free(ucd->untracked);2633free(ucd->dirs);2634free(ucd);2635}26362637voidfree_untracked_cache(struct untracked_cache *uc)2638{2639if(uc)2640free_untracked(uc->root);2641free(uc);2642}26432644struct read_data {2645int index;2646struct untracked_cache_dir **ucd;2647struct ewah_bitmap *check_only;2648struct ewah_bitmap *valid;2649struct ewah_bitmap *sha1_valid;2650const unsigned char*data;2651const unsigned char*end;2652};26532654static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2655{2656 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2657 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2658 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2659 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2660 to->sd_dev =get_be32(&from->sd_dev);2661 to->sd_ino =get_be32(&from->sd_ino);2662 to->sd_uid =get_be32(&from->sd_uid);2663 to->sd_gid =get_be32(&from->sd_gid);2664 to->sd_size =get_be32(&from->sd_size);2665}26662667static intread_one_dir(struct untracked_cache_dir **untracked_,2668struct read_data *rd)2669{2670struct untracked_cache_dir ud, *untracked;2671const unsigned char*next, *data = rd->data, *end = rd->end;2672unsigned int value;2673int i, len;26742675memset(&ud,0,sizeof(ud));26762677 next = data;2678 value =decode_varint(&next);2679if(next > end)2680return-1;2681 ud.recurse =1;2682 ud.untracked_alloc = value;2683 ud.untracked_nr = value;2684if(ud.untracked_nr)2685 ud.untracked =xmalloc(sizeof(*ud.untracked) * ud.untracked_nr);2686 data = next;26872688 next = data;2689 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2690if(next > end)2691return-1;2692 ud.dirs =xmalloc(sizeof(*ud.dirs) * ud.dirs_nr);2693 data = next;26942695 len =strlen((const char*)data);2696 next = data + len +1;2697if(next > rd->end)2698return-1;2699*untracked_ = untracked =xmalloc(sizeof(*untracked) + len);2700memcpy(untracked, &ud,sizeof(ud));2701memcpy(untracked->name, data, len +1);2702 data = next;27032704for(i =0; i < untracked->untracked_nr; i++) {2705 len =strlen((const char*)data);2706 next = data + len +1;2707if(next > rd->end)2708return-1;2709 untracked->untracked[i] =xstrdup((const char*)data);2710 data = next;2711}27122713 rd->ucd[rd->index++] = untracked;2714 rd->data = data;27152716for(i =0; i < untracked->dirs_nr; i++) {2717 len =read_one_dir(untracked->dirs + i, rd);2718if(len <0)2719return-1;2720}2721return0;2722}27232724static voidset_check_only(size_t pos,void*cb)2725{2726struct read_data *rd = cb;2727struct untracked_cache_dir *ud = rd->ucd[pos];2728 ud->check_only =1;2729}27302731static voidread_stat(size_t pos,void*cb)2732{2733struct read_data *rd = cb;2734struct untracked_cache_dir *ud = rd->ucd[pos];2735if(rd->data +sizeof(struct stat_data) > rd->end) {2736 rd->data = rd->end +1;2737return;2738}2739stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2740 rd->data +=sizeof(struct stat_data);2741 ud->valid =1;2742}27432744static voidread_sha1(size_t pos,void*cb)2745{2746struct read_data *rd = cb;2747struct untracked_cache_dir *ud = rd->ucd[pos];2748if(rd->data +20> rd->end) {2749 rd->data = rd->end +1;2750return;2751}2752hashcpy(ud->exclude_sha1, rd->data);2753 rd->data +=20;2754}27552756static voidload_sha1_stat(struct sha1_stat *sha1_stat,2757const struct stat_data *stat,2758const unsigned char*sha1)2759{2760stat_data_from_disk(&sha1_stat->stat, stat);2761hashcpy(sha1_stat->sha1, sha1);2762 sha1_stat->valid =1;2763}27642765struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2766{2767const struct ondisk_untracked_cache *ouc;2768struct untracked_cache *uc;2769struct read_data rd;2770const unsigned char*next = data, *end = (const unsigned char*)data + sz;2771const char*ident;2772int ident_len, len;27732774if(sz <=1|| end[-1] !='\0')2775return NULL;2776 end--;27772778 ident_len =decode_varint(&next);2779if(next + ident_len > end)2780return NULL;2781 ident = (const char*)next;2782 next += ident_len;27832784 ouc = (const struct ondisk_untracked_cache *)next;2785if(next +ouc_size(0) > end)2786return NULL;27872788 uc =xcalloc(1,sizeof(*uc));2789strbuf_init(&uc->ident, ident_len);2790strbuf_add(&uc->ident, ident, ident_len);2791load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2792 ouc->info_exclude_sha1);2793load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2794 ouc->excludes_file_sha1);2795 uc->dir_flags =get_be32(&ouc->dir_flags);2796 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2797/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2798 next +=ouc_size(strlen(ouc->exclude_per_dir));2799if(next >= end)2800goto done2;28012802 len =decode_varint(&next);2803if(next > end || len ==0)2804goto done2;28052806 rd.valid =ewah_new();2807 rd.check_only =ewah_new();2808 rd.sha1_valid =ewah_new();2809 rd.data = next;2810 rd.end = end;2811 rd.index =0;2812 rd.ucd =xmalloc(sizeof(*rd.ucd) * len);28132814if(read_one_dir(&uc->root, &rd) || rd.index != len)2815goto done;28162817 next = rd.data;2818 len =ewah_read_mmap(rd.valid, next, end - next);2819if(len <0)2820goto done;28212822 next += len;2823 len =ewah_read_mmap(rd.check_only, next, end - next);2824if(len <0)2825goto done;28262827 next += len;2828 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2829if(len <0)2830goto done;28312832ewah_each_bit(rd.check_only, set_check_only, &rd);2833 rd.data = next + len;2834ewah_each_bit(rd.valid, read_stat, &rd);2835ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2836 next = rd.data;28372838done:2839free(rd.ucd);2840ewah_free(rd.valid);2841ewah_free(rd.check_only);2842ewah_free(rd.sha1_valid);2843done2:2844if(next != end) {2845free_untracked_cache(uc);2846 uc = NULL;2847}2848return uc;2849}28502851static voidinvalidate_one_directory(struct untracked_cache *uc,2852struct untracked_cache_dir *ucd)2853{2854 uc->dir_invalidated++;2855 ucd->valid =0;2856 ucd->untracked_nr =0;2857}28582859/*2860 * Normally when an entry is added or removed from a directory,2861 * invalidating that directory is enough. No need to touch its2862 * ancestors. When a directory is shown as "foo/bar/" in git-status2863 * however, deleting or adding an entry may have cascading effect.2864 *2865 * Say the "foo/bar/file" has become untracked, we need to tell the2866 * untracked_cache_dir of "foo" that "bar/" is not an untracked2867 * directory any more (because "bar" is managed by foo as an untracked2868 * "file").2869 *2870 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2871 * was the last untracked entry in the entire "foo", we should show2872 * "foo/" instead. Which means we have to invalidate past "bar" up to2873 * "foo".2874 *2875 * This function traverses all directories from root to leaf. If there2876 * is a chance of one of the above cases happening, we invalidate back2877 * to root. Otherwise we just invalidate the leaf. There may be a more2878 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2879 * detect these cases and avoid unnecessary invalidation, for example,2880 * checking for the untracked entry named "bar/" in "foo", but for now2881 * stick to something safe and simple.2882 */2883static intinvalidate_one_component(struct untracked_cache *uc,2884struct untracked_cache_dir *dir,2885const char*path,int len)2886{2887const char*rest =strchr(path,'/');28882889if(rest) {2890int component_len = rest - path;2891struct untracked_cache_dir *d =2892lookup_untracked(uc, dir, path, component_len);2893int ret =2894invalidate_one_component(uc, d, rest +1,2895 len - (component_len +1));2896if(ret)2897invalidate_one_directory(uc, dir);2898return ret;2899}29002901invalidate_one_directory(uc, dir);2902return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2903}29042905voiduntracked_cache_invalidate_path(struct index_state *istate,2906const char*path)2907{2908if(!istate->untracked || !istate->untracked->root)2909return;2910invalidate_one_component(istate->untracked, istate->untracked->root,2911 path,strlen(path));2912}29132914voiduntracked_cache_remove_from_index(struct index_state *istate,2915const char*path)2916{2917untracked_cache_invalidate_path(istate, path);2918}29192920voiduntracked_cache_add_to_index(struct index_state *istate,2921const char*path)2922{2923untracked_cache_invalidate_path(istate, path);2924}