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]->sha1, &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]->sha1); 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, active_cache[pos]->sha1); 759else 760hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 761fill_stat_data(&sha1_stat->stat, &st); 762 sha1_stat->valid =1; 763} 764} 765 766 el->filebuf = buf; 767 768if(skip_utf8_bom(&buf, size)) 769 size -= buf - el->filebuf; 770 771 entry = buf; 772 773for(i =0; i < size; i++) { 774if(buf[i] =='\n') { 775if(entry != buf + i && entry[0] !='#') { 776 buf[i - (i && buf[i-1] =='\r')] =0; 777trim_trailing_spaces(entry); 778add_exclude(entry, base, baselen, el, lineno); 779} 780 lineno++; 781 entry = buf + i +1; 782} 783} 784return0; 785} 786 787intadd_excludes_from_file_to_list(const char*fname,const char*base, 788int baselen,struct exclude_list *el, 789int check_index) 790{ 791returnadd_excludes(fname, base, baselen, el, check_index, NULL); 792} 793 794struct exclude_list *add_exclude_list(struct dir_struct *dir, 795int group_type,const char*src) 796{ 797struct exclude_list *el; 798struct exclude_list_group *group; 799 800 group = &dir->exclude_list_group[group_type]; 801ALLOC_GROW(group->el, group->nr +1, group->alloc); 802 el = &group->el[group->nr++]; 803memset(el,0,sizeof(*el)); 804 el->src = src; 805return el; 806} 807 808/* 809 * Used to set up core.excludesfile and .git/info/exclude lists. 810 */ 811static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 812struct sha1_stat *sha1_stat) 813{ 814struct exclude_list *el; 815/* 816 * catch setup_standard_excludes() that's called before 817 * dir->untracked is assigned. That function behaves 818 * differently when dir->untracked is non-NULL. 819 */ 820if(!dir->untracked) 821 dir->unmanaged_exclude_files++; 822 el =add_exclude_list(dir, EXC_FILE, fname); 823if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 824die("cannot use%sas an exclude file", fname); 825} 826 827voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 828{ 829 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 830add_excludes_from_file_1(dir, fname, NULL); 831} 832 833intmatch_basename(const char*basename,int basenamelen, 834const char*pattern,int prefix,int patternlen, 835unsigned flags) 836{ 837if(prefix == patternlen) { 838if(patternlen == basenamelen && 839!fspathncmp(pattern, basename, basenamelen)) 840return1; 841}else if(flags & EXC_FLAG_ENDSWITH) { 842/* "*literal" matching against "fooliteral" */ 843if(patternlen -1<= basenamelen && 844!fspathncmp(pattern +1, 845 basename + basenamelen - (patternlen -1), 846 patternlen -1)) 847return1; 848}else{ 849if(fnmatch_icase_mem(pattern, patternlen, 850 basename, basenamelen, 8510) ==0) 852return1; 853} 854return0; 855} 856 857intmatch_pathname(const char*pathname,int pathlen, 858const char*base,int baselen, 859const char*pattern,int prefix,int patternlen, 860unsigned flags) 861{ 862const char*name; 863int namelen; 864 865/* 866 * match with FNM_PATHNAME; the pattern has base implicitly 867 * in front of it. 868 */ 869if(*pattern =='/') { 870 pattern++; 871 patternlen--; 872 prefix--; 873} 874 875/* 876 * baselen does not count the trailing slash. base[] may or 877 * may not end with a trailing slash though. 878 */ 879if(pathlen < baselen +1|| 880(baselen && pathname[baselen] !='/') || 881fspathncmp(pathname, base, baselen)) 882return0; 883 884 namelen = baselen ? pathlen - baselen -1: pathlen; 885 name = pathname + pathlen - namelen; 886 887if(prefix) { 888/* 889 * if the non-wildcard part is longer than the 890 * remaining pathname, surely it cannot match. 891 */ 892if(prefix > namelen) 893return0; 894 895if(fspathncmp(pattern, name, prefix)) 896return0; 897 pattern += prefix; 898 patternlen -= prefix; 899 name += prefix; 900 namelen -= prefix; 901 902/* 903 * If the whole pattern did not have a wildcard, 904 * then our prefix match is all we need; we 905 * do not need to call fnmatch at all. 906 */ 907if(!patternlen && !namelen) 908return1; 909} 910 911returnfnmatch_icase_mem(pattern, patternlen, 912 name, namelen, 913 WM_PATHNAME) ==0; 914} 915 916/* 917 * Scan the given exclude list in reverse to see whether pathname 918 * should be ignored. The first match (i.e. the last on the list), if 919 * any, determines the fate. Returns the exclude_list element which 920 * matched, or NULL for undecided. 921 */ 922static struct exclude *last_exclude_matching_from_list(const char*pathname, 923int pathlen, 924const char*basename, 925int*dtype, 926struct exclude_list *el) 927{ 928struct exclude *exc = NULL;/* undecided */ 929int i; 930 931if(!el->nr) 932return NULL;/* undefined */ 933 934for(i = el->nr -1;0<= i; i--) { 935struct exclude *x = el->excludes[i]; 936const char*exclude = x->pattern; 937int prefix = x->nowildcardlen; 938 939if(x->flags & EXC_FLAG_MUSTBEDIR) { 940if(*dtype == DT_UNKNOWN) 941*dtype =get_dtype(NULL, pathname, pathlen); 942if(*dtype != DT_DIR) 943continue; 944} 945 946if(x->flags & EXC_FLAG_NODIR) { 947if(match_basename(basename, 948 pathlen - (basename - pathname), 949 exclude, prefix, x->patternlen, 950 x->flags)) { 951 exc = x; 952break; 953} 954continue; 955} 956 957assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 958if(match_pathname(pathname, pathlen, 959 x->base, x->baselen ? x->baselen -1:0, 960 exclude, prefix, x->patternlen, x->flags)) { 961 exc = x; 962break; 963} 964} 965return exc; 966} 967 968/* 969 * Scan the list and let the last match determine the fate. 970 * Return 1 for exclude, 0 for include and -1 for undecided. 971 */ 972intis_excluded_from_list(const char*pathname, 973int pathlen,const char*basename,int*dtype, 974struct exclude_list *el) 975{ 976struct exclude *exclude; 977 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 978if(exclude) 979return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 980return-1;/* undecided */ 981} 982 983static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 984const char*pathname,int pathlen,const char*basename, 985int*dtype_p) 986{ 987int i, j; 988struct exclude_list_group *group; 989struct exclude *exclude; 990for(i = EXC_CMDL; i <= EXC_FILE; i++) { 991 group = &dir->exclude_list_group[i]; 992for(j = group->nr -1; j >=0; j--) { 993 exclude =last_exclude_matching_from_list( 994 pathname, pathlen, basename, dtype_p, 995&group->el[j]); 996if(exclude) 997return exclude; 998} 999}1000return NULL;1001}10021003/*1004 * Loads the per-directory exclude list for the substring of base1005 * which has a char length of baselen.1006 */1007static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen)1008{1009struct exclude_list_group *group;1010struct exclude_list *el;1011struct exclude_stack *stk = NULL;1012struct untracked_cache_dir *untracked;1013int current;10141015 group = &dir->exclude_list_group[EXC_DIRS];10161017/*1018 * Pop the exclude lists from the EXCL_DIRS exclude_list_group1019 * which originate from directories not in the prefix of the1020 * path being checked.1021 */1022while((stk = dir->exclude_stack) != NULL) {1023if(stk->baselen <= baselen &&1024!strncmp(dir->basebuf.buf, base, stk->baselen))1025break;1026 el = &group->el[dir->exclude_stack->exclude_ix];1027 dir->exclude_stack = stk->prev;1028 dir->exclude = NULL;1029free((char*)el->src);/* see strbuf_detach() below */1030clear_exclude_list(el);1031free(stk);1032 group->nr--;1033}10341035/* Skip traversing into sub directories if the parent is excluded */1036if(dir->exclude)1037return;10381039/*1040 * Lazy initialization. All call sites currently just1041 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1042 * them seems lots of work for little benefit.1043 */1044if(!dir->basebuf.buf)1045strbuf_init(&dir->basebuf, PATH_MAX);10461047/* Read from the parent directories and push them down. */1048 current = stk ? stk->baselen : -1;1049strbuf_setlen(&dir->basebuf, current <0?0: current);1050if(dir->untracked)1051 untracked = stk ? stk->ucd : dir->untracked->root;1052else1053 untracked = NULL;10541055while(current < baselen) {1056const char*cp;1057struct sha1_stat sha1_stat;10581059 stk =xcalloc(1,sizeof(*stk));1060if(current <0) {1061 cp = base;1062 current =0;1063}else{1064 cp =strchr(base + current +1,'/');1065if(!cp)1066die("oops in prep_exclude");1067 cp++;1068 untracked =1069lookup_untracked(dir->untracked, untracked,1070 base + current,1071 cp - base - current);1072}1073 stk->prev = dir->exclude_stack;1074 stk->baselen = cp - base;1075 stk->exclude_ix = group->nr;1076 stk->ucd = untracked;1077 el =add_exclude_list(dir, EXC_DIRS, NULL);1078strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1079assert(stk->baselen == dir->basebuf.len);10801081/* Abort if the directory is excluded */1082if(stk->baselen) {1083int dt = DT_DIR;1084 dir->basebuf.buf[stk->baselen -1] =0;1085 dir->exclude =last_exclude_matching_from_lists(dir,1086 dir->basebuf.buf, stk->baselen -1,1087 dir->basebuf.buf + current, &dt);1088 dir->basebuf.buf[stk->baselen -1] ='/';1089if(dir->exclude &&1090 dir->exclude->flags & EXC_FLAG_NEGATIVE)1091 dir->exclude = NULL;1092if(dir->exclude) {1093 dir->exclude_stack = stk;1094return;1095}1096}10971098/* Try to read per-directory file */1099hashclr(sha1_stat.sha1);1100 sha1_stat.valid =0;1101if(dir->exclude_per_dir &&1102/*1103 * If we know that no files have been added in1104 * this directory (i.e. valid_cached_dir() has1105 * been executed and set untracked->valid) ..1106 */1107(!untracked || !untracked->valid ||1108/*1109 * .. and .gitignore does not exist before1110 * (i.e. null exclude_sha1). Then we can skip1111 * loading .gitignore, which would result in1112 * ENOENT anyway.1113 */1114!is_null_sha1(untracked->exclude_sha1))) {1115/*1116 * dir->basebuf gets reused by the traversal, but we1117 * need fname to remain unchanged to ensure the src1118 * member of each struct exclude correctly1119 * back-references its source file. Other invocations1120 * of add_exclude_list provide stable strings, so we1121 * strbuf_detach() and free() here in the caller.1122 */1123struct strbuf sb = STRBUF_INIT;1124strbuf_addbuf(&sb, &dir->basebuf);1125strbuf_addstr(&sb, dir->exclude_per_dir);1126 el->src =strbuf_detach(&sb, NULL);1127add_excludes(el->src, el->src, stk->baselen, el,1,1128 untracked ? &sha1_stat : NULL);1129}1130/*1131 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1132 * will first be called in valid_cached_dir() then maybe many1133 * times more in last_exclude_matching(). When the cache is1134 * used, last_exclude_matching() will not be called and1135 * reading .gitignore content will be a waste.1136 *1137 * So when it's called by valid_cached_dir() and we can get1138 * .gitignore SHA-1 from the index (i.e. .gitignore is not1139 * modified on work tree), we could delay reading the1140 * .gitignore content until we absolutely need it in1141 * last_exclude_matching(). Be careful about ignore rule1142 * order, though, if you do that.1143 */1144if(untracked &&1145hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1146invalidate_gitignore(dir->untracked, untracked);1147hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1148}1149 dir->exclude_stack = stk;1150 current = stk->baselen;1151}1152strbuf_setlen(&dir->basebuf, baselen);1153}11541155/*1156 * Loads the exclude lists for the directory containing pathname, then1157 * scans all exclude lists to determine whether pathname is excluded.1158 * Returns the exclude_list element which matched, or NULL for1159 * undecided.1160 */1161struct exclude *last_exclude_matching(struct dir_struct *dir,1162const char*pathname,1163int*dtype_p)1164{1165int pathlen =strlen(pathname);1166const char*basename =strrchr(pathname,'/');1167 basename = (basename) ? basename+1: pathname;11681169prep_exclude(dir, pathname, basename-pathname);11701171if(dir->exclude)1172return dir->exclude;11731174returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1175 basename, dtype_p);1176}11771178/*1179 * Loads the exclude lists for the directory containing pathname, then1180 * scans all exclude lists to determine whether pathname is excluded.1181 * Returns 1 if true, otherwise 0.1182 */1183intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1184{1185struct exclude *exclude =1186last_exclude_matching(dir, pathname, dtype_p);1187if(exclude)1188return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1189return0;1190}11911192static struct dir_entry *dir_entry_new(const char*pathname,int len)1193{1194struct dir_entry *ent;11951196FLEX_ALLOC_MEM(ent, name, pathname, len);1197 ent->len = len;1198return ent;1199}12001201static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1202{1203if(cache_file_exists(pathname, len, ignore_case))1204return NULL;12051206ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1207return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1208}12091210struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1211{1212if(!cache_name_is_other(pathname, len))1213return NULL;12141215ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1216return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1217}12181219enum exist_status {1220 index_nonexistent =0,1221 index_directory,1222 index_gitdir1223};12241225/*1226 * Do not use the alphabetically sorted index to look up1227 * the directory name; instead, use the case insensitive1228 * directory hash.1229 */1230static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1231{1232struct cache_entry *ce;12331234if(cache_dir_exists(dirname, len))1235return index_directory;12361237 ce =cache_file_exists(dirname, len, ignore_case);1238if(ce &&S_ISGITLINK(ce->ce_mode))1239return index_gitdir;12401241return index_nonexistent;1242}12431244/*1245 * The index sorts alphabetically by entry name, which1246 * means that a gitlink sorts as '\0' at the end, while1247 * a directory (which is defined not as an entry, but as1248 * the files it contains) will sort with the '/' at the1249 * end.1250 */1251static enum exist_status directory_exists_in_index(const char*dirname,int len)1252{1253int pos;12541255if(ignore_case)1256returndirectory_exists_in_index_icase(dirname, len);12571258 pos =cache_name_pos(dirname, len);1259if(pos <0)1260 pos = -pos-1;1261while(pos < active_nr) {1262const struct cache_entry *ce = active_cache[pos++];1263unsigned char endchar;12641265if(strncmp(ce->name, dirname, len))1266break;1267 endchar = ce->name[len];1268if(endchar >'/')1269break;1270if(endchar =='/')1271return index_directory;1272if(!endchar &&S_ISGITLINK(ce->ce_mode))1273return index_gitdir;1274}1275return index_nonexistent;1276}12771278/*1279 * When we find a directory when traversing the filesystem, we1280 * have three distinct cases:1281 *1282 * - ignore it1283 * - see it as a directory1284 * - recurse into it1285 *1286 * and which one we choose depends on a combination of existing1287 * git index contents and the flags passed into the directory1288 * traversal routine.1289 *1290 * Case 1: If we *already* have entries in the index under that1291 * directory name, we always recurse into the directory to see1292 * all the files.1293 *1294 * Case 2: If we *already* have that directory name as a gitlink,1295 * we always continue to see it as a gitlink, regardless of whether1296 * there is an actual git directory there or not (it might not1297 * be checked out as a subproject!)1298 *1299 * Case 3: if we didn't have it in the index previously, we1300 * have a few sub-cases:1301 *1302 * (a) if "show_other_directories" is true, we show it as1303 * just a directory, unless "hide_empty_directories" is1304 * also true, in which case we need to check if it contains any1305 * untracked and / or ignored files.1306 * (b) if it looks like a git directory, and we don't have1307 * 'no_gitlinks' set we treat it as a gitlink, and show it1308 * as a directory.1309 * (c) otherwise, we recurse into it.1310 */1311static enum path_treatment treat_directory(struct dir_struct *dir,1312struct untracked_cache_dir *untracked,1313const char*dirname,int len,int baselen,int exclude,1314const struct path_simplify *simplify)1315{1316/* The "len-1" is to strip the final '/' */1317switch(directory_exists_in_index(dirname, len-1)) {1318case index_directory:1319return path_recurse;13201321case index_gitdir:1322return path_none;13231324case index_nonexistent:1325if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1326break;1327if(!(dir->flags & DIR_NO_GITLINKS)) {1328unsigned char sha1[20];1329if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1330return path_untracked;1331}1332return path_recurse;1333}13341335/* This is the "show_other_directories" case */13361337if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1338return exclude ? path_excluded : path_untracked;13391340 untracked =lookup_untracked(dir->untracked, untracked,1341 dirname + baselen, len - baselen);1342returnread_directory_recursive(dir, dirname, len,1343 untracked,1, simplify);1344}13451346/*1347 * This is an inexact early pruning of any recursive directory1348 * reading - if the path cannot possibly be in the pathspec,1349 * return true, and we'll skip it early.1350 */1351static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1352{1353if(simplify) {1354for(;;) {1355const char*match = simplify->path;1356int len = simplify->len;13571358if(!match)1359break;1360if(len > pathlen)1361 len = pathlen;1362if(!memcmp(path, match, len))1363return0;1364 simplify++;1365}1366return1;1367}1368return0;1369}13701371/*1372 * This function tells us whether an excluded path matches a1373 * list of "interesting" pathspecs. That is, whether a path matched1374 * by any of the pathspecs could possibly be ignored by excluding1375 * the specified path. This can happen if:1376 *1377 * 1. the path is mentioned explicitly in the pathspec1378 *1379 * 2. the path is a directory prefix of some element in the1380 * pathspec1381 */1382static intexclude_matches_pathspec(const char*path,int len,1383const struct path_simplify *simplify)1384{1385if(simplify) {1386for(; simplify->path; simplify++) {1387if(len == simplify->len1388&& !memcmp(path, simplify->path, len))1389return1;1390if(len < simplify->len1391&& simplify->path[len] =='/'1392&& !memcmp(path, simplify->path, len))1393return1;1394}1395}1396return0;1397}13981399static intget_index_dtype(const char*path,int len)1400{1401int pos;1402const struct cache_entry *ce;14031404 ce =cache_file_exists(path, len,0);1405if(ce) {1406if(!ce_uptodate(ce))1407return DT_UNKNOWN;1408if(S_ISGITLINK(ce->ce_mode))1409return DT_DIR;1410/*1411 * Nobody actually cares about the1412 * difference between DT_LNK and DT_REG1413 */1414return DT_REG;1415}14161417/* Try to look it up as a directory */1418 pos =cache_name_pos(path, len);1419if(pos >=0)1420return DT_UNKNOWN;1421 pos = -pos-1;1422while(pos < active_nr) {1423 ce = active_cache[pos++];1424if(strncmp(ce->name, path, len))1425break;1426if(ce->name[len] >'/')1427break;1428if(ce->name[len] <'/')1429continue;1430if(!ce_uptodate(ce))1431break;/* continue? */1432return DT_DIR;1433}1434return DT_UNKNOWN;1435}14361437static intget_dtype(struct dirent *de,const char*path,int len)1438{1439int dtype = de ?DTYPE(de) : DT_UNKNOWN;1440struct stat st;14411442if(dtype != DT_UNKNOWN)1443return dtype;1444 dtype =get_index_dtype(path, len);1445if(dtype != DT_UNKNOWN)1446return dtype;1447if(lstat(path, &st))1448return dtype;1449if(S_ISREG(st.st_mode))1450return DT_REG;1451if(S_ISDIR(st.st_mode))1452return DT_DIR;1453if(S_ISLNK(st.st_mode))1454return DT_LNK;1455return dtype;1456}14571458static enum path_treatment treat_one_path(struct dir_struct *dir,1459struct untracked_cache_dir *untracked,1460struct strbuf *path,1461int baselen,1462const struct path_simplify *simplify,1463int dtype,struct dirent *de)1464{1465int exclude;1466int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);14671468if(dtype == DT_UNKNOWN)1469 dtype =get_dtype(de, path->buf, path->len);14701471/* Always exclude indexed files */1472if(dtype != DT_DIR && has_path_in_index)1473return path_none;14741475/*1476 * When we are looking at a directory P in the working tree,1477 * there are three cases:1478 *1479 * (1) P exists in the index. Everything inside the directory P in1480 * the working tree needs to go when P is checked out from the1481 * index.1482 *1483 * (2) P does not exist in the index, but there is P/Q in the index.1484 * We know P will stay a directory when we check out the contents1485 * of the index, but we do not know yet if there is a directory1486 * P/Q in the working tree to be killed, so we need to recurse.1487 *1488 * (3) P does not exist in the index, and there is no P/Q in the index1489 * to require P to be a directory, either. Only in this case, we1490 * know that everything inside P will not be killed without1491 * recursing.1492 */1493if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1494(dtype == DT_DIR) &&1495!has_path_in_index &&1496(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1497return path_none;14981499 exclude =is_excluded(dir, path->buf, &dtype);15001501/*1502 * Excluded? If we don't explicitly want to show1503 * ignored files, ignore it1504 */1505if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1506return path_excluded;15071508switch(dtype) {1509default:1510return path_none;1511case DT_DIR:1512strbuf_addch(path,'/');1513returntreat_directory(dir, untracked, path->buf, path->len,1514 baselen, exclude, simplify);1515case DT_REG:1516case DT_LNK:1517return exclude ? path_excluded : path_untracked;1518}1519}15201521static enum path_treatment treat_path_fast(struct dir_struct *dir,1522struct untracked_cache_dir *untracked,1523struct cached_dir *cdir,1524struct strbuf *path,1525int baselen,1526const struct path_simplify *simplify)1527{1528strbuf_setlen(path, baselen);1529if(!cdir->ucd) {1530strbuf_addstr(path, cdir->file);1531return path_untracked;1532}1533strbuf_addstr(path, cdir->ucd->name);1534/* treat_one_path() does this before it calls treat_directory() */1535strbuf_complete(path,'/');1536if(cdir->ucd->check_only)1537/*1538 * check_only is set as a result of treat_directory() getting1539 * to its bottom. Verify again the same set of directories1540 * with check_only set.1541 */1542returnread_directory_recursive(dir, path->buf, path->len,1543 cdir->ucd,1, simplify);1544/*1545 * We get path_recurse in the first run when1546 * directory_exists_in_index() returns index_nonexistent. We1547 * are sure that new changes in the index does not impact the1548 * outcome. Return now.1549 */1550return path_recurse;1551}15521553static enum path_treatment treat_path(struct dir_struct *dir,1554struct untracked_cache_dir *untracked,1555struct cached_dir *cdir,1556struct strbuf *path,1557int baselen,1558const struct path_simplify *simplify)1559{1560int dtype;1561struct dirent *de = cdir->de;15621563if(!de)1564returntreat_path_fast(dir, untracked, cdir, path,1565 baselen, simplify);1566if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1567return path_none;1568strbuf_setlen(path, baselen);1569strbuf_addstr(path, de->d_name);1570if(simplify_away(path->buf, path->len, simplify))1571return path_none;15721573 dtype =DTYPE(de);1574returntreat_one_path(dir, untracked, path, baselen, simplify, dtype, de);1575}15761577static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1578{1579if(!dir)1580return;1581ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1582 dir->untracked_alloc);1583 dir->untracked[dir->untracked_nr++] =xstrdup(name);1584}15851586static intvalid_cached_dir(struct dir_struct *dir,1587struct untracked_cache_dir *untracked,1588struct strbuf *path,1589int check_only)1590{1591struct stat st;15921593if(!untracked)1594return0;15951596if(stat(path->len ? path->buf :".", &st)) {1597invalidate_directory(dir->untracked, untracked);1598memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1599return0;1600}1601if(!untracked->valid ||1602match_stat_data_racy(&the_index, &untracked->stat_data, &st)) {1603if(untracked->valid)1604invalidate_directory(dir->untracked, untracked);1605fill_stat_data(&untracked->stat_data, &st);1606return0;1607}16081609if(untracked->check_only != !!check_only) {1610invalidate_directory(dir->untracked, untracked);1611return0;1612}16131614/*1615 * prep_exclude will be called eventually on this directory,1616 * but it's called much later in last_exclude_matching(). We1617 * need it now to determine the validity of the cache for this1618 * path. The next calls will be nearly no-op, the way1619 * prep_exclude() is designed.1620 */1621if(path->len && path->buf[path->len -1] !='/') {1622strbuf_addch(path,'/');1623prep_exclude(dir, path->buf, path->len);1624strbuf_setlen(path, path->len -1);1625}else1626prep_exclude(dir, path->buf, path->len);16271628/* hopefully prep_exclude() haven't invalidated this entry... */1629return untracked->valid;1630}16311632static intopen_cached_dir(struct cached_dir *cdir,1633struct dir_struct *dir,1634struct untracked_cache_dir *untracked,1635struct strbuf *path,1636int check_only)1637{1638memset(cdir,0,sizeof(*cdir));1639 cdir->untracked = untracked;1640if(valid_cached_dir(dir, untracked, path, check_only))1641return0;1642 cdir->fdir =opendir(path->len ? path->buf :".");1643if(dir->untracked)1644 dir->untracked->dir_opened++;1645if(!cdir->fdir)1646return-1;1647return0;1648}16491650static intread_cached_dir(struct cached_dir *cdir)1651{1652if(cdir->fdir) {1653 cdir->de =readdir(cdir->fdir);1654if(!cdir->de)1655return-1;1656return0;1657}1658while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1659struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1660if(!d->recurse) {1661 cdir->nr_dirs++;1662continue;1663}1664 cdir->ucd = d;1665 cdir->nr_dirs++;1666return0;1667}1668 cdir->ucd = NULL;1669if(cdir->nr_files < cdir->untracked->untracked_nr) {1670struct untracked_cache_dir *d = cdir->untracked;1671 cdir->file = d->untracked[cdir->nr_files++];1672return0;1673}1674return-1;1675}16761677static voidclose_cached_dir(struct cached_dir *cdir)1678{1679if(cdir->fdir)1680closedir(cdir->fdir);1681/*1682 * We have gone through this directory and found no untracked1683 * entries. Mark it valid.1684 */1685if(cdir->untracked) {1686 cdir->untracked->valid =1;1687 cdir->untracked->recurse =1;1688}1689}16901691/*1692 * Read a directory tree. We currently ignore anything but1693 * directories, regular files and symlinks. That's because git1694 * doesn't handle them at all yet. Maybe that will change some1695 * day.1696 *1697 * Also, we ignore the name ".git" (even if it is not a directory).1698 * That likely will not change.1699 *1700 * Returns the most significant path_treatment value encountered in the scan.1701 */1702static enum path_treatment read_directory_recursive(struct dir_struct *dir,1703const char*base,int baselen,1704struct untracked_cache_dir *untracked,int check_only,1705const struct path_simplify *simplify)1706{1707struct cached_dir cdir;1708enum path_treatment state, subdir_state, dir_state = path_none;1709struct strbuf path = STRBUF_INIT;17101711strbuf_add(&path, base, baselen);17121713if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1714goto out;17151716if(untracked)1717 untracked->check_only = !!check_only;17181719while(!read_cached_dir(&cdir)) {1720/* check how the file or directory should be treated */1721 state =treat_path(dir, untracked, &cdir, &path, baselen, simplify);17221723if(state > dir_state)1724 dir_state = state;17251726/* recurse into subdir if instructed by treat_path */1727if(state == path_recurse) {1728struct untracked_cache_dir *ud;1729 ud =lookup_untracked(dir->untracked, untracked,1730 path.buf + baselen,1731 path.len - baselen);1732 subdir_state =1733read_directory_recursive(dir, path.buf, path.len,1734 ud, check_only, simplify);1735if(subdir_state > dir_state)1736 dir_state = subdir_state;1737}17381739if(check_only) {1740/* abort early if maximum state has been reached */1741if(dir_state == path_untracked) {1742if(cdir.fdir)1743add_untracked(untracked, path.buf + baselen);1744break;1745}1746/* skip the dir_add_* part */1747continue;1748}17491750/* add the path to the appropriate result list */1751switch(state) {1752case path_excluded:1753if(dir->flags & DIR_SHOW_IGNORED)1754dir_add_name(dir, path.buf, path.len);1755else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1756((dir->flags & DIR_COLLECT_IGNORED) &&1757exclude_matches_pathspec(path.buf, path.len,1758 simplify)))1759dir_add_ignored(dir, path.buf, path.len);1760break;17611762case path_untracked:1763if(dir->flags & DIR_SHOW_IGNORED)1764break;1765dir_add_name(dir, path.buf, path.len);1766if(cdir.fdir)1767add_untracked(untracked, path.buf + baselen);1768break;17691770default:1771break;1772}1773}1774close_cached_dir(&cdir);1775 out:1776strbuf_release(&path);17771778return dir_state;1779}17801781static intcmp_name(const void*p1,const void*p2)1782{1783const struct dir_entry *e1 = *(const struct dir_entry **)p1;1784const struct dir_entry *e2 = *(const struct dir_entry **)p2;17851786returnname_compare(e1->name, e1->len, e2->name, e2->len);1787}17881789static struct path_simplify *create_simplify(const char**pathspec)1790{1791int nr, alloc =0;1792struct path_simplify *simplify = NULL;17931794if(!pathspec)1795return NULL;17961797for(nr =0; ; nr++) {1798const char*match;1799ALLOC_GROW(simplify, nr +1, alloc);1800 match = *pathspec++;1801if(!match)1802break;1803 simplify[nr].path = match;1804 simplify[nr].len =simple_length(match);1805}1806 simplify[nr].path = NULL;1807 simplify[nr].len =0;1808return simplify;1809}18101811static voidfree_simplify(struct path_simplify *simplify)1812{1813free(simplify);1814}18151816static inttreat_leading_path(struct dir_struct *dir,1817const char*path,int len,1818const struct path_simplify *simplify)1819{1820struct strbuf sb = STRBUF_INIT;1821int baselen, rc =0;1822const char*cp;1823int old_flags = dir->flags;18241825while(len && path[len -1] =='/')1826 len--;1827if(!len)1828return1;1829 baselen =0;1830 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1831while(1) {1832 cp = path + baselen + !!baselen;1833 cp =memchr(cp,'/', path + len - cp);1834if(!cp)1835 baselen = len;1836else1837 baselen = cp - path;1838strbuf_setlen(&sb,0);1839strbuf_add(&sb, path, baselen);1840if(!is_directory(sb.buf))1841break;1842if(simplify_away(sb.buf, sb.len, simplify))1843break;1844if(treat_one_path(dir, NULL, &sb, baselen, simplify,1845 DT_DIR, NULL) == path_none)1846break;/* do not recurse into it */1847if(len <= baselen) {1848 rc =1;1849break;/* finished checking */1850}1851}1852strbuf_release(&sb);1853 dir->flags = old_flags;1854return rc;1855}18561857static const char*get_ident_string(void)1858{1859static struct strbuf sb = STRBUF_INIT;1860struct utsname uts;18611862if(sb.len)1863return sb.buf;1864if(uname(&uts) <0)1865die_errno(_("failed to get kernel name and information"));1866strbuf_addf(&sb,"Location%s, system%s",get_git_work_tree(),1867 uts.sysname);1868return sb.buf;1869}18701871static intident_in_untracked(const struct untracked_cache *uc)1872{1873/*1874 * Previous git versions may have saved many NUL separated1875 * strings in the "ident" field, but it is insane to manage1876 * many locations, so just take care of the first one.1877 */18781879return!strcmp(uc->ident.buf,get_ident_string());1880}18811882static voidset_untracked_ident(struct untracked_cache *uc)1883{1884strbuf_reset(&uc->ident);1885strbuf_addstr(&uc->ident,get_ident_string());18861887/*1888 * This strbuf used to contain a list of NUL separated1889 * strings, so save NUL too for backward compatibility.1890 */1891strbuf_addch(&uc->ident,0);1892}18931894static voidnew_untracked_cache(struct index_state *istate)1895{1896struct untracked_cache *uc =xcalloc(1,sizeof(*uc));1897strbuf_init(&uc->ident,100);1898 uc->exclude_per_dir =".gitignore";1899/* should be the same flags used by git-status */1900 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;1901set_untracked_ident(uc);1902 istate->untracked = uc;1903 istate->cache_changed |= UNTRACKED_CHANGED;1904}19051906voidadd_untracked_cache(struct index_state *istate)1907{1908if(!istate->untracked) {1909new_untracked_cache(istate);1910}else{1911if(!ident_in_untracked(istate->untracked)) {1912free_untracked_cache(istate->untracked);1913new_untracked_cache(istate);1914}1915}1916}19171918voidremove_untracked_cache(struct index_state *istate)1919{1920if(istate->untracked) {1921free_untracked_cache(istate->untracked);1922 istate->untracked = NULL;1923 istate->cache_changed |= UNTRACKED_CHANGED;1924}1925}19261927static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1928int base_len,1929const struct pathspec *pathspec)1930{1931struct untracked_cache_dir *root;19321933if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))1934return NULL;19351936/*1937 * We only support $GIT_DIR/info/exclude and core.excludesfile1938 * as the global ignore rule files. Any other additions1939 * (e.g. from command line) invalidate the cache. This1940 * condition also catches running setup_standard_excludes()1941 * before setting dir->untracked!1942 */1943if(dir->unmanaged_exclude_files)1944return NULL;19451946/*1947 * Optimize for the main use case only: whole-tree git1948 * status. More work involved in treat_leading_path() if we1949 * use cache on just a subset of the worktree. pathspec1950 * support could make the matter even worse.1951 */1952if(base_len || (pathspec && pathspec->nr))1953return NULL;19541955/* Different set of flags may produce different results */1956if(dir->flags != dir->untracked->dir_flags ||1957/*1958 * See treat_directory(), case index_nonexistent. Without1959 * this flag, we may need to also cache .git file content1960 * for the resolve_gitlink_ref() call, which we don't.1961 */1962!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1963/* We don't support collecting ignore files */1964(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1965 DIR_COLLECT_IGNORED)))1966return NULL;19671968/*1969 * If we use .gitignore in the cache and now you change it to1970 * .gitexclude, everything will go wrong.1971 */1972if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1973strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1974return NULL;19751976/*1977 * EXC_CMDL is not considered in the cache. If people set it,1978 * skip the cache.1979 */1980if(dir->exclude_list_group[EXC_CMDL].nr)1981return NULL;19821983if(!ident_in_untracked(dir->untracked)) {1984warning(_("Untracked cache is disabled on this system or location."));1985return NULL;1986}19871988if(!dir->untracked->root) {1989const int len =sizeof(*dir->untracked->root);1990 dir->untracked->root =xmalloc(len);1991memset(dir->untracked->root,0, len);1992}19931994/* Validate $GIT_DIR/info/exclude and core.excludesfile */1995 root = dir->untracked->root;1996if(hashcmp(dir->ss_info_exclude.sha1,1997 dir->untracked->ss_info_exclude.sha1)) {1998invalidate_gitignore(dir->untracked, root);1999 dir->untracked->ss_info_exclude = dir->ss_info_exclude;2000}2001if(hashcmp(dir->ss_excludes_file.sha1,2002 dir->untracked->ss_excludes_file.sha1)) {2003invalidate_gitignore(dir->untracked, root);2004 dir->untracked->ss_excludes_file = dir->ss_excludes_file;2005}20062007/* Make sure this directory is not dropped out at saving phase */2008 root->recurse =1;2009return root;2010}20112012intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)2013{2014struct path_simplify *simplify;2015struct untracked_cache_dir *untracked;20162017/*2018 * Check out create_simplify()2019 */2020if(pathspec)2021GUARD_PATHSPEC(pathspec,2022 PATHSPEC_FROMTOP |2023 PATHSPEC_MAXDEPTH |2024 PATHSPEC_LITERAL |2025 PATHSPEC_GLOB |2026 PATHSPEC_ICASE |2027 PATHSPEC_EXCLUDE);20282029if(has_symlink_leading_path(path, len))2030return dir->nr;20312032/*2033 * exclude patterns are treated like positive ones in2034 * create_simplify. Usually exclude patterns should be a2035 * subset of positive ones, which has no impacts on2036 * create_simplify().2037 */2038 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);2039 untracked =validate_untracked_cache(dir, len, pathspec);2040if(!untracked)2041/*2042 * make sure untracked cache code path is disabled,2043 * e.g. prep_exclude()2044 */2045 dir->untracked = NULL;2046if(!len ||treat_leading_path(dir, path, len, simplify))2047read_directory_recursive(dir, path, len, untracked,0, simplify);2048free_simplify(simplify);2049qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);2050qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);2051if(dir->untracked) {2052static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);2053trace_printf_key(&trace_untracked_stats,2054"node creation:%u\n"2055"gitignore invalidation:%u\n"2056"directory invalidation:%u\n"2057"opendir:%u\n",2058 dir->untracked->dir_created,2059 dir->untracked->gitignore_invalidated,2060 dir->untracked->dir_invalidated,2061 dir->untracked->dir_opened);2062if(dir->untracked == the_index.untracked &&2063(dir->untracked->dir_opened ||2064 dir->untracked->gitignore_invalidated ||2065 dir->untracked->dir_invalidated))2066 the_index.cache_changed |= UNTRACKED_CHANGED;2067if(dir->untracked != the_index.untracked) {2068free(dir->untracked);2069 dir->untracked = NULL;2070}2071}2072return dir->nr;2073}20742075intfile_exists(const char*f)2076{2077struct stat sb;2078returnlstat(f, &sb) ==0;2079}20802081static intcmp_icase(char a,char b)2082{2083if(a == b)2084return0;2085if(ignore_case)2086returntoupper(a) -toupper(b);2087return a - b;2088}20892090/*2091 * Given two normalized paths (a trailing slash is ok), if subdir is2092 * outside dir, return -1. Otherwise return the offset in subdir that2093 * can be used as relative path to dir.2094 */2095intdir_inside_of(const char*subdir,const char*dir)2096{2097int offset =0;20982099assert(dir && subdir && *dir && *subdir);21002101while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2102 dir++;2103 subdir++;2104 offset++;2105}21062107/* hel[p]/me vs hel[l]/yeah */2108if(*dir && *subdir)2109return-1;21102111if(!*subdir)2112return!*dir ? offset : -1;/* same dir */21132114/* foo/[b]ar vs foo/[] */2115if(is_dir_sep(dir[-1]))2116returnis_dir_sep(subdir[-1]) ? offset : -1;21172118/* foo[/]bar vs foo[] */2119returnis_dir_sep(*subdir) ? offset +1: -1;2120}21212122intis_inside_dir(const char*dir)2123{2124char*cwd;2125int rc;21262127if(!dir)2128return0;21292130 cwd =xgetcwd();2131 rc = (dir_inside_of(cwd, dir) >=0);2132free(cwd);2133return rc;2134}21352136intis_empty_dir(const char*path)2137{2138DIR*dir =opendir(path);2139struct dirent *e;2140int ret =1;21412142if(!dir)2143return0;21442145while((e =readdir(dir)) != NULL)2146if(!is_dot_or_dotdot(e->d_name)) {2147 ret =0;2148break;2149}21502151closedir(dir);2152return ret;2153}21542155static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2156{2157DIR*dir;2158struct dirent *e;2159int ret =0, original_len = path->len, len, kept_down =0;2160int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2161int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2162unsigned char submodule_head[20];21632164if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2165!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2166/* Do not descend and nuke a nested git work tree. */2167if(kept_up)2168*kept_up =1;2169return0;2170}21712172 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2173 dir =opendir(path->buf);2174if(!dir) {2175if(errno == ENOENT)2176return keep_toplevel ? -1:0;2177else if(errno == EACCES && !keep_toplevel)2178/*2179 * An empty dir could be removable even if it2180 * is unreadable:2181 */2182returnrmdir(path->buf);2183else2184return-1;2185}2186strbuf_complete(path,'/');21872188 len = path->len;2189while((e =readdir(dir)) != NULL) {2190struct stat st;2191if(is_dot_or_dotdot(e->d_name))2192continue;21932194strbuf_setlen(path, len);2195strbuf_addstr(path, e->d_name);2196if(lstat(path->buf, &st)) {2197if(errno == ENOENT)2198/*2199 * file disappeared, which is what we2200 * wanted anyway2201 */2202continue;2203/* fall thru */2204}else if(S_ISDIR(st.st_mode)) {2205if(!remove_dir_recurse(path, flag, &kept_down))2206continue;/* happy */2207}else if(!only_empty &&2208(!unlink(path->buf) || errno == ENOENT)) {2209continue;/* happy, too */2210}22112212/* path too long, stat fails, or non-directory still exists */2213 ret = -1;2214break;2215}2216closedir(dir);22172218strbuf_setlen(path, original_len);2219if(!ret && !keep_toplevel && !kept_down)2220 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2221else if(kept_up)2222/*2223 * report the uplevel that it is not an error that we2224 * did not rmdir() our directory.2225 */2226*kept_up = !ret;2227return ret;2228}22292230intremove_dir_recursively(struct strbuf *path,int flag)2231{2232returnremove_dir_recurse(path, flag, NULL);2233}22342235staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")22362237voidsetup_standard_excludes(struct dir_struct *dir)2238{2239const char*path;22402241 dir->exclude_per_dir =".gitignore";22422243/* core.excludefile defaulting to $XDG_HOME/git/ignore */2244if(!excludes_file)2245 excludes_file =xdg_config_home("ignore");2246if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2247add_excludes_from_file_1(dir, excludes_file,2248 dir->untracked ? &dir->ss_excludes_file : NULL);22492250/* per repository user preference */2251 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}22562257intremove_path(const char*name)2258{2259char*slash;22602261if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2262return-1;22632264 slash =strrchr(name,'/');2265if(slash) {2266char*dirs =xstrdup(name);2267 slash = dirs + (slash - name);2268do{2269*slash ='\0';2270}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2271free(dirs);2272}2273return0;2274}22752276/*2277 * Frees memory within dir which was allocated for exclude lists and2278 * the exclude_stack. Does not free dir itself.2279 */2280voidclear_directory(struct dir_struct *dir)2281{2282int i, j;2283struct exclude_list_group *group;2284struct exclude_list *el;2285struct exclude_stack *stk;22862287for(i = EXC_CMDL; i <= EXC_FILE; i++) {2288 group = &dir->exclude_list_group[i];2289for(j =0; j < group->nr; j++) {2290 el = &group->el[j];2291if(i == EXC_DIRS)2292free((char*)el->src);2293clear_exclude_list(el);2294}2295free(group->el);2296}22972298 stk = dir->exclude_stack;2299while(stk) {2300struct exclude_stack *prev = stk->prev;2301free(stk);2302 stk = prev;2303}2304strbuf_release(&dir->basebuf);2305}23062307struct ondisk_untracked_cache {2308struct stat_data info_exclude_stat;2309struct stat_data excludes_file_stat;2310uint32_t dir_flags;2311unsigned char info_exclude_sha1[20];2312unsigned char excludes_file_sha1[20];2313char exclude_per_dir[FLEX_ARRAY];2314};23152316#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)23172318struct write_data {2319int index;/* number of written untracked_cache_dir */2320struct ewah_bitmap *check_only;/* from untracked_cache_dir */2321struct ewah_bitmap *valid;/* from untracked_cache_dir */2322struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2323struct strbuf out;2324struct strbuf sb_stat;2325struct strbuf sb_sha1;2326};23272328static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2329{2330 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2331 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2332 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2333 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2334 to->sd_dev =htonl(from->sd_dev);2335 to->sd_ino =htonl(from->sd_ino);2336 to->sd_uid =htonl(from->sd_uid);2337 to->sd_gid =htonl(from->sd_gid);2338 to->sd_size =htonl(from->sd_size);2339}23402341static voidwrite_one_dir(struct untracked_cache_dir *untracked,2342struct write_data *wd)2343{2344struct stat_data stat_data;2345struct strbuf *out = &wd->out;2346unsigned char intbuf[16];2347unsigned int intlen, value;2348int i = wd->index++;23492350/*2351 * untracked_nr should be reset whenever valid is clear, but2352 * for safety..2353 */2354if(!untracked->valid) {2355 untracked->untracked_nr =0;2356 untracked->check_only =0;2357}23582359if(untracked->check_only)2360ewah_set(wd->check_only, i);2361if(untracked->valid) {2362ewah_set(wd->valid, i);2363stat_data_to_disk(&stat_data, &untracked->stat_data);2364strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2365}2366if(!is_null_sha1(untracked->exclude_sha1)) {2367ewah_set(wd->sha1_valid, i);2368strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2369}23702371 intlen =encode_varint(untracked->untracked_nr, intbuf);2372strbuf_add(out, intbuf, intlen);23732374/* skip non-recurse directories */2375for(i =0, value =0; i < untracked->dirs_nr; i++)2376if(untracked->dirs[i]->recurse)2377 value++;2378 intlen =encode_varint(value, intbuf);2379strbuf_add(out, intbuf, intlen);23802381strbuf_add(out, untracked->name,strlen(untracked->name) +1);23822383for(i =0; i < untracked->untracked_nr; i++)2384strbuf_add(out, untracked->untracked[i],2385strlen(untracked->untracked[i]) +1);23862387for(i =0; i < untracked->dirs_nr; i++)2388if(untracked->dirs[i]->recurse)2389write_one_dir(untracked->dirs[i], wd);2390}23912392voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2393{2394struct ondisk_untracked_cache *ouc;2395struct write_data wd;2396unsigned char varbuf[16];2397int varint_len;2398size_t len =strlen(untracked->exclude_per_dir);23992400FLEX_ALLOC_MEM(ouc, exclude_per_dir, untracked->exclude_per_dir, len);2401stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2402stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2403hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2404hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2405 ouc->dir_flags =htonl(untracked->dir_flags);24062407 varint_len =encode_varint(untracked->ident.len, varbuf);2408strbuf_add(out, varbuf, varint_len);2409strbuf_addbuf(out, &untracked->ident);24102411strbuf_add(out, ouc,ouc_size(len));2412free(ouc);2413 ouc = NULL;24142415if(!untracked->root) {2416 varint_len =encode_varint(0, varbuf);2417strbuf_add(out, varbuf, varint_len);2418return;2419}24202421 wd.index =0;2422 wd.check_only =ewah_new();2423 wd.valid =ewah_new();2424 wd.sha1_valid =ewah_new();2425strbuf_init(&wd.out,1024);2426strbuf_init(&wd.sb_stat,1024);2427strbuf_init(&wd.sb_sha1,1024);2428write_one_dir(untracked->root, &wd);24292430 varint_len =encode_varint(wd.index, varbuf);2431strbuf_add(out, varbuf, varint_len);2432strbuf_addbuf(out, &wd.out);2433ewah_serialize_strbuf(wd.valid, out);2434ewah_serialize_strbuf(wd.check_only, out);2435ewah_serialize_strbuf(wd.sha1_valid, out);2436strbuf_addbuf(out, &wd.sb_stat);2437strbuf_addbuf(out, &wd.sb_sha1);2438strbuf_addch(out,'\0');/* safe guard for string lists */24392440ewah_free(wd.valid);2441ewah_free(wd.check_only);2442ewah_free(wd.sha1_valid);2443strbuf_release(&wd.out);2444strbuf_release(&wd.sb_stat);2445strbuf_release(&wd.sb_sha1);2446}24472448static voidfree_untracked(struct untracked_cache_dir *ucd)2449{2450int i;2451if(!ucd)2452return;2453for(i =0; i < ucd->dirs_nr; i++)2454free_untracked(ucd->dirs[i]);2455for(i =0; i < ucd->untracked_nr; i++)2456free(ucd->untracked[i]);2457free(ucd->untracked);2458free(ucd->dirs);2459free(ucd);2460}24612462voidfree_untracked_cache(struct untracked_cache *uc)2463{2464if(uc)2465free_untracked(uc->root);2466free(uc);2467}24682469struct read_data {2470int index;2471struct untracked_cache_dir **ucd;2472struct ewah_bitmap *check_only;2473struct ewah_bitmap *valid;2474struct ewah_bitmap *sha1_valid;2475const unsigned char*data;2476const unsigned char*end;2477};24782479static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2480{2481 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2482 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2483 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2484 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2485 to->sd_dev =get_be32(&from->sd_dev);2486 to->sd_ino =get_be32(&from->sd_ino);2487 to->sd_uid =get_be32(&from->sd_uid);2488 to->sd_gid =get_be32(&from->sd_gid);2489 to->sd_size =get_be32(&from->sd_size);2490}24912492static intread_one_dir(struct untracked_cache_dir **untracked_,2493struct read_data *rd)2494{2495struct untracked_cache_dir ud, *untracked;2496const unsigned char*next, *data = rd->data, *end = rd->end;2497unsigned int value;2498int i, len;24992500memset(&ud,0,sizeof(ud));25012502 next = data;2503 value =decode_varint(&next);2504if(next > end)2505return-1;2506 ud.recurse =1;2507 ud.untracked_alloc = value;2508 ud.untracked_nr = value;2509if(ud.untracked_nr)2510ALLOC_ARRAY(ud.untracked, ud.untracked_nr);2511 data = next;25122513 next = data;2514 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2515if(next > end)2516return-1;2517ALLOC_ARRAY(ud.dirs, ud.dirs_nr);2518 data = next;25192520 len =strlen((const char*)data);2521 next = data + len +1;2522if(next > rd->end)2523return-1;2524*untracked_ = untracked =xmalloc(st_add(sizeof(*untracked), len));2525memcpy(untracked, &ud,sizeof(ud));2526memcpy(untracked->name, data, len +1);2527 data = next;25282529for(i =0; i < untracked->untracked_nr; i++) {2530 len =strlen((const char*)data);2531 next = data + len +1;2532if(next > rd->end)2533return-1;2534 untracked->untracked[i] =xstrdup((const char*)data);2535 data = next;2536}25372538 rd->ucd[rd->index++] = untracked;2539 rd->data = data;25402541for(i =0; i < untracked->dirs_nr; i++) {2542 len =read_one_dir(untracked->dirs + i, rd);2543if(len <0)2544return-1;2545}2546return0;2547}25482549static voidset_check_only(size_t pos,void*cb)2550{2551struct read_data *rd = cb;2552struct untracked_cache_dir *ud = rd->ucd[pos];2553 ud->check_only =1;2554}25552556static voidread_stat(size_t pos,void*cb)2557{2558struct read_data *rd = cb;2559struct untracked_cache_dir *ud = rd->ucd[pos];2560if(rd->data +sizeof(struct stat_data) > rd->end) {2561 rd->data = rd->end +1;2562return;2563}2564stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2565 rd->data +=sizeof(struct stat_data);2566 ud->valid =1;2567}25682569static voidread_sha1(size_t pos,void*cb)2570{2571struct read_data *rd = cb;2572struct untracked_cache_dir *ud = rd->ucd[pos];2573if(rd->data +20> rd->end) {2574 rd->data = rd->end +1;2575return;2576}2577hashcpy(ud->exclude_sha1, rd->data);2578 rd->data +=20;2579}25802581static voidload_sha1_stat(struct sha1_stat *sha1_stat,2582const struct stat_data *stat,2583const unsigned char*sha1)2584{2585stat_data_from_disk(&sha1_stat->stat, stat);2586hashcpy(sha1_stat->sha1, sha1);2587 sha1_stat->valid =1;2588}25892590struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2591{2592const struct ondisk_untracked_cache *ouc;2593struct untracked_cache *uc;2594struct read_data rd;2595const unsigned char*next = data, *end = (const unsigned char*)data + sz;2596const char*ident;2597int ident_len, len;25982599if(sz <=1|| end[-1] !='\0')2600return NULL;2601 end--;26022603 ident_len =decode_varint(&next);2604if(next + ident_len > end)2605return NULL;2606 ident = (const char*)next;2607 next += ident_len;26082609 ouc = (const struct ondisk_untracked_cache *)next;2610if(next +ouc_size(0) > end)2611return NULL;26122613 uc =xcalloc(1,sizeof(*uc));2614strbuf_init(&uc->ident, ident_len);2615strbuf_add(&uc->ident, ident, ident_len);2616load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2617 ouc->info_exclude_sha1);2618load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2619 ouc->excludes_file_sha1);2620 uc->dir_flags =get_be32(&ouc->dir_flags);2621 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2622/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2623 next +=ouc_size(strlen(ouc->exclude_per_dir));2624if(next >= end)2625goto done2;26262627 len =decode_varint(&next);2628if(next > end || len ==0)2629goto done2;26302631 rd.valid =ewah_new();2632 rd.check_only =ewah_new();2633 rd.sha1_valid =ewah_new();2634 rd.data = next;2635 rd.end = end;2636 rd.index =0;2637ALLOC_ARRAY(rd.ucd, len);26382639if(read_one_dir(&uc->root, &rd) || rd.index != len)2640goto done;26412642 next = rd.data;2643 len =ewah_read_mmap(rd.valid, next, end - next);2644if(len <0)2645goto done;26462647 next += len;2648 len =ewah_read_mmap(rd.check_only, next, end - next);2649if(len <0)2650goto done;26512652 next += len;2653 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2654if(len <0)2655goto done;26562657ewah_each_bit(rd.check_only, set_check_only, &rd);2658 rd.data = next + len;2659ewah_each_bit(rd.valid, read_stat, &rd);2660ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2661 next = rd.data;26622663done:2664free(rd.ucd);2665ewah_free(rd.valid);2666ewah_free(rd.check_only);2667ewah_free(rd.sha1_valid);2668done2:2669if(next != end) {2670free_untracked_cache(uc);2671 uc = NULL;2672}2673return uc;2674}26752676static voidinvalidate_one_directory(struct untracked_cache *uc,2677struct untracked_cache_dir *ucd)2678{2679 uc->dir_invalidated++;2680 ucd->valid =0;2681 ucd->untracked_nr =0;2682}26832684/*2685 * Normally when an entry is added or removed from a directory,2686 * invalidating that directory is enough. No need to touch its2687 * ancestors. When a directory is shown as "foo/bar/" in git-status2688 * however, deleting or adding an entry may have cascading effect.2689 *2690 * Say the "foo/bar/file" has become untracked, we need to tell the2691 * untracked_cache_dir of "foo" that "bar/" is not an untracked2692 * directory any more (because "bar" is managed by foo as an untracked2693 * "file").2694 *2695 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2696 * was the last untracked entry in the entire "foo", we should show2697 * "foo/" instead. Which means we have to invalidate past "bar" up to2698 * "foo".2699 *2700 * This function traverses all directories from root to leaf. If there2701 * is a chance of one of the above cases happening, we invalidate back2702 * to root. Otherwise we just invalidate the leaf. There may be a more2703 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2704 * detect these cases and avoid unnecessary invalidation, for example,2705 * checking for the untracked entry named "bar/" in "foo", but for now2706 * stick to something safe and simple.2707 */2708static intinvalidate_one_component(struct untracked_cache *uc,2709struct untracked_cache_dir *dir,2710const char*path,int len)2711{2712const char*rest =strchr(path,'/');27132714if(rest) {2715int component_len = rest - path;2716struct untracked_cache_dir *d =2717lookup_untracked(uc, dir, path, component_len);2718int ret =2719invalidate_one_component(uc, d, rest +1,2720 len - (component_len +1));2721if(ret)2722invalidate_one_directory(uc, dir);2723return ret;2724}27252726invalidate_one_directory(uc, dir);2727return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2728}27292730voiduntracked_cache_invalidate_path(struct index_state *istate,2731const char*path)2732{2733if(!istate->untracked || !istate->untracked->root)2734return;2735invalidate_one_component(istate->untracked, istate->untracked->root,2736 path,strlen(path));2737}27382739voiduntracked_cache_remove_from_index(struct index_state *istate,2740const char*path)2741{2742untracked_cache_invalidate_path(istate, path);2743}27442745voiduntracked_cache_add_to_index(struct index_state *istate,2746const char*path)2747{2748untracked_cache_invalidate_path(istate, path);2749}