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#define NO_THE_INDEX_COMPATIBILITY_MACROS 11#include"cache.h" 12#include"config.h" 13#include"dir.h" 14#include"attr.h" 15#include"refs.h" 16#include"wildmatch.h" 17#include"pathspec.h" 18#include"utf8.h" 19#include"varint.h" 20#include"ewah/ewok.h" 21#include"fsmonitor.h" 22 23/* 24 * Tells read_directory_recursive how a file or directory should be treated. 25 * Values are ordered by significance, e.g. if a directory contains both 26 * excluded and untracked files, it is listed as untracked because 27 * path_untracked > path_excluded. 28 */ 29enum path_treatment { 30 path_none =0, 31 path_recurse, 32 path_excluded, 33 path_untracked 34}; 35 36/* 37 * Support data structure for our opendir/readdir/closedir wrappers 38 */ 39struct cached_dir { 40DIR*fdir; 41struct untracked_cache_dir *untracked; 42int nr_files; 43int nr_dirs; 44 45struct dirent *de; 46const char*file; 47struct untracked_cache_dir *ucd; 48}; 49 50static enum path_treatment read_directory_recursive(struct dir_struct *dir, 51struct index_state *istate,const char*path,int len, 52struct untracked_cache_dir *untracked, 53int check_only,int stop_at_first_file,const struct pathspec *pathspec); 54static intget_dtype(struct dirent *de,struct index_state *istate, 55const char*path,int len); 56 57intcount_slashes(const char*s) 58{ 59int cnt =0; 60while(*s) 61if(*s++ =='/') 62 cnt++; 63return cnt; 64} 65 66intfspathcmp(const char*a,const char*b) 67{ 68return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 69} 70 71intfspathncmp(const char*a,const char*b,size_t count) 72{ 73return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 74} 75 76intgit_fnmatch(const struct pathspec_item *item, 77const char*pattern,const char*string, 78int prefix) 79{ 80if(prefix >0) { 81if(ps_strncmp(item, pattern, string, prefix)) 82return WM_NOMATCH; 83 pattern += prefix; 84 string += prefix; 85} 86if(item->flags & PATHSPEC_ONESTAR) { 87int pattern_len =strlen(++pattern); 88int string_len =strlen(string); 89return string_len < pattern_len || 90ps_strcmp(item, pattern, 91 string + string_len - pattern_len); 92} 93if(item->magic & PATHSPEC_GLOB) 94returnwildmatch(pattern, string, 95 WM_PATHNAME | 96(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0)); 97else 98/* wildmatch has not learned no FNM_PATHNAME mode yet */ 99returnwildmatch(pattern, string, 100 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0); 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); 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 PATHSPEC_ATTR); 152 153for(n =0; n < pathspec->nr; n++) { 154size_t i =0, len =0, item_len; 155if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 156continue; 157if(pathspec->items[n].magic & PATHSPEC_ICASE) 158 item_len = pathspec->items[n].prefix; 159else 160 item_len = pathspec->items[n].nowildcard_len; 161while(i < item_len && (n ==0|| i < max)) { 162char c = pathspec->items[n].match[i]; 163if(c != pathspec->items[0].match[i]) 164break; 165if(c =='/') 166 len = i +1; 167 i++; 168} 169if(n ==0|| len < max) { 170 max = len; 171if(!max) 172break; 173} 174} 175return max; 176} 177 178/* 179 * Returns a copy of the longest leading path common among all 180 * pathspecs. 181 */ 182char*common_prefix(const struct pathspec *pathspec) 183{ 184unsigned long len =common_prefix_len(pathspec); 185 186return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 187} 188 189intfill_directory(struct dir_struct *dir, 190struct index_state *istate, 191const struct pathspec *pathspec) 192{ 193const char*prefix; 194size_t prefix_len; 195 196/* 197 * Calculate common prefix for the pathspec, and 198 * use that to optimize the directory walk 199 */ 200 prefix_len =common_prefix_len(pathspec); 201 prefix = prefix_len ? pathspec->items[0].match :""; 202 203/* Read the directory and prune it */ 204read_directory(dir, istate, prefix, prefix_len, pathspec); 205 206return prefix_len; 207} 208 209intwithin_depth(const char*name,int namelen, 210int depth,int max_depth) 211{ 212const char*cp = name, *cpe = name + namelen; 213 214while(cp < cpe) { 215if(*cp++ !='/') 216continue; 217 depth++; 218if(depth > max_depth) 219return0; 220} 221return1; 222} 223 224/* 225 * Read the contents of the blob with the given OID into a buffer. 226 * Append a trailing LF to the end if the last line doesn't have one. 227 * 228 * Returns: 229 * -1 when the OID is invalid or unknown or does not refer to a blob. 230 * 0 when the blob is empty. 231 * 1 along with { data, size } of the (possibly augmented) buffer 232 * when successful. 233 * 234 * Optionally updates the given oid_stat with the given OID (when valid). 235 */ 236static intdo_read_blob(const struct object_id *oid,struct oid_stat *oid_stat, 237size_t*size_out,char**data_out) 238{ 239enum object_type type; 240unsigned long sz; 241char*data; 242 243*size_out =0; 244*data_out = NULL; 245 246 data =read_sha1_file(oid->hash, &type, &sz); 247if(!data || type != OBJ_BLOB) { 248free(data); 249return-1; 250} 251 252if(oid_stat) { 253memset(&oid_stat->stat,0,sizeof(oid_stat->stat)); 254oidcpy(&oid_stat->oid, oid); 255} 256 257if(sz ==0) { 258free(data); 259return0; 260} 261 262if(data[sz -1] !='\n') { 263 data =xrealloc(data,st_add(sz,1)); 264 data[sz++] ='\n'; 265} 266 267*size_out =xsize_t(sz); 268*data_out = data; 269 270return1; 271} 272 273#define DO_MATCH_EXCLUDE (1<<0) 274#define DO_MATCH_DIRECTORY (1<<1) 275#define DO_MATCH_SUBMODULE (1<<2) 276 277static intmatch_attrs(const char*name,int namelen, 278const struct pathspec_item *item) 279{ 280int i; 281 282git_check_attr(name, item->attr_check); 283for(i =0; i < item->attr_match_nr; i++) { 284const char*value; 285int matched; 286enum attr_match_mode match_mode; 287 288 value = item->attr_check->items[i].value; 289 match_mode = item->attr_match[i].match_mode; 290 291if(ATTR_TRUE(value)) 292 matched = (match_mode == MATCH_SET); 293else if(ATTR_FALSE(value)) 294 matched = (match_mode == MATCH_UNSET); 295else if(ATTR_UNSET(value)) 296 matched = (match_mode == MATCH_UNSPECIFIED); 297else 298 matched = (match_mode == MATCH_VALUE && 299!strcmp(item->attr_match[i].value, value)); 300if(!matched) 301return0; 302} 303 304return1; 305} 306 307/* 308 * Does 'match' match the given name? 309 * A match is found if 310 * 311 * (1) the 'match' string is leading directory of 'name', or 312 * (2) the 'match' string is a wildcard and matches 'name', or 313 * (3) the 'match' string is exactly the same as 'name'. 314 * 315 * and the return value tells which case it was. 316 * 317 * It returns 0 when there is no match. 318 */ 319static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 320const char*name,int namelen,unsigned flags) 321{ 322/* name/namelen has prefix cut off by caller */ 323const char*match = item->match + prefix; 324int matchlen = item->len - prefix; 325 326/* 327 * The normal call pattern is: 328 * 1. prefix = common_prefix_len(ps); 329 * 2. prune something, or fill_directory 330 * 3. match_pathspec() 331 * 332 * 'prefix' at #1 may be shorter than the command's prefix and 333 * it's ok for #2 to match extra files. Those extras will be 334 * trimmed at #3. 335 * 336 * Suppose the pathspec is 'foo' and '../bar' running from 337 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 338 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 339 * user does not want XYZ/foo, only the "foo" part should be 340 * case-insensitive. We need to filter out XYZ/foo here. In 341 * other words, we do not trust the caller on comparing the 342 * prefix part when :(icase) is involved. We do exact 343 * comparison ourselves. 344 * 345 * Normally the caller (common_prefix_len() in fact) does 346 * _exact_ matching on name[-prefix+1..-1] and we do not need 347 * to check that part. Be defensive and check it anyway, in 348 * case common_prefix_len is changed, or a new caller is 349 * introduced that does not use common_prefix_len. 350 * 351 * If the penalty turns out too high when prefix is really 352 * long, maybe change it to 353 * strncmp(match, name, item->prefix - prefix) 354 */ 355if(item->prefix && (item->magic & PATHSPEC_ICASE) && 356strncmp(item->match, name - prefix, item->prefix)) 357return0; 358 359if(item->attr_match_nr && !match_attrs(name, namelen, item)) 360return0; 361 362/* If the match was just the prefix, we matched */ 363if(!*match) 364return MATCHED_RECURSIVELY; 365 366if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 367if(matchlen == namelen) 368return MATCHED_EXACTLY; 369 370if(match[matchlen-1] =='/'|| name[matchlen] =='/') 371return MATCHED_RECURSIVELY; 372}else if((flags & DO_MATCH_DIRECTORY) && 373 match[matchlen -1] =='/'&& 374 namelen == matchlen -1&& 375!ps_strncmp(item, match, name, namelen)) 376return MATCHED_EXACTLY; 377 378if(item->nowildcard_len < item->len && 379!git_fnmatch(item, match, name, 380 item->nowildcard_len - prefix)) 381return MATCHED_FNMATCH; 382 383/* Perform checks to see if "name" is a super set of the pathspec */ 384if(flags & DO_MATCH_SUBMODULE) { 385/* name is a literal prefix of the pathspec */ 386if((namelen < matchlen) && 387(match[namelen] =='/') && 388!ps_strncmp(item, match, name, namelen)) 389return MATCHED_RECURSIVELY; 390 391/* name" doesn't match up to the first wild character */ 392if(item->nowildcard_len < item->len && 393ps_strncmp(item, match, name, 394 item->nowildcard_len - prefix)) 395return0; 396 397/* 398 * Here is where we would perform a wildmatch to check if 399 * "name" can be matched as a directory (or a prefix) against 400 * the pathspec. Since wildmatch doesn't have this capability 401 * at the present we have to punt and say that it is a match, 402 * potentially returning a false positive 403 * The submodules themselves will be able to perform more 404 * accurate matching to determine if the pathspec matches. 405 */ 406return MATCHED_RECURSIVELY; 407} 408 409return0; 410} 411 412/* 413 * Given a name and a list of pathspecs, returns the nature of the 414 * closest (i.e. most specific) match of the name to any of the 415 * pathspecs. 416 * 417 * The caller typically calls this multiple times with the same 418 * pathspec and seen[] array but with different name/namelen 419 * (e.g. entries from the index) and is interested in seeing if and 420 * how each pathspec matches all the names it calls this function 421 * with. A mark is left in the seen[] array for each pathspec element 422 * indicating the closest type of match that element achieved, so if 423 * seen[n] remains zero after multiple invocations, that means the nth 424 * pathspec did not match any names, which could indicate that the 425 * user mistyped the nth pathspec. 426 */ 427static intdo_match_pathspec(const struct pathspec *ps, 428const char*name,int namelen, 429int prefix,char*seen, 430unsigned flags) 431{ 432int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 433 434GUARD_PATHSPEC(ps, 435 PATHSPEC_FROMTOP | 436 PATHSPEC_MAXDEPTH | 437 PATHSPEC_LITERAL | 438 PATHSPEC_GLOB | 439 PATHSPEC_ICASE | 440 PATHSPEC_EXCLUDE | 441 PATHSPEC_ATTR); 442 443if(!ps->nr) { 444if(!ps->recursive || 445!(ps->magic & PATHSPEC_MAXDEPTH) || 446 ps->max_depth == -1) 447return MATCHED_RECURSIVELY; 448 449if(within_depth(name, namelen,0, ps->max_depth)) 450return MATCHED_EXACTLY; 451else 452return0; 453} 454 455 name += prefix; 456 namelen -= prefix; 457 458for(i = ps->nr -1; i >=0; i--) { 459int how; 460 461if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 462( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 463continue; 464 465if(seen && seen[i] == MATCHED_EXACTLY) 466continue; 467/* 468 * Make exclude patterns optional and never report 469 * "pathspec ':(exclude)foo' matches no files" 470 */ 471if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 472 seen[i] = MATCHED_FNMATCH; 473 how =match_pathspec_item(ps->items+i, prefix, name, 474 namelen, flags); 475if(ps->recursive && 476(ps->magic & PATHSPEC_MAXDEPTH) && 477 ps->max_depth != -1&& 478 how && how != MATCHED_FNMATCH) { 479int len = ps->items[i].len; 480if(name[len] =='/') 481 len++; 482if(within_depth(name+len, namelen-len,0, ps->max_depth)) 483 how = MATCHED_EXACTLY; 484else 485 how =0; 486} 487if(how) { 488if(retval < how) 489 retval = how; 490if(seen && seen[i] < how) 491 seen[i] = how; 492} 493} 494return retval; 495} 496 497intmatch_pathspec(const struct pathspec *ps, 498const char*name,int namelen, 499int prefix,char*seen,int is_dir) 500{ 501int positive, negative; 502unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 503 positive =do_match_pathspec(ps, name, namelen, 504 prefix, seen, flags); 505if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 506return positive; 507 negative =do_match_pathspec(ps, name, namelen, 508 prefix, seen, 509 flags | DO_MATCH_EXCLUDE); 510return negative ?0: positive; 511} 512 513/** 514 * Check if a submodule is a superset of the pathspec 515 */ 516intsubmodule_path_match(const struct pathspec *ps, 517const char*submodule_name, 518char*seen) 519{ 520int matched =do_match_pathspec(ps, submodule_name, 521strlen(submodule_name), 5220, seen, 523 DO_MATCH_DIRECTORY | 524 DO_MATCH_SUBMODULE); 525return matched; 526} 527 528intreport_path_error(const char*ps_matched, 529const struct pathspec *pathspec, 530const char*prefix) 531{ 532/* 533 * Make sure all pathspec matched; otherwise it is an error. 534 */ 535int num, errors =0; 536for(num =0; num < pathspec->nr; num++) { 537int other, found_dup; 538 539if(ps_matched[num]) 540continue; 541/* 542 * The caller might have fed identical pathspec 543 * twice. Do not barf on such a mistake. 544 * FIXME: parse_pathspec should have eliminated 545 * duplicate pathspec. 546 */ 547for(found_dup = other =0; 548!found_dup && other < pathspec->nr; 549 other++) { 550if(other == num || !ps_matched[other]) 551continue; 552if(!strcmp(pathspec->items[other].original, 553 pathspec->items[num].original)) 554/* 555 * Ok, we have a match already. 556 */ 557 found_dup =1; 558} 559if(found_dup) 560continue; 561 562error("pathspec '%s' did not match any file(s) known to git.", 563 pathspec->items[num].original); 564 errors++; 565} 566return errors; 567} 568 569/* 570 * Return the length of the "simple" part of a path match limiter. 571 */ 572intsimple_length(const char*match) 573{ 574int len = -1; 575 576for(;;) { 577unsigned char c = *match++; 578 len++; 579if(c =='\0'||is_glob_special(c)) 580return len; 581} 582} 583 584intno_wildcard(const char*string) 585{ 586return string[simple_length(string)] =='\0'; 587} 588 589voidparse_exclude_pattern(const char**pattern, 590int*patternlen, 591unsigned*flags, 592int*nowildcardlen) 593{ 594const char*p = *pattern; 595size_t i, len; 596 597*flags =0; 598if(*p =='!') { 599*flags |= EXC_FLAG_NEGATIVE; 600 p++; 601} 602 len =strlen(p); 603if(len && p[len -1] =='/') { 604 len--; 605*flags |= EXC_FLAG_MUSTBEDIR; 606} 607for(i =0; i < len; i++) { 608if(p[i] =='/') 609break; 610} 611if(i == len) 612*flags |= EXC_FLAG_NODIR; 613*nowildcardlen =simple_length(p); 614/* 615 * we should have excluded the trailing slash from 'p' too, 616 * but that's one more allocation. Instead just make sure 617 * nowildcardlen does not exceed real patternlen 618 */ 619if(*nowildcardlen > len) 620*nowildcardlen = len; 621if(*p =='*'&&no_wildcard(p +1)) 622*flags |= EXC_FLAG_ENDSWITH; 623*pattern = p; 624*patternlen = len; 625} 626 627voidadd_exclude(const char*string,const char*base, 628int baselen,struct exclude_list *el,int srcpos) 629{ 630struct exclude *x; 631int patternlen; 632unsigned flags; 633int nowildcardlen; 634 635parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 636if(flags & EXC_FLAG_MUSTBEDIR) { 637FLEXPTR_ALLOC_MEM(x, pattern, string, patternlen); 638}else{ 639 x =xmalloc(sizeof(*x)); 640 x->pattern = string; 641} 642 x->patternlen = patternlen; 643 x->nowildcardlen = nowildcardlen; 644 x->base = base; 645 x->baselen = baselen; 646 x->flags = flags; 647 x->srcpos = srcpos; 648ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 649 el->excludes[el->nr++] = x; 650 x->el = el; 651} 652 653static intread_skip_worktree_file_from_index(const struct index_state *istate, 654const char*path, 655size_t*size_out,char**data_out, 656struct oid_stat *oid_stat) 657{ 658int pos, len; 659 660 len =strlen(path); 661 pos =index_name_pos(istate, path, len); 662if(pos <0) 663return-1; 664if(!ce_skip_worktree(istate->cache[pos])) 665return-1; 666 667returndo_read_blob(&istate->cache[pos]->oid, oid_stat, size_out, data_out); 668} 669 670/* 671 * Frees memory within el which was allocated for exclude patterns and 672 * the file buffer. Does not free el itself. 673 */ 674voidclear_exclude_list(struct exclude_list *el) 675{ 676int i; 677 678for(i =0; i < el->nr; i++) 679free(el->excludes[i]); 680free(el->excludes); 681free(el->filebuf); 682 683memset(el,0,sizeof(*el)); 684} 685 686static voidtrim_trailing_spaces(char*buf) 687{ 688char*p, *last_space = NULL; 689 690for(p = buf; *p; p++) 691switch(*p) { 692case' ': 693if(!last_space) 694 last_space = p; 695break; 696case'\\': 697 p++; 698if(!*p) 699return; 700/* fallthrough */ 701default: 702 last_space = NULL; 703} 704 705if(last_space) 706*last_space ='\0'; 707} 708 709/* 710 * Given a subdirectory name and "dir" of the current directory, 711 * search the subdir in "dir" and return it, or create a new one if it 712 * does not exist in "dir". 713 * 714 * If "name" has the trailing slash, it'll be excluded in the search. 715 */ 716static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 717struct untracked_cache_dir *dir, 718const char*name,int len) 719{ 720int first, last; 721struct untracked_cache_dir *d; 722if(!dir) 723return NULL; 724if(len && name[len -1] =='/') 725 len--; 726 first =0; 727 last = dir->dirs_nr; 728while(last > first) { 729int cmp, next = (last + first) >>1; 730 d = dir->dirs[next]; 731 cmp =strncmp(name, d->name, len); 732if(!cmp &&strlen(d->name) > len) 733 cmp = -1; 734if(!cmp) 735return d; 736if(cmp <0) { 737 last = next; 738continue; 739} 740 first = next+1; 741} 742 743 uc->dir_created++; 744FLEX_ALLOC_MEM(d, name, name, len); 745 746ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 747MOVE_ARRAY(dir->dirs + first +1, dir->dirs + first, 748 dir->dirs_nr - first); 749 dir->dirs_nr++; 750 dir->dirs[first] = d; 751return d; 752} 753 754static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 755{ 756int i; 757 dir->valid =0; 758 dir->untracked_nr =0; 759for(i =0; i < dir->dirs_nr; i++) 760do_invalidate_gitignore(dir->dirs[i]); 761} 762 763static voidinvalidate_gitignore(struct untracked_cache *uc, 764struct untracked_cache_dir *dir) 765{ 766 uc->gitignore_invalidated++; 767do_invalidate_gitignore(dir); 768} 769 770static voidinvalidate_directory(struct untracked_cache *uc, 771struct untracked_cache_dir *dir) 772{ 773int i; 774 775/* 776 * Invalidation increment here is just roughly correct. If 777 * untracked_nr or any of dirs[].recurse is non-zero, we 778 * should increment dir_invalidated too. But that's more 779 * expensive to do. 780 */ 781if(dir->valid) 782 uc->dir_invalidated++; 783 784 dir->valid =0; 785 dir->untracked_nr =0; 786for(i =0; i < dir->dirs_nr; i++) 787 dir->dirs[i]->recurse =0; 788} 789 790static intadd_excludes_from_buffer(char*buf,size_t size, 791const char*base,int baselen, 792struct exclude_list *el); 793 794/* 795 * Given a file with name "fname", read it (either from disk, or from 796 * an index if 'istate' is non-null), parse it and store the 797 * exclude rules in "el". 798 * 799 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 800 * stat data from disk (only valid if add_excludes returns zero). If 801 * ss_valid is non-zero, "ss" must contain good value as input. 802 */ 803static intadd_excludes(const char*fname,const char*base,int baselen, 804struct exclude_list *el,struct index_state *istate, 805struct oid_stat *oid_stat) 806{ 807struct stat st; 808int r; 809int fd; 810size_t size =0; 811char*buf; 812 813 fd =open(fname, O_RDONLY); 814if(fd <0||fstat(fd, &st) <0) { 815if(fd <0) 816warn_on_fopen_errors(fname); 817else 818close(fd); 819if(!istate) 820return-1; 821 r =read_skip_worktree_file_from_index(istate, fname, 822&size, &buf, 823 oid_stat); 824if(r !=1) 825return r; 826}else{ 827 size =xsize_t(st.st_size); 828if(size ==0) { 829if(oid_stat) { 830fill_stat_data(&oid_stat->stat, &st); 831oidcpy(&oid_stat->oid, &empty_blob_oid); 832 oid_stat->valid =1; 833} 834close(fd); 835return0; 836} 837 buf =xmallocz(size); 838if(read_in_full(fd, buf, size) != size) { 839free(buf); 840close(fd); 841return-1; 842} 843 buf[size++] ='\n'; 844close(fd); 845if(oid_stat) { 846int pos; 847if(oid_stat->valid && 848!match_stat_data_racy(istate, &oid_stat->stat, &st)) 849;/* no content change, ss->sha1 still good */ 850else if(istate && 851(pos =index_name_pos(istate, fname,strlen(fname))) >=0&& 852!ce_stage(istate->cache[pos]) && 853ce_uptodate(istate->cache[pos]) && 854!would_convert_to_git(istate, fname)) 855oidcpy(&oid_stat->oid, 856&istate->cache[pos]->oid); 857else 858hash_object_file(buf, size,"blob", 859&oid_stat->oid); 860fill_stat_data(&oid_stat->stat, &st); 861 oid_stat->valid =1; 862} 863} 864 865add_excludes_from_buffer(buf, size, base, baselen, el); 866return0; 867} 868 869static intadd_excludes_from_buffer(char*buf,size_t size, 870const char*base,int baselen, 871struct exclude_list *el) 872{ 873int i, lineno =1; 874char*entry; 875 876 el->filebuf = buf; 877 878if(skip_utf8_bom(&buf, size)) 879 size -= buf - el->filebuf; 880 881 entry = buf; 882 883for(i =0; i < size; i++) { 884if(buf[i] =='\n') { 885if(entry != buf + i && entry[0] !='#') { 886 buf[i - (i && buf[i-1] =='\r')] =0; 887trim_trailing_spaces(entry); 888add_exclude(entry, base, baselen, el, lineno); 889} 890 lineno++; 891 entry = buf + i +1; 892} 893} 894return0; 895} 896 897intadd_excludes_from_file_to_list(const char*fname,const char*base, 898int baselen,struct exclude_list *el, 899struct index_state *istate) 900{ 901returnadd_excludes(fname, base, baselen, el, istate, NULL); 902} 903 904intadd_excludes_from_blob_to_list( 905struct object_id *oid, 906const char*base,int baselen, 907struct exclude_list *el) 908{ 909char*buf; 910size_t size; 911int r; 912 913 r =do_read_blob(oid, NULL, &size, &buf); 914if(r !=1) 915return r; 916 917add_excludes_from_buffer(buf, size, base, baselen, el); 918return0; 919} 920 921struct exclude_list *add_exclude_list(struct dir_struct *dir, 922int group_type,const char*src) 923{ 924struct exclude_list *el; 925struct exclude_list_group *group; 926 927 group = &dir->exclude_list_group[group_type]; 928ALLOC_GROW(group->el, group->nr +1, group->alloc); 929 el = &group->el[group->nr++]; 930memset(el,0,sizeof(*el)); 931 el->src = src; 932return el; 933} 934 935/* 936 * Used to set up core.excludesfile and .git/info/exclude lists. 937 */ 938static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 939struct oid_stat *oid_stat) 940{ 941struct exclude_list *el; 942/* 943 * catch setup_standard_excludes() that's called before 944 * dir->untracked is assigned. That function behaves 945 * differently when dir->untracked is non-NULL. 946 */ 947if(!dir->untracked) 948 dir->unmanaged_exclude_files++; 949 el =add_exclude_list(dir, EXC_FILE, fname); 950if(add_excludes(fname,"",0, el, NULL, oid_stat) <0) 951die("cannot use%sas an exclude file", fname); 952} 953 954voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 955{ 956 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 957add_excludes_from_file_1(dir, fname, NULL); 958} 959 960intmatch_basename(const char*basename,int basenamelen, 961const char*pattern,int prefix,int patternlen, 962unsigned flags) 963{ 964if(prefix == patternlen) { 965if(patternlen == basenamelen && 966!fspathncmp(pattern, basename, basenamelen)) 967return1; 968}else if(flags & EXC_FLAG_ENDSWITH) { 969/* "*literal" matching against "fooliteral" */ 970if(patternlen -1<= basenamelen && 971!fspathncmp(pattern +1, 972 basename + basenamelen - (patternlen -1), 973 patternlen -1)) 974return1; 975}else{ 976if(fnmatch_icase_mem(pattern, patternlen, 977 basename, basenamelen, 9780) ==0) 979return1; 980} 981return0; 982} 983 984intmatch_pathname(const char*pathname,int pathlen, 985const char*base,int baselen, 986const char*pattern,int prefix,int patternlen, 987unsigned flags) 988{ 989const char*name; 990int namelen; 991 992/* 993 * match with FNM_PATHNAME; the pattern has base implicitly 994 * in front of it. 995 */ 996if(*pattern =='/') { 997 pattern++; 998 patternlen--; 999 prefix--;1000}10011002/*1003 * baselen does not count the trailing slash. base[] may or1004 * may not end with a trailing slash though.1005 */1006if(pathlen < baselen +1||1007(baselen && pathname[baselen] !='/') ||1008fspathncmp(pathname, base, baselen))1009return0;10101011 namelen = baselen ? pathlen - baselen -1: pathlen;1012 name = pathname + pathlen - namelen;10131014if(prefix) {1015/*1016 * if the non-wildcard part is longer than the1017 * remaining pathname, surely it cannot match.1018 */1019if(prefix > namelen)1020return0;10211022if(fspathncmp(pattern, name, prefix))1023return0;1024 pattern += prefix;1025 patternlen -= prefix;1026 name += prefix;1027 namelen -= prefix;10281029/*1030 * If the whole pattern did not have a wildcard,1031 * then our prefix match is all we need; we1032 * do not need to call fnmatch at all.1033 */1034if(!patternlen && !namelen)1035return1;1036}10371038returnfnmatch_icase_mem(pattern, patternlen,1039 name, namelen,1040 WM_PATHNAME) ==0;1041}10421043/*1044 * Scan the given exclude list in reverse to see whether pathname1045 * should be ignored. The first match (i.e. the last on the list), if1046 * any, determines the fate. Returns the exclude_list element which1047 * matched, or NULL for undecided.1048 */1049static struct exclude *last_exclude_matching_from_list(const char*pathname,1050int pathlen,1051const char*basename,1052int*dtype,1053struct exclude_list *el,1054struct index_state *istate)1055{1056struct exclude *exc = NULL;/* undecided */1057int i;10581059if(!el->nr)1060return NULL;/* undefined */10611062for(i = el->nr -1;0<= i; i--) {1063struct exclude *x = el->excludes[i];1064const char*exclude = x->pattern;1065int prefix = x->nowildcardlen;10661067if(x->flags & EXC_FLAG_MUSTBEDIR) {1068if(*dtype == DT_UNKNOWN)1069*dtype =get_dtype(NULL, istate, pathname, pathlen);1070if(*dtype != DT_DIR)1071continue;1072}10731074if(x->flags & EXC_FLAG_NODIR) {1075if(match_basename(basename,1076 pathlen - (basename - pathname),1077 exclude, prefix, x->patternlen,1078 x->flags)) {1079 exc = x;1080break;1081}1082continue;1083}10841085assert(x->baselen ==0|| x->base[x->baselen -1] =='/');1086if(match_pathname(pathname, pathlen,1087 x->base, x->baselen ? x->baselen -1:0,1088 exclude, prefix, x->patternlen, x->flags)) {1089 exc = x;1090break;1091}1092}1093return exc;1094}10951096/*1097 * Scan the list and let the last match determine the fate.1098 * Return 1 for exclude, 0 for include and -1 for undecided.1099 */1100intis_excluded_from_list(const char*pathname,1101int pathlen,const char*basename,int*dtype,1102struct exclude_list *el,struct index_state *istate)1103{1104struct exclude *exclude;1105 exclude =last_exclude_matching_from_list(pathname, pathlen, basename,1106 dtype, el, istate);1107if(exclude)1108return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1109return-1;/* undecided */1110}11111112static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir,1113struct index_state *istate,1114const char*pathname,int pathlen,const char*basename,1115int*dtype_p)1116{1117int i, j;1118struct exclude_list_group *group;1119struct exclude *exclude;1120for(i = EXC_CMDL; i <= EXC_FILE; i++) {1121 group = &dir->exclude_list_group[i];1122for(j = group->nr -1; j >=0; j--) {1123 exclude =last_exclude_matching_from_list(1124 pathname, pathlen, basename, dtype_p,1125&group->el[j], istate);1126if(exclude)1127return exclude;1128}1129}1130return NULL;1131}11321133/*1134 * Loads the per-directory exclude list for the substring of base1135 * which has a char length of baselen.1136 */1137static voidprep_exclude(struct dir_struct *dir,1138struct index_state *istate,1139const char*base,int baselen)1140{1141struct exclude_list_group *group;1142struct exclude_list *el;1143struct exclude_stack *stk = NULL;1144struct untracked_cache_dir *untracked;1145int current;11461147 group = &dir->exclude_list_group[EXC_DIRS];11481149/*1150 * Pop the exclude lists from the EXCL_DIRS exclude_list_group1151 * which originate from directories not in the prefix of the1152 * path being checked.1153 */1154while((stk = dir->exclude_stack) != NULL) {1155if(stk->baselen <= baselen &&1156!strncmp(dir->basebuf.buf, base, stk->baselen))1157break;1158 el = &group->el[dir->exclude_stack->exclude_ix];1159 dir->exclude_stack = stk->prev;1160 dir->exclude = NULL;1161free((char*)el->src);/* see strbuf_detach() below */1162clear_exclude_list(el);1163free(stk);1164 group->nr--;1165}11661167/* Skip traversing into sub directories if the parent is excluded */1168if(dir->exclude)1169return;11701171/*1172 * Lazy initialization. All call sites currently just1173 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1174 * them seems lots of work for little benefit.1175 */1176if(!dir->basebuf.buf)1177strbuf_init(&dir->basebuf, PATH_MAX);11781179/* Read from the parent directories and push them down. */1180 current = stk ? stk->baselen : -1;1181strbuf_setlen(&dir->basebuf, current <0?0: current);1182if(dir->untracked)1183 untracked = stk ? stk->ucd : dir->untracked->root;1184else1185 untracked = NULL;11861187while(current < baselen) {1188const char*cp;1189struct oid_stat oid_stat;11901191 stk =xcalloc(1,sizeof(*stk));1192if(current <0) {1193 cp = base;1194 current =0;1195}else{1196 cp =strchr(base + current +1,'/');1197if(!cp)1198die("oops in prep_exclude");1199 cp++;1200 untracked =1201lookup_untracked(dir->untracked, untracked,1202 base + current,1203 cp - base - current);1204}1205 stk->prev = dir->exclude_stack;1206 stk->baselen = cp - base;1207 stk->exclude_ix = group->nr;1208 stk->ucd = untracked;1209 el =add_exclude_list(dir, EXC_DIRS, NULL);1210strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1211assert(stk->baselen == dir->basebuf.len);12121213/* Abort if the directory is excluded */1214if(stk->baselen) {1215int dt = DT_DIR;1216 dir->basebuf.buf[stk->baselen -1] =0;1217 dir->exclude =last_exclude_matching_from_lists(dir,1218 istate,1219 dir->basebuf.buf, stk->baselen -1,1220 dir->basebuf.buf + current, &dt);1221 dir->basebuf.buf[stk->baselen -1] ='/';1222if(dir->exclude &&1223 dir->exclude->flags & EXC_FLAG_NEGATIVE)1224 dir->exclude = NULL;1225if(dir->exclude) {1226 dir->exclude_stack = stk;1227return;1228}1229}12301231/* Try to read per-directory file */1232oidclr(&oid_stat.oid);1233 oid_stat.valid =0;1234if(dir->exclude_per_dir &&1235/*1236 * If we know that no files have been added in1237 * this directory (i.e. valid_cached_dir() has1238 * been executed and set untracked->valid) ..1239 */1240(!untracked || !untracked->valid ||1241/*1242 * .. and .gitignore does not exist before1243 * (i.e. null exclude_sha1). Then we can skip1244 * loading .gitignore, which would result in1245 * ENOENT anyway.1246 */1247!is_null_sha1(untracked->exclude_sha1))) {1248/*1249 * dir->basebuf gets reused by the traversal, but we1250 * need fname to remain unchanged to ensure the src1251 * member of each struct exclude correctly1252 * back-references its source file. Other invocations1253 * of add_exclude_list provide stable strings, so we1254 * strbuf_detach() and free() here in the caller.1255 */1256struct strbuf sb = STRBUF_INIT;1257strbuf_addbuf(&sb, &dir->basebuf);1258strbuf_addstr(&sb, dir->exclude_per_dir);1259 el->src =strbuf_detach(&sb, NULL);1260add_excludes(el->src, el->src, stk->baselen, el, istate,1261 untracked ? &oid_stat : NULL);1262}1263/*1264 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1265 * will first be called in valid_cached_dir() then maybe many1266 * times more in last_exclude_matching(). When the cache is1267 * used, last_exclude_matching() will not be called and1268 * reading .gitignore content will be a waste.1269 *1270 * So when it's called by valid_cached_dir() and we can get1271 * .gitignore SHA-1 from the index (i.e. .gitignore is not1272 * modified on work tree), we could delay reading the1273 * .gitignore content until we absolutely need it in1274 * last_exclude_matching(). Be careful about ignore rule1275 * order, though, if you do that.1276 */1277if(untracked &&1278hashcmp(oid_stat.oid.hash, untracked->exclude_sha1)) {1279invalidate_gitignore(dir->untracked, untracked);1280hashcpy(untracked->exclude_sha1, oid_stat.oid.hash);1281}1282 dir->exclude_stack = stk;1283 current = stk->baselen;1284}1285strbuf_setlen(&dir->basebuf, baselen);1286}12871288/*1289 * Loads the exclude lists for the directory containing pathname, then1290 * scans all exclude lists to determine whether pathname is excluded.1291 * Returns the exclude_list element which matched, or NULL for1292 * undecided.1293 */1294struct exclude *last_exclude_matching(struct dir_struct *dir,1295struct index_state *istate,1296const char*pathname,1297int*dtype_p)1298{1299int pathlen =strlen(pathname);1300const char*basename =strrchr(pathname,'/');1301 basename = (basename) ? basename+1: pathname;13021303prep_exclude(dir, istate, pathname, basename-pathname);13041305if(dir->exclude)1306return dir->exclude;13071308returnlast_exclude_matching_from_lists(dir, istate, pathname, pathlen,1309 basename, dtype_p);1310}13111312/*1313 * Loads the exclude lists for the directory containing pathname, then1314 * scans all exclude lists to determine whether pathname is excluded.1315 * Returns 1 if true, otherwise 0.1316 */1317intis_excluded(struct dir_struct *dir,struct index_state *istate,1318const char*pathname,int*dtype_p)1319{1320struct exclude *exclude =1321last_exclude_matching(dir, istate, pathname, dtype_p);1322if(exclude)1323return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1324return0;1325}13261327static struct dir_entry *dir_entry_new(const char*pathname,int len)1328{1329struct dir_entry *ent;13301331FLEX_ALLOC_MEM(ent, name, pathname, len);1332 ent->len = len;1333return ent;1334}13351336static struct dir_entry *dir_add_name(struct dir_struct *dir,1337struct index_state *istate,1338const char*pathname,int len)1339{1340if(index_file_exists(istate, pathname, len, ignore_case))1341return NULL;13421343ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1344return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1345}13461347struct dir_entry *dir_add_ignored(struct dir_struct *dir,1348struct index_state *istate,1349const char*pathname,int len)1350{1351if(!index_name_is_other(istate, pathname, len))1352return NULL;13531354ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1355return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1356}13571358enum exist_status {1359 index_nonexistent =0,1360 index_directory,1361 index_gitdir1362};13631364/*1365 * Do not use the alphabetically sorted index to look up1366 * the directory name; instead, use the case insensitive1367 * directory hash.1368 */1369static enum exist_status directory_exists_in_index_icase(struct index_state *istate,1370const char*dirname,int len)1371{1372struct cache_entry *ce;13731374if(index_dir_exists(istate, dirname, len))1375return index_directory;13761377 ce =index_file_exists(istate, dirname, len, ignore_case);1378if(ce &&S_ISGITLINK(ce->ce_mode))1379return index_gitdir;13801381return index_nonexistent;1382}13831384/*1385 * The index sorts alphabetically by entry name, which1386 * means that a gitlink sorts as '\0' at the end, while1387 * a directory (which is defined not as an entry, but as1388 * the files it contains) will sort with the '/' at the1389 * end.1390 */1391static enum exist_status directory_exists_in_index(struct index_state *istate,1392const char*dirname,int len)1393{1394int pos;13951396if(ignore_case)1397returndirectory_exists_in_index_icase(istate, dirname, len);13981399 pos =index_name_pos(istate, dirname, len);1400if(pos <0)1401 pos = -pos-1;1402while(pos < istate->cache_nr) {1403const struct cache_entry *ce = istate->cache[pos++];1404unsigned char endchar;14051406if(strncmp(ce->name, dirname, len))1407break;1408 endchar = ce->name[len];1409if(endchar >'/')1410break;1411if(endchar =='/')1412return index_directory;1413if(!endchar &&S_ISGITLINK(ce->ce_mode))1414return index_gitdir;1415}1416return index_nonexistent;1417}14181419/*1420 * When we find a directory when traversing the filesystem, we1421 * have three distinct cases:1422 *1423 * - ignore it1424 * - see it as a directory1425 * - recurse into it1426 *1427 * and which one we choose depends on a combination of existing1428 * git index contents and the flags passed into the directory1429 * traversal routine.1430 *1431 * Case 1: If we *already* have entries in the index under that1432 * directory name, we always recurse into the directory to see1433 * all the files.1434 *1435 * Case 2: If we *already* have that directory name as a gitlink,1436 * we always continue to see it as a gitlink, regardless of whether1437 * there is an actual git directory there or not (it might not1438 * be checked out as a subproject!)1439 *1440 * Case 3: if we didn't have it in the index previously, we1441 * have a few sub-cases:1442 *1443 * (a) if "show_other_directories" is true, we show it as1444 * just a directory, unless "hide_empty_directories" is1445 * also true, in which case we need to check if it contains any1446 * untracked and / or ignored files.1447 * (b) if it looks like a git directory, and we don't have1448 * 'no_gitlinks' set we treat it as a gitlink, and show it1449 * as a directory.1450 * (c) otherwise, we recurse into it.1451 */1452static enum path_treatment treat_directory(struct dir_struct *dir,1453struct index_state *istate,1454struct untracked_cache_dir *untracked,1455const char*dirname,int len,int baselen,int exclude,1456const struct pathspec *pathspec)1457{1458/* The "len-1" is to strip the final '/' */1459switch(directory_exists_in_index(istate, dirname, len-1)) {1460case index_directory:1461return path_recurse;14621463case index_gitdir:1464return path_none;14651466case index_nonexistent:1467if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1468break;1469if(exclude &&1470(dir->flags & DIR_SHOW_IGNORED_TOO) &&1471(dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING)) {14721473/*1474 * This is an excluded directory and we are1475 * showing ignored paths that match an exclude1476 * pattern. (e.g. show directory as ignored1477 * only if it matches an exclude pattern).1478 * This path will either be 'path_excluded`1479 * (if we are showing empty directories or if1480 * the directory is not empty), or will be1481 * 'path_none' (empty directory, and we are1482 * not showing empty directories).1483 */1484if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1485return path_excluded;14861487if(read_directory_recursive(dir, istate, dirname, len,1488 untracked,1,1, pathspec) == path_excluded)1489return path_excluded;14901491return path_none;1492}1493if(!(dir->flags & DIR_NO_GITLINKS)) {1494struct object_id oid;1495if(resolve_gitlink_ref(dirname,"HEAD", &oid) ==0)1496return exclude ? path_excluded : path_untracked;1497}1498return path_recurse;1499}15001501/* This is the "show_other_directories" case */15021503if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1504return exclude ? path_excluded : path_untracked;15051506 untracked =lookup_untracked(dir->untracked, untracked,1507 dirname + baselen, len - baselen);15081509/*1510 * If this is an excluded directory, then we only need to check if1511 * the directory contains any files.1512 */1513returnread_directory_recursive(dir, istate, dirname, len,1514 untracked,1, exclude, pathspec);1515}15161517/*1518 * This is an inexact early pruning of any recursive directory1519 * reading - if the path cannot possibly be in the pathspec,1520 * return true, and we'll skip it early.1521 */1522static intsimplify_away(const char*path,int pathlen,1523const struct pathspec *pathspec)1524{1525int i;15261527if(!pathspec || !pathspec->nr)1528return0;15291530GUARD_PATHSPEC(pathspec,1531 PATHSPEC_FROMTOP |1532 PATHSPEC_MAXDEPTH |1533 PATHSPEC_LITERAL |1534 PATHSPEC_GLOB |1535 PATHSPEC_ICASE |1536 PATHSPEC_EXCLUDE |1537 PATHSPEC_ATTR);15381539for(i =0; i < pathspec->nr; i++) {1540const struct pathspec_item *item = &pathspec->items[i];1541int len = item->nowildcard_len;15421543if(len > pathlen)1544 len = pathlen;1545if(!ps_strncmp(item, item->match, path, len))1546return0;1547}15481549return1;1550}15511552/*1553 * This function tells us whether an excluded path matches a1554 * list of "interesting" pathspecs. That is, whether a path matched1555 * by any of the pathspecs could possibly be ignored by excluding1556 * the specified path. This can happen if:1557 *1558 * 1. the path is mentioned explicitly in the pathspec1559 *1560 * 2. the path is a directory prefix of some element in the1561 * pathspec1562 */1563static intexclude_matches_pathspec(const char*path,int pathlen,1564const struct pathspec *pathspec)1565{1566int i;15671568if(!pathspec || !pathspec->nr)1569return0;15701571GUARD_PATHSPEC(pathspec,1572 PATHSPEC_FROMTOP |1573 PATHSPEC_MAXDEPTH |1574 PATHSPEC_LITERAL |1575 PATHSPEC_GLOB |1576 PATHSPEC_ICASE |1577 PATHSPEC_EXCLUDE);15781579for(i =0; i < pathspec->nr; i++) {1580const struct pathspec_item *item = &pathspec->items[i];1581int len = item->nowildcard_len;15821583if(len == pathlen &&1584!ps_strncmp(item, item->match, path, pathlen))1585return1;1586if(len > pathlen &&1587 item->match[pathlen] =='/'&&1588!ps_strncmp(item, item->match, path, pathlen))1589return1;1590}1591return0;1592}15931594static intget_index_dtype(struct index_state *istate,1595const char*path,int len)1596{1597int pos;1598const struct cache_entry *ce;15991600 ce =index_file_exists(istate, path, len,0);1601if(ce) {1602if(!ce_uptodate(ce))1603return DT_UNKNOWN;1604if(S_ISGITLINK(ce->ce_mode))1605return DT_DIR;1606/*1607 * Nobody actually cares about the1608 * difference between DT_LNK and DT_REG1609 */1610return DT_REG;1611}16121613/* Try to look it up as a directory */1614 pos =index_name_pos(istate, path, len);1615if(pos >=0)1616return DT_UNKNOWN;1617 pos = -pos-1;1618while(pos < istate->cache_nr) {1619 ce = istate->cache[pos++];1620if(strncmp(ce->name, path, len))1621break;1622if(ce->name[len] >'/')1623break;1624if(ce->name[len] <'/')1625continue;1626if(!ce_uptodate(ce))1627break;/* continue? */1628return DT_DIR;1629}1630return DT_UNKNOWN;1631}16321633static intget_dtype(struct dirent *de,struct index_state *istate,1634const char*path,int len)1635{1636int dtype = de ?DTYPE(de) : DT_UNKNOWN;1637struct stat st;16381639if(dtype != DT_UNKNOWN)1640return dtype;1641 dtype =get_index_dtype(istate, path, len);1642if(dtype != DT_UNKNOWN)1643return dtype;1644if(lstat(path, &st))1645return dtype;1646if(S_ISREG(st.st_mode))1647return DT_REG;1648if(S_ISDIR(st.st_mode))1649return DT_DIR;1650if(S_ISLNK(st.st_mode))1651return DT_LNK;1652return dtype;1653}16541655static enum path_treatment treat_one_path(struct dir_struct *dir,1656struct untracked_cache_dir *untracked,1657struct index_state *istate,1658struct strbuf *path,1659int baselen,1660const struct pathspec *pathspec,1661int dtype,struct dirent *de)1662{1663int exclude;1664int has_path_in_index = !!index_file_exists(istate, path->buf, path->len, ignore_case);1665enum path_treatment path_treatment;16661667if(dtype == DT_UNKNOWN)1668 dtype =get_dtype(de, istate, path->buf, path->len);16691670/* Always exclude indexed files */1671if(dtype != DT_DIR && has_path_in_index)1672return path_none;16731674/*1675 * When we are looking at a directory P in the working tree,1676 * there are three cases:1677 *1678 * (1) P exists in the index. Everything inside the directory P in1679 * the working tree needs to go when P is checked out from the1680 * index.1681 *1682 * (2) P does not exist in the index, but there is P/Q in the index.1683 * We know P will stay a directory when we check out the contents1684 * of the index, but we do not know yet if there is a directory1685 * P/Q in the working tree to be killed, so we need to recurse.1686 *1687 * (3) P does not exist in the index, and there is no P/Q in the index1688 * to require P to be a directory, either. Only in this case, we1689 * know that everything inside P will not be killed without1690 * recursing.1691 */1692if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1693(dtype == DT_DIR) &&1694!has_path_in_index &&1695(directory_exists_in_index(istate, path->buf, path->len) == index_nonexistent))1696return path_none;16971698 exclude =is_excluded(dir, istate, path->buf, &dtype);16991700/*1701 * Excluded? If we don't explicitly want to show1702 * ignored files, ignore it1703 */1704if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1705return path_excluded;17061707switch(dtype) {1708default:1709return path_none;1710case DT_DIR:1711strbuf_addch(path,'/');1712 path_treatment =treat_directory(dir, istate, untracked,1713 path->buf, path->len,1714 baselen, exclude, pathspec);1715/*1716 * If 1) we only want to return directories that1717 * match an exclude pattern and 2) this directory does1718 * not match an exclude pattern but all of its1719 * contents are excluded, then indicate that we should1720 * recurse into this directory (instead of marking the1721 * directory itself as an ignored path).1722 */1723if(!exclude &&1724 path_treatment == path_excluded &&1725(dir->flags & DIR_SHOW_IGNORED_TOO) &&1726(dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING))1727return path_recurse;1728return path_treatment;1729case DT_REG:1730case DT_LNK:1731return exclude ? path_excluded : path_untracked;1732}1733}17341735static enum path_treatment treat_path_fast(struct dir_struct *dir,1736struct untracked_cache_dir *untracked,1737struct cached_dir *cdir,1738struct index_state *istate,1739struct strbuf *path,1740int baselen,1741const struct pathspec *pathspec)1742{1743strbuf_setlen(path, baselen);1744if(!cdir->ucd) {1745strbuf_addstr(path, cdir->file);1746return path_untracked;1747}1748strbuf_addstr(path, cdir->ucd->name);1749/* treat_one_path() does this before it calls treat_directory() */1750strbuf_complete(path,'/');1751if(cdir->ucd->check_only)1752/*1753 * check_only is set as a result of treat_directory() getting1754 * to its bottom. Verify again the same set of directories1755 * with check_only set.1756 */1757returnread_directory_recursive(dir, istate, path->buf, path->len,1758 cdir->ucd,1,0, pathspec);1759/*1760 * We get path_recurse in the first run when1761 * directory_exists_in_index() returns index_nonexistent. We1762 * are sure that new changes in the index does not impact the1763 * outcome. Return now.1764 */1765return path_recurse;1766}17671768static enum path_treatment treat_path(struct dir_struct *dir,1769struct untracked_cache_dir *untracked,1770struct cached_dir *cdir,1771struct index_state *istate,1772struct strbuf *path,1773int baselen,1774const struct pathspec *pathspec)1775{1776int dtype;1777struct dirent *de = cdir->de;17781779if(!de)1780returntreat_path_fast(dir, untracked, cdir, istate, path,1781 baselen, pathspec);1782if(is_dot_or_dotdot(de->d_name) || !fspathcmp(de->d_name,".git"))1783return path_none;1784strbuf_setlen(path, baselen);1785strbuf_addstr(path, de->d_name);1786if(simplify_away(path->buf, path->len, pathspec))1787return path_none;17881789 dtype =DTYPE(de);1790returntreat_one_path(dir, untracked, istate, path, baselen, pathspec, dtype, de);1791}17921793static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1794{1795if(!dir)1796return;1797ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1798 dir->untracked_alloc);1799 dir->untracked[dir->untracked_nr++] =xstrdup(name);1800}18011802static intvalid_cached_dir(struct dir_struct *dir,1803struct untracked_cache_dir *untracked,1804struct index_state *istate,1805struct strbuf *path,1806int check_only)1807{1808struct stat st;18091810if(!untracked)1811return0;18121813/*1814 * With fsmonitor, we can trust the untracked cache's valid field.1815 */1816refresh_fsmonitor(istate);1817if(!(dir->untracked->use_fsmonitor && untracked->valid)) {1818if(lstat(path->len ? path->buf :".", &st)) {1819memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1820return0;1821}1822if(!untracked->valid ||1823match_stat_data_racy(istate, &untracked->stat_data, &st)) {1824fill_stat_data(&untracked->stat_data, &st);1825return0;1826}1827}18281829if(untracked->check_only != !!check_only)1830return0;18311832/*1833 * prep_exclude will be called eventually on this directory,1834 * but it's called much later in last_exclude_matching(). We1835 * need it now to determine the validity of the cache for this1836 * path. The next calls will be nearly no-op, the way1837 * prep_exclude() is designed.1838 */1839if(path->len && path->buf[path->len -1] !='/') {1840strbuf_addch(path,'/');1841prep_exclude(dir, istate, path->buf, path->len);1842strbuf_setlen(path, path->len -1);1843}else1844prep_exclude(dir, istate, path->buf, path->len);18451846/* hopefully prep_exclude() haven't invalidated this entry... */1847return untracked->valid;1848}18491850static intopen_cached_dir(struct cached_dir *cdir,1851struct dir_struct *dir,1852struct untracked_cache_dir *untracked,1853struct index_state *istate,1854struct strbuf *path,1855int check_only)1856{1857const char*c_path;18581859memset(cdir,0,sizeof(*cdir));1860 cdir->untracked = untracked;1861if(valid_cached_dir(dir, untracked, istate, path, check_only))1862return0;1863 c_path = path->len ? path->buf :".";1864 cdir->fdir =opendir(c_path);1865if(!cdir->fdir)1866warning_errno(_("could not open directory '%s'"), c_path);1867if(dir->untracked) {1868invalidate_directory(dir->untracked, untracked);1869 dir->untracked->dir_opened++;1870}1871if(!cdir->fdir)1872return-1;1873return0;1874}18751876static intread_cached_dir(struct cached_dir *cdir)1877{1878if(cdir->fdir) {1879 cdir->de =readdir(cdir->fdir);1880if(!cdir->de)1881return-1;1882return0;1883}1884while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1885struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1886if(!d->recurse) {1887 cdir->nr_dirs++;1888continue;1889}1890 cdir->ucd = d;1891 cdir->nr_dirs++;1892return0;1893}1894 cdir->ucd = NULL;1895if(cdir->nr_files < cdir->untracked->untracked_nr) {1896struct untracked_cache_dir *d = cdir->untracked;1897 cdir->file = d->untracked[cdir->nr_files++];1898return0;1899}1900return-1;1901}19021903static voidclose_cached_dir(struct cached_dir *cdir)1904{1905if(cdir->fdir)1906closedir(cdir->fdir);1907/*1908 * We have gone through this directory and found no untracked1909 * entries. Mark it valid.1910 */1911if(cdir->untracked) {1912 cdir->untracked->valid =1;1913 cdir->untracked->recurse =1;1914}1915}19161917/*1918 * Read a directory tree. We currently ignore anything but1919 * directories, regular files and symlinks. That's because git1920 * doesn't handle them at all yet. Maybe that will change some1921 * day.1922 *1923 * Also, we ignore the name ".git" (even if it is not a directory).1924 * That likely will not change.1925 *1926 * If 'stop_at_first_file' is specified, 'path_excluded' is returned1927 * to signal that a file was found. This is the least significant value that1928 * indicates that a file was encountered that does not depend on the order of1929 * whether an untracked or exluded path was encountered first.1930 *1931 * Returns the most significant path_treatment value encountered in the scan.1932 * If 'stop_at_first_file' is specified, `path_excluded` is the most1933 * significant path_treatment value that will be returned.1934 */19351936static enum path_treatment read_directory_recursive(struct dir_struct *dir,1937struct index_state *istate,const char*base,int baselen,1938struct untracked_cache_dir *untracked,int check_only,1939int stop_at_first_file,const struct pathspec *pathspec)1940{1941struct cached_dir cdir;1942enum path_treatment state, subdir_state, dir_state = path_none;1943struct strbuf path = STRBUF_INIT;19441945strbuf_add(&path, base, baselen);19461947if(open_cached_dir(&cdir, dir, untracked, istate, &path, check_only))1948goto out;19491950if(untracked)1951 untracked->check_only = !!check_only;19521953while(!read_cached_dir(&cdir)) {1954/* check how the file or directory should be treated */1955 state =treat_path(dir, untracked, &cdir, istate, &path,1956 baselen, pathspec);19571958if(state > dir_state)1959 dir_state = state;19601961/* recurse into subdir if instructed by treat_path */1962if((state == path_recurse) ||1963((state == path_untracked) &&1964(dir->flags & DIR_SHOW_IGNORED_TOO) &&1965(get_dtype(cdir.de, istate, path.buf, path.len) == DT_DIR))) {1966struct untracked_cache_dir *ud;1967 ud =lookup_untracked(dir->untracked, untracked,1968 path.buf + baselen,1969 path.len - baselen);1970 subdir_state =1971read_directory_recursive(dir, istate, path.buf,1972 path.len, ud,1973 check_only, stop_at_first_file, pathspec);1974if(subdir_state > dir_state)1975 dir_state = subdir_state;1976}19771978if(check_only) {1979if(stop_at_first_file) {1980/*1981 * If stopping at first file, then1982 * signal that a file was found by1983 * returning `path_excluded`. This is1984 * to return a consistent value1985 * regardless of whether an ignored or1986 * excluded file happened to be1987 * encountered 1st.1988 *1989 * In current usage, the1990 * `stop_at_first_file` is passed when1991 * an ancestor directory has matched1992 * an exclude pattern, so any found1993 * files will be excluded.1994 */1995if(dir_state >= path_excluded) {1996 dir_state = path_excluded;1997break;1998}1999}20002001/* abort early if maximum state has been reached */2002if(dir_state == path_untracked) {2003if(cdir.fdir)2004add_untracked(untracked, path.buf + baselen);2005break;2006}2007/* skip the dir_add_* part */2008continue;2009}20102011/* add the path to the appropriate result list */2012switch(state) {2013case path_excluded:2014if(dir->flags & DIR_SHOW_IGNORED)2015dir_add_name(dir, istate, path.buf, path.len);2016else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||2017((dir->flags & DIR_COLLECT_IGNORED) &&2018exclude_matches_pathspec(path.buf, path.len,2019 pathspec)))2020dir_add_ignored(dir, istate, path.buf, path.len);2021break;20222023case path_untracked:2024if(dir->flags & DIR_SHOW_IGNORED)2025break;2026dir_add_name(dir, istate, path.buf, path.len);2027if(cdir.fdir)2028add_untracked(untracked, path.buf + baselen);2029break;20302031default:2032break;2033}2034}2035close_cached_dir(&cdir);2036 out:2037strbuf_release(&path);20382039return dir_state;2040}20412042intcmp_dir_entry(const void*p1,const void*p2)2043{2044const struct dir_entry *e1 = *(const struct dir_entry **)p1;2045const struct dir_entry *e2 = *(const struct dir_entry **)p2;20462047returnname_compare(e1->name, e1->len, e2->name, e2->len);2048}20492050/* check if *out lexically strictly contains *in */2051intcheck_dir_entry_contains(const struct dir_entry *out,const struct dir_entry *in)2052{2053return(out->len < in->len) &&2054(out->name[out->len -1] =='/') &&2055!memcmp(out->name, in->name, out->len);2056}20572058static inttreat_leading_path(struct dir_struct *dir,2059struct index_state *istate,2060const char*path,int len,2061const struct pathspec *pathspec)2062{2063struct strbuf sb = STRBUF_INIT;2064int baselen, rc =0;2065const char*cp;2066int old_flags = dir->flags;20672068while(len && path[len -1] =='/')2069 len--;2070if(!len)2071return1;2072 baselen =0;2073 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;2074while(1) {2075 cp = path + baselen + !!baselen;2076 cp =memchr(cp,'/', path + len - cp);2077if(!cp)2078 baselen = len;2079else2080 baselen = cp - path;2081strbuf_setlen(&sb,0);2082strbuf_add(&sb, path, baselen);2083if(!is_directory(sb.buf))2084break;2085if(simplify_away(sb.buf, sb.len, pathspec))2086break;2087if(treat_one_path(dir, NULL, istate, &sb, baselen, pathspec,2088 DT_DIR, NULL) == path_none)2089break;/* do not recurse into it */2090if(len <= baselen) {2091 rc =1;2092break;/* finished checking */2093}2094}2095strbuf_release(&sb);2096 dir->flags = old_flags;2097return rc;2098}20992100static const char*get_ident_string(void)2101{2102static struct strbuf sb = STRBUF_INIT;2103struct utsname uts;21042105if(sb.len)2106return sb.buf;2107if(uname(&uts) <0)2108die_errno(_("failed to get kernel name and information"));2109strbuf_addf(&sb,"Location%s, system%s",get_git_work_tree(),2110 uts.sysname);2111return sb.buf;2112}21132114static intident_in_untracked(const struct untracked_cache *uc)2115{2116/*2117 * Previous git versions may have saved many NUL separated2118 * strings in the "ident" field, but it is insane to manage2119 * many locations, so just take care of the first one.2120 */21212122return!strcmp(uc->ident.buf,get_ident_string());2123}21242125static voidset_untracked_ident(struct untracked_cache *uc)2126{2127strbuf_reset(&uc->ident);2128strbuf_addstr(&uc->ident,get_ident_string());21292130/*2131 * This strbuf used to contain a list of NUL separated2132 * strings, so save NUL too for backward compatibility.2133 */2134strbuf_addch(&uc->ident,0);2135}21362137static voidnew_untracked_cache(struct index_state *istate)2138{2139struct untracked_cache *uc =xcalloc(1,sizeof(*uc));2140strbuf_init(&uc->ident,100);2141 uc->exclude_per_dir =".gitignore";2142/* should be the same flags used by git-status */2143 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;2144set_untracked_ident(uc);2145 istate->untracked = uc;2146 istate->cache_changed |= UNTRACKED_CHANGED;2147}21482149voidadd_untracked_cache(struct index_state *istate)2150{2151if(!istate->untracked) {2152new_untracked_cache(istate);2153}else{2154if(!ident_in_untracked(istate->untracked)) {2155free_untracked_cache(istate->untracked);2156new_untracked_cache(istate);2157}2158}2159}21602161voidremove_untracked_cache(struct index_state *istate)2162{2163if(istate->untracked) {2164free_untracked_cache(istate->untracked);2165 istate->untracked = NULL;2166 istate->cache_changed |= UNTRACKED_CHANGED;2167}2168}21692170static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,2171int base_len,2172const struct pathspec *pathspec)2173{2174struct untracked_cache_dir *root;2175static int untracked_cache_disabled = -1;21762177if(!dir->untracked)2178return NULL;2179if(untracked_cache_disabled <0)2180 untracked_cache_disabled =git_env_bool("GIT_DISABLE_UNTRACKED_CACHE",0);2181if(untracked_cache_disabled)2182return NULL;21832184/*2185 * We only support $GIT_DIR/info/exclude and core.excludesfile2186 * as the global ignore rule files. Any other additions2187 * (e.g. from command line) invalidate the cache. This2188 * condition also catches running setup_standard_excludes()2189 * before setting dir->untracked!2190 */2191if(dir->unmanaged_exclude_files)2192return NULL;21932194/*2195 * Optimize for the main use case only: whole-tree git2196 * status. More work involved in treat_leading_path() if we2197 * use cache on just a subset of the worktree. pathspec2198 * support could make the matter even worse.2199 */2200if(base_len || (pathspec && pathspec->nr))2201return NULL;22022203/* Different set of flags may produce different results */2204if(dir->flags != dir->untracked->dir_flags ||2205/*2206 * See treat_directory(), case index_nonexistent. Without2207 * this flag, we may need to also cache .git file content2208 * for the resolve_gitlink_ref() call, which we don't.2209 */2210!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||2211/* We don't support collecting ignore files */2212(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |2213 DIR_COLLECT_IGNORED)))2214return NULL;22152216/*2217 * If we use .gitignore in the cache and now you change it to2218 * .gitexclude, everything will go wrong.2219 */2220if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&2221strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))2222return NULL;22232224/*2225 * EXC_CMDL is not considered in the cache. If people set it,2226 * skip the cache.2227 */2228if(dir->exclude_list_group[EXC_CMDL].nr)2229return NULL;22302231if(!ident_in_untracked(dir->untracked)) {2232warning(_("Untracked cache is disabled on this system or location."));2233return NULL;2234}22352236if(!dir->untracked->root) {2237const int len =sizeof(*dir->untracked->root);2238 dir->untracked->root =xmalloc(len);2239memset(dir->untracked->root,0, len);2240}22412242/* Validate $GIT_DIR/info/exclude and core.excludesfile */2243 root = dir->untracked->root;2244if(oidcmp(&dir->ss_info_exclude.oid,2245&dir->untracked->ss_info_exclude.oid)) {2246invalidate_gitignore(dir->untracked, root);2247 dir->untracked->ss_info_exclude = dir->ss_info_exclude;2248}2249if(oidcmp(&dir->ss_excludes_file.oid,2250&dir->untracked->ss_excludes_file.oid)) {2251invalidate_gitignore(dir->untracked, root);2252 dir->untracked->ss_excludes_file = dir->ss_excludes_file;2253}22542255/* Make sure this directory is not dropped out at saving phase */2256 root->recurse =1;2257return root;2258}22592260intread_directory(struct dir_struct *dir,struct index_state *istate,2261const char*path,int len,const struct pathspec *pathspec)2262{2263struct untracked_cache_dir *untracked;2264uint64_t start =getnanotime();22652266if(has_symlink_leading_path(path, len))2267return dir->nr;22682269 untracked =validate_untracked_cache(dir, len, pathspec);2270if(!untracked)2271/*2272 * make sure untracked cache code path is disabled,2273 * e.g. prep_exclude()2274 */2275 dir->untracked = NULL;2276if(!len ||treat_leading_path(dir, istate, path, len, pathspec))2277read_directory_recursive(dir, istate, path, len, untracked,0,0, pathspec);2278QSORT(dir->entries, dir->nr, cmp_dir_entry);2279QSORT(dir->ignored, dir->ignored_nr, cmp_dir_entry);22802281/*2282 * If DIR_SHOW_IGNORED_TOO is set, read_directory_recursive() will2283 * also pick up untracked contents of untracked dirs; by default2284 * we discard these, but given DIR_KEEP_UNTRACKED_CONTENTS we do not.2285 */2286if((dir->flags & DIR_SHOW_IGNORED_TOO) &&2287!(dir->flags & DIR_KEEP_UNTRACKED_CONTENTS)) {2288int i, j;22892290/* remove from dir->entries untracked contents of untracked dirs */2291for(i = j =0; j < dir->nr; j++) {2292if(i &&2293check_dir_entry_contains(dir->entries[i -1], dir->entries[j])) {2294FREE_AND_NULL(dir->entries[j]);2295}else{2296 dir->entries[i++] = dir->entries[j];2297}2298}22992300 dir->nr = i;2301}23022303trace_performance_since(start,"read directory %.*s", len, path);2304if(dir->untracked) {2305static int force_untracked_cache = -1;2306static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);23072308if(force_untracked_cache <0)2309 force_untracked_cache =2310git_env_bool("GIT_FORCE_UNTRACKED_CACHE",0);2311trace_printf_key(&trace_untracked_stats,2312"node creation:%u\n"2313"gitignore invalidation:%u\n"2314"directory invalidation:%u\n"2315"opendir:%u\n",2316 dir->untracked->dir_created,2317 dir->untracked->gitignore_invalidated,2318 dir->untracked->dir_invalidated,2319 dir->untracked->dir_opened);2320if(force_untracked_cache &&2321 dir->untracked == istate->untracked &&2322(dir->untracked->dir_opened ||2323 dir->untracked->gitignore_invalidated ||2324 dir->untracked->dir_invalidated))2325 istate->cache_changed |= UNTRACKED_CHANGED;2326if(dir->untracked != istate->untracked) {2327FREE_AND_NULL(dir->untracked);2328}2329}2330return dir->nr;2331}23322333intfile_exists(const char*f)2334{2335struct stat sb;2336returnlstat(f, &sb) ==0;2337}23382339static intcmp_icase(char a,char b)2340{2341if(a == b)2342return0;2343if(ignore_case)2344returntoupper(a) -toupper(b);2345return a - b;2346}23472348/*2349 * Given two normalized paths (a trailing slash is ok), if subdir is2350 * outside dir, return -1. Otherwise return the offset in subdir that2351 * can be used as relative path to dir.2352 */2353intdir_inside_of(const char*subdir,const char*dir)2354{2355int offset =0;23562357assert(dir && subdir && *dir && *subdir);23582359while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2360 dir++;2361 subdir++;2362 offset++;2363}23642365/* hel[p]/me vs hel[l]/yeah */2366if(*dir && *subdir)2367return-1;23682369if(!*subdir)2370return!*dir ? offset : -1;/* same dir */23712372/* foo/[b]ar vs foo/[] */2373if(is_dir_sep(dir[-1]))2374returnis_dir_sep(subdir[-1]) ? offset : -1;23752376/* foo[/]bar vs foo[] */2377returnis_dir_sep(*subdir) ? offset +1: -1;2378}23792380intis_inside_dir(const char*dir)2381{2382char*cwd;2383int rc;23842385if(!dir)2386return0;23872388 cwd =xgetcwd();2389 rc = (dir_inside_of(cwd, dir) >=0);2390free(cwd);2391return rc;2392}23932394intis_empty_dir(const char*path)2395{2396DIR*dir =opendir(path);2397struct dirent *e;2398int ret =1;23992400if(!dir)2401return0;24022403while((e =readdir(dir)) != NULL)2404if(!is_dot_or_dotdot(e->d_name)) {2405 ret =0;2406break;2407}24082409closedir(dir);2410return ret;2411}24122413static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2414{2415DIR*dir;2416struct dirent *e;2417int ret =0, original_len = path->len, len, kept_down =0;2418int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2419int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2420struct object_id submodule_head;24212422if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2423!resolve_gitlink_ref(path->buf,"HEAD", &submodule_head)) {2424/* Do not descend and nuke a nested git work tree. */2425if(kept_up)2426*kept_up =1;2427return0;2428}24292430 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2431 dir =opendir(path->buf);2432if(!dir) {2433if(errno == ENOENT)2434return keep_toplevel ? -1:0;2435else if(errno == EACCES && !keep_toplevel)2436/*2437 * An empty dir could be removable even if it2438 * is unreadable:2439 */2440returnrmdir(path->buf);2441else2442return-1;2443}2444strbuf_complete(path,'/');24452446 len = path->len;2447while((e =readdir(dir)) != NULL) {2448struct stat st;2449if(is_dot_or_dotdot(e->d_name))2450continue;24512452strbuf_setlen(path, len);2453strbuf_addstr(path, e->d_name);2454if(lstat(path->buf, &st)) {2455if(errno == ENOENT)2456/*2457 * file disappeared, which is what we2458 * wanted anyway2459 */2460continue;2461/* fall thru */2462}else if(S_ISDIR(st.st_mode)) {2463if(!remove_dir_recurse(path, flag, &kept_down))2464continue;/* happy */2465}else if(!only_empty &&2466(!unlink(path->buf) || errno == ENOENT)) {2467continue;/* happy, too */2468}24692470/* path too long, stat fails, or non-directory still exists */2471 ret = -1;2472break;2473}2474closedir(dir);24752476strbuf_setlen(path, original_len);2477if(!ret && !keep_toplevel && !kept_down)2478 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2479else if(kept_up)2480/*2481 * report the uplevel that it is not an error that we2482 * did not rmdir() our directory.2483 */2484*kept_up = !ret;2485return ret;2486}24872488intremove_dir_recursively(struct strbuf *path,int flag)2489{2490returnremove_dir_recurse(path, flag, NULL);2491}24922493staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")24942495voidsetup_standard_excludes(struct dir_struct *dir)2496{2497 dir->exclude_per_dir =".gitignore";24982499/* core.excludefile defaulting to $XDG_HOME/git/ignore */2500if(!excludes_file)2501 excludes_file =xdg_config_home("ignore");2502if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2503add_excludes_from_file_1(dir, excludes_file,2504 dir->untracked ? &dir->ss_excludes_file : NULL);25052506/* per repository user preference */2507if(startup_info->have_repository) {2508const char*path =git_path_info_exclude();2509if(!access_or_warn(path, R_OK,0))2510add_excludes_from_file_1(dir, path,2511 dir->untracked ? &dir->ss_info_exclude : NULL);2512}2513}25142515intremove_path(const char*name)2516{2517char*slash;25182519if(unlink(name) && !is_missing_file_error(errno))2520return-1;25212522 slash =strrchr(name,'/');2523if(slash) {2524char*dirs =xstrdup(name);2525 slash = dirs + (slash - name);2526do{2527*slash ='\0';2528}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2529free(dirs);2530}2531return0;2532}25332534/*2535 * Frees memory within dir which was allocated for exclude lists and2536 * the exclude_stack. Does not free dir itself.2537 */2538voidclear_directory(struct dir_struct *dir)2539{2540int i, j;2541struct exclude_list_group *group;2542struct exclude_list *el;2543struct exclude_stack *stk;25442545for(i = EXC_CMDL; i <= EXC_FILE; i++) {2546 group = &dir->exclude_list_group[i];2547for(j =0; j < group->nr; j++) {2548 el = &group->el[j];2549if(i == EXC_DIRS)2550free((char*)el->src);2551clear_exclude_list(el);2552}2553free(group->el);2554}25552556 stk = dir->exclude_stack;2557while(stk) {2558struct exclude_stack *prev = stk->prev;2559free(stk);2560 stk = prev;2561}2562strbuf_release(&dir->basebuf);2563}25642565struct ondisk_untracked_cache {2566struct stat_data info_exclude_stat;2567struct stat_data excludes_file_stat;2568uint32_t dir_flags;2569unsigned char info_exclude_sha1[20];2570unsigned char excludes_file_sha1[20];2571char exclude_per_dir[FLEX_ARRAY];2572};25732574#define ouc_offset(x) offsetof(struct ondisk_untracked_cache, x)2575#define ouc_size(len) (ouc_offset(exclude_per_dir) + len + 1)25762577struct write_data {2578int index;/* number of written untracked_cache_dir */2579struct ewah_bitmap *check_only;/* from untracked_cache_dir */2580struct ewah_bitmap *valid;/* from untracked_cache_dir */2581struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2582struct strbuf out;2583struct strbuf sb_stat;2584struct strbuf sb_sha1;2585};25862587static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2588{2589 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2590 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2591 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2592 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2593 to->sd_dev =htonl(from->sd_dev);2594 to->sd_ino =htonl(from->sd_ino);2595 to->sd_uid =htonl(from->sd_uid);2596 to->sd_gid =htonl(from->sd_gid);2597 to->sd_size =htonl(from->sd_size);2598}25992600static voidwrite_one_dir(struct untracked_cache_dir *untracked,2601struct write_data *wd)2602{2603struct stat_data stat_data;2604struct strbuf *out = &wd->out;2605unsigned char intbuf[16];2606unsigned int intlen, value;2607int i = wd->index++;26082609/*2610 * untracked_nr should be reset whenever valid is clear, but2611 * for safety..2612 */2613if(!untracked->valid) {2614 untracked->untracked_nr =0;2615 untracked->check_only =0;2616}26172618if(untracked->check_only)2619ewah_set(wd->check_only, i);2620if(untracked->valid) {2621ewah_set(wd->valid, i);2622stat_data_to_disk(&stat_data, &untracked->stat_data);2623strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2624}2625if(!is_null_sha1(untracked->exclude_sha1)) {2626ewah_set(wd->sha1_valid, i);2627strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2628}26292630 intlen =encode_varint(untracked->untracked_nr, intbuf);2631strbuf_add(out, intbuf, intlen);26322633/* skip non-recurse directories */2634for(i =0, value =0; i < untracked->dirs_nr; i++)2635if(untracked->dirs[i]->recurse)2636 value++;2637 intlen =encode_varint(value, intbuf);2638strbuf_add(out, intbuf, intlen);26392640strbuf_add(out, untracked->name,strlen(untracked->name) +1);26412642for(i =0; i < untracked->untracked_nr; i++)2643strbuf_add(out, untracked->untracked[i],2644strlen(untracked->untracked[i]) +1);26452646for(i =0; i < untracked->dirs_nr; i++)2647if(untracked->dirs[i]->recurse)2648write_one_dir(untracked->dirs[i], wd);2649}26502651voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2652{2653struct ondisk_untracked_cache *ouc;2654struct write_data wd;2655unsigned char varbuf[16];2656int varint_len;2657size_t len =strlen(untracked->exclude_per_dir);26582659FLEX_ALLOC_MEM(ouc, exclude_per_dir, untracked->exclude_per_dir, len);2660stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2661stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2662hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.oid.hash);2663hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.oid.hash);2664 ouc->dir_flags =htonl(untracked->dir_flags);26652666 varint_len =encode_varint(untracked->ident.len, varbuf);2667strbuf_add(out, varbuf, varint_len);2668strbuf_addbuf(out, &untracked->ident);26692670strbuf_add(out, ouc,ouc_size(len));2671FREE_AND_NULL(ouc);26722673if(!untracked->root) {2674 varint_len =encode_varint(0, varbuf);2675strbuf_add(out, varbuf, varint_len);2676return;2677}26782679 wd.index =0;2680 wd.check_only =ewah_new();2681 wd.valid =ewah_new();2682 wd.sha1_valid =ewah_new();2683strbuf_init(&wd.out,1024);2684strbuf_init(&wd.sb_stat,1024);2685strbuf_init(&wd.sb_sha1,1024);2686write_one_dir(untracked->root, &wd);26872688 varint_len =encode_varint(wd.index, varbuf);2689strbuf_add(out, varbuf, varint_len);2690strbuf_addbuf(out, &wd.out);2691ewah_serialize_strbuf(wd.valid, out);2692ewah_serialize_strbuf(wd.check_only, out);2693ewah_serialize_strbuf(wd.sha1_valid, out);2694strbuf_addbuf(out, &wd.sb_stat);2695strbuf_addbuf(out, &wd.sb_sha1);2696strbuf_addch(out,'\0');/* safe guard for string lists */26972698ewah_free(wd.valid);2699ewah_free(wd.check_only);2700ewah_free(wd.sha1_valid);2701strbuf_release(&wd.out);2702strbuf_release(&wd.sb_stat);2703strbuf_release(&wd.sb_sha1);2704}27052706static voidfree_untracked(struct untracked_cache_dir *ucd)2707{2708int i;2709if(!ucd)2710return;2711for(i =0; i < ucd->dirs_nr; i++)2712free_untracked(ucd->dirs[i]);2713for(i =0; i < ucd->untracked_nr; i++)2714free(ucd->untracked[i]);2715free(ucd->untracked);2716free(ucd->dirs);2717free(ucd);2718}27192720voidfree_untracked_cache(struct untracked_cache *uc)2721{2722if(uc)2723free_untracked(uc->root);2724free(uc);2725}27262727struct read_data {2728int index;2729struct untracked_cache_dir **ucd;2730struct ewah_bitmap *check_only;2731struct ewah_bitmap *valid;2732struct ewah_bitmap *sha1_valid;2733const unsigned char*data;2734const unsigned char*end;2735};27362737static voidstat_data_from_disk(struct stat_data *to,const unsigned char*data)2738{2739memcpy(to, data,sizeof(*to));2740 to->sd_ctime.sec =ntohl(to->sd_ctime.sec);2741 to->sd_ctime.nsec =ntohl(to->sd_ctime.nsec);2742 to->sd_mtime.sec =ntohl(to->sd_mtime.sec);2743 to->sd_mtime.nsec =ntohl(to->sd_mtime.nsec);2744 to->sd_dev =ntohl(to->sd_dev);2745 to->sd_ino =ntohl(to->sd_ino);2746 to->sd_uid =ntohl(to->sd_uid);2747 to->sd_gid =ntohl(to->sd_gid);2748 to->sd_size =ntohl(to->sd_size);2749}27502751static intread_one_dir(struct untracked_cache_dir **untracked_,2752struct read_data *rd)2753{2754struct untracked_cache_dir ud, *untracked;2755const unsigned char*next, *data = rd->data, *end = rd->end;2756unsigned int value;2757int i, len;27582759memset(&ud,0,sizeof(ud));27602761 next = data;2762 value =decode_varint(&next);2763if(next > end)2764return-1;2765 ud.recurse =1;2766 ud.untracked_alloc = value;2767 ud.untracked_nr = value;2768if(ud.untracked_nr)2769ALLOC_ARRAY(ud.untracked, ud.untracked_nr);2770 data = next;27712772 next = data;2773 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2774if(next > end)2775return-1;2776ALLOC_ARRAY(ud.dirs, ud.dirs_nr);2777 data = next;27782779 len =strlen((const char*)data);2780 next = data + len +1;2781if(next > rd->end)2782return-1;2783*untracked_ = untracked =xmalloc(st_add(sizeof(*untracked), len));2784memcpy(untracked, &ud,sizeof(ud));2785memcpy(untracked->name, data, len +1);2786 data = next;27872788for(i =0; i < untracked->untracked_nr; i++) {2789 len =strlen((const char*)data);2790 next = data + len +1;2791if(next > rd->end)2792return-1;2793 untracked->untracked[i] =xstrdup((const char*)data);2794 data = next;2795}27962797 rd->ucd[rd->index++] = untracked;2798 rd->data = data;27992800for(i =0; i < untracked->dirs_nr; i++) {2801 len =read_one_dir(untracked->dirs + i, rd);2802if(len <0)2803return-1;2804}2805return0;2806}28072808static voidset_check_only(size_t pos,void*cb)2809{2810struct read_data *rd = cb;2811struct untracked_cache_dir *ud = rd->ucd[pos];2812 ud->check_only =1;2813}28142815static voidread_stat(size_t pos,void*cb)2816{2817struct read_data *rd = cb;2818struct untracked_cache_dir *ud = rd->ucd[pos];2819if(rd->data +sizeof(struct stat_data) > rd->end) {2820 rd->data = rd->end +1;2821return;2822}2823stat_data_from_disk(&ud->stat_data, rd->data);2824 rd->data +=sizeof(struct stat_data);2825 ud->valid =1;2826}28272828static voidread_sha1(size_t pos,void*cb)2829{2830struct read_data *rd = cb;2831struct untracked_cache_dir *ud = rd->ucd[pos];2832if(rd->data +20> rd->end) {2833 rd->data = rd->end +1;2834return;2835}2836hashcpy(ud->exclude_sha1, rd->data);2837 rd->data +=20;2838}28392840static voidload_oid_stat(struct oid_stat *oid_stat,const unsigned char*data,2841const unsigned char*sha1)2842{2843stat_data_from_disk(&oid_stat->stat, data);2844hashcpy(oid_stat->oid.hash, sha1);2845 oid_stat->valid =1;2846}28472848struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2849{2850struct untracked_cache *uc;2851struct read_data rd;2852const unsigned char*next = data, *end = (const unsigned char*)data + sz;2853const char*ident;2854int ident_len, len;2855const char*exclude_per_dir;28562857if(sz <=1|| end[-1] !='\0')2858return NULL;2859 end--;28602861 ident_len =decode_varint(&next);2862if(next + ident_len > end)2863return NULL;2864 ident = (const char*)next;2865 next += ident_len;28662867if(next +ouc_size(0) > end)2868return NULL;28692870 uc =xcalloc(1,sizeof(*uc));2871strbuf_init(&uc->ident, ident_len);2872strbuf_add(&uc->ident, ident, ident_len);2873load_oid_stat(&uc->ss_info_exclude,2874 next +ouc_offset(info_exclude_stat),2875 next +ouc_offset(info_exclude_sha1));2876load_oid_stat(&uc->ss_excludes_file,2877 next +ouc_offset(excludes_file_stat),2878 next +ouc_offset(excludes_file_sha1));2879 uc->dir_flags =get_be32(next +ouc_offset(dir_flags));2880 exclude_per_dir = (const char*)next +ouc_offset(exclude_per_dir);2881 uc->exclude_per_dir =xstrdup(exclude_per_dir);2882/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2883 next +=ouc_size(strlen(exclude_per_dir));2884if(next >= end)2885goto done2;28862887 len =decode_varint(&next);2888if(next > end || len ==0)2889goto done2;28902891 rd.valid =ewah_new();2892 rd.check_only =ewah_new();2893 rd.sha1_valid =ewah_new();2894 rd.data = next;2895 rd.end = end;2896 rd.index =0;2897ALLOC_ARRAY(rd.ucd, len);28982899if(read_one_dir(&uc->root, &rd) || rd.index != len)2900goto done;29012902 next = rd.data;2903 len =ewah_read_mmap(rd.valid, next, end - next);2904if(len <0)2905goto done;29062907 next += len;2908 len =ewah_read_mmap(rd.check_only, next, end - next);2909if(len <0)2910goto done;29112912 next += len;2913 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2914if(len <0)2915goto done;29162917ewah_each_bit(rd.check_only, set_check_only, &rd);2918 rd.data = next + len;2919ewah_each_bit(rd.valid, read_stat, &rd);2920ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2921 next = rd.data;29222923done:2924free(rd.ucd);2925ewah_free(rd.valid);2926ewah_free(rd.check_only);2927ewah_free(rd.sha1_valid);2928done2:2929if(next != end) {2930free_untracked_cache(uc);2931 uc = NULL;2932}2933return uc;2934}29352936static voidinvalidate_one_directory(struct untracked_cache *uc,2937struct untracked_cache_dir *ucd)2938{2939 uc->dir_invalidated++;2940 ucd->valid =0;2941 ucd->untracked_nr =0;2942}29432944/*2945 * Normally when an entry is added or removed from a directory,2946 * invalidating that directory is enough. No need to touch its2947 * ancestors. When a directory is shown as "foo/bar/" in git-status2948 * however, deleting or adding an entry may have cascading effect.2949 *2950 * Say the "foo/bar/file" has become untracked, we need to tell the2951 * untracked_cache_dir of "foo" that "bar/" is not an untracked2952 * directory any more (because "bar" is managed by foo as an untracked2953 * "file").2954 *2955 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2956 * was the last untracked entry in the entire "foo", we should show2957 * "foo/" instead. Which means we have to invalidate past "bar" up to2958 * "foo".2959 *2960 * This function traverses all directories from root to leaf. If there2961 * is a chance of one of the above cases happening, we invalidate back2962 * to root. Otherwise we just invalidate the leaf. There may be a more2963 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2964 * detect these cases and avoid unnecessary invalidation, for example,2965 * checking for the untracked entry named "bar/" in "foo", but for now2966 * stick to something safe and simple.2967 */2968static intinvalidate_one_component(struct untracked_cache *uc,2969struct untracked_cache_dir *dir,2970const char*path,int len)2971{2972const char*rest =strchr(path,'/');29732974if(rest) {2975int component_len = rest - path;2976struct untracked_cache_dir *d =2977lookup_untracked(uc, dir, path, component_len);2978int ret =2979invalidate_one_component(uc, d, rest +1,2980 len - (component_len +1));2981if(ret)2982invalidate_one_directory(uc, dir);2983return ret;2984}29852986invalidate_one_directory(uc, dir);2987return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2988}29892990voiduntracked_cache_invalidate_path(struct index_state *istate,2991const char*path,int safe_path)2992{2993if(!istate->untracked || !istate->untracked->root)2994return;2995if(!safe_path && !verify_path(path))2996return;2997invalidate_one_component(istate->untracked, istate->untracked->root,2998 path,strlen(path));2999}30003001voiduntracked_cache_remove_from_index(struct index_state *istate,3002const char*path)3003{3004untracked_cache_invalidate_path(istate, path,1);3005}30063007voiduntracked_cache_add_to_index(struct index_state *istate,3008const char*path)3009{3010untracked_cache_invalidate_path(istate, path,1);3011}30123013/* Update gitfile and core.worktree setting to connect work tree and git dir */3014voidconnect_work_tree_and_git_dir(const char*work_tree_,const char*git_dir_)3015{3016struct strbuf gitfile_sb = STRBUF_INIT;3017struct strbuf cfg_sb = STRBUF_INIT;3018struct strbuf rel_path = STRBUF_INIT;3019char*git_dir, *work_tree;30203021/* Prepare .git file */3022strbuf_addf(&gitfile_sb,"%s/.git", work_tree_);3023if(safe_create_leading_directories_const(gitfile_sb.buf))3024die(_("could not create directories for%s"), gitfile_sb.buf);30253026/* Prepare config file */3027strbuf_addf(&cfg_sb,"%s/config", git_dir_);3028if(safe_create_leading_directories_const(cfg_sb.buf))3029die(_("could not create directories for%s"), cfg_sb.buf);30303031 git_dir =real_pathdup(git_dir_,1);3032 work_tree =real_pathdup(work_tree_,1);30333034/* Write .git file */3035write_file(gitfile_sb.buf,"gitdir:%s",3036relative_path(git_dir, work_tree, &rel_path));3037/* Update core.worktree setting */3038git_config_set_in_file(cfg_sb.buf,"core.worktree",3039relative_path(work_tree, git_dir, &rel_path));30403041strbuf_release(&gitfile_sb);3042strbuf_release(&cfg_sb);3043strbuf_release(&rel_path);3044free(work_tree);3045free(git_dir);3046}30473048/*3049 * Migrate the git directory of the given path from old_git_dir to new_git_dir.3050 */3051voidrelocate_gitdir(const char*path,const char*old_git_dir,const char*new_git_dir)3052{3053if(rename(old_git_dir, new_git_dir) <0)3054die_errno(_("could not migrate git directory from '%s' to '%s'"),3055 old_git_dir, new_git_dir);30563057connect_work_tree_and_git_dir(path, new_git_dir);3058}