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"attr.h" 13#include"refs.h" 14#include"wildmatch.h" 15#include"pathspec.h" 16#include"utf8.h" 17#include"varint.h" 18#include"ewah/ewok.h" 19 20/* 21 * Tells read_directory_recursive how a file or directory should be treated. 22 * Values are ordered by significance, e.g. if a directory contains both 23 * excluded and untracked files, it is listed as untracked because 24 * path_untracked > path_excluded. 25 */ 26enum path_treatment { 27 path_none =0, 28 path_recurse, 29 path_excluded, 30 path_untracked 31}; 32 33/* 34 * Support data structure for our opendir/readdir/closedir wrappers 35 */ 36struct cached_dir { 37DIR*fdir; 38struct untracked_cache_dir *untracked; 39int nr_files; 40int nr_dirs; 41 42struct dirent *de; 43const char*file; 44struct untracked_cache_dir *ucd; 45}; 46 47static enum path_treatment read_directory_recursive(struct dir_struct *dir, 48const char*path,int len,struct untracked_cache_dir *untracked, 49int check_only,const struct pathspec *pathspec); 50static intget_dtype(struct dirent *de,const char*path,int len); 51 52intfspathcmp(const char*a,const char*b) 53{ 54return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 55} 56 57intfspathncmp(const char*a,const char*b,size_t count) 58{ 59return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 60} 61 62intgit_fnmatch(const struct pathspec_item *item, 63const char*pattern,const char*string, 64int prefix) 65{ 66if(prefix >0) { 67if(ps_strncmp(item, pattern, string, prefix)) 68return WM_NOMATCH; 69 pattern += prefix; 70 string += prefix; 71} 72if(item->flags & PATHSPEC_ONESTAR) { 73int pattern_len =strlen(++pattern); 74int string_len =strlen(string); 75return string_len < pattern_len || 76ps_strcmp(item, pattern, 77 string + string_len - pattern_len); 78} 79if(item->magic & PATHSPEC_GLOB) 80returnwildmatch(pattern, string, 81 WM_PATHNAME | 82(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 83 NULL); 84else 85/* wildmatch has not learned no FNM_PATHNAME mode yet */ 86returnwildmatch(pattern, string, 87 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 88 NULL); 89} 90 91static intfnmatch_icase_mem(const char*pattern,int patternlen, 92const char*string,int stringlen, 93int flags) 94{ 95int match_status; 96struct strbuf pat_buf = STRBUF_INIT; 97struct strbuf str_buf = STRBUF_INIT; 98const char*use_pat = pattern; 99const char*use_str = string; 100 101if(pattern[patternlen]) { 102strbuf_add(&pat_buf, pattern, patternlen); 103 use_pat = pat_buf.buf; 104} 105if(string[stringlen]) { 106strbuf_add(&str_buf, string, stringlen); 107 use_str = str_buf.buf; 108} 109 110if(ignore_case) 111 flags |= WM_CASEFOLD; 112 match_status =wildmatch(use_pat, use_str, flags, NULL); 113 114strbuf_release(&pat_buf); 115strbuf_release(&str_buf); 116 117return match_status; 118} 119 120static size_tcommon_prefix_len(const struct pathspec *pathspec) 121{ 122int n; 123size_t max =0; 124 125/* 126 * ":(icase)path" is treated as a pathspec full of 127 * wildcard. In other words, only prefix is considered common 128 * prefix. If the pathspec is abc/foo abc/bar, running in 129 * subdir xyz, the common prefix is still xyz, not xuz/abc as 130 * in non-:(icase). 131 */ 132GUARD_PATHSPEC(pathspec, 133 PATHSPEC_FROMTOP | 134 PATHSPEC_MAXDEPTH | 135 PATHSPEC_LITERAL | 136 PATHSPEC_GLOB | 137 PATHSPEC_ICASE | 138 PATHSPEC_EXCLUDE | 139 PATHSPEC_ATTR); 140 141for(n =0; n < pathspec->nr; n++) { 142size_t i =0, len =0, item_len; 143if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 144continue; 145if(pathspec->items[n].magic & PATHSPEC_ICASE) 146 item_len = pathspec->items[n].prefix; 147else 148 item_len = pathspec->items[n].nowildcard_len; 149while(i < item_len && (n ==0|| i < max)) { 150char c = pathspec->items[n].match[i]; 151if(c != pathspec->items[0].match[i]) 152break; 153if(c =='/') 154 len = i +1; 155 i++; 156} 157if(n ==0|| len < max) { 158 max = len; 159if(!max) 160break; 161} 162} 163return max; 164} 165 166/* 167 * Returns a copy of the longest leading path common among all 168 * pathspecs. 169 */ 170char*common_prefix(const struct pathspec *pathspec) 171{ 172unsigned long len =common_prefix_len(pathspec); 173 174return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 175} 176 177intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 178{ 179const char*prefix; 180size_t prefix_len; 181 182/* 183 * Calculate common prefix for the pathspec, and 184 * use that to optimize the directory walk 185 */ 186 prefix_len =common_prefix_len(pathspec); 187 prefix = prefix_len ? pathspec->items[0].match :""; 188 189/* Read the directory and prune it */ 190read_directory(dir, prefix, prefix_len, pathspec); 191 192return prefix_len; 193} 194 195intwithin_depth(const char*name,int namelen, 196int depth,int max_depth) 197{ 198const char*cp = name, *cpe = name + namelen; 199 200while(cp < cpe) { 201if(*cp++ !='/') 202continue; 203 depth++; 204if(depth > max_depth) 205return0; 206} 207return1; 208} 209 210#define DO_MATCH_EXCLUDE (1<<0) 211#define DO_MATCH_DIRECTORY (1<<1) 212#define DO_MATCH_SUBMODULE (1<<2) 213 214static intmatch_attrs(const char*name,int namelen, 215const struct pathspec_item *item) 216{ 217int i; 218 219git_check_attr(name, item->attr_check); 220for(i =0; i < item->attr_match_nr; i++) { 221const char*value; 222int matched; 223enum attr_match_mode match_mode; 224 225 value = item->attr_check->items[i].value; 226 match_mode = item->attr_match[i].match_mode; 227 228if(ATTR_TRUE(value)) 229 matched = (match_mode == MATCH_SET); 230else if(ATTR_FALSE(value)) 231 matched = (match_mode == MATCH_UNSET); 232else if(ATTR_UNSET(value)) 233 matched = (match_mode == MATCH_UNSPECIFIED); 234else 235 matched = (match_mode == MATCH_VALUE && 236!strcmp(item->attr_match[i].value, value)); 237if(!matched) 238return0; 239} 240 241return1; 242} 243 244/* 245 * Does 'match' match the given name? 246 * A match is found if 247 * 248 * (1) the 'match' string is leading directory of 'name', or 249 * (2) the 'match' string is a wildcard and matches 'name', or 250 * (3) the 'match' string is exactly the same as 'name'. 251 * 252 * and the return value tells which case it was. 253 * 254 * It returns 0 when there is no match. 255 */ 256static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 257const char*name,int namelen,unsigned flags) 258{ 259/* name/namelen has prefix cut off by caller */ 260const char*match = item->match + prefix; 261int matchlen = item->len - prefix; 262 263/* 264 * The normal call pattern is: 265 * 1. prefix = common_prefix_len(ps); 266 * 2. prune something, or fill_directory 267 * 3. match_pathspec() 268 * 269 * 'prefix' at #1 may be shorter than the command's prefix and 270 * it's ok for #2 to match extra files. Those extras will be 271 * trimmed at #3. 272 * 273 * Suppose the pathspec is 'foo' and '../bar' running from 274 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 275 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 276 * user does not want XYZ/foo, only the "foo" part should be 277 * case-insensitive. We need to filter out XYZ/foo here. In 278 * other words, we do not trust the caller on comparing the 279 * prefix part when :(icase) is involved. We do exact 280 * comparison ourselves. 281 * 282 * Normally the caller (common_prefix_len() in fact) does 283 * _exact_ matching on name[-prefix+1..-1] and we do not need 284 * to check that part. Be defensive and check it anyway, in 285 * case common_prefix_len is changed, or a new caller is 286 * introduced that does not use common_prefix_len. 287 * 288 * If the penalty turns out too high when prefix is really 289 * long, maybe change it to 290 * strncmp(match, name, item->prefix - prefix) 291 */ 292if(item->prefix && (item->magic & PATHSPEC_ICASE) && 293strncmp(item->match, name - prefix, item->prefix)) 294return0; 295 296if(item->attr_match_nr && !match_attrs(name, namelen, item)) 297return0; 298 299/* If the match was just the prefix, we matched */ 300if(!*match) 301return MATCHED_RECURSIVELY; 302 303if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 304if(matchlen == namelen) 305return MATCHED_EXACTLY; 306 307if(match[matchlen-1] =='/'|| name[matchlen] =='/') 308return MATCHED_RECURSIVELY; 309}else if((flags & DO_MATCH_DIRECTORY) && 310 match[matchlen -1] =='/'&& 311 namelen == matchlen -1&& 312!ps_strncmp(item, match, name, namelen)) 313return MATCHED_EXACTLY; 314 315if(item->nowildcard_len < item->len && 316!git_fnmatch(item, match, name, 317 item->nowildcard_len - prefix)) 318return MATCHED_FNMATCH; 319 320/* Perform checks to see if "name" is a super set of the pathspec */ 321if(flags & DO_MATCH_SUBMODULE) { 322/* name is a literal prefix of the pathspec */ 323if((namelen < matchlen) && 324(match[namelen] =='/') && 325!ps_strncmp(item, match, name, namelen)) 326return MATCHED_RECURSIVELY; 327 328/* name" doesn't match up to the first wild character */ 329if(item->nowildcard_len < item->len && 330ps_strncmp(item, match, name, 331 item->nowildcard_len - prefix)) 332return0; 333 334/* 335 * Here is where we would perform a wildmatch to check if 336 * "name" can be matched as a directory (or a prefix) against 337 * the pathspec. Since wildmatch doesn't have this capability 338 * at the present we have to punt and say that it is a match, 339 * potentially returning a false positive 340 * The submodules themselves will be able to perform more 341 * accurate matching to determine if the pathspec matches. 342 */ 343return MATCHED_RECURSIVELY; 344} 345 346return0; 347} 348 349/* 350 * Given a name and a list of pathspecs, returns the nature of the 351 * closest (i.e. most specific) match of the name to any of the 352 * pathspecs. 353 * 354 * The caller typically calls this multiple times with the same 355 * pathspec and seen[] array but with different name/namelen 356 * (e.g. entries from the index) and is interested in seeing if and 357 * how each pathspec matches all the names it calls this function 358 * with. A mark is left in the seen[] array for each pathspec element 359 * indicating the closest type of match that element achieved, so if 360 * seen[n] remains zero after multiple invocations, that means the nth 361 * pathspec did not match any names, which could indicate that the 362 * user mistyped the nth pathspec. 363 */ 364static intdo_match_pathspec(const struct pathspec *ps, 365const char*name,int namelen, 366int prefix,char*seen, 367unsigned flags) 368{ 369int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 370 371GUARD_PATHSPEC(ps, 372 PATHSPEC_FROMTOP | 373 PATHSPEC_MAXDEPTH | 374 PATHSPEC_LITERAL | 375 PATHSPEC_GLOB | 376 PATHSPEC_ICASE | 377 PATHSPEC_EXCLUDE | 378 PATHSPEC_ATTR); 379 380if(!ps->nr) { 381if(!ps->recursive || 382!(ps->magic & PATHSPEC_MAXDEPTH) || 383 ps->max_depth == -1) 384return MATCHED_RECURSIVELY; 385 386if(within_depth(name, namelen,0, ps->max_depth)) 387return MATCHED_EXACTLY; 388else 389return0; 390} 391 392 name += prefix; 393 namelen -= prefix; 394 395for(i = ps->nr -1; i >=0; i--) { 396int how; 397 398if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 399( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 400continue; 401 402if(seen && seen[i] == MATCHED_EXACTLY) 403continue; 404/* 405 * Make exclude patterns optional and never report 406 * "pathspec ':(exclude)foo' matches no files" 407 */ 408if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 409 seen[i] = MATCHED_FNMATCH; 410 how =match_pathspec_item(ps->items+i, prefix, name, 411 namelen, flags); 412if(ps->recursive && 413(ps->magic & PATHSPEC_MAXDEPTH) && 414 ps->max_depth != -1&& 415 how && how != MATCHED_FNMATCH) { 416int len = ps->items[i].len; 417if(name[len] =='/') 418 len++; 419if(within_depth(name+len, namelen-len,0, ps->max_depth)) 420 how = MATCHED_EXACTLY; 421else 422 how =0; 423} 424if(how) { 425if(retval < how) 426 retval = how; 427if(seen && seen[i] < how) 428 seen[i] = how; 429} 430} 431return retval; 432} 433 434intmatch_pathspec(const struct pathspec *ps, 435const char*name,int namelen, 436int prefix,char*seen,int is_dir) 437{ 438int positive, negative; 439unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 440 positive =do_match_pathspec(ps, name, namelen, 441 prefix, seen, flags); 442if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 443return positive; 444 negative =do_match_pathspec(ps, name, namelen, 445 prefix, seen, 446 flags | DO_MATCH_EXCLUDE); 447return negative ?0: positive; 448} 449 450/** 451 * Check if a submodule is a superset of the pathspec 452 */ 453intsubmodule_path_match(const struct pathspec *ps, 454const char*submodule_name, 455char*seen) 456{ 457int matched =do_match_pathspec(ps, submodule_name, 458strlen(submodule_name), 4590, seen, 460 DO_MATCH_DIRECTORY | 461 DO_MATCH_SUBMODULE); 462return matched; 463} 464 465intreport_path_error(const char*ps_matched, 466const struct pathspec *pathspec, 467const char*prefix) 468{ 469/* 470 * Make sure all pathspec matched; otherwise it is an error. 471 */ 472int num, errors =0; 473for(num =0; num < pathspec->nr; num++) { 474int other, found_dup; 475 476if(ps_matched[num]) 477continue; 478/* 479 * The caller might have fed identical pathspec 480 * twice. Do not barf on such a mistake. 481 * FIXME: parse_pathspec should have eliminated 482 * duplicate pathspec. 483 */ 484for(found_dup = other =0; 485!found_dup && other < pathspec->nr; 486 other++) { 487if(other == num || !ps_matched[other]) 488continue; 489if(!strcmp(pathspec->items[other].original, 490 pathspec->items[num].original)) 491/* 492 * Ok, we have a match already. 493 */ 494 found_dup =1; 495} 496if(found_dup) 497continue; 498 499error("pathspec '%s' did not match any file(s) known to git.", 500 pathspec->items[num].original); 501 errors++; 502} 503return errors; 504} 505 506/* 507 * Return the length of the "simple" part of a path match limiter. 508 */ 509intsimple_length(const char*match) 510{ 511int len = -1; 512 513for(;;) { 514unsigned char c = *match++; 515 len++; 516if(c =='\0'||is_glob_special(c)) 517return len; 518} 519} 520 521intno_wildcard(const char*string) 522{ 523return string[simple_length(string)] =='\0'; 524} 525 526voidparse_exclude_pattern(const char**pattern, 527int*patternlen, 528unsigned*flags, 529int*nowildcardlen) 530{ 531const char*p = *pattern; 532size_t i, len; 533 534*flags =0; 535if(*p =='!') { 536*flags |= EXC_FLAG_NEGATIVE; 537 p++; 538} 539 len =strlen(p); 540if(len && p[len -1] =='/') { 541 len--; 542*flags |= EXC_FLAG_MUSTBEDIR; 543} 544for(i =0; i < len; i++) { 545if(p[i] =='/') 546break; 547} 548if(i == len) 549*flags |= EXC_FLAG_NODIR; 550*nowildcardlen =simple_length(p); 551/* 552 * we should have excluded the trailing slash from 'p' too, 553 * but that's one more allocation. Instead just make sure 554 * nowildcardlen does not exceed real patternlen 555 */ 556if(*nowildcardlen > len) 557*nowildcardlen = len; 558if(*p =='*'&&no_wildcard(p +1)) 559*flags |= EXC_FLAG_ENDSWITH; 560*pattern = p; 561*patternlen = len; 562} 563 564voidadd_exclude(const char*string,const char*base, 565int baselen,struct exclude_list *el,int srcpos) 566{ 567struct exclude *x; 568int patternlen; 569unsigned flags; 570int nowildcardlen; 571 572parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 573if(flags & EXC_FLAG_MUSTBEDIR) { 574FLEXPTR_ALLOC_MEM(x, pattern, string, patternlen); 575}else{ 576 x =xmalloc(sizeof(*x)); 577 x->pattern = string; 578} 579 x->patternlen = patternlen; 580 x->nowildcardlen = nowildcardlen; 581 x->base = base; 582 x->baselen = baselen; 583 x->flags = flags; 584 x->srcpos = srcpos; 585ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 586 el->excludes[el->nr++] = x; 587 x->el = el; 588} 589 590static void*read_skip_worktree_file_from_index(const char*path,size_t*size, 591struct sha1_stat *sha1_stat) 592{ 593int pos, len; 594unsigned long sz; 595enum object_type type; 596void*data; 597 598 len =strlen(path); 599 pos =cache_name_pos(path, len); 600if(pos <0) 601return NULL; 602if(!ce_skip_worktree(active_cache[pos])) 603return NULL; 604 data =read_sha1_file(active_cache[pos]->oid.hash, &type, &sz); 605if(!data || type != OBJ_BLOB) { 606free(data); 607return NULL; 608} 609*size =xsize_t(sz); 610if(sha1_stat) { 611memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 612hashcpy(sha1_stat->sha1, active_cache[pos]->oid.hash); 613} 614return data; 615} 616 617/* 618 * Frees memory within el which was allocated for exclude patterns and 619 * the file buffer. Does not free el itself. 620 */ 621voidclear_exclude_list(struct exclude_list *el) 622{ 623int i; 624 625for(i =0; i < el->nr; i++) 626free(el->excludes[i]); 627free(el->excludes); 628free(el->filebuf); 629 630memset(el,0,sizeof(*el)); 631} 632 633static voidtrim_trailing_spaces(char*buf) 634{ 635char*p, *last_space = NULL; 636 637for(p = buf; *p; p++) 638switch(*p) { 639case' ': 640if(!last_space) 641 last_space = p; 642break; 643case'\\': 644 p++; 645if(!*p) 646return; 647/* fallthrough */ 648default: 649 last_space = NULL; 650} 651 652if(last_space) 653*last_space ='\0'; 654} 655 656/* 657 * Given a subdirectory name and "dir" of the current directory, 658 * search the subdir in "dir" and return it, or create a new one if it 659 * does not exist in "dir". 660 * 661 * If "name" has the trailing slash, it'll be excluded in the search. 662 */ 663static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 664struct untracked_cache_dir *dir, 665const char*name,int len) 666{ 667int first, last; 668struct untracked_cache_dir *d; 669if(!dir) 670return NULL; 671if(len && name[len -1] =='/') 672 len--; 673 first =0; 674 last = dir->dirs_nr; 675while(last > first) { 676int cmp, next = (last + first) >>1; 677 d = dir->dirs[next]; 678 cmp =strncmp(name, d->name, len); 679if(!cmp &&strlen(d->name) > len) 680 cmp = -1; 681if(!cmp) 682return d; 683if(cmp <0) { 684 last = next; 685continue; 686} 687 first = next+1; 688} 689 690 uc->dir_created++; 691FLEX_ALLOC_MEM(d, name, name, len); 692 693ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 694memmove(dir->dirs + first +1, dir->dirs + first, 695(dir->dirs_nr - first) *sizeof(*dir->dirs)); 696 dir->dirs_nr++; 697 dir->dirs[first] = d; 698return d; 699} 700 701static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 702{ 703int i; 704 dir->valid =0; 705 dir->untracked_nr =0; 706for(i =0; i < dir->dirs_nr; i++) 707do_invalidate_gitignore(dir->dirs[i]); 708} 709 710static voidinvalidate_gitignore(struct untracked_cache *uc, 711struct untracked_cache_dir *dir) 712{ 713 uc->gitignore_invalidated++; 714do_invalidate_gitignore(dir); 715} 716 717static voidinvalidate_directory(struct untracked_cache *uc, 718struct untracked_cache_dir *dir) 719{ 720int i; 721 uc->dir_invalidated++; 722 dir->valid =0; 723 dir->untracked_nr =0; 724for(i =0; i < dir->dirs_nr; i++) 725 dir->dirs[i]->recurse =0; 726} 727 728/* 729 * Given a file with name "fname", read it (either from disk, or from 730 * the index if "check_index" is non-zero), parse it and store the 731 * exclude rules in "el". 732 * 733 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 734 * stat data from disk (only valid if add_excludes returns zero). If 735 * ss_valid is non-zero, "ss" must contain good value as input. 736 */ 737static intadd_excludes(const char*fname,const char*base,int baselen, 738struct exclude_list *el,int check_index, 739struct sha1_stat *sha1_stat) 740{ 741struct stat st; 742int fd, i, lineno =1; 743size_t size =0; 744char*buf, *entry; 745 746 fd =open(fname, O_RDONLY); 747if(fd <0||fstat(fd, &st) <0) { 748if(errno != ENOENT) 749warn_on_inaccessible(fname); 750if(0<= fd) 751close(fd); 752if(!check_index || 753(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 754return-1; 755if(size ==0) { 756free(buf); 757return0; 758} 759if(buf[size-1] !='\n') { 760 buf =xrealloc(buf,st_add(size,1)); 761 buf[size++] ='\n'; 762} 763}else{ 764 size =xsize_t(st.st_size); 765if(size ==0) { 766if(sha1_stat) { 767fill_stat_data(&sha1_stat->stat, &st); 768hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 769 sha1_stat->valid =1; 770} 771close(fd); 772return0; 773} 774 buf =xmallocz(size); 775if(read_in_full(fd, buf, size) != size) { 776free(buf); 777close(fd); 778return-1; 779} 780 buf[size++] ='\n'; 781close(fd); 782if(sha1_stat) { 783int pos; 784if(sha1_stat->valid && 785!match_stat_data_racy(&the_index, &sha1_stat->stat, &st)) 786;/* no content change, ss->sha1 still good */ 787else if(check_index && 788(pos =cache_name_pos(fname,strlen(fname))) >=0&& 789!ce_stage(active_cache[pos]) && 790ce_uptodate(active_cache[pos]) && 791!would_convert_to_git(fname)) 792hashcpy(sha1_stat->sha1, 793 active_cache[pos]->oid.hash); 794else 795hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 796fill_stat_data(&sha1_stat->stat, &st); 797 sha1_stat->valid =1; 798} 799} 800 801 el->filebuf = buf; 802 803if(skip_utf8_bom(&buf, size)) 804 size -= buf - el->filebuf; 805 806 entry = buf; 807 808for(i =0; i < size; i++) { 809if(buf[i] =='\n') { 810if(entry != buf + i && entry[0] !='#') { 811 buf[i - (i && buf[i-1] =='\r')] =0; 812trim_trailing_spaces(entry); 813add_exclude(entry, base, baselen, el, lineno); 814} 815 lineno++; 816 entry = buf + i +1; 817} 818} 819return0; 820} 821 822intadd_excludes_from_file_to_list(const char*fname,const char*base, 823int baselen,struct exclude_list *el, 824int check_index) 825{ 826returnadd_excludes(fname, base, baselen, el, check_index, NULL); 827} 828 829struct exclude_list *add_exclude_list(struct dir_struct *dir, 830int group_type,const char*src) 831{ 832struct exclude_list *el; 833struct exclude_list_group *group; 834 835 group = &dir->exclude_list_group[group_type]; 836ALLOC_GROW(group->el, group->nr +1, group->alloc); 837 el = &group->el[group->nr++]; 838memset(el,0,sizeof(*el)); 839 el->src = src; 840return el; 841} 842 843/* 844 * Used to set up core.excludesfile and .git/info/exclude lists. 845 */ 846static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 847struct sha1_stat *sha1_stat) 848{ 849struct exclude_list *el; 850/* 851 * catch setup_standard_excludes() that's called before 852 * dir->untracked is assigned. That function behaves 853 * differently when dir->untracked is non-NULL. 854 */ 855if(!dir->untracked) 856 dir->unmanaged_exclude_files++; 857 el =add_exclude_list(dir, EXC_FILE, fname); 858if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 859die("cannot use%sas an exclude file", fname); 860} 861 862voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 863{ 864 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 865add_excludes_from_file_1(dir, fname, NULL); 866} 867 868intmatch_basename(const char*basename,int basenamelen, 869const char*pattern,int prefix,int patternlen, 870unsigned flags) 871{ 872if(prefix == patternlen) { 873if(patternlen == basenamelen && 874!fspathncmp(pattern, basename, basenamelen)) 875return1; 876}else if(flags & EXC_FLAG_ENDSWITH) { 877/* "*literal" matching against "fooliteral" */ 878if(patternlen -1<= basenamelen && 879!fspathncmp(pattern +1, 880 basename + basenamelen - (patternlen -1), 881 patternlen -1)) 882return1; 883}else{ 884if(fnmatch_icase_mem(pattern, patternlen, 885 basename, basenamelen, 8860) ==0) 887return1; 888} 889return0; 890} 891 892intmatch_pathname(const char*pathname,int pathlen, 893const char*base,int baselen, 894const char*pattern,int prefix,int patternlen, 895unsigned flags) 896{ 897const char*name; 898int namelen; 899 900/* 901 * match with FNM_PATHNAME; the pattern has base implicitly 902 * in front of it. 903 */ 904if(*pattern =='/') { 905 pattern++; 906 patternlen--; 907 prefix--; 908} 909 910/* 911 * baselen does not count the trailing slash. base[] may or 912 * may not end with a trailing slash though. 913 */ 914if(pathlen < baselen +1|| 915(baselen && pathname[baselen] !='/') || 916fspathncmp(pathname, base, baselen)) 917return0; 918 919 namelen = baselen ? pathlen - baselen -1: pathlen; 920 name = pathname + pathlen - namelen; 921 922if(prefix) { 923/* 924 * if the non-wildcard part is longer than the 925 * remaining pathname, surely it cannot match. 926 */ 927if(prefix > namelen) 928return0; 929 930if(fspathncmp(pattern, name, prefix)) 931return0; 932 pattern += prefix; 933 patternlen -= prefix; 934 name += prefix; 935 namelen -= prefix; 936 937/* 938 * If the whole pattern did not have a wildcard, 939 * then our prefix match is all we need; we 940 * do not need to call fnmatch at all. 941 */ 942if(!patternlen && !namelen) 943return1; 944} 945 946returnfnmatch_icase_mem(pattern, patternlen, 947 name, namelen, 948 WM_PATHNAME) ==0; 949} 950 951/* 952 * Scan the given exclude list in reverse to see whether pathname 953 * should be ignored. The first match (i.e. the last on the list), if 954 * any, determines the fate. Returns the exclude_list element which 955 * matched, or NULL for undecided. 956 */ 957static struct exclude *last_exclude_matching_from_list(const char*pathname, 958int pathlen, 959const char*basename, 960int*dtype, 961struct exclude_list *el) 962{ 963struct exclude *exc = NULL;/* undecided */ 964int i; 965 966if(!el->nr) 967return NULL;/* undefined */ 968 969for(i = el->nr -1;0<= i; i--) { 970struct exclude *x = el->excludes[i]; 971const char*exclude = x->pattern; 972int prefix = x->nowildcardlen; 973 974if(x->flags & EXC_FLAG_MUSTBEDIR) { 975if(*dtype == DT_UNKNOWN) 976*dtype =get_dtype(NULL, pathname, pathlen); 977if(*dtype != DT_DIR) 978continue; 979} 980 981if(x->flags & EXC_FLAG_NODIR) { 982if(match_basename(basename, 983 pathlen - (basename - pathname), 984 exclude, prefix, x->patternlen, 985 x->flags)) { 986 exc = x; 987break; 988} 989continue; 990} 991 992assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 993if(match_pathname(pathname, pathlen, 994 x->base, x->baselen ? x->baselen -1:0, 995 exclude, prefix, x->patternlen, x->flags)) { 996 exc = x; 997break; 998} 999}1000return exc;1001}10021003/*1004 * Scan the list and let the last match determine the fate.1005 * Return 1 for exclude, 0 for include and -1 for undecided.1006 */1007intis_excluded_from_list(const char*pathname,1008int pathlen,const char*basename,int*dtype,1009struct exclude_list *el)1010{1011struct exclude *exclude;1012 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el);1013if(exclude)1014return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1015return-1;/* undecided */1016}10171018static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir,1019const char*pathname,int pathlen,const char*basename,1020int*dtype_p)1021{1022int i, j;1023struct exclude_list_group *group;1024struct exclude *exclude;1025for(i = EXC_CMDL; i <= EXC_FILE; i++) {1026 group = &dir->exclude_list_group[i];1027for(j = group->nr -1; j >=0; j--) {1028 exclude =last_exclude_matching_from_list(1029 pathname, pathlen, basename, dtype_p,1030&group->el[j]);1031if(exclude)1032return exclude;1033}1034}1035return NULL;1036}10371038/*1039 * Loads the per-directory exclude list for the substring of base1040 * which has a char length of baselen.1041 */1042static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen)1043{1044struct exclude_list_group *group;1045struct exclude_list *el;1046struct exclude_stack *stk = NULL;1047struct untracked_cache_dir *untracked;1048int current;10491050 group = &dir->exclude_list_group[EXC_DIRS];10511052/*1053 * Pop the exclude lists from the EXCL_DIRS exclude_list_group1054 * which originate from directories not in the prefix of the1055 * path being checked.1056 */1057while((stk = dir->exclude_stack) != NULL) {1058if(stk->baselen <= baselen &&1059!strncmp(dir->basebuf.buf, base, stk->baselen))1060break;1061 el = &group->el[dir->exclude_stack->exclude_ix];1062 dir->exclude_stack = stk->prev;1063 dir->exclude = NULL;1064free((char*)el->src);/* see strbuf_detach() below */1065clear_exclude_list(el);1066free(stk);1067 group->nr--;1068}10691070/* Skip traversing into sub directories if the parent is excluded */1071if(dir->exclude)1072return;10731074/*1075 * Lazy initialization. All call sites currently just1076 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1077 * them seems lots of work for little benefit.1078 */1079if(!dir->basebuf.buf)1080strbuf_init(&dir->basebuf, PATH_MAX);10811082/* Read from the parent directories and push them down. */1083 current = stk ? stk->baselen : -1;1084strbuf_setlen(&dir->basebuf, current <0?0: current);1085if(dir->untracked)1086 untracked = stk ? stk->ucd : dir->untracked->root;1087else1088 untracked = NULL;10891090while(current < baselen) {1091const char*cp;1092struct sha1_stat sha1_stat;10931094 stk =xcalloc(1,sizeof(*stk));1095if(current <0) {1096 cp = base;1097 current =0;1098}else{1099 cp =strchr(base + current +1,'/');1100if(!cp)1101die("oops in prep_exclude");1102 cp++;1103 untracked =1104lookup_untracked(dir->untracked, untracked,1105 base + current,1106 cp - base - current);1107}1108 stk->prev = dir->exclude_stack;1109 stk->baselen = cp - base;1110 stk->exclude_ix = group->nr;1111 stk->ucd = untracked;1112 el =add_exclude_list(dir, EXC_DIRS, NULL);1113strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1114assert(stk->baselen == dir->basebuf.len);11151116/* Abort if the directory is excluded */1117if(stk->baselen) {1118int dt = DT_DIR;1119 dir->basebuf.buf[stk->baselen -1] =0;1120 dir->exclude =last_exclude_matching_from_lists(dir,1121 dir->basebuf.buf, stk->baselen -1,1122 dir->basebuf.buf + current, &dt);1123 dir->basebuf.buf[stk->baselen -1] ='/';1124if(dir->exclude &&1125 dir->exclude->flags & EXC_FLAG_NEGATIVE)1126 dir->exclude = NULL;1127if(dir->exclude) {1128 dir->exclude_stack = stk;1129return;1130}1131}11321133/* Try to read per-directory file */1134hashclr(sha1_stat.sha1);1135 sha1_stat.valid =0;1136if(dir->exclude_per_dir &&1137/*1138 * If we know that no files have been added in1139 * this directory (i.e. valid_cached_dir() has1140 * been executed and set untracked->valid) ..1141 */1142(!untracked || !untracked->valid ||1143/*1144 * .. and .gitignore does not exist before1145 * (i.e. null exclude_sha1). Then we can skip1146 * loading .gitignore, which would result in1147 * ENOENT anyway.1148 */1149!is_null_sha1(untracked->exclude_sha1))) {1150/*1151 * dir->basebuf gets reused by the traversal, but we1152 * need fname to remain unchanged to ensure the src1153 * member of each struct exclude correctly1154 * back-references its source file. Other invocations1155 * of add_exclude_list provide stable strings, so we1156 * strbuf_detach() and free() here in the caller.1157 */1158struct strbuf sb = STRBUF_INIT;1159strbuf_addbuf(&sb, &dir->basebuf);1160strbuf_addstr(&sb, dir->exclude_per_dir);1161 el->src =strbuf_detach(&sb, NULL);1162add_excludes(el->src, el->src, stk->baselen, el,1,1163 untracked ? &sha1_stat : NULL);1164}1165/*1166 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1167 * will first be called in valid_cached_dir() then maybe many1168 * times more in last_exclude_matching(). When the cache is1169 * used, last_exclude_matching() will not be called and1170 * reading .gitignore content will be a waste.1171 *1172 * So when it's called by valid_cached_dir() and we can get1173 * .gitignore SHA-1 from the index (i.e. .gitignore is not1174 * modified on work tree), we could delay reading the1175 * .gitignore content until we absolutely need it in1176 * last_exclude_matching(). Be careful about ignore rule1177 * order, though, if you do that.1178 */1179if(untracked &&1180hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1181invalidate_gitignore(dir->untracked, untracked);1182hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1183}1184 dir->exclude_stack = stk;1185 current = stk->baselen;1186}1187strbuf_setlen(&dir->basebuf, baselen);1188}11891190/*1191 * Loads the exclude lists for the directory containing pathname, then1192 * scans all exclude lists to determine whether pathname is excluded.1193 * Returns the exclude_list element which matched, or NULL for1194 * undecided.1195 */1196struct exclude *last_exclude_matching(struct dir_struct *dir,1197const char*pathname,1198int*dtype_p)1199{1200int pathlen =strlen(pathname);1201const char*basename =strrchr(pathname,'/');1202 basename = (basename) ? basename+1: pathname;12031204prep_exclude(dir, pathname, basename-pathname);12051206if(dir->exclude)1207return dir->exclude;12081209returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1210 basename, dtype_p);1211}12121213/*1214 * Loads the exclude lists for the directory containing pathname, then1215 * scans all exclude lists to determine whether pathname is excluded.1216 * Returns 1 if true, otherwise 0.1217 */1218intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1219{1220struct exclude *exclude =1221last_exclude_matching(dir, pathname, dtype_p);1222if(exclude)1223return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1224return0;1225}12261227static struct dir_entry *dir_entry_new(const char*pathname,int len)1228{1229struct dir_entry *ent;12301231FLEX_ALLOC_MEM(ent, name, pathname, len);1232 ent->len = len;1233return ent;1234}12351236static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1237{1238if(cache_file_exists(pathname, len, ignore_case))1239return NULL;12401241ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1242return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1243}12441245struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1246{1247if(!cache_name_is_other(pathname, len))1248return NULL;12491250ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1251return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1252}12531254enum exist_status {1255 index_nonexistent =0,1256 index_directory,1257 index_gitdir1258};12591260/*1261 * Do not use the alphabetically sorted index to look up1262 * the directory name; instead, use the case insensitive1263 * directory hash.1264 */1265static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1266{1267struct cache_entry *ce;12681269if(cache_dir_exists(dirname, len))1270return index_directory;12711272 ce =cache_file_exists(dirname, len, ignore_case);1273if(ce &&S_ISGITLINK(ce->ce_mode))1274return index_gitdir;12751276return index_nonexistent;1277}12781279/*1280 * The index sorts alphabetically by entry name, which1281 * means that a gitlink sorts as '\0' at the end, while1282 * a directory (which is defined not as an entry, but as1283 * the files it contains) will sort with the '/' at the1284 * end.1285 */1286static enum exist_status directory_exists_in_index(const char*dirname,int len)1287{1288int pos;12891290if(ignore_case)1291returndirectory_exists_in_index_icase(dirname, len);12921293 pos =cache_name_pos(dirname, len);1294if(pos <0)1295 pos = -pos-1;1296while(pos < active_nr) {1297const struct cache_entry *ce = active_cache[pos++];1298unsigned char endchar;12991300if(strncmp(ce->name, dirname, len))1301break;1302 endchar = ce->name[len];1303if(endchar >'/')1304break;1305if(endchar =='/')1306return index_directory;1307if(!endchar &&S_ISGITLINK(ce->ce_mode))1308return index_gitdir;1309}1310return index_nonexistent;1311}13121313/*1314 * When we find a directory when traversing the filesystem, we1315 * have three distinct cases:1316 *1317 * - ignore it1318 * - see it as a directory1319 * - recurse into it1320 *1321 * and which one we choose depends on a combination of existing1322 * git index contents and the flags passed into the directory1323 * traversal routine.1324 *1325 * Case 1: If we *already* have entries in the index under that1326 * directory name, we always recurse into the directory to see1327 * all the files.1328 *1329 * Case 2: If we *already* have that directory name as a gitlink,1330 * we always continue to see it as a gitlink, regardless of whether1331 * there is an actual git directory there or not (it might not1332 * be checked out as a subproject!)1333 *1334 * Case 3: if we didn't have it in the index previously, we1335 * have a few sub-cases:1336 *1337 * (a) if "show_other_directories" is true, we show it as1338 * just a directory, unless "hide_empty_directories" is1339 * also true, in which case we need to check if it contains any1340 * untracked and / or ignored files.1341 * (b) if it looks like a git directory, and we don't have1342 * 'no_gitlinks' set we treat it as a gitlink, and show it1343 * as a directory.1344 * (c) otherwise, we recurse into it.1345 */1346static enum path_treatment treat_directory(struct dir_struct *dir,1347struct untracked_cache_dir *untracked,1348const char*dirname,int len,int baselen,int exclude,1349const struct pathspec *pathspec)1350{1351/* The "len-1" is to strip the final '/' */1352switch(directory_exists_in_index(dirname, len-1)) {1353case index_directory:1354return path_recurse;13551356case index_gitdir:1357return path_none;13581359case index_nonexistent:1360if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1361break;1362if(!(dir->flags & DIR_NO_GITLINKS)) {1363unsigned char sha1[20];1364if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1365return path_untracked;1366}1367return path_recurse;1368}13691370/* This is the "show_other_directories" case */13711372if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1373return exclude ? path_excluded : path_untracked;13741375 untracked =lookup_untracked(dir->untracked, untracked,1376 dirname + baselen, len - baselen);1377returnread_directory_recursive(dir, dirname, len,1378 untracked,1, pathspec);1379}13801381/*1382 * This is an inexact early pruning of any recursive directory1383 * reading - if the path cannot possibly be in the pathspec,1384 * return true, and we'll skip it early.1385 */1386static intsimplify_away(const char*path,int pathlen,1387const struct pathspec *pathspec)1388{1389int i;13901391if(!pathspec || !pathspec->nr)1392return0;13931394GUARD_PATHSPEC(pathspec,1395 PATHSPEC_FROMTOP |1396 PATHSPEC_MAXDEPTH |1397 PATHSPEC_LITERAL |1398 PATHSPEC_GLOB |1399 PATHSPEC_ICASE |1400 PATHSPEC_EXCLUDE |1401 PATHSPEC_ATTR);14021403for(i =0; i < pathspec->nr; i++) {1404const struct pathspec_item *item = &pathspec->items[i];1405int len = item->nowildcard_len;14061407if(len > pathlen)1408 len = pathlen;1409if(!ps_strncmp(item, item->match, path, len))1410return0;1411}14121413return1;1414}14151416/*1417 * This function tells us whether an excluded path matches a1418 * list of "interesting" pathspecs. That is, whether a path matched1419 * by any of the pathspecs could possibly be ignored by excluding1420 * the specified path. This can happen if:1421 *1422 * 1. the path is mentioned explicitly in the pathspec1423 *1424 * 2. the path is a directory prefix of some element in the1425 * pathspec1426 */1427static intexclude_matches_pathspec(const char*path,int pathlen,1428const struct pathspec *pathspec)1429{1430int i;14311432if(!pathspec || !pathspec->nr)1433return0;14341435GUARD_PATHSPEC(pathspec,1436 PATHSPEC_FROMTOP |1437 PATHSPEC_MAXDEPTH |1438 PATHSPEC_LITERAL |1439 PATHSPEC_GLOB |1440 PATHSPEC_ICASE |1441 PATHSPEC_EXCLUDE);14421443for(i =0; i < pathspec->nr; i++) {1444const struct pathspec_item *item = &pathspec->items[i];1445int len = item->nowildcard_len;14461447if(len == pathlen &&1448!ps_strncmp(item, item->match, path, pathlen))1449return1;1450if(len > pathlen &&1451 item->match[pathlen] =='/'&&1452!ps_strncmp(item, item->match, path, pathlen))1453return1;1454}1455return0;1456}14571458static intget_index_dtype(const char*path,int len)1459{1460int pos;1461const struct cache_entry *ce;14621463 ce =cache_file_exists(path, len,0);1464if(ce) {1465if(!ce_uptodate(ce))1466return DT_UNKNOWN;1467if(S_ISGITLINK(ce->ce_mode))1468return DT_DIR;1469/*1470 * Nobody actually cares about the1471 * difference between DT_LNK and DT_REG1472 */1473return DT_REG;1474}14751476/* Try to look it up as a directory */1477 pos =cache_name_pos(path, len);1478if(pos >=0)1479return DT_UNKNOWN;1480 pos = -pos-1;1481while(pos < active_nr) {1482 ce = active_cache[pos++];1483if(strncmp(ce->name, path, len))1484break;1485if(ce->name[len] >'/')1486break;1487if(ce->name[len] <'/')1488continue;1489if(!ce_uptodate(ce))1490break;/* continue? */1491return DT_DIR;1492}1493return DT_UNKNOWN;1494}14951496static intget_dtype(struct dirent *de,const char*path,int len)1497{1498int dtype = de ?DTYPE(de) : DT_UNKNOWN;1499struct stat st;15001501if(dtype != DT_UNKNOWN)1502return dtype;1503 dtype =get_index_dtype(path, len);1504if(dtype != DT_UNKNOWN)1505return dtype;1506if(lstat(path, &st))1507return dtype;1508if(S_ISREG(st.st_mode))1509return DT_REG;1510if(S_ISDIR(st.st_mode))1511return DT_DIR;1512if(S_ISLNK(st.st_mode))1513return DT_LNK;1514return dtype;1515}15161517static enum path_treatment treat_one_path(struct dir_struct *dir,1518struct untracked_cache_dir *untracked,1519struct strbuf *path,1520int baselen,1521const struct pathspec *pathspec,1522int dtype,struct dirent *de)1523{1524int exclude;1525int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);15261527if(dtype == DT_UNKNOWN)1528 dtype =get_dtype(de, path->buf, path->len);15291530/* Always exclude indexed files */1531if(dtype != DT_DIR && has_path_in_index)1532return path_none;15331534/*1535 * When we are looking at a directory P in the working tree,1536 * there are three cases:1537 *1538 * (1) P exists in the index. Everything inside the directory P in1539 * the working tree needs to go when P is checked out from the1540 * index.1541 *1542 * (2) P does not exist in the index, but there is P/Q in the index.1543 * We know P will stay a directory when we check out the contents1544 * of the index, but we do not know yet if there is a directory1545 * P/Q in the working tree to be killed, so we need to recurse.1546 *1547 * (3) P does not exist in the index, and there is no P/Q in the index1548 * to require P to be a directory, either. Only in this case, we1549 * know that everything inside P will not be killed without1550 * recursing.1551 */1552if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1553(dtype == DT_DIR) &&1554!has_path_in_index &&1555(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1556return path_none;15571558 exclude =is_excluded(dir, path->buf, &dtype);15591560/*1561 * Excluded? If we don't explicitly want to show1562 * ignored files, ignore it1563 */1564if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1565return path_excluded;15661567switch(dtype) {1568default:1569return path_none;1570case DT_DIR:1571strbuf_addch(path,'/');1572returntreat_directory(dir, untracked, path->buf, path->len,1573 baselen, exclude, pathspec);1574case DT_REG:1575case DT_LNK:1576return exclude ? path_excluded : path_untracked;1577}1578}15791580static enum path_treatment treat_path_fast(struct dir_struct *dir,1581struct untracked_cache_dir *untracked,1582struct cached_dir *cdir,1583struct strbuf *path,1584int baselen,1585const struct pathspec *pathspec)1586{1587strbuf_setlen(path, baselen);1588if(!cdir->ucd) {1589strbuf_addstr(path, cdir->file);1590return path_untracked;1591}1592strbuf_addstr(path, cdir->ucd->name);1593/* treat_one_path() does this before it calls treat_directory() */1594strbuf_complete(path,'/');1595if(cdir->ucd->check_only)1596/*1597 * check_only is set as a result of treat_directory() getting1598 * to its bottom. Verify again the same set of directories1599 * with check_only set.1600 */1601returnread_directory_recursive(dir, path->buf, path->len,1602 cdir->ucd,1, pathspec);1603/*1604 * We get path_recurse in the first run when1605 * directory_exists_in_index() returns index_nonexistent. We1606 * are sure that new changes in the index does not impact the1607 * outcome. Return now.1608 */1609return path_recurse;1610}16111612static enum path_treatment treat_path(struct dir_struct *dir,1613struct untracked_cache_dir *untracked,1614struct cached_dir *cdir,1615struct strbuf *path,1616int baselen,1617const struct pathspec *pathspec)1618{1619int dtype;1620struct dirent *de = cdir->de;16211622if(!de)1623returntreat_path_fast(dir, untracked, cdir, path,1624 baselen, pathspec);1625if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1626return path_none;1627strbuf_setlen(path, baselen);1628strbuf_addstr(path, de->d_name);1629if(simplify_away(path->buf, path->len, pathspec))1630return path_none;16311632 dtype =DTYPE(de);1633returntreat_one_path(dir, untracked, path, baselen, pathspec, dtype, de);1634}16351636static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1637{1638if(!dir)1639return;1640ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1641 dir->untracked_alloc);1642 dir->untracked[dir->untracked_nr++] =xstrdup(name);1643}16441645static intvalid_cached_dir(struct dir_struct *dir,1646struct untracked_cache_dir *untracked,1647struct strbuf *path,1648int check_only)1649{1650struct stat st;16511652if(!untracked)1653return0;16541655if(stat(path->len ? path->buf :".", &st)) {1656invalidate_directory(dir->untracked, untracked);1657memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1658return0;1659}1660if(!untracked->valid ||1661match_stat_data_racy(&the_index, &untracked->stat_data, &st)) {1662if(untracked->valid)1663invalidate_directory(dir->untracked, untracked);1664fill_stat_data(&untracked->stat_data, &st);1665return0;1666}16671668if(untracked->check_only != !!check_only) {1669invalidate_directory(dir->untracked, untracked);1670return0;1671}16721673/*1674 * prep_exclude will be called eventually on this directory,1675 * but it's called much later in last_exclude_matching(). We1676 * need it now to determine the validity of the cache for this1677 * path. The next calls will be nearly no-op, the way1678 * prep_exclude() is designed.1679 */1680if(path->len && path->buf[path->len -1] !='/') {1681strbuf_addch(path,'/');1682prep_exclude(dir, path->buf, path->len);1683strbuf_setlen(path, path->len -1);1684}else1685prep_exclude(dir, path->buf, path->len);16861687/* hopefully prep_exclude() haven't invalidated this entry... */1688return untracked->valid;1689}16901691static intopen_cached_dir(struct cached_dir *cdir,1692struct dir_struct *dir,1693struct untracked_cache_dir *untracked,1694struct strbuf *path,1695int check_only)1696{1697memset(cdir,0,sizeof(*cdir));1698 cdir->untracked = untracked;1699if(valid_cached_dir(dir, untracked, path, check_only))1700return0;1701 cdir->fdir =opendir(path->len ? path->buf :".");1702if(dir->untracked)1703 dir->untracked->dir_opened++;1704if(!cdir->fdir)1705return-1;1706return0;1707}17081709static intread_cached_dir(struct cached_dir *cdir)1710{1711if(cdir->fdir) {1712 cdir->de =readdir(cdir->fdir);1713if(!cdir->de)1714return-1;1715return0;1716}1717while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1718struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1719if(!d->recurse) {1720 cdir->nr_dirs++;1721continue;1722}1723 cdir->ucd = d;1724 cdir->nr_dirs++;1725return0;1726}1727 cdir->ucd = NULL;1728if(cdir->nr_files < cdir->untracked->untracked_nr) {1729struct untracked_cache_dir *d = cdir->untracked;1730 cdir->file = d->untracked[cdir->nr_files++];1731return0;1732}1733return-1;1734}17351736static voidclose_cached_dir(struct cached_dir *cdir)1737{1738if(cdir->fdir)1739closedir(cdir->fdir);1740/*1741 * We have gone through this directory and found no untracked1742 * entries. Mark it valid.1743 */1744if(cdir->untracked) {1745 cdir->untracked->valid =1;1746 cdir->untracked->recurse =1;1747}1748}17491750/*1751 * Read a directory tree. We currently ignore anything but1752 * directories, regular files and symlinks. That's because git1753 * doesn't handle them at all yet. Maybe that will change some1754 * day.1755 *1756 * Also, we ignore the name ".git" (even if it is not a directory).1757 * That likely will not change.1758 *1759 * Returns the most significant path_treatment value encountered in the scan.1760 */1761static enum path_treatment read_directory_recursive(struct dir_struct *dir,1762const char*base,int baselen,1763struct untracked_cache_dir *untracked,int check_only,1764const struct pathspec *pathspec)1765{1766struct cached_dir cdir;1767enum path_treatment state, subdir_state, dir_state = path_none;1768struct strbuf path = STRBUF_INIT;17691770strbuf_add(&path, base, baselen);17711772if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1773goto out;17741775if(untracked)1776 untracked->check_only = !!check_only;17771778while(!read_cached_dir(&cdir)) {1779/* check how the file or directory should be treated */1780 state =treat_path(dir, untracked, &cdir, &path,1781 baselen, pathspec);17821783if(state > dir_state)1784 dir_state = state;17851786/* recurse into subdir if instructed by treat_path */1787if((state == path_recurse) ||1788((state == path_untracked) &&1789(dir->flags & DIR_SHOW_IGNORED_TOO) &&1790(get_dtype(cdir.de, path.buf, path.len) == DT_DIR))) {1791struct untracked_cache_dir *ud;1792 ud =lookup_untracked(dir->untracked, untracked,1793 path.buf + baselen,1794 path.len - baselen);1795 subdir_state =1796read_directory_recursive(dir, path.buf,1797 path.len, ud,1798 check_only, pathspec);1799if(subdir_state > dir_state)1800 dir_state = subdir_state;1801}18021803if(check_only) {1804/* abort early if maximum state has been reached */1805if(dir_state == path_untracked) {1806if(cdir.fdir)1807add_untracked(untracked, path.buf + baselen);1808break;1809}1810/* skip the dir_add_* part */1811continue;1812}18131814/* add the path to the appropriate result list */1815switch(state) {1816case path_excluded:1817if(dir->flags & DIR_SHOW_IGNORED)1818dir_add_name(dir, path.buf, path.len);1819else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1820((dir->flags & DIR_COLLECT_IGNORED) &&1821exclude_matches_pathspec(path.buf, path.len,1822 pathspec)))1823dir_add_ignored(dir, path.buf, path.len);1824break;18251826case path_untracked:1827if(dir->flags & DIR_SHOW_IGNORED)1828break;1829dir_add_name(dir, path.buf, path.len);1830if(cdir.fdir)1831add_untracked(untracked, path.buf + baselen);1832break;18331834default:1835break;1836}1837}1838close_cached_dir(&cdir);1839 out:1840strbuf_release(&path);18411842return dir_state;1843}18441845intcmp_dir_entry(const void*p1,const void*p2)1846{1847const struct dir_entry *e1 = *(const struct dir_entry **)p1;1848const struct dir_entry *e2 = *(const struct dir_entry **)p2;18491850returnname_compare(e1->name, e1->len, e2->name, e2->len);1851}18521853/* check if *out lexically strictly contains *in */1854intcheck_dir_entry_contains(const struct dir_entry *out,const struct dir_entry *in)1855{1856return(out->len < in->len) &&1857(out->name[out->len -1] =='/') &&1858!memcmp(out->name, in->name, out->len);1859}18601861static inttreat_leading_path(struct dir_struct *dir,1862const char*path,int len,1863const struct pathspec *pathspec)1864{1865struct strbuf sb = STRBUF_INIT;1866int baselen, rc =0;1867const char*cp;1868int old_flags = dir->flags;18691870while(len && path[len -1] =='/')1871 len--;1872if(!len)1873return1;1874 baselen =0;1875 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1876while(1) {1877 cp = path + baselen + !!baselen;1878 cp =memchr(cp,'/', path + len - cp);1879if(!cp)1880 baselen = len;1881else1882 baselen = cp - path;1883strbuf_setlen(&sb,0);1884strbuf_add(&sb, path, baselen);1885if(!is_directory(sb.buf))1886break;1887if(simplify_away(sb.buf, sb.len, pathspec))1888break;1889if(treat_one_path(dir, NULL, &sb, baselen, pathspec,1890 DT_DIR, NULL) == path_none)1891break;/* do not recurse into it */1892if(len <= baselen) {1893 rc =1;1894break;/* finished checking */1895}1896}1897strbuf_release(&sb);1898 dir->flags = old_flags;1899return rc;1900}19011902static const char*get_ident_string(void)1903{1904static struct strbuf sb = STRBUF_INIT;1905struct utsname uts;19061907if(sb.len)1908return sb.buf;1909if(uname(&uts) <0)1910die_errno(_("failed to get kernel name and information"));1911strbuf_addf(&sb,"Location%s, system%s",get_git_work_tree(),1912 uts.sysname);1913return sb.buf;1914}19151916static intident_in_untracked(const struct untracked_cache *uc)1917{1918/*1919 * Previous git versions may have saved many NUL separated1920 * strings in the "ident" field, but it is insane to manage1921 * many locations, so just take care of the first one.1922 */19231924return!strcmp(uc->ident.buf,get_ident_string());1925}19261927static voidset_untracked_ident(struct untracked_cache *uc)1928{1929strbuf_reset(&uc->ident);1930strbuf_addstr(&uc->ident,get_ident_string());19311932/*1933 * This strbuf used to contain a list of NUL separated1934 * strings, so save NUL too for backward compatibility.1935 */1936strbuf_addch(&uc->ident,0);1937}19381939static voidnew_untracked_cache(struct index_state *istate)1940{1941struct untracked_cache *uc =xcalloc(1,sizeof(*uc));1942strbuf_init(&uc->ident,100);1943 uc->exclude_per_dir =".gitignore";1944/* should be the same flags used by git-status */1945 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;1946set_untracked_ident(uc);1947 istate->untracked = uc;1948 istate->cache_changed |= UNTRACKED_CHANGED;1949}19501951voidadd_untracked_cache(struct index_state *istate)1952{1953if(!istate->untracked) {1954new_untracked_cache(istate);1955}else{1956if(!ident_in_untracked(istate->untracked)) {1957free_untracked_cache(istate->untracked);1958new_untracked_cache(istate);1959}1960}1961}19621963voidremove_untracked_cache(struct index_state *istate)1964{1965if(istate->untracked) {1966free_untracked_cache(istate->untracked);1967 istate->untracked = NULL;1968 istate->cache_changed |= UNTRACKED_CHANGED;1969}1970}19711972static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1973int base_len,1974const struct pathspec *pathspec)1975{1976struct untracked_cache_dir *root;19771978if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))1979return NULL;19801981/*1982 * We only support $GIT_DIR/info/exclude and core.excludesfile1983 * as the global ignore rule files. Any other additions1984 * (e.g. from command line) invalidate the cache. This1985 * condition also catches running setup_standard_excludes()1986 * before setting dir->untracked!1987 */1988if(dir->unmanaged_exclude_files)1989return NULL;19901991/*1992 * Optimize for the main use case only: whole-tree git1993 * status. More work involved in treat_leading_path() if we1994 * use cache on just a subset of the worktree. pathspec1995 * support could make the matter even worse.1996 */1997if(base_len || (pathspec && pathspec->nr))1998return NULL;19992000/* Different set of flags may produce different results */2001if(dir->flags != dir->untracked->dir_flags ||2002/*2003 * See treat_directory(), case index_nonexistent. Without2004 * this flag, we may need to also cache .git file content2005 * for the resolve_gitlink_ref() call, which we don't.2006 */2007!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||2008/* We don't support collecting ignore files */2009(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |2010 DIR_COLLECT_IGNORED)))2011return NULL;20122013/*2014 * If we use .gitignore in the cache and now you change it to2015 * .gitexclude, everything will go wrong.2016 */2017if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&2018strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))2019return NULL;20202021/*2022 * EXC_CMDL is not considered in the cache. If people set it,2023 * skip the cache.2024 */2025if(dir->exclude_list_group[EXC_CMDL].nr)2026return NULL;20272028if(!ident_in_untracked(dir->untracked)) {2029warning(_("Untracked cache is disabled on this system or location."));2030return NULL;2031}20322033if(!dir->untracked->root) {2034const int len =sizeof(*dir->untracked->root);2035 dir->untracked->root =xmalloc(len);2036memset(dir->untracked->root,0, len);2037}20382039/* Validate $GIT_DIR/info/exclude and core.excludesfile */2040 root = dir->untracked->root;2041if(hashcmp(dir->ss_info_exclude.sha1,2042 dir->untracked->ss_info_exclude.sha1)) {2043invalidate_gitignore(dir->untracked, root);2044 dir->untracked->ss_info_exclude = dir->ss_info_exclude;2045}2046if(hashcmp(dir->ss_excludes_file.sha1,2047 dir->untracked->ss_excludes_file.sha1)) {2048invalidate_gitignore(dir->untracked, root);2049 dir->untracked->ss_excludes_file = dir->ss_excludes_file;2050}20512052/* Make sure this directory is not dropped out at saving phase */2053 root->recurse =1;2054return root;2055}20562057intread_directory(struct dir_struct *dir,const char*path,2058int len,const struct pathspec *pathspec)2059{2060struct untracked_cache_dir *untracked;20612062if(has_symlink_leading_path(path, len))2063return dir->nr;20642065 untracked =validate_untracked_cache(dir, len, pathspec);2066if(!untracked)2067/*2068 * make sure untracked cache code path is disabled,2069 * e.g. prep_exclude()2070 */2071 dir->untracked = NULL;2072if(!len ||treat_leading_path(dir, path, len, pathspec))2073read_directory_recursive(dir, path, len, untracked,0, pathspec);2074QSORT(dir->entries, dir->nr, cmp_dir_entry);2075QSORT(dir->ignored, dir->ignored_nr, cmp_dir_entry);20762077/*2078 * If DIR_SHOW_IGNORED_TOO is set, read_directory_recursive() will2079 * also pick up untracked contents of untracked dirs; by default2080 * we discard these, but given DIR_KEEP_UNTRACKED_CONTENTS we do not.2081 */2082if((dir->flags & DIR_SHOW_IGNORED_TOO) &&2083!(dir->flags & DIR_KEEP_UNTRACKED_CONTENTS)) {2084int i, j;20852086/* remove from dir->entries untracked contents of untracked dirs */2087for(i = j =0; j < dir->nr; j++) {2088if(i &&2089check_dir_entry_contains(dir->entries[i -1], dir->entries[j])) {2090free(dir->entries[j]);2091 dir->entries[j] = NULL;2092}else{2093 dir->entries[i++] = dir->entries[j];2094}2095}20962097 dir->nr = i;2098}20992100if(dir->untracked) {2101static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);2102trace_printf_key(&trace_untracked_stats,2103"node creation:%u\n"2104"gitignore invalidation:%u\n"2105"directory invalidation:%u\n"2106"opendir:%u\n",2107 dir->untracked->dir_created,2108 dir->untracked->gitignore_invalidated,2109 dir->untracked->dir_invalidated,2110 dir->untracked->dir_opened);2111if(dir->untracked == the_index.untracked &&2112(dir->untracked->dir_opened ||2113 dir->untracked->gitignore_invalidated ||2114 dir->untracked->dir_invalidated))2115 the_index.cache_changed |= UNTRACKED_CHANGED;2116if(dir->untracked != the_index.untracked) {2117free(dir->untracked);2118 dir->untracked = NULL;2119}2120}2121return dir->nr;2122}21232124intfile_exists(const char*f)2125{2126struct stat sb;2127returnlstat(f, &sb) ==0;2128}21292130static intcmp_icase(char a,char b)2131{2132if(a == b)2133return0;2134if(ignore_case)2135returntoupper(a) -toupper(b);2136return a - b;2137}21382139/*2140 * Given two normalized paths (a trailing slash is ok), if subdir is2141 * outside dir, return -1. Otherwise return the offset in subdir that2142 * can be used as relative path to dir.2143 */2144intdir_inside_of(const char*subdir,const char*dir)2145{2146int offset =0;21472148assert(dir && subdir && *dir && *subdir);21492150while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2151 dir++;2152 subdir++;2153 offset++;2154}21552156/* hel[p]/me vs hel[l]/yeah */2157if(*dir && *subdir)2158return-1;21592160if(!*subdir)2161return!*dir ? offset : -1;/* same dir */21622163/* foo/[b]ar vs foo/[] */2164if(is_dir_sep(dir[-1]))2165returnis_dir_sep(subdir[-1]) ? offset : -1;21662167/* foo[/]bar vs foo[] */2168returnis_dir_sep(*subdir) ? offset +1: -1;2169}21702171intis_inside_dir(const char*dir)2172{2173char*cwd;2174int rc;21752176if(!dir)2177return0;21782179 cwd =xgetcwd();2180 rc = (dir_inside_of(cwd, dir) >=0);2181free(cwd);2182return rc;2183}21842185intis_empty_dir(const char*path)2186{2187DIR*dir =opendir(path);2188struct dirent *e;2189int ret =1;21902191if(!dir)2192return0;21932194while((e =readdir(dir)) != NULL)2195if(!is_dot_or_dotdot(e->d_name)) {2196 ret =0;2197break;2198}21992200closedir(dir);2201return ret;2202}22032204static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2205{2206DIR*dir;2207struct dirent *e;2208int ret =0, original_len = path->len, len, kept_down =0;2209int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2210int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2211unsigned char submodule_head[20];22122213if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2214!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2215/* Do not descend and nuke a nested git work tree. */2216if(kept_up)2217*kept_up =1;2218return0;2219}22202221 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2222 dir =opendir(path->buf);2223if(!dir) {2224if(errno == ENOENT)2225return keep_toplevel ? -1:0;2226else if(errno == EACCES && !keep_toplevel)2227/*2228 * An empty dir could be removable even if it2229 * is unreadable:2230 */2231returnrmdir(path->buf);2232else2233return-1;2234}2235strbuf_complete(path,'/');22362237 len = path->len;2238while((e =readdir(dir)) != NULL) {2239struct stat st;2240if(is_dot_or_dotdot(e->d_name))2241continue;22422243strbuf_setlen(path, len);2244strbuf_addstr(path, e->d_name);2245if(lstat(path->buf, &st)) {2246if(errno == ENOENT)2247/*2248 * file disappeared, which is what we2249 * wanted anyway2250 */2251continue;2252/* fall thru */2253}else if(S_ISDIR(st.st_mode)) {2254if(!remove_dir_recurse(path, flag, &kept_down))2255continue;/* happy */2256}else if(!only_empty &&2257(!unlink(path->buf) || errno == ENOENT)) {2258continue;/* happy, too */2259}22602261/* path too long, stat fails, or non-directory still exists */2262 ret = -1;2263break;2264}2265closedir(dir);22662267strbuf_setlen(path, original_len);2268if(!ret && !keep_toplevel && !kept_down)2269 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2270else if(kept_up)2271/*2272 * report the uplevel that it is not an error that we2273 * did not rmdir() our directory.2274 */2275*kept_up = !ret;2276return ret;2277}22782279intremove_dir_recursively(struct strbuf *path,int flag)2280{2281returnremove_dir_recurse(path, flag, NULL);2282}22832284staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")22852286voidsetup_standard_excludes(struct dir_struct *dir)2287{2288 dir->exclude_per_dir =".gitignore";22892290/* core.excludefile defaulting to $XDG_HOME/git/ignore */2291if(!excludes_file)2292 excludes_file =xdg_config_home("ignore");2293if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2294add_excludes_from_file_1(dir, excludes_file,2295 dir->untracked ? &dir->ss_excludes_file : NULL);22962297/* per repository user preference */2298if(startup_info->have_repository) {2299const char*path =git_path_info_exclude();2300if(!access_or_warn(path, R_OK,0))2301add_excludes_from_file_1(dir, path,2302 dir->untracked ? &dir->ss_info_exclude : NULL);2303}2304}23052306intremove_path(const char*name)2307{2308char*slash;23092310if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2311return-1;23122313 slash =strrchr(name,'/');2314if(slash) {2315char*dirs =xstrdup(name);2316 slash = dirs + (slash - name);2317do{2318*slash ='\0';2319}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2320free(dirs);2321}2322return0;2323}23242325/*2326 * Frees memory within dir which was allocated for exclude lists and2327 * the exclude_stack. Does not free dir itself.2328 */2329voidclear_directory(struct dir_struct *dir)2330{2331int i, j;2332struct exclude_list_group *group;2333struct exclude_list *el;2334struct exclude_stack *stk;23352336for(i = EXC_CMDL; i <= EXC_FILE; i++) {2337 group = &dir->exclude_list_group[i];2338for(j =0; j < group->nr; j++) {2339 el = &group->el[j];2340if(i == EXC_DIRS)2341free((char*)el->src);2342clear_exclude_list(el);2343}2344free(group->el);2345}23462347 stk = dir->exclude_stack;2348while(stk) {2349struct exclude_stack *prev = stk->prev;2350free(stk);2351 stk = prev;2352}2353strbuf_release(&dir->basebuf);2354}23552356struct ondisk_untracked_cache {2357struct stat_data info_exclude_stat;2358struct stat_data excludes_file_stat;2359uint32_t dir_flags;2360unsigned char info_exclude_sha1[20];2361unsigned char excludes_file_sha1[20];2362char exclude_per_dir[FLEX_ARRAY];2363};23642365#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)23662367struct write_data {2368int index;/* number of written untracked_cache_dir */2369struct ewah_bitmap *check_only;/* from untracked_cache_dir */2370struct ewah_bitmap *valid;/* from untracked_cache_dir */2371struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2372struct strbuf out;2373struct strbuf sb_stat;2374struct strbuf sb_sha1;2375};23762377static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2378{2379 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2380 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2381 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2382 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2383 to->sd_dev =htonl(from->sd_dev);2384 to->sd_ino =htonl(from->sd_ino);2385 to->sd_uid =htonl(from->sd_uid);2386 to->sd_gid =htonl(from->sd_gid);2387 to->sd_size =htonl(from->sd_size);2388}23892390static voidwrite_one_dir(struct untracked_cache_dir *untracked,2391struct write_data *wd)2392{2393struct stat_data stat_data;2394struct strbuf *out = &wd->out;2395unsigned char intbuf[16];2396unsigned int intlen, value;2397int i = wd->index++;23982399/*2400 * untracked_nr should be reset whenever valid is clear, but2401 * for safety..2402 */2403if(!untracked->valid) {2404 untracked->untracked_nr =0;2405 untracked->check_only =0;2406}24072408if(untracked->check_only)2409ewah_set(wd->check_only, i);2410if(untracked->valid) {2411ewah_set(wd->valid, i);2412stat_data_to_disk(&stat_data, &untracked->stat_data);2413strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2414}2415if(!is_null_sha1(untracked->exclude_sha1)) {2416ewah_set(wd->sha1_valid, i);2417strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2418}24192420 intlen =encode_varint(untracked->untracked_nr, intbuf);2421strbuf_add(out, intbuf, intlen);24222423/* skip non-recurse directories */2424for(i =0, value =0; i < untracked->dirs_nr; i++)2425if(untracked->dirs[i]->recurse)2426 value++;2427 intlen =encode_varint(value, intbuf);2428strbuf_add(out, intbuf, intlen);24292430strbuf_add(out, untracked->name,strlen(untracked->name) +1);24312432for(i =0; i < untracked->untracked_nr; i++)2433strbuf_add(out, untracked->untracked[i],2434strlen(untracked->untracked[i]) +1);24352436for(i =0; i < untracked->dirs_nr; i++)2437if(untracked->dirs[i]->recurse)2438write_one_dir(untracked->dirs[i], wd);2439}24402441voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2442{2443struct ondisk_untracked_cache *ouc;2444struct write_data wd;2445unsigned char varbuf[16];2446int varint_len;2447size_t len =strlen(untracked->exclude_per_dir);24482449FLEX_ALLOC_MEM(ouc, exclude_per_dir, untracked->exclude_per_dir, len);2450stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2451stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2452hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2453hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2454 ouc->dir_flags =htonl(untracked->dir_flags);24552456 varint_len =encode_varint(untracked->ident.len, varbuf);2457strbuf_add(out, varbuf, varint_len);2458strbuf_addbuf(out, &untracked->ident);24592460strbuf_add(out, ouc,ouc_size(len));2461free(ouc);2462 ouc = NULL;24632464if(!untracked->root) {2465 varint_len =encode_varint(0, varbuf);2466strbuf_add(out, varbuf, varint_len);2467return;2468}24692470 wd.index =0;2471 wd.check_only =ewah_new();2472 wd.valid =ewah_new();2473 wd.sha1_valid =ewah_new();2474strbuf_init(&wd.out,1024);2475strbuf_init(&wd.sb_stat,1024);2476strbuf_init(&wd.sb_sha1,1024);2477write_one_dir(untracked->root, &wd);24782479 varint_len =encode_varint(wd.index, varbuf);2480strbuf_add(out, varbuf, varint_len);2481strbuf_addbuf(out, &wd.out);2482ewah_serialize_strbuf(wd.valid, out);2483ewah_serialize_strbuf(wd.check_only, out);2484ewah_serialize_strbuf(wd.sha1_valid, out);2485strbuf_addbuf(out, &wd.sb_stat);2486strbuf_addbuf(out, &wd.sb_sha1);2487strbuf_addch(out,'\0');/* safe guard for string lists */24882489ewah_free(wd.valid);2490ewah_free(wd.check_only);2491ewah_free(wd.sha1_valid);2492strbuf_release(&wd.out);2493strbuf_release(&wd.sb_stat);2494strbuf_release(&wd.sb_sha1);2495}24962497static voidfree_untracked(struct untracked_cache_dir *ucd)2498{2499int i;2500if(!ucd)2501return;2502for(i =0; i < ucd->dirs_nr; i++)2503free_untracked(ucd->dirs[i]);2504for(i =0; i < ucd->untracked_nr; i++)2505free(ucd->untracked[i]);2506free(ucd->untracked);2507free(ucd->dirs);2508free(ucd);2509}25102511voidfree_untracked_cache(struct untracked_cache *uc)2512{2513if(uc)2514free_untracked(uc->root);2515free(uc);2516}25172518struct read_data {2519int index;2520struct untracked_cache_dir **ucd;2521struct ewah_bitmap *check_only;2522struct ewah_bitmap *valid;2523struct ewah_bitmap *sha1_valid;2524const unsigned char*data;2525const unsigned char*end;2526};25272528static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2529{2530 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2531 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2532 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2533 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2534 to->sd_dev =get_be32(&from->sd_dev);2535 to->sd_ino =get_be32(&from->sd_ino);2536 to->sd_uid =get_be32(&from->sd_uid);2537 to->sd_gid =get_be32(&from->sd_gid);2538 to->sd_size =get_be32(&from->sd_size);2539}25402541static intread_one_dir(struct untracked_cache_dir **untracked_,2542struct read_data *rd)2543{2544struct untracked_cache_dir ud, *untracked;2545const unsigned char*next, *data = rd->data, *end = rd->end;2546unsigned int value;2547int i, len;25482549memset(&ud,0,sizeof(ud));25502551 next = data;2552 value =decode_varint(&next);2553if(next > end)2554return-1;2555 ud.recurse =1;2556 ud.untracked_alloc = value;2557 ud.untracked_nr = value;2558if(ud.untracked_nr)2559ALLOC_ARRAY(ud.untracked, ud.untracked_nr);2560 data = next;25612562 next = data;2563 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2564if(next > end)2565return-1;2566ALLOC_ARRAY(ud.dirs, ud.dirs_nr);2567 data = next;25682569 len =strlen((const char*)data);2570 next = data + len +1;2571if(next > rd->end)2572return-1;2573*untracked_ = untracked =xmalloc(st_add(sizeof(*untracked), len));2574memcpy(untracked, &ud,sizeof(ud));2575memcpy(untracked->name, data, len +1);2576 data = next;25772578for(i =0; i < untracked->untracked_nr; i++) {2579 len =strlen((const char*)data);2580 next = data + len +1;2581if(next > rd->end)2582return-1;2583 untracked->untracked[i] =xstrdup((const char*)data);2584 data = next;2585}25862587 rd->ucd[rd->index++] = untracked;2588 rd->data = data;25892590for(i =0; i < untracked->dirs_nr; i++) {2591 len =read_one_dir(untracked->dirs + i, rd);2592if(len <0)2593return-1;2594}2595return0;2596}25972598static voidset_check_only(size_t pos,void*cb)2599{2600struct read_data *rd = cb;2601struct untracked_cache_dir *ud = rd->ucd[pos];2602 ud->check_only =1;2603}26042605static voidread_stat(size_t pos,void*cb)2606{2607struct read_data *rd = cb;2608struct untracked_cache_dir *ud = rd->ucd[pos];2609if(rd->data +sizeof(struct stat_data) > rd->end) {2610 rd->data = rd->end +1;2611return;2612}2613stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2614 rd->data +=sizeof(struct stat_data);2615 ud->valid =1;2616}26172618static voidread_sha1(size_t pos,void*cb)2619{2620struct read_data *rd = cb;2621struct untracked_cache_dir *ud = rd->ucd[pos];2622if(rd->data +20> rd->end) {2623 rd->data = rd->end +1;2624return;2625}2626hashcpy(ud->exclude_sha1, rd->data);2627 rd->data +=20;2628}26292630static voidload_sha1_stat(struct sha1_stat *sha1_stat,2631const struct stat_data *stat,2632const unsigned char*sha1)2633{2634stat_data_from_disk(&sha1_stat->stat, stat);2635hashcpy(sha1_stat->sha1, sha1);2636 sha1_stat->valid =1;2637}26382639struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2640{2641const struct ondisk_untracked_cache *ouc;2642struct untracked_cache *uc;2643struct read_data rd;2644const unsigned char*next = data, *end = (const unsigned char*)data + sz;2645const char*ident;2646int ident_len, len;26472648if(sz <=1|| end[-1] !='\0')2649return NULL;2650 end--;26512652 ident_len =decode_varint(&next);2653if(next + ident_len > end)2654return NULL;2655 ident = (const char*)next;2656 next += ident_len;26572658 ouc = (const struct ondisk_untracked_cache *)next;2659if(next +ouc_size(0) > end)2660return NULL;26612662 uc =xcalloc(1,sizeof(*uc));2663strbuf_init(&uc->ident, ident_len);2664strbuf_add(&uc->ident, ident, ident_len);2665load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2666 ouc->info_exclude_sha1);2667load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2668 ouc->excludes_file_sha1);2669 uc->dir_flags =get_be32(&ouc->dir_flags);2670 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2671/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2672 next +=ouc_size(strlen(ouc->exclude_per_dir));2673if(next >= end)2674goto done2;26752676 len =decode_varint(&next);2677if(next > end || len ==0)2678goto done2;26792680 rd.valid =ewah_new();2681 rd.check_only =ewah_new();2682 rd.sha1_valid =ewah_new();2683 rd.data = next;2684 rd.end = end;2685 rd.index =0;2686ALLOC_ARRAY(rd.ucd, len);26872688if(read_one_dir(&uc->root, &rd) || rd.index != len)2689goto done;26902691 next = rd.data;2692 len =ewah_read_mmap(rd.valid, next, end - next);2693if(len <0)2694goto done;26952696 next += len;2697 len =ewah_read_mmap(rd.check_only, next, end - next);2698if(len <0)2699goto done;27002701 next += len;2702 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2703if(len <0)2704goto done;27052706ewah_each_bit(rd.check_only, set_check_only, &rd);2707 rd.data = next + len;2708ewah_each_bit(rd.valid, read_stat, &rd);2709ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2710 next = rd.data;27112712done:2713free(rd.ucd);2714ewah_free(rd.valid);2715ewah_free(rd.check_only);2716ewah_free(rd.sha1_valid);2717done2:2718if(next != end) {2719free_untracked_cache(uc);2720 uc = NULL;2721}2722return uc;2723}27242725static voidinvalidate_one_directory(struct untracked_cache *uc,2726struct untracked_cache_dir *ucd)2727{2728 uc->dir_invalidated++;2729 ucd->valid =0;2730 ucd->untracked_nr =0;2731}27322733/*2734 * Normally when an entry is added or removed from a directory,2735 * invalidating that directory is enough. No need to touch its2736 * ancestors. When a directory is shown as "foo/bar/" in git-status2737 * however, deleting or adding an entry may have cascading effect.2738 *2739 * Say the "foo/bar/file" has become untracked, we need to tell the2740 * untracked_cache_dir of "foo" that "bar/" is not an untracked2741 * directory any more (because "bar" is managed by foo as an untracked2742 * "file").2743 *2744 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2745 * was the last untracked entry in the entire "foo", we should show2746 * "foo/" instead. Which means we have to invalidate past "bar" up to2747 * "foo".2748 *2749 * This function traverses all directories from root to leaf. If there2750 * is a chance of one of the above cases happening, we invalidate back2751 * to root. Otherwise we just invalidate the leaf. There may be a more2752 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2753 * detect these cases and avoid unnecessary invalidation, for example,2754 * checking for the untracked entry named "bar/" in "foo", but for now2755 * stick to something safe and simple.2756 */2757static intinvalidate_one_component(struct untracked_cache *uc,2758struct untracked_cache_dir *dir,2759const char*path,int len)2760{2761const char*rest =strchr(path,'/');27622763if(rest) {2764int component_len = rest - path;2765struct untracked_cache_dir *d =2766lookup_untracked(uc, dir, path, component_len);2767int ret =2768invalidate_one_component(uc, d, rest +1,2769 len - (component_len +1));2770if(ret)2771invalidate_one_directory(uc, dir);2772return ret;2773}27742775invalidate_one_directory(uc, dir);2776return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2777}27782779voiduntracked_cache_invalidate_path(struct index_state *istate,2780const char*path)2781{2782if(!istate->untracked || !istate->untracked->root)2783return;2784invalidate_one_component(istate->untracked, istate->untracked->root,2785 path,strlen(path));2786}27872788voiduntracked_cache_remove_from_index(struct index_state *istate,2789const char*path)2790{2791untracked_cache_invalidate_path(istate, path);2792}27932794voiduntracked_cache_add_to_index(struct index_state *istate,2795const char*path)2796{2797untracked_cache_invalidate_path(istate, path);2798}27992800/* Update gitfile and core.worktree setting to connect work tree and git dir */2801voidconnect_work_tree_and_git_dir(const char*work_tree_,const char*git_dir_)2802{2803struct strbuf gitfile_sb = STRBUF_INIT;2804struct strbuf cfg_sb = STRBUF_INIT;2805struct strbuf rel_path = STRBUF_INIT;2806char*git_dir, *work_tree;28072808/* Prepare .git file */2809strbuf_addf(&gitfile_sb,"%s/.git", work_tree_);2810if(safe_create_leading_directories_const(gitfile_sb.buf))2811die(_("could not create directories for%s"), gitfile_sb.buf);28122813/* Prepare config file */2814strbuf_addf(&cfg_sb,"%s/config", git_dir_);2815if(safe_create_leading_directories_const(cfg_sb.buf))2816die(_("could not create directories for%s"), cfg_sb.buf);28172818 git_dir =real_pathdup(git_dir_,1);2819 work_tree =real_pathdup(work_tree_,1);28202821/* Write .git file */2822write_file(gitfile_sb.buf,"gitdir:%s",2823relative_path(git_dir, work_tree, &rel_path));2824/* Update core.worktree setting */2825git_config_set_in_file(cfg_sb.buf,"core.worktree",2826relative_path(work_tree, git_dir, &rel_path));28272828strbuf_release(&gitfile_sb);2829strbuf_release(&cfg_sb);2830strbuf_release(&rel_path);2831free(work_tree);2832free(git_dir);2833}28342835/*2836 * Migrate the git directory of the given path from old_git_dir to new_git_dir.2837 */2838voidrelocate_gitdir(const char*path,const char*old_git_dir,const char*new_git_dir)2839{2840if(rename(old_git_dir, new_git_dir) <0)2841die_errno(_("could not migrate git directory from '%s' to '%s'"),2842 old_git_dir, new_git_dir);28432844connect_work_tree_and_git_dir(path, new_git_dir);2845}