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 56intfspathcmp(const char*a,const char*b) 57{ 58return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 59} 60 61intfspathncmp(const char*a,const char*b,size_t count) 62{ 63return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 64} 65 66intgit_fnmatch(const struct pathspec_item *item, 67const char*pattern,const char*string, 68int prefix) 69{ 70if(prefix >0) { 71if(ps_strncmp(item, pattern, string, prefix)) 72return WM_NOMATCH; 73 pattern += prefix; 74 string += prefix; 75} 76if(item->flags & PATHSPEC_ONESTAR) { 77int pattern_len =strlen(++pattern); 78int string_len =strlen(string); 79return string_len < pattern_len || 80ps_strcmp(item, pattern, 81 string + string_len - pattern_len); 82} 83if(item->magic & PATHSPEC_GLOB) 84returnwildmatch(pattern, string, 85 WM_PATHNAME | 86(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 87 NULL); 88else 89/* wildmatch has not learned no FNM_PATHNAME mode yet */ 90returnwildmatch(pattern, string, 91 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 92 NULL); 93} 94 95static intfnmatch_icase_mem(const char*pattern,int patternlen, 96const char*string,int stringlen, 97int flags) 98{ 99int match_status; 100struct strbuf pat_buf = STRBUF_INIT; 101struct strbuf str_buf = STRBUF_INIT; 102const char*use_pat = pattern; 103const char*use_str = string; 104 105if(pattern[patternlen]) { 106strbuf_add(&pat_buf, pattern, patternlen); 107 use_pat = pat_buf.buf; 108} 109if(string[stringlen]) { 110strbuf_add(&str_buf, string, stringlen); 111 use_str = str_buf.buf; 112} 113 114if(ignore_case) 115 flags |= WM_CASEFOLD; 116 match_status =wildmatch(use_pat, use_str, flags, NULL); 117 118strbuf_release(&pat_buf); 119strbuf_release(&str_buf); 120 121return match_status; 122} 123 124static size_tcommon_prefix_len(const struct pathspec *pathspec) 125{ 126int n; 127size_t max =0; 128 129/* 130 * ":(icase)path" is treated as a pathspec full of 131 * wildcard. In other words, only prefix is considered common 132 * prefix. If the pathspec is abc/foo abc/bar, running in 133 * subdir xyz, the common prefix is still xyz, not xuz/abc as 134 * in non-:(icase). 135 */ 136GUARD_PATHSPEC(pathspec, 137 PATHSPEC_FROMTOP | 138 PATHSPEC_MAXDEPTH | 139 PATHSPEC_LITERAL | 140 PATHSPEC_GLOB | 141 PATHSPEC_ICASE | 142 PATHSPEC_EXCLUDE); 143 144for(n =0; n < pathspec->nr; n++) { 145size_t i =0, len =0, item_len; 146if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 147continue; 148if(pathspec->items[n].magic & PATHSPEC_ICASE) 149 item_len = pathspec->items[n].prefix; 150else 151 item_len = pathspec->items[n].nowildcard_len; 152while(i < item_len && (n ==0|| i < max)) { 153char c = pathspec->items[n].match[i]; 154if(c != pathspec->items[0].match[i]) 155break; 156if(c =='/') 157 len = i +1; 158 i++; 159} 160if(n ==0|| len < max) { 161 max = len; 162if(!max) 163break; 164} 165} 166return max; 167} 168 169/* 170 * Returns a copy of the longest leading path common among all 171 * pathspecs. 172 */ 173char*common_prefix(const struct pathspec *pathspec) 174{ 175unsigned long len =common_prefix_len(pathspec); 176 177return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 178} 179 180intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 181{ 182size_t len; 183 184/* 185 * Calculate common prefix for the pathspec, and 186 * use that to optimize the directory walk 187 */ 188 len =common_prefix_len(pathspec); 189 190/* Read the directory and prune it */ 191read_directory(dir, pathspec->nr ? pathspec->_raw[0] :"", len, pathspec); 192return len; 193} 194 195intwithin_depth(const char*name,int namelen, 196int depth,int max_depth) 197{ 198const char*cp = name, *cpe = name + namelen; 199 200while(cp < cpe) { 201if(*cp++ !='/') 202continue; 203 depth++; 204if(depth > max_depth) 205return0; 206} 207return1; 208} 209 210#define DO_MATCH_EXCLUDE (1<<0) 211#define DO_MATCH_DIRECTORY (1<<1) 212#define DO_MATCH_SUBMODULE (1<<2) 213 214/* 215 * Does 'match' match the given name? 216 * A match is found if 217 * 218 * (1) the 'match' string is leading directory of 'name', or 219 * (2) the 'match' string is a wildcard and matches 'name', or 220 * (3) the 'match' string is exactly the same as 'name'. 221 * 222 * and the return value tells which case it was. 223 * 224 * It returns 0 when there is no match. 225 */ 226static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 227const char*name,int namelen,unsigned flags) 228{ 229/* name/namelen has prefix cut off by caller */ 230const char*match = item->match + prefix; 231int matchlen = item->len - prefix; 232 233/* 234 * The normal call pattern is: 235 * 1. prefix = common_prefix_len(ps); 236 * 2. prune something, or fill_directory 237 * 3. match_pathspec() 238 * 239 * 'prefix' at #1 may be shorter than the command's prefix and 240 * it's ok for #2 to match extra files. Those extras will be 241 * trimmed at #3. 242 * 243 * Suppose the pathspec is 'foo' and '../bar' running from 244 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 245 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 246 * user does not want XYZ/foo, only the "foo" part should be 247 * case-insensitive. We need to filter out XYZ/foo here. In 248 * other words, we do not trust the caller on comparing the 249 * prefix part when :(icase) is involved. We do exact 250 * comparison ourselves. 251 * 252 * Normally the caller (common_prefix_len() in fact) does 253 * _exact_ matching on name[-prefix+1..-1] and we do not need 254 * to check that part. Be defensive and check it anyway, in 255 * case common_prefix_len is changed, or a new caller is 256 * introduced that does not use common_prefix_len. 257 * 258 * If the penalty turns out too high when prefix is really 259 * long, maybe change it to 260 * strncmp(match, name, item->prefix - prefix) 261 */ 262if(item->prefix && (item->magic & PATHSPEC_ICASE) && 263strncmp(item->match, name - prefix, item->prefix)) 264return0; 265 266/* If the match was just the prefix, we matched */ 267if(!*match) 268return MATCHED_RECURSIVELY; 269 270if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 271if(matchlen == namelen) 272return MATCHED_EXACTLY; 273 274if(match[matchlen-1] =='/'|| name[matchlen] =='/') 275return MATCHED_RECURSIVELY; 276}else if((flags & DO_MATCH_DIRECTORY) && 277 match[matchlen -1] =='/'&& 278 namelen == matchlen -1&& 279!ps_strncmp(item, match, name, namelen)) 280return MATCHED_EXACTLY; 281 282if(item->nowildcard_len < item->len && 283!git_fnmatch(item, match, name, 284 item->nowildcard_len - prefix)) 285return MATCHED_FNMATCH; 286 287/* Perform checks to see if "name" is a super set of the pathspec */ 288if(flags & DO_MATCH_SUBMODULE) { 289/* name is a literal prefix of the pathspec */ 290if((namelen < matchlen) && 291(match[namelen] =='/') && 292!ps_strncmp(item, match, name, namelen)) 293return MATCHED_RECURSIVELY; 294 295/* name" doesn't match up to the first wild character */ 296if(item->nowildcard_len < item->len && 297ps_strncmp(item, match, name, 298 item->nowildcard_len - prefix)) 299return0; 300 301/* 302 * Here is where we would perform a wildmatch to check if 303 * "name" can be matched as a directory (or a prefix) against 304 * the pathspec. Since wildmatch doesn't have this capability 305 * at the present we have to punt and say that it is a match, 306 * potentially returning a false positive 307 * The submodules themselves will be able to perform more 308 * accurate matching to determine if the pathspec matches. 309 */ 310return MATCHED_RECURSIVELY; 311} 312 313return0; 314} 315 316/* 317 * Given a name and a list of pathspecs, returns the nature of the 318 * closest (i.e. most specific) match of the name to any of the 319 * pathspecs. 320 * 321 * The caller typically calls this multiple times with the same 322 * pathspec and seen[] array but with different name/namelen 323 * (e.g. entries from the index) and is interested in seeing if and 324 * how each pathspec matches all the names it calls this function 325 * with. A mark is left in the seen[] array for each pathspec element 326 * indicating the closest type of match that element achieved, so if 327 * seen[n] remains zero after multiple invocations, that means the nth 328 * pathspec did not match any names, which could indicate that the 329 * user mistyped the nth pathspec. 330 */ 331static intdo_match_pathspec(const struct pathspec *ps, 332const char*name,int namelen, 333int prefix,char*seen, 334unsigned flags) 335{ 336int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 337 338GUARD_PATHSPEC(ps, 339 PATHSPEC_FROMTOP | 340 PATHSPEC_MAXDEPTH | 341 PATHSPEC_LITERAL | 342 PATHSPEC_GLOB | 343 PATHSPEC_ICASE | 344 PATHSPEC_EXCLUDE); 345 346if(!ps->nr) { 347if(!ps->recursive || 348!(ps->magic & PATHSPEC_MAXDEPTH) || 349 ps->max_depth == -1) 350return MATCHED_RECURSIVELY; 351 352if(within_depth(name, namelen,0, ps->max_depth)) 353return MATCHED_EXACTLY; 354else 355return0; 356} 357 358 name += prefix; 359 namelen -= prefix; 360 361for(i = ps->nr -1; i >=0; i--) { 362int how; 363 364if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 365( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 366continue; 367 368if(seen && seen[i] == MATCHED_EXACTLY) 369continue; 370/* 371 * Make exclude patterns optional and never report 372 * "pathspec ':(exclude)foo' matches no files" 373 */ 374if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 375 seen[i] = MATCHED_FNMATCH; 376 how =match_pathspec_item(ps->items+i, prefix, name, 377 namelen, flags); 378if(ps->recursive && 379(ps->magic & PATHSPEC_MAXDEPTH) && 380 ps->max_depth != -1&& 381 how && how != MATCHED_FNMATCH) { 382int len = ps->items[i].len; 383if(name[len] =='/') 384 len++; 385if(within_depth(name+len, namelen-len,0, ps->max_depth)) 386 how = MATCHED_EXACTLY; 387else 388 how =0; 389} 390if(how) { 391if(retval < how) 392 retval = how; 393if(seen && seen[i] < how) 394 seen[i] = how; 395} 396} 397return retval; 398} 399 400intmatch_pathspec(const struct pathspec *ps, 401const char*name,int namelen, 402int prefix,char*seen,int is_dir) 403{ 404int positive, negative; 405unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 406 positive =do_match_pathspec(ps, name, namelen, 407 prefix, seen, flags); 408if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 409return positive; 410 negative =do_match_pathspec(ps, name, namelen, 411 prefix, seen, 412 flags | DO_MATCH_EXCLUDE); 413return negative ?0: positive; 414} 415 416/** 417 * Check if a submodule is a superset of the pathspec 418 */ 419intsubmodule_path_match(const struct pathspec *ps, 420const char*submodule_name, 421char*seen) 422{ 423int matched =do_match_pathspec(ps, submodule_name, 424strlen(submodule_name), 4250, seen, 426 DO_MATCH_DIRECTORY | 427 DO_MATCH_SUBMODULE); 428return matched; 429} 430 431intreport_path_error(const char*ps_matched, 432const struct pathspec *pathspec, 433const char*prefix) 434{ 435/* 436 * Make sure all pathspec matched; otherwise it is an error. 437 */ 438int num, errors =0; 439for(num =0; num < pathspec->nr; num++) { 440int other, found_dup; 441 442if(ps_matched[num]) 443continue; 444/* 445 * The caller might have fed identical pathspec 446 * twice. Do not barf on such a mistake. 447 * FIXME: parse_pathspec should have eliminated 448 * duplicate pathspec. 449 */ 450for(found_dup = other =0; 451!found_dup && other < pathspec->nr; 452 other++) { 453if(other == num || !ps_matched[other]) 454continue; 455if(!strcmp(pathspec->items[other].original, 456 pathspec->items[num].original)) 457/* 458 * Ok, we have a match already. 459 */ 460 found_dup =1; 461} 462if(found_dup) 463continue; 464 465error("pathspec '%s' did not match any file(s) known to git.", 466 pathspec->items[num].original); 467 errors++; 468} 469return errors; 470} 471 472/* 473 * Return the length of the "simple" part of a path match limiter. 474 */ 475intsimple_length(const char*match) 476{ 477int len = -1; 478 479for(;;) { 480unsigned char c = *match++; 481 len++; 482if(c =='\0'||is_glob_special(c)) 483return len; 484} 485} 486 487intno_wildcard(const char*string) 488{ 489return string[simple_length(string)] =='\0'; 490} 491 492voidparse_exclude_pattern(const char**pattern, 493int*patternlen, 494unsigned*flags, 495int*nowildcardlen) 496{ 497const char*p = *pattern; 498size_t i, len; 499 500*flags =0; 501if(*p =='!') { 502*flags |= EXC_FLAG_NEGATIVE; 503 p++; 504} 505 len =strlen(p); 506if(len && p[len -1] =='/') { 507 len--; 508*flags |= EXC_FLAG_MUSTBEDIR; 509} 510for(i =0; i < len; i++) { 511if(p[i] =='/') 512break; 513} 514if(i == len) 515*flags |= EXC_FLAG_NODIR; 516*nowildcardlen =simple_length(p); 517/* 518 * we should have excluded the trailing slash from 'p' too, 519 * but that's one more allocation. Instead just make sure 520 * nowildcardlen does not exceed real patternlen 521 */ 522if(*nowildcardlen > len) 523*nowildcardlen = len; 524if(*p =='*'&&no_wildcard(p +1)) 525*flags |= EXC_FLAG_ENDSWITH; 526*pattern = p; 527*patternlen = len; 528} 529 530voidadd_exclude(const char*string,const char*base, 531int baselen,struct exclude_list *el,int srcpos) 532{ 533struct exclude *x; 534int patternlen; 535unsigned flags; 536int nowildcardlen; 537 538parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 539if(flags & EXC_FLAG_MUSTBEDIR) { 540FLEXPTR_ALLOC_MEM(x, pattern, string, patternlen); 541}else{ 542 x =xmalloc(sizeof(*x)); 543 x->pattern = string; 544} 545 x->patternlen = patternlen; 546 x->nowildcardlen = nowildcardlen; 547 x->base = base; 548 x->baselen = baselen; 549 x->flags = flags; 550 x->srcpos = srcpos; 551ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 552 el->excludes[el->nr++] = x; 553 x->el = el; 554} 555 556static void*read_skip_worktree_file_from_index(const char*path,size_t*size, 557struct sha1_stat *sha1_stat) 558{ 559int pos, len; 560unsigned long sz; 561enum object_type type; 562void*data; 563 564 len =strlen(path); 565 pos =cache_name_pos(path, len); 566if(pos <0) 567return NULL; 568if(!ce_skip_worktree(active_cache[pos])) 569return NULL; 570 data =read_sha1_file(active_cache[pos]->oid.hash, &type, &sz); 571if(!data || type != OBJ_BLOB) { 572free(data); 573return NULL; 574} 575*size =xsize_t(sz); 576if(sha1_stat) { 577memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 578hashcpy(sha1_stat->sha1, active_cache[pos]->oid.hash); 579} 580return data; 581} 582 583/* 584 * Frees memory within el which was allocated for exclude patterns and 585 * the file buffer. Does not free el itself. 586 */ 587voidclear_exclude_list(struct exclude_list *el) 588{ 589int i; 590 591for(i =0; i < el->nr; i++) 592free(el->excludes[i]); 593free(el->excludes); 594free(el->filebuf); 595 596memset(el,0,sizeof(*el)); 597} 598 599static voidtrim_trailing_spaces(char*buf) 600{ 601char*p, *last_space = NULL; 602 603for(p = buf; *p; p++) 604switch(*p) { 605case' ': 606if(!last_space) 607 last_space = p; 608break; 609case'\\': 610 p++; 611if(!*p) 612return; 613/* fallthrough */ 614default: 615 last_space = NULL; 616} 617 618if(last_space) 619*last_space ='\0'; 620} 621 622/* 623 * Given a subdirectory name and "dir" of the current directory, 624 * search the subdir in "dir" and return it, or create a new one if it 625 * does not exist in "dir". 626 * 627 * If "name" has the trailing slash, it'll be excluded in the search. 628 */ 629static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 630struct untracked_cache_dir *dir, 631const char*name,int len) 632{ 633int first, last; 634struct untracked_cache_dir *d; 635if(!dir) 636return NULL; 637if(len && name[len -1] =='/') 638 len--; 639 first =0; 640 last = dir->dirs_nr; 641while(last > first) { 642int cmp, next = (last + first) >>1; 643 d = dir->dirs[next]; 644 cmp =strncmp(name, d->name, len); 645if(!cmp &&strlen(d->name) > len) 646 cmp = -1; 647if(!cmp) 648return d; 649if(cmp <0) { 650 last = next; 651continue; 652} 653 first = next+1; 654} 655 656 uc->dir_created++; 657FLEX_ALLOC_MEM(d, name, name, len); 658 659ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 660memmove(dir->dirs + first +1, dir->dirs + first, 661(dir->dirs_nr - first) *sizeof(*dir->dirs)); 662 dir->dirs_nr++; 663 dir->dirs[first] = d; 664return d; 665} 666 667static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 668{ 669int i; 670 dir->valid =0; 671 dir->untracked_nr =0; 672for(i =0; i < dir->dirs_nr; i++) 673do_invalidate_gitignore(dir->dirs[i]); 674} 675 676static voidinvalidate_gitignore(struct untracked_cache *uc, 677struct untracked_cache_dir *dir) 678{ 679 uc->gitignore_invalidated++; 680do_invalidate_gitignore(dir); 681} 682 683static voidinvalidate_directory(struct untracked_cache *uc, 684struct untracked_cache_dir *dir) 685{ 686int i; 687 uc->dir_invalidated++; 688 dir->valid =0; 689 dir->untracked_nr =0; 690for(i =0; i < dir->dirs_nr; i++) 691 dir->dirs[i]->recurse =0; 692} 693 694/* 695 * Given a file with name "fname", read it (either from disk, or from 696 * the index if "check_index" is non-zero), parse it and store the 697 * exclude rules in "el". 698 * 699 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 700 * stat data from disk (only valid if add_excludes returns zero). If 701 * ss_valid is non-zero, "ss" must contain good value as input. 702 */ 703static intadd_excludes(const char*fname,const char*base,int baselen, 704struct exclude_list *el,int check_index, 705struct sha1_stat *sha1_stat) 706{ 707struct stat st; 708int fd, i, lineno =1; 709size_t size =0; 710char*buf, *entry; 711 712 fd =open(fname, O_RDONLY); 713if(fd <0||fstat(fd, &st) <0) { 714if(errno != ENOENT) 715warn_on_inaccessible(fname); 716if(0<= fd) 717close(fd); 718if(!check_index || 719(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 720return-1; 721if(size ==0) { 722free(buf); 723return0; 724} 725if(buf[size-1] !='\n') { 726 buf =xrealloc(buf,st_add(size,1)); 727 buf[size++] ='\n'; 728} 729}else{ 730 size =xsize_t(st.st_size); 731if(size ==0) { 732if(sha1_stat) { 733fill_stat_data(&sha1_stat->stat, &st); 734hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 735 sha1_stat->valid =1; 736} 737close(fd); 738return0; 739} 740 buf =xmallocz(size); 741if(read_in_full(fd, buf, size) != size) { 742free(buf); 743close(fd); 744return-1; 745} 746 buf[size++] ='\n'; 747close(fd); 748if(sha1_stat) { 749int pos; 750if(sha1_stat->valid && 751!match_stat_data_racy(&the_index, &sha1_stat->stat, &st)) 752;/* no content change, ss->sha1 still good */ 753else if(check_index && 754(pos =cache_name_pos(fname,strlen(fname))) >=0&& 755!ce_stage(active_cache[pos]) && 756ce_uptodate(active_cache[pos]) && 757!would_convert_to_git(fname)) 758hashcpy(sha1_stat->sha1, 759 active_cache[pos]->oid.hash); 760else 761hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 762fill_stat_data(&sha1_stat->stat, &st); 763 sha1_stat->valid =1; 764} 765} 766 767 el->filebuf = buf; 768 769if(skip_utf8_bom(&buf, size)) 770 size -= buf - el->filebuf; 771 772 entry = buf; 773 774for(i =0; i < size; i++) { 775if(buf[i] =='\n') { 776if(entry != buf + i && entry[0] !='#') { 777 buf[i - (i && buf[i-1] =='\r')] =0; 778trim_trailing_spaces(entry); 779add_exclude(entry, base, baselen, el, lineno); 780} 781 lineno++; 782 entry = buf + i +1; 783} 784} 785return0; 786} 787 788intadd_excludes_from_file_to_list(const char*fname,const char*base, 789int baselen,struct exclude_list *el, 790int check_index) 791{ 792returnadd_excludes(fname, base, baselen, el, check_index, NULL); 793} 794 795struct exclude_list *add_exclude_list(struct dir_struct *dir, 796int group_type,const char*src) 797{ 798struct exclude_list *el; 799struct exclude_list_group *group; 800 801 group = &dir->exclude_list_group[group_type]; 802ALLOC_GROW(group->el, group->nr +1, group->alloc); 803 el = &group->el[group->nr++]; 804memset(el,0,sizeof(*el)); 805 el->src = src; 806return el; 807} 808 809/* 810 * Used to set up core.excludesfile and .git/info/exclude lists. 811 */ 812static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 813struct sha1_stat *sha1_stat) 814{ 815struct exclude_list *el; 816/* 817 * catch setup_standard_excludes() that's called before 818 * dir->untracked is assigned. That function behaves 819 * differently when dir->untracked is non-NULL. 820 */ 821if(!dir->untracked) 822 dir->unmanaged_exclude_files++; 823 el =add_exclude_list(dir, EXC_FILE, fname); 824if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 825die("cannot use%sas an exclude file", fname); 826} 827 828voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 829{ 830 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 831add_excludes_from_file_1(dir, fname, NULL); 832} 833 834intmatch_basename(const char*basename,int basenamelen, 835const char*pattern,int prefix,int patternlen, 836unsigned flags) 837{ 838if(prefix == patternlen) { 839if(patternlen == basenamelen && 840!fspathncmp(pattern, basename, basenamelen)) 841return1; 842}else if(flags & EXC_FLAG_ENDSWITH) { 843/* "*literal" matching against "fooliteral" */ 844if(patternlen -1<= basenamelen && 845!fspathncmp(pattern +1, 846 basename + basenamelen - (patternlen -1), 847 patternlen -1)) 848return1; 849}else{ 850if(fnmatch_icase_mem(pattern, patternlen, 851 basename, basenamelen, 8520) ==0) 853return1; 854} 855return0; 856} 857 858intmatch_pathname(const char*pathname,int pathlen, 859const char*base,int baselen, 860const char*pattern,int prefix,int patternlen, 861unsigned flags) 862{ 863const char*name; 864int namelen; 865 866/* 867 * match with FNM_PATHNAME; the pattern has base implicitly 868 * in front of it. 869 */ 870if(*pattern =='/') { 871 pattern++; 872 patternlen--; 873 prefix--; 874} 875 876/* 877 * baselen does not count the trailing slash. base[] may or 878 * may not end with a trailing slash though. 879 */ 880if(pathlen < baselen +1|| 881(baselen && pathname[baselen] !='/') || 882fspathncmp(pathname, base, baselen)) 883return0; 884 885 namelen = baselen ? pathlen - baselen -1: pathlen; 886 name = pathname + pathlen - namelen; 887 888if(prefix) { 889/* 890 * if the non-wildcard part is longer than the 891 * remaining pathname, surely it cannot match. 892 */ 893if(prefix > namelen) 894return0; 895 896if(fspathncmp(pattern, name, prefix)) 897return0; 898 pattern += prefix; 899 patternlen -= prefix; 900 name += prefix; 901 namelen -= prefix; 902 903/* 904 * If the whole pattern did not have a wildcard, 905 * then our prefix match is all we need; we 906 * do not need to call fnmatch at all. 907 */ 908if(!patternlen && !namelen) 909return1; 910} 911 912returnfnmatch_icase_mem(pattern, patternlen, 913 name, namelen, 914 WM_PATHNAME) ==0; 915} 916 917/* 918 * Scan the given exclude list in reverse to see whether pathname 919 * should be ignored. The first match (i.e. the last on the list), if 920 * any, determines the fate. Returns the exclude_list element which 921 * matched, or NULL for undecided. 922 */ 923static struct exclude *last_exclude_matching_from_list(const char*pathname, 924int pathlen, 925const char*basename, 926int*dtype, 927struct exclude_list *el) 928{ 929struct exclude *exc = NULL;/* undecided */ 930int i; 931 932if(!el->nr) 933return NULL;/* undefined */ 934 935for(i = el->nr -1;0<= i; i--) { 936struct exclude *x = el->excludes[i]; 937const char*exclude = x->pattern; 938int prefix = x->nowildcardlen; 939 940if(x->flags & EXC_FLAG_MUSTBEDIR) { 941if(*dtype == DT_UNKNOWN) 942*dtype =get_dtype(NULL, pathname, pathlen); 943if(*dtype != DT_DIR) 944continue; 945} 946 947if(x->flags & EXC_FLAG_NODIR) { 948if(match_basename(basename, 949 pathlen - (basename - pathname), 950 exclude, prefix, x->patternlen, 951 x->flags)) { 952 exc = x; 953break; 954} 955continue; 956} 957 958assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 959if(match_pathname(pathname, pathlen, 960 x->base, x->baselen ? x->baselen -1:0, 961 exclude, prefix, x->patternlen, x->flags)) { 962 exc = x; 963break; 964} 965} 966return exc; 967} 968 969/* 970 * Scan the list and let the last match determine the fate. 971 * Return 1 for exclude, 0 for include and -1 for undecided. 972 */ 973intis_excluded_from_list(const char*pathname, 974int pathlen,const char*basename,int*dtype, 975struct exclude_list *el) 976{ 977struct exclude *exclude; 978 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 979if(exclude) 980return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 981return-1;/* undecided */ 982} 983 984static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 985const char*pathname,int pathlen,const char*basename, 986int*dtype_p) 987{ 988int i, j; 989struct exclude_list_group *group; 990struct exclude *exclude; 991for(i = EXC_CMDL; i <= EXC_FILE; i++) { 992 group = &dir->exclude_list_group[i]; 993for(j = group->nr -1; j >=0; j--) { 994 exclude =last_exclude_matching_from_list( 995 pathname, pathlen, basename, dtype_p, 996&group->el[j]); 997if(exclude) 998return exclude; 999}1000}1001return NULL;1002}10031004/*1005 * Loads the per-directory exclude list for the substring of base1006 * which has a char length of baselen.1007 */1008static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen)1009{1010struct exclude_list_group *group;1011struct exclude_list *el;1012struct exclude_stack *stk = NULL;1013struct untracked_cache_dir *untracked;1014int current;10151016 group = &dir->exclude_list_group[EXC_DIRS];10171018/*1019 * Pop the exclude lists from the EXCL_DIRS exclude_list_group1020 * which originate from directories not in the prefix of the1021 * path being checked.1022 */1023while((stk = dir->exclude_stack) != NULL) {1024if(stk->baselen <= baselen &&1025!strncmp(dir->basebuf.buf, base, stk->baselen))1026break;1027 el = &group->el[dir->exclude_stack->exclude_ix];1028 dir->exclude_stack = stk->prev;1029 dir->exclude = NULL;1030free((char*)el->src);/* see strbuf_detach() below */1031clear_exclude_list(el);1032free(stk);1033 group->nr--;1034}10351036/* Skip traversing into sub directories if the parent is excluded */1037if(dir->exclude)1038return;10391040/*1041 * Lazy initialization. All call sites currently just1042 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1043 * them seems lots of work for little benefit.1044 */1045if(!dir->basebuf.buf)1046strbuf_init(&dir->basebuf, PATH_MAX);10471048/* Read from the parent directories and push them down. */1049 current = stk ? stk->baselen : -1;1050strbuf_setlen(&dir->basebuf, current <0?0: current);1051if(dir->untracked)1052 untracked = stk ? stk->ucd : dir->untracked->root;1053else1054 untracked = NULL;10551056while(current < baselen) {1057const char*cp;1058struct sha1_stat sha1_stat;10591060 stk =xcalloc(1,sizeof(*stk));1061if(current <0) {1062 cp = base;1063 current =0;1064}else{1065 cp =strchr(base + current +1,'/');1066if(!cp)1067die("oops in prep_exclude");1068 cp++;1069 untracked =1070lookup_untracked(dir->untracked, untracked,1071 base + current,1072 cp - base - current);1073}1074 stk->prev = dir->exclude_stack;1075 stk->baselen = cp - base;1076 stk->exclude_ix = group->nr;1077 stk->ucd = untracked;1078 el =add_exclude_list(dir, EXC_DIRS, NULL);1079strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1080assert(stk->baselen == dir->basebuf.len);10811082/* Abort if the directory is excluded */1083if(stk->baselen) {1084int dt = DT_DIR;1085 dir->basebuf.buf[stk->baselen -1] =0;1086 dir->exclude =last_exclude_matching_from_lists(dir,1087 dir->basebuf.buf, stk->baselen -1,1088 dir->basebuf.buf + current, &dt);1089 dir->basebuf.buf[stk->baselen -1] ='/';1090if(dir->exclude &&1091 dir->exclude->flags & EXC_FLAG_NEGATIVE)1092 dir->exclude = NULL;1093if(dir->exclude) {1094 dir->exclude_stack = stk;1095return;1096}1097}10981099/* Try to read per-directory file */1100hashclr(sha1_stat.sha1);1101 sha1_stat.valid =0;1102if(dir->exclude_per_dir &&1103/*1104 * If we know that no files have been added in1105 * this directory (i.e. valid_cached_dir() has1106 * been executed and set untracked->valid) ..1107 */1108(!untracked || !untracked->valid ||1109/*1110 * .. and .gitignore does not exist before1111 * (i.e. null exclude_sha1). Then we can skip1112 * loading .gitignore, which would result in1113 * ENOENT anyway.1114 */1115!is_null_sha1(untracked->exclude_sha1))) {1116/*1117 * dir->basebuf gets reused by the traversal, but we1118 * need fname to remain unchanged to ensure the src1119 * member of each struct exclude correctly1120 * back-references its source file. Other invocations1121 * of add_exclude_list provide stable strings, so we1122 * strbuf_detach() and free() here in the caller.1123 */1124struct strbuf sb = STRBUF_INIT;1125strbuf_addbuf(&sb, &dir->basebuf);1126strbuf_addstr(&sb, dir->exclude_per_dir);1127 el->src =strbuf_detach(&sb, NULL);1128add_excludes(el->src, el->src, stk->baselen, el,1,1129 untracked ? &sha1_stat : NULL);1130}1131/*1132 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1133 * will first be called in valid_cached_dir() then maybe many1134 * times more in last_exclude_matching(). When the cache is1135 * used, last_exclude_matching() will not be called and1136 * reading .gitignore content will be a waste.1137 *1138 * So when it's called by valid_cached_dir() and we can get1139 * .gitignore SHA-1 from the index (i.e. .gitignore is not1140 * modified on work tree), we could delay reading the1141 * .gitignore content until we absolutely need it in1142 * last_exclude_matching(). Be careful about ignore rule1143 * order, though, if you do that.1144 */1145if(untracked &&1146hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1147invalidate_gitignore(dir->untracked, untracked);1148hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1149}1150 dir->exclude_stack = stk;1151 current = stk->baselen;1152}1153strbuf_setlen(&dir->basebuf, baselen);1154}11551156/*1157 * Loads the exclude lists for the directory containing pathname, then1158 * scans all exclude lists to determine whether pathname is excluded.1159 * Returns the exclude_list element which matched, or NULL for1160 * undecided.1161 */1162struct exclude *last_exclude_matching(struct dir_struct *dir,1163const char*pathname,1164int*dtype_p)1165{1166int pathlen =strlen(pathname);1167const char*basename =strrchr(pathname,'/');1168 basename = (basename) ? basename+1: pathname;11691170prep_exclude(dir, pathname, basename-pathname);11711172if(dir->exclude)1173return dir->exclude;11741175returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1176 basename, dtype_p);1177}11781179/*1180 * Loads the exclude lists for the directory containing pathname, then1181 * scans all exclude lists to determine whether pathname is excluded.1182 * Returns 1 if true, otherwise 0.1183 */1184intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1185{1186struct exclude *exclude =1187last_exclude_matching(dir, pathname, dtype_p);1188if(exclude)1189return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1190return0;1191}11921193static struct dir_entry *dir_entry_new(const char*pathname,int len)1194{1195struct dir_entry *ent;11961197FLEX_ALLOC_MEM(ent, name, pathname, len);1198 ent->len = len;1199return ent;1200}12011202static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1203{1204if(cache_file_exists(pathname, len, ignore_case))1205return NULL;12061207ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1208return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1209}12101211struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1212{1213if(!cache_name_is_other(pathname, len))1214return NULL;12151216ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1217return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1218}12191220enum exist_status {1221 index_nonexistent =0,1222 index_directory,1223 index_gitdir1224};12251226/*1227 * Do not use the alphabetically sorted index to look up1228 * the directory name; instead, use the case insensitive1229 * directory hash.1230 */1231static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1232{1233struct cache_entry *ce;12341235if(cache_dir_exists(dirname, len))1236return index_directory;12371238 ce =cache_file_exists(dirname, len, ignore_case);1239if(ce &&S_ISGITLINK(ce->ce_mode))1240return index_gitdir;12411242return index_nonexistent;1243}12441245/*1246 * The index sorts alphabetically by entry name, which1247 * means that a gitlink sorts as '\0' at the end, while1248 * a directory (which is defined not as an entry, but as1249 * the files it contains) will sort with the '/' at the1250 * end.1251 */1252static enum exist_status directory_exists_in_index(const char*dirname,int len)1253{1254int pos;12551256if(ignore_case)1257returndirectory_exists_in_index_icase(dirname, len);12581259 pos =cache_name_pos(dirname, len);1260if(pos <0)1261 pos = -pos-1;1262while(pos < active_nr) {1263const struct cache_entry *ce = active_cache[pos++];1264unsigned char endchar;12651266if(strncmp(ce->name, dirname, len))1267break;1268 endchar = ce->name[len];1269if(endchar >'/')1270break;1271if(endchar =='/')1272return index_directory;1273if(!endchar &&S_ISGITLINK(ce->ce_mode))1274return index_gitdir;1275}1276return index_nonexistent;1277}12781279/*1280 * When we find a directory when traversing the filesystem, we1281 * have three distinct cases:1282 *1283 * - ignore it1284 * - see it as a directory1285 * - recurse into it1286 *1287 * and which one we choose depends on a combination of existing1288 * git index contents and the flags passed into the directory1289 * traversal routine.1290 *1291 * Case 1: If we *already* have entries in the index under that1292 * directory name, we always recurse into the directory to see1293 * all the files.1294 *1295 * Case 2: If we *already* have that directory name as a gitlink,1296 * we always continue to see it as a gitlink, regardless of whether1297 * there is an actual git directory there or not (it might not1298 * be checked out as a subproject!)1299 *1300 * Case 3: if we didn't have it in the index previously, we1301 * have a few sub-cases:1302 *1303 * (a) if "show_other_directories" is true, we show it as1304 * just a directory, unless "hide_empty_directories" is1305 * also true, in which case we need to check if it contains any1306 * untracked and / or ignored files.1307 * (b) if it looks like a git directory, and we don't have1308 * 'no_gitlinks' set we treat it as a gitlink, and show it1309 * as a directory.1310 * (c) otherwise, we recurse into it.1311 */1312static enum path_treatment treat_directory(struct dir_struct *dir,1313struct untracked_cache_dir *untracked,1314const char*dirname,int len,int baselen,int exclude,1315const struct path_simplify *simplify)1316{1317/* The "len-1" is to strip the final '/' */1318switch(directory_exists_in_index(dirname, len-1)) {1319case index_directory:1320return path_recurse;13211322case index_gitdir:1323return path_none;13241325case index_nonexistent:1326if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1327break;1328if(!(dir->flags & DIR_NO_GITLINKS)) {1329unsigned char sha1[20];1330if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1331return path_untracked;1332}1333return path_recurse;1334}13351336/* This is the "show_other_directories" case */13371338if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1339return exclude ? path_excluded : path_untracked;13401341 untracked =lookup_untracked(dir->untracked, untracked,1342 dirname + baselen, len - baselen);1343returnread_directory_recursive(dir, dirname, len,1344 untracked,1, simplify);1345}13461347/*1348 * This is an inexact early pruning of any recursive directory1349 * reading - if the path cannot possibly be in the pathspec,1350 * return true, and we'll skip it early.1351 */1352static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1353{1354if(simplify) {1355for(;;) {1356const char*match = simplify->path;1357int len = simplify->len;13581359if(!match)1360break;1361if(len > pathlen)1362 len = pathlen;1363if(!memcmp(path, match, len))1364return0;1365 simplify++;1366}1367return1;1368}1369return0;1370}13711372/*1373 * This function tells us whether an excluded path matches a1374 * list of "interesting" pathspecs. That is, whether a path matched1375 * by any of the pathspecs could possibly be ignored by excluding1376 * the specified path. This can happen if:1377 *1378 * 1. the path is mentioned explicitly in the pathspec1379 *1380 * 2. the path is a directory prefix of some element in the1381 * pathspec1382 */1383static intexclude_matches_pathspec(const char*path,int len,1384const struct path_simplify *simplify)1385{1386if(simplify) {1387for(; simplify->path; simplify++) {1388if(len == simplify->len1389&& !memcmp(path, simplify->path, len))1390return1;1391if(len < simplify->len1392&& simplify->path[len] =='/'1393&& !memcmp(path, simplify->path, len))1394return1;1395}1396}1397return0;1398}13991400static intget_index_dtype(const char*path,int len)1401{1402int pos;1403const struct cache_entry *ce;14041405 ce =cache_file_exists(path, len,0);1406if(ce) {1407if(!ce_uptodate(ce))1408return DT_UNKNOWN;1409if(S_ISGITLINK(ce->ce_mode))1410return DT_DIR;1411/*1412 * Nobody actually cares about the1413 * difference between DT_LNK and DT_REG1414 */1415return DT_REG;1416}14171418/* Try to look it up as a directory */1419 pos =cache_name_pos(path, len);1420if(pos >=0)1421return DT_UNKNOWN;1422 pos = -pos-1;1423while(pos < active_nr) {1424 ce = active_cache[pos++];1425if(strncmp(ce->name, path, len))1426break;1427if(ce->name[len] >'/')1428break;1429if(ce->name[len] <'/')1430continue;1431if(!ce_uptodate(ce))1432break;/* continue? */1433return DT_DIR;1434}1435return DT_UNKNOWN;1436}14371438static intget_dtype(struct dirent *de,const char*path,int len)1439{1440int dtype = de ?DTYPE(de) : DT_UNKNOWN;1441struct stat st;14421443if(dtype != DT_UNKNOWN)1444return dtype;1445 dtype =get_index_dtype(path, len);1446if(dtype != DT_UNKNOWN)1447return dtype;1448if(lstat(path, &st))1449return dtype;1450if(S_ISREG(st.st_mode))1451return DT_REG;1452if(S_ISDIR(st.st_mode))1453return DT_DIR;1454if(S_ISLNK(st.st_mode))1455return DT_LNK;1456return dtype;1457}14581459static enum path_treatment treat_one_path(struct dir_struct *dir,1460struct untracked_cache_dir *untracked,1461struct strbuf *path,1462int baselen,1463const struct path_simplify *simplify,1464int dtype,struct dirent *de)1465{1466int exclude;1467int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);14681469if(dtype == DT_UNKNOWN)1470 dtype =get_dtype(de, path->buf, path->len);14711472/* Always exclude indexed files */1473if(dtype != DT_DIR && has_path_in_index)1474return path_none;14751476/*1477 * When we are looking at a directory P in the working tree,1478 * there are three cases:1479 *1480 * (1) P exists in the index. Everything inside the directory P in1481 * the working tree needs to go when P is checked out from the1482 * index.1483 *1484 * (2) P does not exist in the index, but there is P/Q in the index.1485 * We know P will stay a directory when we check out the contents1486 * of the index, but we do not know yet if there is a directory1487 * P/Q in the working tree to be killed, so we need to recurse.1488 *1489 * (3) P does not exist in the index, and there is no P/Q in the index1490 * to require P to be a directory, either. Only in this case, we1491 * know that everything inside P will not be killed without1492 * recursing.1493 */1494if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1495(dtype == DT_DIR) &&1496!has_path_in_index &&1497(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1498return path_none;14991500 exclude =is_excluded(dir, path->buf, &dtype);15011502/*1503 * Excluded? If we don't explicitly want to show1504 * ignored files, ignore it1505 */1506if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1507return path_excluded;15081509switch(dtype) {1510default:1511return path_none;1512case DT_DIR:1513strbuf_addch(path,'/');1514returntreat_directory(dir, untracked, path->buf, path->len,1515 baselen, exclude, simplify);1516case DT_REG:1517case DT_LNK:1518return exclude ? path_excluded : path_untracked;1519}1520}15211522static enum path_treatment treat_path_fast(struct dir_struct *dir,1523struct untracked_cache_dir *untracked,1524struct cached_dir *cdir,1525struct strbuf *path,1526int baselen,1527const struct path_simplify *simplify)1528{1529strbuf_setlen(path, baselen);1530if(!cdir->ucd) {1531strbuf_addstr(path, cdir->file);1532return path_untracked;1533}1534strbuf_addstr(path, cdir->ucd->name);1535/* treat_one_path() does this before it calls treat_directory() */1536strbuf_complete(path,'/');1537if(cdir->ucd->check_only)1538/*1539 * check_only is set as a result of treat_directory() getting1540 * to its bottom. Verify again the same set of directories1541 * with check_only set.1542 */1543returnread_directory_recursive(dir, path->buf, path->len,1544 cdir->ucd,1, simplify);1545/*1546 * We get path_recurse in the first run when1547 * directory_exists_in_index() returns index_nonexistent. We1548 * are sure that new changes in the index does not impact the1549 * outcome. Return now.1550 */1551return path_recurse;1552}15531554static enum path_treatment treat_path(struct dir_struct *dir,1555struct untracked_cache_dir *untracked,1556struct cached_dir *cdir,1557struct strbuf *path,1558int baselen,1559const struct path_simplify *simplify)1560{1561int dtype;1562struct dirent *de = cdir->de;15631564if(!de)1565returntreat_path_fast(dir, untracked, cdir, path,1566 baselen, simplify);1567if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1568return path_none;1569strbuf_setlen(path, baselen);1570strbuf_addstr(path, de->d_name);1571if(simplify_away(path->buf, path->len, simplify))1572return path_none;15731574 dtype =DTYPE(de);1575returntreat_one_path(dir, untracked, path, baselen, simplify, dtype, de);1576}15771578static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1579{1580if(!dir)1581return;1582ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1583 dir->untracked_alloc);1584 dir->untracked[dir->untracked_nr++] =xstrdup(name);1585}15861587static intvalid_cached_dir(struct dir_struct *dir,1588struct untracked_cache_dir *untracked,1589struct strbuf *path,1590int check_only)1591{1592struct stat st;15931594if(!untracked)1595return0;15961597if(stat(path->len ? path->buf :".", &st)) {1598invalidate_directory(dir->untracked, untracked);1599memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1600return0;1601}1602if(!untracked->valid ||1603match_stat_data_racy(&the_index, &untracked->stat_data, &st)) {1604if(untracked->valid)1605invalidate_directory(dir->untracked, untracked);1606fill_stat_data(&untracked->stat_data, &st);1607return0;1608}16091610if(untracked->check_only != !!check_only) {1611invalidate_directory(dir->untracked, untracked);1612return0;1613}16141615/*1616 * prep_exclude will be called eventually on this directory,1617 * but it's called much later in last_exclude_matching(). We1618 * need it now to determine the validity of the cache for this1619 * path. The next calls will be nearly no-op, the way1620 * prep_exclude() is designed.1621 */1622if(path->len && path->buf[path->len -1] !='/') {1623strbuf_addch(path,'/');1624prep_exclude(dir, path->buf, path->len);1625strbuf_setlen(path, path->len -1);1626}else1627prep_exclude(dir, path->buf, path->len);16281629/* hopefully prep_exclude() haven't invalidated this entry... */1630return untracked->valid;1631}16321633static intopen_cached_dir(struct cached_dir *cdir,1634struct dir_struct *dir,1635struct untracked_cache_dir *untracked,1636struct strbuf *path,1637int check_only)1638{1639memset(cdir,0,sizeof(*cdir));1640 cdir->untracked = untracked;1641if(valid_cached_dir(dir, untracked, path, check_only))1642return0;1643 cdir->fdir =opendir(path->len ? path->buf :".");1644if(dir->untracked)1645 dir->untracked->dir_opened++;1646if(!cdir->fdir)1647return-1;1648return0;1649}16501651static intread_cached_dir(struct cached_dir *cdir)1652{1653if(cdir->fdir) {1654 cdir->de =readdir(cdir->fdir);1655if(!cdir->de)1656return-1;1657return0;1658}1659while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1660struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1661if(!d->recurse) {1662 cdir->nr_dirs++;1663continue;1664}1665 cdir->ucd = d;1666 cdir->nr_dirs++;1667return0;1668}1669 cdir->ucd = NULL;1670if(cdir->nr_files < cdir->untracked->untracked_nr) {1671struct untracked_cache_dir *d = cdir->untracked;1672 cdir->file = d->untracked[cdir->nr_files++];1673return0;1674}1675return-1;1676}16771678static voidclose_cached_dir(struct cached_dir *cdir)1679{1680if(cdir->fdir)1681closedir(cdir->fdir);1682/*1683 * We have gone through this directory and found no untracked1684 * entries. Mark it valid.1685 */1686if(cdir->untracked) {1687 cdir->untracked->valid =1;1688 cdir->untracked->recurse =1;1689}1690}16911692/*1693 * Read a directory tree. We currently ignore anything but1694 * directories, regular files and symlinks. That's because git1695 * doesn't handle them at all yet. Maybe that will change some1696 * day.1697 *1698 * Also, we ignore the name ".git" (even if it is not a directory).1699 * That likely will not change.1700 *1701 * Returns the most significant path_treatment value encountered in the scan.1702 */1703static enum path_treatment read_directory_recursive(struct dir_struct *dir,1704const char*base,int baselen,1705struct untracked_cache_dir *untracked,int check_only,1706const struct path_simplify *simplify)1707{1708struct cached_dir cdir;1709enum path_treatment state, subdir_state, dir_state = path_none;1710struct strbuf path = STRBUF_INIT;17111712strbuf_add(&path, base, baselen);17131714if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1715goto out;17161717if(untracked)1718 untracked->check_only = !!check_only;17191720while(!read_cached_dir(&cdir)) {1721/* check how the file or directory should be treated */1722 state =treat_path(dir, untracked, &cdir, &path, baselen, simplify);17231724if(state > dir_state)1725 dir_state = state;17261727/* recurse into subdir if instructed by treat_path */1728if(state == path_recurse) {1729struct untracked_cache_dir *ud;1730 ud =lookup_untracked(dir->untracked, untracked,1731 path.buf + baselen,1732 path.len - baselen);1733 subdir_state =1734read_directory_recursive(dir, path.buf, path.len,1735 ud, check_only, simplify);1736if(subdir_state > dir_state)1737 dir_state = subdir_state;1738}17391740if(check_only) {1741/* abort early if maximum state has been reached */1742if(dir_state == path_untracked) {1743if(cdir.fdir)1744add_untracked(untracked, path.buf + baselen);1745break;1746}1747/* skip the dir_add_* part */1748continue;1749}17501751/* add the path to the appropriate result list */1752switch(state) {1753case path_excluded:1754if(dir->flags & DIR_SHOW_IGNORED)1755dir_add_name(dir, path.buf, path.len);1756else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1757((dir->flags & DIR_COLLECT_IGNORED) &&1758exclude_matches_pathspec(path.buf, path.len,1759 simplify)))1760dir_add_ignored(dir, path.buf, path.len);1761break;17621763case path_untracked:1764if(dir->flags & DIR_SHOW_IGNORED)1765break;1766dir_add_name(dir, path.buf, path.len);1767if(cdir.fdir)1768add_untracked(untracked, path.buf + baselen);1769break;17701771default:1772break;1773}1774}1775close_cached_dir(&cdir);1776 out:1777strbuf_release(&path);17781779return dir_state;1780}17811782static intcmp_name(const void*p1,const void*p2)1783{1784const struct dir_entry *e1 = *(const struct dir_entry **)p1;1785const struct dir_entry *e2 = *(const struct dir_entry **)p2;17861787returnname_compare(e1->name, e1->len, e2->name, e2->len);1788}17891790static struct path_simplify *create_simplify(const char**pathspec)1791{1792int nr, alloc =0;1793struct path_simplify *simplify = NULL;17941795if(!pathspec)1796return NULL;17971798for(nr =0; ; nr++) {1799const char*match;1800ALLOC_GROW(simplify, nr +1, alloc);1801 match = *pathspec++;1802if(!match)1803break;1804 simplify[nr].path = match;1805 simplify[nr].len =simple_length(match);1806}1807 simplify[nr].path = NULL;1808 simplify[nr].len =0;1809return simplify;1810}18111812static voidfree_simplify(struct path_simplify *simplify)1813{1814free(simplify);1815}18161817static inttreat_leading_path(struct dir_struct *dir,1818const char*path,int len,1819const struct path_simplify *simplify)1820{1821struct strbuf sb = STRBUF_INIT;1822int baselen, rc =0;1823const char*cp;1824int old_flags = dir->flags;18251826while(len && path[len -1] =='/')1827 len--;1828if(!len)1829return1;1830 baselen =0;1831 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1832while(1) {1833 cp = path + baselen + !!baselen;1834 cp =memchr(cp,'/', path + len - cp);1835if(!cp)1836 baselen = len;1837else1838 baselen = cp - path;1839strbuf_setlen(&sb,0);1840strbuf_add(&sb, path, baselen);1841if(!is_directory(sb.buf))1842break;1843if(simplify_away(sb.buf, sb.len, simplify))1844break;1845if(treat_one_path(dir, NULL, &sb, baselen, simplify,1846 DT_DIR, NULL) == path_none)1847break;/* do not recurse into it */1848if(len <= baselen) {1849 rc =1;1850break;/* finished checking */1851}1852}1853strbuf_release(&sb);1854 dir->flags = old_flags;1855return rc;1856}18571858static const char*get_ident_string(void)1859{1860static struct strbuf sb = STRBUF_INIT;1861struct utsname uts;18621863if(sb.len)1864return sb.buf;1865if(uname(&uts) <0)1866die_errno(_("failed to get kernel name and information"));1867strbuf_addf(&sb,"Location%s, system%s",get_git_work_tree(),1868 uts.sysname);1869return sb.buf;1870}18711872static intident_in_untracked(const struct untracked_cache *uc)1873{1874/*1875 * Previous git versions may have saved many NUL separated1876 * strings in the "ident" field, but it is insane to manage1877 * many locations, so just take care of the first one.1878 */18791880return!strcmp(uc->ident.buf,get_ident_string());1881}18821883static voidset_untracked_ident(struct untracked_cache *uc)1884{1885strbuf_reset(&uc->ident);1886strbuf_addstr(&uc->ident,get_ident_string());18871888/*1889 * This strbuf used to contain a list of NUL separated1890 * strings, so save NUL too for backward compatibility.1891 */1892strbuf_addch(&uc->ident,0);1893}18941895static voidnew_untracked_cache(struct index_state *istate)1896{1897struct untracked_cache *uc =xcalloc(1,sizeof(*uc));1898strbuf_init(&uc->ident,100);1899 uc->exclude_per_dir =".gitignore";1900/* should be the same flags used by git-status */1901 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;1902set_untracked_ident(uc);1903 istate->untracked = uc;1904 istate->cache_changed |= UNTRACKED_CHANGED;1905}19061907voidadd_untracked_cache(struct index_state *istate)1908{1909if(!istate->untracked) {1910new_untracked_cache(istate);1911}else{1912if(!ident_in_untracked(istate->untracked)) {1913free_untracked_cache(istate->untracked);1914new_untracked_cache(istate);1915}1916}1917}19181919voidremove_untracked_cache(struct index_state *istate)1920{1921if(istate->untracked) {1922free_untracked_cache(istate->untracked);1923 istate->untracked = NULL;1924 istate->cache_changed |= UNTRACKED_CHANGED;1925}1926}19271928static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1929int base_len,1930const struct pathspec *pathspec)1931{1932struct untracked_cache_dir *root;19331934if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))1935return NULL;19361937/*1938 * We only support $GIT_DIR/info/exclude and core.excludesfile1939 * as the global ignore rule files. Any other additions1940 * (e.g. from command line) invalidate the cache. This1941 * condition also catches running setup_standard_excludes()1942 * before setting dir->untracked!1943 */1944if(dir->unmanaged_exclude_files)1945return NULL;19461947/*1948 * Optimize for the main use case only: whole-tree git1949 * status. More work involved in treat_leading_path() if we1950 * use cache on just a subset of the worktree. pathspec1951 * support could make the matter even worse.1952 */1953if(base_len || (pathspec && pathspec->nr))1954return NULL;19551956/* Different set of flags may produce different results */1957if(dir->flags != dir->untracked->dir_flags ||1958/*1959 * See treat_directory(), case index_nonexistent. Without1960 * this flag, we may need to also cache .git file content1961 * for the resolve_gitlink_ref() call, which we don't.1962 */1963!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1964/* We don't support collecting ignore files */1965(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1966 DIR_COLLECT_IGNORED)))1967return NULL;19681969/*1970 * If we use .gitignore in the cache and now you change it to1971 * .gitexclude, everything will go wrong.1972 */1973if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1974strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1975return NULL;19761977/*1978 * EXC_CMDL is not considered in the cache. If people set it,1979 * skip the cache.1980 */1981if(dir->exclude_list_group[EXC_CMDL].nr)1982return NULL;19831984if(!ident_in_untracked(dir->untracked)) {1985warning(_("Untracked cache is disabled on this system or location."));1986return NULL;1987}19881989if(!dir->untracked->root) {1990const int len =sizeof(*dir->untracked->root);1991 dir->untracked->root =xmalloc(len);1992memset(dir->untracked->root,0, len);1993}19941995/* Validate $GIT_DIR/info/exclude and core.excludesfile */1996 root = dir->untracked->root;1997if(hashcmp(dir->ss_info_exclude.sha1,1998 dir->untracked->ss_info_exclude.sha1)) {1999invalidate_gitignore(dir->untracked, root);2000 dir->untracked->ss_info_exclude = dir->ss_info_exclude;2001}2002if(hashcmp(dir->ss_excludes_file.sha1,2003 dir->untracked->ss_excludes_file.sha1)) {2004invalidate_gitignore(dir->untracked, root);2005 dir->untracked->ss_excludes_file = dir->ss_excludes_file;2006}20072008/* Make sure this directory is not dropped out at saving phase */2009 root->recurse =1;2010return root;2011}20122013intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)2014{2015struct path_simplify *simplify;2016struct untracked_cache_dir *untracked;20172018/*2019 * Check out create_simplify()2020 */2021if(pathspec)2022GUARD_PATHSPEC(pathspec,2023 PATHSPEC_FROMTOP |2024 PATHSPEC_MAXDEPTH |2025 PATHSPEC_LITERAL |2026 PATHSPEC_GLOB |2027 PATHSPEC_ICASE |2028 PATHSPEC_EXCLUDE);20292030if(has_symlink_leading_path(path, len))2031return dir->nr;20322033/*2034 * exclude patterns are treated like positive ones in2035 * create_simplify. Usually exclude patterns should be a2036 * subset of positive ones, which has no impacts on2037 * create_simplify().2038 */2039 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);2040 untracked =validate_untracked_cache(dir, len, pathspec);2041if(!untracked)2042/*2043 * make sure untracked cache code path is disabled,2044 * e.g. prep_exclude()2045 */2046 dir->untracked = NULL;2047if(!len ||treat_leading_path(dir, path, len, simplify))2048read_directory_recursive(dir, path, len, untracked,0, simplify);2049free_simplify(simplify);2050QSORT(dir->entries, dir->nr, cmp_name);2051QSORT(dir->ignored, dir->ignored_nr, cmp_name);2052if(dir->untracked) {2053static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);2054trace_printf_key(&trace_untracked_stats,2055"node creation:%u\n"2056"gitignore invalidation:%u\n"2057"directory invalidation:%u\n"2058"opendir:%u\n",2059 dir->untracked->dir_created,2060 dir->untracked->gitignore_invalidated,2061 dir->untracked->dir_invalidated,2062 dir->untracked->dir_opened);2063if(dir->untracked == the_index.untracked &&2064(dir->untracked->dir_opened ||2065 dir->untracked->gitignore_invalidated ||2066 dir->untracked->dir_invalidated))2067 the_index.cache_changed |= UNTRACKED_CHANGED;2068if(dir->untracked != the_index.untracked) {2069free(dir->untracked);2070 dir->untracked = NULL;2071}2072}2073return dir->nr;2074}20752076intfile_exists(const char*f)2077{2078struct stat sb;2079returnlstat(f, &sb) ==0;2080}20812082static intcmp_icase(char a,char b)2083{2084if(a == b)2085return0;2086if(ignore_case)2087returntoupper(a) -toupper(b);2088return a - b;2089}20902091/*2092 * Given two normalized paths (a trailing slash is ok), if subdir is2093 * outside dir, return -1. Otherwise return the offset in subdir that2094 * can be used as relative path to dir.2095 */2096intdir_inside_of(const char*subdir,const char*dir)2097{2098int offset =0;20992100assert(dir && subdir && *dir && *subdir);21012102while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2103 dir++;2104 subdir++;2105 offset++;2106}21072108/* hel[p]/me vs hel[l]/yeah */2109if(*dir && *subdir)2110return-1;21112112if(!*subdir)2113return!*dir ? offset : -1;/* same dir */21142115/* foo/[b]ar vs foo/[] */2116if(is_dir_sep(dir[-1]))2117returnis_dir_sep(subdir[-1]) ? offset : -1;21182119/* foo[/]bar vs foo[] */2120returnis_dir_sep(*subdir) ? offset +1: -1;2121}21222123intis_inside_dir(const char*dir)2124{2125char*cwd;2126int rc;21272128if(!dir)2129return0;21302131 cwd =xgetcwd();2132 rc = (dir_inside_of(cwd, dir) >=0);2133free(cwd);2134return rc;2135}21362137intis_empty_dir(const char*path)2138{2139DIR*dir =opendir(path);2140struct dirent *e;2141int ret =1;21422143if(!dir)2144return0;21452146while((e =readdir(dir)) != NULL)2147if(!is_dot_or_dotdot(e->d_name)) {2148 ret =0;2149break;2150}21512152closedir(dir);2153return ret;2154}21552156static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2157{2158DIR*dir;2159struct dirent *e;2160int ret =0, original_len = path->len, len, kept_down =0;2161int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2162int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2163unsigned char submodule_head[20];21642165if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2166!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2167/* Do not descend and nuke a nested git work tree. */2168if(kept_up)2169*kept_up =1;2170return0;2171}21722173 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2174 dir =opendir(path->buf);2175if(!dir) {2176if(errno == ENOENT)2177return keep_toplevel ? -1:0;2178else if(errno == EACCES && !keep_toplevel)2179/*2180 * An empty dir could be removable even if it2181 * is unreadable:2182 */2183returnrmdir(path->buf);2184else2185return-1;2186}2187strbuf_complete(path,'/');21882189 len = path->len;2190while((e =readdir(dir)) != NULL) {2191struct stat st;2192if(is_dot_or_dotdot(e->d_name))2193continue;21942195strbuf_setlen(path, len);2196strbuf_addstr(path, e->d_name);2197if(lstat(path->buf, &st)) {2198if(errno == ENOENT)2199/*2200 * file disappeared, which is what we2201 * wanted anyway2202 */2203continue;2204/* fall thru */2205}else if(S_ISDIR(st.st_mode)) {2206if(!remove_dir_recurse(path, flag, &kept_down))2207continue;/* happy */2208}else if(!only_empty &&2209(!unlink(path->buf) || errno == ENOENT)) {2210continue;/* happy, too */2211}22122213/* path too long, stat fails, or non-directory still exists */2214 ret = -1;2215break;2216}2217closedir(dir);22182219strbuf_setlen(path, original_len);2220if(!ret && !keep_toplevel && !kept_down)2221 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2222else if(kept_up)2223/*2224 * report the uplevel that it is not an error that we2225 * did not rmdir() our directory.2226 */2227*kept_up = !ret;2228return ret;2229}22302231intremove_dir_recursively(struct strbuf *path,int flag)2232{2233returnremove_dir_recurse(path, flag, NULL);2234}22352236staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")22372238voidsetup_standard_excludes(struct dir_struct *dir)2239{2240 dir->exclude_per_dir =".gitignore";22412242/* core.excludefile defaulting to $XDG_HOME/git/ignore */2243if(!excludes_file)2244 excludes_file =xdg_config_home("ignore");2245if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2246add_excludes_from_file_1(dir, excludes_file,2247 dir->untracked ? &dir->ss_excludes_file : NULL);22482249/* per repository user preference */2250if(startup_info->have_repository) {2251const char*path =git_path_info_exclude();2252if(!access_or_warn(path, R_OK,0))2253add_excludes_from_file_1(dir, path,2254 dir->untracked ? &dir->ss_info_exclude : NULL);2255}2256}22572258intremove_path(const char*name)2259{2260char*slash;22612262if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2263return-1;22642265 slash =strrchr(name,'/');2266if(slash) {2267char*dirs =xstrdup(name);2268 slash = dirs + (slash - name);2269do{2270*slash ='\0';2271}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2272free(dirs);2273}2274return0;2275}22762277/*2278 * Frees memory within dir which was allocated for exclude lists and2279 * the exclude_stack. Does not free dir itself.2280 */2281voidclear_directory(struct dir_struct *dir)2282{2283int i, j;2284struct exclude_list_group *group;2285struct exclude_list *el;2286struct exclude_stack *stk;22872288for(i = EXC_CMDL; i <= EXC_FILE; i++) {2289 group = &dir->exclude_list_group[i];2290for(j =0; j < group->nr; j++) {2291 el = &group->el[j];2292if(i == EXC_DIRS)2293free((char*)el->src);2294clear_exclude_list(el);2295}2296free(group->el);2297}22982299 stk = dir->exclude_stack;2300while(stk) {2301struct exclude_stack *prev = stk->prev;2302free(stk);2303 stk = prev;2304}2305strbuf_release(&dir->basebuf);2306}23072308struct ondisk_untracked_cache {2309struct stat_data info_exclude_stat;2310struct stat_data excludes_file_stat;2311uint32_t dir_flags;2312unsigned char info_exclude_sha1[20];2313unsigned char excludes_file_sha1[20];2314char exclude_per_dir[FLEX_ARRAY];2315};23162317#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)23182319struct write_data {2320int index;/* number of written untracked_cache_dir */2321struct ewah_bitmap *check_only;/* from untracked_cache_dir */2322struct ewah_bitmap *valid;/* from untracked_cache_dir */2323struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2324struct strbuf out;2325struct strbuf sb_stat;2326struct strbuf sb_sha1;2327};23282329static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2330{2331 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2332 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2333 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2334 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2335 to->sd_dev =htonl(from->sd_dev);2336 to->sd_ino =htonl(from->sd_ino);2337 to->sd_uid =htonl(from->sd_uid);2338 to->sd_gid =htonl(from->sd_gid);2339 to->sd_size =htonl(from->sd_size);2340}23412342static voidwrite_one_dir(struct untracked_cache_dir *untracked,2343struct write_data *wd)2344{2345struct stat_data stat_data;2346struct strbuf *out = &wd->out;2347unsigned char intbuf[16];2348unsigned int intlen, value;2349int i = wd->index++;23502351/*2352 * untracked_nr should be reset whenever valid is clear, but2353 * for safety..2354 */2355if(!untracked->valid) {2356 untracked->untracked_nr =0;2357 untracked->check_only =0;2358}23592360if(untracked->check_only)2361ewah_set(wd->check_only, i);2362if(untracked->valid) {2363ewah_set(wd->valid, i);2364stat_data_to_disk(&stat_data, &untracked->stat_data);2365strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2366}2367if(!is_null_sha1(untracked->exclude_sha1)) {2368ewah_set(wd->sha1_valid, i);2369strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2370}23712372 intlen =encode_varint(untracked->untracked_nr, intbuf);2373strbuf_add(out, intbuf, intlen);23742375/* skip non-recurse directories */2376for(i =0, value =0; i < untracked->dirs_nr; i++)2377if(untracked->dirs[i]->recurse)2378 value++;2379 intlen =encode_varint(value, intbuf);2380strbuf_add(out, intbuf, intlen);23812382strbuf_add(out, untracked->name,strlen(untracked->name) +1);23832384for(i =0; i < untracked->untracked_nr; i++)2385strbuf_add(out, untracked->untracked[i],2386strlen(untracked->untracked[i]) +1);23872388for(i =0; i < untracked->dirs_nr; i++)2389if(untracked->dirs[i]->recurse)2390write_one_dir(untracked->dirs[i], wd);2391}23922393voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2394{2395struct ondisk_untracked_cache *ouc;2396struct write_data wd;2397unsigned char varbuf[16];2398int varint_len;2399size_t len =strlen(untracked->exclude_per_dir);24002401FLEX_ALLOC_MEM(ouc, exclude_per_dir, untracked->exclude_per_dir, len);2402stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2403stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2404hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2405hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2406 ouc->dir_flags =htonl(untracked->dir_flags);24072408 varint_len =encode_varint(untracked->ident.len, varbuf);2409strbuf_add(out, varbuf, varint_len);2410strbuf_addbuf(out, &untracked->ident);24112412strbuf_add(out, ouc,ouc_size(len));2413free(ouc);2414 ouc = NULL;24152416if(!untracked->root) {2417 varint_len =encode_varint(0, varbuf);2418strbuf_add(out, varbuf, varint_len);2419return;2420}24212422 wd.index =0;2423 wd.check_only =ewah_new();2424 wd.valid =ewah_new();2425 wd.sha1_valid =ewah_new();2426strbuf_init(&wd.out,1024);2427strbuf_init(&wd.sb_stat,1024);2428strbuf_init(&wd.sb_sha1,1024);2429write_one_dir(untracked->root, &wd);24302431 varint_len =encode_varint(wd.index, varbuf);2432strbuf_add(out, varbuf, varint_len);2433strbuf_addbuf(out, &wd.out);2434ewah_serialize_strbuf(wd.valid, out);2435ewah_serialize_strbuf(wd.check_only, out);2436ewah_serialize_strbuf(wd.sha1_valid, out);2437strbuf_addbuf(out, &wd.sb_stat);2438strbuf_addbuf(out, &wd.sb_sha1);2439strbuf_addch(out,'\0');/* safe guard for string lists */24402441ewah_free(wd.valid);2442ewah_free(wd.check_only);2443ewah_free(wd.sha1_valid);2444strbuf_release(&wd.out);2445strbuf_release(&wd.sb_stat);2446strbuf_release(&wd.sb_sha1);2447}24482449static voidfree_untracked(struct untracked_cache_dir *ucd)2450{2451int i;2452if(!ucd)2453return;2454for(i =0; i < ucd->dirs_nr; i++)2455free_untracked(ucd->dirs[i]);2456for(i =0; i < ucd->untracked_nr; i++)2457free(ucd->untracked[i]);2458free(ucd->untracked);2459free(ucd->dirs);2460free(ucd);2461}24622463voidfree_untracked_cache(struct untracked_cache *uc)2464{2465if(uc)2466free_untracked(uc->root);2467free(uc);2468}24692470struct read_data {2471int index;2472struct untracked_cache_dir **ucd;2473struct ewah_bitmap *check_only;2474struct ewah_bitmap *valid;2475struct ewah_bitmap *sha1_valid;2476const unsigned char*data;2477const unsigned char*end;2478};24792480static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2481{2482 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2483 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2484 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2485 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2486 to->sd_dev =get_be32(&from->sd_dev);2487 to->sd_ino =get_be32(&from->sd_ino);2488 to->sd_uid =get_be32(&from->sd_uid);2489 to->sd_gid =get_be32(&from->sd_gid);2490 to->sd_size =get_be32(&from->sd_size);2491}24922493static intread_one_dir(struct untracked_cache_dir **untracked_,2494struct read_data *rd)2495{2496struct untracked_cache_dir ud, *untracked;2497const unsigned char*next, *data = rd->data, *end = rd->end;2498unsigned int value;2499int i, len;25002501memset(&ud,0,sizeof(ud));25022503 next = data;2504 value =decode_varint(&next);2505if(next > end)2506return-1;2507 ud.recurse =1;2508 ud.untracked_alloc = value;2509 ud.untracked_nr = value;2510if(ud.untracked_nr)2511ALLOC_ARRAY(ud.untracked, ud.untracked_nr);2512 data = next;25132514 next = data;2515 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2516if(next > end)2517return-1;2518ALLOC_ARRAY(ud.dirs, ud.dirs_nr);2519 data = next;25202521 len =strlen((const char*)data);2522 next = data + len +1;2523if(next > rd->end)2524return-1;2525*untracked_ = untracked =xmalloc(st_add(sizeof(*untracked), len));2526memcpy(untracked, &ud,sizeof(ud));2527memcpy(untracked->name, data, len +1);2528 data = next;25292530for(i =0; i < untracked->untracked_nr; i++) {2531 len =strlen((const char*)data);2532 next = data + len +1;2533if(next > rd->end)2534return-1;2535 untracked->untracked[i] =xstrdup((const char*)data);2536 data = next;2537}25382539 rd->ucd[rd->index++] = untracked;2540 rd->data = data;25412542for(i =0; i < untracked->dirs_nr; i++) {2543 len =read_one_dir(untracked->dirs + i, rd);2544if(len <0)2545return-1;2546}2547return0;2548}25492550static voidset_check_only(size_t pos,void*cb)2551{2552struct read_data *rd = cb;2553struct untracked_cache_dir *ud = rd->ucd[pos];2554 ud->check_only =1;2555}25562557static voidread_stat(size_t pos,void*cb)2558{2559struct read_data *rd = cb;2560struct untracked_cache_dir *ud = rd->ucd[pos];2561if(rd->data +sizeof(struct stat_data) > rd->end) {2562 rd->data = rd->end +1;2563return;2564}2565stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2566 rd->data +=sizeof(struct stat_data);2567 ud->valid =1;2568}25692570static voidread_sha1(size_t pos,void*cb)2571{2572struct read_data *rd = cb;2573struct untracked_cache_dir *ud = rd->ucd[pos];2574if(rd->data +20> rd->end) {2575 rd->data = rd->end +1;2576return;2577}2578hashcpy(ud->exclude_sha1, rd->data);2579 rd->data +=20;2580}25812582static voidload_sha1_stat(struct sha1_stat *sha1_stat,2583const struct stat_data *stat,2584const unsigned char*sha1)2585{2586stat_data_from_disk(&sha1_stat->stat, stat);2587hashcpy(sha1_stat->sha1, sha1);2588 sha1_stat->valid =1;2589}25902591struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2592{2593const struct ondisk_untracked_cache *ouc;2594struct untracked_cache *uc;2595struct read_data rd;2596const unsigned char*next = data, *end = (const unsigned char*)data + sz;2597const char*ident;2598int ident_len, len;25992600if(sz <=1|| end[-1] !='\0')2601return NULL;2602 end--;26032604 ident_len =decode_varint(&next);2605if(next + ident_len > end)2606return NULL;2607 ident = (const char*)next;2608 next += ident_len;26092610 ouc = (const struct ondisk_untracked_cache *)next;2611if(next +ouc_size(0) > end)2612return NULL;26132614 uc =xcalloc(1,sizeof(*uc));2615strbuf_init(&uc->ident, ident_len);2616strbuf_add(&uc->ident, ident, ident_len);2617load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2618 ouc->info_exclude_sha1);2619load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2620 ouc->excludes_file_sha1);2621 uc->dir_flags =get_be32(&ouc->dir_flags);2622 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2623/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2624 next +=ouc_size(strlen(ouc->exclude_per_dir));2625if(next >= end)2626goto done2;26272628 len =decode_varint(&next);2629if(next > end || len ==0)2630goto done2;26312632 rd.valid =ewah_new();2633 rd.check_only =ewah_new();2634 rd.sha1_valid =ewah_new();2635 rd.data = next;2636 rd.end = end;2637 rd.index =0;2638ALLOC_ARRAY(rd.ucd, len);26392640if(read_one_dir(&uc->root, &rd) || rd.index != len)2641goto done;26422643 next = rd.data;2644 len =ewah_read_mmap(rd.valid, next, end - next);2645if(len <0)2646goto done;26472648 next += len;2649 len =ewah_read_mmap(rd.check_only, next, end - next);2650if(len <0)2651goto done;26522653 next += len;2654 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2655if(len <0)2656goto done;26572658ewah_each_bit(rd.check_only, set_check_only, &rd);2659 rd.data = next + len;2660ewah_each_bit(rd.valid, read_stat, &rd);2661ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2662 next = rd.data;26632664done:2665free(rd.ucd);2666ewah_free(rd.valid);2667ewah_free(rd.check_only);2668ewah_free(rd.sha1_valid);2669done2:2670if(next != end) {2671free_untracked_cache(uc);2672 uc = NULL;2673}2674return uc;2675}26762677static voidinvalidate_one_directory(struct untracked_cache *uc,2678struct untracked_cache_dir *ucd)2679{2680 uc->dir_invalidated++;2681 ucd->valid =0;2682 ucd->untracked_nr =0;2683}26842685/*2686 * Normally when an entry is added or removed from a directory,2687 * invalidating that directory is enough. No need to touch its2688 * ancestors. When a directory is shown as "foo/bar/" in git-status2689 * however, deleting or adding an entry may have cascading effect.2690 *2691 * Say the "foo/bar/file" has become untracked, we need to tell the2692 * untracked_cache_dir of "foo" that "bar/" is not an untracked2693 * directory any more (because "bar" is managed by foo as an untracked2694 * "file").2695 *2696 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2697 * was the last untracked entry in the entire "foo", we should show2698 * "foo/" instead. Which means we have to invalidate past "bar" up to2699 * "foo".2700 *2701 * This function traverses all directories from root to leaf. If there2702 * is a chance of one of the above cases happening, we invalidate back2703 * to root. Otherwise we just invalidate the leaf. There may be a more2704 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2705 * detect these cases and avoid unnecessary invalidation, for example,2706 * checking for the untracked entry named "bar/" in "foo", but for now2707 * stick to something safe and simple.2708 */2709static intinvalidate_one_component(struct untracked_cache *uc,2710struct untracked_cache_dir *dir,2711const char*path,int len)2712{2713const char*rest =strchr(path,'/');27142715if(rest) {2716int component_len = rest - path;2717struct untracked_cache_dir *d =2718lookup_untracked(uc, dir, path, component_len);2719int ret =2720invalidate_one_component(uc, d, rest +1,2721 len - (component_len +1));2722if(ret)2723invalidate_one_directory(uc, dir);2724return ret;2725}27262727invalidate_one_directory(uc, dir);2728return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2729}27302731voiduntracked_cache_invalidate_path(struct index_state *istate,2732const char*path)2733{2734if(!istate->untracked || !istate->untracked->root)2735return;2736invalidate_one_component(istate->untracked, istate->untracked->root,2737 path,strlen(path));2738}27392740voiduntracked_cache_remove_from_index(struct index_state *istate,2741const char*path)2742{2743untracked_cache_invalidate_path(istate, path);2744}27452746voiduntracked_cache_add_to_index(struct index_state *istate,2747const char*path)2748{2749untracked_cache_invalidate_path(istate, path);2750}