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 56static struct trace_key trace_exclude =TRACE_KEY_INIT(EXCLUDE); 57 58/* helper string functions with support for the ignore_case flag */ 59intstrcmp_icase(const char*a,const char*b) 60{ 61return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 62} 63 64intstrncmp_icase(const char*a,const char*b,size_t count) 65{ 66return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 67} 68 69intfnmatch_icase(const char*pattern,const char*string,int flags) 70{ 71returnwildmatch(pattern, string, 72 flags | (ignore_case ? WM_CASEFOLD :0), 73 NULL); 74} 75 76intgit_fnmatch(const struct pathspec_item *item, 77const char*pattern,const char*string, 78int prefix) 79{ 80if(prefix >0) { 81if(ps_strncmp(item, pattern, string, prefix)) 82return WM_NOMATCH; 83 pattern += prefix; 84 string += prefix; 85} 86if(item->flags & PATHSPEC_ONESTAR) { 87int pattern_len =strlen(++pattern); 88int string_len =strlen(string); 89return string_len < pattern_len || 90ps_strcmp(item, pattern, 91 string + string_len - pattern_len); 92} 93if(item->magic & PATHSPEC_GLOB) 94returnwildmatch(pattern, string, 95 WM_PATHNAME | 96(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 97 NULL); 98else 99/* wildmatch has not learned no FNM_PATHNAME mode yet */ 100returnwildmatch(pattern, string, 101 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 102 NULL); 103} 104 105static intfnmatch_icase_mem(const char*pattern,int patternlen, 106const char*string,int stringlen, 107int flags) 108{ 109int match_status; 110struct strbuf pat_buf = STRBUF_INIT; 111struct strbuf str_buf = STRBUF_INIT; 112const char*use_pat = pattern; 113const char*use_str = string; 114 115if(pattern[patternlen]) { 116strbuf_add(&pat_buf, pattern, patternlen); 117 use_pat = pat_buf.buf; 118} 119if(string[stringlen]) { 120strbuf_add(&str_buf, string, stringlen); 121 use_str = str_buf.buf; 122} 123 124if(ignore_case) 125 flags |= WM_CASEFOLD; 126 match_status =wildmatch(use_pat, use_str, flags, NULL); 127 128strbuf_release(&pat_buf); 129strbuf_release(&str_buf); 130 131return match_status; 132} 133 134static size_tcommon_prefix_len(const struct pathspec *pathspec) 135{ 136int n; 137size_t max =0; 138 139/* 140 * ":(icase)path" is treated as a pathspec full of 141 * wildcard. In other words, only prefix is considered common 142 * prefix. If the pathspec is abc/foo abc/bar, running in 143 * subdir xyz, the common prefix is still xyz, not xuz/abc as 144 * in non-:(icase). 145 */ 146GUARD_PATHSPEC(pathspec, 147 PATHSPEC_FROMTOP | 148 PATHSPEC_MAXDEPTH | 149 PATHSPEC_LITERAL | 150 PATHSPEC_GLOB | 151 PATHSPEC_ICASE | 152 PATHSPEC_EXCLUDE); 153 154for(n =0; n < pathspec->nr; n++) { 155size_t i =0, len =0, item_len; 156if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 157continue; 158if(pathspec->items[n].magic & PATHSPEC_ICASE) 159 item_len = pathspec->items[n].prefix; 160else 161 item_len = pathspec->items[n].nowildcard_len; 162while(i < item_len && (n ==0|| i < max)) { 163char c = pathspec->items[n].match[i]; 164if(c != pathspec->items[0].match[i]) 165break; 166if(c =='/') 167 len = i +1; 168 i++; 169} 170if(n ==0|| len < max) { 171 max = len; 172if(!max) 173break; 174} 175} 176return max; 177} 178 179/* 180 * Returns a copy of the longest leading path common among all 181 * pathspecs. 182 */ 183char*common_prefix(const struct pathspec *pathspec) 184{ 185unsigned long len =common_prefix_len(pathspec); 186 187return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 188} 189 190intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 191{ 192size_t len; 193 194/* 195 * Calculate common prefix for the pathspec, and 196 * use that to optimize the directory walk 197 */ 198 len =common_prefix_len(pathspec); 199 200/* Read the directory and prune it */ 201read_directory(dir, pathspec->nr ? pathspec->_raw[0] :"", len, pathspec); 202return len; 203} 204 205intwithin_depth(const char*name,int namelen, 206int depth,int max_depth) 207{ 208const char*cp = name, *cpe = name + namelen; 209 210while(cp < cpe) { 211if(*cp++ !='/') 212continue; 213 depth++; 214if(depth > max_depth) 215return0; 216} 217return1; 218} 219 220#define DO_MATCH_EXCLUDE 1 221#define DO_MATCH_DIRECTORY 2 222 223/* 224 * Does 'match' match the given name? 225 * A match is found if 226 * 227 * (1) the 'match' string is leading directory of 'name', or 228 * (2) the 'match' string is a wildcard and matches 'name', or 229 * (3) the 'match' string is exactly the same as 'name'. 230 * 231 * and the return value tells which case it was. 232 * 233 * It returns 0 when there is no match. 234 */ 235static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 236const char*name,int namelen,unsigned flags) 237{ 238/* name/namelen has prefix cut off by caller */ 239const char*match = item->match + prefix; 240int matchlen = item->len - prefix; 241 242/* 243 * The normal call pattern is: 244 * 1. prefix = common_prefix_len(ps); 245 * 2. prune something, or fill_directory 246 * 3. match_pathspec() 247 * 248 * 'prefix' at #1 may be shorter than the command's prefix and 249 * it's ok for #2 to match extra files. Those extras will be 250 * trimmed at #3. 251 * 252 * Suppose the pathspec is 'foo' and '../bar' running from 253 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 254 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 255 * user does not want XYZ/foo, only the "foo" part should be 256 * case-insensitive. We need to filter out XYZ/foo here. In 257 * other words, we do not trust the caller on comparing the 258 * prefix part when :(icase) is involved. We do exact 259 * comparison ourselves. 260 * 261 * Normally the caller (common_prefix_len() in fact) does 262 * _exact_ matching on name[-prefix+1..-1] and we do not need 263 * to check that part. Be defensive and check it anyway, in 264 * case common_prefix_len is changed, or a new caller is 265 * introduced that does not use common_prefix_len. 266 * 267 * If the penalty turns out too high when prefix is really 268 * long, maybe change it to 269 * strncmp(match, name, item->prefix - prefix) 270 */ 271if(item->prefix && (item->magic & PATHSPEC_ICASE) && 272strncmp(item->match, name - prefix, item->prefix)) 273return0; 274 275/* If the match was just the prefix, we matched */ 276if(!*match) 277return MATCHED_RECURSIVELY; 278 279if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 280if(matchlen == namelen) 281return MATCHED_EXACTLY; 282 283if(match[matchlen-1] =='/'|| name[matchlen] =='/') 284return MATCHED_RECURSIVELY; 285}else if((flags & DO_MATCH_DIRECTORY) && 286 match[matchlen -1] =='/'&& 287 namelen == matchlen -1&& 288!ps_strncmp(item, match, name, namelen)) 289return MATCHED_EXACTLY; 290 291if(item->nowildcard_len < item->len && 292!git_fnmatch(item, match, name, 293 item->nowildcard_len - prefix)) 294return MATCHED_FNMATCH; 295 296return0; 297} 298 299/* 300 * Given a name and a list of pathspecs, returns the nature of the 301 * closest (i.e. most specific) match of the name to any of the 302 * pathspecs. 303 * 304 * The caller typically calls this multiple times with the same 305 * pathspec and seen[] array but with different name/namelen 306 * (e.g. entries from the index) and is interested in seeing if and 307 * how each pathspec matches all the names it calls this function 308 * with. A mark is left in the seen[] array for each pathspec element 309 * indicating the closest type of match that element achieved, so if 310 * seen[n] remains zero after multiple invocations, that means the nth 311 * pathspec did not match any names, which could indicate that the 312 * user mistyped the nth pathspec. 313 */ 314static intdo_match_pathspec(const struct pathspec *ps, 315const char*name,int namelen, 316int prefix,char*seen, 317unsigned flags) 318{ 319int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 320 321GUARD_PATHSPEC(ps, 322 PATHSPEC_FROMTOP | 323 PATHSPEC_MAXDEPTH | 324 PATHSPEC_LITERAL | 325 PATHSPEC_GLOB | 326 PATHSPEC_ICASE | 327 PATHSPEC_EXCLUDE); 328 329if(!ps->nr) { 330if(!ps->recursive || 331!(ps->magic & PATHSPEC_MAXDEPTH) || 332 ps->max_depth == -1) 333return MATCHED_RECURSIVELY; 334 335if(within_depth(name, namelen,0, ps->max_depth)) 336return MATCHED_EXACTLY; 337else 338return0; 339} 340 341 name += prefix; 342 namelen -= prefix; 343 344for(i = ps->nr -1; i >=0; i--) { 345int how; 346 347if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 348( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 349continue; 350 351if(seen && seen[i] == MATCHED_EXACTLY) 352continue; 353/* 354 * Make exclude patterns optional and never report 355 * "pathspec ':(exclude)foo' matches no files" 356 */ 357if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 358 seen[i] = MATCHED_FNMATCH; 359 how =match_pathspec_item(ps->items+i, prefix, name, 360 namelen, flags); 361if(ps->recursive && 362(ps->magic & PATHSPEC_MAXDEPTH) && 363 ps->max_depth != -1&& 364 how && how != MATCHED_FNMATCH) { 365int len = ps->items[i].len; 366if(name[len] =='/') 367 len++; 368if(within_depth(name+len, namelen-len,0, ps->max_depth)) 369 how = MATCHED_EXACTLY; 370else 371 how =0; 372} 373if(how) { 374if(retval < how) 375 retval = how; 376if(seen && seen[i] < how) 377 seen[i] = how; 378} 379} 380return retval; 381} 382 383intmatch_pathspec(const struct pathspec *ps, 384const char*name,int namelen, 385int prefix,char*seen,int is_dir) 386{ 387int positive, negative; 388unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 389 positive =do_match_pathspec(ps, name, namelen, 390 prefix, seen, flags); 391if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 392return positive; 393 negative =do_match_pathspec(ps, name, namelen, 394 prefix, seen, 395 flags | DO_MATCH_EXCLUDE); 396return negative ?0: positive; 397} 398 399intreport_path_error(const char*ps_matched, 400const struct pathspec *pathspec, 401const char*prefix) 402{ 403/* 404 * Make sure all pathspec matched; otherwise it is an error. 405 */ 406int num, errors =0; 407for(num =0; num < pathspec->nr; num++) { 408int other, found_dup; 409 410if(ps_matched[num]) 411continue; 412/* 413 * The caller might have fed identical pathspec 414 * twice. Do not barf on such a mistake. 415 * FIXME: parse_pathspec should have eliminated 416 * duplicate pathspec. 417 */ 418for(found_dup = other =0; 419!found_dup && other < pathspec->nr; 420 other++) { 421if(other == num || !ps_matched[other]) 422continue; 423if(!strcmp(pathspec->items[other].original, 424 pathspec->items[num].original)) 425/* 426 * Ok, we have a match already. 427 */ 428 found_dup =1; 429} 430if(found_dup) 431continue; 432 433error("pathspec '%s' did not match any file(s) known to git.", 434 pathspec->items[num].original); 435 errors++; 436} 437return errors; 438} 439 440/* 441 * Return the length of the "simple" part of a path match limiter. 442 */ 443intsimple_length(const char*match) 444{ 445int len = -1; 446 447for(;;) { 448unsigned char c = *match++; 449 len++; 450if(c =='\0'||is_glob_special(c)) 451return len; 452} 453} 454 455intno_wildcard(const char*string) 456{ 457return string[simple_length(string)] =='\0'; 458} 459 460voidparse_exclude_pattern(const char**pattern, 461int*patternlen, 462int*flags, 463int*nowildcardlen) 464{ 465const char*p = *pattern; 466size_t i, len; 467 468*flags =0; 469if(*p =='!') { 470*flags |= EXC_FLAG_NEGATIVE; 471 p++; 472} 473 len =strlen(p); 474if(len && p[len -1] =='/') { 475 len--; 476*flags |= EXC_FLAG_MUSTBEDIR; 477} 478for(i =0; i < len; i++) { 479if(p[i] =='/') 480break; 481} 482if(i == len) 483*flags |= EXC_FLAG_NODIR; 484*nowildcardlen =simple_length(p); 485/* 486 * we should have excluded the trailing slash from 'p' too, 487 * but that's one more allocation. Instead just make sure 488 * nowildcardlen does not exceed real patternlen 489 */ 490if(*nowildcardlen > len) 491*nowildcardlen = len; 492if(*p =='*'&&no_wildcard(p +1)) 493*flags |= EXC_FLAG_ENDSWITH; 494*pattern = p; 495*patternlen = len; 496} 497 498voidadd_exclude(const char*string,const char*base, 499int baselen,struct exclude_list *el,int srcpos) 500{ 501struct exclude *x; 502int patternlen; 503int flags; 504int nowildcardlen; 505 506parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 507if(flags & EXC_FLAG_MUSTBEDIR) { 508char*s; 509 x =xmalloc(sizeof(*x) + patternlen +1); 510 s = (char*)(x+1); 511memcpy(s, string, patternlen); 512 s[patternlen] ='\0'; 513 x->pattern = s; 514}else{ 515 x =xmalloc(sizeof(*x)); 516 x->pattern = string; 517} 518 x->patternlen = patternlen; 519 x->nowildcardlen = nowildcardlen; 520 x->base = base; 521 x->baselen = baselen; 522 x->flags = flags; 523 x->srcpos = srcpos; 524ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 525 el->excludes[el->nr++] = x; 526 x->el = el; 527} 528 529static void*read_skip_worktree_file_from_index(const char*path,size_t*size, 530struct sha1_stat *sha1_stat) 531{ 532int pos, len; 533unsigned long sz; 534enum object_type type; 535void*data; 536 537 len =strlen(path); 538 pos =cache_name_pos(path, len); 539if(pos <0) 540return NULL; 541if(!ce_skip_worktree(active_cache[pos])) 542return NULL; 543 data =read_sha1_file(active_cache[pos]->sha1, &type, &sz); 544if(!data || type != OBJ_BLOB) { 545free(data); 546return NULL; 547} 548*size =xsize_t(sz); 549if(sha1_stat) { 550memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 551hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 552} 553return data; 554} 555 556/* 557 * Frees memory within el which was allocated for exclude patterns and 558 * the file buffer. Does not free el itself. 559 */ 560voidclear_exclude_list(struct exclude_list *el) 561{ 562int i; 563 564for(i =0; i < el->nr; i++) 565free(el->excludes[i]); 566free(el->excludes); 567free(el->filebuf); 568 569memset(el,0,sizeof(*el)); 570} 571 572static voidtrim_trailing_spaces(char*buf) 573{ 574char*p, *last_space = NULL; 575 576for(p = buf; *p; p++) 577switch(*p) { 578case' ': 579if(!last_space) 580 last_space = p; 581break; 582case'\\': 583 p++; 584if(!*p) 585return; 586/* fallthrough */ 587default: 588 last_space = NULL; 589} 590 591if(last_space) 592*last_space ='\0'; 593} 594 595/* 596 * Given a subdirectory name and "dir" of the current directory, 597 * search the subdir in "dir" and return it, or create a new one if it 598 * does not exist in "dir". 599 * 600 * If "name" has the trailing slash, it'll be excluded in the search. 601 */ 602static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 603struct untracked_cache_dir *dir, 604const char*name,int len) 605{ 606int first, last; 607struct untracked_cache_dir *d; 608if(!dir) 609return NULL; 610if(len && name[len -1] =='/') 611 len--; 612 first =0; 613 last = dir->dirs_nr; 614while(last > first) { 615int cmp, next = (last + first) >>1; 616 d = dir->dirs[next]; 617 cmp =strncmp(name, d->name, len); 618if(!cmp &&strlen(d->name) > len) 619 cmp = -1; 620if(!cmp) 621return d; 622if(cmp <0) { 623 last = next; 624continue; 625} 626 first = next+1; 627} 628 629 uc->dir_created++; 630 d =xmalloc(sizeof(*d) + len +1); 631memset(d,0,sizeof(*d)); 632memcpy(d->name, name, len); 633 d->name[len] ='\0'; 634 635ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 636memmove(dir->dirs + first +1, dir->dirs + first, 637(dir->dirs_nr - first) *sizeof(*dir->dirs)); 638 dir->dirs_nr++; 639 dir->dirs[first] = d; 640return d; 641} 642 643static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 644{ 645int i; 646 dir->valid =0; 647 dir->untracked_nr =0; 648for(i =0; i < dir->dirs_nr; i++) 649do_invalidate_gitignore(dir->dirs[i]); 650} 651 652static voidinvalidate_gitignore(struct untracked_cache *uc, 653struct untracked_cache_dir *dir) 654{ 655 uc->gitignore_invalidated++; 656do_invalidate_gitignore(dir); 657} 658 659static voidinvalidate_directory(struct untracked_cache *uc, 660struct untracked_cache_dir *dir) 661{ 662int i; 663 uc->dir_invalidated++; 664 dir->valid =0; 665 dir->untracked_nr =0; 666for(i =0; i < dir->dirs_nr; i++) 667 dir->dirs[i]->recurse =0; 668} 669 670/* 671 * Given a file with name "fname", read it (either from disk, or from 672 * the index if "check_index" is non-zero), parse it and store the 673 * exclude rules in "el". 674 * 675 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 676 * stat data from disk (only valid if add_excludes returns zero). If 677 * ss_valid is non-zero, "ss" must contain good value as input. 678 */ 679static intadd_excludes(const char*fname,const char*base,int baselen, 680struct exclude_list *el,int check_index, 681struct sha1_stat *sha1_stat) 682{ 683struct stat st; 684int fd, i, lineno =1; 685size_t size =0; 686char*buf, *entry; 687 688 fd =open(fname, O_RDONLY); 689if(fd <0||fstat(fd, &st) <0) { 690if(errno != ENOENT) 691warn_on_inaccessible(fname); 692if(0<= fd) 693close(fd); 694if(!check_index || 695(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 696return-1; 697if(size ==0) { 698free(buf); 699return0; 700} 701if(buf[size-1] !='\n') { 702 buf =xrealloc(buf, size+1); 703 buf[size++] ='\n'; 704} 705}else{ 706 size =xsize_t(st.st_size); 707if(size ==0) { 708if(sha1_stat) { 709fill_stat_data(&sha1_stat->stat, &st); 710hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 711 sha1_stat->valid =1; 712} 713close(fd); 714return0; 715} 716 buf =xmalloc(size+1); 717if(read_in_full(fd, buf, size) != size) { 718free(buf); 719close(fd); 720return-1; 721} 722 buf[size++] ='\n'; 723close(fd); 724if(sha1_stat) { 725int pos; 726if(sha1_stat->valid && 727!match_stat_data_racy(&the_index, &sha1_stat->stat, &st)) 728;/* no content change, ss->sha1 still good */ 729else if(check_index && 730(pos =cache_name_pos(fname,strlen(fname))) >=0&& 731!ce_stage(active_cache[pos]) && 732ce_uptodate(active_cache[pos]) && 733!would_convert_to_git(fname)) 734hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 735else 736hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 737fill_stat_data(&sha1_stat->stat, &st); 738 sha1_stat->valid =1; 739} 740} 741 742 el->filebuf = buf; 743 744if(skip_utf8_bom(&buf, size)) 745 size -= buf - el->filebuf; 746 747 entry = buf; 748 749for(i =0; i < size; i++) { 750if(buf[i] =='\n') { 751if(entry != buf + i && entry[0] !='#') { 752 buf[i - (i && buf[i-1] =='\r')] =0; 753trim_trailing_spaces(entry); 754add_exclude(entry, base, baselen, el, lineno); 755} 756 lineno++; 757 entry = buf + i +1; 758} 759} 760return0; 761} 762 763intadd_excludes_from_file_to_list(const char*fname,const char*base, 764int baselen,struct exclude_list *el, 765int check_index) 766{ 767returnadd_excludes(fname, base, baselen, el, check_index, NULL); 768} 769 770struct exclude_list *add_exclude_list(struct dir_struct *dir, 771int group_type,const char*src) 772{ 773struct exclude_list *el; 774struct exclude_list_group *group; 775 776 group = &dir->exclude_list_group[group_type]; 777ALLOC_GROW(group->el, group->nr +1, group->alloc); 778 el = &group->el[group->nr++]; 779memset(el,0,sizeof(*el)); 780 el->src = src; 781return el; 782} 783 784/* 785 * Used to set up core.excludesfile and .git/info/exclude lists. 786 */ 787static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 788struct sha1_stat *sha1_stat) 789{ 790struct exclude_list *el; 791/* 792 * catch setup_standard_excludes() that's called before 793 * dir->untracked is assigned. That function behaves 794 * differently when dir->untracked is non-NULL. 795 */ 796if(!dir->untracked) 797 dir->unmanaged_exclude_files++; 798 el =add_exclude_list(dir, EXC_FILE, fname); 799if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 800die("cannot use%sas an exclude file", fname); 801} 802 803voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 804{ 805 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 806add_excludes_from_file_1(dir, fname, NULL); 807} 808 809intmatch_basename(const char*basename,int basenamelen, 810const char*pattern,int prefix,int patternlen, 811int flags) 812{ 813if(prefix == patternlen) { 814if(patternlen == basenamelen && 815!strncmp_icase(pattern, basename, basenamelen)) 816return1; 817}else if(flags & EXC_FLAG_ENDSWITH) { 818/* "*literal" matching against "fooliteral" */ 819if(patternlen -1<= basenamelen && 820!strncmp_icase(pattern +1, 821 basename + basenamelen - (patternlen -1), 822 patternlen -1)) 823return1; 824}else{ 825if(fnmatch_icase_mem(pattern, patternlen, 826 basename, basenamelen, 8270) ==0) 828return1; 829} 830return0; 831} 832 833intmatch_pathname(const char*pathname,int pathlen, 834const char*base,int baselen, 835const char*pattern,int prefix,int patternlen, 836int flags) 837{ 838const char*name; 839int namelen; 840 841/* 842 * match with FNM_PATHNAME; the pattern has base implicitly 843 * in front of it. 844 */ 845if(*pattern =='/') { 846 pattern++; 847 patternlen--; 848 prefix--; 849} 850 851/* 852 * baselen does not count the trailing slash. base[] may or 853 * may not end with a trailing slash though. 854 */ 855if(pathlen < baselen +1|| 856(baselen && pathname[baselen] !='/') || 857strncmp_icase(pathname, base, baselen)) 858return0; 859 860 namelen = baselen ? pathlen - baselen -1: pathlen; 861 name = pathname + pathlen - namelen; 862 863if(prefix) { 864/* 865 * if the non-wildcard part is longer than the 866 * remaining pathname, surely it cannot match. 867 */ 868if(prefix > namelen) 869return0; 870 871if(strncmp_icase(pattern, name, prefix)) 872return0; 873 pattern += prefix; 874 patternlen -= prefix; 875 name += prefix; 876 namelen -= prefix; 877 878/* 879 * If the whole pattern did not have a wildcard, 880 * then our prefix match is all we need; we 881 * do not need to call fnmatch at all. 882 */ 883if(!patternlen && (!namelen || *name =='/')) 884return1; 885} 886 887returnfnmatch_icase_mem(pattern, patternlen, 888 name, namelen, 889 WM_PATHNAME) ==0; 890} 891 892/* 893 * Scan the given exclude list in reverse to see whether pathname 894 * should be ignored. The first match (i.e. the last on the list), if 895 * any, determines the fate. Returns the exclude_list element which 896 * matched, or NULL for undecided. 897 */ 898static struct exclude *last_exclude_matching_from_list(const char*pathname, 899int pathlen, 900const char*basename, 901int*dtype, 902struct exclude_list *el) 903{ 904struct exclude *exc = NULL;/* undecided */ 905int i; 906 907if(!el->nr) 908return NULL;/* undefined */ 909 910trace_printf_key(&trace_exclude,"exclude: from%s\n", el->src); 911 912for(i = el->nr -1;0<= i; i--) { 913struct exclude *x = el->excludes[i]; 914const char*exclude = x->pattern; 915int prefix = x->nowildcardlen; 916 917if(x->flags & EXC_FLAG_MUSTBEDIR) { 918if(*dtype == DT_UNKNOWN) 919*dtype =get_dtype(NULL, pathname, pathlen); 920if(*dtype != DT_DIR) 921continue; 922} 923 924if(x->flags & EXC_FLAG_NODIR) { 925if(match_basename(basename, 926 pathlen - (basename - pathname), 927 exclude, prefix, x->patternlen, 928 x->flags)) { 929 exc = x; 930break; 931} 932continue; 933} 934 935assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 936if(match_pathname(pathname, pathlen, 937 x->base, x->baselen ? x->baselen -1:0, 938 exclude, prefix, x->patternlen, x->flags)) { 939 exc = x; 940break; 941} 942} 943 944if(!exc) { 945trace_printf_key(&trace_exclude,"exclude: %.*s => n/a\n", 946 pathlen, pathname); 947return NULL; 948} 949 950trace_printf_key(&trace_exclude,"exclude: %.*s vs%sat line%d=>%s\n", 951 pathlen, pathname, exc->pattern, exc->srcpos, 952 exc->flags & EXC_FLAG_NEGATIVE ?"no":"yes"); 953return exc; 954} 955 956/* 957 * Scan the list and let the last match determine the fate. 958 * Return 1 for exclude, 0 for include and -1 for undecided. 959 */ 960intis_excluded_from_list(const char*pathname, 961int pathlen,const char*basename,int*dtype, 962struct exclude_list *el) 963{ 964struct exclude *exclude; 965 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 966if(exclude) 967return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 968return-1;/* undecided */ 969} 970 971static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 972const char*pathname,int pathlen,const char*basename, 973int*dtype_p) 974{ 975int i, j; 976struct exclude_list_group *group; 977struct exclude *exclude; 978for(i = EXC_CMDL; i <= EXC_FILE; i++) { 979 group = &dir->exclude_list_group[i]; 980for(j = group->nr -1; j >=0; j--) { 981 exclude =last_exclude_matching_from_list( 982 pathname, pathlen, basename, dtype_p, 983&group->el[j]); 984if(exclude) 985return exclude; 986} 987} 988return NULL; 989} 990 991/* 992 * Loads the per-directory exclude list for the substring of base 993 * which has a char length of baselen. 994 */ 995static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen) 996{ 997struct exclude_list_group *group; 998struct exclude_list *el; 999struct exclude_stack *stk = NULL;1000struct untracked_cache_dir *untracked;1001int current;10021003 group = &dir->exclude_list_group[EXC_DIRS];10041005/*1006 * Pop the exclude lists from the EXCL_DIRS exclude_list_group1007 * which originate from directories not in the prefix of the1008 * path being checked.1009 */1010while((stk = dir->exclude_stack) != NULL) {1011if(stk->baselen <= baselen &&1012!strncmp(dir->basebuf.buf, base, stk->baselen))1013break;1014 el = &group->el[dir->exclude_stack->exclude_ix];1015 dir->exclude_stack = stk->prev;1016 dir->exclude = NULL;1017free((char*)el->src);/* see strbuf_detach() below */1018clear_exclude_list(el);1019free(stk);1020 group->nr--;1021}10221023/* Skip traversing into sub directories if the parent is excluded */1024if(dir->exclude)1025return;10261027/*1028 * Lazy initialization. All call sites currently just1029 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1030 * them seems lots of work for little benefit.1031 */1032if(!dir->basebuf.buf)1033strbuf_init(&dir->basebuf, PATH_MAX);10341035/* Read from the parent directories and push them down. */1036 current = stk ? stk->baselen : -1;1037strbuf_setlen(&dir->basebuf, current <0?0: current);1038if(dir->untracked)1039 untracked = stk ? stk->ucd : dir->untracked->root;1040else1041 untracked = NULL;10421043while(current < baselen) {1044const char*cp;1045struct sha1_stat sha1_stat;10461047 stk =xcalloc(1,sizeof(*stk));1048if(current <0) {1049 cp = base;1050 current =0;1051}else{1052 cp =strchr(base + current +1,'/');1053if(!cp)1054die("oops in prep_exclude");1055 cp++;1056 untracked =1057lookup_untracked(dir->untracked, untracked,1058 base + current,1059 cp - base - current);1060}1061 stk->prev = dir->exclude_stack;1062 stk->baselen = cp - base;1063 stk->exclude_ix = group->nr;1064 stk->ucd = untracked;1065 el =add_exclude_list(dir, EXC_DIRS, NULL);1066strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1067assert(stk->baselen == dir->basebuf.len);10681069/* Abort if the directory is excluded */1070if(stk->baselen) {1071int dt = DT_DIR;1072 dir->basebuf.buf[stk->baselen -1] =0;1073 dir->exclude =last_exclude_matching_from_lists(dir,1074 dir->basebuf.buf, stk->baselen -1,1075 dir->basebuf.buf + current, &dt);1076 dir->basebuf.buf[stk->baselen -1] ='/';1077if(dir->exclude &&1078 dir->exclude->flags & EXC_FLAG_NEGATIVE)1079 dir->exclude = NULL;1080if(dir->exclude) {1081 dir->exclude_stack = stk;1082return;1083}1084}10851086/* Try to read per-directory file */1087hashclr(sha1_stat.sha1);1088 sha1_stat.valid =0;1089if(dir->exclude_per_dir &&1090/*1091 * If we know that no files have been added in1092 * this directory (i.e. valid_cached_dir() has1093 * been executed and set untracked->valid) ..1094 */1095(!untracked || !untracked->valid ||1096/*1097 * .. and .gitignore does not exist before1098 * (i.e. null exclude_sha1). Then we can skip1099 * loading .gitignore, which would result in1100 * ENOENT anyway.1101 */1102!is_null_sha1(untracked->exclude_sha1))) {1103/*1104 * dir->basebuf gets reused by the traversal, but we1105 * need fname to remain unchanged to ensure the src1106 * member of each struct exclude correctly1107 * back-references its source file. Other invocations1108 * of add_exclude_list provide stable strings, so we1109 * strbuf_detach() and free() here in the caller.1110 */1111struct strbuf sb = STRBUF_INIT;1112strbuf_addbuf(&sb, &dir->basebuf);1113strbuf_addstr(&sb, dir->exclude_per_dir);1114 el->src =strbuf_detach(&sb, NULL);1115add_excludes(el->src, el->src, stk->baselen, el,1,1116 untracked ? &sha1_stat : NULL);1117}1118/*1119 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1120 * will first be called in valid_cached_dir() then maybe many1121 * times more in last_exclude_matching(). When the cache is1122 * used, last_exclude_matching() will not be called and1123 * reading .gitignore content will be a waste.1124 *1125 * So when it's called by valid_cached_dir() and we can get1126 * .gitignore SHA-1 from the index (i.e. .gitignore is not1127 * modified on work tree), we could delay reading the1128 * .gitignore content until we absolutely need it in1129 * last_exclude_matching(). Be careful about ignore rule1130 * order, though, if you do that.1131 */1132if(untracked &&1133hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1134invalidate_gitignore(dir->untracked, untracked);1135hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1136}1137 dir->exclude_stack = stk;1138 current = stk->baselen;1139}1140strbuf_setlen(&dir->basebuf, baselen);1141}11421143/*1144 * Loads the exclude lists for the directory containing pathname, then1145 * scans all exclude lists to determine whether pathname is excluded.1146 * Returns the exclude_list element which matched, or NULL for1147 * undecided.1148 */1149struct exclude *last_exclude_matching(struct dir_struct *dir,1150const char*pathname,1151int*dtype_p)1152{1153int pathlen =strlen(pathname);1154const char*basename =strrchr(pathname,'/');1155 basename = (basename) ? basename+1: pathname;11561157prep_exclude(dir, pathname, basename-pathname);11581159if(dir->exclude)1160return dir->exclude;11611162returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1163 basename, dtype_p);1164}11651166/*1167 * Loads the exclude lists for the directory containing pathname, then1168 * scans all exclude lists to determine whether pathname is excluded.1169 * Returns 1 if true, otherwise 0.1170 */1171intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1172{1173struct exclude *exclude =1174last_exclude_matching(dir, pathname, dtype_p);1175if(exclude)1176return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1177return0;1178}11791180static struct dir_entry *dir_entry_new(const char*pathname,int len)1181{1182struct dir_entry *ent;11831184 ent =xmalloc(sizeof(*ent) + len +1);1185 ent->len = len;1186memcpy(ent->name, pathname, len);1187 ent->name[len] =0;1188return ent;1189}11901191static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1192{1193if(cache_file_exists(pathname, len, ignore_case))1194return NULL;11951196ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1197return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1198}11991200struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1201{1202if(!cache_name_is_other(pathname, len))1203return NULL;12041205ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1206return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1207}12081209enum exist_status {1210 index_nonexistent =0,1211 index_directory,1212 index_gitdir1213};12141215/*1216 * Do not use the alphabetically sorted index to look up1217 * the directory name; instead, use the case insensitive1218 * directory hash.1219 */1220static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1221{1222struct cache_entry *ce;12231224if(cache_dir_exists(dirname, len))1225return index_directory;12261227 ce =cache_file_exists(dirname, len, ignore_case);1228if(ce &&S_ISGITLINK(ce->ce_mode))1229return index_gitdir;12301231return index_nonexistent;1232}12331234/*1235 * The index sorts alphabetically by entry name, which1236 * means that a gitlink sorts as '\0' at the end, while1237 * a directory (which is defined not as an entry, but as1238 * the files it contains) will sort with the '/' at the1239 * end.1240 */1241static enum exist_status directory_exists_in_index(const char*dirname,int len)1242{1243int pos;12441245if(ignore_case)1246returndirectory_exists_in_index_icase(dirname, len);12471248 pos =cache_name_pos(dirname, len);1249if(pos <0)1250 pos = -pos-1;1251while(pos < active_nr) {1252const struct cache_entry *ce = active_cache[pos++];1253unsigned char endchar;12541255if(strncmp(ce->name, dirname, len))1256break;1257 endchar = ce->name[len];1258if(endchar >'/')1259break;1260if(endchar =='/')1261return index_directory;1262if(!endchar &&S_ISGITLINK(ce->ce_mode))1263return index_gitdir;1264}1265return index_nonexistent;1266}12671268/*1269 * When we find a directory when traversing the filesystem, we1270 * have three distinct cases:1271 *1272 * - ignore it1273 * - see it as a directory1274 * - recurse into it1275 *1276 * and which one we choose depends on a combination of existing1277 * git index contents and the flags passed into the directory1278 * traversal routine.1279 *1280 * Case 1: If we *already* have entries in the index under that1281 * directory name, we always recurse into the directory to see1282 * all the files.1283 *1284 * Case 2: If we *already* have that directory name as a gitlink,1285 * we always continue to see it as a gitlink, regardless of whether1286 * there is an actual git directory there or not (it might not1287 * be checked out as a subproject!)1288 *1289 * Case 3: if we didn't have it in the index previously, we1290 * have a few sub-cases:1291 *1292 * (a) if "show_other_directories" is true, we show it as1293 * just a directory, unless "hide_empty_directories" is1294 * also true, in which case we need to check if it contains any1295 * untracked and / or ignored files.1296 * (b) if it looks like a git directory, and we don't have1297 * 'no_gitlinks' set we treat it as a gitlink, and show it1298 * as a directory.1299 * (c) otherwise, we recurse into it.1300 */1301static enum path_treatment treat_directory(struct dir_struct *dir,1302struct untracked_cache_dir *untracked,1303const char*dirname,int len,int baselen,int exclude,1304const struct path_simplify *simplify)1305{1306/* The "len-1" is to strip the final '/' */1307switch(directory_exists_in_index(dirname, len-1)) {1308case index_directory:1309return path_recurse;13101311case index_gitdir:1312return path_none;13131314case index_nonexistent:1315if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1316break;1317if(!(dir->flags & DIR_NO_GITLINKS)) {1318unsigned char sha1[20];1319if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1320return path_untracked;1321}1322return path_recurse;1323}13241325/* This is the "show_other_directories" case */13261327if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1328return exclude ? path_excluded : path_untracked;13291330 untracked =lookup_untracked(dir->untracked, untracked,1331 dirname + baselen, len - baselen);1332returnread_directory_recursive(dir, dirname, len,1333 untracked,1, simplify);1334}13351336/*1337 * This is an inexact early pruning of any recursive directory1338 * reading - if the path cannot possibly be in the pathspec,1339 * return true, and we'll skip it early.1340 */1341static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1342{1343if(simplify) {1344for(;;) {1345const char*match = simplify->path;1346int len = simplify->len;13471348if(!match)1349break;1350if(len > pathlen)1351 len = pathlen;1352if(!memcmp(path, match, len))1353return0;1354 simplify++;1355}1356return1;1357}1358return0;1359}13601361/*1362 * This function tells us whether an excluded path matches a1363 * list of "interesting" pathspecs. That is, whether a path matched1364 * by any of the pathspecs could possibly be ignored by excluding1365 * the specified path. This can happen if:1366 *1367 * 1. the path is mentioned explicitly in the pathspec1368 *1369 * 2. the path is a directory prefix of some element in the1370 * pathspec1371 */1372static intexclude_matches_pathspec(const char*path,int len,1373const struct path_simplify *simplify)1374{1375if(simplify) {1376for(; simplify->path; simplify++) {1377if(len == simplify->len1378&& !memcmp(path, simplify->path, len))1379return1;1380if(len < simplify->len1381&& simplify->path[len] =='/'1382&& !memcmp(path, simplify->path, len))1383return1;1384}1385}1386return0;1387}13881389static intget_index_dtype(const char*path,int len)1390{1391int pos;1392const struct cache_entry *ce;13931394 ce =cache_file_exists(path, len,0);1395if(ce) {1396if(!ce_uptodate(ce))1397return DT_UNKNOWN;1398if(S_ISGITLINK(ce->ce_mode))1399return DT_DIR;1400/*1401 * Nobody actually cares about the1402 * difference between DT_LNK and DT_REG1403 */1404return DT_REG;1405}14061407/* Try to look it up as a directory */1408 pos =cache_name_pos(path, len);1409if(pos >=0)1410return DT_UNKNOWN;1411 pos = -pos-1;1412while(pos < active_nr) {1413 ce = active_cache[pos++];1414if(strncmp(ce->name, path, len))1415break;1416if(ce->name[len] >'/')1417break;1418if(ce->name[len] <'/')1419continue;1420if(!ce_uptodate(ce))1421break;/* continue? */1422return DT_DIR;1423}1424return DT_UNKNOWN;1425}14261427static intget_dtype(struct dirent *de,const char*path,int len)1428{1429int dtype = de ?DTYPE(de) : DT_UNKNOWN;1430struct stat st;14311432if(dtype != DT_UNKNOWN)1433return dtype;1434 dtype =get_index_dtype(path, len);1435if(dtype != DT_UNKNOWN)1436return dtype;1437if(lstat(path, &st))1438return dtype;1439if(S_ISREG(st.st_mode))1440return DT_REG;1441if(S_ISDIR(st.st_mode))1442return DT_DIR;1443if(S_ISLNK(st.st_mode))1444return DT_LNK;1445return dtype;1446}14471448static enum path_treatment treat_one_path(struct dir_struct *dir,1449struct untracked_cache_dir *untracked,1450struct strbuf *path,1451int baselen,1452const struct path_simplify *simplify,1453int dtype,struct dirent *de)1454{1455int exclude;1456int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);14571458if(dtype == DT_UNKNOWN)1459 dtype =get_dtype(de, path->buf, path->len);14601461/* Always exclude indexed files */1462if(dtype != DT_DIR && has_path_in_index)1463return path_none;14641465/*1466 * When we are looking at a directory P in the working tree,1467 * there are three cases:1468 *1469 * (1) P exists in the index. Everything inside the directory P in1470 * the working tree needs to go when P is checked out from the1471 * index.1472 *1473 * (2) P does not exist in the index, but there is P/Q in the index.1474 * We know P will stay a directory when we check out the contents1475 * of the index, but we do not know yet if there is a directory1476 * P/Q in the working tree to be killed, so we need to recurse.1477 *1478 * (3) P does not exist in the index, and there is no P/Q in the index1479 * to require P to be a directory, either. Only in this case, we1480 * know that everything inside P will not be killed without1481 * recursing.1482 */1483if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1484(dtype == DT_DIR) &&1485!has_path_in_index &&1486(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1487return path_none;14881489 exclude =is_excluded(dir, path->buf, &dtype);14901491/*1492 * Excluded? If we don't explicitly want to show1493 * ignored files, ignore it1494 */1495if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1496return path_excluded;14971498switch(dtype) {1499default:1500return path_none;1501case DT_DIR:1502strbuf_addch(path,'/');1503returntreat_directory(dir, untracked, path->buf, path->len,1504 baselen, exclude, simplify);1505case DT_REG:1506case DT_LNK:1507return exclude ? path_excluded : path_untracked;1508}1509}15101511static enum path_treatment treat_path_fast(struct dir_struct *dir,1512struct untracked_cache_dir *untracked,1513struct cached_dir *cdir,1514struct strbuf *path,1515int baselen,1516const struct path_simplify *simplify)1517{1518strbuf_setlen(path, baselen);1519if(!cdir->ucd) {1520strbuf_addstr(path, cdir->file);1521return path_untracked;1522}1523strbuf_addstr(path, cdir->ucd->name);1524/* treat_one_path() does this before it calls treat_directory() */1525strbuf_complete(path,'/');1526if(cdir->ucd->check_only)1527/*1528 * check_only is set as a result of treat_directory() getting1529 * to its bottom. Verify again the same set of directories1530 * with check_only set.1531 */1532returnread_directory_recursive(dir, path->buf, path->len,1533 cdir->ucd,1, simplify);1534/*1535 * We get path_recurse in the first run when1536 * directory_exists_in_index() returns index_nonexistent. We1537 * are sure that new changes in the index does not impact the1538 * outcome. Return now.1539 */1540return path_recurse;1541}15421543static enum path_treatment treat_path(struct dir_struct *dir,1544struct untracked_cache_dir *untracked,1545struct cached_dir *cdir,1546struct strbuf *path,1547int baselen,1548const struct path_simplify *simplify)1549{1550int dtype;1551struct dirent *de = cdir->de;15521553if(!de)1554returntreat_path_fast(dir, untracked, cdir, path,1555 baselen, simplify);1556if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1557return path_none;1558strbuf_setlen(path, baselen);1559strbuf_addstr(path, de->d_name);1560if(simplify_away(path->buf, path->len, simplify))1561return path_none;15621563 dtype =DTYPE(de);1564returntreat_one_path(dir, untracked, path, baselen, simplify, dtype, de);1565}15661567static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1568{1569if(!dir)1570return;1571ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1572 dir->untracked_alloc);1573 dir->untracked[dir->untracked_nr++] =xstrdup(name);1574}15751576static intvalid_cached_dir(struct dir_struct *dir,1577struct untracked_cache_dir *untracked,1578struct strbuf *path,1579int check_only)1580{1581struct stat st;15821583if(!untracked)1584return0;15851586if(stat(path->len ? path->buf :".", &st)) {1587invalidate_directory(dir->untracked, untracked);1588memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1589return0;1590}1591if(!untracked->valid ||1592match_stat_data_racy(&the_index, &untracked->stat_data, &st)) {1593if(untracked->valid)1594invalidate_directory(dir->untracked, untracked);1595fill_stat_data(&untracked->stat_data, &st);1596return0;1597}15981599if(untracked->check_only != !!check_only) {1600invalidate_directory(dir->untracked, untracked);1601return0;1602}16031604/*1605 * prep_exclude will be called eventually on this directory,1606 * but it's called much later in last_exclude_matching(). We1607 * need it now to determine the validity of the cache for this1608 * path. The next calls will be nearly no-op, the way1609 * prep_exclude() is designed.1610 */1611if(path->len && path->buf[path->len -1] !='/') {1612strbuf_addch(path,'/');1613prep_exclude(dir, path->buf, path->len);1614strbuf_setlen(path, path->len -1);1615}else1616prep_exclude(dir, path->buf, path->len);16171618/* hopefully prep_exclude() haven't invalidated this entry... */1619return untracked->valid;1620}16211622static intopen_cached_dir(struct cached_dir *cdir,1623struct dir_struct *dir,1624struct untracked_cache_dir *untracked,1625struct strbuf *path,1626int check_only)1627{1628memset(cdir,0,sizeof(*cdir));1629 cdir->untracked = untracked;1630if(valid_cached_dir(dir, untracked, path, check_only))1631return0;1632 cdir->fdir =opendir(path->len ? path->buf :".");1633if(dir->untracked)1634 dir->untracked->dir_opened++;1635if(!cdir->fdir)1636return-1;1637return0;1638}16391640static intread_cached_dir(struct cached_dir *cdir)1641{1642if(cdir->fdir) {1643 cdir->de =readdir(cdir->fdir);1644if(!cdir->de)1645return-1;1646return0;1647}1648while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1649struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1650if(!d->recurse) {1651 cdir->nr_dirs++;1652continue;1653}1654 cdir->ucd = d;1655 cdir->nr_dirs++;1656return0;1657}1658 cdir->ucd = NULL;1659if(cdir->nr_files < cdir->untracked->untracked_nr) {1660struct untracked_cache_dir *d = cdir->untracked;1661 cdir->file = d->untracked[cdir->nr_files++];1662return0;1663}1664return-1;1665}16661667static voidclose_cached_dir(struct cached_dir *cdir)1668{1669if(cdir->fdir)1670closedir(cdir->fdir);1671/*1672 * We have gone through this directory and found no untracked1673 * entries. Mark it valid.1674 */1675if(cdir->untracked) {1676 cdir->untracked->valid =1;1677 cdir->untracked->recurse =1;1678}1679}16801681/*1682 * Read a directory tree. We currently ignore anything but1683 * directories, regular files and symlinks. That's because git1684 * doesn't handle them at all yet. Maybe that will change some1685 * day.1686 *1687 * Also, we ignore the name ".git" (even if it is not a directory).1688 * That likely will not change.1689 *1690 * Returns the most significant path_treatment value encountered in the scan.1691 */1692static enum path_treatment read_directory_recursive(struct dir_struct *dir,1693const char*base,int baselen,1694struct untracked_cache_dir *untracked,int check_only,1695const struct path_simplify *simplify)1696{1697struct cached_dir cdir;1698enum path_treatment state, subdir_state, dir_state = path_none;1699struct strbuf path = STRBUF_INIT;1700static int level =0;17011702strbuf_add(&path, base, baselen);17031704trace_printf_key(&trace_exclude,"exclude: [%d] enter '%.*s'\n",1705 level++, baselen, base);17061707if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1708goto out;17091710if(untracked)1711 untracked->check_only = !!check_only;17121713while(!read_cached_dir(&cdir)) {1714/* check how the file or directory should be treated */1715 state =treat_path(dir, untracked, &cdir, &path, baselen, simplify);17161717if(state > dir_state)1718 dir_state = state;17191720/* recurse into subdir if instructed by treat_path */1721if(state == path_recurse) {1722struct untracked_cache_dir *ud;1723 ud =lookup_untracked(dir->untracked, untracked,1724 path.buf + baselen,1725 path.len - baselen);1726 subdir_state =1727read_directory_recursive(dir, path.buf, path.len,1728 ud, check_only, simplify);1729if(subdir_state > dir_state)1730 dir_state = subdir_state;1731}17321733if(check_only) {1734/* abort early if maximum state has been reached */1735if(dir_state == path_untracked) {1736if(cdir.fdir)1737add_untracked(untracked, path.buf + baselen);1738break;1739}1740/* skip the dir_add_* part */1741continue;1742}17431744/* add the path to the appropriate result list */1745switch(state) {1746case path_excluded:1747if(dir->flags & DIR_SHOW_IGNORED)1748dir_add_name(dir, path.buf, path.len);1749else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1750((dir->flags & DIR_COLLECT_IGNORED) &&1751exclude_matches_pathspec(path.buf, path.len,1752 simplify)))1753dir_add_ignored(dir, path.buf, path.len);1754break;17551756case path_untracked:1757if(dir->flags & DIR_SHOW_IGNORED)1758break;1759dir_add_name(dir, path.buf, path.len);1760if(cdir.fdir)1761add_untracked(untracked, path.buf + baselen);1762break;17631764default:1765break;1766}1767}1768close_cached_dir(&cdir);1769 out:1770trace_printf_key(&trace_exclude,"exclude: [%d] leave '%.*s'\n",1771--level, baselen, base);1772strbuf_release(&path);17731774return dir_state;1775}17761777static intcmp_name(const void*p1,const void*p2)1778{1779const struct dir_entry *e1 = *(const struct dir_entry **)p1;1780const struct dir_entry *e2 = *(const struct dir_entry **)p2;17811782returnname_compare(e1->name, e1->len, e2->name, e2->len);1783}17841785static struct path_simplify *create_simplify(const char**pathspec)1786{1787int nr, alloc =0;1788struct path_simplify *simplify = NULL;17891790if(!pathspec)1791return NULL;17921793for(nr =0; ; nr++) {1794const char*match;1795ALLOC_GROW(simplify, nr +1, alloc);1796 match = *pathspec++;1797if(!match)1798break;1799 simplify[nr].path = match;1800 simplify[nr].len =simple_length(match);1801}1802 simplify[nr].path = NULL;1803 simplify[nr].len =0;1804return simplify;1805}18061807static voidfree_simplify(struct path_simplify *simplify)1808{1809free(simplify);1810}18111812static inttreat_leading_path(struct dir_struct *dir,1813const char*path,int len,1814const struct path_simplify *simplify)1815{1816struct strbuf sb = STRBUF_INIT;1817int baselen, rc =0;1818const char*cp;1819int old_flags = dir->flags;18201821while(len && path[len -1] =='/')1822 len--;1823if(!len)1824return1;1825 baselen =0;1826 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1827while(1) {1828 cp = path + baselen + !!baselen;1829 cp =memchr(cp,'/', path + len - cp);1830if(!cp)1831 baselen = len;1832else1833 baselen = cp - path;1834strbuf_setlen(&sb,0);1835strbuf_add(&sb, path, baselen);1836if(!is_directory(sb.buf))1837break;1838if(simplify_away(sb.buf, sb.len, simplify))1839break;1840if(treat_one_path(dir, NULL, &sb, baselen, simplify,1841 DT_DIR, NULL) == path_none)1842break;/* do not recurse into it */1843if(len <= baselen) {1844 rc =1;1845break;/* finished checking */1846}1847}1848strbuf_release(&sb);1849 dir->flags = old_flags;1850return rc;1851}18521853static const char*get_ident_string(void)1854{1855static struct strbuf sb = STRBUF_INIT;1856struct utsname uts;18571858if(sb.len)1859return sb.buf;1860if(uname(&uts) <0)1861die_errno(_("failed to get kernel name and information"));1862strbuf_addf(&sb,"Location%s, system%s",get_git_work_tree(),1863 uts.sysname);1864return sb.buf;1865}18661867static intident_in_untracked(const struct untracked_cache *uc)1868{1869/*1870 * Previous git versions may have saved many NUL separated1871 * strings in the "ident" field, but it is insane to manage1872 * many locations, so just take care of the first one.1873 */18741875return!strcmp(uc->ident.buf,get_ident_string());1876}18771878static voidset_untracked_ident(struct untracked_cache *uc)1879{1880strbuf_reset(&uc->ident);1881strbuf_addstr(&uc->ident,get_ident_string());18821883/*1884 * This strbuf used to contain a list of NUL separated1885 * strings, so save NUL too for backward compatibility.1886 */1887strbuf_addch(&uc->ident,0);1888}18891890static voidnew_untracked_cache(struct index_state *istate)1891{1892struct untracked_cache *uc =xcalloc(1,sizeof(*uc));1893strbuf_init(&uc->ident,100);1894 uc->exclude_per_dir =".gitignore";1895/* should be the same flags used by git-status */1896 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;1897set_untracked_ident(uc);1898 istate->untracked = uc;1899 istate->cache_changed |= UNTRACKED_CHANGED;1900}19011902voidadd_untracked_cache(struct index_state *istate)1903{1904if(!istate->untracked) {1905new_untracked_cache(istate);1906}else{1907if(!ident_in_untracked(istate->untracked)) {1908free_untracked_cache(istate->untracked);1909new_untracked_cache(istate);1910}1911}1912}19131914voidremove_untracked_cache(struct index_state *istate)1915{1916if(istate->untracked) {1917free_untracked_cache(istate->untracked);1918 istate->untracked = NULL;1919 istate->cache_changed |= UNTRACKED_CHANGED;1920}1921}19221923static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1924int base_len,1925const struct pathspec *pathspec)1926{1927struct untracked_cache_dir *root;19281929if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))1930return NULL;19311932/*1933 * We only support $GIT_DIR/info/exclude and core.excludesfile1934 * as the global ignore rule files. Any other additions1935 * (e.g. from command line) invalidate the cache. This1936 * condition also catches running setup_standard_excludes()1937 * before setting dir->untracked!1938 */1939if(dir->unmanaged_exclude_files)1940return NULL;19411942/*1943 * Optimize for the main use case only: whole-tree git1944 * status. More work involved in treat_leading_path() if we1945 * use cache on just a subset of the worktree. pathspec1946 * support could make the matter even worse.1947 */1948if(base_len || (pathspec && pathspec->nr))1949return NULL;19501951/* Different set of flags may produce different results */1952if(dir->flags != dir->untracked->dir_flags ||1953/*1954 * See treat_directory(), case index_nonexistent. Without1955 * this flag, we may need to also cache .git file content1956 * for the resolve_gitlink_ref() call, which we don't.1957 */1958!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1959/* We don't support collecting ignore files */1960(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1961 DIR_COLLECT_IGNORED)))1962return NULL;19631964/*1965 * If we use .gitignore in the cache and now you change it to1966 * .gitexclude, everything will go wrong.1967 */1968if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1969strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1970return NULL;19711972/*1973 * EXC_CMDL is not considered in the cache. If people set it,1974 * skip the cache.1975 */1976if(dir->exclude_list_group[EXC_CMDL].nr)1977return NULL;19781979if(!ident_in_untracked(dir->untracked)) {1980warning(_("Untracked cache is disabled on this system or location."));1981return NULL;1982}19831984if(!dir->untracked->root) {1985const int len =sizeof(*dir->untracked->root);1986 dir->untracked->root =xmalloc(len);1987memset(dir->untracked->root,0, len);1988}19891990/* Validate $GIT_DIR/info/exclude and core.excludesfile */1991 root = dir->untracked->root;1992if(hashcmp(dir->ss_info_exclude.sha1,1993 dir->untracked->ss_info_exclude.sha1)) {1994invalidate_gitignore(dir->untracked, root);1995 dir->untracked->ss_info_exclude = dir->ss_info_exclude;1996}1997if(hashcmp(dir->ss_excludes_file.sha1,1998 dir->untracked->ss_excludes_file.sha1)) {1999invalidate_gitignore(dir->untracked, root);2000 dir->untracked->ss_excludes_file = dir->ss_excludes_file;2001}20022003/* Make sure this directory is not dropped out at saving phase */2004 root->recurse =1;2005return root;2006}20072008intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)2009{2010struct path_simplify *simplify;2011struct untracked_cache_dir *untracked;20122013/*2014 * Check out create_simplify()2015 */2016if(pathspec)2017GUARD_PATHSPEC(pathspec,2018 PATHSPEC_FROMTOP |2019 PATHSPEC_MAXDEPTH |2020 PATHSPEC_LITERAL |2021 PATHSPEC_GLOB |2022 PATHSPEC_ICASE |2023 PATHSPEC_EXCLUDE);20242025if(has_symlink_leading_path(path, len))2026return dir->nr;20272028/*2029 * exclude patterns are treated like positive ones in2030 * create_simplify. Usually exclude patterns should be a2031 * subset of positive ones, which has no impacts on2032 * create_simplify().2033 */2034 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);2035 untracked =validate_untracked_cache(dir, len, pathspec);2036if(!untracked)2037/*2038 * make sure untracked cache code path is disabled,2039 * e.g. prep_exclude()2040 */2041 dir->untracked = NULL;2042if(!len ||treat_leading_path(dir, path, len, simplify))2043read_directory_recursive(dir, path, len, untracked,0, simplify);2044free_simplify(simplify);2045qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);2046qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);2047if(dir->untracked) {2048static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);2049trace_printf_key(&trace_untracked_stats,2050"node creation:%u\n"2051"gitignore invalidation:%u\n"2052"directory invalidation:%u\n"2053"opendir:%u\n",2054 dir->untracked->dir_created,2055 dir->untracked->gitignore_invalidated,2056 dir->untracked->dir_invalidated,2057 dir->untracked->dir_opened);2058if(dir->untracked == the_index.untracked &&2059(dir->untracked->dir_opened ||2060 dir->untracked->gitignore_invalidated ||2061 dir->untracked->dir_invalidated))2062 the_index.cache_changed |= UNTRACKED_CHANGED;2063if(dir->untracked != the_index.untracked) {2064free(dir->untracked);2065 dir->untracked = NULL;2066}2067}2068return dir->nr;2069}20702071intfile_exists(const char*f)2072{2073struct stat sb;2074returnlstat(f, &sb) ==0;2075}20762077static intcmp_icase(char a,char b)2078{2079if(a == b)2080return0;2081if(ignore_case)2082returntoupper(a) -toupper(b);2083return a - b;2084}20852086/*2087 * Given two normalized paths (a trailing slash is ok), if subdir is2088 * outside dir, return -1. Otherwise return the offset in subdir that2089 * can be used as relative path to dir.2090 */2091intdir_inside_of(const char*subdir,const char*dir)2092{2093int offset =0;20942095assert(dir && subdir && *dir && *subdir);20962097while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2098 dir++;2099 subdir++;2100 offset++;2101}21022103/* hel[p]/me vs hel[l]/yeah */2104if(*dir && *subdir)2105return-1;21062107if(!*subdir)2108return!*dir ? offset : -1;/* same dir */21092110/* foo/[b]ar vs foo/[] */2111if(is_dir_sep(dir[-1]))2112returnis_dir_sep(subdir[-1]) ? offset : -1;21132114/* foo[/]bar vs foo[] */2115returnis_dir_sep(*subdir) ? offset +1: -1;2116}21172118intis_inside_dir(const char*dir)2119{2120char*cwd;2121int rc;21222123if(!dir)2124return0;21252126 cwd =xgetcwd();2127 rc = (dir_inside_of(cwd, dir) >=0);2128free(cwd);2129return rc;2130}21312132intis_empty_dir(const char*path)2133{2134DIR*dir =opendir(path);2135struct dirent *e;2136int ret =1;21372138if(!dir)2139return0;21402141while((e =readdir(dir)) != NULL)2142if(!is_dot_or_dotdot(e->d_name)) {2143 ret =0;2144break;2145}21462147closedir(dir);2148return ret;2149}21502151static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2152{2153DIR*dir;2154struct dirent *e;2155int ret =0, original_len = path->len, len, kept_down =0;2156int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2157int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2158unsigned char submodule_head[20];21592160if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2161!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2162/* Do not descend and nuke a nested git work tree. */2163if(kept_up)2164*kept_up =1;2165return0;2166}21672168 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2169 dir =opendir(path->buf);2170if(!dir) {2171if(errno == ENOENT)2172return keep_toplevel ? -1:0;2173else if(errno == EACCES && !keep_toplevel)2174/*2175 * An empty dir could be removable even if it2176 * is unreadable:2177 */2178returnrmdir(path->buf);2179else2180return-1;2181}2182strbuf_complete(path,'/');21832184 len = path->len;2185while((e =readdir(dir)) != NULL) {2186struct stat st;2187if(is_dot_or_dotdot(e->d_name))2188continue;21892190strbuf_setlen(path, len);2191strbuf_addstr(path, e->d_name);2192if(lstat(path->buf, &st)) {2193if(errno == ENOENT)2194/*2195 * file disappeared, which is what we2196 * wanted anyway2197 */2198continue;2199/* fall thru */2200}else if(S_ISDIR(st.st_mode)) {2201if(!remove_dir_recurse(path, flag, &kept_down))2202continue;/* happy */2203}else if(!only_empty &&2204(!unlink(path->buf) || errno == ENOENT)) {2205continue;/* happy, too */2206}22072208/* path too long, stat fails, or non-directory still exists */2209 ret = -1;2210break;2211}2212closedir(dir);22132214strbuf_setlen(path, original_len);2215if(!ret && !keep_toplevel && !kept_down)2216 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2217else if(kept_up)2218/*2219 * report the uplevel that it is not an error that we2220 * did not rmdir() our directory.2221 */2222*kept_up = !ret;2223return ret;2224}22252226intremove_dir_recursively(struct strbuf *path,int flag)2227{2228returnremove_dir_recurse(path, flag, NULL);2229}22302231staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")22322233voidsetup_standard_excludes(struct dir_struct *dir)2234{2235const char*path;22362237 dir->exclude_per_dir =".gitignore";22382239/* core.excludefile defaulting to $XDG_HOME/git/ignore */2240if(!excludes_file)2241 excludes_file =xdg_config_home("ignore");2242if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2243add_excludes_from_file_1(dir, excludes_file,2244 dir->untracked ? &dir->ss_excludes_file : NULL);22452246/* per repository user preference */2247 path =git_path_info_exclude();2248if(!access_or_warn(path, R_OK,0))2249add_excludes_from_file_1(dir, path,2250 dir->untracked ? &dir->ss_info_exclude : NULL);2251}22522253intremove_path(const char*name)2254{2255char*slash;22562257if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2258return-1;22592260 slash =strrchr(name,'/');2261if(slash) {2262char*dirs =xstrdup(name);2263 slash = dirs + (slash - name);2264do{2265*slash ='\0';2266}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2267free(dirs);2268}2269return0;2270}22712272/*2273 * Frees memory within dir which was allocated for exclude lists and2274 * the exclude_stack. Does not free dir itself.2275 */2276voidclear_directory(struct dir_struct *dir)2277{2278int i, j;2279struct exclude_list_group *group;2280struct exclude_list *el;2281struct exclude_stack *stk;22822283for(i = EXC_CMDL; i <= EXC_FILE; i++) {2284 group = &dir->exclude_list_group[i];2285for(j =0; j < group->nr; j++) {2286 el = &group->el[j];2287if(i == EXC_DIRS)2288free((char*)el->src);2289clear_exclude_list(el);2290}2291free(group->el);2292}22932294 stk = dir->exclude_stack;2295while(stk) {2296struct exclude_stack *prev = stk->prev;2297free(stk);2298 stk = prev;2299}2300strbuf_release(&dir->basebuf);2301}23022303struct ondisk_untracked_cache {2304struct stat_data info_exclude_stat;2305struct stat_data excludes_file_stat;2306uint32_t dir_flags;2307unsigned char info_exclude_sha1[20];2308unsigned char excludes_file_sha1[20];2309char exclude_per_dir[FLEX_ARRAY];2310};23112312#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)23132314struct write_data {2315int index;/* number of written untracked_cache_dir */2316struct ewah_bitmap *check_only;/* from untracked_cache_dir */2317struct ewah_bitmap *valid;/* from untracked_cache_dir */2318struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2319struct strbuf out;2320struct strbuf sb_stat;2321struct strbuf sb_sha1;2322};23232324static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2325{2326 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2327 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2328 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2329 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2330 to->sd_dev =htonl(from->sd_dev);2331 to->sd_ino =htonl(from->sd_ino);2332 to->sd_uid =htonl(from->sd_uid);2333 to->sd_gid =htonl(from->sd_gid);2334 to->sd_size =htonl(from->sd_size);2335}23362337static voidwrite_one_dir(struct untracked_cache_dir *untracked,2338struct write_data *wd)2339{2340struct stat_data stat_data;2341struct strbuf *out = &wd->out;2342unsigned char intbuf[16];2343unsigned int intlen, value;2344int i = wd->index++;23452346/*2347 * untracked_nr should be reset whenever valid is clear, but2348 * for safety..2349 */2350if(!untracked->valid) {2351 untracked->untracked_nr =0;2352 untracked->check_only =0;2353}23542355if(untracked->check_only)2356ewah_set(wd->check_only, i);2357if(untracked->valid) {2358ewah_set(wd->valid, i);2359stat_data_to_disk(&stat_data, &untracked->stat_data);2360strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2361}2362if(!is_null_sha1(untracked->exclude_sha1)) {2363ewah_set(wd->sha1_valid, i);2364strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2365}23662367 intlen =encode_varint(untracked->untracked_nr, intbuf);2368strbuf_add(out, intbuf, intlen);23692370/* skip non-recurse directories */2371for(i =0, value =0; i < untracked->dirs_nr; i++)2372if(untracked->dirs[i]->recurse)2373 value++;2374 intlen =encode_varint(value, intbuf);2375strbuf_add(out, intbuf, intlen);23762377strbuf_add(out, untracked->name,strlen(untracked->name) +1);23782379for(i =0; i < untracked->untracked_nr; i++)2380strbuf_add(out, untracked->untracked[i],2381strlen(untracked->untracked[i]) +1);23822383for(i =0; i < untracked->dirs_nr; i++)2384if(untracked->dirs[i]->recurse)2385write_one_dir(untracked->dirs[i], wd);2386}23872388voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2389{2390struct ondisk_untracked_cache *ouc;2391struct write_data wd;2392unsigned char varbuf[16];2393int len =0, varint_len;2394if(untracked->exclude_per_dir)2395 len =strlen(untracked->exclude_per_dir);2396 ouc =xmalloc(sizeof(*ouc) + len +1);2397stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2398stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2399hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2400hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2401 ouc->dir_flags =htonl(untracked->dir_flags);2402memcpy(ouc->exclude_per_dir, untracked->exclude_per_dir, len +1);24032404 varint_len =encode_varint(untracked->ident.len, varbuf);2405strbuf_add(out, varbuf, varint_len);2406strbuf_add(out, untracked->ident.buf, untracked->ident.len);24072408strbuf_add(out, ouc,ouc_size(len));2409free(ouc);2410 ouc = NULL;24112412if(!untracked->root) {2413 varint_len =encode_varint(0, varbuf);2414strbuf_add(out, varbuf, varint_len);2415return;2416}24172418 wd.index =0;2419 wd.check_only =ewah_new();2420 wd.valid =ewah_new();2421 wd.sha1_valid =ewah_new();2422strbuf_init(&wd.out,1024);2423strbuf_init(&wd.sb_stat,1024);2424strbuf_init(&wd.sb_sha1,1024);2425write_one_dir(untracked->root, &wd);24262427 varint_len =encode_varint(wd.index, varbuf);2428strbuf_add(out, varbuf, varint_len);2429strbuf_addbuf(out, &wd.out);2430ewah_serialize_strbuf(wd.valid, out);2431ewah_serialize_strbuf(wd.check_only, out);2432ewah_serialize_strbuf(wd.sha1_valid, out);2433strbuf_addbuf(out, &wd.sb_stat);2434strbuf_addbuf(out, &wd.sb_sha1);2435strbuf_addch(out,'\0');/* safe guard for string lists */24362437ewah_free(wd.valid);2438ewah_free(wd.check_only);2439ewah_free(wd.sha1_valid);2440strbuf_release(&wd.out);2441strbuf_release(&wd.sb_stat);2442strbuf_release(&wd.sb_sha1);2443}24442445static voidfree_untracked(struct untracked_cache_dir *ucd)2446{2447int i;2448if(!ucd)2449return;2450for(i =0; i < ucd->dirs_nr; i++)2451free_untracked(ucd->dirs[i]);2452for(i =0; i < ucd->untracked_nr; i++)2453free(ucd->untracked[i]);2454free(ucd->untracked);2455free(ucd->dirs);2456free(ucd);2457}24582459voidfree_untracked_cache(struct untracked_cache *uc)2460{2461if(uc)2462free_untracked(uc->root);2463free(uc);2464}24652466struct read_data {2467int index;2468struct untracked_cache_dir **ucd;2469struct ewah_bitmap *check_only;2470struct ewah_bitmap *valid;2471struct ewah_bitmap *sha1_valid;2472const unsigned char*data;2473const unsigned char*end;2474};24752476static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2477{2478 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2479 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2480 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2481 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2482 to->sd_dev =get_be32(&from->sd_dev);2483 to->sd_ino =get_be32(&from->sd_ino);2484 to->sd_uid =get_be32(&from->sd_uid);2485 to->sd_gid =get_be32(&from->sd_gid);2486 to->sd_size =get_be32(&from->sd_size);2487}24882489static intread_one_dir(struct untracked_cache_dir **untracked_,2490struct read_data *rd)2491{2492struct untracked_cache_dir ud, *untracked;2493const unsigned char*next, *data = rd->data, *end = rd->end;2494unsigned int value;2495int i, len;24962497memset(&ud,0,sizeof(ud));24982499 next = data;2500 value =decode_varint(&next);2501if(next > end)2502return-1;2503 ud.recurse =1;2504 ud.untracked_alloc = value;2505 ud.untracked_nr = value;2506if(ud.untracked_nr)2507 ud.untracked =xmalloc(sizeof(*ud.untracked) * ud.untracked_nr);2508 data = next;25092510 next = data;2511 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2512if(next > end)2513return-1;2514 ud.dirs =xmalloc(sizeof(*ud.dirs) * ud.dirs_nr);2515 data = next;25162517 len =strlen((const char*)data);2518 next = data + len +1;2519if(next > rd->end)2520return-1;2521*untracked_ = untracked =xmalloc(sizeof(*untracked) + len);2522memcpy(untracked, &ud,sizeof(ud));2523memcpy(untracked->name, data, len +1);2524 data = next;25252526for(i =0; i < untracked->untracked_nr; i++) {2527 len =strlen((const char*)data);2528 next = data + len +1;2529if(next > rd->end)2530return-1;2531 untracked->untracked[i] =xstrdup((const char*)data);2532 data = next;2533}25342535 rd->ucd[rd->index++] = untracked;2536 rd->data = data;25372538for(i =0; i < untracked->dirs_nr; i++) {2539 len =read_one_dir(untracked->dirs + i, rd);2540if(len <0)2541return-1;2542}2543return0;2544}25452546static voidset_check_only(size_t pos,void*cb)2547{2548struct read_data *rd = cb;2549struct untracked_cache_dir *ud = rd->ucd[pos];2550 ud->check_only =1;2551}25522553static voidread_stat(size_t pos,void*cb)2554{2555struct read_data *rd = cb;2556struct untracked_cache_dir *ud = rd->ucd[pos];2557if(rd->data +sizeof(struct stat_data) > rd->end) {2558 rd->data = rd->end +1;2559return;2560}2561stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2562 rd->data +=sizeof(struct stat_data);2563 ud->valid =1;2564}25652566static voidread_sha1(size_t pos,void*cb)2567{2568struct read_data *rd = cb;2569struct untracked_cache_dir *ud = rd->ucd[pos];2570if(rd->data +20> rd->end) {2571 rd->data = rd->end +1;2572return;2573}2574hashcpy(ud->exclude_sha1, rd->data);2575 rd->data +=20;2576}25772578static voidload_sha1_stat(struct sha1_stat *sha1_stat,2579const struct stat_data *stat,2580const unsigned char*sha1)2581{2582stat_data_from_disk(&sha1_stat->stat, stat);2583hashcpy(sha1_stat->sha1, sha1);2584 sha1_stat->valid =1;2585}25862587struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2588{2589const struct ondisk_untracked_cache *ouc;2590struct untracked_cache *uc;2591struct read_data rd;2592const unsigned char*next = data, *end = (const unsigned char*)data + sz;2593const char*ident;2594int ident_len, len;25952596if(sz <=1|| end[-1] !='\0')2597return NULL;2598 end--;25992600 ident_len =decode_varint(&next);2601if(next + ident_len > end)2602return NULL;2603 ident = (const char*)next;2604 next += ident_len;26052606 ouc = (const struct ondisk_untracked_cache *)next;2607if(next +ouc_size(0) > end)2608return NULL;26092610 uc =xcalloc(1,sizeof(*uc));2611strbuf_init(&uc->ident, ident_len);2612strbuf_add(&uc->ident, ident, ident_len);2613load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2614 ouc->info_exclude_sha1);2615load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2616 ouc->excludes_file_sha1);2617 uc->dir_flags =get_be32(&ouc->dir_flags);2618 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2619/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2620 next +=ouc_size(strlen(ouc->exclude_per_dir));2621if(next >= end)2622goto done2;26232624 len =decode_varint(&next);2625if(next > end || len ==0)2626goto done2;26272628 rd.valid =ewah_new();2629 rd.check_only =ewah_new();2630 rd.sha1_valid =ewah_new();2631 rd.data = next;2632 rd.end = end;2633 rd.index =0;2634 rd.ucd =xmalloc(sizeof(*rd.ucd) * len);26352636if(read_one_dir(&uc->root, &rd) || rd.index != len)2637goto done;26382639 next = rd.data;2640 len =ewah_read_mmap(rd.valid, next, end - next);2641if(len <0)2642goto done;26432644 next += len;2645 len =ewah_read_mmap(rd.check_only, next, end - next);2646if(len <0)2647goto done;26482649 next += len;2650 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2651if(len <0)2652goto done;26532654ewah_each_bit(rd.check_only, set_check_only, &rd);2655 rd.data = next + len;2656ewah_each_bit(rd.valid, read_stat, &rd);2657ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2658 next = rd.data;26592660done:2661free(rd.ucd);2662ewah_free(rd.valid);2663ewah_free(rd.check_only);2664ewah_free(rd.sha1_valid);2665done2:2666if(next != end) {2667free_untracked_cache(uc);2668 uc = NULL;2669}2670return uc;2671}26722673static voidinvalidate_one_directory(struct untracked_cache *uc,2674struct untracked_cache_dir *ucd)2675{2676 uc->dir_invalidated++;2677 ucd->valid =0;2678 ucd->untracked_nr =0;2679}26802681/*2682 * Normally when an entry is added or removed from a directory,2683 * invalidating that directory is enough. No need to touch its2684 * ancestors. When a directory is shown as "foo/bar/" in git-status2685 * however, deleting or adding an entry may have cascading effect.2686 *2687 * Say the "foo/bar/file" has become untracked, we need to tell the2688 * untracked_cache_dir of "foo" that "bar/" is not an untracked2689 * directory any more (because "bar" is managed by foo as an untracked2690 * "file").2691 *2692 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2693 * was the last untracked entry in the entire "foo", we should show2694 * "foo/" instead. Which means we have to invalidate past "bar" up to2695 * "foo".2696 *2697 * This function traverses all directories from root to leaf. If there2698 * is a chance of one of the above cases happening, we invalidate back2699 * to root. Otherwise we just invalidate the leaf. There may be a more2700 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2701 * detect these cases and avoid unnecessary invalidation, for example,2702 * checking for the untracked entry named "bar/" in "foo", but for now2703 * stick to something safe and simple.2704 */2705static intinvalidate_one_component(struct untracked_cache *uc,2706struct untracked_cache_dir *dir,2707const char*path,int len)2708{2709const char*rest =strchr(path,'/');27102711if(rest) {2712int component_len = rest - path;2713struct untracked_cache_dir *d =2714lookup_untracked(uc, dir, path, component_len);2715int ret =2716invalidate_one_component(uc, d, rest +1,2717 len - (component_len +1));2718if(ret)2719invalidate_one_directory(uc, dir);2720return ret;2721}27222723invalidate_one_directory(uc, dir);2724return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2725}27262727voiduntracked_cache_invalidate_path(struct index_state *istate,2728const char*path)2729{2730if(!istate->untracked || !istate->untracked->root)2731return;2732invalidate_one_component(istate->untracked, istate->untracked->root,2733 path,strlen(path));2734}27352736voiduntracked_cache_remove_from_index(struct index_state *istate,2737const char*path)2738{2739untracked_cache_invalidate_path(istate, path);2740}27412742voiduntracked_cache_add_to_index(struct index_state *istate,2743const char*path)2744{2745untracked_cache_invalidate_path(istate, path);2746}