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 56/* helper string functions with support for the ignore_case flag */ 57intstrcmp_icase(const char*a,const char*b) 58{ 59return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 60} 61 62intstrncmp_icase(const char*a,const char*b,size_t count) 63{ 64return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 65} 66 67intfnmatch_icase(const char*pattern,const char*string,int flags) 68{ 69returnwildmatch(pattern, string, 70 flags | (ignore_case ? WM_CASEFOLD :0), 71 NULL); 72} 73 74intgit_fnmatch(const struct pathspec_item *item, 75const char*pattern,const char*string, 76int prefix) 77{ 78if(prefix >0) { 79if(ps_strncmp(item, pattern, string, prefix)) 80return WM_NOMATCH; 81 pattern += prefix; 82 string += prefix; 83} 84if(item->flags & PATHSPEC_ONESTAR) { 85int pattern_len =strlen(++pattern); 86int string_len =strlen(string); 87return string_len < pattern_len || 88ps_strcmp(item, pattern, 89 string + string_len - pattern_len); 90} 91if(item->magic & PATHSPEC_GLOB) 92returnwildmatch(pattern, string, 93 WM_PATHNAME | 94(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 95 NULL); 96else 97/* wildmatch has not learned no FNM_PATHNAME mode yet */ 98returnwildmatch(pattern, string, 99 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 100 NULL); 101} 102 103static intfnmatch_icase_mem(const char*pattern,int patternlen, 104const char*string,int stringlen, 105int flags) 106{ 107int match_status; 108struct strbuf pat_buf = STRBUF_INIT; 109struct strbuf str_buf = STRBUF_INIT; 110const char*use_pat = pattern; 111const char*use_str = string; 112 113if(pattern[patternlen]) { 114strbuf_add(&pat_buf, pattern, patternlen); 115 use_pat = pat_buf.buf; 116} 117if(string[stringlen]) { 118strbuf_add(&str_buf, string, stringlen); 119 use_str = str_buf.buf; 120} 121 122if(ignore_case) 123 flags |= WM_CASEFOLD; 124 match_status =wildmatch(use_pat, use_str, flags, NULL); 125 126strbuf_release(&pat_buf); 127strbuf_release(&str_buf); 128 129return match_status; 130} 131 132static size_tcommon_prefix_len(const struct pathspec *pathspec) 133{ 134int n; 135size_t max =0; 136 137/* 138 * ":(icase)path" is treated as a pathspec full of 139 * wildcard. In other words, only prefix is considered common 140 * prefix. If the pathspec is abc/foo abc/bar, running in 141 * subdir xyz, the common prefix is still xyz, not xuz/abc as 142 * in non-:(icase). 143 */ 144GUARD_PATHSPEC(pathspec, 145 PATHSPEC_FROMTOP | 146 PATHSPEC_MAXDEPTH | 147 PATHSPEC_LITERAL | 148 PATHSPEC_GLOB | 149 PATHSPEC_ICASE | 150 PATHSPEC_EXCLUDE); 151 152for(n =0; n < pathspec->nr; n++) { 153size_t i =0, len =0, item_len; 154if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 155continue; 156if(pathspec->items[n].magic & PATHSPEC_ICASE) 157 item_len = pathspec->items[n].prefix; 158else 159 item_len = pathspec->items[n].nowildcard_len; 160while(i < item_len && (n ==0|| i < max)) { 161char c = pathspec->items[n].match[i]; 162if(c != pathspec->items[0].match[i]) 163break; 164if(c =='/') 165 len = i +1; 166 i++; 167} 168if(n ==0|| len < max) { 169 max = len; 170if(!max) 171break; 172} 173} 174return max; 175} 176 177/* 178 * Returns a copy of the longest leading path common among all 179 * pathspecs. 180 */ 181char*common_prefix(const struct pathspec *pathspec) 182{ 183unsigned long len =common_prefix_len(pathspec); 184 185return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 186} 187 188intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 189{ 190size_t len; 191 192/* 193 * Calculate common prefix for the pathspec, and 194 * use that to optimize the directory walk 195 */ 196 len =common_prefix_len(pathspec); 197 198/* Read the directory and prune it */ 199read_directory(dir, pathspec->nr ? pathspec->_raw[0] :"", len, pathspec); 200return len; 201} 202 203intwithin_depth(const char*name,int namelen, 204int depth,int max_depth) 205{ 206const char*cp = name, *cpe = name + namelen; 207 208while(cp < cpe) { 209if(*cp++ !='/') 210continue; 211 depth++; 212if(depth > max_depth) 213return0; 214} 215return1; 216} 217 218#define DO_MATCH_EXCLUDE 1 219#define DO_MATCH_DIRECTORY 2 220 221/* 222 * Does 'match' match the given name? 223 * A match is found if 224 * 225 * (1) the 'match' string is leading directory of 'name', or 226 * (2) the 'match' string is a wildcard and matches 'name', or 227 * (3) the 'match' string is exactly the same as 'name'. 228 * 229 * and the return value tells which case it was. 230 * 231 * It returns 0 when there is no match. 232 */ 233static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 234const char*name,int namelen,unsigned flags) 235{ 236/* name/namelen has prefix cut off by caller */ 237const char*match = item->match + prefix; 238int matchlen = item->len - prefix; 239 240/* 241 * The normal call pattern is: 242 * 1. prefix = common_prefix_len(ps); 243 * 2. prune something, or fill_directory 244 * 3. match_pathspec() 245 * 246 * 'prefix' at #1 may be shorter than the command's prefix and 247 * it's ok for #2 to match extra files. Those extras will be 248 * trimmed at #3. 249 * 250 * Suppose the pathspec is 'foo' and '../bar' running from 251 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 252 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 253 * user does not want XYZ/foo, only the "foo" part should be 254 * case-insensitive. We need to filter out XYZ/foo here. In 255 * other words, we do not trust the caller on comparing the 256 * prefix part when :(icase) is involved. We do exact 257 * comparison ourselves. 258 * 259 * Normally the caller (common_prefix_len() in fact) does 260 * _exact_ matching on name[-prefix+1..-1] and we do not need 261 * to check that part. Be defensive and check it anyway, in 262 * case common_prefix_len is changed, or a new caller is 263 * introduced that does not use common_prefix_len. 264 * 265 * If the penalty turns out too high when prefix is really 266 * long, maybe change it to 267 * strncmp(match, name, item->prefix - prefix) 268 */ 269if(item->prefix && (item->magic & PATHSPEC_ICASE) && 270strncmp(item->match, name - prefix, item->prefix)) 271return0; 272 273/* If the match was just the prefix, we matched */ 274if(!*match) 275return MATCHED_RECURSIVELY; 276 277if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 278if(matchlen == namelen) 279return MATCHED_EXACTLY; 280 281if(match[matchlen-1] =='/'|| name[matchlen] =='/') 282return MATCHED_RECURSIVELY; 283}else if((flags & DO_MATCH_DIRECTORY) && 284 match[matchlen -1] =='/'&& 285 namelen == matchlen -1&& 286!ps_strncmp(item, match, name, namelen)) 287return MATCHED_EXACTLY; 288 289if(item->nowildcard_len < item->len && 290!git_fnmatch(item, match, name, 291 item->nowildcard_len - prefix)) 292return MATCHED_FNMATCH; 293 294return0; 295} 296 297/* 298 * Given a name and a list of pathspecs, returns the nature of the 299 * closest (i.e. most specific) match of the name to any of the 300 * pathspecs. 301 * 302 * The caller typically calls this multiple times with the same 303 * pathspec and seen[] array but with different name/namelen 304 * (e.g. entries from the index) and is interested in seeing if and 305 * how each pathspec matches all the names it calls this function 306 * with. A mark is left in the seen[] array for each pathspec element 307 * indicating the closest type of match that element achieved, so if 308 * seen[n] remains zero after multiple invocations, that means the nth 309 * pathspec did not match any names, which could indicate that the 310 * user mistyped the nth pathspec. 311 */ 312static intdo_match_pathspec(const struct pathspec *ps, 313const char*name,int namelen, 314int prefix,char*seen, 315unsigned flags) 316{ 317int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 318 319GUARD_PATHSPEC(ps, 320 PATHSPEC_FROMTOP | 321 PATHSPEC_MAXDEPTH | 322 PATHSPEC_LITERAL | 323 PATHSPEC_GLOB | 324 PATHSPEC_ICASE | 325 PATHSPEC_EXCLUDE); 326 327if(!ps->nr) { 328if(!ps->recursive || 329!(ps->magic & PATHSPEC_MAXDEPTH) || 330 ps->max_depth == -1) 331return MATCHED_RECURSIVELY; 332 333if(within_depth(name, namelen,0, ps->max_depth)) 334return MATCHED_EXACTLY; 335else 336return0; 337} 338 339 name += prefix; 340 namelen -= prefix; 341 342for(i = ps->nr -1; i >=0; i--) { 343int how; 344 345if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 346( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 347continue; 348 349if(seen && seen[i] == MATCHED_EXACTLY) 350continue; 351/* 352 * Make exclude patterns optional and never report 353 * "pathspec ':(exclude)foo' matches no files" 354 */ 355if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 356 seen[i] = MATCHED_FNMATCH; 357 how =match_pathspec_item(ps->items+i, prefix, name, 358 namelen, flags); 359if(ps->recursive && 360(ps->magic & PATHSPEC_MAXDEPTH) && 361 ps->max_depth != -1&& 362 how && how != MATCHED_FNMATCH) { 363int len = ps->items[i].len; 364if(name[len] =='/') 365 len++; 366if(within_depth(name+len, namelen-len,0, ps->max_depth)) 367 how = MATCHED_EXACTLY; 368else 369 how =0; 370} 371if(how) { 372if(retval < how) 373 retval = how; 374if(seen && seen[i] < how) 375 seen[i] = how; 376} 377} 378return retval; 379} 380 381intmatch_pathspec(const struct pathspec *ps, 382const char*name,int namelen, 383int prefix,char*seen,int is_dir) 384{ 385int positive, negative; 386unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 387 positive =do_match_pathspec(ps, name, namelen, 388 prefix, seen, flags); 389if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 390return positive; 391 negative =do_match_pathspec(ps, name, namelen, 392 prefix, seen, 393 flags | DO_MATCH_EXCLUDE); 394return negative ?0: positive; 395} 396 397intreport_path_error(const char*ps_matched, 398const struct pathspec *pathspec, 399const char*prefix) 400{ 401/* 402 * Make sure all pathspec matched; otherwise it is an error. 403 */ 404int num, errors =0; 405for(num =0; num < pathspec->nr; num++) { 406int other, found_dup; 407 408if(ps_matched[num]) 409continue; 410/* 411 * The caller might have fed identical pathspec 412 * twice. Do not barf on such a mistake. 413 * FIXME: parse_pathspec should have eliminated 414 * duplicate pathspec. 415 */ 416for(found_dup = other =0; 417!found_dup && other < pathspec->nr; 418 other++) { 419if(other == num || !ps_matched[other]) 420continue; 421if(!strcmp(pathspec->items[other].original, 422 pathspec->items[num].original)) 423/* 424 * Ok, we have a match already. 425 */ 426 found_dup =1; 427} 428if(found_dup) 429continue; 430 431error("pathspec '%s' did not match any file(s) known to git.", 432 pathspec->items[num].original); 433 errors++; 434} 435return errors; 436} 437 438/* 439 * Return the length of the "simple" part of a path match limiter. 440 */ 441intsimple_length(const char*match) 442{ 443int len = -1; 444 445for(;;) { 446unsigned char c = *match++; 447 len++; 448if(c =='\0'||is_glob_special(c)) 449return len; 450} 451} 452 453intno_wildcard(const char*string) 454{ 455return string[simple_length(string)] =='\0'; 456} 457 458voidparse_exclude_pattern(const char**pattern, 459int*patternlen, 460int*flags, 461int*nowildcardlen) 462{ 463const char*p = *pattern; 464size_t i, len; 465 466*flags =0; 467if(*p =='!') { 468*flags |= EXC_FLAG_NEGATIVE; 469 p++; 470} 471 len =strlen(p); 472if(len && p[len -1] =='/') { 473 len--; 474*flags |= EXC_FLAG_MUSTBEDIR; 475} 476for(i =0; i < len; i++) { 477if(p[i] =='/') 478break; 479} 480if(i == len) 481*flags |= EXC_FLAG_NODIR; 482*nowildcardlen =simple_length(p); 483/* 484 * we should have excluded the trailing slash from 'p' too, 485 * but that's one more allocation. Instead just make sure 486 * nowildcardlen does not exceed real patternlen 487 */ 488if(*nowildcardlen > len) 489*nowildcardlen = len; 490if(*p =='*'&&no_wildcard(p +1)) 491*flags |= EXC_FLAG_ENDSWITH; 492*pattern = p; 493*patternlen = len; 494} 495 496voidadd_exclude(const char*string,const char*base, 497int baselen,struct exclude_list *el,int srcpos) 498{ 499struct exclude *x; 500int patternlen; 501int flags; 502int nowildcardlen; 503 504parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 505if(flags & EXC_FLAG_MUSTBEDIR) { 506FLEXPTR_ALLOC_MEM(x, pattern, string, patternlen); 507}else{ 508 x =xmalloc(sizeof(*x)); 509 x->pattern = string; 510} 511 x->patternlen = patternlen; 512 x->nowildcardlen = nowildcardlen; 513 x->base = base; 514 x->baselen = baselen; 515 x->flags = flags; 516 x->srcpos = srcpos; 517ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 518 el->excludes[el->nr++] = x; 519 x->el = el; 520} 521 522static void*read_skip_worktree_file_from_index(const char*path,size_t*size, 523struct sha1_stat *sha1_stat) 524{ 525int pos, len; 526unsigned long sz; 527enum object_type type; 528void*data; 529 530 len =strlen(path); 531 pos =cache_name_pos(path, len); 532if(pos <0) 533return NULL; 534if(!ce_skip_worktree(active_cache[pos])) 535return NULL; 536 data =read_sha1_file(active_cache[pos]->sha1, &type, &sz); 537if(!data || type != OBJ_BLOB) { 538free(data); 539return NULL; 540} 541*size =xsize_t(sz); 542if(sha1_stat) { 543memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 544hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 545} 546return data; 547} 548 549/* 550 * Frees memory within el which was allocated for exclude patterns and 551 * the file buffer. Does not free el itself. 552 */ 553voidclear_exclude_list(struct exclude_list *el) 554{ 555int i; 556 557for(i =0; i < el->nr; i++) 558free(el->excludes[i]); 559free(el->excludes); 560free(el->filebuf); 561 562memset(el,0,sizeof(*el)); 563} 564 565static voidtrim_trailing_spaces(char*buf) 566{ 567char*p, *last_space = NULL; 568 569for(p = buf; *p; p++) 570switch(*p) { 571case' ': 572if(!last_space) 573 last_space = p; 574break; 575case'\\': 576 p++; 577if(!*p) 578return; 579/* fallthrough */ 580default: 581 last_space = NULL; 582} 583 584if(last_space) 585*last_space ='\0'; 586} 587 588/* 589 * Given a subdirectory name and "dir" of the current directory, 590 * search the subdir in "dir" and return it, or create a new one if it 591 * does not exist in "dir". 592 * 593 * If "name" has the trailing slash, it'll be excluded in the search. 594 */ 595static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 596struct untracked_cache_dir *dir, 597const char*name,int len) 598{ 599int first, last; 600struct untracked_cache_dir *d; 601if(!dir) 602return NULL; 603if(len && name[len -1] =='/') 604 len--; 605 first =0; 606 last = dir->dirs_nr; 607while(last > first) { 608int cmp, next = (last + first) >>1; 609 d = dir->dirs[next]; 610 cmp =strncmp(name, d->name, len); 611if(!cmp &&strlen(d->name) > len) 612 cmp = -1; 613if(!cmp) 614return d; 615if(cmp <0) { 616 last = next; 617continue; 618} 619 first = next+1; 620} 621 622 uc->dir_created++; 623FLEX_ALLOC_MEM(d, name, name, len); 624 625ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 626memmove(dir->dirs + first +1, dir->dirs + first, 627(dir->dirs_nr - first) *sizeof(*dir->dirs)); 628 dir->dirs_nr++; 629 dir->dirs[first] = d; 630return d; 631} 632 633static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 634{ 635int i; 636 dir->valid =0; 637 dir->untracked_nr =0; 638for(i =0; i < dir->dirs_nr; i++) 639do_invalidate_gitignore(dir->dirs[i]); 640} 641 642static voidinvalidate_gitignore(struct untracked_cache *uc, 643struct untracked_cache_dir *dir) 644{ 645 uc->gitignore_invalidated++; 646do_invalidate_gitignore(dir); 647} 648 649static voidinvalidate_directory(struct untracked_cache *uc, 650struct untracked_cache_dir *dir) 651{ 652int i; 653 uc->dir_invalidated++; 654 dir->valid =0; 655 dir->untracked_nr =0; 656for(i =0; i < dir->dirs_nr; i++) 657 dir->dirs[i]->recurse =0; 658} 659 660/* 661 * Given a file with name "fname", read it (either from disk, or from 662 * the index if "check_index" is non-zero), parse it and store the 663 * exclude rules in "el". 664 * 665 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 666 * stat data from disk (only valid if add_excludes returns zero). If 667 * ss_valid is non-zero, "ss" must contain good value as input. 668 */ 669static intadd_excludes(const char*fname,const char*base,int baselen, 670struct exclude_list *el,int check_index, 671struct sha1_stat *sha1_stat) 672{ 673struct stat st; 674int fd, i, lineno =1; 675size_t size =0; 676char*buf, *entry; 677 678 fd =open(fname, O_RDONLY); 679if(fd <0||fstat(fd, &st) <0) { 680if(errno != ENOENT) 681warn_on_inaccessible(fname); 682if(0<= fd) 683close(fd); 684if(!check_index || 685(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 686return-1; 687if(size ==0) { 688free(buf); 689return0; 690} 691if(buf[size-1] !='\n') { 692 buf =xrealloc(buf,st_add(size,1)); 693 buf[size++] ='\n'; 694} 695}else{ 696 size =xsize_t(st.st_size); 697if(size ==0) { 698if(sha1_stat) { 699fill_stat_data(&sha1_stat->stat, &st); 700hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 701 sha1_stat->valid =1; 702} 703close(fd); 704return0; 705} 706 buf =xmallocz(size); 707if(read_in_full(fd, buf, size) != size) { 708free(buf); 709close(fd); 710return-1; 711} 712 buf[size++] ='\n'; 713close(fd); 714if(sha1_stat) { 715int pos; 716if(sha1_stat->valid && 717!match_stat_data_racy(&the_index, &sha1_stat->stat, &st)) 718;/* no content change, ss->sha1 still good */ 719else if(check_index && 720(pos =cache_name_pos(fname,strlen(fname))) >=0&& 721!ce_stage(active_cache[pos]) && 722ce_uptodate(active_cache[pos]) && 723!would_convert_to_git(fname)) 724hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 725else 726hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 727fill_stat_data(&sha1_stat->stat, &st); 728 sha1_stat->valid =1; 729} 730} 731 732 el->filebuf = buf; 733 734if(skip_utf8_bom(&buf, size)) 735 size -= buf - el->filebuf; 736 737 entry = buf; 738 739for(i =0; i < size; i++) { 740if(buf[i] =='\n') { 741if(entry != buf + i && entry[0] !='#') { 742 buf[i - (i && buf[i-1] =='\r')] =0; 743trim_trailing_spaces(entry); 744add_exclude(entry, base, baselen, el, lineno); 745} 746 lineno++; 747 entry = buf + i +1; 748} 749} 750return0; 751} 752 753intadd_excludes_from_file_to_list(const char*fname,const char*base, 754int baselen,struct exclude_list *el, 755int check_index) 756{ 757returnadd_excludes(fname, base, baselen, el, check_index, NULL); 758} 759 760struct exclude_list *add_exclude_list(struct dir_struct *dir, 761int group_type,const char*src) 762{ 763struct exclude_list *el; 764struct exclude_list_group *group; 765 766 group = &dir->exclude_list_group[group_type]; 767ALLOC_GROW(group->el, group->nr +1, group->alloc); 768 el = &group->el[group->nr++]; 769memset(el,0,sizeof(*el)); 770 el->src = src; 771return el; 772} 773 774/* 775 * Used to set up core.excludesfile and .git/info/exclude lists. 776 */ 777static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 778struct sha1_stat *sha1_stat) 779{ 780struct exclude_list *el; 781/* 782 * catch setup_standard_excludes() that's called before 783 * dir->untracked is assigned. That function behaves 784 * differently when dir->untracked is non-NULL. 785 */ 786if(!dir->untracked) 787 dir->unmanaged_exclude_files++; 788 el =add_exclude_list(dir, EXC_FILE, fname); 789if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 790die("cannot use%sas an exclude file", fname); 791} 792 793voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 794{ 795 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 796add_excludes_from_file_1(dir, fname, NULL); 797} 798 799intmatch_basename(const char*basename,int basenamelen, 800const char*pattern,int prefix,int patternlen, 801int flags) 802{ 803if(prefix == patternlen) { 804if(patternlen == basenamelen && 805!strncmp_icase(pattern, basename, basenamelen)) 806return1; 807}else if(flags & EXC_FLAG_ENDSWITH) { 808/* "*literal" matching against "fooliteral" */ 809if(patternlen -1<= basenamelen && 810!strncmp_icase(pattern +1, 811 basename + basenamelen - (patternlen -1), 812 patternlen -1)) 813return1; 814}else{ 815if(fnmatch_icase_mem(pattern, patternlen, 816 basename, basenamelen, 8170) ==0) 818return1; 819} 820return0; 821} 822 823intmatch_pathname(const char*pathname,int pathlen, 824const char*base,int baselen, 825const char*pattern,int prefix,int patternlen, 826int flags) 827{ 828const char*name; 829int namelen; 830 831/* 832 * match with FNM_PATHNAME; the pattern has base implicitly 833 * in front of it. 834 */ 835if(*pattern =='/') { 836 pattern++; 837 patternlen--; 838 prefix--; 839} 840 841/* 842 * baselen does not count the trailing slash. base[] may or 843 * may not end with a trailing slash though. 844 */ 845if(pathlen < baselen +1|| 846(baselen && pathname[baselen] !='/') || 847strncmp_icase(pathname, base, baselen)) 848return0; 849 850 namelen = baselen ? pathlen - baselen -1: pathlen; 851 name = pathname + pathlen - namelen; 852 853if(prefix) { 854/* 855 * if the non-wildcard part is longer than the 856 * remaining pathname, surely it cannot match. 857 */ 858if(prefix > namelen) 859return0; 860 861if(strncmp_icase(pattern, name, prefix)) 862return0; 863 pattern += prefix; 864 patternlen -= prefix; 865 name += prefix; 866 namelen -= prefix; 867 868/* 869 * If the whole pattern did not have a wildcard, 870 * then our prefix match is all we need; we 871 * do not need to call fnmatch at all. 872 */ 873if(!patternlen && !namelen) 874return1; 875} 876 877returnfnmatch_icase_mem(pattern, patternlen, 878 name, namelen, 879 WM_PATHNAME) ==0; 880} 881 882/* 883 * Scan the given exclude list in reverse to see whether pathname 884 * should be ignored. The first match (i.e. the last on the list), if 885 * any, determines the fate. Returns the exclude_list element which 886 * matched, or NULL for undecided. 887 */ 888static struct exclude *last_exclude_matching_from_list(const char*pathname, 889int pathlen, 890const char*basename, 891int*dtype, 892struct exclude_list *el) 893{ 894struct exclude *exc = NULL;/* undecided */ 895int i; 896 897if(!el->nr) 898return NULL;/* undefined */ 899 900for(i = el->nr -1;0<= i; i--) { 901struct exclude *x = el->excludes[i]; 902const char*exclude = x->pattern; 903int prefix = x->nowildcardlen; 904 905if(x->flags & EXC_FLAG_MUSTBEDIR) { 906if(*dtype == DT_UNKNOWN) 907*dtype =get_dtype(NULL, pathname, pathlen); 908if(*dtype != DT_DIR) 909continue; 910} 911 912if(x->flags & EXC_FLAG_NODIR) { 913if(match_basename(basename, 914 pathlen - (basename - pathname), 915 exclude, prefix, x->patternlen, 916 x->flags)) { 917 exc = x; 918break; 919} 920continue; 921} 922 923assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 924if(match_pathname(pathname, pathlen, 925 x->base, x->baselen ? x->baselen -1:0, 926 exclude, prefix, x->patternlen, x->flags)) { 927 exc = x; 928break; 929} 930} 931return exc; 932} 933 934/* 935 * Scan the list and let the last match determine the fate. 936 * Return 1 for exclude, 0 for include and -1 for undecided. 937 */ 938intis_excluded_from_list(const char*pathname, 939int pathlen,const char*basename,int*dtype, 940struct exclude_list *el) 941{ 942struct exclude *exclude; 943 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 944if(exclude) 945return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 946return-1;/* undecided */ 947} 948 949static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 950const char*pathname,int pathlen,const char*basename, 951int*dtype_p) 952{ 953int i, j; 954struct exclude_list_group *group; 955struct exclude *exclude; 956for(i = EXC_CMDL; i <= EXC_FILE; i++) { 957 group = &dir->exclude_list_group[i]; 958for(j = group->nr -1; j >=0; j--) { 959 exclude =last_exclude_matching_from_list( 960 pathname, pathlen, basename, dtype_p, 961&group->el[j]); 962if(exclude) 963return exclude; 964} 965} 966return NULL; 967} 968 969/* 970 * Loads the per-directory exclude list for the substring of base 971 * which has a char length of baselen. 972 */ 973static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen) 974{ 975struct exclude_list_group *group; 976struct exclude_list *el; 977struct exclude_stack *stk = NULL; 978struct untracked_cache_dir *untracked; 979int current; 980 981 group = &dir->exclude_list_group[EXC_DIRS]; 982 983/* 984 * Pop the exclude lists from the EXCL_DIRS exclude_list_group 985 * which originate from directories not in the prefix of the 986 * path being checked. 987 */ 988while((stk = dir->exclude_stack) != NULL) { 989if(stk->baselen <= baselen && 990!strncmp(dir->basebuf.buf, base, stk->baselen)) 991break; 992 el = &group->el[dir->exclude_stack->exclude_ix]; 993 dir->exclude_stack = stk->prev; 994 dir->exclude = NULL; 995free((char*)el->src);/* see strbuf_detach() below */ 996clear_exclude_list(el); 997free(stk); 998 group->nr--; 999}10001001/* Skip traversing into sub directories if the parent is excluded */1002if(dir->exclude)1003return;10041005/*1006 * Lazy initialization. All call sites currently just1007 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1008 * them seems lots of work for little benefit.1009 */1010if(!dir->basebuf.buf)1011strbuf_init(&dir->basebuf, PATH_MAX);10121013/* Read from the parent directories and push them down. */1014 current = stk ? stk->baselen : -1;1015strbuf_setlen(&dir->basebuf, current <0?0: current);1016if(dir->untracked)1017 untracked = stk ? stk->ucd : dir->untracked->root;1018else1019 untracked = NULL;10201021while(current < baselen) {1022const char*cp;1023struct sha1_stat sha1_stat;10241025 stk =xcalloc(1,sizeof(*stk));1026if(current <0) {1027 cp = base;1028 current =0;1029}else{1030 cp =strchr(base + current +1,'/');1031if(!cp)1032die("oops in prep_exclude");1033 cp++;1034 untracked =1035lookup_untracked(dir->untracked, untracked,1036 base + current,1037 cp - base - current);1038}1039 stk->prev = dir->exclude_stack;1040 stk->baselen = cp - base;1041 stk->exclude_ix = group->nr;1042 stk->ucd = untracked;1043 el =add_exclude_list(dir, EXC_DIRS, NULL);1044strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1045assert(stk->baselen == dir->basebuf.len);10461047/* Abort if the directory is excluded */1048if(stk->baselen) {1049int dt = DT_DIR;1050 dir->basebuf.buf[stk->baselen -1] =0;1051 dir->exclude =last_exclude_matching_from_lists(dir,1052 dir->basebuf.buf, stk->baselen -1,1053 dir->basebuf.buf + current, &dt);1054 dir->basebuf.buf[stk->baselen -1] ='/';1055if(dir->exclude &&1056 dir->exclude->flags & EXC_FLAG_NEGATIVE)1057 dir->exclude = NULL;1058if(dir->exclude) {1059 dir->exclude_stack = stk;1060return;1061}1062}10631064/* Try to read per-directory file */1065hashclr(sha1_stat.sha1);1066 sha1_stat.valid =0;1067if(dir->exclude_per_dir &&1068/*1069 * If we know that no files have been added in1070 * this directory (i.e. valid_cached_dir() has1071 * been executed and set untracked->valid) ..1072 */1073(!untracked || !untracked->valid ||1074/*1075 * .. and .gitignore does not exist before1076 * (i.e. null exclude_sha1). Then we can skip1077 * loading .gitignore, which would result in1078 * ENOENT anyway.1079 */1080!is_null_sha1(untracked->exclude_sha1))) {1081/*1082 * dir->basebuf gets reused by the traversal, but we1083 * need fname to remain unchanged to ensure the src1084 * member of each struct exclude correctly1085 * back-references its source file. Other invocations1086 * of add_exclude_list provide stable strings, so we1087 * strbuf_detach() and free() here in the caller.1088 */1089struct strbuf sb = STRBUF_INIT;1090strbuf_addbuf(&sb, &dir->basebuf);1091strbuf_addstr(&sb, dir->exclude_per_dir);1092 el->src =strbuf_detach(&sb, NULL);1093add_excludes(el->src, el->src, stk->baselen, el,1,1094 untracked ? &sha1_stat : NULL);1095}1096/*1097 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1098 * will first be called in valid_cached_dir() then maybe many1099 * times more in last_exclude_matching(). When the cache is1100 * used, last_exclude_matching() will not be called and1101 * reading .gitignore content will be a waste.1102 *1103 * So when it's called by valid_cached_dir() and we can get1104 * .gitignore SHA-1 from the index (i.e. .gitignore is not1105 * modified on work tree), we could delay reading the1106 * .gitignore content until we absolutely need it in1107 * last_exclude_matching(). Be careful about ignore rule1108 * order, though, if you do that.1109 */1110if(untracked &&1111hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1112invalidate_gitignore(dir->untracked, untracked);1113hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1114}1115 dir->exclude_stack = stk;1116 current = stk->baselen;1117}1118strbuf_setlen(&dir->basebuf, baselen);1119}11201121/*1122 * Loads the exclude lists for the directory containing pathname, then1123 * scans all exclude lists to determine whether pathname is excluded.1124 * Returns the exclude_list element which matched, or NULL for1125 * undecided.1126 */1127struct exclude *last_exclude_matching(struct dir_struct *dir,1128const char*pathname,1129int*dtype_p)1130{1131int pathlen =strlen(pathname);1132const char*basename =strrchr(pathname,'/');1133 basename = (basename) ? basename+1: pathname;11341135prep_exclude(dir, pathname, basename-pathname);11361137if(dir->exclude)1138return dir->exclude;11391140returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1141 basename, dtype_p);1142}11431144/*1145 * Loads the exclude lists for the directory containing pathname, then1146 * scans all exclude lists to determine whether pathname is excluded.1147 * Returns 1 if true, otherwise 0.1148 */1149intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1150{1151struct exclude *exclude =1152last_exclude_matching(dir, pathname, dtype_p);1153if(exclude)1154return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1155return0;1156}11571158static struct dir_entry *dir_entry_new(const char*pathname,int len)1159{1160struct dir_entry *ent;11611162FLEX_ALLOC_MEM(ent, name, pathname, len);1163 ent->len = len;1164return ent;1165}11661167static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1168{1169if(cache_file_exists(pathname, len, ignore_case))1170return NULL;11711172ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1173return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1174}11751176struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1177{1178if(!cache_name_is_other(pathname, len))1179return NULL;11801181ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1182return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1183}11841185enum exist_status {1186 index_nonexistent =0,1187 index_directory,1188 index_gitdir1189};11901191/*1192 * Do not use the alphabetically sorted index to look up1193 * the directory name; instead, use the case insensitive1194 * directory hash.1195 */1196static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1197{1198struct cache_entry *ce;11991200if(cache_dir_exists(dirname, len))1201return index_directory;12021203 ce =cache_file_exists(dirname, len, ignore_case);1204if(ce &&S_ISGITLINK(ce->ce_mode))1205return index_gitdir;12061207return index_nonexistent;1208}12091210/*1211 * The index sorts alphabetically by entry name, which1212 * means that a gitlink sorts as '\0' at the end, while1213 * a directory (which is defined not as an entry, but as1214 * the files it contains) will sort with the '/' at the1215 * end.1216 */1217static enum exist_status directory_exists_in_index(const char*dirname,int len)1218{1219int pos;12201221if(ignore_case)1222returndirectory_exists_in_index_icase(dirname, len);12231224 pos =cache_name_pos(dirname, len);1225if(pos <0)1226 pos = -pos-1;1227while(pos < active_nr) {1228const struct cache_entry *ce = active_cache[pos++];1229unsigned char endchar;12301231if(strncmp(ce->name, dirname, len))1232break;1233 endchar = ce->name[len];1234if(endchar >'/')1235break;1236if(endchar =='/')1237return index_directory;1238if(!endchar &&S_ISGITLINK(ce->ce_mode))1239return index_gitdir;1240}1241return index_nonexistent;1242}12431244/*1245 * When we find a directory when traversing the filesystem, we1246 * have three distinct cases:1247 *1248 * - ignore it1249 * - see it as a directory1250 * - recurse into it1251 *1252 * and which one we choose depends on a combination of existing1253 * git index contents and the flags passed into the directory1254 * traversal routine.1255 *1256 * Case 1: If we *already* have entries in the index under that1257 * directory name, we always recurse into the directory to see1258 * all the files.1259 *1260 * Case 2: If we *already* have that directory name as a gitlink,1261 * we always continue to see it as a gitlink, regardless of whether1262 * there is an actual git directory there or not (it might not1263 * be checked out as a subproject!)1264 *1265 * Case 3: if we didn't have it in the index previously, we1266 * have a few sub-cases:1267 *1268 * (a) if "show_other_directories" is true, we show it as1269 * just a directory, unless "hide_empty_directories" is1270 * also true, in which case we need to check if it contains any1271 * untracked and / or ignored files.1272 * (b) if it looks like a git directory, and we don't have1273 * 'no_gitlinks' set we treat it as a gitlink, and show it1274 * as a directory.1275 * (c) otherwise, we recurse into it.1276 */1277static enum path_treatment treat_directory(struct dir_struct *dir,1278struct untracked_cache_dir *untracked,1279const char*dirname,int len,int baselen,int exclude,1280const struct path_simplify *simplify)1281{1282/* The "len-1" is to strip the final '/' */1283switch(directory_exists_in_index(dirname, len-1)) {1284case index_directory:1285return path_recurse;12861287case index_gitdir:1288return path_none;12891290case index_nonexistent:1291if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1292break;1293if(!(dir->flags & DIR_NO_GITLINKS)) {1294unsigned char sha1[20];1295if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1296return path_untracked;1297}1298return path_recurse;1299}13001301/* This is the "show_other_directories" case */13021303if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1304return exclude ? path_excluded : path_untracked;13051306 untracked =lookup_untracked(dir->untracked, untracked,1307 dirname + baselen, len - baselen);1308returnread_directory_recursive(dir, dirname, len,1309 untracked,1, simplify);1310}13111312/*1313 * This is an inexact early pruning of any recursive directory1314 * reading - if the path cannot possibly be in the pathspec,1315 * return true, and we'll skip it early.1316 */1317static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1318{1319if(simplify) {1320for(;;) {1321const char*match = simplify->path;1322int len = simplify->len;13231324if(!match)1325break;1326if(len > pathlen)1327 len = pathlen;1328if(!memcmp(path, match, len))1329return0;1330 simplify++;1331}1332return1;1333}1334return0;1335}13361337/*1338 * This function tells us whether an excluded path matches a1339 * list of "interesting" pathspecs. That is, whether a path matched1340 * by any of the pathspecs could possibly be ignored by excluding1341 * the specified path. This can happen if:1342 *1343 * 1. the path is mentioned explicitly in the pathspec1344 *1345 * 2. the path is a directory prefix of some element in the1346 * pathspec1347 */1348static intexclude_matches_pathspec(const char*path,int len,1349const struct path_simplify *simplify)1350{1351if(simplify) {1352for(; simplify->path; simplify++) {1353if(len == simplify->len1354&& !memcmp(path, simplify->path, len))1355return1;1356if(len < simplify->len1357&& simplify->path[len] =='/'1358&& !memcmp(path, simplify->path, len))1359return1;1360}1361}1362return0;1363}13641365static intget_index_dtype(const char*path,int len)1366{1367int pos;1368const struct cache_entry *ce;13691370 ce =cache_file_exists(path, len,0);1371if(ce) {1372if(!ce_uptodate(ce))1373return DT_UNKNOWN;1374if(S_ISGITLINK(ce->ce_mode))1375return DT_DIR;1376/*1377 * Nobody actually cares about the1378 * difference between DT_LNK and DT_REG1379 */1380return DT_REG;1381}13821383/* Try to look it up as a directory */1384 pos =cache_name_pos(path, len);1385if(pos >=0)1386return DT_UNKNOWN;1387 pos = -pos-1;1388while(pos < active_nr) {1389 ce = active_cache[pos++];1390if(strncmp(ce->name, path, len))1391break;1392if(ce->name[len] >'/')1393break;1394if(ce->name[len] <'/')1395continue;1396if(!ce_uptodate(ce))1397break;/* continue? */1398return DT_DIR;1399}1400return DT_UNKNOWN;1401}14021403static intget_dtype(struct dirent *de,const char*path,int len)1404{1405int dtype = de ?DTYPE(de) : DT_UNKNOWN;1406struct stat st;14071408if(dtype != DT_UNKNOWN)1409return dtype;1410 dtype =get_index_dtype(path, len);1411if(dtype != DT_UNKNOWN)1412return dtype;1413if(lstat(path, &st))1414return dtype;1415if(S_ISREG(st.st_mode))1416return DT_REG;1417if(S_ISDIR(st.st_mode))1418return DT_DIR;1419if(S_ISLNK(st.st_mode))1420return DT_LNK;1421return dtype;1422}14231424static enum path_treatment treat_one_path(struct dir_struct *dir,1425struct untracked_cache_dir *untracked,1426struct strbuf *path,1427int baselen,1428const struct path_simplify *simplify,1429int dtype,struct dirent *de)1430{1431int exclude;1432int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);14331434if(dtype == DT_UNKNOWN)1435 dtype =get_dtype(de, path->buf, path->len);14361437/* Always exclude indexed files */1438if(dtype != DT_DIR && has_path_in_index)1439return path_none;14401441/*1442 * When we are looking at a directory P in the working tree,1443 * there are three cases:1444 *1445 * (1) P exists in the index. Everything inside the directory P in1446 * the working tree needs to go when P is checked out from the1447 * index.1448 *1449 * (2) P does not exist in the index, but there is P/Q in the index.1450 * We know P will stay a directory when we check out the contents1451 * of the index, but we do not know yet if there is a directory1452 * P/Q in the working tree to be killed, so we need to recurse.1453 *1454 * (3) P does not exist in the index, and there is no P/Q in the index1455 * to require P to be a directory, either. Only in this case, we1456 * know that everything inside P will not be killed without1457 * recursing.1458 */1459if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1460(dtype == DT_DIR) &&1461!has_path_in_index &&1462(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1463return path_none;14641465 exclude =is_excluded(dir, path->buf, &dtype);14661467/*1468 * Excluded? If we don't explicitly want to show1469 * ignored files, ignore it1470 */1471if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1472return path_excluded;14731474switch(dtype) {1475default:1476return path_none;1477case DT_DIR:1478strbuf_addch(path,'/');1479returntreat_directory(dir, untracked, path->buf, path->len,1480 baselen, exclude, simplify);1481case DT_REG:1482case DT_LNK:1483return exclude ? path_excluded : path_untracked;1484}1485}14861487static enum path_treatment treat_path_fast(struct dir_struct *dir,1488struct untracked_cache_dir *untracked,1489struct cached_dir *cdir,1490struct strbuf *path,1491int baselen,1492const struct path_simplify *simplify)1493{1494strbuf_setlen(path, baselen);1495if(!cdir->ucd) {1496strbuf_addstr(path, cdir->file);1497return path_untracked;1498}1499strbuf_addstr(path, cdir->ucd->name);1500/* treat_one_path() does this before it calls treat_directory() */1501strbuf_complete(path,'/');1502if(cdir->ucd->check_only)1503/*1504 * check_only is set as a result of treat_directory() getting1505 * to its bottom. Verify again the same set of directories1506 * with check_only set.1507 */1508returnread_directory_recursive(dir, path->buf, path->len,1509 cdir->ucd,1, simplify);1510/*1511 * We get path_recurse in the first run when1512 * directory_exists_in_index() returns index_nonexistent. We1513 * are sure that new changes in the index does not impact the1514 * outcome. Return now.1515 */1516return path_recurse;1517}15181519static enum path_treatment treat_path(struct dir_struct *dir,1520struct untracked_cache_dir *untracked,1521struct cached_dir *cdir,1522struct strbuf *path,1523int baselen,1524const struct path_simplify *simplify)1525{1526int dtype;1527struct dirent *de = cdir->de;15281529if(!de)1530returntreat_path_fast(dir, untracked, cdir, path,1531 baselen, simplify);1532if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1533return path_none;1534strbuf_setlen(path, baselen);1535strbuf_addstr(path, de->d_name);1536if(simplify_away(path->buf, path->len, simplify))1537return path_none;15381539 dtype =DTYPE(de);1540returntreat_one_path(dir, untracked, path, baselen, simplify, dtype, de);1541}15421543static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1544{1545if(!dir)1546return;1547ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1548 dir->untracked_alloc);1549 dir->untracked[dir->untracked_nr++] =xstrdup(name);1550}15511552static intvalid_cached_dir(struct dir_struct *dir,1553struct untracked_cache_dir *untracked,1554struct strbuf *path,1555int check_only)1556{1557struct stat st;15581559if(!untracked)1560return0;15611562if(stat(path->len ? path->buf :".", &st)) {1563invalidate_directory(dir->untracked, untracked);1564memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1565return0;1566}1567if(!untracked->valid ||1568match_stat_data_racy(&the_index, &untracked->stat_data, &st)) {1569if(untracked->valid)1570invalidate_directory(dir->untracked, untracked);1571fill_stat_data(&untracked->stat_data, &st);1572return0;1573}15741575if(untracked->check_only != !!check_only) {1576invalidate_directory(dir->untracked, untracked);1577return0;1578}15791580/*1581 * prep_exclude will be called eventually on this directory,1582 * but it's called much later in last_exclude_matching(). We1583 * need it now to determine the validity of the cache for this1584 * path. The next calls will be nearly no-op, the way1585 * prep_exclude() is designed.1586 */1587if(path->len && path->buf[path->len -1] !='/') {1588strbuf_addch(path,'/');1589prep_exclude(dir, path->buf, path->len);1590strbuf_setlen(path, path->len -1);1591}else1592prep_exclude(dir, path->buf, path->len);15931594/* hopefully prep_exclude() haven't invalidated this entry... */1595return untracked->valid;1596}15971598static intopen_cached_dir(struct cached_dir *cdir,1599struct dir_struct *dir,1600struct untracked_cache_dir *untracked,1601struct strbuf *path,1602int check_only)1603{1604memset(cdir,0,sizeof(*cdir));1605 cdir->untracked = untracked;1606if(valid_cached_dir(dir, untracked, path, check_only))1607return0;1608 cdir->fdir =opendir(path->len ? path->buf :".");1609if(dir->untracked)1610 dir->untracked->dir_opened++;1611if(!cdir->fdir)1612return-1;1613return0;1614}16151616static intread_cached_dir(struct cached_dir *cdir)1617{1618if(cdir->fdir) {1619 cdir->de =readdir(cdir->fdir);1620if(!cdir->de)1621return-1;1622return0;1623}1624while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1625struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1626if(!d->recurse) {1627 cdir->nr_dirs++;1628continue;1629}1630 cdir->ucd = d;1631 cdir->nr_dirs++;1632return0;1633}1634 cdir->ucd = NULL;1635if(cdir->nr_files < cdir->untracked->untracked_nr) {1636struct untracked_cache_dir *d = cdir->untracked;1637 cdir->file = d->untracked[cdir->nr_files++];1638return0;1639}1640return-1;1641}16421643static voidclose_cached_dir(struct cached_dir *cdir)1644{1645if(cdir->fdir)1646closedir(cdir->fdir);1647/*1648 * We have gone through this directory and found no untracked1649 * entries. Mark it valid.1650 */1651if(cdir->untracked) {1652 cdir->untracked->valid =1;1653 cdir->untracked->recurse =1;1654}1655}16561657/*1658 * Read a directory tree. We currently ignore anything but1659 * directories, regular files and symlinks. That's because git1660 * doesn't handle them at all yet. Maybe that will change some1661 * day.1662 *1663 * Also, we ignore the name ".git" (even if it is not a directory).1664 * That likely will not change.1665 *1666 * Returns the most significant path_treatment value encountered in the scan.1667 */1668static enum path_treatment read_directory_recursive(struct dir_struct *dir,1669const char*base,int baselen,1670struct untracked_cache_dir *untracked,int check_only,1671const struct path_simplify *simplify)1672{1673struct cached_dir cdir;1674enum path_treatment state, subdir_state, dir_state = path_none;1675struct strbuf path = STRBUF_INIT;16761677strbuf_add(&path, base, baselen);16781679if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1680goto out;16811682if(untracked)1683 untracked->check_only = !!check_only;16841685while(!read_cached_dir(&cdir)) {1686/* check how the file or directory should be treated */1687 state =treat_path(dir, untracked, &cdir, &path, baselen, simplify);16881689if(state > dir_state)1690 dir_state = state;16911692/* recurse into subdir if instructed by treat_path */1693if(state == path_recurse) {1694struct untracked_cache_dir *ud;1695 ud =lookup_untracked(dir->untracked, untracked,1696 path.buf + baselen,1697 path.len - baselen);1698 subdir_state =1699read_directory_recursive(dir, path.buf, path.len,1700 ud, check_only, simplify);1701if(subdir_state > dir_state)1702 dir_state = subdir_state;1703}17041705if(check_only) {1706/* abort early if maximum state has been reached */1707if(dir_state == path_untracked) {1708if(cdir.fdir)1709add_untracked(untracked, path.buf + baselen);1710break;1711}1712/* skip the dir_add_* part */1713continue;1714}17151716/* add the path to the appropriate result list */1717switch(state) {1718case path_excluded:1719if(dir->flags & DIR_SHOW_IGNORED)1720dir_add_name(dir, path.buf, path.len);1721else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1722((dir->flags & DIR_COLLECT_IGNORED) &&1723exclude_matches_pathspec(path.buf, path.len,1724 simplify)))1725dir_add_ignored(dir, path.buf, path.len);1726break;17271728case path_untracked:1729if(dir->flags & DIR_SHOW_IGNORED)1730break;1731dir_add_name(dir, path.buf, path.len);1732if(cdir.fdir)1733add_untracked(untracked, path.buf + baselen);1734break;17351736default:1737break;1738}1739}1740close_cached_dir(&cdir);1741 out:1742strbuf_release(&path);17431744return dir_state;1745}17461747static intcmp_name(const void*p1,const void*p2)1748{1749const struct dir_entry *e1 = *(const struct dir_entry **)p1;1750const struct dir_entry *e2 = *(const struct dir_entry **)p2;17511752returnname_compare(e1->name, e1->len, e2->name, e2->len);1753}17541755static struct path_simplify *create_simplify(const char**pathspec)1756{1757int nr, alloc =0;1758struct path_simplify *simplify = NULL;17591760if(!pathspec)1761return NULL;17621763for(nr =0; ; nr++) {1764const char*match;1765ALLOC_GROW(simplify, nr +1, alloc);1766 match = *pathspec++;1767if(!match)1768break;1769 simplify[nr].path = match;1770 simplify[nr].len =simple_length(match);1771}1772 simplify[nr].path = NULL;1773 simplify[nr].len =0;1774return simplify;1775}17761777static voidfree_simplify(struct path_simplify *simplify)1778{1779free(simplify);1780}17811782static inttreat_leading_path(struct dir_struct *dir,1783const char*path,int len,1784const struct path_simplify *simplify)1785{1786struct strbuf sb = STRBUF_INIT;1787int baselen, rc =0;1788const char*cp;1789int old_flags = dir->flags;17901791while(len && path[len -1] =='/')1792 len--;1793if(!len)1794return1;1795 baselen =0;1796 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1797while(1) {1798 cp = path + baselen + !!baselen;1799 cp =memchr(cp,'/', path + len - cp);1800if(!cp)1801 baselen = len;1802else1803 baselen = cp - path;1804strbuf_setlen(&sb,0);1805strbuf_add(&sb, path, baselen);1806if(!is_directory(sb.buf))1807break;1808if(simplify_away(sb.buf, sb.len, simplify))1809break;1810if(treat_one_path(dir, NULL, &sb, baselen, simplify,1811 DT_DIR, NULL) == path_none)1812break;/* do not recurse into it */1813if(len <= baselen) {1814 rc =1;1815break;/* finished checking */1816}1817}1818strbuf_release(&sb);1819 dir->flags = old_flags;1820return rc;1821}18221823static const char*get_ident_string(void)1824{1825static struct strbuf sb = STRBUF_INIT;1826struct utsname uts;18271828if(sb.len)1829return sb.buf;1830if(uname(&uts) <0)1831die_errno(_("failed to get kernel name and information"));1832strbuf_addf(&sb,"Location%s, system%s %s %s",get_git_work_tree(),1833 uts.sysname, uts.release, uts.version);1834return sb.buf;1835}18361837static intident_in_untracked(const struct untracked_cache *uc)1838{1839const char*end = uc->ident.buf + uc->ident.len;1840const char*p = uc->ident.buf;18411842for(p = uc->ident.buf; p < end; p +=strlen(p) +1)1843if(!strcmp(p,get_ident_string()))1844return1;1845return0;1846}18471848voidadd_untracked_ident(struct untracked_cache *uc)1849{1850if(ident_in_untracked(uc))1851return;1852strbuf_addstr(&uc->ident,get_ident_string());1853/* this strbuf contains a list of strings, save NUL too */1854strbuf_addch(&uc->ident,0);1855}18561857static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1858int base_len,1859const struct pathspec *pathspec)1860{1861struct untracked_cache_dir *root;18621863if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))1864return NULL;18651866/*1867 * We only support $GIT_DIR/info/exclude and core.excludesfile1868 * as the global ignore rule files. Any other additions1869 * (e.g. from command line) invalidate the cache. This1870 * condition also catches running setup_standard_excludes()1871 * before setting dir->untracked!1872 */1873if(dir->unmanaged_exclude_files)1874return NULL;18751876/*1877 * Optimize for the main use case only: whole-tree git1878 * status. More work involved in treat_leading_path() if we1879 * use cache on just a subset of the worktree. pathspec1880 * support could make the matter even worse.1881 */1882if(base_len || (pathspec && pathspec->nr))1883return NULL;18841885/* Different set of flags may produce different results */1886if(dir->flags != dir->untracked->dir_flags ||1887/*1888 * See treat_directory(), case index_nonexistent. Without1889 * this flag, we may need to also cache .git file content1890 * for the resolve_gitlink_ref() call, which we don't.1891 */1892!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1893/* We don't support collecting ignore files */1894(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1895 DIR_COLLECT_IGNORED)))1896return NULL;18971898/*1899 * If we use .gitignore in the cache and now you change it to1900 * .gitexclude, everything will go wrong.1901 */1902if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1903strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1904return NULL;19051906/*1907 * EXC_CMDL is not considered in the cache. If people set it,1908 * skip the cache.1909 */1910if(dir->exclude_list_group[EXC_CMDL].nr)1911return NULL;19121913if(!ident_in_untracked(dir->untracked)) {1914warning(_("Untracked cache is disabled on this system."));1915return NULL;1916}19171918if(!dir->untracked->root) {1919const int len =sizeof(*dir->untracked->root);1920 dir->untracked->root =xmalloc(len);1921memset(dir->untracked->root,0, len);1922}19231924/* Validate $GIT_DIR/info/exclude and core.excludesfile */1925 root = dir->untracked->root;1926if(hashcmp(dir->ss_info_exclude.sha1,1927 dir->untracked->ss_info_exclude.sha1)) {1928invalidate_gitignore(dir->untracked, root);1929 dir->untracked->ss_info_exclude = dir->ss_info_exclude;1930}1931if(hashcmp(dir->ss_excludes_file.sha1,1932 dir->untracked->ss_excludes_file.sha1)) {1933invalidate_gitignore(dir->untracked, root);1934 dir->untracked->ss_excludes_file = dir->ss_excludes_file;1935}19361937/* Make sure this directory is not dropped out at saving phase */1938 root->recurse =1;1939return root;1940}19411942intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)1943{1944struct path_simplify *simplify;1945struct untracked_cache_dir *untracked;19461947/*1948 * Check out create_simplify()1949 */1950if(pathspec)1951GUARD_PATHSPEC(pathspec,1952 PATHSPEC_FROMTOP |1953 PATHSPEC_MAXDEPTH |1954 PATHSPEC_LITERAL |1955 PATHSPEC_GLOB |1956 PATHSPEC_ICASE |1957 PATHSPEC_EXCLUDE);19581959if(has_symlink_leading_path(path, len))1960return dir->nr;19611962/*1963 * exclude patterns are treated like positive ones in1964 * create_simplify. Usually exclude patterns should be a1965 * subset of positive ones, which has no impacts on1966 * create_simplify().1967 */1968 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);1969 untracked =validate_untracked_cache(dir, len, pathspec);1970if(!untracked)1971/*1972 * make sure untracked cache code path is disabled,1973 * e.g. prep_exclude()1974 */1975 dir->untracked = NULL;1976if(!len ||treat_leading_path(dir, path, len, simplify))1977read_directory_recursive(dir, path, len, untracked,0, simplify);1978free_simplify(simplify);1979qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);1980qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);1981if(dir->untracked) {1982static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);1983trace_printf_key(&trace_untracked_stats,1984"node creation:%u\n"1985"gitignore invalidation:%u\n"1986"directory invalidation:%u\n"1987"opendir:%u\n",1988 dir->untracked->dir_created,1989 dir->untracked->gitignore_invalidated,1990 dir->untracked->dir_invalidated,1991 dir->untracked->dir_opened);1992if(dir->untracked == the_index.untracked &&1993(dir->untracked->dir_opened ||1994 dir->untracked->gitignore_invalidated ||1995 dir->untracked->dir_invalidated))1996 the_index.cache_changed |= UNTRACKED_CHANGED;1997if(dir->untracked != the_index.untracked) {1998free(dir->untracked);1999 dir->untracked = NULL;2000}2001}2002return dir->nr;2003}20042005intfile_exists(const char*f)2006{2007struct stat sb;2008returnlstat(f, &sb) ==0;2009}20102011static intcmp_icase(char a,char b)2012{2013if(a == b)2014return0;2015if(ignore_case)2016returntoupper(a) -toupper(b);2017return a - b;2018}20192020/*2021 * Given two normalized paths (a trailing slash is ok), if subdir is2022 * outside dir, return -1. Otherwise return the offset in subdir that2023 * can be used as relative path to dir.2024 */2025intdir_inside_of(const char*subdir,const char*dir)2026{2027int offset =0;20282029assert(dir && subdir && *dir && *subdir);20302031while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2032 dir++;2033 subdir++;2034 offset++;2035}20362037/* hel[p]/me vs hel[l]/yeah */2038if(*dir && *subdir)2039return-1;20402041if(!*subdir)2042return!*dir ? offset : -1;/* same dir */20432044/* foo/[b]ar vs foo/[] */2045if(is_dir_sep(dir[-1]))2046returnis_dir_sep(subdir[-1]) ? offset : -1;20472048/* foo[/]bar vs foo[] */2049returnis_dir_sep(*subdir) ? offset +1: -1;2050}20512052intis_inside_dir(const char*dir)2053{2054char*cwd;2055int rc;20562057if(!dir)2058return0;20592060 cwd =xgetcwd();2061 rc = (dir_inside_of(cwd, dir) >=0);2062free(cwd);2063return rc;2064}20652066intis_empty_dir(const char*path)2067{2068DIR*dir =opendir(path);2069struct dirent *e;2070int ret =1;20712072if(!dir)2073return0;20742075while((e =readdir(dir)) != NULL)2076if(!is_dot_or_dotdot(e->d_name)) {2077 ret =0;2078break;2079}20802081closedir(dir);2082return ret;2083}20842085static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2086{2087DIR*dir;2088struct dirent *e;2089int ret =0, original_len = path->len, len, kept_down =0;2090int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2091int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2092unsigned char submodule_head[20];20932094if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2095!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2096/* Do not descend and nuke a nested git work tree. */2097if(kept_up)2098*kept_up =1;2099return0;2100}21012102 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2103 dir =opendir(path->buf);2104if(!dir) {2105if(errno == ENOENT)2106return keep_toplevel ? -1:0;2107else if(errno == EACCES && !keep_toplevel)2108/*2109 * An empty dir could be removable even if it2110 * is unreadable:2111 */2112returnrmdir(path->buf);2113else2114return-1;2115}2116strbuf_complete(path,'/');21172118 len = path->len;2119while((e =readdir(dir)) != NULL) {2120struct stat st;2121if(is_dot_or_dotdot(e->d_name))2122continue;21232124strbuf_setlen(path, len);2125strbuf_addstr(path, e->d_name);2126if(lstat(path->buf, &st)) {2127if(errno == ENOENT)2128/*2129 * file disappeared, which is what we2130 * wanted anyway2131 */2132continue;2133/* fall thru */2134}else if(S_ISDIR(st.st_mode)) {2135if(!remove_dir_recurse(path, flag, &kept_down))2136continue;/* happy */2137}else if(!only_empty &&2138(!unlink(path->buf) || errno == ENOENT)) {2139continue;/* happy, too */2140}21412142/* path too long, stat fails, or non-directory still exists */2143 ret = -1;2144break;2145}2146closedir(dir);21472148strbuf_setlen(path, original_len);2149if(!ret && !keep_toplevel && !kept_down)2150 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2151else if(kept_up)2152/*2153 * report the uplevel that it is not an error that we2154 * did not rmdir() our directory.2155 */2156*kept_up = !ret;2157return ret;2158}21592160intremove_dir_recursively(struct strbuf *path,int flag)2161{2162returnremove_dir_recurse(path, flag, NULL);2163}21642165staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")21662167voidsetup_standard_excludes(struct dir_struct *dir)2168{2169const char*path;21702171 dir->exclude_per_dir =".gitignore";21722173/* core.excludefile defaulting to $XDG_HOME/git/ignore */2174if(!excludes_file)2175 excludes_file =xdg_config_home("ignore");2176if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2177add_excludes_from_file_1(dir, excludes_file,2178 dir->untracked ? &dir->ss_excludes_file : NULL);21792180/* per repository user preference */2181 path =git_path_info_exclude();2182if(!access_or_warn(path, R_OK,0))2183add_excludes_from_file_1(dir, path,2184 dir->untracked ? &dir->ss_info_exclude : NULL);2185}21862187intremove_path(const char*name)2188{2189char*slash;21902191if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2192return-1;21932194 slash =strrchr(name,'/');2195if(slash) {2196char*dirs =xstrdup(name);2197 slash = dirs + (slash - name);2198do{2199*slash ='\0';2200}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2201free(dirs);2202}2203return0;2204}22052206/*2207 * Frees memory within dir which was allocated for exclude lists and2208 * the exclude_stack. Does not free dir itself.2209 */2210voidclear_directory(struct dir_struct *dir)2211{2212int i, j;2213struct exclude_list_group *group;2214struct exclude_list *el;2215struct exclude_stack *stk;22162217for(i = EXC_CMDL; i <= EXC_FILE; i++) {2218 group = &dir->exclude_list_group[i];2219for(j =0; j < group->nr; j++) {2220 el = &group->el[j];2221if(i == EXC_DIRS)2222free((char*)el->src);2223clear_exclude_list(el);2224}2225free(group->el);2226}22272228 stk = dir->exclude_stack;2229while(stk) {2230struct exclude_stack *prev = stk->prev;2231free(stk);2232 stk = prev;2233}2234strbuf_release(&dir->basebuf);2235}22362237struct ondisk_untracked_cache {2238struct stat_data info_exclude_stat;2239struct stat_data excludes_file_stat;2240uint32_t dir_flags;2241unsigned char info_exclude_sha1[20];2242unsigned char excludes_file_sha1[20];2243char exclude_per_dir[FLEX_ARRAY];2244};22452246#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)22472248struct write_data {2249int index;/* number of written untracked_cache_dir */2250struct ewah_bitmap *check_only;/* from untracked_cache_dir */2251struct ewah_bitmap *valid;/* from untracked_cache_dir */2252struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2253struct strbuf out;2254struct strbuf sb_stat;2255struct strbuf sb_sha1;2256};22572258static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2259{2260 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2261 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2262 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2263 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2264 to->sd_dev =htonl(from->sd_dev);2265 to->sd_ino =htonl(from->sd_ino);2266 to->sd_uid =htonl(from->sd_uid);2267 to->sd_gid =htonl(from->sd_gid);2268 to->sd_size =htonl(from->sd_size);2269}22702271static voidwrite_one_dir(struct untracked_cache_dir *untracked,2272struct write_data *wd)2273{2274struct stat_data stat_data;2275struct strbuf *out = &wd->out;2276unsigned char intbuf[16];2277unsigned int intlen, value;2278int i = wd->index++;22792280/*2281 * untracked_nr should be reset whenever valid is clear, but2282 * for safety..2283 */2284if(!untracked->valid) {2285 untracked->untracked_nr =0;2286 untracked->check_only =0;2287}22882289if(untracked->check_only)2290ewah_set(wd->check_only, i);2291if(untracked->valid) {2292ewah_set(wd->valid, i);2293stat_data_to_disk(&stat_data, &untracked->stat_data);2294strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2295}2296if(!is_null_sha1(untracked->exclude_sha1)) {2297ewah_set(wd->sha1_valid, i);2298strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2299}23002301 intlen =encode_varint(untracked->untracked_nr, intbuf);2302strbuf_add(out, intbuf, intlen);23032304/* skip non-recurse directories */2305for(i =0, value =0; i < untracked->dirs_nr; i++)2306if(untracked->dirs[i]->recurse)2307 value++;2308 intlen =encode_varint(value, intbuf);2309strbuf_add(out, intbuf, intlen);23102311strbuf_add(out, untracked->name,strlen(untracked->name) +1);23122313for(i =0; i < untracked->untracked_nr; i++)2314strbuf_add(out, untracked->untracked[i],2315strlen(untracked->untracked[i]) +1);23162317for(i =0; i < untracked->dirs_nr; i++)2318if(untracked->dirs[i]->recurse)2319write_one_dir(untracked->dirs[i], wd);2320}23212322voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2323{2324struct ondisk_untracked_cache *ouc;2325struct write_data wd;2326unsigned char varbuf[16];2327int varint_len;2328size_t len =strlen(untracked->exclude_per_dir);23292330FLEX_ALLOC_MEM(ouc, exclude_per_dir, untracked->exclude_per_dir, len);2331stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2332stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2333hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2334hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2335 ouc->dir_flags =htonl(untracked->dir_flags);23362337 varint_len =encode_varint(untracked->ident.len, varbuf);2338strbuf_add(out, varbuf, varint_len);2339strbuf_add(out, untracked->ident.buf, untracked->ident.len);23402341strbuf_add(out, ouc,ouc_size(len));2342free(ouc);2343 ouc = NULL;23442345if(!untracked->root) {2346 varint_len =encode_varint(0, varbuf);2347strbuf_add(out, varbuf, varint_len);2348return;2349}23502351 wd.index =0;2352 wd.check_only =ewah_new();2353 wd.valid =ewah_new();2354 wd.sha1_valid =ewah_new();2355strbuf_init(&wd.out,1024);2356strbuf_init(&wd.sb_stat,1024);2357strbuf_init(&wd.sb_sha1,1024);2358write_one_dir(untracked->root, &wd);23592360 varint_len =encode_varint(wd.index, varbuf);2361strbuf_add(out, varbuf, varint_len);2362strbuf_addbuf(out, &wd.out);2363ewah_serialize_strbuf(wd.valid, out);2364ewah_serialize_strbuf(wd.check_only, out);2365ewah_serialize_strbuf(wd.sha1_valid, out);2366strbuf_addbuf(out, &wd.sb_stat);2367strbuf_addbuf(out, &wd.sb_sha1);2368strbuf_addch(out,'\0');/* safe guard for string lists */23692370ewah_free(wd.valid);2371ewah_free(wd.check_only);2372ewah_free(wd.sha1_valid);2373strbuf_release(&wd.out);2374strbuf_release(&wd.sb_stat);2375strbuf_release(&wd.sb_sha1);2376}23772378static voidfree_untracked(struct untracked_cache_dir *ucd)2379{2380int i;2381if(!ucd)2382return;2383for(i =0; i < ucd->dirs_nr; i++)2384free_untracked(ucd->dirs[i]);2385for(i =0; i < ucd->untracked_nr; i++)2386free(ucd->untracked[i]);2387free(ucd->untracked);2388free(ucd->dirs);2389free(ucd);2390}23912392voidfree_untracked_cache(struct untracked_cache *uc)2393{2394if(uc)2395free_untracked(uc->root);2396free(uc);2397}23982399struct read_data {2400int index;2401struct untracked_cache_dir **ucd;2402struct ewah_bitmap *check_only;2403struct ewah_bitmap *valid;2404struct ewah_bitmap *sha1_valid;2405const unsigned char*data;2406const unsigned char*end;2407};24082409static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2410{2411 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2412 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2413 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2414 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2415 to->sd_dev =get_be32(&from->sd_dev);2416 to->sd_ino =get_be32(&from->sd_ino);2417 to->sd_uid =get_be32(&from->sd_uid);2418 to->sd_gid =get_be32(&from->sd_gid);2419 to->sd_size =get_be32(&from->sd_size);2420}24212422static intread_one_dir(struct untracked_cache_dir **untracked_,2423struct read_data *rd)2424{2425struct untracked_cache_dir ud, *untracked;2426const unsigned char*next, *data = rd->data, *end = rd->end;2427unsigned int value;2428int i, len;24292430memset(&ud,0,sizeof(ud));24312432 next = data;2433 value =decode_varint(&next);2434if(next > end)2435return-1;2436 ud.recurse =1;2437 ud.untracked_alloc = value;2438 ud.untracked_nr = value;2439if(ud.untracked_nr)2440ALLOC_ARRAY(ud.untracked, ud.untracked_nr);2441 data = next;24422443 next = data;2444 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2445if(next > end)2446return-1;2447ALLOC_ARRAY(ud.dirs, ud.dirs_nr);2448 data = next;24492450 len =strlen((const char*)data);2451 next = data + len +1;2452if(next > rd->end)2453return-1;2454*untracked_ = untracked =xmalloc(st_add(sizeof(*untracked), len));2455memcpy(untracked, &ud,sizeof(ud));2456memcpy(untracked->name, data, len +1);2457 data = next;24582459for(i =0; i < untracked->untracked_nr; i++) {2460 len =strlen((const char*)data);2461 next = data + len +1;2462if(next > rd->end)2463return-1;2464 untracked->untracked[i] =xstrdup((const char*)data);2465 data = next;2466}24672468 rd->ucd[rd->index++] = untracked;2469 rd->data = data;24702471for(i =0; i < untracked->dirs_nr; i++) {2472 len =read_one_dir(untracked->dirs + i, rd);2473if(len <0)2474return-1;2475}2476return0;2477}24782479static voidset_check_only(size_t pos,void*cb)2480{2481struct read_data *rd = cb;2482struct untracked_cache_dir *ud = rd->ucd[pos];2483 ud->check_only =1;2484}24852486static voidread_stat(size_t pos,void*cb)2487{2488struct read_data *rd = cb;2489struct untracked_cache_dir *ud = rd->ucd[pos];2490if(rd->data +sizeof(struct stat_data) > rd->end) {2491 rd->data = rd->end +1;2492return;2493}2494stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2495 rd->data +=sizeof(struct stat_data);2496 ud->valid =1;2497}24982499static voidread_sha1(size_t pos,void*cb)2500{2501struct read_data *rd = cb;2502struct untracked_cache_dir *ud = rd->ucd[pos];2503if(rd->data +20> rd->end) {2504 rd->data = rd->end +1;2505return;2506}2507hashcpy(ud->exclude_sha1, rd->data);2508 rd->data +=20;2509}25102511static voidload_sha1_stat(struct sha1_stat *sha1_stat,2512const struct stat_data *stat,2513const unsigned char*sha1)2514{2515stat_data_from_disk(&sha1_stat->stat, stat);2516hashcpy(sha1_stat->sha1, sha1);2517 sha1_stat->valid =1;2518}25192520struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2521{2522const struct ondisk_untracked_cache *ouc;2523struct untracked_cache *uc;2524struct read_data rd;2525const unsigned char*next = data, *end = (const unsigned char*)data + sz;2526const char*ident;2527int ident_len, len;25282529if(sz <=1|| end[-1] !='\0')2530return NULL;2531 end--;25322533 ident_len =decode_varint(&next);2534if(next + ident_len > end)2535return NULL;2536 ident = (const char*)next;2537 next += ident_len;25382539 ouc = (const struct ondisk_untracked_cache *)next;2540if(next +ouc_size(0) > end)2541return NULL;25422543 uc =xcalloc(1,sizeof(*uc));2544strbuf_init(&uc->ident, ident_len);2545strbuf_add(&uc->ident, ident, ident_len);2546load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2547 ouc->info_exclude_sha1);2548load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2549 ouc->excludes_file_sha1);2550 uc->dir_flags =get_be32(&ouc->dir_flags);2551 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2552/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2553 next +=ouc_size(strlen(ouc->exclude_per_dir));2554if(next >= end)2555goto done2;25562557 len =decode_varint(&next);2558if(next > end || len ==0)2559goto done2;25602561 rd.valid =ewah_new();2562 rd.check_only =ewah_new();2563 rd.sha1_valid =ewah_new();2564 rd.data = next;2565 rd.end = end;2566 rd.index =0;2567ALLOC_ARRAY(rd.ucd, len);25682569if(read_one_dir(&uc->root, &rd) || rd.index != len)2570goto done;25712572 next = rd.data;2573 len =ewah_read_mmap(rd.valid, next, end - next);2574if(len <0)2575goto done;25762577 next += len;2578 len =ewah_read_mmap(rd.check_only, next, end - next);2579if(len <0)2580goto done;25812582 next += len;2583 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2584if(len <0)2585goto done;25862587ewah_each_bit(rd.check_only, set_check_only, &rd);2588 rd.data = next + len;2589ewah_each_bit(rd.valid, read_stat, &rd);2590ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2591 next = rd.data;25922593done:2594free(rd.ucd);2595ewah_free(rd.valid);2596ewah_free(rd.check_only);2597ewah_free(rd.sha1_valid);2598done2:2599if(next != end) {2600free_untracked_cache(uc);2601 uc = NULL;2602}2603return uc;2604}26052606static voidinvalidate_one_directory(struct untracked_cache *uc,2607struct untracked_cache_dir *ucd)2608{2609 uc->dir_invalidated++;2610 ucd->valid =0;2611 ucd->untracked_nr =0;2612}26132614/*2615 * Normally when an entry is added or removed from a directory,2616 * invalidating that directory is enough. No need to touch its2617 * ancestors. When a directory is shown as "foo/bar/" in git-status2618 * however, deleting or adding an entry may have cascading effect.2619 *2620 * Say the "foo/bar/file" has become untracked, we need to tell the2621 * untracked_cache_dir of "foo" that "bar/" is not an untracked2622 * directory any more (because "bar" is managed by foo as an untracked2623 * "file").2624 *2625 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2626 * was the last untracked entry in the entire "foo", we should show2627 * "foo/" instead. Which means we have to invalidate past "bar" up to2628 * "foo".2629 *2630 * This function traverses all directories from root to leaf. If there2631 * is a chance of one of the above cases happening, we invalidate back2632 * to root. Otherwise we just invalidate the leaf. There may be a more2633 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2634 * detect these cases and avoid unnecessary invalidation, for example,2635 * checking for the untracked entry named "bar/" in "foo", but for now2636 * stick to something safe and simple.2637 */2638static intinvalidate_one_component(struct untracked_cache *uc,2639struct untracked_cache_dir *dir,2640const char*path,int len)2641{2642const char*rest =strchr(path,'/');26432644if(rest) {2645int component_len = rest - path;2646struct untracked_cache_dir *d =2647lookup_untracked(uc, dir, path, component_len);2648int ret =2649invalidate_one_component(uc, d, rest +1,2650 len - (component_len +1));2651if(ret)2652invalidate_one_directory(uc, dir);2653return ret;2654}26552656invalidate_one_directory(uc, dir);2657return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2658}26592660voiduntracked_cache_invalidate_path(struct index_state *istate,2661const char*path)2662{2663if(!istate->untracked || !istate->untracked->root)2664return;2665invalidate_one_component(istate->untracked, istate->untracked->root,2666 path,strlen(path));2667}26682669voiduntracked_cache_remove_from_index(struct index_state *istate,2670const char*path)2671{2672untracked_cache_invalidate_path(istate, path);2673}26742675voiduntracked_cache_add_to_index(struct index_state *istate,2676const char*path)2677{2678untracked_cache_invalidate_path(istate, path);2679}