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 */ 404struct strbuf sb = STRBUF_INIT; 405int num, errors =0; 406for(num =0; num < pathspec->nr; num++) { 407int other, found_dup; 408 409if(ps_matched[num]) 410continue; 411/* 412 * The caller might have fed identical pathspec 413 * twice. Do not barf on such a mistake. 414 * FIXME: parse_pathspec should have eliminated 415 * duplicate pathspec. 416 */ 417for(found_dup = other =0; 418!found_dup && other < pathspec->nr; 419 other++) { 420if(other == num || !ps_matched[other]) 421continue; 422if(!strcmp(pathspec->items[other].original, 423 pathspec->items[num].original)) 424/* 425 * Ok, we have a match already. 426 */ 427 found_dup =1; 428} 429if(found_dup) 430continue; 431 432error("pathspec '%s' did not match any file(s) known to git.", 433 pathspec->items[num].original); 434 errors++; 435} 436strbuf_release(&sb); 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 569 el->nr =0; 570 el->excludes = NULL; 571 el->filebuf = NULL; 572} 573 574static voidtrim_trailing_spaces(char*buf) 575{ 576char*p, *last_space = NULL; 577 578for(p = buf; *p; p++) 579switch(*p) { 580case' ': 581if(!last_space) 582 last_space = p; 583break; 584case'\\': 585 p++; 586if(!*p) 587return; 588/* fallthrough */ 589default: 590 last_space = NULL; 591} 592 593if(last_space) 594*last_space ='\0'; 595} 596 597/* 598 * Given a subdirectory name and "dir" of the current directory, 599 * search the subdir in "dir" and return it, or create a new one if it 600 * does not exist in "dir". 601 * 602 * If "name" has the trailing slash, it'll be excluded in the search. 603 */ 604static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 605struct untracked_cache_dir *dir, 606const char*name,int len) 607{ 608int first, last; 609struct untracked_cache_dir *d; 610if(!dir) 611return NULL; 612if(len && name[len -1] =='/') 613 len--; 614 first =0; 615 last = dir->dirs_nr; 616while(last > first) { 617int cmp, next = (last + first) >>1; 618 d = dir->dirs[next]; 619 cmp =strncmp(name, d->name, len); 620if(!cmp &&strlen(d->name) > len) 621 cmp = -1; 622if(!cmp) 623return d; 624if(cmp <0) { 625 last = next; 626continue; 627} 628 first = next+1; 629} 630 631 uc->dir_created++; 632 d =xmalloc(sizeof(*d) + len +1); 633memset(d,0,sizeof(*d)); 634memcpy(d->name, name, len); 635 d->name[len] ='\0'; 636 637ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 638memmove(dir->dirs + first +1, dir->dirs + first, 639(dir->dirs_nr - first) *sizeof(*dir->dirs)); 640 dir->dirs_nr++; 641 dir->dirs[first] = d; 642return d; 643} 644 645static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 646{ 647int i; 648 dir->valid =0; 649 dir->untracked_nr =0; 650for(i =0; i < dir->dirs_nr; i++) 651do_invalidate_gitignore(dir->dirs[i]); 652} 653 654static voidinvalidate_gitignore(struct untracked_cache *uc, 655struct untracked_cache_dir *dir) 656{ 657 uc->gitignore_invalidated++; 658do_invalidate_gitignore(dir); 659} 660 661static voidinvalidate_directory(struct untracked_cache *uc, 662struct untracked_cache_dir *dir) 663{ 664int i; 665 uc->dir_invalidated++; 666 dir->valid =0; 667 dir->untracked_nr =0; 668for(i =0; i < dir->dirs_nr; i++) 669 dir->dirs[i]->recurse =0; 670} 671 672/* 673 * Given a file with name "fname", read it (either from disk, or from 674 * the index if "check_index" is non-zero), parse it and store the 675 * exclude rules in "el". 676 * 677 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 678 * stat data from disk (only valid if add_excludes returns zero). If 679 * ss_valid is non-zero, "ss" must contain good value as input. 680 */ 681static intadd_excludes(const char*fname,const char*base,int baselen, 682struct exclude_list *el,int check_index, 683struct sha1_stat *sha1_stat) 684{ 685struct stat st; 686int fd, i, lineno =1; 687size_t size =0; 688char*buf, *entry; 689 690 fd =open(fname, O_RDONLY); 691if(fd <0||fstat(fd, &st) <0) { 692if(errno != ENOENT) 693warn_on_inaccessible(fname); 694if(0<= fd) 695close(fd); 696if(!check_index || 697(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 698return-1; 699if(size ==0) { 700free(buf); 701return0; 702} 703if(buf[size-1] !='\n') { 704 buf =xrealloc(buf, size+1); 705 buf[size++] ='\n'; 706} 707}else{ 708 size =xsize_t(st.st_size); 709if(size ==0) { 710if(sha1_stat) { 711fill_stat_data(&sha1_stat->stat, &st); 712hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 713 sha1_stat->valid =1; 714} 715close(fd); 716return0; 717} 718 buf =xmalloc(size+1); 719if(read_in_full(fd, buf, size) != size) { 720free(buf); 721close(fd); 722return-1; 723} 724 buf[size++] ='\n'; 725close(fd); 726if(sha1_stat) { 727int pos; 728if(sha1_stat->valid && 729!match_stat_data_racy(&the_index, &sha1_stat->stat, &st)) 730;/* no content change, ss->sha1 still good */ 731else if(check_index && 732(pos =cache_name_pos(fname,strlen(fname))) >=0&& 733!ce_stage(active_cache[pos]) && 734ce_uptodate(active_cache[pos]) && 735!would_convert_to_git(fname)) 736hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 737else 738hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 739fill_stat_data(&sha1_stat->stat, &st); 740 sha1_stat->valid =1; 741} 742} 743 744 el->filebuf = buf; 745 746if(skip_utf8_bom(&buf, size)) 747 size -= buf - el->filebuf; 748 749 entry = buf; 750 751for(i =0; i < size; i++) { 752if(buf[i] =='\n') { 753if(entry != buf + i && entry[0] !='#') { 754 buf[i - (i && buf[i-1] =='\r')] =0; 755trim_trailing_spaces(entry); 756add_exclude(entry, base, baselen, el, lineno); 757} 758 lineno++; 759 entry = buf + i +1; 760} 761} 762return0; 763} 764 765intadd_excludes_from_file_to_list(const char*fname,const char*base, 766int baselen,struct exclude_list *el, 767int check_index) 768{ 769returnadd_excludes(fname, base, baselen, el, check_index, NULL); 770} 771 772struct exclude_list *add_exclude_list(struct dir_struct *dir, 773int group_type,const char*src) 774{ 775struct exclude_list *el; 776struct exclude_list_group *group; 777 778 group = &dir->exclude_list_group[group_type]; 779ALLOC_GROW(group->el, group->nr +1, group->alloc); 780 el = &group->el[group->nr++]; 781memset(el,0,sizeof(*el)); 782 el->src = src; 783return el; 784} 785 786/* 787 * Used to set up core.excludesfile and .git/info/exclude lists. 788 */ 789static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 790struct sha1_stat *sha1_stat) 791{ 792struct exclude_list *el; 793/* 794 * catch setup_standard_excludes() that's called before 795 * dir->untracked is assigned. That function behaves 796 * differently when dir->untracked is non-NULL. 797 */ 798if(!dir->untracked) 799 dir->unmanaged_exclude_files++; 800 el =add_exclude_list(dir, EXC_FILE, fname); 801if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 802die("cannot use%sas an exclude file", fname); 803} 804 805voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 806{ 807 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 808add_excludes_from_file_1(dir, fname, NULL); 809} 810 811intmatch_basename(const char*basename,int basenamelen, 812const char*pattern,int prefix,int patternlen, 813int flags) 814{ 815if(prefix == patternlen) { 816if(patternlen == basenamelen && 817!strncmp_icase(pattern, basename, basenamelen)) 818return1; 819}else if(flags & EXC_FLAG_ENDSWITH) { 820/* "*literal" matching against "fooliteral" */ 821if(patternlen -1<= basenamelen && 822!strncmp_icase(pattern +1, 823 basename + basenamelen - (patternlen -1), 824 patternlen -1)) 825return1; 826}else{ 827if(fnmatch_icase_mem(pattern, patternlen, 828 basename, basenamelen, 8290) ==0) 830return1; 831} 832return0; 833} 834 835intmatch_pathname(const char*pathname,int pathlen, 836const char*base,int baselen, 837const char*pattern,int prefix,int patternlen, 838int flags) 839{ 840const char*name; 841int namelen; 842 843/* 844 * match with FNM_PATHNAME; the pattern has base implicitly 845 * in front of it. 846 */ 847if(*pattern =='/') { 848 pattern++; 849 patternlen--; 850 prefix--; 851} 852 853/* 854 * baselen does not count the trailing slash. base[] may or 855 * may not end with a trailing slash though. 856 */ 857if(pathlen < baselen +1|| 858(baselen && pathname[baselen] !='/') || 859strncmp_icase(pathname, base, baselen)) 860return0; 861 862 namelen = baselen ? pathlen - baselen -1: pathlen; 863 name = pathname + pathlen - namelen; 864 865if(prefix) { 866/* 867 * if the non-wildcard part is longer than the 868 * remaining pathname, surely it cannot match. 869 */ 870if(prefix > namelen) 871return0; 872 873if(strncmp_icase(pattern, name, prefix)) 874return0; 875 pattern += prefix; 876 patternlen -= prefix; 877 name += prefix; 878 namelen -= prefix; 879 880/* 881 * If the whole pattern did not have a wildcard, 882 * then our prefix match is all we need; we 883 * do not need to call fnmatch at all. 884 */ 885if(!patternlen && !namelen) 886return1; 887} 888 889returnfnmatch_icase_mem(pattern, patternlen, 890 name, namelen, 891 WM_PATHNAME) ==0; 892} 893 894/* 895 * Scan the given exclude list in reverse to see whether pathname 896 * should be ignored. The first match (i.e. the last on the list), if 897 * any, determines the fate. Returns the exclude_list element which 898 * matched, or NULL for undecided. 899 */ 900static struct exclude *last_exclude_matching_from_list(const char*pathname, 901int pathlen, 902const char*basename, 903int*dtype, 904struct exclude_list *el) 905{ 906int i; 907 908if(!el->nr) 909return NULL;/* undefined */ 910 911for(i = el->nr -1;0<= i; i--) { 912struct exclude *x = el->excludes[i]; 913const char*exclude = x->pattern; 914int prefix = x->nowildcardlen; 915 916if(x->flags & EXC_FLAG_MUSTBEDIR) { 917if(*dtype == DT_UNKNOWN) 918*dtype =get_dtype(NULL, pathname, pathlen); 919if(*dtype != DT_DIR) 920continue; 921} 922 923if(x->flags & EXC_FLAG_NODIR) { 924if(match_basename(basename, 925 pathlen - (basename - pathname), 926 exclude, prefix, x->patternlen, 927 x->flags)) 928return x; 929continue; 930} 931 932assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 933if(match_pathname(pathname, pathlen, 934 x->base, x->baselen ? x->baselen -1:0, 935 exclude, prefix, x->patternlen, x->flags)) 936return x; 937} 938return NULL;/* undecided */ 939} 940 941/* 942 * Scan the list and let the last match determine the fate. 943 * Return 1 for exclude, 0 for include and -1 for undecided. 944 */ 945intis_excluded_from_list(const char*pathname, 946int pathlen,const char*basename,int*dtype, 947struct exclude_list *el) 948{ 949struct exclude *exclude; 950 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 951if(exclude) 952return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 953return-1;/* undecided */ 954} 955 956static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 957const char*pathname,int pathlen,const char*basename, 958int*dtype_p) 959{ 960int i, j; 961struct exclude_list_group *group; 962struct exclude *exclude; 963for(i = EXC_CMDL; i <= EXC_FILE; i++) { 964 group = &dir->exclude_list_group[i]; 965for(j = group->nr -1; j >=0; j--) { 966 exclude =last_exclude_matching_from_list( 967 pathname, pathlen, basename, dtype_p, 968&group->el[j]); 969if(exclude) 970return exclude; 971} 972} 973return NULL; 974} 975 976/* 977 * Loads the per-directory exclude list for the substring of base 978 * which has a char length of baselen. 979 */ 980static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen) 981{ 982struct exclude_list_group *group; 983struct exclude_list *el; 984struct exclude_stack *stk = NULL; 985struct untracked_cache_dir *untracked; 986int current; 987 988 group = &dir->exclude_list_group[EXC_DIRS]; 989 990/* 991 * Pop the exclude lists from the EXCL_DIRS exclude_list_group 992 * which originate from directories not in the prefix of the 993 * path being checked. 994 */ 995while((stk = dir->exclude_stack) != NULL) { 996if(stk->baselen <= baselen && 997!strncmp(dir->basebuf.buf, base, stk->baselen)) 998break; 999 el = &group->el[dir->exclude_stack->exclude_ix];1000 dir->exclude_stack = stk->prev;1001 dir->exclude = NULL;1002free((char*)el->src);/* see strbuf_detach() below */1003clear_exclude_list(el);1004free(stk);1005 group->nr--;1006}10071008/* Skip traversing into sub directories if the parent is excluded */1009if(dir->exclude)1010return;10111012/*1013 * Lazy initialization. All call sites currently just1014 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1015 * them seems lots of work for little benefit.1016 */1017if(!dir->basebuf.buf)1018strbuf_init(&dir->basebuf, PATH_MAX);10191020/* Read from the parent directories and push them down. */1021 current = stk ? stk->baselen : -1;1022strbuf_setlen(&dir->basebuf, current <0?0: current);1023if(dir->untracked)1024 untracked = stk ? stk->ucd : dir->untracked->root;1025else1026 untracked = NULL;10271028while(current < baselen) {1029const char*cp;1030struct sha1_stat sha1_stat;10311032 stk =xcalloc(1,sizeof(*stk));1033if(current <0) {1034 cp = base;1035 current =0;1036}else{1037 cp =strchr(base + current +1,'/');1038if(!cp)1039die("oops in prep_exclude");1040 cp++;1041 untracked =1042lookup_untracked(dir->untracked, untracked,1043 base + current,1044 cp - base - current);1045}1046 stk->prev = dir->exclude_stack;1047 stk->baselen = cp - base;1048 stk->exclude_ix = group->nr;1049 stk->ucd = untracked;1050 el =add_exclude_list(dir, EXC_DIRS, NULL);1051strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1052assert(stk->baselen == dir->basebuf.len);10531054/* Abort if the directory is excluded */1055if(stk->baselen) {1056int dt = DT_DIR;1057 dir->basebuf.buf[stk->baselen -1] =0;1058 dir->exclude =last_exclude_matching_from_lists(dir,1059 dir->basebuf.buf, stk->baselen -1,1060 dir->basebuf.buf + current, &dt);1061 dir->basebuf.buf[stk->baselen -1] ='/';1062if(dir->exclude &&1063 dir->exclude->flags & EXC_FLAG_NEGATIVE)1064 dir->exclude = NULL;1065if(dir->exclude) {1066 dir->exclude_stack = stk;1067return;1068}1069}10701071/* Try to read per-directory file */1072hashclr(sha1_stat.sha1);1073 sha1_stat.valid =0;1074if(dir->exclude_per_dir &&1075/*1076 * If we know that no files have been added in1077 * this directory (i.e. valid_cached_dir() has1078 * been executed and set untracked->valid) ..1079 */1080(!untracked || !untracked->valid ||1081/*1082 * .. and .gitignore does not exist before1083 * (i.e. null exclude_sha1 and skip_worktree is1084 * not set). Then we can skip loading .gitignore,1085 * which would result in ENOENT anyway.1086 * skip_worktree is taken care in read_directory()1087 */1088!is_null_sha1(untracked->exclude_sha1))) {1089/*1090 * dir->basebuf gets reused by the traversal, but we1091 * need fname to remain unchanged to ensure the src1092 * member of each struct exclude correctly1093 * back-references its source file. Other invocations1094 * of add_exclude_list provide stable strings, so we1095 * strbuf_detach() and free() here in the caller.1096 */1097struct strbuf sb = STRBUF_INIT;1098strbuf_addbuf(&sb, &dir->basebuf);1099strbuf_addstr(&sb, dir->exclude_per_dir);1100 el->src =strbuf_detach(&sb, NULL);1101add_excludes(el->src, el->src, stk->baselen, el,1,1102 untracked ? &sha1_stat : NULL);1103}1104/*1105 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1106 * will first be called in valid_cached_dir() then maybe many1107 * times more in last_exclude_matching(). When the cache is1108 * used, last_exclude_matching() will not be called and1109 * reading .gitignore content will be a waste.1110 *1111 * So when it's called by valid_cached_dir() and we can get1112 * .gitignore SHA-1 from the index (i.e. .gitignore is not1113 * modified on work tree), we could delay reading the1114 * .gitignore content until we absolutely need it in1115 * last_exclude_matching(). Be careful about ignore rule1116 * order, though, if you do that.1117 */1118if(untracked &&1119hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1120invalidate_gitignore(dir->untracked, untracked);1121hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1122}1123 dir->exclude_stack = stk;1124 current = stk->baselen;1125}1126strbuf_setlen(&dir->basebuf, baselen);1127}11281129/*1130 * Loads the exclude lists for the directory containing pathname, then1131 * scans all exclude lists to determine whether pathname is excluded.1132 * Returns the exclude_list element which matched, or NULL for1133 * undecided.1134 */1135struct exclude *last_exclude_matching(struct dir_struct *dir,1136const char*pathname,1137int*dtype_p)1138{1139int pathlen =strlen(pathname);1140const char*basename =strrchr(pathname,'/');1141 basename = (basename) ? basename+1: pathname;11421143prep_exclude(dir, pathname, basename-pathname);11441145if(dir->exclude)1146return dir->exclude;11471148returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1149 basename, dtype_p);1150}11511152/*1153 * Loads the exclude lists for the directory containing pathname, then1154 * scans all exclude lists to determine whether pathname is excluded.1155 * Returns 1 if true, otherwise 0.1156 */1157intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1158{1159struct exclude *exclude =1160last_exclude_matching(dir, pathname, dtype_p);1161if(exclude)1162return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1163return0;1164}11651166static struct dir_entry *dir_entry_new(const char*pathname,int len)1167{1168struct dir_entry *ent;11691170 ent =xmalloc(sizeof(*ent) + len +1);1171 ent->len = len;1172memcpy(ent->name, pathname, len);1173 ent->name[len] =0;1174return ent;1175}11761177static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1178{1179if(cache_file_exists(pathname, len, ignore_case))1180return NULL;11811182ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1183return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1184}11851186struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1187{1188if(!cache_name_is_other(pathname, len))1189return NULL;11901191ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1192return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1193}11941195enum exist_status {1196 index_nonexistent =0,1197 index_directory,1198 index_gitdir1199};12001201/*1202 * Do not use the alphabetically sorted index to look up1203 * the directory name; instead, use the case insensitive1204 * directory hash.1205 */1206static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1207{1208const struct cache_entry *ce =cache_dir_exists(dirname, len);1209unsigned char endchar;12101211if(!ce)1212return index_nonexistent;1213 endchar = ce->name[len];12141215/*1216 * The cache_entry structure returned will contain this dirname1217 * and possibly additional path components.1218 */1219if(endchar =='/')1220return index_directory;12211222/*1223 * If there are no additional path components, then this cache_entry1224 * represents a submodule. Submodules, despite being directories,1225 * are stored in the cache without a closing slash.1226 */1227if(!endchar &&S_ISGITLINK(ce->ce_mode))1228return index_gitdir;12291230/* This should never be hit, but it exists just in case. */1231return 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 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, dirname, len);1331returnread_directory_recursive(dir, dirname, len,1332 untracked,1, simplify);1333}13341335/*1336 * This is an inexact early pruning of any recursive directory1337 * reading - if the path cannot possibly be in the pathspec,1338 * return true, and we'll skip it early.1339 */1340static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1341{1342if(simplify) {1343for(;;) {1344const char*match = simplify->path;1345int len = simplify->len;13461347if(!match)1348break;1349if(len > pathlen)1350 len = pathlen;1351if(!memcmp(path, match, len))1352return0;1353 simplify++;1354}1355return1;1356}1357return0;1358}13591360/*1361 * This function tells us whether an excluded path matches a1362 * list of "interesting" pathspecs. That is, whether a path matched1363 * by any of the pathspecs could possibly be ignored by excluding1364 * the specified path. This can happen if:1365 *1366 * 1. the path is mentioned explicitly in the pathspec1367 *1368 * 2. the path is a directory prefix of some element in the1369 * pathspec1370 */1371static intexclude_matches_pathspec(const char*path,int len,1372const struct path_simplify *simplify)1373{1374if(simplify) {1375for(; simplify->path; simplify++) {1376if(len == simplify->len1377&& !memcmp(path, simplify->path, len))1378return1;1379if(len < simplify->len1380&& simplify->path[len] =='/'1381&& !memcmp(path, simplify->path, len))1382return1;1383}1384}1385return0;1386}13871388static intget_index_dtype(const char*path,int len)1389{1390int pos;1391const struct cache_entry *ce;13921393 ce =cache_file_exists(path, len,0);1394if(ce) {1395if(!ce_uptodate(ce))1396return DT_UNKNOWN;1397if(S_ISGITLINK(ce->ce_mode))1398return DT_DIR;1399/*1400 * Nobody actually cares about the1401 * difference between DT_LNK and DT_REG1402 */1403return DT_REG;1404}14051406/* Try to look it up as a directory */1407 pos =cache_name_pos(path, len);1408if(pos >=0)1409return DT_UNKNOWN;1410 pos = -pos-1;1411while(pos < active_nr) {1412 ce = active_cache[pos++];1413if(strncmp(ce->name, path, len))1414break;1415if(ce->name[len] >'/')1416break;1417if(ce->name[len] <'/')1418continue;1419if(!ce_uptodate(ce))1420break;/* continue? */1421return DT_DIR;1422}1423return DT_UNKNOWN;1424}14251426static intget_dtype(struct dirent *de,const char*path,int len)1427{1428int dtype = de ?DTYPE(de) : DT_UNKNOWN;1429struct stat st;14301431if(dtype != DT_UNKNOWN)1432return dtype;1433 dtype =get_index_dtype(path, len);1434if(dtype != DT_UNKNOWN)1435return dtype;1436if(lstat(path, &st))1437return dtype;1438if(S_ISREG(st.st_mode))1439return DT_REG;1440if(S_ISDIR(st.st_mode))1441return DT_DIR;1442if(S_ISLNK(st.st_mode))1443return DT_LNK;1444return dtype;1445}14461447static enum path_treatment treat_one_path(struct dir_struct *dir,1448struct untracked_cache_dir *untracked,1449struct strbuf *path,1450const struct path_simplify *simplify,1451int dtype,struct dirent *de)1452{1453int exclude;1454int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);14551456if(dtype == DT_UNKNOWN)1457 dtype =get_dtype(de, path->buf, path->len);14581459/* Always exclude indexed files */1460if(dtype != DT_DIR && has_path_in_index)1461return path_none;14621463/*1464 * When we are looking at a directory P in the working tree,1465 * there are three cases:1466 *1467 * (1) P exists in the index. Everything inside the directory P in1468 * the working tree needs to go when P is checked out from the1469 * index.1470 *1471 * (2) P does not exist in the index, but there is P/Q in the index.1472 * We know P will stay a directory when we check out the contents1473 * of the index, but we do not know yet if there is a directory1474 * P/Q in the working tree to be killed, so we need to recurse.1475 *1476 * (3) P does not exist in the index, and there is no P/Q in the index1477 * to require P to be a directory, either. Only in this case, we1478 * know that everything inside P will not be killed without1479 * recursing.1480 */1481if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1482(dtype == DT_DIR) &&1483!has_path_in_index &&1484(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1485return path_none;14861487 exclude =is_excluded(dir, path->buf, &dtype);14881489/*1490 * Excluded? If we don't explicitly want to show1491 * ignored files, ignore it1492 */1493if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1494return path_excluded;14951496switch(dtype) {1497default:1498return path_none;1499case DT_DIR:1500strbuf_addch(path,'/');1501returntreat_directory(dir, untracked, path->buf, path->len, exclude,1502 simplify);1503case DT_REG:1504case DT_LNK:1505return exclude ? path_excluded : path_untracked;1506}1507}15081509static enum path_treatment treat_path_fast(struct dir_struct *dir,1510struct untracked_cache_dir *untracked,1511struct cached_dir *cdir,1512struct strbuf *path,1513int baselen,1514const struct path_simplify *simplify)1515{1516strbuf_setlen(path, baselen);1517if(!cdir->ucd) {1518strbuf_addstr(path, cdir->file);1519return path_untracked;1520}1521strbuf_addstr(path, cdir->ucd->name);1522/* treat_one_path() does this before it calls treat_directory() */1523if(path->buf[path->len -1] !='/')1524strbuf_addch(path,'/');1525if(cdir->ucd->check_only)1526/*1527 * check_only is set as a result of treat_directory() getting1528 * to its bottom. Verify again the same set of directories1529 * with check_only set.1530 */1531returnread_directory_recursive(dir, path->buf, path->len,1532 cdir->ucd,1, simplify);1533/*1534 * We get path_recurse in the first run when1535 * directory_exists_in_index() returns index_nonexistent. We1536 * are sure that new changes in the index does not impact the1537 * outcome. Return now.1538 */1539return path_recurse;1540}15411542static enum path_treatment treat_path(struct dir_struct *dir,1543struct untracked_cache_dir *untracked,1544struct cached_dir *cdir,1545struct strbuf *path,1546int baselen,1547const struct path_simplify *simplify)1548{1549int dtype;1550struct dirent *de = cdir->de;15511552if(!de)1553returntreat_path_fast(dir, untracked, cdir, path,1554 baselen, simplify);1555if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1556return path_none;1557strbuf_setlen(path, baselen);1558strbuf_addstr(path, de->d_name);1559if(simplify_away(path->buf, path->len, simplify))1560return path_none;15611562 dtype =DTYPE(de);1563returntreat_one_path(dir, untracked, path, simplify, dtype, de);1564}15651566static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1567{1568if(!dir)1569return;1570ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1571 dir->untracked_alloc);1572 dir->untracked[dir->untracked_nr++] =xstrdup(name);1573}15741575static intvalid_cached_dir(struct dir_struct *dir,1576struct untracked_cache_dir *untracked,1577struct strbuf *path,1578int check_only)1579{1580struct stat st;15811582if(!untracked)1583return0;15841585if(stat(path->len ? path->buf :".", &st)) {1586invalidate_directory(dir->untracked, untracked);1587memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1588return0;1589}1590if(!untracked->valid ||1591match_stat_data_racy(&the_index, &untracked->stat_data, &st)) {1592if(untracked->valid)1593invalidate_directory(dir->untracked, untracked);1594fill_stat_data(&untracked->stat_data, &st);1595return0;1596}15971598if(untracked->check_only != !!check_only) {1599invalidate_directory(dir->untracked, untracked);1600return0;1601}16021603/*1604 * prep_exclude will be called eventually on this directory,1605 * but it's called much later in last_exclude_matching(). We1606 * need it now to determine the validity of the cache for this1607 * path. The next calls will be nearly no-op, the way1608 * prep_exclude() is designed.1609 */1610if(path->len && path->buf[path->len -1] !='/') {1611strbuf_addch(path,'/');1612prep_exclude(dir, path->buf, path->len);1613strbuf_setlen(path, path->len -1);1614}else1615prep_exclude(dir, path->buf, path->len);16161617/* hopefully prep_exclude() haven't invalidated this entry... */1618return untracked->valid;1619}16201621static intopen_cached_dir(struct cached_dir *cdir,1622struct dir_struct *dir,1623struct untracked_cache_dir *untracked,1624struct strbuf *path,1625int check_only)1626{1627memset(cdir,0,sizeof(*cdir));1628 cdir->untracked = untracked;1629if(valid_cached_dir(dir, untracked, path, check_only))1630return0;1631 cdir->fdir =opendir(path->len ? path->buf :".");1632if(dir->untracked)1633 dir->untracked->dir_opened++;1634if(!cdir->fdir)1635return-1;1636return0;1637}16381639static intread_cached_dir(struct cached_dir *cdir)1640{1641if(cdir->fdir) {1642 cdir->de =readdir(cdir->fdir);1643if(!cdir->de)1644return-1;1645return0;1646}1647while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1648struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1649if(!d->recurse) {1650 cdir->nr_dirs++;1651continue;1652}1653 cdir->ucd = d;1654 cdir->nr_dirs++;1655return0;1656}1657 cdir->ucd = NULL;1658if(cdir->nr_files < cdir->untracked->untracked_nr) {1659struct untracked_cache_dir *d = cdir->untracked;1660 cdir->file = d->untracked[cdir->nr_files++];1661return0;1662}1663return-1;1664}16651666static voidclose_cached_dir(struct cached_dir *cdir)1667{1668if(cdir->fdir)1669closedir(cdir->fdir);1670/*1671 * We have gone through this directory and found no untracked1672 * entries. Mark it valid.1673 */1674if(cdir->untracked) {1675 cdir->untracked->valid =1;1676 cdir->untracked->recurse =1;1677}1678}16791680/*1681 * Read a directory tree. We currently ignore anything but1682 * directories, regular files and symlinks. That's because git1683 * doesn't handle them at all yet. Maybe that will change some1684 * day.1685 *1686 * Also, we ignore the name ".git" (even if it is not a directory).1687 * That likely will not change.1688 *1689 * Returns the most significant path_treatment value encountered in the scan.1690 */1691static enum path_treatment read_directory_recursive(struct dir_struct *dir,1692const char*base,int baselen,1693struct untracked_cache_dir *untracked,int check_only,1694const struct path_simplify *simplify)1695{1696struct cached_dir cdir;1697enum path_treatment state, subdir_state, dir_state = path_none;1698struct strbuf path = STRBUF_INIT;16991700strbuf_add(&path, base, baselen);17011702if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1703goto out;17041705if(untracked)1706 untracked->check_only = !!check_only;17071708while(!read_cached_dir(&cdir)) {1709/* check how the file or directory should be treated */1710 state =treat_path(dir, untracked, &cdir, &path, baselen, simplify);17111712if(state > dir_state)1713 dir_state = state;17141715/* recurse into subdir if instructed by treat_path */1716if(state == path_recurse) {1717struct untracked_cache_dir *ud;1718 ud =lookup_untracked(dir->untracked, untracked,1719 path.buf + baselen,1720 path.len - baselen);1721 subdir_state =1722read_directory_recursive(dir, path.buf, path.len,1723 ud, check_only, simplify);1724if(subdir_state > dir_state)1725 dir_state = subdir_state;1726}17271728if(check_only) {1729/* abort early if maximum state has been reached */1730if(dir_state == path_untracked) {1731if(cdir.fdir)1732add_untracked(untracked, path.buf + baselen);1733break;1734}1735/* skip the dir_add_* part */1736continue;1737}17381739/* add the path to the appropriate result list */1740switch(state) {1741case path_excluded:1742if(dir->flags & DIR_SHOW_IGNORED)1743dir_add_name(dir, path.buf, path.len);1744else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1745((dir->flags & DIR_COLLECT_IGNORED) &&1746exclude_matches_pathspec(path.buf, path.len,1747 simplify)))1748dir_add_ignored(dir, path.buf, path.len);1749break;17501751case path_untracked:1752if(dir->flags & DIR_SHOW_IGNORED)1753break;1754dir_add_name(dir, path.buf, path.len);1755if(cdir.fdir)1756add_untracked(untracked, path.buf + baselen);1757break;17581759default:1760break;1761}1762}1763close_cached_dir(&cdir);1764 out:1765strbuf_release(&path);17661767return dir_state;1768}17691770static intcmp_name(const void*p1,const void*p2)1771{1772const struct dir_entry *e1 = *(const struct dir_entry **)p1;1773const struct dir_entry *e2 = *(const struct dir_entry **)p2;17741775returnname_compare(e1->name, e1->len, e2->name, e2->len);1776}17771778static struct path_simplify *create_simplify(const char**pathspec)1779{1780int nr, alloc =0;1781struct path_simplify *simplify = NULL;17821783if(!pathspec)1784return NULL;17851786for(nr =0; ; nr++) {1787const char*match;1788ALLOC_GROW(simplify, nr +1, alloc);1789 match = *pathspec++;1790if(!match)1791break;1792 simplify[nr].path = match;1793 simplify[nr].len =simple_length(match);1794}1795 simplify[nr].path = NULL;1796 simplify[nr].len =0;1797return simplify;1798}17991800static voidfree_simplify(struct path_simplify *simplify)1801{1802free(simplify);1803}18041805static inttreat_leading_path(struct dir_struct *dir,1806const char*path,int len,1807const struct path_simplify *simplify)1808{1809struct strbuf sb = STRBUF_INIT;1810int baselen, rc =0;1811const char*cp;1812int old_flags = dir->flags;18131814while(len && path[len -1] =='/')1815 len--;1816if(!len)1817return1;1818 baselen =0;1819 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1820while(1) {1821 cp = path + baselen + !!baselen;1822 cp =memchr(cp,'/', path + len - cp);1823if(!cp)1824 baselen = len;1825else1826 baselen = cp - path;1827strbuf_setlen(&sb,0);1828strbuf_add(&sb, path, baselen);1829if(!is_directory(sb.buf))1830break;1831if(simplify_away(sb.buf, sb.len, simplify))1832break;1833if(treat_one_path(dir, NULL, &sb, simplify,1834 DT_DIR, NULL) == path_none)1835break;/* do not recurse into it */1836if(len <= baselen) {1837 rc =1;1838break;/* finished checking */1839}1840}1841strbuf_release(&sb);1842 dir->flags = old_flags;1843return rc;1844}18451846static const char*get_ident_string(void)1847{1848static struct strbuf sb = STRBUF_INIT;1849struct utsname uts;18501851if(sb.len)1852return sb.buf;1853if(uname(&uts))1854die_errno(_("failed to get kernel name and information"));1855strbuf_addf(&sb,"Location%s, system%s %s %s",get_git_work_tree(),1856 uts.sysname, uts.release, uts.version);1857return sb.buf;1858}18591860static intident_in_untracked(const struct untracked_cache *uc)1861{1862const char*end = uc->ident.buf + uc->ident.len;1863const char*p = uc->ident.buf;18641865for(p = uc->ident.buf; p < end; p +=strlen(p) +1)1866if(!strcmp(p,get_ident_string()))1867return1;1868return0;1869}18701871voidadd_untracked_ident(struct untracked_cache *uc)1872{1873if(ident_in_untracked(uc))1874return;1875strbuf_addstr(&uc->ident,get_ident_string());1876/* this strbuf contains a list of strings, save NUL too */1877strbuf_addch(&uc->ident,0);1878}18791880static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1881int base_len,1882const struct pathspec *pathspec)1883{1884struct untracked_cache_dir *root;1885int i;18861887if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))1888return NULL;18891890/*1891 * We only support $GIT_DIR/info/exclude and core.excludesfile1892 * as the global ignore rule files. Any other additions1893 * (e.g. from command line) invalidate the cache. This1894 * condition also catches running setup_standard_excludes()1895 * before setting dir->untracked!1896 */1897if(dir->unmanaged_exclude_files)1898return NULL;18991900/*1901 * Optimize for the main use case only: whole-tree git1902 * status. More work involved in treat_leading_path() if we1903 * use cache on just a subset of the worktree. pathspec1904 * support could make the matter even worse.1905 */1906if(base_len || (pathspec && pathspec->nr))1907return NULL;19081909/* Different set of flags may produce different results */1910if(dir->flags != dir->untracked->dir_flags ||1911/*1912 * See treat_directory(), case index_nonexistent. Without1913 * this flag, we may need to also cache .git file content1914 * for the resolve_gitlink_ref() call, which we don't.1915 */1916!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1917/* We don't support collecting ignore files */1918(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1919 DIR_COLLECT_IGNORED)))1920return NULL;19211922/*1923 * If we use .gitignore in the cache and now you change it to1924 * .gitexclude, everything will go wrong.1925 */1926if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1927strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1928return NULL;19291930/*1931 * EXC_CMDL is not considered in the cache. If people set it,1932 * skip the cache.1933 */1934if(dir->exclude_list_group[EXC_CMDL].nr)1935return NULL;19361937/*1938 * An optimization in prep_exclude() does not play well with1939 * CE_SKIP_WORKTREE. It's a rare case anyway, if a single1940 * entry has that bit set, disable the whole untracked cache.1941 */1942for(i =0; i < active_nr; i++)1943if(ce_skip_worktree(active_cache[i]))1944return NULL;19451946if(!ident_in_untracked(dir->untracked)) {1947warning(_("Untracked cache is disabled on this system."));1948return NULL;1949}19501951if(!dir->untracked->root) {1952const int len =sizeof(*dir->untracked->root);1953 dir->untracked->root =xmalloc(len);1954memset(dir->untracked->root,0, len);1955}19561957/* Validate $GIT_DIR/info/exclude and core.excludesfile */1958 root = dir->untracked->root;1959if(hashcmp(dir->ss_info_exclude.sha1,1960 dir->untracked->ss_info_exclude.sha1)) {1961invalidate_gitignore(dir->untracked, root);1962 dir->untracked->ss_info_exclude = dir->ss_info_exclude;1963}1964if(hashcmp(dir->ss_excludes_file.sha1,1965 dir->untracked->ss_excludes_file.sha1)) {1966invalidate_gitignore(dir->untracked, root);1967 dir->untracked->ss_excludes_file = dir->ss_excludes_file;1968}19691970/* Make sure this directory is not dropped out at saving phase */1971 root->recurse =1;1972return root;1973}19741975intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)1976{1977struct path_simplify *simplify;1978struct untracked_cache_dir *untracked;19791980/*1981 * Check out create_simplify()1982 */1983if(pathspec)1984GUARD_PATHSPEC(pathspec,1985 PATHSPEC_FROMTOP |1986 PATHSPEC_MAXDEPTH |1987 PATHSPEC_LITERAL |1988 PATHSPEC_GLOB |1989 PATHSPEC_ICASE |1990 PATHSPEC_EXCLUDE);19911992if(has_symlink_leading_path(path, len))1993return dir->nr;19941995/*1996 * exclude patterns are treated like positive ones in1997 * create_simplify. Usually exclude patterns should be a1998 * subset of positive ones, which has no impacts on1999 * create_simplify().2000 */2001 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);2002 untracked =validate_untracked_cache(dir, len, pathspec);2003if(!untracked)2004/*2005 * make sure untracked cache code path is disabled,2006 * e.g. prep_exclude()2007 */2008 dir->untracked = NULL;2009if(!len ||treat_leading_path(dir, path, len, simplify))2010read_directory_recursive(dir, path, len, untracked,0, simplify);2011free_simplify(simplify);2012qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);2013qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);2014if(dir->untracked) {2015static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);2016trace_printf_key(&trace_untracked_stats,2017"node creation:%u\n"2018"gitignore invalidation:%u\n"2019"directory invalidation:%u\n"2020"opendir:%u\n",2021 dir->untracked->dir_created,2022 dir->untracked->gitignore_invalidated,2023 dir->untracked->dir_invalidated,2024 dir->untracked->dir_opened);2025if(dir->untracked == the_index.untracked &&2026(dir->untracked->dir_opened ||2027 dir->untracked->gitignore_invalidated ||2028 dir->untracked->dir_invalidated))2029 the_index.cache_changed |= UNTRACKED_CHANGED;2030if(dir->untracked != the_index.untracked) {2031free(dir->untracked);2032 dir->untracked = NULL;2033}2034}2035return dir->nr;2036}20372038intfile_exists(const char*f)2039{2040struct stat sb;2041returnlstat(f, &sb) ==0;2042}20432044/*2045 * Given two normalized paths (a trailing slash is ok), if subdir is2046 * outside dir, return -1. Otherwise return the offset in subdir that2047 * can be used as relative path to dir.2048 */2049intdir_inside_of(const char*subdir,const char*dir)2050{2051int offset =0;20522053assert(dir && subdir && *dir && *subdir);20542055while(*dir && *subdir && *dir == *subdir) {2056 dir++;2057 subdir++;2058 offset++;2059}20602061/* hel[p]/me vs hel[l]/yeah */2062if(*dir && *subdir)2063return-1;20642065if(!*subdir)2066return!*dir ? offset : -1;/* same dir */20672068/* foo/[b]ar vs foo/[] */2069if(is_dir_sep(dir[-1]))2070returnis_dir_sep(subdir[-1]) ? offset : -1;20712072/* foo[/]bar vs foo[] */2073returnis_dir_sep(*subdir) ? offset +1: -1;2074}20752076intis_inside_dir(const char*dir)2077{2078char*cwd;2079int rc;20802081if(!dir)2082return0;20832084 cwd =xgetcwd();2085 rc = (dir_inside_of(cwd, dir) >=0);2086free(cwd);2087return rc;2088}20892090intis_empty_dir(const char*path)2091{2092DIR*dir =opendir(path);2093struct dirent *e;2094int ret =1;20952096if(!dir)2097return0;20982099while((e =readdir(dir)) != NULL)2100if(!is_dot_or_dotdot(e->d_name)) {2101 ret =0;2102break;2103}21042105closedir(dir);2106return ret;2107}21082109static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2110{2111DIR*dir;2112struct dirent *e;2113int ret =0, original_len = path->len, len, kept_down =0;2114int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2115int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2116unsigned char submodule_head[20];21172118if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2119!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2120/* Do not descend and nuke a nested git work tree. */2121if(kept_up)2122*kept_up =1;2123return0;2124}21252126 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2127 dir =opendir(path->buf);2128if(!dir) {2129if(errno == ENOENT)2130return keep_toplevel ? -1:0;2131else if(errno == EACCES && !keep_toplevel)2132/*2133 * An empty dir could be removable even if it2134 * is unreadable:2135 */2136returnrmdir(path->buf);2137else2138return-1;2139}2140if(path->buf[original_len -1] !='/')2141strbuf_addch(path,'/');21422143 len = path->len;2144while((e =readdir(dir)) != NULL) {2145struct stat st;2146if(is_dot_or_dotdot(e->d_name))2147continue;21482149strbuf_setlen(path, len);2150strbuf_addstr(path, e->d_name);2151if(lstat(path->buf, &st)) {2152if(errno == ENOENT)2153/*2154 * file disappeared, which is what we2155 * wanted anyway2156 */2157continue;2158/* fall thru */2159}else if(S_ISDIR(st.st_mode)) {2160if(!remove_dir_recurse(path, flag, &kept_down))2161continue;/* happy */2162}else if(!only_empty &&2163(!unlink(path->buf) || errno == ENOENT)) {2164continue;/* happy, too */2165}21662167/* path too long, stat fails, or non-directory still exists */2168 ret = -1;2169break;2170}2171closedir(dir);21722173strbuf_setlen(path, original_len);2174if(!ret && !keep_toplevel && !kept_down)2175 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2176else if(kept_up)2177/*2178 * report the uplevel that it is not an error that we2179 * did not rmdir() our directory.2180 */2181*kept_up = !ret;2182return ret;2183}21842185intremove_dir_recursively(struct strbuf *path,int flag)2186{2187returnremove_dir_recurse(path, flag, NULL);2188}21892190voidsetup_standard_excludes(struct dir_struct *dir)2191{2192const char*path;21932194 dir->exclude_per_dir =".gitignore";21952196/* core.excludefile defaulting to $XDG_HOME/git/ignore */2197if(!excludes_file)2198 excludes_file =xdg_config_home("ignore");2199if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2200add_excludes_from_file_1(dir, excludes_file,2201 dir->untracked ? &dir->ss_excludes_file : NULL);22022203/* per repository user preference */2204 path =git_path("info/exclude");2205if(!access_or_warn(path, R_OK,0))2206add_excludes_from_file_1(dir, path,2207 dir->untracked ? &dir->ss_info_exclude : NULL);2208}22092210intremove_path(const char*name)2211{2212char*slash;22132214if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2215return-1;22162217 slash =strrchr(name,'/');2218if(slash) {2219char*dirs =xstrdup(name);2220 slash = dirs + (slash - name);2221do{2222*slash ='\0';2223}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2224free(dirs);2225}2226return0;2227}22282229/*2230 * Frees memory within dir which was allocated for exclude lists and2231 * the exclude_stack. Does not free dir itself.2232 */2233voidclear_directory(struct dir_struct *dir)2234{2235int i, j;2236struct exclude_list_group *group;2237struct exclude_list *el;2238struct exclude_stack *stk;22392240for(i = EXC_CMDL; i <= EXC_FILE; i++) {2241 group = &dir->exclude_list_group[i];2242for(j =0; j < group->nr; j++) {2243 el = &group->el[j];2244if(i == EXC_DIRS)2245free((char*)el->src);2246clear_exclude_list(el);2247}2248free(group->el);2249}22502251 stk = dir->exclude_stack;2252while(stk) {2253struct exclude_stack *prev = stk->prev;2254free(stk);2255 stk = prev;2256}2257strbuf_release(&dir->basebuf);2258}22592260struct ondisk_untracked_cache {2261struct stat_data info_exclude_stat;2262struct stat_data excludes_file_stat;2263uint32_t dir_flags;2264unsigned char info_exclude_sha1[20];2265unsigned char excludes_file_sha1[20];2266char exclude_per_dir[FLEX_ARRAY];2267};22682269#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)22702271struct write_data {2272int index;/* number of written untracked_cache_dir */2273struct ewah_bitmap *check_only;/* from untracked_cache_dir */2274struct ewah_bitmap *valid;/* from untracked_cache_dir */2275struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2276struct strbuf out;2277struct strbuf sb_stat;2278struct strbuf sb_sha1;2279};22802281static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2282{2283 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2284 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2285 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2286 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2287 to->sd_dev =htonl(from->sd_dev);2288 to->sd_ino =htonl(from->sd_ino);2289 to->sd_uid =htonl(from->sd_uid);2290 to->sd_gid =htonl(from->sd_gid);2291 to->sd_size =htonl(from->sd_size);2292}22932294static voidwrite_one_dir(struct untracked_cache_dir *untracked,2295struct write_data *wd)2296{2297struct stat_data stat_data;2298struct strbuf *out = &wd->out;2299unsigned char intbuf[16];2300unsigned int intlen, value;2301int i = wd->index++;23022303/*2304 * untracked_nr should be reset whenever valid is clear, but2305 * for safety..2306 */2307if(!untracked->valid) {2308 untracked->untracked_nr =0;2309 untracked->check_only =0;2310}23112312if(untracked->check_only)2313ewah_set(wd->check_only, i);2314if(untracked->valid) {2315ewah_set(wd->valid, i);2316stat_data_to_disk(&stat_data, &untracked->stat_data);2317strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2318}2319if(!is_null_sha1(untracked->exclude_sha1)) {2320ewah_set(wd->sha1_valid, i);2321strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2322}23232324 intlen =encode_varint(untracked->untracked_nr, intbuf);2325strbuf_add(out, intbuf, intlen);23262327/* skip non-recurse directories */2328for(i =0, value =0; i < untracked->dirs_nr; i++)2329if(untracked->dirs[i]->recurse)2330 value++;2331 intlen =encode_varint(value, intbuf);2332strbuf_add(out, intbuf, intlen);23332334strbuf_add(out, untracked->name,strlen(untracked->name) +1);23352336for(i =0; i < untracked->untracked_nr; i++)2337strbuf_add(out, untracked->untracked[i],2338strlen(untracked->untracked[i]) +1);23392340for(i =0; i < untracked->dirs_nr; i++)2341if(untracked->dirs[i]->recurse)2342write_one_dir(untracked->dirs[i], wd);2343}23442345voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2346{2347struct ondisk_untracked_cache *ouc;2348struct write_data wd;2349unsigned char varbuf[16];2350int len =0, varint_len;2351if(untracked->exclude_per_dir)2352 len =strlen(untracked->exclude_per_dir);2353 ouc =xmalloc(sizeof(*ouc) + len +1);2354stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2355stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2356hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2357hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2358 ouc->dir_flags =htonl(untracked->dir_flags);2359memcpy(ouc->exclude_per_dir, untracked->exclude_per_dir, len +1);23602361 varint_len =encode_varint(untracked->ident.len, varbuf);2362strbuf_add(out, varbuf, varint_len);2363strbuf_add(out, untracked->ident.buf, untracked->ident.len);23642365strbuf_add(out, ouc,ouc_size(len));2366free(ouc);2367 ouc = NULL;23682369if(!untracked->root) {2370 varint_len =encode_varint(0, varbuf);2371strbuf_add(out, varbuf, varint_len);2372return;2373}23742375 wd.index =0;2376 wd.check_only =ewah_new();2377 wd.valid =ewah_new();2378 wd.sha1_valid =ewah_new();2379strbuf_init(&wd.out,1024);2380strbuf_init(&wd.sb_stat,1024);2381strbuf_init(&wd.sb_sha1,1024);2382write_one_dir(untracked->root, &wd);23832384 varint_len =encode_varint(wd.index, varbuf);2385strbuf_add(out, varbuf, varint_len);2386strbuf_addbuf(out, &wd.out);2387ewah_serialize_strbuf(wd.valid, out);2388ewah_serialize_strbuf(wd.check_only, out);2389ewah_serialize_strbuf(wd.sha1_valid, out);2390strbuf_addbuf(out, &wd.sb_stat);2391strbuf_addbuf(out, &wd.sb_sha1);2392strbuf_addch(out,'\0');/* safe guard for string lists */23932394ewah_free(wd.valid);2395ewah_free(wd.check_only);2396ewah_free(wd.sha1_valid);2397strbuf_release(&wd.out);2398strbuf_release(&wd.sb_stat);2399strbuf_release(&wd.sb_sha1);2400}24012402static voidfree_untracked(struct untracked_cache_dir *ucd)2403{2404int i;2405if(!ucd)2406return;2407for(i =0; i < ucd->dirs_nr; i++)2408free_untracked(ucd->dirs[i]);2409for(i =0; i < ucd->untracked_nr; i++)2410free(ucd->untracked[i]);2411free(ucd->untracked);2412free(ucd->dirs);2413free(ucd);2414}24152416voidfree_untracked_cache(struct untracked_cache *uc)2417{2418if(uc)2419free_untracked(uc->root);2420free(uc);2421}24222423struct read_data {2424int index;2425struct untracked_cache_dir **ucd;2426struct ewah_bitmap *check_only;2427struct ewah_bitmap *valid;2428struct ewah_bitmap *sha1_valid;2429const unsigned char*data;2430const unsigned char*end;2431};24322433static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2434{2435 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2436 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2437 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2438 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2439 to->sd_dev =get_be32(&from->sd_dev);2440 to->sd_ino =get_be32(&from->sd_ino);2441 to->sd_uid =get_be32(&from->sd_uid);2442 to->sd_gid =get_be32(&from->sd_gid);2443 to->sd_size =get_be32(&from->sd_size);2444}24452446static intread_one_dir(struct untracked_cache_dir **untracked_,2447struct read_data *rd)2448{2449struct untracked_cache_dir ud, *untracked;2450const unsigned char*next, *data = rd->data, *end = rd->end;2451unsigned int value;2452int i, len;24532454memset(&ud,0,sizeof(ud));24552456 next = data;2457 value =decode_varint(&next);2458if(next > end)2459return-1;2460 ud.recurse =1;2461 ud.untracked_alloc = value;2462 ud.untracked_nr = value;2463if(ud.untracked_nr)2464 ud.untracked =xmalloc(sizeof(*ud.untracked) * ud.untracked_nr);2465 data = next;24662467 next = data;2468 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2469if(next > end)2470return-1;2471 ud.dirs =xmalloc(sizeof(*ud.dirs) * ud.dirs_nr);2472 data = next;24732474 len =strlen((const char*)data);2475 next = data + len +1;2476if(next > rd->end)2477return-1;2478*untracked_ = untracked =xmalloc(sizeof(*untracked) + len);2479memcpy(untracked, &ud,sizeof(ud));2480memcpy(untracked->name, data, len +1);2481 data = next;24822483for(i =0; i < untracked->untracked_nr; i++) {2484 len =strlen((const char*)data);2485 next = data + len +1;2486if(next > rd->end)2487return-1;2488 untracked->untracked[i] =xstrdup((const char*)data);2489 data = next;2490}24912492 rd->ucd[rd->index++] = untracked;2493 rd->data = data;24942495for(i =0; i < untracked->dirs_nr; i++) {2496 len =read_one_dir(untracked->dirs + i, rd);2497if(len <0)2498return-1;2499}2500return0;2501}25022503static voidset_check_only(size_t pos,void*cb)2504{2505struct read_data *rd = cb;2506struct untracked_cache_dir *ud = rd->ucd[pos];2507 ud->check_only =1;2508}25092510static voidread_stat(size_t pos,void*cb)2511{2512struct read_data *rd = cb;2513struct untracked_cache_dir *ud = rd->ucd[pos];2514if(rd->data +sizeof(struct stat_data) > rd->end) {2515 rd->data = rd->end +1;2516return;2517}2518stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2519 rd->data +=sizeof(struct stat_data);2520 ud->valid =1;2521}25222523static voidread_sha1(size_t pos,void*cb)2524{2525struct read_data *rd = cb;2526struct untracked_cache_dir *ud = rd->ucd[pos];2527if(rd->data +20> rd->end) {2528 rd->data = rd->end +1;2529return;2530}2531hashcpy(ud->exclude_sha1, rd->data);2532 rd->data +=20;2533}25342535static voidload_sha1_stat(struct sha1_stat *sha1_stat,2536const struct stat_data *stat,2537const unsigned char*sha1)2538{2539stat_data_from_disk(&sha1_stat->stat, stat);2540hashcpy(sha1_stat->sha1, sha1);2541 sha1_stat->valid =1;2542}25432544struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2545{2546const struct ondisk_untracked_cache *ouc;2547struct untracked_cache *uc;2548struct read_data rd;2549const unsigned char*next = data, *end = (const unsigned char*)data + sz;2550const char*ident;2551int ident_len, len;25522553if(sz <=1|| end[-1] !='\0')2554return NULL;2555 end--;25562557 ident_len =decode_varint(&next);2558if(next + ident_len > end)2559return NULL;2560 ident = (const char*)next;2561 next += ident_len;25622563 ouc = (const struct ondisk_untracked_cache *)next;2564if(next +ouc_size(0) > end)2565return NULL;25662567 uc =xcalloc(1,sizeof(*uc));2568strbuf_init(&uc->ident, ident_len);2569strbuf_add(&uc->ident, ident, ident_len);2570load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2571 ouc->info_exclude_sha1);2572load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2573 ouc->excludes_file_sha1);2574 uc->dir_flags =get_be32(&ouc->dir_flags);2575 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2576/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2577 next +=ouc_size(strlen(ouc->exclude_per_dir));2578if(next >= end)2579goto done2;25802581 len =decode_varint(&next);2582if(next > end || len ==0)2583goto done2;25842585 rd.valid =ewah_new();2586 rd.check_only =ewah_new();2587 rd.sha1_valid =ewah_new();2588 rd.data = next;2589 rd.end = end;2590 rd.index =0;2591 rd.ucd =xmalloc(sizeof(*rd.ucd) * len);25922593if(read_one_dir(&uc->root, &rd) || rd.index != len)2594goto done;25952596 next = rd.data;2597 len =ewah_read_mmap(rd.valid, next, end - next);2598if(len <0)2599goto done;26002601 next += len;2602 len =ewah_read_mmap(rd.check_only, next, end - next);2603if(len <0)2604goto done;26052606 next += len;2607 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2608if(len <0)2609goto done;26102611ewah_each_bit(rd.check_only, set_check_only, &rd);2612 rd.data = next + len;2613ewah_each_bit(rd.valid, read_stat, &rd);2614ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2615 next = rd.data;26162617done:2618free(rd.ucd);2619ewah_free(rd.valid);2620ewah_free(rd.check_only);2621ewah_free(rd.sha1_valid);2622done2:2623if(next != end) {2624free_untracked_cache(uc);2625 uc = NULL;2626}2627return uc;2628}26292630voiduntracked_cache_invalidate_path(struct index_state *istate,2631const char*path)2632{2633const char*sep;2634struct untracked_cache_dir *d;2635if(!istate->untracked || !istate->untracked->root)2636return;2637 sep =strrchr(path,'/');2638if(sep)2639 d =lookup_untracked(istate->untracked,2640 istate->untracked->root,2641 path, sep - path);2642else2643 d = istate->untracked->root;2644 istate->untracked->dir_invalidated++;2645 d->valid =0;2646 d->untracked_nr =0;2647}26482649voiduntracked_cache_remove_from_index(struct index_state *istate,2650const char*path)2651{2652untracked_cache_invalidate_path(istate, path);2653}26542655voiduntracked_cache_add_to_index(struct index_state *istate,2656const char*path)2657{2658untracked_cache_invalidate_path(istate, path);2659}