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 66intfnmatch_icase(const char*pattern,const char*string,int flags) 67{ 68returnwildmatch(pattern, string, 69 flags | (ignore_case ? WM_CASEFOLD :0), 70 NULL); 71} 72 73intgit_fnmatch(const struct pathspec_item *item, 74const char*pattern,const char*string, 75int prefix) 76{ 77if(prefix >0) { 78if(ps_strncmp(item, pattern, string, prefix)) 79return WM_NOMATCH; 80 pattern += prefix; 81 string += prefix; 82} 83if(item->flags & PATHSPEC_ONESTAR) { 84int pattern_len =strlen(++pattern); 85int string_len =strlen(string); 86return string_len < pattern_len || 87ps_strcmp(item, pattern, 88 string + string_len - pattern_len); 89} 90if(item->magic & PATHSPEC_GLOB) 91returnwildmatch(pattern, string, 92 WM_PATHNAME | 93(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 94 NULL); 95else 96/* wildmatch has not learned no FNM_PATHNAME mode yet */ 97returnwildmatch(pattern, string, 98 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 99 NULL); 100} 101 102static intfnmatch_icase_mem(const char*pattern,int patternlen, 103const char*string,int stringlen, 104int flags) 105{ 106int match_status; 107struct strbuf pat_buf = STRBUF_INIT; 108struct strbuf str_buf = STRBUF_INIT; 109const char*use_pat = pattern; 110const char*use_str = string; 111 112if(pattern[patternlen]) { 113strbuf_add(&pat_buf, pattern, patternlen); 114 use_pat = pat_buf.buf; 115} 116if(string[stringlen]) { 117strbuf_add(&str_buf, string, stringlen); 118 use_str = str_buf.buf; 119} 120 121if(ignore_case) 122 flags |= WM_CASEFOLD; 123 match_status =wildmatch(use_pat, use_str, flags, NULL); 124 125strbuf_release(&pat_buf); 126strbuf_release(&str_buf); 127 128return match_status; 129} 130 131static size_tcommon_prefix_len(const struct pathspec *pathspec) 132{ 133int n; 134size_t max =0; 135 136/* 137 * ":(icase)path" is treated as a pathspec full of 138 * wildcard. In other words, only prefix is considered common 139 * prefix. If the pathspec is abc/foo abc/bar, running in 140 * subdir xyz, the common prefix is still xyz, not xuz/abc as 141 * in non-:(icase). 142 */ 143GUARD_PATHSPEC(pathspec, 144 PATHSPEC_FROMTOP | 145 PATHSPEC_MAXDEPTH | 146 PATHSPEC_LITERAL | 147 PATHSPEC_GLOB | 148 PATHSPEC_ICASE | 149 PATHSPEC_EXCLUDE); 150 151for(n =0; n < pathspec->nr; n++) { 152size_t i =0, len =0, item_len; 153if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 154continue; 155if(pathspec->items[n].magic & PATHSPEC_ICASE) 156 item_len = pathspec->items[n].prefix; 157else 158 item_len = pathspec->items[n].nowildcard_len; 159while(i < item_len && (n ==0|| i < max)) { 160char c = pathspec->items[n].match[i]; 161if(c != pathspec->items[0].match[i]) 162break; 163if(c =='/') 164 len = i +1; 165 i++; 166} 167if(n ==0|| len < max) { 168 max = len; 169if(!max) 170break; 171} 172} 173return max; 174} 175 176/* 177 * Returns a copy of the longest leading path common among all 178 * pathspecs. 179 */ 180char*common_prefix(const struct pathspec *pathspec) 181{ 182unsigned long len =common_prefix_len(pathspec); 183 184return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 185} 186 187intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 188{ 189size_t len; 190 191/* 192 * Calculate common prefix for the pathspec, and 193 * use that to optimize the directory walk 194 */ 195 len =common_prefix_len(pathspec); 196 197/* Read the directory and prune it */ 198read_directory(dir, pathspec->nr ? pathspec->_raw[0] :"", len, pathspec); 199return len; 200} 201 202intwithin_depth(const char*name,int namelen, 203int depth,int max_depth) 204{ 205const char*cp = name, *cpe = name + namelen; 206 207while(cp < cpe) { 208if(*cp++ !='/') 209continue; 210 depth++; 211if(depth > max_depth) 212return0; 213} 214return1; 215} 216 217#define DO_MATCH_EXCLUDE 1 218#define DO_MATCH_DIRECTORY 2 219 220/* 221 * Does 'match' match the given name? 222 * A match is found if 223 * 224 * (1) the 'match' string is leading directory of 'name', or 225 * (2) the 'match' string is a wildcard and matches 'name', or 226 * (3) the 'match' string is exactly the same as 'name'. 227 * 228 * and the return value tells which case it was. 229 * 230 * It returns 0 when there is no match. 231 */ 232static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 233const char*name,int namelen,unsigned flags) 234{ 235/* name/namelen has prefix cut off by caller */ 236const char*match = item->match + prefix; 237int matchlen = item->len - prefix; 238 239/* 240 * The normal call pattern is: 241 * 1. prefix = common_prefix_len(ps); 242 * 2. prune something, or fill_directory 243 * 3. match_pathspec() 244 * 245 * 'prefix' at #1 may be shorter than the command's prefix and 246 * it's ok for #2 to match extra files. Those extras will be 247 * trimmed at #3. 248 * 249 * Suppose the pathspec is 'foo' and '../bar' running from 250 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 251 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 252 * user does not want XYZ/foo, only the "foo" part should be 253 * case-insensitive. We need to filter out XYZ/foo here. In 254 * other words, we do not trust the caller on comparing the 255 * prefix part when :(icase) is involved. We do exact 256 * comparison ourselves. 257 * 258 * Normally the caller (common_prefix_len() in fact) does 259 * _exact_ matching on name[-prefix+1..-1] and we do not need 260 * to check that part. Be defensive and check it anyway, in 261 * case common_prefix_len is changed, or a new caller is 262 * introduced that does not use common_prefix_len. 263 * 264 * If the penalty turns out too high when prefix is really 265 * long, maybe change it to 266 * strncmp(match, name, item->prefix - prefix) 267 */ 268if(item->prefix && (item->magic & PATHSPEC_ICASE) && 269strncmp(item->match, name - prefix, item->prefix)) 270return0; 271 272/* If the match was just the prefix, we matched */ 273if(!*match) 274return MATCHED_RECURSIVELY; 275 276if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 277if(matchlen == namelen) 278return MATCHED_EXACTLY; 279 280if(match[matchlen-1] =='/'|| name[matchlen] =='/') 281return MATCHED_RECURSIVELY; 282}else if((flags & DO_MATCH_DIRECTORY) && 283 match[matchlen -1] =='/'&& 284 namelen == matchlen -1&& 285!ps_strncmp(item, match, name, namelen)) 286return MATCHED_EXACTLY; 287 288if(item->nowildcard_len < item->len && 289!git_fnmatch(item, match, name, 290 item->nowildcard_len - prefix)) 291return MATCHED_FNMATCH; 292 293return0; 294} 295 296/* 297 * Given a name and a list of pathspecs, returns the nature of the 298 * closest (i.e. most specific) match of the name to any of the 299 * pathspecs. 300 * 301 * The caller typically calls this multiple times with the same 302 * pathspec and seen[] array but with different name/namelen 303 * (e.g. entries from the index) and is interested in seeing if and 304 * how each pathspec matches all the names it calls this function 305 * with. A mark is left in the seen[] array for each pathspec element 306 * indicating the closest type of match that element achieved, so if 307 * seen[n] remains zero after multiple invocations, that means the nth 308 * pathspec did not match any names, which could indicate that the 309 * user mistyped the nth pathspec. 310 */ 311static intdo_match_pathspec(const struct pathspec *ps, 312const char*name,int namelen, 313int prefix,char*seen, 314unsigned flags) 315{ 316int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 317 318GUARD_PATHSPEC(ps, 319 PATHSPEC_FROMTOP | 320 PATHSPEC_MAXDEPTH | 321 PATHSPEC_LITERAL | 322 PATHSPEC_GLOB | 323 PATHSPEC_ICASE | 324 PATHSPEC_EXCLUDE); 325 326if(!ps->nr) { 327if(!ps->recursive || 328!(ps->magic & PATHSPEC_MAXDEPTH) || 329 ps->max_depth == -1) 330return MATCHED_RECURSIVELY; 331 332if(within_depth(name, namelen,0, ps->max_depth)) 333return MATCHED_EXACTLY; 334else 335return0; 336} 337 338 name += prefix; 339 namelen -= prefix; 340 341for(i = ps->nr -1; i >=0; i--) { 342int how; 343 344if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 345( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 346continue; 347 348if(seen && seen[i] == MATCHED_EXACTLY) 349continue; 350/* 351 * Make exclude patterns optional and never report 352 * "pathspec ':(exclude)foo' matches no files" 353 */ 354if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 355 seen[i] = MATCHED_FNMATCH; 356 how =match_pathspec_item(ps->items+i, prefix, name, 357 namelen, flags); 358if(ps->recursive && 359(ps->magic & PATHSPEC_MAXDEPTH) && 360 ps->max_depth != -1&& 361 how && how != MATCHED_FNMATCH) { 362int len = ps->items[i].len; 363if(name[len] =='/') 364 len++; 365if(within_depth(name+len, namelen-len,0, ps->max_depth)) 366 how = MATCHED_EXACTLY; 367else 368 how =0; 369} 370if(how) { 371if(retval < how) 372 retval = how; 373if(seen && seen[i] < how) 374 seen[i] = how; 375} 376} 377return retval; 378} 379 380intmatch_pathspec(const struct pathspec *ps, 381const char*name,int namelen, 382int prefix,char*seen,int is_dir) 383{ 384int positive, negative; 385unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 386 positive =do_match_pathspec(ps, name, namelen, 387 prefix, seen, flags); 388if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 389return positive; 390 negative =do_match_pathspec(ps, name, namelen, 391 prefix, seen, 392 flags | DO_MATCH_EXCLUDE); 393return negative ?0: positive; 394} 395 396intreport_path_error(const char*ps_matched, 397const struct pathspec *pathspec, 398const char*prefix) 399{ 400/* 401 * Make sure all pathspec matched; otherwise it is an error. 402 */ 403int num, errors =0; 404for(num =0; num < pathspec->nr; num++) { 405int other, found_dup; 406 407if(ps_matched[num]) 408continue; 409/* 410 * The caller might have fed identical pathspec 411 * twice. Do not barf on such a mistake. 412 * FIXME: parse_pathspec should have eliminated 413 * duplicate pathspec. 414 */ 415for(found_dup = other =0; 416!found_dup && other < pathspec->nr; 417 other++) { 418if(other == num || !ps_matched[other]) 419continue; 420if(!strcmp(pathspec->items[other].original, 421 pathspec->items[num].original)) 422/* 423 * Ok, we have a match already. 424 */ 425 found_dup =1; 426} 427if(found_dup) 428continue; 429 430error("pathspec '%s' did not match any file(s) known to git.", 431 pathspec->items[num].original); 432 errors++; 433} 434return errors; 435} 436 437/* 438 * Return the length of the "simple" part of a path match limiter. 439 */ 440intsimple_length(const char*match) 441{ 442int len = -1; 443 444for(;;) { 445unsigned char c = *match++; 446 len++; 447if(c =='\0'||is_glob_special(c)) 448return len; 449} 450} 451 452intno_wildcard(const char*string) 453{ 454return string[simple_length(string)] =='\0'; 455} 456 457voidparse_exclude_pattern(const char**pattern, 458int*patternlen, 459unsigned*flags, 460int*nowildcardlen) 461{ 462const char*p = *pattern; 463size_t i, len; 464 465*flags =0; 466if(*p =='!') { 467*flags |= EXC_FLAG_NEGATIVE; 468 p++; 469} 470 len =strlen(p); 471if(len && p[len -1] =='/') { 472 len--; 473*flags |= EXC_FLAG_MUSTBEDIR; 474} 475for(i =0; i < len; i++) { 476if(p[i] =='/') 477break; 478} 479if(i == len) 480*flags |= EXC_FLAG_NODIR; 481*nowildcardlen =simple_length(p); 482/* 483 * we should have excluded the trailing slash from 'p' too, 484 * but that's one more allocation. Instead just make sure 485 * nowildcardlen does not exceed real patternlen 486 */ 487if(*nowildcardlen > len) 488*nowildcardlen = len; 489if(*p =='*'&&no_wildcard(p +1)) 490*flags |= EXC_FLAG_ENDSWITH; 491*pattern = p; 492*patternlen = len; 493} 494 495voidadd_exclude(const char*string,const char*base, 496int baselen,struct exclude_list *el,int srcpos) 497{ 498struct exclude *x; 499int patternlen; 500unsigned flags; 501int nowildcardlen; 502 503parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 504if(flags & EXC_FLAG_MUSTBEDIR) { 505FLEXPTR_ALLOC_MEM(x, pattern, string, patternlen); 506}else{ 507 x =xmalloc(sizeof(*x)); 508 x->pattern = string; 509} 510 x->patternlen = patternlen; 511 x->nowildcardlen = nowildcardlen; 512 x->base = base; 513 x->baselen = baselen; 514 x->flags = flags; 515 x->srcpos = srcpos; 516ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 517 el->excludes[el->nr++] = x; 518 x->el = el; 519} 520 521static void*read_skip_worktree_file_from_index(const char*path,size_t*size, 522struct sha1_stat *sha1_stat) 523{ 524int pos, len; 525unsigned long sz; 526enum object_type type; 527void*data; 528 529 len =strlen(path); 530 pos =cache_name_pos(path, len); 531if(pos <0) 532return NULL; 533if(!ce_skip_worktree(active_cache[pos])) 534return NULL; 535 data =read_sha1_file(active_cache[pos]->sha1, &type, &sz); 536if(!data || type != OBJ_BLOB) { 537free(data); 538return NULL; 539} 540*size =xsize_t(sz); 541if(sha1_stat) { 542memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 543hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 544} 545return data; 546} 547 548/* 549 * Frees memory within el which was allocated for exclude patterns and 550 * the file buffer. Does not free el itself. 551 */ 552voidclear_exclude_list(struct exclude_list *el) 553{ 554int i; 555 556for(i =0; i < el->nr; i++) 557free(el->excludes[i]); 558free(el->excludes); 559free(el->filebuf); 560 561memset(el,0,sizeof(*el)); 562} 563 564static voidtrim_trailing_spaces(char*buf) 565{ 566char*p, *last_space = NULL; 567 568for(p = buf; *p; p++) 569switch(*p) { 570case' ': 571if(!last_space) 572 last_space = p; 573break; 574case'\\': 575 p++; 576if(!*p) 577return; 578/* fallthrough */ 579default: 580 last_space = NULL; 581} 582 583if(last_space) 584*last_space ='\0'; 585} 586 587/* 588 * Given a subdirectory name and "dir" of the current directory, 589 * search the subdir in "dir" and return it, or create a new one if it 590 * does not exist in "dir". 591 * 592 * If "name" has the trailing slash, it'll be excluded in the search. 593 */ 594static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 595struct untracked_cache_dir *dir, 596const char*name,int len) 597{ 598int first, last; 599struct untracked_cache_dir *d; 600if(!dir) 601return NULL; 602if(len && name[len -1] =='/') 603 len--; 604 first =0; 605 last = dir->dirs_nr; 606while(last > first) { 607int cmp, next = (last + first) >>1; 608 d = dir->dirs[next]; 609 cmp =strncmp(name, d->name, len); 610if(!cmp &&strlen(d->name) > len) 611 cmp = -1; 612if(!cmp) 613return d; 614if(cmp <0) { 615 last = next; 616continue; 617} 618 first = next+1; 619} 620 621 uc->dir_created++; 622FLEX_ALLOC_MEM(d, name, name, len); 623 624ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 625memmove(dir->dirs + first +1, dir->dirs + first, 626(dir->dirs_nr - first) *sizeof(*dir->dirs)); 627 dir->dirs_nr++; 628 dir->dirs[first] = d; 629return d; 630} 631 632static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 633{ 634int i; 635 dir->valid =0; 636 dir->untracked_nr =0; 637for(i =0; i < dir->dirs_nr; i++) 638do_invalidate_gitignore(dir->dirs[i]); 639} 640 641static voidinvalidate_gitignore(struct untracked_cache *uc, 642struct untracked_cache_dir *dir) 643{ 644 uc->gitignore_invalidated++; 645do_invalidate_gitignore(dir); 646} 647 648static voidinvalidate_directory(struct untracked_cache *uc, 649struct untracked_cache_dir *dir) 650{ 651int i; 652 uc->dir_invalidated++; 653 dir->valid =0; 654 dir->untracked_nr =0; 655for(i =0; i < dir->dirs_nr; i++) 656 dir->dirs[i]->recurse =0; 657} 658 659/* 660 * Given a file with name "fname", read it (either from disk, or from 661 * the index if "check_index" is non-zero), parse it and store the 662 * exclude rules in "el". 663 * 664 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 665 * stat data from disk (only valid if add_excludes returns zero). If 666 * ss_valid is non-zero, "ss" must contain good value as input. 667 */ 668static intadd_excludes(const char*fname,const char*base,int baselen, 669struct exclude_list *el,int check_index, 670struct sha1_stat *sha1_stat) 671{ 672struct stat st; 673int fd, i, lineno =1; 674size_t size =0; 675char*buf, *entry; 676 677 fd =open(fname, O_RDONLY); 678if(fd <0||fstat(fd, &st) <0) { 679if(errno != ENOENT) 680warn_on_inaccessible(fname); 681if(0<= fd) 682close(fd); 683if(!check_index || 684(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 685return-1; 686if(size ==0) { 687free(buf); 688return0; 689} 690if(buf[size-1] !='\n') { 691 buf =xrealloc(buf,st_add(size,1)); 692 buf[size++] ='\n'; 693} 694}else{ 695 size =xsize_t(st.st_size); 696if(size ==0) { 697if(sha1_stat) { 698fill_stat_data(&sha1_stat->stat, &st); 699hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 700 sha1_stat->valid =1; 701} 702close(fd); 703return0; 704} 705 buf =xmallocz(size); 706if(read_in_full(fd, buf, size) != size) { 707free(buf); 708close(fd); 709return-1; 710} 711 buf[size++] ='\n'; 712close(fd); 713if(sha1_stat) { 714int pos; 715if(sha1_stat->valid && 716!match_stat_data_racy(&the_index, &sha1_stat->stat, &st)) 717;/* no content change, ss->sha1 still good */ 718else if(check_index && 719(pos =cache_name_pos(fname,strlen(fname))) >=0&& 720!ce_stage(active_cache[pos]) && 721ce_uptodate(active_cache[pos]) && 722!would_convert_to_git(fname)) 723hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 724else 725hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 726fill_stat_data(&sha1_stat->stat, &st); 727 sha1_stat->valid =1; 728} 729} 730 731 el->filebuf = buf; 732 733if(skip_utf8_bom(&buf, size)) 734 size -= buf - el->filebuf; 735 736 entry = buf; 737 738for(i =0; i < size; i++) { 739if(buf[i] =='\n') { 740if(entry != buf + i && entry[0] !='#') { 741 buf[i - (i && buf[i-1] =='\r')] =0; 742trim_trailing_spaces(entry); 743add_exclude(entry, base, baselen, el, lineno); 744} 745 lineno++; 746 entry = buf + i +1; 747} 748} 749return0; 750} 751 752intadd_excludes_from_file_to_list(const char*fname,const char*base, 753int baselen,struct exclude_list *el, 754int check_index) 755{ 756returnadd_excludes(fname, base, baselen, el, check_index, NULL); 757} 758 759struct exclude_list *add_exclude_list(struct dir_struct *dir, 760int group_type,const char*src) 761{ 762struct exclude_list *el; 763struct exclude_list_group *group; 764 765 group = &dir->exclude_list_group[group_type]; 766ALLOC_GROW(group->el, group->nr +1, group->alloc); 767 el = &group->el[group->nr++]; 768memset(el,0,sizeof(*el)); 769 el->src = src; 770return el; 771} 772 773/* 774 * Used to set up core.excludesfile and .git/info/exclude lists. 775 */ 776static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 777struct sha1_stat *sha1_stat) 778{ 779struct exclude_list *el; 780/* 781 * catch setup_standard_excludes() that's called before 782 * dir->untracked is assigned. That function behaves 783 * differently when dir->untracked is non-NULL. 784 */ 785if(!dir->untracked) 786 dir->unmanaged_exclude_files++; 787 el =add_exclude_list(dir, EXC_FILE, fname); 788if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 789die("cannot use%sas an exclude file", fname); 790} 791 792voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 793{ 794 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 795add_excludes_from_file_1(dir, fname, NULL); 796} 797 798intmatch_basename(const char*basename,int basenamelen, 799const char*pattern,int prefix,int patternlen, 800unsigned flags) 801{ 802if(prefix == patternlen) { 803if(patternlen == basenamelen && 804!fspathncmp(pattern, basename, basenamelen)) 805return1; 806}else if(flags & EXC_FLAG_ENDSWITH) { 807/* "*literal" matching against "fooliteral" */ 808if(patternlen -1<= basenamelen && 809!fspathncmp(pattern +1, 810 basename + basenamelen - (patternlen -1), 811 patternlen -1)) 812return1; 813}else{ 814if(fnmatch_icase_mem(pattern, patternlen, 815 basename, basenamelen, 8160) ==0) 817return1; 818} 819return0; 820} 821 822intmatch_pathname(const char*pathname,int pathlen, 823const char*base,int baselen, 824const char*pattern,int prefix,int patternlen, 825unsigned flags) 826{ 827const char*name; 828int namelen; 829 830/* 831 * match with FNM_PATHNAME; the pattern has base implicitly 832 * in front of it. 833 */ 834if(*pattern =='/') { 835 pattern++; 836 patternlen--; 837 prefix--; 838} 839 840/* 841 * baselen does not count the trailing slash. base[] may or 842 * may not end with a trailing slash though. 843 */ 844if(pathlen < baselen +1|| 845(baselen && pathname[baselen] !='/') || 846fspathncmp(pathname, base, baselen)) 847return0; 848 849 namelen = baselen ? pathlen - baselen -1: pathlen; 850 name = pathname + pathlen - namelen; 851 852if(prefix) { 853/* 854 * if the non-wildcard part is longer than the 855 * remaining pathname, surely it cannot match. 856 */ 857if(prefix > namelen) 858return0; 859 860if(fspathncmp(pattern, name, prefix)) 861return0; 862 pattern += prefix; 863 patternlen -= prefix; 864 name += prefix; 865 namelen -= prefix; 866 867/* 868 * If the whole pattern did not have a wildcard, 869 * then our prefix match is all we need; we 870 * do not need to call fnmatch at all. 871 */ 872if(!patternlen && !namelen) 873return1; 874} 875 876returnfnmatch_icase_mem(pattern, patternlen, 877 name, namelen, 878 WM_PATHNAME) ==0; 879} 880 881/* 882 * Scan the given exclude list in reverse to see whether pathname 883 * should be ignored. The first match (i.e. the last on the list), if 884 * any, determines the fate. Returns the exclude_list element which 885 * matched, or NULL for undecided. 886 */ 887static struct exclude *last_exclude_matching_from_list(const char*pathname, 888int pathlen, 889const char*basename, 890int*dtype, 891struct exclude_list *el) 892{ 893struct exclude *exc = NULL;/* undecided */ 894int i; 895 896if(!el->nr) 897return NULL;/* undefined */ 898 899for(i = el->nr -1;0<= i; i--) { 900struct exclude *x = el->excludes[i]; 901const char*exclude = x->pattern; 902int prefix = x->nowildcardlen; 903 904if(x->flags & EXC_FLAG_MUSTBEDIR) { 905if(*dtype == DT_UNKNOWN) 906*dtype =get_dtype(NULL, pathname, pathlen); 907if(*dtype != DT_DIR) 908continue; 909} 910 911if(x->flags & EXC_FLAG_NODIR) { 912if(match_basename(basename, 913 pathlen - (basename - pathname), 914 exclude, prefix, x->patternlen, 915 x->flags)) { 916 exc = x; 917break; 918} 919continue; 920} 921 922assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 923if(match_pathname(pathname, pathlen, 924 x->base, x->baselen ? x->baselen -1:0, 925 exclude, prefix, x->patternlen, x->flags)) { 926 exc = x; 927break; 928} 929} 930return exc; 931} 932 933/* 934 * Scan the list and let the last match determine the fate. 935 * Return 1 for exclude, 0 for include and -1 for undecided. 936 */ 937intis_excluded_from_list(const char*pathname, 938int pathlen,const char*basename,int*dtype, 939struct exclude_list *el) 940{ 941struct exclude *exclude; 942 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 943if(exclude) 944return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 945return-1;/* undecided */ 946} 947 948static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 949const char*pathname,int pathlen,const char*basename, 950int*dtype_p) 951{ 952int i, j; 953struct exclude_list_group *group; 954struct exclude *exclude; 955for(i = EXC_CMDL; i <= EXC_FILE; i++) { 956 group = &dir->exclude_list_group[i]; 957for(j = group->nr -1; j >=0; j--) { 958 exclude =last_exclude_matching_from_list( 959 pathname, pathlen, basename, dtype_p, 960&group->el[j]); 961if(exclude) 962return exclude; 963} 964} 965return NULL; 966} 967 968/* 969 * Loads the per-directory exclude list for the substring of base 970 * which has a char length of baselen. 971 */ 972static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen) 973{ 974struct exclude_list_group *group; 975struct exclude_list *el; 976struct exclude_stack *stk = NULL; 977struct untracked_cache_dir *untracked; 978int current; 979 980 group = &dir->exclude_list_group[EXC_DIRS]; 981 982/* 983 * Pop the exclude lists from the EXCL_DIRS exclude_list_group 984 * which originate from directories not in the prefix of the 985 * path being checked. 986 */ 987while((stk = dir->exclude_stack) != NULL) { 988if(stk->baselen <= baselen && 989!strncmp(dir->basebuf.buf, base, stk->baselen)) 990break; 991 el = &group->el[dir->exclude_stack->exclude_ix]; 992 dir->exclude_stack = stk->prev; 993 dir->exclude = NULL; 994free((char*)el->src);/* see strbuf_detach() below */ 995clear_exclude_list(el); 996free(stk); 997 group->nr--; 998} 9991000/* Skip traversing into sub directories if the parent is excluded */1001if(dir->exclude)1002return;10031004/*1005 * Lazy initialization. All call sites currently just1006 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1007 * them seems lots of work for little benefit.1008 */1009if(!dir->basebuf.buf)1010strbuf_init(&dir->basebuf, PATH_MAX);10111012/* Read from the parent directories and push them down. */1013 current = stk ? stk->baselen : -1;1014strbuf_setlen(&dir->basebuf, current <0?0: current);1015if(dir->untracked)1016 untracked = stk ? stk->ucd : dir->untracked->root;1017else1018 untracked = NULL;10191020while(current < baselen) {1021const char*cp;1022struct sha1_stat sha1_stat;10231024 stk =xcalloc(1,sizeof(*stk));1025if(current <0) {1026 cp = base;1027 current =0;1028}else{1029 cp =strchr(base + current +1,'/');1030if(!cp)1031die("oops in prep_exclude");1032 cp++;1033 untracked =1034lookup_untracked(dir->untracked, untracked,1035 base + current,1036 cp - base - current);1037}1038 stk->prev = dir->exclude_stack;1039 stk->baselen = cp - base;1040 stk->exclude_ix = group->nr;1041 stk->ucd = untracked;1042 el =add_exclude_list(dir, EXC_DIRS, NULL);1043strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1044assert(stk->baselen == dir->basebuf.len);10451046/* Abort if the directory is excluded */1047if(stk->baselen) {1048int dt = DT_DIR;1049 dir->basebuf.buf[stk->baselen -1] =0;1050 dir->exclude =last_exclude_matching_from_lists(dir,1051 dir->basebuf.buf, stk->baselen -1,1052 dir->basebuf.buf + current, &dt);1053 dir->basebuf.buf[stk->baselen -1] ='/';1054if(dir->exclude &&1055 dir->exclude->flags & EXC_FLAG_NEGATIVE)1056 dir->exclude = NULL;1057if(dir->exclude) {1058 dir->exclude_stack = stk;1059return;1060}1061}10621063/* Try to read per-directory file */1064hashclr(sha1_stat.sha1);1065 sha1_stat.valid =0;1066if(dir->exclude_per_dir &&1067/*1068 * If we know that no files have been added in1069 * this directory (i.e. valid_cached_dir() has1070 * been executed and set untracked->valid) ..1071 */1072(!untracked || !untracked->valid ||1073/*1074 * .. and .gitignore does not exist before1075 * (i.e. null exclude_sha1). Then we can skip1076 * loading .gitignore, which would result in1077 * ENOENT anyway.1078 */1079!is_null_sha1(untracked->exclude_sha1))) {1080/*1081 * dir->basebuf gets reused by the traversal, but we1082 * need fname to remain unchanged to ensure the src1083 * member of each struct exclude correctly1084 * back-references its source file. Other invocations1085 * of add_exclude_list provide stable strings, so we1086 * strbuf_detach() and free() here in the caller.1087 */1088struct strbuf sb = STRBUF_INIT;1089strbuf_addbuf(&sb, &dir->basebuf);1090strbuf_addstr(&sb, dir->exclude_per_dir);1091 el->src =strbuf_detach(&sb, NULL);1092add_excludes(el->src, el->src, stk->baselen, el,1,1093 untracked ? &sha1_stat : NULL);1094}1095/*1096 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1097 * will first be called in valid_cached_dir() then maybe many1098 * times more in last_exclude_matching(). When the cache is1099 * used, last_exclude_matching() will not be called and1100 * reading .gitignore content will be a waste.1101 *1102 * So when it's called by valid_cached_dir() and we can get1103 * .gitignore SHA-1 from the index (i.e. .gitignore is not1104 * modified on work tree), we could delay reading the1105 * .gitignore content until we absolutely need it in1106 * last_exclude_matching(). Be careful about ignore rule1107 * order, though, if you do that.1108 */1109if(untracked &&1110hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1111invalidate_gitignore(dir->untracked, untracked);1112hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1113}1114 dir->exclude_stack = stk;1115 current = stk->baselen;1116}1117strbuf_setlen(&dir->basebuf, baselen);1118}11191120/*1121 * Loads the exclude lists for the directory containing pathname, then1122 * scans all exclude lists to determine whether pathname is excluded.1123 * Returns the exclude_list element which matched, or NULL for1124 * undecided.1125 */1126struct exclude *last_exclude_matching(struct dir_struct *dir,1127const char*pathname,1128int*dtype_p)1129{1130int pathlen =strlen(pathname);1131const char*basename =strrchr(pathname,'/');1132 basename = (basename) ? basename+1: pathname;11331134prep_exclude(dir, pathname, basename-pathname);11351136if(dir->exclude)1137return dir->exclude;11381139returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1140 basename, dtype_p);1141}11421143/*1144 * Loads the exclude lists for the directory containing pathname, then1145 * scans all exclude lists to determine whether pathname is excluded.1146 * Returns 1 if true, otherwise 0.1147 */1148intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1149{1150struct exclude *exclude =1151last_exclude_matching(dir, pathname, dtype_p);1152if(exclude)1153return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1154return0;1155}11561157static struct dir_entry *dir_entry_new(const char*pathname,int len)1158{1159struct dir_entry *ent;11601161FLEX_ALLOC_MEM(ent, name, pathname, len);1162 ent->len = len;1163return ent;1164}11651166static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1167{1168if(cache_file_exists(pathname, len, ignore_case))1169return NULL;11701171ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1172return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1173}11741175struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1176{1177if(!cache_name_is_other(pathname, len))1178return NULL;11791180ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1181return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1182}11831184enum exist_status {1185 index_nonexistent =0,1186 index_directory,1187 index_gitdir1188};11891190/*1191 * Do not use the alphabetically sorted index to look up1192 * the directory name; instead, use the case insensitive1193 * directory hash.1194 */1195static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1196{1197struct cache_entry *ce;11981199if(cache_dir_exists(dirname, len))1200return index_directory;12011202 ce =cache_file_exists(dirname, len, ignore_case);1203if(ce &&S_ISGITLINK(ce->ce_mode))1204return index_gitdir;12051206return index_nonexistent;1207}12081209/*1210 * The index sorts alphabetically by entry name, which1211 * means that a gitlink sorts as '\0' at the end, while1212 * a directory (which is defined not as an entry, but as1213 * the files it contains) will sort with the '/' at the1214 * end.1215 */1216static enum exist_status directory_exists_in_index(const char*dirname,int len)1217{1218int pos;12191220if(ignore_case)1221returndirectory_exists_in_index_icase(dirname, len);12221223 pos =cache_name_pos(dirname, len);1224if(pos <0)1225 pos = -pos-1;1226while(pos < active_nr) {1227const struct cache_entry *ce = active_cache[pos++];1228unsigned char endchar;12291230if(strncmp(ce->name, dirname, len))1231break;1232 endchar = ce->name[len];1233if(endchar >'/')1234break;1235if(endchar =='/')1236return index_directory;1237if(!endchar &&S_ISGITLINK(ce->ce_mode))1238return index_gitdir;1239}1240return index_nonexistent;1241}12421243/*1244 * When we find a directory when traversing the filesystem, we1245 * have three distinct cases:1246 *1247 * - ignore it1248 * - see it as a directory1249 * - recurse into it1250 *1251 * and which one we choose depends on a combination of existing1252 * git index contents and the flags passed into the directory1253 * traversal routine.1254 *1255 * Case 1: If we *already* have entries in the index under that1256 * directory name, we always recurse into the directory to see1257 * all the files.1258 *1259 * Case 2: If we *already* have that directory name as a gitlink,1260 * we always continue to see it as a gitlink, regardless of whether1261 * there is an actual git directory there or not (it might not1262 * be checked out as a subproject!)1263 *1264 * Case 3: if we didn't have it in the index previously, we1265 * have a few sub-cases:1266 *1267 * (a) if "show_other_directories" is true, we show it as1268 * just a directory, unless "hide_empty_directories" is1269 * also true, in which case we need to check if it contains any1270 * untracked and / or ignored files.1271 * (b) if it looks like a git directory, and we don't have1272 * 'no_gitlinks' set we treat it as a gitlink, and show it1273 * as a directory.1274 * (c) otherwise, we recurse into it.1275 */1276static enum path_treatment treat_directory(struct dir_struct *dir,1277struct untracked_cache_dir *untracked,1278const char*dirname,int len,int baselen,int exclude,1279const struct path_simplify *simplify)1280{1281/* The "len-1" is to strip the final '/' */1282switch(directory_exists_in_index(dirname, len-1)) {1283case index_directory:1284return path_recurse;12851286case index_gitdir:1287return path_none;12881289case index_nonexistent:1290if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1291break;1292if(!(dir->flags & DIR_NO_GITLINKS)) {1293unsigned char sha1[20];1294if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1295return path_untracked;1296}1297return path_recurse;1298}12991300/* This is the "show_other_directories" case */13011302if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1303return exclude ? path_excluded : path_untracked;13041305 untracked =lookup_untracked(dir->untracked, untracked,1306 dirname + baselen, len - baselen);1307returnread_directory_recursive(dir, dirname, len,1308 untracked,1, simplify);1309}13101311/*1312 * This is an inexact early pruning of any recursive directory1313 * reading - if the path cannot possibly be in the pathspec,1314 * return true, and we'll skip it early.1315 */1316static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1317{1318if(simplify) {1319for(;;) {1320const char*match = simplify->path;1321int len = simplify->len;13221323if(!match)1324break;1325if(len > pathlen)1326 len = pathlen;1327if(!memcmp(path, match, len))1328return0;1329 simplify++;1330}1331return1;1332}1333return0;1334}13351336/*1337 * This function tells us whether an excluded path matches a1338 * list of "interesting" pathspecs. That is, whether a path matched1339 * by any of the pathspecs could possibly be ignored by excluding1340 * the specified path. This can happen if:1341 *1342 * 1. the path is mentioned explicitly in the pathspec1343 *1344 * 2. the path is a directory prefix of some element in the1345 * pathspec1346 */1347static intexclude_matches_pathspec(const char*path,int len,1348const struct path_simplify *simplify)1349{1350if(simplify) {1351for(; simplify->path; simplify++) {1352if(len == simplify->len1353&& !memcmp(path, simplify->path, len))1354return1;1355if(len < simplify->len1356&& simplify->path[len] =='/'1357&& !memcmp(path, simplify->path, len))1358return1;1359}1360}1361return0;1362}13631364static intget_index_dtype(const char*path,int len)1365{1366int pos;1367const struct cache_entry *ce;13681369 ce =cache_file_exists(path, len,0);1370if(ce) {1371if(!ce_uptodate(ce))1372return DT_UNKNOWN;1373if(S_ISGITLINK(ce->ce_mode))1374return DT_DIR;1375/*1376 * Nobody actually cares about the1377 * difference between DT_LNK and DT_REG1378 */1379return DT_REG;1380}13811382/* Try to look it up as a directory */1383 pos =cache_name_pos(path, len);1384if(pos >=0)1385return DT_UNKNOWN;1386 pos = -pos-1;1387while(pos < active_nr) {1388 ce = active_cache[pos++];1389if(strncmp(ce->name, path, len))1390break;1391if(ce->name[len] >'/')1392break;1393if(ce->name[len] <'/')1394continue;1395if(!ce_uptodate(ce))1396break;/* continue? */1397return DT_DIR;1398}1399return DT_UNKNOWN;1400}14011402static intget_dtype(struct dirent *de,const char*path,int len)1403{1404int dtype = de ?DTYPE(de) : DT_UNKNOWN;1405struct stat st;14061407if(dtype != DT_UNKNOWN)1408return dtype;1409 dtype =get_index_dtype(path, len);1410if(dtype != DT_UNKNOWN)1411return dtype;1412if(lstat(path, &st))1413return dtype;1414if(S_ISREG(st.st_mode))1415return DT_REG;1416if(S_ISDIR(st.st_mode))1417return DT_DIR;1418if(S_ISLNK(st.st_mode))1419return DT_LNK;1420return dtype;1421}14221423static enum path_treatment treat_one_path(struct dir_struct *dir,1424struct untracked_cache_dir *untracked,1425struct strbuf *path,1426int baselen,1427const struct path_simplify *simplify,1428int dtype,struct dirent *de)1429{1430int exclude;1431int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);14321433if(dtype == DT_UNKNOWN)1434 dtype =get_dtype(de, path->buf, path->len);14351436/* Always exclude indexed files */1437if(dtype != DT_DIR && has_path_in_index)1438return path_none;14391440/*1441 * When we are looking at a directory P in the working tree,1442 * there are three cases:1443 *1444 * (1) P exists in the index. Everything inside the directory P in1445 * the working tree needs to go when P is checked out from the1446 * index.1447 *1448 * (2) P does not exist in the index, but there is P/Q in the index.1449 * We know P will stay a directory when we check out the contents1450 * of the index, but we do not know yet if there is a directory1451 * P/Q in the working tree to be killed, so we need to recurse.1452 *1453 * (3) P does not exist in the index, and there is no P/Q in the index1454 * to require P to be a directory, either. Only in this case, we1455 * know that everything inside P will not be killed without1456 * recursing.1457 */1458if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1459(dtype == DT_DIR) &&1460!has_path_in_index &&1461(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1462return path_none;14631464 exclude =is_excluded(dir, path->buf, &dtype);14651466/*1467 * Excluded? If we don't explicitly want to show1468 * ignored files, ignore it1469 */1470if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1471return path_excluded;14721473switch(dtype) {1474default:1475return path_none;1476case DT_DIR:1477strbuf_addch(path,'/');1478returntreat_directory(dir, untracked, path->buf, path->len,1479 baselen, exclude, simplify);1480case DT_REG:1481case DT_LNK:1482return exclude ? path_excluded : path_untracked;1483}1484}14851486static enum path_treatment treat_path_fast(struct dir_struct *dir,1487struct untracked_cache_dir *untracked,1488struct cached_dir *cdir,1489struct strbuf *path,1490int baselen,1491const struct path_simplify *simplify)1492{1493strbuf_setlen(path, baselen);1494if(!cdir->ucd) {1495strbuf_addstr(path, cdir->file);1496return path_untracked;1497}1498strbuf_addstr(path, cdir->ucd->name);1499/* treat_one_path() does this before it calls treat_directory() */1500strbuf_complete(path,'/');1501if(cdir->ucd->check_only)1502/*1503 * check_only is set as a result of treat_directory() getting1504 * to its bottom. Verify again the same set of directories1505 * with check_only set.1506 */1507returnread_directory_recursive(dir, path->buf, path->len,1508 cdir->ucd,1, simplify);1509/*1510 * We get path_recurse in the first run when1511 * directory_exists_in_index() returns index_nonexistent. We1512 * are sure that new changes in the index does not impact the1513 * outcome. Return now.1514 */1515return path_recurse;1516}15171518static enum path_treatment treat_path(struct dir_struct *dir,1519struct untracked_cache_dir *untracked,1520struct cached_dir *cdir,1521struct strbuf *path,1522int baselen,1523const struct path_simplify *simplify)1524{1525int dtype;1526struct dirent *de = cdir->de;15271528if(!de)1529returntreat_path_fast(dir, untracked, cdir, path,1530 baselen, simplify);1531if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1532return path_none;1533strbuf_setlen(path, baselen);1534strbuf_addstr(path, de->d_name);1535if(simplify_away(path->buf, path->len, simplify))1536return path_none;15371538 dtype =DTYPE(de);1539returntreat_one_path(dir, untracked, path, baselen, simplify, dtype, de);1540}15411542static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1543{1544if(!dir)1545return;1546ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1547 dir->untracked_alloc);1548 dir->untracked[dir->untracked_nr++] =xstrdup(name);1549}15501551static intvalid_cached_dir(struct dir_struct *dir,1552struct untracked_cache_dir *untracked,1553struct strbuf *path,1554int check_only)1555{1556struct stat st;15571558if(!untracked)1559return0;15601561if(stat(path->len ? path->buf :".", &st)) {1562invalidate_directory(dir->untracked, untracked);1563memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1564return0;1565}1566if(!untracked->valid ||1567match_stat_data_racy(&the_index, &untracked->stat_data, &st)) {1568if(untracked->valid)1569invalidate_directory(dir->untracked, untracked);1570fill_stat_data(&untracked->stat_data, &st);1571return0;1572}15731574if(untracked->check_only != !!check_only) {1575invalidate_directory(dir->untracked, untracked);1576return0;1577}15781579/*1580 * prep_exclude will be called eventually on this directory,1581 * but it's called much later in last_exclude_matching(). We1582 * need it now to determine the validity of the cache for this1583 * path. The next calls will be nearly no-op, the way1584 * prep_exclude() is designed.1585 */1586if(path->len && path->buf[path->len -1] !='/') {1587strbuf_addch(path,'/');1588prep_exclude(dir, path->buf, path->len);1589strbuf_setlen(path, path->len -1);1590}else1591prep_exclude(dir, path->buf, path->len);15921593/* hopefully prep_exclude() haven't invalidated this entry... */1594return untracked->valid;1595}15961597static intopen_cached_dir(struct cached_dir *cdir,1598struct dir_struct *dir,1599struct untracked_cache_dir *untracked,1600struct strbuf *path,1601int check_only)1602{1603memset(cdir,0,sizeof(*cdir));1604 cdir->untracked = untracked;1605if(valid_cached_dir(dir, untracked, path, check_only))1606return0;1607 cdir->fdir =opendir(path->len ? path->buf :".");1608if(dir->untracked)1609 dir->untracked->dir_opened++;1610if(!cdir->fdir)1611return-1;1612return0;1613}16141615static intread_cached_dir(struct cached_dir *cdir)1616{1617if(cdir->fdir) {1618 cdir->de =readdir(cdir->fdir);1619if(!cdir->de)1620return-1;1621return0;1622}1623while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1624struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1625if(!d->recurse) {1626 cdir->nr_dirs++;1627continue;1628}1629 cdir->ucd = d;1630 cdir->nr_dirs++;1631return0;1632}1633 cdir->ucd = NULL;1634if(cdir->nr_files < cdir->untracked->untracked_nr) {1635struct untracked_cache_dir *d = cdir->untracked;1636 cdir->file = d->untracked[cdir->nr_files++];1637return0;1638}1639return-1;1640}16411642static voidclose_cached_dir(struct cached_dir *cdir)1643{1644if(cdir->fdir)1645closedir(cdir->fdir);1646/*1647 * We have gone through this directory and found no untracked1648 * entries. Mark it valid.1649 */1650if(cdir->untracked) {1651 cdir->untracked->valid =1;1652 cdir->untracked->recurse =1;1653}1654}16551656/*1657 * Read a directory tree. We currently ignore anything but1658 * directories, regular files and symlinks. That's because git1659 * doesn't handle them at all yet. Maybe that will change some1660 * day.1661 *1662 * Also, we ignore the name ".git" (even if it is not a directory).1663 * That likely will not change.1664 *1665 * Returns the most significant path_treatment value encountered in the scan.1666 */1667static enum path_treatment read_directory_recursive(struct dir_struct *dir,1668const char*base,int baselen,1669struct untracked_cache_dir *untracked,int check_only,1670const struct path_simplify *simplify)1671{1672struct cached_dir cdir;1673enum path_treatment state, subdir_state, dir_state = path_none;1674struct strbuf path = STRBUF_INIT;16751676strbuf_add(&path, base, baselen);16771678if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1679goto out;16801681if(untracked)1682 untracked->check_only = !!check_only;16831684while(!read_cached_dir(&cdir)) {1685/* check how the file or directory should be treated */1686 state =treat_path(dir, untracked, &cdir, &path, baselen, simplify);16871688if(state > dir_state)1689 dir_state = state;16901691/* recurse into subdir if instructed by treat_path */1692if(state == path_recurse) {1693struct untracked_cache_dir *ud;1694 ud =lookup_untracked(dir->untracked, untracked,1695 path.buf + baselen,1696 path.len - baselen);1697 subdir_state =1698read_directory_recursive(dir, path.buf, path.len,1699 ud, check_only, simplify);1700if(subdir_state > dir_state)1701 dir_state = subdir_state;1702}17031704if(check_only) {1705/* abort early if maximum state has been reached */1706if(dir_state == path_untracked) {1707if(cdir.fdir)1708add_untracked(untracked, path.buf + baselen);1709break;1710}1711/* skip the dir_add_* part */1712continue;1713}17141715/* add the path to the appropriate result list */1716switch(state) {1717case path_excluded:1718if(dir->flags & DIR_SHOW_IGNORED)1719dir_add_name(dir, path.buf, path.len);1720else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1721((dir->flags & DIR_COLLECT_IGNORED) &&1722exclude_matches_pathspec(path.buf, path.len,1723 simplify)))1724dir_add_ignored(dir, path.buf, path.len);1725break;17261727case path_untracked:1728if(dir->flags & DIR_SHOW_IGNORED)1729break;1730dir_add_name(dir, path.buf, path.len);1731if(cdir.fdir)1732add_untracked(untracked, path.buf + baselen);1733break;17341735default:1736break;1737}1738}1739close_cached_dir(&cdir);1740 out:1741strbuf_release(&path);17421743return dir_state;1744}17451746static intcmp_name(const void*p1,const void*p2)1747{1748const struct dir_entry *e1 = *(const struct dir_entry **)p1;1749const struct dir_entry *e2 = *(const struct dir_entry **)p2;17501751returnname_compare(e1->name, e1->len, e2->name, e2->len);1752}17531754static struct path_simplify *create_simplify(const char**pathspec)1755{1756int nr, alloc =0;1757struct path_simplify *simplify = NULL;17581759if(!pathspec)1760return NULL;17611762for(nr =0; ; nr++) {1763const char*match;1764ALLOC_GROW(simplify, nr +1, alloc);1765 match = *pathspec++;1766if(!match)1767break;1768 simplify[nr].path = match;1769 simplify[nr].len =simple_length(match);1770}1771 simplify[nr].path = NULL;1772 simplify[nr].len =0;1773return simplify;1774}17751776static voidfree_simplify(struct path_simplify *simplify)1777{1778free(simplify);1779}17801781static inttreat_leading_path(struct dir_struct *dir,1782const char*path,int len,1783const struct path_simplify *simplify)1784{1785struct strbuf sb = STRBUF_INIT;1786int baselen, rc =0;1787const char*cp;1788int old_flags = dir->flags;17891790while(len && path[len -1] =='/')1791 len--;1792if(!len)1793return1;1794 baselen =0;1795 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1796while(1) {1797 cp = path + baselen + !!baselen;1798 cp =memchr(cp,'/', path + len - cp);1799if(!cp)1800 baselen = len;1801else1802 baselen = cp - path;1803strbuf_setlen(&sb,0);1804strbuf_add(&sb, path, baselen);1805if(!is_directory(sb.buf))1806break;1807if(simplify_away(sb.buf, sb.len, simplify))1808break;1809if(treat_one_path(dir, NULL, &sb, baselen, simplify,1810 DT_DIR, NULL) == path_none)1811break;/* do not recurse into it */1812if(len <= baselen) {1813 rc =1;1814break;/* finished checking */1815}1816}1817strbuf_release(&sb);1818 dir->flags = old_flags;1819return rc;1820}18211822static const char*get_ident_string(void)1823{1824static struct strbuf sb = STRBUF_INIT;1825struct utsname uts;18261827if(sb.len)1828return sb.buf;1829if(uname(&uts) <0)1830die_errno(_("failed to get kernel name and information"));1831strbuf_addf(&sb,"Location%s, system%s",get_git_work_tree(),1832 uts.sysname);1833return sb.buf;1834}18351836static intident_in_untracked(const struct untracked_cache *uc)1837{1838/*1839 * Previous git versions may have saved many NUL separated1840 * strings in the "ident" field, but it is insane to manage1841 * many locations, so just take care of the first one.1842 */18431844return!strcmp(uc->ident.buf,get_ident_string());1845}18461847static voidset_untracked_ident(struct untracked_cache *uc)1848{1849strbuf_reset(&uc->ident);1850strbuf_addstr(&uc->ident,get_ident_string());18511852/*1853 * This strbuf used to contain a list of NUL separated1854 * strings, so save NUL too for backward compatibility.1855 */1856strbuf_addch(&uc->ident,0);1857}18581859static voidnew_untracked_cache(struct index_state *istate)1860{1861struct untracked_cache *uc =xcalloc(1,sizeof(*uc));1862strbuf_init(&uc->ident,100);1863 uc->exclude_per_dir =".gitignore";1864/* should be the same flags used by git-status */1865 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;1866set_untracked_ident(uc);1867 istate->untracked = uc;1868 istate->cache_changed |= UNTRACKED_CHANGED;1869}18701871voidadd_untracked_cache(struct index_state *istate)1872{1873if(!istate->untracked) {1874new_untracked_cache(istate);1875}else{1876if(!ident_in_untracked(istate->untracked)) {1877free_untracked_cache(istate->untracked);1878new_untracked_cache(istate);1879}1880}1881}18821883voidremove_untracked_cache(struct index_state *istate)1884{1885if(istate->untracked) {1886free_untracked_cache(istate->untracked);1887 istate->untracked = NULL;1888 istate->cache_changed |= UNTRACKED_CHANGED;1889}1890}18911892static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1893int base_len,1894const struct pathspec *pathspec)1895{1896struct untracked_cache_dir *root;18971898if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))1899return NULL;19001901/*1902 * We only support $GIT_DIR/info/exclude and core.excludesfile1903 * as the global ignore rule files. Any other additions1904 * (e.g. from command line) invalidate the cache. This1905 * condition also catches running setup_standard_excludes()1906 * before setting dir->untracked!1907 */1908if(dir->unmanaged_exclude_files)1909return NULL;19101911/*1912 * Optimize for the main use case only: whole-tree git1913 * status. More work involved in treat_leading_path() if we1914 * use cache on just a subset of the worktree. pathspec1915 * support could make the matter even worse.1916 */1917if(base_len || (pathspec && pathspec->nr))1918return NULL;19191920/* Different set of flags may produce different results */1921if(dir->flags != dir->untracked->dir_flags ||1922/*1923 * See treat_directory(), case index_nonexistent. Without1924 * this flag, we may need to also cache .git file content1925 * for the resolve_gitlink_ref() call, which we don't.1926 */1927!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1928/* We don't support collecting ignore files */1929(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1930 DIR_COLLECT_IGNORED)))1931return NULL;19321933/*1934 * If we use .gitignore in the cache and now you change it to1935 * .gitexclude, everything will go wrong.1936 */1937if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1938strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1939return NULL;19401941/*1942 * EXC_CMDL is not considered in the cache. If people set it,1943 * skip the cache.1944 */1945if(dir->exclude_list_group[EXC_CMDL].nr)1946return NULL;19471948if(!ident_in_untracked(dir->untracked)) {1949warning(_("Untracked cache is disabled on this system or location."));1950return NULL;1951}19521953if(!dir->untracked->root) {1954const int len =sizeof(*dir->untracked->root);1955 dir->untracked->root =xmalloc(len);1956memset(dir->untracked->root,0, len);1957}19581959/* Validate $GIT_DIR/info/exclude and core.excludesfile */1960 root = dir->untracked->root;1961if(hashcmp(dir->ss_info_exclude.sha1,1962 dir->untracked->ss_info_exclude.sha1)) {1963invalidate_gitignore(dir->untracked, root);1964 dir->untracked->ss_info_exclude = dir->ss_info_exclude;1965}1966if(hashcmp(dir->ss_excludes_file.sha1,1967 dir->untracked->ss_excludes_file.sha1)) {1968invalidate_gitignore(dir->untracked, root);1969 dir->untracked->ss_excludes_file = dir->ss_excludes_file;1970}19711972/* Make sure this directory is not dropped out at saving phase */1973 root->recurse =1;1974return root;1975}19761977intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)1978{1979struct path_simplify *simplify;1980struct untracked_cache_dir *untracked;19811982/*1983 * Check out create_simplify()1984 */1985if(pathspec)1986GUARD_PATHSPEC(pathspec,1987 PATHSPEC_FROMTOP |1988 PATHSPEC_MAXDEPTH |1989 PATHSPEC_LITERAL |1990 PATHSPEC_GLOB |1991 PATHSPEC_ICASE |1992 PATHSPEC_EXCLUDE);19931994if(has_symlink_leading_path(path, len))1995return dir->nr;19961997/*1998 * exclude patterns are treated like positive ones in1999 * create_simplify. Usually exclude patterns should be a2000 * subset of positive ones, which has no impacts on2001 * create_simplify().2002 */2003 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);2004 untracked =validate_untracked_cache(dir, len, pathspec);2005if(!untracked)2006/*2007 * make sure untracked cache code path is disabled,2008 * e.g. prep_exclude()2009 */2010 dir->untracked = NULL;2011if(!len ||treat_leading_path(dir, path, len, simplify))2012read_directory_recursive(dir, path, len, untracked,0, simplify);2013free_simplify(simplify);2014qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);2015qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);2016if(dir->untracked) {2017static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);2018trace_printf_key(&trace_untracked_stats,2019"node creation:%u\n"2020"gitignore invalidation:%u\n"2021"directory invalidation:%u\n"2022"opendir:%u\n",2023 dir->untracked->dir_created,2024 dir->untracked->gitignore_invalidated,2025 dir->untracked->dir_invalidated,2026 dir->untracked->dir_opened);2027if(dir->untracked == the_index.untracked &&2028(dir->untracked->dir_opened ||2029 dir->untracked->gitignore_invalidated ||2030 dir->untracked->dir_invalidated))2031 the_index.cache_changed |= UNTRACKED_CHANGED;2032if(dir->untracked != the_index.untracked) {2033free(dir->untracked);2034 dir->untracked = NULL;2035}2036}2037return dir->nr;2038}20392040intfile_exists(const char*f)2041{2042struct stat sb;2043returnlstat(f, &sb) ==0;2044}20452046static intcmp_icase(char a,char b)2047{2048if(a == b)2049return0;2050if(ignore_case)2051returntoupper(a) -toupper(b);2052return a - b;2053}20542055/*2056 * Given two normalized paths (a trailing slash is ok), if subdir is2057 * outside dir, return -1. Otherwise return the offset in subdir that2058 * can be used as relative path to dir.2059 */2060intdir_inside_of(const char*subdir,const char*dir)2061{2062int offset =0;20632064assert(dir && subdir && *dir && *subdir);20652066while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2067 dir++;2068 subdir++;2069 offset++;2070}20712072/* hel[p]/me vs hel[l]/yeah */2073if(*dir && *subdir)2074return-1;20752076if(!*subdir)2077return!*dir ? offset : -1;/* same dir */20782079/* foo/[b]ar vs foo/[] */2080if(is_dir_sep(dir[-1]))2081returnis_dir_sep(subdir[-1]) ? offset : -1;20822083/* foo[/]bar vs foo[] */2084returnis_dir_sep(*subdir) ? offset +1: -1;2085}20862087intis_inside_dir(const char*dir)2088{2089char*cwd;2090int rc;20912092if(!dir)2093return0;20942095 cwd =xgetcwd();2096 rc = (dir_inside_of(cwd, dir) >=0);2097free(cwd);2098return rc;2099}21002101intis_empty_dir(const char*path)2102{2103DIR*dir =opendir(path);2104struct dirent *e;2105int ret =1;21062107if(!dir)2108return0;21092110while((e =readdir(dir)) != NULL)2111if(!is_dot_or_dotdot(e->d_name)) {2112 ret =0;2113break;2114}21152116closedir(dir);2117return ret;2118}21192120static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2121{2122DIR*dir;2123struct dirent *e;2124int ret =0, original_len = path->len, len, kept_down =0;2125int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2126int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2127unsigned char submodule_head[20];21282129if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2130!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2131/* Do not descend and nuke a nested git work tree. */2132if(kept_up)2133*kept_up =1;2134return0;2135}21362137 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2138 dir =opendir(path->buf);2139if(!dir) {2140if(errno == ENOENT)2141return keep_toplevel ? -1:0;2142else if(errno == EACCES && !keep_toplevel)2143/*2144 * An empty dir could be removable even if it2145 * is unreadable:2146 */2147returnrmdir(path->buf);2148else2149return-1;2150}2151strbuf_complete(path,'/');21522153 len = path->len;2154while((e =readdir(dir)) != NULL) {2155struct stat st;2156if(is_dot_or_dotdot(e->d_name))2157continue;21582159strbuf_setlen(path, len);2160strbuf_addstr(path, e->d_name);2161if(lstat(path->buf, &st)) {2162if(errno == ENOENT)2163/*2164 * file disappeared, which is what we2165 * wanted anyway2166 */2167continue;2168/* fall thru */2169}else if(S_ISDIR(st.st_mode)) {2170if(!remove_dir_recurse(path, flag, &kept_down))2171continue;/* happy */2172}else if(!only_empty &&2173(!unlink(path->buf) || errno == ENOENT)) {2174continue;/* happy, too */2175}21762177/* path too long, stat fails, or non-directory still exists */2178 ret = -1;2179break;2180}2181closedir(dir);21822183strbuf_setlen(path, original_len);2184if(!ret && !keep_toplevel && !kept_down)2185 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2186else if(kept_up)2187/*2188 * report the uplevel that it is not an error that we2189 * did not rmdir() our directory.2190 */2191*kept_up = !ret;2192return ret;2193}21942195intremove_dir_recursively(struct strbuf *path,int flag)2196{2197returnremove_dir_recurse(path, flag, NULL);2198}21992200staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")22012202voidsetup_standard_excludes(struct dir_struct *dir)2203{2204const char*path;22052206 dir->exclude_per_dir =".gitignore";22072208/* core.excludefile defaulting to $XDG_HOME/git/ignore */2209if(!excludes_file)2210 excludes_file =xdg_config_home("ignore");2211if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2212add_excludes_from_file_1(dir, excludes_file,2213 dir->untracked ? &dir->ss_excludes_file : NULL);22142215/* per repository user preference */2216 path =git_path_info_exclude();2217if(!access_or_warn(path, R_OK,0))2218add_excludes_from_file_1(dir, path,2219 dir->untracked ? &dir->ss_info_exclude : NULL);2220}22212222intremove_path(const char*name)2223{2224char*slash;22252226if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2227return-1;22282229 slash =strrchr(name,'/');2230if(slash) {2231char*dirs =xstrdup(name);2232 slash = dirs + (slash - name);2233do{2234*slash ='\0';2235}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2236free(dirs);2237}2238return0;2239}22402241/*2242 * Frees memory within dir which was allocated for exclude lists and2243 * the exclude_stack. Does not free dir itself.2244 */2245voidclear_directory(struct dir_struct *dir)2246{2247int i, j;2248struct exclude_list_group *group;2249struct exclude_list *el;2250struct exclude_stack *stk;22512252for(i = EXC_CMDL; i <= EXC_FILE; i++) {2253 group = &dir->exclude_list_group[i];2254for(j =0; j < group->nr; j++) {2255 el = &group->el[j];2256if(i == EXC_DIRS)2257free((char*)el->src);2258clear_exclude_list(el);2259}2260free(group->el);2261}22622263 stk = dir->exclude_stack;2264while(stk) {2265struct exclude_stack *prev = stk->prev;2266free(stk);2267 stk = prev;2268}2269strbuf_release(&dir->basebuf);2270}22712272struct ondisk_untracked_cache {2273struct stat_data info_exclude_stat;2274struct stat_data excludes_file_stat;2275uint32_t dir_flags;2276unsigned char info_exclude_sha1[20];2277unsigned char excludes_file_sha1[20];2278char exclude_per_dir[FLEX_ARRAY];2279};22802281#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)22822283struct write_data {2284int index;/* number of written untracked_cache_dir */2285struct ewah_bitmap *check_only;/* from untracked_cache_dir */2286struct ewah_bitmap *valid;/* from untracked_cache_dir */2287struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2288struct strbuf out;2289struct strbuf sb_stat;2290struct strbuf sb_sha1;2291};22922293static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2294{2295 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2296 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2297 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2298 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2299 to->sd_dev =htonl(from->sd_dev);2300 to->sd_ino =htonl(from->sd_ino);2301 to->sd_uid =htonl(from->sd_uid);2302 to->sd_gid =htonl(from->sd_gid);2303 to->sd_size =htonl(from->sd_size);2304}23052306static voidwrite_one_dir(struct untracked_cache_dir *untracked,2307struct write_data *wd)2308{2309struct stat_data stat_data;2310struct strbuf *out = &wd->out;2311unsigned char intbuf[16];2312unsigned int intlen, value;2313int i = wd->index++;23142315/*2316 * untracked_nr should be reset whenever valid is clear, but2317 * for safety..2318 */2319if(!untracked->valid) {2320 untracked->untracked_nr =0;2321 untracked->check_only =0;2322}23232324if(untracked->check_only)2325ewah_set(wd->check_only, i);2326if(untracked->valid) {2327ewah_set(wd->valid, i);2328stat_data_to_disk(&stat_data, &untracked->stat_data);2329strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2330}2331if(!is_null_sha1(untracked->exclude_sha1)) {2332ewah_set(wd->sha1_valid, i);2333strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2334}23352336 intlen =encode_varint(untracked->untracked_nr, intbuf);2337strbuf_add(out, intbuf, intlen);23382339/* skip non-recurse directories */2340for(i =0, value =0; i < untracked->dirs_nr; i++)2341if(untracked->dirs[i]->recurse)2342 value++;2343 intlen =encode_varint(value, intbuf);2344strbuf_add(out, intbuf, intlen);23452346strbuf_add(out, untracked->name,strlen(untracked->name) +1);23472348for(i =0; i < untracked->untracked_nr; i++)2349strbuf_add(out, untracked->untracked[i],2350strlen(untracked->untracked[i]) +1);23512352for(i =0; i < untracked->dirs_nr; i++)2353if(untracked->dirs[i]->recurse)2354write_one_dir(untracked->dirs[i], wd);2355}23562357voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2358{2359struct ondisk_untracked_cache *ouc;2360struct write_data wd;2361unsigned char varbuf[16];2362int varint_len;2363size_t len =strlen(untracked->exclude_per_dir);23642365FLEX_ALLOC_MEM(ouc, exclude_per_dir, untracked->exclude_per_dir, len);2366stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2367stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2368hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2369hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2370 ouc->dir_flags =htonl(untracked->dir_flags);23712372 varint_len =encode_varint(untracked->ident.len, varbuf);2373strbuf_add(out, varbuf, varint_len);2374strbuf_add(out, untracked->ident.buf, untracked->ident.len);23752376strbuf_add(out, ouc,ouc_size(len));2377free(ouc);2378 ouc = NULL;23792380if(!untracked->root) {2381 varint_len =encode_varint(0, varbuf);2382strbuf_add(out, varbuf, varint_len);2383return;2384}23852386 wd.index =0;2387 wd.check_only =ewah_new();2388 wd.valid =ewah_new();2389 wd.sha1_valid =ewah_new();2390strbuf_init(&wd.out,1024);2391strbuf_init(&wd.sb_stat,1024);2392strbuf_init(&wd.sb_sha1,1024);2393write_one_dir(untracked->root, &wd);23942395 varint_len =encode_varint(wd.index, varbuf);2396strbuf_add(out, varbuf, varint_len);2397strbuf_addbuf(out, &wd.out);2398ewah_serialize_strbuf(wd.valid, out);2399ewah_serialize_strbuf(wd.check_only, out);2400ewah_serialize_strbuf(wd.sha1_valid, out);2401strbuf_addbuf(out, &wd.sb_stat);2402strbuf_addbuf(out, &wd.sb_sha1);2403strbuf_addch(out,'\0');/* safe guard for string lists */24042405ewah_free(wd.valid);2406ewah_free(wd.check_only);2407ewah_free(wd.sha1_valid);2408strbuf_release(&wd.out);2409strbuf_release(&wd.sb_stat);2410strbuf_release(&wd.sb_sha1);2411}24122413static voidfree_untracked(struct untracked_cache_dir *ucd)2414{2415int i;2416if(!ucd)2417return;2418for(i =0; i < ucd->dirs_nr; i++)2419free_untracked(ucd->dirs[i]);2420for(i =0; i < ucd->untracked_nr; i++)2421free(ucd->untracked[i]);2422free(ucd->untracked);2423free(ucd->dirs);2424free(ucd);2425}24262427voidfree_untracked_cache(struct untracked_cache *uc)2428{2429if(uc)2430free_untracked(uc->root);2431free(uc);2432}24332434struct read_data {2435int index;2436struct untracked_cache_dir **ucd;2437struct ewah_bitmap *check_only;2438struct ewah_bitmap *valid;2439struct ewah_bitmap *sha1_valid;2440const unsigned char*data;2441const unsigned char*end;2442};24432444static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2445{2446 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2447 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2448 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2449 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2450 to->sd_dev =get_be32(&from->sd_dev);2451 to->sd_ino =get_be32(&from->sd_ino);2452 to->sd_uid =get_be32(&from->sd_uid);2453 to->sd_gid =get_be32(&from->sd_gid);2454 to->sd_size =get_be32(&from->sd_size);2455}24562457static intread_one_dir(struct untracked_cache_dir **untracked_,2458struct read_data *rd)2459{2460struct untracked_cache_dir ud, *untracked;2461const unsigned char*next, *data = rd->data, *end = rd->end;2462unsigned int value;2463int i, len;24642465memset(&ud,0,sizeof(ud));24662467 next = data;2468 value =decode_varint(&next);2469if(next > end)2470return-1;2471 ud.recurse =1;2472 ud.untracked_alloc = value;2473 ud.untracked_nr = value;2474if(ud.untracked_nr)2475ALLOC_ARRAY(ud.untracked, ud.untracked_nr);2476 data = next;24772478 next = data;2479 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2480if(next > end)2481return-1;2482ALLOC_ARRAY(ud.dirs, ud.dirs_nr);2483 data = next;24842485 len =strlen((const char*)data);2486 next = data + len +1;2487if(next > rd->end)2488return-1;2489*untracked_ = untracked =xmalloc(st_add(sizeof(*untracked), len));2490memcpy(untracked, &ud,sizeof(ud));2491memcpy(untracked->name, data, len +1);2492 data = next;24932494for(i =0; i < untracked->untracked_nr; i++) {2495 len =strlen((const char*)data);2496 next = data + len +1;2497if(next > rd->end)2498return-1;2499 untracked->untracked[i] =xstrdup((const char*)data);2500 data = next;2501}25022503 rd->ucd[rd->index++] = untracked;2504 rd->data = data;25052506for(i =0; i < untracked->dirs_nr; i++) {2507 len =read_one_dir(untracked->dirs + i, rd);2508if(len <0)2509return-1;2510}2511return0;2512}25132514static voidset_check_only(size_t pos,void*cb)2515{2516struct read_data *rd = cb;2517struct untracked_cache_dir *ud = rd->ucd[pos];2518 ud->check_only =1;2519}25202521static voidread_stat(size_t pos,void*cb)2522{2523struct read_data *rd = cb;2524struct untracked_cache_dir *ud = rd->ucd[pos];2525if(rd->data +sizeof(struct stat_data) > rd->end) {2526 rd->data = rd->end +1;2527return;2528}2529stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2530 rd->data +=sizeof(struct stat_data);2531 ud->valid =1;2532}25332534static voidread_sha1(size_t pos,void*cb)2535{2536struct read_data *rd = cb;2537struct untracked_cache_dir *ud = rd->ucd[pos];2538if(rd->data +20> rd->end) {2539 rd->data = rd->end +1;2540return;2541}2542hashcpy(ud->exclude_sha1, rd->data);2543 rd->data +=20;2544}25452546static voidload_sha1_stat(struct sha1_stat *sha1_stat,2547const struct stat_data *stat,2548const unsigned char*sha1)2549{2550stat_data_from_disk(&sha1_stat->stat, stat);2551hashcpy(sha1_stat->sha1, sha1);2552 sha1_stat->valid =1;2553}25542555struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2556{2557const struct ondisk_untracked_cache *ouc;2558struct untracked_cache *uc;2559struct read_data rd;2560const unsigned char*next = data, *end = (const unsigned char*)data + sz;2561const char*ident;2562int ident_len, len;25632564if(sz <=1|| end[-1] !='\0')2565return NULL;2566 end--;25672568 ident_len =decode_varint(&next);2569if(next + ident_len > end)2570return NULL;2571 ident = (const char*)next;2572 next += ident_len;25732574 ouc = (const struct ondisk_untracked_cache *)next;2575if(next +ouc_size(0) > end)2576return NULL;25772578 uc =xcalloc(1,sizeof(*uc));2579strbuf_init(&uc->ident, ident_len);2580strbuf_add(&uc->ident, ident, ident_len);2581load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2582 ouc->info_exclude_sha1);2583load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2584 ouc->excludes_file_sha1);2585 uc->dir_flags =get_be32(&ouc->dir_flags);2586 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2587/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2588 next +=ouc_size(strlen(ouc->exclude_per_dir));2589if(next >= end)2590goto done2;25912592 len =decode_varint(&next);2593if(next > end || len ==0)2594goto done2;25952596 rd.valid =ewah_new();2597 rd.check_only =ewah_new();2598 rd.sha1_valid =ewah_new();2599 rd.data = next;2600 rd.end = end;2601 rd.index =0;2602ALLOC_ARRAY(rd.ucd, len);26032604if(read_one_dir(&uc->root, &rd) || rd.index != len)2605goto done;26062607 next = rd.data;2608 len =ewah_read_mmap(rd.valid, next, end - next);2609if(len <0)2610goto done;26112612 next += len;2613 len =ewah_read_mmap(rd.check_only, next, end - next);2614if(len <0)2615goto done;26162617 next += len;2618 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2619if(len <0)2620goto done;26212622ewah_each_bit(rd.check_only, set_check_only, &rd);2623 rd.data = next + len;2624ewah_each_bit(rd.valid, read_stat, &rd);2625ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2626 next = rd.data;26272628done:2629free(rd.ucd);2630ewah_free(rd.valid);2631ewah_free(rd.check_only);2632ewah_free(rd.sha1_valid);2633done2:2634if(next != end) {2635free_untracked_cache(uc);2636 uc = NULL;2637}2638return uc;2639}26402641static voidinvalidate_one_directory(struct untracked_cache *uc,2642struct untracked_cache_dir *ucd)2643{2644 uc->dir_invalidated++;2645 ucd->valid =0;2646 ucd->untracked_nr =0;2647}26482649/*2650 * Normally when an entry is added or removed from a directory,2651 * invalidating that directory is enough. No need to touch its2652 * ancestors. When a directory is shown as "foo/bar/" in git-status2653 * however, deleting or adding an entry may have cascading effect.2654 *2655 * Say the "foo/bar/file" has become untracked, we need to tell the2656 * untracked_cache_dir of "foo" that "bar/" is not an untracked2657 * directory any more (because "bar" is managed by foo as an untracked2658 * "file").2659 *2660 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2661 * was the last untracked entry in the entire "foo", we should show2662 * "foo/" instead. Which means we have to invalidate past "bar" up to2663 * "foo".2664 *2665 * This function traverses all directories from root to leaf. If there2666 * is a chance of one of the above cases happening, we invalidate back2667 * to root. Otherwise we just invalidate the leaf. There may be a more2668 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2669 * detect these cases and avoid unnecessary invalidation, for example,2670 * checking for the untracked entry named "bar/" in "foo", but for now2671 * stick to something safe and simple.2672 */2673static intinvalidate_one_component(struct untracked_cache *uc,2674struct untracked_cache_dir *dir,2675const char*path,int len)2676{2677const char*rest =strchr(path,'/');26782679if(rest) {2680int component_len = rest - path;2681struct untracked_cache_dir *d =2682lookup_untracked(uc, dir, path, component_len);2683int ret =2684invalidate_one_component(uc, d, rest +1,2685 len - (component_len +1));2686if(ret)2687invalidate_one_directory(uc, dir);2688return ret;2689}26902691invalidate_one_directory(uc, dir);2692return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2693}26942695voiduntracked_cache_invalidate_path(struct index_state *istate,2696const char*path)2697{2698if(!istate->untracked || !istate->untracked->root)2699return;2700invalidate_one_component(istate->untracked, istate->untracked->root,2701 path,strlen(path));2702}27032704voiduntracked_cache_remove_from_index(struct index_state *istate,2705const char*path)2706{2707untracked_cache_invalidate_path(istate, path);2708}27092710voiduntracked_cache_add_to_index(struct index_state *istate,2711const char*path)2712{2713untracked_cache_invalidate_path(istate, path);2714}