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 67intgit_fnmatch(const struct pathspec_item *item, 68const char*pattern,const char*string, 69int prefix) 70{ 71if(prefix >0) { 72if(ps_strncmp(item, pattern, string, prefix)) 73return WM_NOMATCH; 74 pattern += prefix; 75 string += prefix; 76} 77if(item->flags & PATHSPEC_ONESTAR) { 78int pattern_len =strlen(++pattern); 79int string_len =strlen(string); 80return string_len < pattern_len || 81ps_strcmp(item, pattern, 82 string + string_len - pattern_len); 83} 84if(item->magic & PATHSPEC_GLOB) 85returnwildmatch(pattern, string, 86 WM_PATHNAME | 87(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 88 NULL); 89else 90/* wildmatch has not learned no FNM_PATHNAME mode yet */ 91returnwildmatch(pattern, string, 92 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 93 NULL); 94} 95 96static intfnmatch_icase_mem(const char*pattern,int patternlen, 97const char*string,int stringlen, 98int flags) 99{ 100int match_status; 101struct strbuf pat_buf = STRBUF_INIT; 102struct strbuf str_buf = STRBUF_INIT; 103const char*use_pat = pattern; 104const char*use_str = string; 105 106if(pattern[patternlen]) { 107strbuf_add(&pat_buf, pattern, patternlen); 108 use_pat = pat_buf.buf; 109} 110if(string[stringlen]) { 111strbuf_add(&str_buf, string, stringlen); 112 use_str = str_buf.buf; 113} 114 115if(ignore_case) 116 flags |= WM_CASEFOLD; 117 match_status =wildmatch(use_pat, use_str, flags, NULL); 118 119strbuf_release(&pat_buf); 120strbuf_release(&str_buf); 121 122return match_status; 123} 124 125static size_tcommon_prefix_len(const struct pathspec *pathspec) 126{ 127int n; 128size_t max =0; 129 130/* 131 * ":(icase)path" is treated as a pathspec full of 132 * wildcard. In other words, only prefix is considered common 133 * prefix. If the pathspec is abc/foo abc/bar, running in 134 * subdir xyz, the common prefix is still xyz, not xuz/abc as 135 * in non-:(icase). 136 */ 137GUARD_PATHSPEC(pathspec, 138 PATHSPEC_FROMTOP | 139 PATHSPEC_MAXDEPTH | 140 PATHSPEC_LITERAL | 141 PATHSPEC_GLOB | 142 PATHSPEC_ICASE | 143 PATHSPEC_EXCLUDE); 144 145for(n =0; n < pathspec->nr; n++) { 146size_t i =0, len =0, item_len; 147if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 148continue; 149if(pathspec->items[n].magic & PATHSPEC_ICASE) 150 item_len = pathspec->items[n].prefix; 151else 152 item_len = pathspec->items[n].nowildcard_len; 153while(i < item_len && (n ==0|| i < max)) { 154char c = pathspec->items[n].match[i]; 155if(c != pathspec->items[0].match[i]) 156break; 157if(c =='/') 158 len = i +1; 159 i++; 160} 161if(n ==0|| len < max) { 162 max = len; 163if(!max) 164break; 165} 166} 167return max; 168} 169 170/* 171 * Returns a copy of the longest leading path common among all 172 * pathspecs. 173 */ 174char*common_prefix(const struct pathspec *pathspec) 175{ 176unsigned long len =common_prefix_len(pathspec); 177 178return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 179} 180 181intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 182{ 183size_t len; 184 185/* 186 * Calculate common prefix for the pathspec, and 187 * use that to optimize the directory walk 188 */ 189 len =common_prefix_len(pathspec); 190 191/* Read the directory and prune it */ 192read_directory(dir, pathspec->nr ? pathspec->_raw[0] :"", len, pathspec); 193return len; 194} 195 196intwithin_depth(const char*name,int namelen, 197int depth,int max_depth) 198{ 199const char*cp = name, *cpe = name + namelen; 200 201while(cp < cpe) { 202if(*cp++ !='/') 203continue; 204 depth++; 205if(depth > max_depth) 206return0; 207} 208return1; 209} 210 211#define DO_MATCH_EXCLUDE 1 212#define DO_MATCH_DIRECTORY 2 213 214/* 215 * Does 'match' match the given name? 216 * A match is found if 217 * 218 * (1) the 'match' string is leading directory of 'name', or 219 * (2) the 'match' string is a wildcard and matches 'name', or 220 * (3) the 'match' string is exactly the same as 'name'. 221 * 222 * and the return value tells which case it was. 223 * 224 * It returns 0 when there is no match. 225 */ 226static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 227const char*name,int namelen,unsigned flags) 228{ 229/* name/namelen has prefix cut off by caller */ 230const char*match = item->match + prefix; 231int matchlen = item->len - prefix; 232 233/* 234 * The normal call pattern is: 235 * 1. prefix = common_prefix_len(ps); 236 * 2. prune something, or fill_directory 237 * 3. match_pathspec() 238 * 239 * 'prefix' at #1 may be shorter than the command's prefix and 240 * it's ok for #2 to match extra files. Those extras will be 241 * trimmed at #3. 242 * 243 * Suppose the pathspec is 'foo' and '../bar' running from 244 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 245 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 246 * user does not want XYZ/foo, only the "foo" part should be 247 * case-insensitive. We need to filter out XYZ/foo here. In 248 * other words, we do not trust the caller on comparing the 249 * prefix part when :(icase) is involved. We do exact 250 * comparison ourselves. 251 * 252 * Normally the caller (common_prefix_len() in fact) does 253 * _exact_ matching on name[-prefix+1..-1] and we do not need 254 * to check that part. Be defensive and check it anyway, in 255 * case common_prefix_len is changed, or a new caller is 256 * introduced that does not use common_prefix_len. 257 * 258 * If the penalty turns out too high when prefix is really 259 * long, maybe change it to 260 * strncmp(match, name, item->prefix - prefix) 261 */ 262if(item->prefix && (item->magic & PATHSPEC_ICASE) && 263strncmp(item->match, name - prefix, item->prefix)) 264return0; 265 266/* If the match was just the prefix, we matched */ 267if(!*match) 268return MATCHED_RECURSIVELY; 269 270if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 271if(matchlen == namelen) 272return MATCHED_EXACTLY; 273 274if(match[matchlen-1] =='/'|| name[matchlen] =='/') 275return MATCHED_RECURSIVELY; 276}else if((flags & DO_MATCH_DIRECTORY) && 277 match[matchlen -1] =='/'&& 278 namelen == matchlen -1&& 279!ps_strncmp(item, match, name, namelen)) 280return MATCHED_EXACTLY; 281 282if(item->nowildcard_len < item->len && 283!git_fnmatch(item, match, name, 284 item->nowildcard_len - prefix)) 285return MATCHED_FNMATCH; 286 287return0; 288} 289 290/* 291 * Given a name and a list of pathspecs, returns the nature of the 292 * closest (i.e. most specific) match of the name to any of the 293 * pathspecs. 294 * 295 * The caller typically calls this multiple times with the same 296 * pathspec and seen[] array but with different name/namelen 297 * (e.g. entries from the index) and is interested in seeing if and 298 * how each pathspec matches all the names it calls this function 299 * with. A mark is left in the seen[] array for each pathspec element 300 * indicating the closest type of match that element achieved, so if 301 * seen[n] remains zero after multiple invocations, that means the nth 302 * pathspec did not match any names, which could indicate that the 303 * user mistyped the nth pathspec. 304 */ 305static intdo_match_pathspec(const struct pathspec *ps, 306const char*name,int namelen, 307int prefix,char*seen, 308unsigned flags) 309{ 310int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 311 312GUARD_PATHSPEC(ps, 313 PATHSPEC_FROMTOP | 314 PATHSPEC_MAXDEPTH | 315 PATHSPEC_LITERAL | 316 PATHSPEC_GLOB | 317 PATHSPEC_ICASE | 318 PATHSPEC_EXCLUDE); 319 320if(!ps->nr) { 321if(!ps->recursive || 322!(ps->magic & PATHSPEC_MAXDEPTH) || 323 ps->max_depth == -1) 324return MATCHED_RECURSIVELY; 325 326if(within_depth(name, namelen,0, ps->max_depth)) 327return MATCHED_EXACTLY; 328else 329return0; 330} 331 332 name += prefix; 333 namelen -= prefix; 334 335for(i = ps->nr -1; i >=0; i--) { 336int how; 337 338if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 339( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 340continue; 341 342if(seen && seen[i] == MATCHED_EXACTLY) 343continue; 344/* 345 * Make exclude patterns optional and never report 346 * "pathspec ':(exclude)foo' matches no files" 347 */ 348if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 349 seen[i] = MATCHED_FNMATCH; 350 how =match_pathspec_item(ps->items+i, prefix, name, 351 namelen, flags); 352if(ps->recursive && 353(ps->magic & PATHSPEC_MAXDEPTH) && 354 ps->max_depth != -1&& 355 how && how != MATCHED_FNMATCH) { 356int len = ps->items[i].len; 357if(name[len] =='/') 358 len++; 359if(within_depth(name+len, namelen-len,0, ps->max_depth)) 360 how = MATCHED_EXACTLY; 361else 362 how =0; 363} 364if(how) { 365if(retval < how) 366 retval = how; 367if(seen && seen[i] < how) 368 seen[i] = how; 369} 370} 371return retval; 372} 373 374intmatch_pathspec(const struct pathspec *ps, 375const char*name,int namelen, 376int prefix,char*seen,int is_dir) 377{ 378int positive, negative; 379unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 380 positive =do_match_pathspec(ps, name, namelen, 381 prefix, seen, flags); 382if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 383return positive; 384 negative =do_match_pathspec(ps, name, namelen, 385 prefix, seen, 386 flags | DO_MATCH_EXCLUDE); 387return negative ?0: positive; 388} 389 390intreport_path_error(const char*ps_matched, 391const struct pathspec *pathspec, 392const char*prefix) 393{ 394/* 395 * Make sure all pathspec matched; otherwise it is an error. 396 */ 397int num, errors =0; 398for(num =0; num < pathspec->nr; num++) { 399int other, found_dup; 400 401if(ps_matched[num]) 402continue; 403/* 404 * The caller might have fed identical pathspec 405 * twice. Do not barf on such a mistake. 406 * FIXME: parse_pathspec should have eliminated 407 * duplicate pathspec. 408 */ 409for(found_dup = other =0; 410!found_dup && other < pathspec->nr; 411 other++) { 412if(other == num || !ps_matched[other]) 413continue; 414if(!strcmp(pathspec->items[other].original, 415 pathspec->items[num].original)) 416/* 417 * Ok, we have a match already. 418 */ 419 found_dup =1; 420} 421if(found_dup) 422continue; 423 424error("pathspec '%s' did not match any file(s) known to git.", 425 pathspec->items[num].original); 426 errors++; 427} 428return errors; 429} 430 431/* 432 * Return the length of the "simple" part of a path match limiter. 433 */ 434intsimple_length(const char*match) 435{ 436int len = -1; 437 438for(;;) { 439unsigned char c = *match++; 440 len++; 441if(c =='\0'||is_glob_special(c)) 442return len; 443} 444} 445 446intno_wildcard(const char*string) 447{ 448return string[simple_length(string)] =='\0'; 449} 450 451voidparse_exclude_pattern(const char**pattern, 452int*patternlen, 453unsigned*flags, 454int*nowildcardlen) 455{ 456const char*p = *pattern; 457size_t i, len; 458 459*flags =0; 460if(*p =='!') { 461*flags |= EXC_FLAG_NEGATIVE; 462 p++; 463} 464 len =strlen(p); 465if(len && p[len -1] =='/') { 466 len--; 467*flags |= EXC_FLAG_MUSTBEDIR; 468} 469for(i =0; i < len; i++) { 470if(p[i] =='/') 471break; 472} 473if(i == len) 474*flags |= EXC_FLAG_NODIR; 475*nowildcardlen =simple_length(p); 476/* 477 * we should have excluded the trailing slash from 'p' too, 478 * but that's one more allocation. Instead just make sure 479 * nowildcardlen does not exceed real patternlen 480 */ 481if(*nowildcardlen > len) 482*nowildcardlen = len; 483if(*p =='*'&&no_wildcard(p +1)) 484*flags |= EXC_FLAG_ENDSWITH; 485*pattern = p; 486*patternlen = len; 487} 488 489voidadd_exclude(const char*string,const char*base, 490int baselen,struct exclude_list *el,int srcpos) 491{ 492struct exclude *x; 493int patternlen; 494unsigned flags; 495int nowildcardlen; 496 497parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 498if(flags & EXC_FLAG_MUSTBEDIR) { 499FLEXPTR_ALLOC_MEM(x, pattern, string, patternlen); 500}else{ 501 x =xmalloc(sizeof(*x)); 502 x->pattern = string; 503} 504 x->patternlen = patternlen; 505 x->nowildcardlen = nowildcardlen; 506 x->base = base; 507 x->baselen = baselen; 508 x->flags = flags; 509 x->srcpos = srcpos; 510ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 511 el->excludes[el->nr++] = x; 512 x->el = el; 513} 514 515static void*read_skip_worktree_file_from_index(const char*path,size_t*size, 516struct sha1_stat *sha1_stat) 517{ 518int pos, len; 519unsigned long sz; 520enum object_type type; 521void*data; 522 523 len =strlen(path); 524 pos =cache_name_pos(path, len); 525if(pos <0) 526return NULL; 527if(!ce_skip_worktree(active_cache[pos])) 528return NULL; 529 data =read_sha1_file(active_cache[pos]->sha1, &type, &sz); 530if(!data || type != OBJ_BLOB) { 531free(data); 532return NULL; 533} 534*size =xsize_t(sz); 535if(sha1_stat) { 536memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 537hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 538} 539return data; 540} 541 542/* 543 * Frees memory within el which was allocated for exclude patterns and 544 * the file buffer. Does not free el itself. 545 */ 546voidclear_exclude_list(struct exclude_list *el) 547{ 548int i; 549 550for(i =0; i < el->nr; i++) 551free(el->excludes[i]); 552free(el->excludes); 553free(el->filebuf); 554 555memset(el,0,sizeof(*el)); 556} 557 558static voidtrim_trailing_spaces(char*buf) 559{ 560char*p, *last_space = NULL; 561 562for(p = buf; *p; p++) 563switch(*p) { 564case' ': 565if(!last_space) 566 last_space = p; 567break; 568case'\\': 569 p++; 570if(!*p) 571return; 572/* fallthrough */ 573default: 574 last_space = NULL; 575} 576 577if(last_space) 578*last_space ='\0'; 579} 580 581/* 582 * Given a subdirectory name and "dir" of the current directory, 583 * search the subdir in "dir" and return it, or create a new one if it 584 * does not exist in "dir". 585 * 586 * If "name" has the trailing slash, it'll be excluded in the search. 587 */ 588static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 589struct untracked_cache_dir *dir, 590const char*name,int len) 591{ 592int first, last; 593struct untracked_cache_dir *d; 594if(!dir) 595return NULL; 596if(len && name[len -1] =='/') 597 len--; 598 first =0; 599 last = dir->dirs_nr; 600while(last > first) { 601int cmp, next = (last + first) >>1; 602 d = dir->dirs[next]; 603 cmp =strncmp(name, d->name, len); 604if(!cmp &&strlen(d->name) > len) 605 cmp = -1; 606if(!cmp) 607return d; 608if(cmp <0) { 609 last = next; 610continue; 611} 612 first = next+1; 613} 614 615 uc->dir_created++; 616FLEX_ALLOC_MEM(d, name, name, len); 617 618ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 619memmove(dir->dirs + first +1, dir->dirs + first, 620(dir->dirs_nr - first) *sizeof(*dir->dirs)); 621 dir->dirs_nr++; 622 dir->dirs[first] = d; 623return d; 624} 625 626static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 627{ 628int i; 629 dir->valid =0; 630 dir->untracked_nr =0; 631for(i =0; i < dir->dirs_nr; i++) 632do_invalidate_gitignore(dir->dirs[i]); 633} 634 635static voidinvalidate_gitignore(struct untracked_cache *uc, 636struct untracked_cache_dir *dir) 637{ 638 uc->gitignore_invalidated++; 639do_invalidate_gitignore(dir); 640} 641 642static voidinvalidate_directory(struct untracked_cache *uc, 643struct untracked_cache_dir *dir) 644{ 645int i; 646 uc->dir_invalidated++; 647 dir->valid =0; 648 dir->untracked_nr =0; 649for(i =0; i < dir->dirs_nr; i++) 650 dir->dirs[i]->recurse =0; 651} 652 653/* 654 * Given a file with name "fname", read it (either from disk, or from 655 * the index if "check_index" is non-zero), parse it and store the 656 * exclude rules in "el". 657 * 658 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 659 * stat data from disk (only valid if add_excludes returns zero). If 660 * ss_valid is non-zero, "ss" must contain good value as input. 661 */ 662static intadd_excludes(const char*fname,const char*base,int baselen, 663struct exclude_list *el,int check_index, 664struct sha1_stat *sha1_stat) 665{ 666struct stat st; 667int fd, i, lineno =1; 668size_t size =0; 669char*buf, *entry; 670 671 fd =open(fname, O_RDONLY); 672if(fd <0||fstat(fd, &st) <0) { 673if(errno != ENOENT) 674warn_on_inaccessible(fname); 675if(0<= fd) 676close(fd); 677if(!check_index || 678(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 679return-1; 680if(size ==0) { 681free(buf); 682return0; 683} 684if(buf[size-1] !='\n') { 685 buf =xrealloc(buf,st_add(size,1)); 686 buf[size++] ='\n'; 687} 688}else{ 689 size =xsize_t(st.st_size); 690if(size ==0) { 691if(sha1_stat) { 692fill_stat_data(&sha1_stat->stat, &st); 693hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 694 sha1_stat->valid =1; 695} 696close(fd); 697return0; 698} 699 buf =xmallocz(size); 700if(read_in_full(fd, buf, size) != size) { 701free(buf); 702close(fd); 703return-1; 704} 705 buf[size++] ='\n'; 706close(fd); 707if(sha1_stat) { 708int pos; 709if(sha1_stat->valid && 710!match_stat_data_racy(&the_index, &sha1_stat->stat, &st)) 711;/* no content change, ss->sha1 still good */ 712else if(check_index && 713(pos =cache_name_pos(fname,strlen(fname))) >=0&& 714!ce_stage(active_cache[pos]) && 715ce_uptodate(active_cache[pos]) && 716!would_convert_to_git(fname)) 717hashcpy(sha1_stat->sha1, active_cache[pos]->sha1); 718else 719hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 720fill_stat_data(&sha1_stat->stat, &st); 721 sha1_stat->valid =1; 722} 723} 724 725 el->filebuf = buf; 726 727if(skip_utf8_bom(&buf, size)) 728 size -= buf - el->filebuf; 729 730 entry = buf; 731 732for(i =0; i < size; i++) { 733if(buf[i] =='\n') { 734if(entry != buf + i && entry[0] !='#') { 735 buf[i - (i && buf[i-1] =='\r')] =0; 736trim_trailing_spaces(entry); 737add_exclude(entry, base, baselen, el, lineno); 738} 739 lineno++; 740 entry = buf + i +1; 741} 742} 743return0; 744} 745 746intadd_excludes_from_file_to_list(const char*fname,const char*base, 747int baselen,struct exclude_list *el, 748int check_index) 749{ 750returnadd_excludes(fname, base, baselen, el, check_index, NULL); 751} 752 753struct exclude_list *add_exclude_list(struct dir_struct *dir, 754int group_type,const char*src) 755{ 756struct exclude_list *el; 757struct exclude_list_group *group; 758 759 group = &dir->exclude_list_group[group_type]; 760ALLOC_GROW(group->el, group->nr +1, group->alloc); 761 el = &group->el[group->nr++]; 762memset(el,0,sizeof(*el)); 763 el->src = src; 764return el; 765} 766 767/* 768 * Used to set up core.excludesfile and .git/info/exclude lists. 769 */ 770static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 771struct sha1_stat *sha1_stat) 772{ 773struct exclude_list *el; 774/* 775 * catch setup_standard_excludes() that's called before 776 * dir->untracked is assigned. That function behaves 777 * differently when dir->untracked is non-NULL. 778 */ 779if(!dir->untracked) 780 dir->unmanaged_exclude_files++; 781 el =add_exclude_list(dir, EXC_FILE, fname); 782if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 783die("cannot use%sas an exclude file", fname); 784} 785 786voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 787{ 788 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 789add_excludes_from_file_1(dir, fname, NULL); 790} 791 792intmatch_basename(const char*basename,int basenamelen, 793const char*pattern,int prefix,int patternlen, 794unsigned flags) 795{ 796if(prefix == patternlen) { 797if(patternlen == basenamelen && 798!strncmp_icase(pattern, basename, basenamelen)) 799return1; 800}else if(flags & EXC_FLAG_ENDSWITH) { 801/* "*literal" matching against "fooliteral" */ 802if(patternlen -1<= basenamelen && 803!strncmp_icase(pattern +1, 804 basename + basenamelen - (patternlen -1), 805 patternlen -1)) 806return1; 807}else{ 808if(fnmatch_icase_mem(pattern, patternlen, 809 basename, basenamelen, 8100) ==0) 811return1; 812} 813return0; 814} 815 816intmatch_pathname(const char*pathname,int pathlen, 817const char*base,int baselen, 818const char*pattern,int prefix,int patternlen, 819unsigned flags) 820{ 821const char*name; 822int namelen; 823 824/* 825 * match with FNM_PATHNAME; the pattern has base implicitly 826 * in front of it. 827 */ 828if(*pattern =='/') { 829 pattern++; 830 patternlen--; 831 prefix--; 832} 833 834/* 835 * baselen does not count the trailing slash. base[] may or 836 * may not end with a trailing slash though. 837 */ 838if(pathlen < baselen +1|| 839(baselen && pathname[baselen] !='/') || 840strncmp_icase(pathname, base, baselen)) 841return0; 842 843 namelen = baselen ? pathlen - baselen -1: pathlen; 844 name = pathname + pathlen - namelen; 845 846if(prefix) { 847/* 848 * if the non-wildcard part is longer than the 849 * remaining pathname, surely it cannot match. 850 */ 851if(prefix > namelen) 852return0; 853 854if(strncmp_icase(pattern, name, prefix)) 855return0; 856 pattern += prefix; 857 patternlen -= prefix; 858 name += prefix; 859 namelen -= prefix; 860 861/* 862 * If the whole pattern did not have a wildcard, 863 * then our prefix match is all we need; we 864 * do not need to call fnmatch at all. 865 */ 866if(!patternlen && !namelen) 867return1; 868} 869 870returnfnmatch_icase_mem(pattern, patternlen, 871 name, namelen, 872 WM_PATHNAME) ==0; 873} 874 875/* 876 * Scan the given exclude list in reverse to see whether pathname 877 * should be ignored. The first match (i.e. the last on the list), if 878 * any, determines the fate. Returns the exclude_list element which 879 * matched, or NULL for undecided. 880 */ 881static struct exclude *last_exclude_matching_from_list(const char*pathname, 882int pathlen, 883const char*basename, 884int*dtype, 885struct exclude_list *el) 886{ 887struct exclude *exc = NULL;/* undecided */ 888int i; 889 890if(!el->nr) 891return NULL;/* undefined */ 892 893for(i = el->nr -1;0<= i; i--) { 894struct exclude *x = el->excludes[i]; 895const char*exclude = x->pattern; 896int prefix = x->nowildcardlen; 897 898if(x->flags & EXC_FLAG_MUSTBEDIR) { 899if(*dtype == DT_UNKNOWN) 900*dtype =get_dtype(NULL, pathname, pathlen); 901if(*dtype != DT_DIR) 902continue; 903} 904 905if(x->flags & EXC_FLAG_NODIR) { 906if(match_basename(basename, 907 pathlen - (basename - pathname), 908 exclude, prefix, x->patternlen, 909 x->flags)) { 910 exc = x; 911break; 912} 913continue; 914} 915 916assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 917if(match_pathname(pathname, pathlen, 918 x->base, x->baselen ? x->baselen -1:0, 919 exclude, prefix, x->patternlen, x->flags)) { 920 exc = x; 921break; 922} 923} 924return exc; 925} 926 927/* 928 * Scan the list and let the last match determine the fate. 929 * Return 1 for exclude, 0 for include and -1 for undecided. 930 */ 931intis_excluded_from_list(const char*pathname, 932int pathlen,const char*basename,int*dtype, 933struct exclude_list *el) 934{ 935struct exclude *exclude; 936 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 937if(exclude) 938return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 939return-1;/* undecided */ 940} 941 942static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 943const char*pathname,int pathlen,const char*basename, 944int*dtype_p) 945{ 946int i, j; 947struct exclude_list_group *group; 948struct exclude *exclude; 949for(i = EXC_CMDL; i <= EXC_FILE; i++) { 950 group = &dir->exclude_list_group[i]; 951for(j = group->nr -1; j >=0; j--) { 952 exclude =last_exclude_matching_from_list( 953 pathname, pathlen, basename, dtype_p, 954&group->el[j]); 955if(exclude) 956return exclude; 957} 958} 959return NULL; 960} 961 962/* 963 * Loads the per-directory exclude list for the substring of base 964 * which has a char length of baselen. 965 */ 966static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen) 967{ 968struct exclude_list_group *group; 969struct exclude_list *el; 970struct exclude_stack *stk = NULL; 971struct untracked_cache_dir *untracked; 972int current; 973 974 group = &dir->exclude_list_group[EXC_DIRS]; 975 976/* 977 * Pop the exclude lists from the EXCL_DIRS exclude_list_group 978 * which originate from directories not in the prefix of the 979 * path being checked. 980 */ 981while((stk = dir->exclude_stack) != NULL) { 982if(stk->baselen <= baselen && 983!strncmp(dir->basebuf.buf, base, stk->baselen)) 984break; 985 el = &group->el[dir->exclude_stack->exclude_ix]; 986 dir->exclude_stack = stk->prev; 987 dir->exclude = NULL; 988free((char*)el->src);/* see strbuf_detach() below */ 989clear_exclude_list(el); 990free(stk); 991 group->nr--; 992} 993 994/* Skip traversing into sub directories if the parent is excluded */ 995if(dir->exclude) 996return; 997 998/* 999 * Lazy initialization. All call sites currently just1000 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1001 * them seems lots of work for little benefit.1002 */1003if(!dir->basebuf.buf)1004strbuf_init(&dir->basebuf, PATH_MAX);10051006/* Read from the parent directories and push them down. */1007 current = stk ? stk->baselen : -1;1008strbuf_setlen(&dir->basebuf, current <0?0: current);1009if(dir->untracked)1010 untracked = stk ? stk->ucd : dir->untracked->root;1011else1012 untracked = NULL;10131014while(current < baselen) {1015const char*cp;1016struct sha1_stat sha1_stat;10171018 stk =xcalloc(1,sizeof(*stk));1019if(current <0) {1020 cp = base;1021 current =0;1022}else{1023 cp =strchr(base + current +1,'/');1024if(!cp)1025die("oops in prep_exclude");1026 cp++;1027 untracked =1028lookup_untracked(dir->untracked, untracked,1029 base + current,1030 cp - base - current);1031}1032 stk->prev = dir->exclude_stack;1033 stk->baselen = cp - base;1034 stk->exclude_ix = group->nr;1035 stk->ucd = untracked;1036 el =add_exclude_list(dir, EXC_DIRS, NULL);1037strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1038assert(stk->baselen == dir->basebuf.len);10391040/* Abort if the directory is excluded */1041if(stk->baselen) {1042int dt = DT_DIR;1043 dir->basebuf.buf[stk->baselen -1] =0;1044 dir->exclude =last_exclude_matching_from_lists(dir,1045 dir->basebuf.buf, stk->baselen -1,1046 dir->basebuf.buf + current, &dt);1047 dir->basebuf.buf[stk->baselen -1] ='/';1048if(dir->exclude &&1049 dir->exclude->flags & EXC_FLAG_NEGATIVE)1050 dir->exclude = NULL;1051if(dir->exclude) {1052 dir->exclude_stack = stk;1053return;1054}1055}10561057/* Try to read per-directory file */1058hashclr(sha1_stat.sha1);1059 sha1_stat.valid =0;1060if(dir->exclude_per_dir &&1061/*1062 * If we know that no files have been added in1063 * this directory (i.e. valid_cached_dir() has1064 * been executed and set untracked->valid) ..1065 */1066(!untracked || !untracked->valid ||1067/*1068 * .. and .gitignore does not exist before1069 * (i.e. null exclude_sha1). Then we can skip1070 * loading .gitignore, which would result in1071 * ENOENT anyway.1072 */1073!is_null_sha1(untracked->exclude_sha1))) {1074/*1075 * dir->basebuf gets reused by the traversal, but we1076 * need fname to remain unchanged to ensure the src1077 * member of each struct exclude correctly1078 * back-references its source file. Other invocations1079 * of add_exclude_list provide stable strings, so we1080 * strbuf_detach() and free() here in the caller.1081 */1082struct strbuf sb = STRBUF_INIT;1083strbuf_addbuf(&sb, &dir->basebuf);1084strbuf_addstr(&sb, dir->exclude_per_dir);1085 el->src =strbuf_detach(&sb, NULL);1086add_excludes(el->src, el->src, stk->baselen, el,1,1087 untracked ? &sha1_stat : NULL);1088}1089/*1090 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1091 * will first be called in valid_cached_dir() then maybe many1092 * times more in last_exclude_matching(). When the cache is1093 * used, last_exclude_matching() will not be called and1094 * reading .gitignore content will be a waste.1095 *1096 * So when it's called by valid_cached_dir() and we can get1097 * .gitignore SHA-1 from the index (i.e. .gitignore is not1098 * modified on work tree), we could delay reading the1099 * .gitignore content until we absolutely need it in1100 * last_exclude_matching(). Be careful about ignore rule1101 * order, though, if you do that.1102 */1103if(untracked &&1104hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1105invalidate_gitignore(dir->untracked, untracked);1106hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1107}1108 dir->exclude_stack = stk;1109 current = stk->baselen;1110}1111strbuf_setlen(&dir->basebuf, baselen);1112}11131114/*1115 * Loads the exclude lists for the directory containing pathname, then1116 * scans all exclude lists to determine whether pathname is excluded.1117 * Returns the exclude_list element which matched, or NULL for1118 * undecided.1119 */1120struct exclude *last_exclude_matching(struct dir_struct *dir,1121const char*pathname,1122int*dtype_p)1123{1124int pathlen =strlen(pathname);1125const char*basename =strrchr(pathname,'/');1126 basename = (basename) ? basename+1: pathname;11271128prep_exclude(dir, pathname, basename-pathname);11291130if(dir->exclude)1131return dir->exclude;11321133returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1134 basename, dtype_p);1135}11361137/*1138 * Loads the exclude lists for the directory containing pathname, then1139 * scans all exclude lists to determine whether pathname is excluded.1140 * Returns 1 if true, otherwise 0.1141 */1142intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1143{1144struct exclude *exclude =1145last_exclude_matching(dir, pathname, dtype_p);1146if(exclude)1147return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1148return0;1149}11501151static struct dir_entry *dir_entry_new(const char*pathname,int len)1152{1153struct dir_entry *ent;11541155FLEX_ALLOC_MEM(ent, name, pathname, len);1156 ent->len = len;1157return ent;1158}11591160static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1161{1162if(cache_file_exists(pathname, len, ignore_case))1163return NULL;11641165ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1166return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1167}11681169struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1170{1171if(!cache_name_is_other(pathname, len))1172return NULL;11731174ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1175return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1176}11771178enum exist_status {1179 index_nonexistent =0,1180 index_directory,1181 index_gitdir1182};11831184/*1185 * Do not use the alphabetically sorted index to look up1186 * the directory name; instead, use the case insensitive1187 * directory hash.1188 */1189static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1190{1191struct cache_entry *ce;11921193if(cache_dir_exists(dirname, len))1194return index_directory;11951196 ce =cache_file_exists(dirname, len, ignore_case);1197if(ce &&S_ISGITLINK(ce->ce_mode))1198return index_gitdir;11991200return index_nonexistent;1201}12021203/*1204 * The index sorts alphabetically by entry name, which1205 * means that a gitlink sorts as '\0' at the end, while1206 * a directory (which is defined not as an entry, but as1207 * the files it contains) will sort with the '/' at the1208 * end.1209 */1210static enum exist_status directory_exists_in_index(const char*dirname,int len)1211{1212int pos;12131214if(ignore_case)1215returndirectory_exists_in_index_icase(dirname, len);12161217 pos =cache_name_pos(dirname, len);1218if(pos <0)1219 pos = -pos-1;1220while(pos < active_nr) {1221const struct cache_entry *ce = active_cache[pos++];1222unsigned char endchar;12231224if(strncmp(ce->name, dirname, len))1225break;1226 endchar = ce->name[len];1227if(endchar >'/')1228break;1229if(endchar =='/')1230return index_directory;1231if(!endchar &&S_ISGITLINK(ce->ce_mode))1232return index_gitdir;1233}1234return index_nonexistent;1235}12361237/*1238 * When we find a directory when traversing the filesystem, we1239 * have three distinct cases:1240 *1241 * - ignore it1242 * - see it as a directory1243 * - recurse into it1244 *1245 * and which one we choose depends on a combination of existing1246 * git index contents and the flags passed into the directory1247 * traversal routine.1248 *1249 * Case 1: If we *already* have entries in the index under that1250 * directory name, we always recurse into the directory to see1251 * all the files.1252 *1253 * Case 2: If we *already* have that directory name as a gitlink,1254 * we always continue to see it as a gitlink, regardless of whether1255 * there is an actual git directory there or not (it might not1256 * be checked out as a subproject!)1257 *1258 * Case 3: if we didn't have it in the index previously, we1259 * have a few sub-cases:1260 *1261 * (a) if "show_other_directories" is true, we show it as1262 * just a directory, unless "hide_empty_directories" is1263 * also true, in which case we need to check if it contains any1264 * untracked and / or ignored files.1265 * (b) if it looks like a git directory, and we don't have1266 * 'no_gitlinks' set we treat it as a gitlink, and show it1267 * as a directory.1268 * (c) otherwise, we recurse into it.1269 */1270static enum path_treatment treat_directory(struct dir_struct *dir,1271struct untracked_cache_dir *untracked,1272const char*dirname,int len,int baselen,int exclude,1273const struct path_simplify *simplify)1274{1275/* The "len-1" is to strip the final '/' */1276switch(directory_exists_in_index(dirname, len-1)) {1277case index_directory:1278return path_recurse;12791280case index_gitdir:1281return path_none;12821283case index_nonexistent:1284if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1285break;1286if(!(dir->flags & DIR_NO_GITLINKS)) {1287unsigned char sha1[20];1288if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1289return path_untracked;1290}1291return path_recurse;1292}12931294/* This is the "show_other_directories" case */12951296if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1297return exclude ? path_excluded : path_untracked;12981299 untracked =lookup_untracked(dir->untracked, untracked,1300 dirname + baselen, len - baselen);1301returnread_directory_recursive(dir, dirname, len,1302 untracked,1, simplify);1303}13041305/*1306 * This is an inexact early pruning of any recursive directory1307 * reading - if the path cannot possibly be in the pathspec,1308 * return true, and we'll skip it early.1309 */1310static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1311{1312if(simplify) {1313for(;;) {1314const char*match = simplify->path;1315int len = simplify->len;13161317if(!match)1318break;1319if(len > pathlen)1320 len = pathlen;1321if(!memcmp(path, match, len))1322return0;1323 simplify++;1324}1325return1;1326}1327return0;1328}13291330/*1331 * This function tells us whether an excluded path matches a1332 * list of "interesting" pathspecs. That is, whether a path matched1333 * by any of the pathspecs could possibly be ignored by excluding1334 * the specified path. This can happen if:1335 *1336 * 1. the path is mentioned explicitly in the pathspec1337 *1338 * 2. the path is a directory prefix of some element in the1339 * pathspec1340 */1341static intexclude_matches_pathspec(const char*path,int len,1342const struct path_simplify *simplify)1343{1344if(simplify) {1345for(; simplify->path; simplify++) {1346if(len == simplify->len1347&& !memcmp(path, simplify->path, len))1348return1;1349if(len < simplify->len1350&& simplify->path[len] =='/'1351&& !memcmp(path, simplify->path, len))1352return1;1353}1354}1355return0;1356}13571358static intget_index_dtype(const char*path,int len)1359{1360int pos;1361const struct cache_entry *ce;13621363 ce =cache_file_exists(path, len,0);1364if(ce) {1365if(!ce_uptodate(ce))1366return DT_UNKNOWN;1367if(S_ISGITLINK(ce->ce_mode))1368return DT_DIR;1369/*1370 * Nobody actually cares about the1371 * difference between DT_LNK and DT_REG1372 */1373return DT_REG;1374}13751376/* Try to look it up as a directory */1377 pos =cache_name_pos(path, len);1378if(pos >=0)1379return DT_UNKNOWN;1380 pos = -pos-1;1381while(pos < active_nr) {1382 ce = active_cache[pos++];1383if(strncmp(ce->name, path, len))1384break;1385if(ce->name[len] >'/')1386break;1387if(ce->name[len] <'/')1388continue;1389if(!ce_uptodate(ce))1390break;/* continue? */1391return DT_DIR;1392}1393return DT_UNKNOWN;1394}13951396static intget_dtype(struct dirent *de,const char*path,int len)1397{1398int dtype = de ?DTYPE(de) : DT_UNKNOWN;1399struct stat st;14001401if(dtype != DT_UNKNOWN)1402return dtype;1403 dtype =get_index_dtype(path, len);1404if(dtype != DT_UNKNOWN)1405return dtype;1406if(lstat(path, &st))1407return dtype;1408if(S_ISREG(st.st_mode))1409return DT_REG;1410if(S_ISDIR(st.st_mode))1411return DT_DIR;1412if(S_ISLNK(st.st_mode))1413return DT_LNK;1414return dtype;1415}14161417static enum path_treatment treat_one_path(struct dir_struct *dir,1418struct untracked_cache_dir *untracked,1419struct strbuf *path,1420int baselen,1421const struct path_simplify *simplify,1422int dtype,struct dirent *de)1423{1424int exclude;1425int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);14261427if(dtype == DT_UNKNOWN)1428 dtype =get_dtype(de, path->buf, path->len);14291430/* Always exclude indexed files */1431if(dtype != DT_DIR && has_path_in_index)1432return path_none;14331434/*1435 * When we are looking at a directory P in the working tree,1436 * there are three cases:1437 *1438 * (1) P exists in the index. Everything inside the directory P in1439 * the working tree needs to go when P is checked out from the1440 * index.1441 *1442 * (2) P does not exist in the index, but there is P/Q in the index.1443 * We know P will stay a directory when we check out the contents1444 * of the index, but we do not know yet if there is a directory1445 * P/Q in the working tree to be killed, so we need to recurse.1446 *1447 * (3) P does not exist in the index, and there is no P/Q in the index1448 * to require P to be a directory, either. Only in this case, we1449 * know that everything inside P will not be killed without1450 * recursing.1451 */1452if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1453(dtype == DT_DIR) &&1454!has_path_in_index &&1455(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1456return path_none;14571458 exclude =is_excluded(dir, path->buf, &dtype);14591460/*1461 * Excluded? If we don't explicitly want to show1462 * ignored files, ignore it1463 */1464if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1465return path_excluded;14661467switch(dtype) {1468default:1469return path_none;1470case DT_DIR:1471strbuf_addch(path,'/');1472returntreat_directory(dir, untracked, path->buf, path->len,1473 baselen, exclude, simplify);1474case DT_REG:1475case DT_LNK:1476return exclude ? path_excluded : path_untracked;1477}1478}14791480static enum path_treatment treat_path_fast(struct dir_struct *dir,1481struct untracked_cache_dir *untracked,1482struct cached_dir *cdir,1483struct strbuf *path,1484int baselen,1485const struct path_simplify *simplify)1486{1487strbuf_setlen(path, baselen);1488if(!cdir->ucd) {1489strbuf_addstr(path, cdir->file);1490return path_untracked;1491}1492strbuf_addstr(path, cdir->ucd->name);1493/* treat_one_path() does this before it calls treat_directory() */1494strbuf_complete(path,'/');1495if(cdir->ucd->check_only)1496/*1497 * check_only is set as a result of treat_directory() getting1498 * to its bottom. Verify again the same set of directories1499 * with check_only set.1500 */1501returnread_directory_recursive(dir, path->buf, path->len,1502 cdir->ucd,1, simplify);1503/*1504 * We get path_recurse in the first run when1505 * directory_exists_in_index() returns index_nonexistent. We1506 * are sure that new changes in the index does not impact the1507 * outcome. Return now.1508 */1509return path_recurse;1510}15111512static enum path_treatment treat_path(struct dir_struct *dir,1513struct untracked_cache_dir *untracked,1514struct cached_dir *cdir,1515struct strbuf *path,1516int baselen,1517const struct path_simplify *simplify)1518{1519int dtype;1520struct dirent *de = cdir->de;15211522if(!de)1523returntreat_path_fast(dir, untracked, cdir, path,1524 baselen, simplify);1525if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1526return path_none;1527strbuf_setlen(path, baselen);1528strbuf_addstr(path, de->d_name);1529if(simplify_away(path->buf, path->len, simplify))1530return path_none;15311532 dtype =DTYPE(de);1533returntreat_one_path(dir, untracked, path, baselen, simplify, dtype, de);1534}15351536static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1537{1538if(!dir)1539return;1540ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1541 dir->untracked_alloc);1542 dir->untracked[dir->untracked_nr++] =xstrdup(name);1543}15441545static intvalid_cached_dir(struct dir_struct *dir,1546struct untracked_cache_dir *untracked,1547struct strbuf *path,1548int check_only)1549{1550struct stat st;15511552if(!untracked)1553return0;15541555if(stat(path->len ? path->buf :".", &st)) {1556invalidate_directory(dir->untracked, untracked);1557memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1558return0;1559}1560if(!untracked->valid ||1561match_stat_data_racy(&the_index, &untracked->stat_data, &st)) {1562if(untracked->valid)1563invalidate_directory(dir->untracked, untracked);1564fill_stat_data(&untracked->stat_data, &st);1565return0;1566}15671568if(untracked->check_only != !!check_only) {1569invalidate_directory(dir->untracked, untracked);1570return0;1571}15721573/*1574 * prep_exclude will be called eventually on this directory,1575 * but it's called much later in last_exclude_matching(). We1576 * need it now to determine the validity of the cache for this1577 * path. The next calls will be nearly no-op, the way1578 * prep_exclude() is designed.1579 */1580if(path->len && path->buf[path->len -1] !='/') {1581strbuf_addch(path,'/');1582prep_exclude(dir, path->buf, path->len);1583strbuf_setlen(path, path->len -1);1584}else1585prep_exclude(dir, path->buf, path->len);15861587/* hopefully prep_exclude() haven't invalidated this entry... */1588return untracked->valid;1589}15901591static intopen_cached_dir(struct cached_dir *cdir,1592struct dir_struct *dir,1593struct untracked_cache_dir *untracked,1594struct strbuf *path,1595int check_only)1596{1597memset(cdir,0,sizeof(*cdir));1598 cdir->untracked = untracked;1599if(valid_cached_dir(dir, untracked, path, check_only))1600return0;1601 cdir->fdir =opendir(path->len ? path->buf :".");1602if(dir->untracked)1603 dir->untracked->dir_opened++;1604if(!cdir->fdir)1605return-1;1606return0;1607}16081609static intread_cached_dir(struct cached_dir *cdir)1610{1611if(cdir->fdir) {1612 cdir->de =readdir(cdir->fdir);1613if(!cdir->de)1614return-1;1615return0;1616}1617while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1618struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1619if(!d->recurse) {1620 cdir->nr_dirs++;1621continue;1622}1623 cdir->ucd = d;1624 cdir->nr_dirs++;1625return0;1626}1627 cdir->ucd = NULL;1628if(cdir->nr_files < cdir->untracked->untracked_nr) {1629struct untracked_cache_dir *d = cdir->untracked;1630 cdir->file = d->untracked[cdir->nr_files++];1631return0;1632}1633return-1;1634}16351636static voidclose_cached_dir(struct cached_dir *cdir)1637{1638if(cdir->fdir)1639closedir(cdir->fdir);1640/*1641 * We have gone through this directory and found no untracked1642 * entries. Mark it valid.1643 */1644if(cdir->untracked) {1645 cdir->untracked->valid =1;1646 cdir->untracked->recurse =1;1647}1648}16491650/*1651 * Read a directory tree. We currently ignore anything but1652 * directories, regular files and symlinks. That's because git1653 * doesn't handle them at all yet. Maybe that will change some1654 * day.1655 *1656 * Also, we ignore the name ".git" (even if it is not a directory).1657 * That likely will not change.1658 *1659 * Returns the most significant path_treatment value encountered in the scan.1660 */1661static enum path_treatment read_directory_recursive(struct dir_struct *dir,1662const char*base,int baselen,1663struct untracked_cache_dir *untracked,int check_only,1664const struct path_simplify *simplify)1665{1666struct cached_dir cdir;1667enum path_treatment state, subdir_state, dir_state = path_none;1668struct strbuf path = STRBUF_INIT;16691670strbuf_add(&path, base, baselen);16711672if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1673goto out;16741675if(untracked)1676 untracked->check_only = !!check_only;16771678while(!read_cached_dir(&cdir)) {1679/* check how the file or directory should be treated */1680 state =treat_path(dir, untracked, &cdir, &path, baselen, simplify);16811682if(state > dir_state)1683 dir_state = state;16841685/* recurse into subdir if instructed by treat_path */1686if(state == path_recurse) {1687struct untracked_cache_dir *ud;1688 ud =lookup_untracked(dir->untracked, untracked,1689 path.buf + baselen,1690 path.len - baselen);1691 subdir_state =1692read_directory_recursive(dir, path.buf, path.len,1693 ud, check_only, simplify);1694if(subdir_state > dir_state)1695 dir_state = subdir_state;1696}16971698if(check_only) {1699/* abort early if maximum state has been reached */1700if(dir_state == path_untracked) {1701if(cdir.fdir)1702add_untracked(untracked, path.buf + baselen);1703break;1704}1705/* skip the dir_add_* part */1706continue;1707}17081709/* add the path to the appropriate result list */1710switch(state) {1711case path_excluded:1712if(dir->flags & DIR_SHOW_IGNORED)1713dir_add_name(dir, path.buf, path.len);1714else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1715((dir->flags & DIR_COLLECT_IGNORED) &&1716exclude_matches_pathspec(path.buf, path.len,1717 simplify)))1718dir_add_ignored(dir, path.buf, path.len);1719break;17201721case path_untracked:1722if(dir->flags & DIR_SHOW_IGNORED)1723break;1724dir_add_name(dir, path.buf, path.len);1725if(cdir.fdir)1726add_untracked(untracked, path.buf + baselen);1727break;17281729default:1730break;1731}1732}1733close_cached_dir(&cdir);1734 out:1735strbuf_release(&path);17361737return dir_state;1738}17391740static intcmp_name(const void*p1,const void*p2)1741{1742const struct dir_entry *e1 = *(const struct dir_entry **)p1;1743const struct dir_entry *e2 = *(const struct dir_entry **)p2;17441745returnname_compare(e1->name, e1->len, e2->name, e2->len);1746}17471748static struct path_simplify *create_simplify(const char**pathspec)1749{1750int nr, alloc =0;1751struct path_simplify *simplify = NULL;17521753if(!pathspec)1754return NULL;17551756for(nr =0; ; nr++) {1757const char*match;1758ALLOC_GROW(simplify, nr +1, alloc);1759 match = *pathspec++;1760if(!match)1761break;1762 simplify[nr].path = match;1763 simplify[nr].len =simple_length(match);1764}1765 simplify[nr].path = NULL;1766 simplify[nr].len =0;1767return simplify;1768}17691770static voidfree_simplify(struct path_simplify *simplify)1771{1772free(simplify);1773}17741775static inttreat_leading_path(struct dir_struct *dir,1776const char*path,int len,1777const struct path_simplify *simplify)1778{1779struct strbuf sb = STRBUF_INIT;1780int baselen, rc =0;1781const char*cp;1782int old_flags = dir->flags;17831784while(len && path[len -1] =='/')1785 len--;1786if(!len)1787return1;1788 baselen =0;1789 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1790while(1) {1791 cp = path + baselen + !!baselen;1792 cp =memchr(cp,'/', path + len - cp);1793if(!cp)1794 baselen = len;1795else1796 baselen = cp - path;1797strbuf_setlen(&sb,0);1798strbuf_add(&sb, path, baselen);1799if(!is_directory(sb.buf))1800break;1801if(simplify_away(sb.buf, sb.len, simplify))1802break;1803if(treat_one_path(dir, NULL, &sb, baselen, simplify,1804 DT_DIR, NULL) == path_none)1805break;/* do not recurse into it */1806if(len <= baselen) {1807 rc =1;1808break;/* finished checking */1809}1810}1811strbuf_release(&sb);1812 dir->flags = old_flags;1813return rc;1814}18151816static const char*get_ident_string(void)1817{1818static struct strbuf sb = STRBUF_INIT;1819struct utsname uts;18201821if(sb.len)1822return sb.buf;1823if(uname(&uts) <0)1824die_errno(_("failed to get kernel name and information"));1825strbuf_addf(&sb,"Location%s, system%s",get_git_work_tree(),1826 uts.sysname);1827return sb.buf;1828}18291830static intident_in_untracked(const struct untracked_cache *uc)1831{1832/*1833 * Previous git versions may have saved many NUL separated1834 * strings in the "ident" field, but it is insane to manage1835 * many locations, so just take care of the first one.1836 */18371838return!strcmp(uc->ident.buf,get_ident_string());1839}18401841static voidset_untracked_ident(struct untracked_cache *uc)1842{1843strbuf_reset(&uc->ident);1844strbuf_addstr(&uc->ident,get_ident_string());18451846/*1847 * This strbuf used to contain a list of NUL separated1848 * strings, so save NUL too for backward compatibility.1849 */1850strbuf_addch(&uc->ident,0);1851}18521853static voidnew_untracked_cache(struct index_state *istate)1854{1855struct untracked_cache *uc =xcalloc(1,sizeof(*uc));1856strbuf_init(&uc->ident,100);1857 uc->exclude_per_dir =".gitignore";1858/* should be the same flags used by git-status */1859 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;1860set_untracked_ident(uc);1861 istate->untracked = uc;1862 istate->cache_changed |= UNTRACKED_CHANGED;1863}18641865voidadd_untracked_cache(struct index_state *istate)1866{1867if(!istate->untracked) {1868new_untracked_cache(istate);1869}else{1870if(!ident_in_untracked(istate->untracked)) {1871free_untracked_cache(istate->untracked);1872new_untracked_cache(istate);1873}1874}1875}18761877voidremove_untracked_cache(struct index_state *istate)1878{1879if(istate->untracked) {1880free_untracked_cache(istate->untracked);1881 istate->untracked = NULL;1882 istate->cache_changed |= UNTRACKED_CHANGED;1883}1884}18851886static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1887int base_len,1888const struct pathspec *pathspec)1889{1890struct untracked_cache_dir *root;18911892if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))1893return NULL;18941895/*1896 * We only support $GIT_DIR/info/exclude and core.excludesfile1897 * as the global ignore rule files. Any other additions1898 * (e.g. from command line) invalidate the cache. This1899 * condition also catches running setup_standard_excludes()1900 * before setting dir->untracked!1901 */1902if(dir->unmanaged_exclude_files)1903return NULL;19041905/*1906 * Optimize for the main use case only: whole-tree git1907 * status. More work involved in treat_leading_path() if we1908 * use cache on just a subset of the worktree. pathspec1909 * support could make the matter even worse.1910 */1911if(base_len || (pathspec && pathspec->nr))1912return NULL;19131914/* Different set of flags may produce different results */1915if(dir->flags != dir->untracked->dir_flags ||1916/*1917 * See treat_directory(), case index_nonexistent. Without1918 * this flag, we may need to also cache .git file content1919 * for the resolve_gitlink_ref() call, which we don't.1920 */1921!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1922/* We don't support collecting ignore files */1923(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1924 DIR_COLLECT_IGNORED)))1925return NULL;19261927/*1928 * If we use .gitignore in the cache and now you change it to1929 * .gitexclude, everything will go wrong.1930 */1931if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1932strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1933return NULL;19341935/*1936 * EXC_CMDL is not considered in the cache. If people set it,1937 * skip the cache.1938 */1939if(dir->exclude_list_group[EXC_CMDL].nr)1940return NULL;19411942if(!ident_in_untracked(dir->untracked)) {1943warning(_("Untracked cache is disabled on this system or location."));1944return NULL;1945}19461947if(!dir->untracked->root) {1948const int len =sizeof(*dir->untracked->root);1949 dir->untracked->root =xmalloc(len);1950memset(dir->untracked->root,0, len);1951}19521953/* Validate $GIT_DIR/info/exclude and core.excludesfile */1954 root = dir->untracked->root;1955if(hashcmp(dir->ss_info_exclude.sha1,1956 dir->untracked->ss_info_exclude.sha1)) {1957invalidate_gitignore(dir->untracked, root);1958 dir->untracked->ss_info_exclude = dir->ss_info_exclude;1959}1960if(hashcmp(dir->ss_excludes_file.sha1,1961 dir->untracked->ss_excludes_file.sha1)) {1962invalidate_gitignore(dir->untracked, root);1963 dir->untracked->ss_excludes_file = dir->ss_excludes_file;1964}19651966/* Make sure this directory is not dropped out at saving phase */1967 root->recurse =1;1968return root;1969}19701971intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)1972{1973struct path_simplify *simplify;1974struct untracked_cache_dir *untracked;19751976/*1977 * Check out create_simplify()1978 */1979if(pathspec)1980GUARD_PATHSPEC(pathspec,1981 PATHSPEC_FROMTOP |1982 PATHSPEC_MAXDEPTH |1983 PATHSPEC_LITERAL |1984 PATHSPEC_GLOB |1985 PATHSPEC_ICASE |1986 PATHSPEC_EXCLUDE);19871988if(has_symlink_leading_path(path, len))1989return dir->nr;19901991/*1992 * exclude patterns are treated like positive ones in1993 * create_simplify. Usually exclude patterns should be a1994 * subset of positive ones, which has no impacts on1995 * create_simplify().1996 */1997 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);1998 untracked =validate_untracked_cache(dir, len, pathspec);1999if(!untracked)2000/*2001 * make sure untracked cache code path is disabled,2002 * e.g. prep_exclude()2003 */2004 dir->untracked = NULL;2005if(!len ||treat_leading_path(dir, path, len, simplify))2006read_directory_recursive(dir, path, len, untracked,0, simplify);2007free_simplify(simplify);2008qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);2009qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);2010if(dir->untracked) {2011static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);2012trace_printf_key(&trace_untracked_stats,2013"node creation:%u\n"2014"gitignore invalidation:%u\n"2015"directory invalidation:%u\n"2016"opendir:%u\n",2017 dir->untracked->dir_created,2018 dir->untracked->gitignore_invalidated,2019 dir->untracked->dir_invalidated,2020 dir->untracked->dir_opened);2021if(dir->untracked == the_index.untracked &&2022(dir->untracked->dir_opened ||2023 dir->untracked->gitignore_invalidated ||2024 dir->untracked->dir_invalidated))2025 the_index.cache_changed |= UNTRACKED_CHANGED;2026if(dir->untracked != the_index.untracked) {2027free(dir->untracked);2028 dir->untracked = NULL;2029}2030}2031return dir->nr;2032}20332034intfile_exists(const char*f)2035{2036struct stat sb;2037returnlstat(f, &sb) ==0;2038}20392040static intcmp_icase(char a,char b)2041{2042if(a == b)2043return0;2044if(ignore_case)2045returntoupper(a) -toupper(b);2046return a - b;2047}20482049/*2050 * Given two normalized paths (a trailing slash is ok), if subdir is2051 * outside dir, return -1. Otherwise return the offset in subdir that2052 * can be used as relative path to dir.2053 */2054intdir_inside_of(const char*subdir,const char*dir)2055{2056int offset =0;20572058assert(dir && subdir && *dir && *subdir);20592060while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2061 dir++;2062 subdir++;2063 offset++;2064}20652066/* hel[p]/me vs hel[l]/yeah */2067if(*dir && *subdir)2068return-1;20692070if(!*subdir)2071return!*dir ? offset : -1;/* same dir */20722073/* foo/[b]ar vs foo/[] */2074if(is_dir_sep(dir[-1]))2075returnis_dir_sep(subdir[-1]) ? offset : -1;20762077/* foo[/]bar vs foo[] */2078returnis_dir_sep(*subdir) ? offset +1: -1;2079}20802081intis_inside_dir(const char*dir)2082{2083char*cwd;2084int rc;20852086if(!dir)2087return0;20882089 cwd =xgetcwd();2090 rc = (dir_inside_of(cwd, dir) >=0);2091free(cwd);2092return rc;2093}20942095intis_empty_dir(const char*path)2096{2097DIR*dir =opendir(path);2098struct dirent *e;2099int ret =1;21002101if(!dir)2102return0;21032104while((e =readdir(dir)) != NULL)2105if(!is_dot_or_dotdot(e->d_name)) {2106 ret =0;2107break;2108}21092110closedir(dir);2111return ret;2112}21132114static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2115{2116DIR*dir;2117struct dirent *e;2118int ret =0, original_len = path->len, len, kept_down =0;2119int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2120int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2121unsigned char submodule_head[20];21222123if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2124!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2125/* Do not descend and nuke a nested git work tree. */2126if(kept_up)2127*kept_up =1;2128return0;2129}21302131 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2132 dir =opendir(path->buf);2133if(!dir) {2134if(errno == ENOENT)2135return keep_toplevel ? -1:0;2136else if(errno == EACCES && !keep_toplevel)2137/*2138 * An empty dir could be removable even if it2139 * is unreadable:2140 */2141returnrmdir(path->buf);2142else2143return-1;2144}2145strbuf_complete(path,'/');21462147 len = path->len;2148while((e =readdir(dir)) != NULL) {2149struct stat st;2150if(is_dot_or_dotdot(e->d_name))2151continue;21522153strbuf_setlen(path, len);2154strbuf_addstr(path, e->d_name);2155if(lstat(path->buf, &st)) {2156if(errno == ENOENT)2157/*2158 * file disappeared, which is what we2159 * wanted anyway2160 */2161continue;2162/* fall thru */2163}else if(S_ISDIR(st.st_mode)) {2164if(!remove_dir_recurse(path, flag, &kept_down))2165continue;/* happy */2166}else if(!only_empty &&2167(!unlink(path->buf) || errno == ENOENT)) {2168continue;/* happy, too */2169}21702171/* path too long, stat fails, or non-directory still exists */2172 ret = -1;2173break;2174}2175closedir(dir);21762177strbuf_setlen(path, original_len);2178if(!ret && !keep_toplevel && !kept_down)2179 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2180else if(kept_up)2181/*2182 * report the uplevel that it is not an error that we2183 * did not rmdir() our directory.2184 */2185*kept_up = !ret;2186return ret;2187}21882189intremove_dir_recursively(struct strbuf *path,int flag)2190{2191returnremove_dir_recurse(path, flag, NULL);2192}21932194staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")21952196voidsetup_standard_excludes(struct dir_struct *dir)2197{2198const char*path;21992200 dir->exclude_per_dir =".gitignore";22012202/* core.excludefile defaulting to $XDG_HOME/git/ignore */2203if(!excludes_file)2204 excludes_file =xdg_config_home("ignore");2205if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2206add_excludes_from_file_1(dir, excludes_file,2207 dir->untracked ? &dir->ss_excludes_file : NULL);22082209/* per repository user preference */2210 path =git_path_info_exclude();2211if(!access_or_warn(path, R_OK,0))2212add_excludes_from_file_1(dir, path,2213 dir->untracked ? &dir->ss_info_exclude : NULL);2214}22152216intremove_path(const char*name)2217{2218char*slash;22192220if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2221return-1;22222223 slash =strrchr(name,'/');2224if(slash) {2225char*dirs =xstrdup(name);2226 slash = dirs + (slash - name);2227do{2228*slash ='\0';2229}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2230free(dirs);2231}2232return0;2233}22342235/*2236 * Frees memory within dir which was allocated for exclude lists and2237 * the exclude_stack. Does not free dir itself.2238 */2239voidclear_directory(struct dir_struct *dir)2240{2241int i, j;2242struct exclude_list_group *group;2243struct exclude_list *el;2244struct exclude_stack *stk;22452246for(i = EXC_CMDL; i <= EXC_FILE; i++) {2247 group = &dir->exclude_list_group[i];2248for(j =0; j < group->nr; j++) {2249 el = &group->el[j];2250if(i == EXC_DIRS)2251free((char*)el->src);2252clear_exclude_list(el);2253}2254free(group->el);2255}22562257 stk = dir->exclude_stack;2258while(stk) {2259struct exclude_stack *prev = stk->prev;2260free(stk);2261 stk = prev;2262}2263strbuf_release(&dir->basebuf);2264}22652266struct ondisk_untracked_cache {2267struct stat_data info_exclude_stat;2268struct stat_data excludes_file_stat;2269uint32_t dir_flags;2270unsigned char info_exclude_sha1[20];2271unsigned char excludes_file_sha1[20];2272char exclude_per_dir[FLEX_ARRAY];2273};22742275#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)22762277struct write_data {2278int index;/* number of written untracked_cache_dir */2279struct ewah_bitmap *check_only;/* from untracked_cache_dir */2280struct ewah_bitmap *valid;/* from untracked_cache_dir */2281struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2282struct strbuf out;2283struct strbuf sb_stat;2284struct strbuf sb_sha1;2285};22862287static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2288{2289 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2290 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2291 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2292 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2293 to->sd_dev =htonl(from->sd_dev);2294 to->sd_ino =htonl(from->sd_ino);2295 to->sd_uid =htonl(from->sd_uid);2296 to->sd_gid =htonl(from->sd_gid);2297 to->sd_size =htonl(from->sd_size);2298}22992300static voidwrite_one_dir(struct untracked_cache_dir *untracked,2301struct write_data *wd)2302{2303struct stat_data stat_data;2304struct strbuf *out = &wd->out;2305unsigned char intbuf[16];2306unsigned int intlen, value;2307int i = wd->index++;23082309/*2310 * untracked_nr should be reset whenever valid is clear, but2311 * for safety..2312 */2313if(!untracked->valid) {2314 untracked->untracked_nr =0;2315 untracked->check_only =0;2316}23172318if(untracked->check_only)2319ewah_set(wd->check_only, i);2320if(untracked->valid) {2321ewah_set(wd->valid, i);2322stat_data_to_disk(&stat_data, &untracked->stat_data);2323strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2324}2325if(!is_null_sha1(untracked->exclude_sha1)) {2326ewah_set(wd->sha1_valid, i);2327strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2328}23292330 intlen =encode_varint(untracked->untracked_nr, intbuf);2331strbuf_add(out, intbuf, intlen);23322333/* skip non-recurse directories */2334for(i =0, value =0; i < untracked->dirs_nr; i++)2335if(untracked->dirs[i]->recurse)2336 value++;2337 intlen =encode_varint(value, intbuf);2338strbuf_add(out, intbuf, intlen);23392340strbuf_add(out, untracked->name,strlen(untracked->name) +1);23412342for(i =0; i < untracked->untracked_nr; i++)2343strbuf_add(out, untracked->untracked[i],2344strlen(untracked->untracked[i]) +1);23452346for(i =0; i < untracked->dirs_nr; i++)2347if(untracked->dirs[i]->recurse)2348write_one_dir(untracked->dirs[i], wd);2349}23502351voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2352{2353struct ondisk_untracked_cache *ouc;2354struct write_data wd;2355unsigned char varbuf[16];2356int varint_len;2357size_t len =strlen(untracked->exclude_per_dir);23582359FLEX_ALLOC_MEM(ouc, exclude_per_dir, untracked->exclude_per_dir, len);2360stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2361stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2362hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2363hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2364 ouc->dir_flags =htonl(untracked->dir_flags);23652366 varint_len =encode_varint(untracked->ident.len, varbuf);2367strbuf_add(out, varbuf, varint_len);2368strbuf_add(out, untracked->ident.buf, untracked->ident.len);23692370strbuf_add(out, ouc,ouc_size(len));2371free(ouc);2372 ouc = NULL;23732374if(!untracked->root) {2375 varint_len =encode_varint(0, varbuf);2376strbuf_add(out, varbuf, varint_len);2377return;2378}23792380 wd.index =0;2381 wd.check_only =ewah_new();2382 wd.valid =ewah_new();2383 wd.sha1_valid =ewah_new();2384strbuf_init(&wd.out,1024);2385strbuf_init(&wd.sb_stat,1024);2386strbuf_init(&wd.sb_sha1,1024);2387write_one_dir(untracked->root, &wd);23882389 varint_len =encode_varint(wd.index, varbuf);2390strbuf_add(out, varbuf, varint_len);2391strbuf_addbuf(out, &wd.out);2392ewah_serialize_strbuf(wd.valid, out);2393ewah_serialize_strbuf(wd.check_only, out);2394ewah_serialize_strbuf(wd.sha1_valid, out);2395strbuf_addbuf(out, &wd.sb_stat);2396strbuf_addbuf(out, &wd.sb_sha1);2397strbuf_addch(out,'\0');/* safe guard for string lists */23982399ewah_free(wd.valid);2400ewah_free(wd.check_only);2401ewah_free(wd.sha1_valid);2402strbuf_release(&wd.out);2403strbuf_release(&wd.sb_stat);2404strbuf_release(&wd.sb_sha1);2405}24062407static voidfree_untracked(struct untracked_cache_dir *ucd)2408{2409int i;2410if(!ucd)2411return;2412for(i =0; i < ucd->dirs_nr; i++)2413free_untracked(ucd->dirs[i]);2414for(i =0; i < ucd->untracked_nr; i++)2415free(ucd->untracked[i]);2416free(ucd->untracked);2417free(ucd->dirs);2418free(ucd);2419}24202421voidfree_untracked_cache(struct untracked_cache *uc)2422{2423if(uc)2424free_untracked(uc->root);2425free(uc);2426}24272428struct read_data {2429int index;2430struct untracked_cache_dir **ucd;2431struct ewah_bitmap *check_only;2432struct ewah_bitmap *valid;2433struct ewah_bitmap *sha1_valid;2434const unsigned char*data;2435const unsigned char*end;2436};24372438static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2439{2440 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2441 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2442 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2443 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2444 to->sd_dev =get_be32(&from->sd_dev);2445 to->sd_ino =get_be32(&from->sd_ino);2446 to->sd_uid =get_be32(&from->sd_uid);2447 to->sd_gid =get_be32(&from->sd_gid);2448 to->sd_size =get_be32(&from->sd_size);2449}24502451static intread_one_dir(struct untracked_cache_dir **untracked_,2452struct read_data *rd)2453{2454struct untracked_cache_dir ud, *untracked;2455const unsigned char*next, *data = rd->data, *end = rd->end;2456unsigned int value;2457int i, len;24582459memset(&ud,0,sizeof(ud));24602461 next = data;2462 value =decode_varint(&next);2463if(next > end)2464return-1;2465 ud.recurse =1;2466 ud.untracked_alloc = value;2467 ud.untracked_nr = value;2468if(ud.untracked_nr)2469ALLOC_ARRAY(ud.untracked, ud.untracked_nr);2470 data = next;24712472 next = data;2473 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2474if(next > end)2475return-1;2476ALLOC_ARRAY(ud.dirs, ud.dirs_nr);2477 data = next;24782479 len =strlen((const char*)data);2480 next = data + len +1;2481if(next > rd->end)2482return-1;2483*untracked_ = untracked =xmalloc(st_add(sizeof(*untracked), len));2484memcpy(untracked, &ud,sizeof(ud));2485memcpy(untracked->name, data, len +1);2486 data = next;24872488for(i =0; i < untracked->untracked_nr; i++) {2489 len =strlen((const char*)data);2490 next = data + len +1;2491if(next > rd->end)2492return-1;2493 untracked->untracked[i] =xstrdup((const char*)data);2494 data = next;2495}24962497 rd->ucd[rd->index++] = untracked;2498 rd->data = data;24992500for(i =0; i < untracked->dirs_nr; i++) {2501 len =read_one_dir(untracked->dirs + i, rd);2502if(len <0)2503return-1;2504}2505return0;2506}25072508static voidset_check_only(size_t pos,void*cb)2509{2510struct read_data *rd = cb;2511struct untracked_cache_dir *ud = rd->ucd[pos];2512 ud->check_only =1;2513}25142515static voidread_stat(size_t pos,void*cb)2516{2517struct read_data *rd = cb;2518struct untracked_cache_dir *ud = rd->ucd[pos];2519if(rd->data +sizeof(struct stat_data) > rd->end) {2520 rd->data = rd->end +1;2521return;2522}2523stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2524 rd->data +=sizeof(struct stat_data);2525 ud->valid =1;2526}25272528static voidread_sha1(size_t pos,void*cb)2529{2530struct read_data *rd = cb;2531struct untracked_cache_dir *ud = rd->ucd[pos];2532if(rd->data +20> rd->end) {2533 rd->data = rd->end +1;2534return;2535}2536hashcpy(ud->exclude_sha1, rd->data);2537 rd->data +=20;2538}25392540static voidload_sha1_stat(struct sha1_stat *sha1_stat,2541const struct stat_data *stat,2542const unsigned char*sha1)2543{2544stat_data_from_disk(&sha1_stat->stat, stat);2545hashcpy(sha1_stat->sha1, sha1);2546 sha1_stat->valid =1;2547}25482549struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2550{2551const struct ondisk_untracked_cache *ouc;2552struct untracked_cache *uc;2553struct read_data rd;2554const unsigned char*next = data, *end = (const unsigned char*)data + sz;2555const char*ident;2556int ident_len, len;25572558if(sz <=1|| end[-1] !='\0')2559return NULL;2560 end--;25612562 ident_len =decode_varint(&next);2563if(next + ident_len > end)2564return NULL;2565 ident = (const char*)next;2566 next += ident_len;25672568 ouc = (const struct ondisk_untracked_cache *)next;2569if(next +ouc_size(0) > end)2570return NULL;25712572 uc =xcalloc(1,sizeof(*uc));2573strbuf_init(&uc->ident, ident_len);2574strbuf_add(&uc->ident, ident, ident_len);2575load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2576 ouc->info_exclude_sha1);2577load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2578 ouc->excludes_file_sha1);2579 uc->dir_flags =get_be32(&ouc->dir_flags);2580 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2581/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2582 next +=ouc_size(strlen(ouc->exclude_per_dir));2583if(next >= end)2584goto done2;25852586 len =decode_varint(&next);2587if(next > end || len ==0)2588goto done2;25892590 rd.valid =ewah_new();2591 rd.check_only =ewah_new();2592 rd.sha1_valid =ewah_new();2593 rd.data = next;2594 rd.end = end;2595 rd.index =0;2596ALLOC_ARRAY(rd.ucd, len);25972598if(read_one_dir(&uc->root, &rd) || rd.index != len)2599goto done;26002601 next = rd.data;2602 len =ewah_read_mmap(rd.valid, next, end - next);2603if(len <0)2604goto done;26052606 next += len;2607 len =ewah_read_mmap(rd.check_only, next, end - next);2608if(len <0)2609goto done;26102611 next += len;2612 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2613if(len <0)2614goto done;26152616ewah_each_bit(rd.check_only, set_check_only, &rd);2617 rd.data = next + len;2618ewah_each_bit(rd.valid, read_stat, &rd);2619ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2620 next = rd.data;26212622done:2623free(rd.ucd);2624ewah_free(rd.valid);2625ewah_free(rd.check_only);2626ewah_free(rd.sha1_valid);2627done2:2628if(next != end) {2629free_untracked_cache(uc);2630 uc = NULL;2631}2632return uc;2633}26342635static voidinvalidate_one_directory(struct untracked_cache *uc,2636struct untracked_cache_dir *ucd)2637{2638 uc->dir_invalidated++;2639 ucd->valid =0;2640 ucd->untracked_nr =0;2641}26422643/*2644 * Normally when an entry is added or removed from a directory,2645 * invalidating that directory is enough. No need to touch its2646 * ancestors. When a directory is shown as "foo/bar/" in git-status2647 * however, deleting or adding an entry may have cascading effect.2648 *2649 * Say the "foo/bar/file" has become untracked, we need to tell the2650 * untracked_cache_dir of "foo" that "bar/" is not an untracked2651 * directory any more (because "bar" is managed by foo as an untracked2652 * "file").2653 *2654 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2655 * was the last untracked entry in the entire "foo", we should show2656 * "foo/" instead. Which means we have to invalidate past "bar" up to2657 * "foo".2658 *2659 * This function traverses all directories from root to leaf. If there2660 * is a chance of one of the above cases happening, we invalidate back2661 * to root. Otherwise we just invalidate the leaf. There may be a more2662 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2663 * detect these cases and avoid unnecessary invalidation, for example,2664 * checking for the untracked entry named "bar/" in "foo", but for now2665 * stick to something safe and simple.2666 */2667static intinvalidate_one_component(struct untracked_cache *uc,2668struct untracked_cache_dir *dir,2669const char*path,int len)2670{2671const char*rest =strchr(path,'/');26722673if(rest) {2674int component_len = rest - path;2675struct untracked_cache_dir *d =2676lookup_untracked(uc, dir, path, component_len);2677int ret =2678invalidate_one_component(uc, d, rest +1,2679 len - (component_len +1));2680if(ret)2681invalidate_one_directory(uc, dir);2682return ret;2683}26842685invalidate_one_directory(uc, dir);2686return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2687}26882689voiduntracked_cache_invalidate_path(struct index_state *istate,2690const char*path)2691{2692if(!istate->untracked || !istate->untracked->root)2693return;2694invalidate_one_component(istate->untracked, istate->untracked->root,2695 path,strlen(path));2696}26972698voiduntracked_cache_remove_from_index(struct index_state *istate,2699const char*path)2700{2701untracked_cache_invalidate_path(istate, path);2702}27032704voiduntracked_cache_add_to_index(struct index_state *istate,2705const char*path)2706{2707untracked_cache_invalidate_path(istate, path);2708}