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",get_git_work_tree(),1833 uts.sysname);1834return sb.buf;1835}18361837static intident_in_untracked(const struct untracked_cache *uc)1838{1839/*1840 * Previous git versions may have saved many NUL separated1841 * strings in the "ident" field, but it is insane to manage1842 * many locations, so just take care of the first one.1843 */18441845return!strcmp(uc->ident.buf,get_ident_string());1846}18471848static voidset_untracked_ident(struct untracked_cache *uc)1849{1850strbuf_reset(&uc->ident);1851strbuf_addstr(&uc->ident,get_ident_string());18521853/*1854 * This strbuf used to contain a list of NUL separated1855 * strings, so save NUL too for backward compatibility.1856 */1857strbuf_addch(&uc->ident,0);1858}18591860static voidnew_untracked_cache(struct index_state *istate)1861{1862struct untracked_cache *uc =xcalloc(1,sizeof(*uc));1863strbuf_init(&uc->ident,100);1864 uc->exclude_per_dir =".gitignore";1865/* should be the same flags used by git-status */1866 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;1867set_untracked_ident(uc);1868 istate->untracked = uc;1869 istate->cache_changed |= UNTRACKED_CHANGED;1870}18711872voidadd_untracked_cache(struct index_state *istate)1873{1874if(!istate->untracked) {1875new_untracked_cache(istate);1876}else{1877if(!ident_in_untracked(istate->untracked)) {1878free_untracked_cache(istate->untracked);1879new_untracked_cache(istate);1880}1881}1882}18831884voidremove_untracked_cache(struct index_state *istate)1885{1886if(istate->untracked) {1887free_untracked_cache(istate->untracked);1888 istate->untracked = NULL;1889 istate->cache_changed |= UNTRACKED_CHANGED;1890}1891}18921893static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1894int base_len,1895const struct pathspec *pathspec)1896{1897struct untracked_cache_dir *root;18981899if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))1900return NULL;19011902/*1903 * We only support $GIT_DIR/info/exclude and core.excludesfile1904 * as the global ignore rule files. Any other additions1905 * (e.g. from command line) invalidate the cache. This1906 * condition also catches running setup_standard_excludes()1907 * before setting dir->untracked!1908 */1909if(dir->unmanaged_exclude_files)1910return NULL;19111912/*1913 * Optimize for the main use case only: whole-tree git1914 * status. More work involved in treat_leading_path() if we1915 * use cache on just a subset of the worktree. pathspec1916 * support could make the matter even worse.1917 */1918if(base_len || (pathspec && pathspec->nr))1919return NULL;19201921/* Different set of flags may produce different results */1922if(dir->flags != dir->untracked->dir_flags ||1923/*1924 * See treat_directory(), case index_nonexistent. Without1925 * this flag, we may need to also cache .git file content1926 * for the resolve_gitlink_ref() call, which we don't.1927 */1928!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1929/* We don't support collecting ignore files */1930(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1931 DIR_COLLECT_IGNORED)))1932return NULL;19331934/*1935 * If we use .gitignore in the cache and now you change it to1936 * .gitexclude, everything will go wrong.1937 */1938if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1939strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1940return NULL;19411942/*1943 * EXC_CMDL is not considered in the cache. If people set it,1944 * skip the cache.1945 */1946if(dir->exclude_list_group[EXC_CMDL].nr)1947return NULL;19481949if(!ident_in_untracked(dir->untracked)) {1950warning(_("Untracked cache is disabled on this system or location."));1951return NULL;1952}19531954if(!dir->untracked->root) {1955const int len =sizeof(*dir->untracked->root);1956 dir->untracked->root =xmalloc(len);1957memset(dir->untracked->root,0, len);1958}19591960/* Validate $GIT_DIR/info/exclude and core.excludesfile */1961 root = dir->untracked->root;1962if(hashcmp(dir->ss_info_exclude.sha1,1963 dir->untracked->ss_info_exclude.sha1)) {1964invalidate_gitignore(dir->untracked, root);1965 dir->untracked->ss_info_exclude = dir->ss_info_exclude;1966}1967if(hashcmp(dir->ss_excludes_file.sha1,1968 dir->untracked->ss_excludes_file.sha1)) {1969invalidate_gitignore(dir->untracked, root);1970 dir->untracked->ss_excludes_file = dir->ss_excludes_file;1971}19721973/* Make sure this directory is not dropped out at saving phase */1974 root->recurse =1;1975return root;1976}19771978intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)1979{1980struct path_simplify *simplify;1981struct untracked_cache_dir *untracked;19821983/*1984 * Check out create_simplify()1985 */1986if(pathspec)1987GUARD_PATHSPEC(pathspec,1988 PATHSPEC_FROMTOP |1989 PATHSPEC_MAXDEPTH |1990 PATHSPEC_LITERAL |1991 PATHSPEC_GLOB |1992 PATHSPEC_ICASE |1993 PATHSPEC_EXCLUDE);19941995if(has_symlink_leading_path(path, len))1996return dir->nr;19971998/*1999 * exclude patterns are treated like positive ones in2000 * create_simplify. Usually exclude patterns should be a2001 * subset of positive ones, which has no impacts on2002 * create_simplify().2003 */2004 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);2005 untracked =validate_untracked_cache(dir, len, pathspec);2006if(!untracked)2007/*2008 * make sure untracked cache code path is disabled,2009 * e.g. prep_exclude()2010 */2011 dir->untracked = NULL;2012if(!len ||treat_leading_path(dir, path, len, simplify))2013read_directory_recursive(dir, path, len, untracked,0, simplify);2014free_simplify(simplify);2015qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);2016qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);2017if(dir->untracked) {2018static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);2019trace_printf_key(&trace_untracked_stats,2020"node creation:%u\n"2021"gitignore invalidation:%u\n"2022"directory invalidation:%u\n"2023"opendir:%u\n",2024 dir->untracked->dir_created,2025 dir->untracked->gitignore_invalidated,2026 dir->untracked->dir_invalidated,2027 dir->untracked->dir_opened);2028if(dir->untracked == the_index.untracked &&2029(dir->untracked->dir_opened ||2030 dir->untracked->gitignore_invalidated ||2031 dir->untracked->dir_invalidated))2032 the_index.cache_changed |= UNTRACKED_CHANGED;2033if(dir->untracked != the_index.untracked) {2034free(dir->untracked);2035 dir->untracked = NULL;2036}2037}2038return dir->nr;2039}20402041intfile_exists(const char*f)2042{2043struct stat sb;2044returnlstat(f, &sb) ==0;2045}20462047static intcmp_icase(char a,char b)2048{2049if(a == b)2050return0;2051if(ignore_case)2052returntoupper(a) -toupper(b);2053return a - b;2054}20552056/*2057 * Given two normalized paths (a trailing slash is ok), if subdir is2058 * outside dir, return -1. Otherwise return the offset in subdir that2059 * can be used as relative path to dir.2060 */2061intdir_inside_of(const char*subdir,const char*dir)2062{2063int offset =0;20642065assert(dir && subdir && *dir && *subdir);20662067while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2068 dir++;2069 subdir++;2070 offset++;2071}20722073/* hel[p]/me vs hel[l]/yeah */2074if(*dir && *subdir)2075return-1;20762077if(!*subdir)2078return!*dir ? offset : -1;/* same dir */20792080/* foo/[b]ar vs foo/[] */2081if(is_dir_sep(dir[-1]))2082returnis_dir_sep(subdir[-1]) ? offset : -1;20832084/* foo[/]bar vs foo[] */2085returnis_dir_sep(*subdir) ? offset +1: -1;2086}20872088intis_inside_dir(const char*dir)2089{2090char*cwd;2091int rc;20922093if(!dir)2094return0;20952096 cwd =xgetcwd();2097 rc = (dir_inside_of(cwd, dir) >=0);2098free(cwd);2099return rc;2100}21012102intis_empty_dir(const char*path)2103{2104DIR*dir =opendir(path);2105struct dirent *e;2106int ret =1;21072108if(!dir)2109return0;21102111while((e =readdir(dir)) != NULL)2112if(!is_dot_or_dotdot(e->d_name)) {2113 ret =0;2114break;2115}21162117closedir(dir);2118return ret;2119}21202121static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2122{2123DIR*dir;2124struct dirent *e;2125int ret =0, original_len = path->len, len, kept_down =0;2126int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2127int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2128unsigned char submodule_head[20];21292130if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2131!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2132/* Do not descend and nuke a nested git work tree. */2133if(kept_up)2134*kept_up =1;2135return0;2136}21372138 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2139 dir =opendir(path->buf);2140if(!dir) {2141if(errno == ENOENT)2142return keep_toplevel ? -1:0;2143else if(errno == EACCES && !keep_toplevel)2144/*2145 * An empty dir could be removable even if it2146 * is unreadable:2147 */2148returnrmdir(path->buf);2149else2150return-1;2151}2152strbuf_complete(path,'/');21532154 len = path->len;2155while((e =readdir(dir)) != NULL) {2156struct stat st;2157if(is_dot_or_dotdot(e->d_name))2158continue;21592160strbuf_setlen(path, len);2161strbuf_addstr(path, e->d_name);2162if(lstat(path->buf, &st)) {2163if(errno == ENOENT)2164/*2165 * file disappeared, which is what we2166 * wanted anyway2167 */2168continue;2169/* fall thru */2170}else if(S_ISDIR(st.st_mode)) {2171if(!remove_dir_recurse(path, flag, &kept_down))2172continue;/* happy */2173}else if(!only_empty &&2174(!unlink(path->buf) || errno == ENOENT)) {2175continue;/* happy, too */2176}21772178/* path too long, stat fails, or non-directory still exists */2179 ret = -1;2180break;2181}2182closedir(dir);21832184strbuf_setlen(path, original_len);2185if(!ret && !keep_toplevel && !kept_down)2186 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2187else if(kept_up)2188/*2189 * report the uplevel that it is not an error that we2190 * did not rmdir() our directory.2191 */2192*kept_up = !ret;2193return ret;2194}21952196intremove_dir_recursively(struct strbuf *path,int flag)2197{2198returnremove_dir_recurse(path, flag, NULL);2199}22002201staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")22022203voidsetup_standard_excludes(struct dir_struct *dir)2204{2205const char*path;22062207 dir->exclude_per_dir =".gitignore";22082209/* core.excludefile defaulting to $XDG_HOME/git/ignore */2210if(!excludes_file)2211 excludes_file =xdg_config_home("ignore");2212if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2213add_excludes_from_file_1(dir, excludes_file,2214 dir->untracked ? &dir->ss_excludes_file : NULL);22152216/* per repository user preference */2217 path =git_path_info_exclude();2218if(!access_or_warn(path, R_OK,0))2219add_excludes_from_file_1(dir, path,2220 dir->untracked ? &dir->ss_info_exclude : NULL);2221}22222223intremove_path(const char*name)2224{2225char*slash;22262227if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2228return-1;22292230 slash =strrchr(name,'/');2231if(slash) {2232char*dirs =xstrdup(name);2233 slash = dirs + (slash - name);2234do{2235*slash ='\0';2236}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2237free(dirs);2238}2239return0;2240}22412242/*2243 * Frees memory within dir which was allocated for exclude lists and2244 * the exclude_stack. Does not free dir itself.2245 */2246voidclear_directory(struct dir_struct *dir)2247{2248int i, j;2249struct exclude_list_group *group;2250struct exclude_list *el;2251struct exclude_stack *stk;22522253for(i = EXC_CMDL; i <= EXC_FILE; i++) {2254 group = &dir->exclude_list_group[i];2255for(j =0; j < group->nr; j++) {2256 el = &group->el[j];2257if(i == EXC_DIRS)2258free((char*)el->src);2259clear_exclude_list(el);2260}2261free(group->el);2262}22632264 stk = dir->exclude_stack;2265while(stk) {2266struct exclude_stack *prev = stk->prev;2267free(stk);2268 stk = prev;2269}2270strbuf_release(&dir->basebuf);2271}22722273struct ondisk_untracked_cache {2274struct stat_data info_exclude_stat;2275struct stat_data excludes_file_stat;2276uint32_t dir_flags;2277unsigned char info_exclude_sha1[20];2278unsigned char excludes_file_sha1[20];2279char exclude_per_dir[FLEX_ARRAY];2280};22812282#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)22832284struct write_data {2285int index;/* number of written untracked_cache_dir */2286struct ewah_bitmap *check_only;/* from untracked_cache_dir */2287struct ewah_bitmap *valid;/* from untracked_cache_dir */2288struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2289struct strbuf out;2290struct strbuf sb_stat;2291struct strbuf sb_sha1;2292};22932294static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2295{2296 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2297 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2298 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2299 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2300 to->sd_dev =htonl(from->sd_dev);2301 to->sd_ino =htonl(from->sd_ino);2302 to->sd_uid =htonl(from->sd_uid);2303 to->sd_gid =htonl(from->sd_gid);2304 to->sd_size =htonl(from->sd_size);2305}23062307static voidwrite_one_dir(struct untracked_cache_dir *untracked,2308struct write_data *wd)2309{2310struct stat_data stat_data;2311struct strbuf *out = &wd->out;2312unsigned char intbuf[16];2313unsigned int intlen, value;2314int i = wd->index++;23152316/*2317 * untracked_nr should be reset whenever valid is clear, but2318 * for safety..2319 */2320if(!untracked->valid) {2321 untracked->untracked_nr =0;2322 untracked->check_only =0;2323}23242325if(untracked->check_only)2326ewah_set(wd->check_only, i);2327if(untracked->valid) {2328ewah_set(wd->valid, i);2329stat_data_to_disk(&stat_data, &untracked->stat_data);2330strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2331}2332if(!is_null_sha1(untracked->exclude_sha1)) {2333ewah_set(wd->sha1_valid, i);2334strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2335}23362337 intlen =encode_varint(untracked->untracked_nr, intbuf);2338strbuf_add(out, intbuf, intlen);23392340/* skip non-recurse directories */2341for(i =0, value =0; i < untracked->dirs_nr; i++)2342if(untracked->dirs[i]->recurse)2343 value++;2344 intlen =encode_varint(value, intbuf);2345strbuf_add(out, intbuf, intlen);23462347strbuf_add(out, untracked->name,strlen(untracked->name) +1);23482349for(i =0; i < untracked->untracked_nr; i++)2350strbuf_add(out, untracked->untracked[i],2351strlen(untracked->untracked[i]) +1);23522353for(i =0; i < untracked->dirs_nr; i++)2354if(untracked->dirs[i]->recurse)2355write_one_dir(untracked->dirs[i], wd);2356}23572358voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2359{2360struct ondisk_untracked_cache *ouc;2361struct write_data wd;2362unsigned char varbuf[16];2363int varint_len;2364size_t len =strlen(untracked->exclude_per_dir);23652366FLEX_ALLOC_MEM(ouc, exclude_per_dir, untracked->exclude_per_dir, len);2367stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2368stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2369hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2370hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2371 ouc->dir_flags =htonl(untracked->dir_flags);23722373 varint_len =encode_varint(untracked->ident.len, varbuf);2374strbuf_add(out, varbuf, varint_len);2375strbuf_add(out, untracked->ident.buf, untracked->ident.len);23762377strbuf_add(out, ouc,ouc_size(len));2378free(ouc);2379 ouc = NULL;23802381if(!untracked->root) {2382 varint_len =encode_varint(0, varbuf);2383strbuf_add(out, varbuf, varint_len);2384return;2385}23862387 wd.index =0;2388 wd.check_only =ewah_new();2389 wd.valid =ewah_new();2390 wd.sha1_valid =ewah_new();2391strbuf_init(&wd.out,1024);2392strbuf_init(&wd.sb_stat,1024);2393strbuf_init(&wd.sb_sha1,1024);2394write_one_dir(untracked->root, &wd);23952396 varint_len =encode_varint(wd.index, varbuf);2397strbuf_add(out, varbuf, varint_len);2398strbuf_addbuf(out, &wd.out);2399ewah_serialize_strbuf(wd.valid, out);2400ewah_serialize_strbuf(wd.check_only, out);2401ewah_serialize_strbuf(wd.sha1_valid, out);2402strbuf_addbuf(out, &wd.sb_stat);2403strbuf_addbuf(out, &wd.sb_sha1);2404strbuf_addch(out,'\0');/* safe guard for string lists */24052406ewah_free(wd.valid);2407ewah_free(wd.check_only);2408ewah_free(wd.sha1_valid);2409strbuf_release(&wd.out);2410strbuf_release(&wd.sb_stat);2411strbuf_release(&wd.sb_sha1);2412}24132414static voidfree_untracked(struct untracked_cache_dir *ucd)2415{2416int i;2417if(!ucd)2418return;2419for(i =0; i < ucd->dirs_nr; i++)2420free_untracked(ucd->dirs[i]);2421for(i =0; i < ucd->untracked_nr; i++)2422free(ucd->untracked[i]);2423free(ucd->untracked);2424free(ucd->dirs);2425free(ucd);2426}24272428voidfree_untracked_cache(struct untracked_cache *uc)2429{2430if(uc)2431free_untracked(uc->root);2432free(uc);2433}24342435struct read_data {2436int index;2437struct untracked_cache_dir **ucd;2438struct ewah_bitmap *check_only;2439struct ewah_bitmap *valid;2440struct ewah_bitmap *sha1_valid;2441const unsigned char*data;2442const unsigned char*end;2443};24442445static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2446{2447 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2448 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2449 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2450 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2451 to->sd_dev =get_be32(&from->sd_dev);2452 to->sd_ino =get_be32(&from->sd_ino);2453 to->sd_uid =get_be32(&from->sd_uid);2454 to->sd_gid =get_be32(&from->sd_gid);2455 to->sd_size =get_be32(&from->sd_size);2456}24572458static intread_one_dir(struct untracked_cache_dir **untracked_,2459struct read_data *rd)2460{2461struct untracked_cache_dir ud, *untracked;2462const unsigned char*next, *data = rd->data, *end = rd->end;2463unsigned int value;2464int i, len;24652466memset(&ud,0,sizeof(ud));24672468 next = data;2469 value =decode_varint(&next);2470if(next > end)2471return-1;2472 ud.recurse =1;2473 ud.untracked_alloc = value;2474 ud.untracked_nr = value;2475if(ud.untracked_nr)2476ALLOC_ARRAY(ud.untracked, ud.untracked_nr);2477 data = next;24782479 next = data;2480 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2481if(next > end)2482return-1;2483ALLOC_ARRAY(ud.dirs, ud.dirs_nr);2484 data = next;24852486 len =strlen((const char*)data);2487 next = data + len +1;2488if(next > rd->end)2489return-1;2490*untracked_ = untracked =xmalloc(st_add(sizeof(*untracked), len));2491memcpy(untracked, &ud,sizeof(ud));2492memcpy(untracked->name, data, len +1);2493 data = next;24942495for(i =0; i < untracked->untracked_nr; i++) {2496 len =strlen((const char*)data);2497 next = data + len +1;2498if(next > rd->end)2499return-1;2500 untracked->untracked[i] =xstrdup((const char*)data);2501 data = next;2502}25032504 rd->ucd[rd->index++] = untracked;2505 rd->data = data;25062507for(i =0; i < untracked->dirs_nr; i++) {2508 len =read_one_dir(untracked->dirs + i, rd);2509if(len <0)2510return-1;2511}2512return0;2513}25142515static voidset_check_only(size_t pos,void*cb)2516{2517struct read_data *rd = cb;2518struct untracked_cache_dir *ud = rd->ucd[pos];2519 ud->check_only =1;2520}25212522static voidread_stat(size_t pos,void*cb)2523{2524struct read_data *rd = cb;2525struct untracked_cache_dir *ud = rd->ucd[pos];2526if(rd->data +sizeof(struct stat_data) > rd->end) {2527 rd->data = rd->end +1;2528return;2529}2530stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2531 rd->data +=sizeof(struct stat_data);2532 ud->valid =1;2533}25342535static voidread_sha1(size_t pos,void*cb)2536{2537struct read_data *rd = cb;2538struct untracked_cache_dir *ud = rd->ucd[pos];2539if(rd->data +20> rd->end) {2540 rd->data = rd->end +1;2541return;2542}2543hashcpy(ud->exclude_sha1, rd->data);2544 rd->data +=20;2545}25462547static voidload_sha1_stat(struct sha1_stat *sha1_stat,2548const struct stat_data *stat,2549const unsigned char*sha1)2550{2551stat_data_from_disk(&sha1_stat->stat, stat);2552hashcpy(sha1_stat->sha1, sha1);2553 sha1_stat->valid =1;2554}25552556struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2557{2558const struct ondisk_untracked_cache *ouc;2559struct untracked_cache *uc;2560struct read_data rd;2561const unsigned char*next = data, *end = (const unsigned char*)data + sz;2562const char*ident;2563int ident_len, len;25642565if(sz <=1|| end[-1] !='\0')2566return NULL;2567 end--;25682569 ident_len =decode_varint(&next);2570if(next + ident_len > end)2571return NULL;2572 ident = (const char*)next;2573 next += ident_len;25742575 ouc = (const struct ondisk_untracked_cache *)next;2576if(next +ouc_size(0) > end)2577return NULL;25782579 uc =xcalloc(1,sizeof(*uc));2580strbuf_init(&uc->ident, ident_len);2581strbuf_add(&uc->ident, ident, ident_len);2582load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2583 ouc->info_exclude_sha1);2584load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2585 ouc->excludes_file_sha1);2586 uc->dir_flags =get_be32(&ouc->dir_flags);2587 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2588/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2589 next +=ouc_size(strlen(ouc->exclude_per_dir));2590if(next >= end)2591goto done2;25922593 len =decode_varint(&next);2594if(next > end || len ==0)2595goto done2;25962597 rd.valid =ewah_new();2598 rd.check_only =ewah_new();2599 rd.sha1_valid =ewah_new();2600 rd.data = next;2601 rd.end = end;2602 rd.index =0;2603ALLOC_ARRAY(rd.ucd, len);26042605if(read_one_dir(&uc->root, &rd) || rd.index != len)2606goto done;26072608 next = rd.data;2609 len =ewah_read_mmap(rd.valid, next, end - next);2610if(len <0)2611goto done;26122613 next += len;2614 len =ewah_read_mmap(rd.check_only, next, end - next);2615if(len <0)2616goto done;26172618 next += len;2619 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2620if(len <0)2621goto done;26222623ewah_each_bit(rd.check_only, set_check_only, &rd);2624 rd.data = next + len;2625ewah_each_bit(rd.valid, read_stat, &rd);2626ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2627 next = rd.data;26282629done:2630free(rd.ucd);2631ewah_free(rd.valid);2632ewah_free(rd.check_only);2633ewah_free(rd.sha1_valid);2634done2:2635if(next != end) {2636free_untracked_cache(uc);2637 uc = NULL;2638}2639return uc;2640}26412642static voidinvalidate_one_directory(struct untracked_cache *uc,2643struct untracked_cache_dir *ucd)2644{2645 uc->dir_invalidated++;2646 ucd->valid =0;2647 ucd->untracked_nr =0;2648}26492650/*2651 * Normally when an entry is added or removed from a directory,2652 * invalidating that directory is enough. No need to touch its2653 * ancestors. When a directory is shown as "foo/bar/" in git-status2654 * however, deleting or adding an entry may have cascading effect.2655 *2656 * Say the "foo/bar/file" has become untracked, we need to tell the2657 * untracked_cache_dir of "foo" that "bar/" is not an untracked2658 * directory any more (because "bar" is managed by foo as an untracked2659 * "file").2660 *2661 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2662 * was the last untracked entry in the entire "foo", we should show2663 * "foo/" instead. Which means we have to invalidate past "bar" up to2664 * "foo".2665 *2666 * This function traverses all directories from root to leaf. If there2667 * is a chance of one of the above cases happening, we invalidate back2668 * to root. Otherwise we just invalidate the leaf. There may be a more2669 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2670 * detect these cases and avoid unnecessary invalidation, for example,2671 * checking for the untracked entry named "bar/" in "foo", but for now2672 * stick to something safe and simple.2673 */2674static intinvalidate_one_component(struct untracked_cache *uc,2675struct untracked_cache_dir *dir,2676const char*path,int len)2677{2678const char*rest =strchr(path,'/');26792680if(rest) {2681int component_len = rest - path;2682struct untracked_cache_dir *d =2683lookup_untracked(uc, dir, path, component_len);2684int ret =2685invalidate_one_component(uc, d, rest +1,2686 len - (component_len +1));2687if(ret)2688invalidate_one_directory(uc, dir);2689return ret;2690}26912692invalidate_one_directory(uc, dir);2693return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2694}26952696voiduntracked_cache_invalidate_path(struct index_state *istate,2697const char*path)2698{2699if(!istate->untracked || !istate->untracked->root)2700return;2701invalidate_one_component(istate->untracked, istate->untracked->root,2702 path,strlen(path));2703}27042705voiduntracked_cache_remove_from_index(struct index_state *istate,2706const char*path)2707{2708untracked_cache_invalidate_path(istate, path);2709}27102711voiduntracked_cache_add_to_index(struct index_state *istate,2712const char*path)2713{2714untracked_cache_invalidate_path(istate, path);2715}