1/* 2 * This handles recursive filename detection with exclude 3 * files, index knowledge etc.. 4 * 5 * See Documentation/technical/api-directory-listing.txt 6 * 7 * Copyright (C) Linus Torvalds, 2005-2006 8 * Junio Hamano, 2005-2006 9 */ 10#include"cache.h" 11#include"dir.h" 12#include"refs.h" 13#include"wildmatch.h" 14#include"pathspec.h" 15#include"utf8.h" 16#include"varint.h" 17#include"ewah/ewok.h" 18 19/* 20 * Tells read_directory_recursive how a file or directory should be treated. 21 * Values are ordered by significance, e.g. if a directory contains both 22 * excluded and untracked files, it is listed as untracked because 23 * path_untracked > path_excluded. 24 */ 25enum path_treatment { 26 path_none =0, 27 path_recurse, 28 path_excluded, 29 path_untracked 30}; 31 32/* 33 * Support data structure for our opendir/readdir/closedir wrappers 34 */ 35struct cached_dir { 36DIR*fdir; 37struct untracked_cache_dir *untracked; 38int nr_files; 39int nr_dirs; 40 41struct dirent *de; 42const char*file; 43struct untracked_cache_dir *ucd; 44}; 45 46static enum path_treatment read_directory_recursive(struct dir_struct *dir, 47const char*path,int len,struct untracked_cache_dir *untracked, 48int check_only,const struct pathspec *pathspec); 49static intget_dtype(struct dirent *de,const char*path,int len); 50 51intfspathcmp(const char*a,const char*b) 52{ 53return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 54} 55 56intfspathncmp(const char*a,const char*b,size_t count) 57{ 58return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 59} 60 61intgit_fnmatch(const struct pathspec_item *item, 62const char*pattern,const char*string, 63int prefix) 64{ 65if(prefix >0) { 66if(ps_strncmp(item, pattern, string, prefix)) 67return WM_NOMATCH; 68 pattern += prefix; 69 string += prefix; 70} 71if(item->flags & PATHSPEC_ONESTAR) { 72int pattern_len =strlen(++pattern); 73int string_len =strlen(string); 74return string_len < pattern_len || 75ps_strcmp(item, pattern, 76 string + string_len - pattern_len); 77} 78if(item->magic & PATHSPEC_GLOB) 79returnwildmatch(pattern, string, 80 WM_PATHNAME | 81(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 82 NULL); 83else 84/* wildmatch has not learned no FNM_PATHNAME mode yet */ 85returnwildmatch(pattern, string, 86 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 87 NULL); 88} 89 90static intfnmatch_icase_mem(const char*pattern,int patternlen, 91const char*string,int stringlen, 92int flags) 93{ 94int match_status; 95struct strbuf pat_buf = STRBUF_INIT; 96struct strbuf str_buf = STRBUF_INIT; 97const char*use_pat = pattern; 98const char*use_str = string; 99 100if(pattern[patternlen]) { 101strbuf_add(&pat_buf, pattern, patternlen); 102 use_pat = pat_buf.buf; 103} 104if(string[stringlen]) { 105strbuf_add(&str_buf, string, stringlen); 106 use_str = str_buf.buf; 107} 108 109if(ignore_case) 110 flags |= WM_CASEFOLD; 111 match_status =wildmatch(use_pat, use_str, flags, NULL); 112 113strbuf_release(&pat_buf); 114strbuf_release(&str_buf); 115 116return match_status; 117} 118 119static size_tcommon_prefix_len(const struct pathspec *pathspec) 120{ 121int n; 122size_t max =0; 123 124/* 125 * ":(icase)path" is treated as a pathspec full of 126 * wildcard. In other words, only prefix is considered common 127 * prefix. If the pathspec is abc/foo abc/bar, running in 128 * subdir xyz, the common prefix is still xyz, not xuz/abc as 129 * in non-:(icase). 130 */ 131GUARD_PATHSPEC(pathspec, 132 PATHSPEC_FROMTOP | 133 PATHSPEC_MAXDEPTH | 134 PATHSPEC_LITERAL | 135 PATHSPEC_GLOB | 136 PATHSPEC_ICASE | 137 PATHSPEC_EXCLUDE); 138 139for(n =0; n < pathspec->nr; n++) { 140size_t i =0, len =0, item_len; 141if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 142continue; 143if(pathspec->items[n].magic & PATHSPEC_ICASE) 144 item_len = pathspec->items[n].prefix; 145else 146 item_len = pathspec->items[n].nowildcard_len; 147while(i < item_len && (n ==0|| i < max)) { 148char c = pathspec->items[n].match[i]; 149if(c != pathspec->items[0].match[i]) 150break; 151if(c =='/') 152 len = i +1; 153 i++; 154} 155if(n ==0|| len < max) { 156 max = len; 157if(!max) 158break; 159} 160} 161return max; 162} 163 164/* 165 * Returns a copy of the longest leading path common among all 166 * pathspecs. 167 */ 168char*common_prefix(const struct pathspec *pathspec) 169{ 170unsigned long len =common_prefix_len(pathspec); 171 172return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 173} 174 175intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 176{ 177char*prefix; 178size_t prefix_len; 179 180/* 181 * Calculate common prefix for the pathspec, and 182 * use that to optimize the directory walk 183 */ 184 prefix =common_prefix(pathspec); 185 prefix_len = prefix ?strlen(prefix) :0; 186 187/* Read the directory and prune it */ 188read_directory(dir, prefix, prefix_len, pathspec); 189 190free(prefix); 191return prefix_len; 192} 193 194intwithin_depth(const char*name,int namelen, 195int depth,int max_depth) 196{ 197const char*cp = name, *cpe = name + namelen; 198 199while(cp < cpe) { 200if(*cp++ !='/') 201continue; 202 depth++; 203if(depth > max_depth) 204return0; 205} 206return1; 207} 208 209#define DO_MATCH_EXCLUDE (1<<0) 210#define DO_MATCH_DIRECTORY (1<<1) 211#define DO_MATCH_SUBMODULE (1<<2) 212 213/* 214 * Does 'match' match the given name? 215 * A match is found if 216 * 217 * (1) the 'match' string is leading directory of 'name', or 218 * (2) the 'match' string is a wildcard and matches 'name', or 219 * (3) the 'match' string is exactly the same as 'name'. 220 * 221 * and the return value tells which case it was. 222 * 223 * It returns 0 when there is no match. 224 */ 225static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 226const char*name,int namelen,unsigned flags) 227{ 228/* name/namelen has prefix cut off by caller */ 229const char*match = item->match + prefix; 230int matchlen = item->len - prefix; 231 232/* 233 * The normal call pattern is: 234 * 1. prefix = common_prefix_len(ps); 235 * 2. prune something, or fill_directory 236 * 3. match_pathspec() 237 * 238 * 'prefix' at #1 may be shorter than the command's prefix and 239 * it's ok for #2 to match extra files. Those extras will be 240 * trimmed at #3. 241 * 242 * Suppose the pathspec is 'foo' and '../bar' running from 243 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 244 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 245 * user does not want XYZ/foo, only the "foo" part should be 246 * case-insensitive. We need to filter out XYZ/foo here. In 247 * other words, we do not trust the caller on comparing the 248 * prefix part when :(icase) is involved. We do exact 249 * comparison ourselves. 250 * 251 * Normally the caller (common_prefix_len() in fact) does 252 * _exact_ matching on name[-prefix+1..-1] and we do not need 253 * to check that part. Be defensive and check it anyway, in 254 * case common_prefix_len is changed, or a new caller is 255 * introduced that does not use common_prefix_len. 256 * 257 * If the penalty turns out too high when prefix is really 258 * long, maybe change it to 259 * strncmp(match, name, item->prefix - prefix) 260 */ 261if(item->prefix && (item->magic & PATHSPEC_ICASE) && 262strncmp(item->match, name - prefix, item->prefix)) 263return0; 264 265/* If the match was just the prefix, we matched */ 266if(!*match) 267return MATCHED_RECURSIVELY; 268 269if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 270if(matchlen == namelen) 271return MATCHED_EXACTLY; 272 273if(match[matchlen-1] =='/'|| name[matchlen] =='/') 274return MATCHED_RECURSIVELY; 275}else if((flags & DO_MATCH_DIRECTORY) && 276 match[matchlen -1] =='/'&& 277 namelen == matchlen -1&& 278!ps_strncmp(item, match, name, namelen)) 279return MATCHED_EXACTLY; 280 281if(item->nowildcard_len < item->len && 282!git_fnmatch(item, match, name, 283 item->nowildcard_len - prefix)) 284return MATCHED_FNMATCH; 285 286/* Perform checks to see if "name" is a super set of the pathspec */ 287if(flags & DO_MATCH_SUBMODULE) { 288/* name is a literal prefix of the pathspec */ 289if((namelen < matchlen) && 290(match[namelen] =='/') && 291!ps_strncmp(item, match, name, namelen)) 292return MATCHED_RECURSIVELY; 293 294/* name" doesn't match up to the first wild character */ 295if(item->nowildcard_len < item->len && 296ps_strncmp(item, match, name, 297 item->nowildcard_len - prefix)) 298return0; 299 300/* 301 * Here is where we would perform a wildmatch to check if 302 * "name" can be matched as a directory (or a prefix) against 303 * the pathspec. Since wildmatch doesn't have this capability 304 * at the present we have to punt and say that it is a match, 305 * potentially returning a false positive 306 * The submodules themselves will be able to perform more 307 * accurate matching to determine if the pathspec matches. 308 */ 309return MATCHED_RECURSIVELY; 310} 311 312return0; 313} 314 315/* 316 * Given a name and a list of pathspecs, returns the nature of the 317 * closest (i.e. most specific) match of the name to any of the 318 * pathspecs. 319 * 320 * The caller typically calls this multiple times with the same 321 * pathspec and seen[] array but with different name/namelen 322 * (e.g. entries from the index) and is interested in seeing if and 323 * how each pathspec matches all the names it calls this function 324 * with. A mark is left in the seen[] array for each pathspec element 325 * indicating the closest type of match that element achieved, so if 326 * seen[n] remains zero after multiple invocations, that means the nth 327 * pathspec did not match any names, which could indicate that the 328 * user mistyped the nth pathspec. 329 */ 330static intdo_match_pathspec(const struct pathspec *ps, 331const char*name,int namelen, 332int prefix,char*seen, 333unsigned flags) 334{ 335int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 336 337GUARD_PATHSPEC(ps, 338 PATHSPEC_FROMTOP | 339 PATHSPEC_MAXDEPTH | 340 PATHSPEC_LITERAL | 341 PATHSPEC_GLOB | 342 PATHSPEC_ICASE | 343 PATHSPEC_EXCLUDE); 344 345if(!ps->nr) { 346if(!ps->recursive || 347!(ps->magic & PATHSPEC_MAXDEPTH) || 348 ps->max_depth == -1) 349return MATCHED_RECURSIVELY; 350 351if(within_depth(name, namelen,0, ps->max_depth)) 352return MATCHED_EXACTLY; 353else 354return0; 355} 356 357 name += prefix; 358 namelen -= prefix; 359 360for(i = ps->nr -1; i >=0; i--) { 361int how; 362 363if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 364( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 365continue; 366 367if(seen && seen[i] == MATCHED_EXACTLY) 368continue; 369/* 370 * Make exclude patterns optional and never report 371 * "pathspec ':(exclude)foo' matches no files" 372 */ 373if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 374 seen[i] = MATCHED_FNMATCH; 375 how =match_pathspec_item(ps->items+i, prefix, name, 376 namelen, flags); 377if(ps->recursive && 378(ps->magic & PATHSPEC_MAXDEPTH) && 379 ps->max_depth != -1&& 380 how && how != MATCHED_FNMATCH) { 381int len = ps->items[i].len; 382if(name[len] =='/') 383 len++; 384if(within_depth(name+len, namelen-len,0, ps->max_depth)) 385 how = MATCHED_EXACTLY; 386else 387 how =0; 388} 389if(how) { 390if(retval < how) 391 retval = how; 392if(seen && seen[i] < how) 393 seen[i] = how; 394} 395} 396return retval; 397} 398 399intmatch_pathspec(const struct pathspec *ps, 400const char*name,int namelen, 401int prefix,char*seen,int is_dir) 402{ 403int positive, negative; 404unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 405 positive =do_match_pathspec(ps, name, namelen, 406 prefix, seen, flags); 407if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 408return positive; 409 negative =do_match_pathspec(ps, name, namelen, 410 prefix, seen, 411 flags | DO_MATCH_EXCLUDE); 412return negative ?0: positive; 413} 414 415/** 416 * Check if a submodule is a superset of the pathspec 417 */ 418intsubmodule_path_match(const struct pathspec *ps, 419const char*submodule_name, 420char*seen) 421{ 422int matched =do_match_pathspec(ps, submodule_name, 423strlen(submodule_name), 4240, seen, 425 DO_MATCH_DIRECTORY | 426 DO_MATCH_SUBMODULE); 427return matched; 428} 429 430intreport_path_error(const char*ps_matched, 431const struct pathspec *pathspec, 432const char*prefix) 433{ 434/* 435 * Make sure all pathspec matched; otherwise it is an error. 436 */ 437int num, errors =0; 438for(num =0; num < pathspec->nr; num++) { 439int other, found_dup; 440 441if(ps_matched[num]) 442continue; 443/* 444 * The caller might have fed identical pathspec 445 * twice. Do not barf on such a mistake. 446 * FIXME: parse_pathspec should have eliminated 447 * duplicate pathspec. 448 */ 449for(found_dup = other =0; 450!found_dup && other < pathspec->nr; 451 other++) { 452if(other == num || !ps_matched[other]) 453continue; 454if(!strcmp(pathspec->items[other].original, 455 pathspec->items[num].original)) 456/* 457 * Ok, we have a match already. 458 */ 459 found_dup =1; 460} 461if(found_dup) 462continue; 463 464error("pathspec '%s' did not match any file(s) known to git.", 465 pathspec->items[num].original); 466 errors++; 467} 468return errors; 469} 470 471/* 472 * Return the length of the "simple" part of a path match limiter. 473 */ 474intsimple_length(const char*match) 475{ 476int len = -1; 477 478for(;;) { 479unsigned char c = *match++; 480 len++; 481if(c =='\0'||is_glob_special(c)) 482return len; 483} 484} 485 486intno_wildcard(const char*string) 487{ 488return string[simple_length(string)] =='\0'; 489} 490 491voidparse_exclude_pattern(const char**pattern, 492int*patternlen, 493unsigned*flags, 494int*nowildcardlen) 495{ 496const char*p = *pattern; 497size_t i, len; 498 499*flags =0; 500if(*p =='!') { 501*flags |= EXC_FLAG_NEGATIVE; 502 p++; 503} 504 len =strlen(p); 505if(len && p[len -1] =='/') { 506 len--; 507*flags |= EXC_FLAG_MUSTBEDIR; 508} 509for(i =0; i < len; i++) { 510if(p[i] =='/') 511break; 512} 513if(i == len) 514*flags |= EXC_FLAG_NODIR; 515*nowildcardlen =simple_length(p); 516/* 517 * we should have excluded the trailing slash from 'p' too, 518 * but that's one more allocation. Instead just make sure 519 * nowildcardlen does not exceed real patternlen 520 */ 521if(*nowildcardlen > len) 522*nowildcardlen = len; 523if(*p =='*'&&no_wildcard(p +1)) 524*flags |= EXC_FLAG_ENDSWITH; 525*pattern = p; 526*patternlen = len; 527} 528 529voidadd_exclude(const char*string,const char*base, 530int baselen,struct exclude_list *el,int srcpos) 531{ 532struct exclude *x; 533int patternlen; 534unsigned flags; 535int nowildcardlen; 536 537parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 538if(flags & EXC_FLAG_MUSTBEDIR) { 539FLEXPTR_ALLOC_MEM(x, pattern, string, patternlen); 540}else{ 541 x =xmalloc(sizeof(*x)); 542 x->pattern = string; 543} 544 x->patternlen = patternlen; 545 x->nowildcardlen = nowildcardlen; 546 x->base = base; 547 x->baselen = baselen; 548 x->flags = flags; 549 x->srcpos = srcpos; 550ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 551 el->excludes[el->nr++] = x; 552 x->el = el; 553} 554 555static void*read_skip_worktree_file_from_index(const char*path,size_t*size, 556struct sha1_stat *sha1_stat) 557{ 558int pos, len; 559unsigned long sz; 560enum object_type type; 561void*data; 562 563 len =strlen(path); 564 pos =cache_name_pos(path, len); 565if(pos <0) 566return NULL; 567if(!ce_skip_worktree(active_cache[pos])) 568return NULL; 569 data =read_sha1_file(active_cache[pos]->oid.hash, &type, &sz); 570if(!data || type != OBJ_BLOB) { 571free(data); 572return NULL; 573} 574*size =xsize_t(sz); 575if(sha1_stat) { 576memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 577hashcpy(sha1_stat->sha1, active_cache[pos]->oid.hash); 578} 579return data; 580} 581 582/* 583 * Frees memory within el which was allocated for exclude patterns and 584 * the file buffer. Does not free el itself. 585 */ 586voidclear_exclude_list(struct exclude_list *el) 587{ 588int i; 589 590for(i =0; i < el->nr; i++) 591free(el->excludes[i]); 592free(el->excludes); 593free(el->filebuf); 594 595memset(el,0,sizeof(*el)); 596} 597 598static voidtrim_trailing_spaces(char*buf) 599{ 600char*p, *last_space = NULL; 601 602for(p = buf; *p; p++) 603switch(*p) { 604case' ': 605if(!last_space) 606 last_space = p; 607break; 608case'\\': 609 p++; 610if(!*p) 611return; 612/* fallthrough */ 613default: 614 last_space = NULL; 615} 616 617if(last_space) 618*last_space ='\0'; 619} 620 621/* 622 * Given a subdirectory name and "dir" of the current directory, 623 * search the subdir in "dir" and return it, or create a new one if it 624 * does not exist in "dir". 625 * 626 * If "name" has the trailing slash, it'll be excluded in the search. 627 */ 628static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 629struct untracked_cache_dir *dir, 630const char*name,int len) 631{ 632int first, last; 633struct untracked_cache_dir *d; 634if(!dir) 635return NULL; 636if(len && name[len -1] =='/') 637 len--; 638 first =0; 639 last = dir->dirs_nr; 640while(last > first) { 641int cmp, next = (last + first) >>1; 642 d = dir->dirs[next]; 643 cmp =strncmp(name, d->name, len); 644if(!cmp &&strlen(d->name) > len) 645 cmp = -1; 646if(!cmp) 647return d; 648if(cmp <0) { 649 last = next; 650continue; 651} 652 first = next+1; 653} 654 655 uc->dir_created++; 656FLEX_ALLOC_MEM(d, name, name, len); 657 658ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 659memmove(dir->dirs + first +1, dir->dirs + first, 660(dir->dirs_nr - first) *sizeof(*dir->dirs)); 661 dir->dirs_nr++; 662 dir->dirs[first] = d; 663return d; 664} 665 666static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 667{ 668int i; 669 dir->valid =0; 670 dir->untracked_nr =0; 671for(i =0; i < dir->dirs_nr; i++) 672do_invalidate_gitignore(dir->dirs[i]); 673} 674 675static voidinvalidate_gitignore(struct untracked_cache *uc, 676struct untracked_cache_dir *dir) 677{ 678 uc->gitignore_invalidated++; 679do_invalidate_gitignore(dir); 680} 681 682static voidinvalidate_directory(struct untracked_cache *uc, 683struct untracked_cache_dir *dir) 684{ 685int i; 686 uc->dir_invalidated++; 687 dir->valid =0; 688 dir->untracked_nr =0; 689for(i =0; i < dir->dirs_nr; i++) 690 dir->dirs[i]->recurse =0; 691} 692 693/* 694 * Given a file with name "fname", read it (either from disk, or from 695 * the index if "check_index" is non-zero), parse it and store the 696 * exclude rules in "el". 697 * 698 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 699 * stat data from disk (only valid if add_excludes returns zero). If 700 * ss_valid is non-zero, "ss" must contain good value as input. 701 */ 702static intadd_excludes(const char*fname,const char*base,int baselen, 703struct exclude_list *el,int check_index, 704struct sha1_stat *sha1_stat) 705{ 706struct stat st; 707int fd, i, lineno =1; 708size_t size =0; 709char*buf, *entry; 710 711 fd =open(fname, O_RDONLY); 712if(fd <0||fstat(fd, &st) <0) { 713if(errno != ENOENT) 714warn_on_inaccessible(fname); 715if(0<= fd) 716close(fd); 717if(!check_index || 718(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 719return-1; 720if(size ==0) { 721free(buf); 722return0; 723} 724if(buf[size-1] !='\n') { 725 buf =xrealloc(buf,st_add(size,1)); 726 buf[size++] ='\n'; 727} 728}else{ 729 size =xsize_t(st.st_size); 730if(size ==0) { 731if(sha1_stat) { 732fill_stat_data(&sha1_stat->stat, &st); 733hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 734 sha1_stat->valid =1; 735} 736close(fd); 737return0; 738} 739 buf =xmallocz(size); 740if(read_in_full(fd, buf, size) != size) { 741free(buf); 742close(fd); 743return-1; 744} 745 buf[size++] ='\n'; 746close(fd); 747if(sha1_stat) { 748int pos; 749if(sha1_stat->valid && 750!match_stat_data_racy(&the_index, &sha1_stat->stat, &st)) 751;/* no content change, ss->sha1 still good */ 752else if(check_index && 753(pos =cache_name_pos(fname,strlen(fname))) >=0&& 754!ce_stage(active_cache[pos]) && 755ce_uptodate(active_cache[pos]) && 756!would_convert_to_git(fname)) 757hashcpy(sha1_stat->sha1, 758 active_cache[pos]->oid.hash); 759else 760hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 761fill_stat_data(&sha1_stat->stat, &st); 762 sha1_stat->valid =1; 763} 764} 765 766 el->filebuf = buf; 767 768if(skip_utf8_bom(&buf, size)) 769 size -= buf - el->filebuf; 770 771 entry = buf; 772 773for(i =0; i < size; i++) { 774if(buf[i] =='\n') { 775if(entry != buf + i && entry[0] !='#') { 776 buf[i - (i && buf[i-1] =='\r')] =0; 777trim_trailing_spaces(entry); 778add_exclude(entry, base, baselen, el, lineno); 779} 780 lineno++; 781 entry = buf + i +1; 782} 783} 784return0; 785} 786 787intadd_excludes_from_file_to_list(const char*fname,const char*base, 788int baselen,struct exclude_list *el, 789int check_index) 790{ 791returnadd_excludes(fname, base, baselen, el, check_index, NULL); 792} 793 794struct exclude_list *add_exclude_list(struct dir_struct *dir, 795int group_type,const char*src) 796{ 797struct exclude_list *el; 798struct exclude_list_group *group; 799 800 group = &dir->exclude_list_group[group_type]; 801ALLOC_GROW(group->el, group->nr +1, group->alloc); 802 el = &group->el[group->nr++]; 803memset(el,0,sizeof(*el)); 804 el->src = src; 805return el; 806} 807 808/* 809 * Used to set up core.excludesfile and .git/info/exclude lists. 810 */ 811static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 812struct sha1_stat *sha1_stat) 813{ 814struct exclude_list *el; 815/* 816 * catch setup_standard_excludes() that's called before 817 * dir->untracked is assigned. That function behaves 818 * differently when dir->untracked is non-NULL. 819 */ 820if(!dir->untracked) 821 dir->unmanaged_exclude_files++; 822 el =add_exclude_list(dir, EXC_FILE, fname); 823if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 824die("cannot use%sas an exclude file", fname); 825} 826 827voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 828{ 829 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 830add_excludes_from_file_1(dir, fname, NULL); 831} 832 833intmatch_basename(const char*basename,int basenamelen, 834const char*pattern,int prefix,int patternlen, 835unsigned flags) 836{ 837if(prefix == patternlen) { 838if(patternlen == basenamelen && 839!fspathncmp(pattern, basename, basenamelen)) 840return1; 841}else if(flags & EXC_FLAG_ENDSWITH) { 842/* "*literal" matching against "fooliteral" */ 843if(patternlen -1<= basenamelen && 844!fspathncmp(pattern +1, 845 basename + basenamelen - (patternlen -1), 846 patternlen -1)) 847return1; 848}else{ 849if(fnmatch_icase_mem(pattern, patternlen, 850 basename, basenamelen, 8510) ==0) 852return1; 853} 854return0; 855} 856 857intmatch_pathname(const char*pathname,int pathlen, 858const char*base,int baselen, 859const char*pattern,int prefix,int patternlen, 860unsigned flags) 861{ 862const char*name; 863int namelen; 864 865/* 866 * match with FNM_PATHNAME; the pattern has base implicitly 867 * in front of it. 868 */ 869if(*pattern =='/') { 870 pattern++; 871 patternlen--; 872 prefix--; 873} 874 875/* 876 * baselen does not count the trailing slash. base[] may or 877 * may not end with a trailing slash though. 878 */ 879if(pathlen < baselen +1|| 880(baselen && pathname[baselen] !='/') || 881fspathncmp(pathname, base, baselen)) 882return0; 883 884 namelen = baselen ? pathlen - baselen -1: pathlen; 885 name = pathname + pathlen - namelen; 886 887if(prefix) { 888/* 889 * if the non-wildcard part is longer than the 890 * remaining pathname, surely it cannot match. 891 */ 892if(prefix > namelen) 893return0; 894 895if(fspathncmp(pattern, name, prefix)) 896return0; 897 pattern += prefix; 898 patternlen -= prefix; 899 name += prefix; 900 namelen -= prefix; 901 902/* 903 * If the whole pattern did not have a wildcard, 904 * then our prefix match is all we need; we 905 * do not need to call fnmatch at all. 906 */ 907if(!patternlen && !namelen) 908return1; 909} 910 911returnfnmatch_icase_mem(pattern, patternlen, 912 name, namelen, 913 WM_PATHNAME) ==0; 914} 915 916/* 917 * Scan the given exclude list in reverse to see whether pathname 918 * should be ignored. The first match (i.e. the last on the list), if 919 * any, determines the fate. Returns the exclude_list element which 920 * matched, or NULL for undecided. 921 */ 922static struct exclude *last_exclude_matching_from_list(const char*pathname, 923int pathlen, 924const char*basename, 925int*dtype, 926struct exclude_list *el) 927{ 928struct exclude *exc = NULL;/* undecided */ 929int i; 930 931if(!el->nr) 932return NULL;/* undefined */ 933 934for(i = el->nr -1;0<= i; i--) { 935struct exclude *x = el->excludes[i]; 936const char*exclude = x->pattern; 937int prefix = x->nowildcardlen; 938 939if(x->flags & EXC_FLAG_MUSTBEDIR) { 940if(*dtype == DT_UNKNOWN) 941*dtype =get_dtype(NULL, pathname, pathlen); 942if(*dtype != DT_DIR) 943continue; 944} 945 946if(x->flags & EXC_FLAG_NODIR) { 947if(match_basename(basename, 948 pathlen - (basename - pathname), 949 exclude, prefix, x->patternlen, 950 x->flags)) { 951 exc = x; 952break; 953} 954continue; 955} 956 957assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 958if(match_pathname(pathname, pathlen, 959 x->base, x->baselen ? x->baselen -1:0, 960 exclude, prefix, x->patternlen, x->flags)) { 961 exc = x; 962break; 963} 964} 965return exc; 966} 967 968/* 969 * Scan the list and let the last match determine the fate. 970 * Return 1 for exclude, 0 for include and -1 for undecided. 971 */ 972intis_excluded_from_list(const char*pathname, 973int pathlen,const char*basename,int*dtype, 974struct exclude_list *el) 975{ 976struct exclude *exclude; 977 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 978if(exclude) 979return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 980return-1;/* undecided */ 981} 982 983static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 984const char*pathname,int pathlen,const char*basename, 985int*dtype_p) 986{ 987int i, j; 988struct exclude_list_group *group; 989struct exclude *exclude; 990for(i = EXC_CMDL; i <= EXC_FILE; i++) { 991 group = &dir->exclude_list_group[i]; 992for(j = group->nr -1; j >=0; j--) { 993 exclude =last_exclude_matching_from_list( 994 pathname, pathlen, basename, dtype_p, 995&group->el[j]); 996if(exclude) 997return exclude; 998} 999}1000return NULL;1001}10021003/*1004 * Loads the per-directory exclude list for the substring of base1005 * which has a char length of baselen.1006 */1007static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen)1008{1009struct exclude_list_group *group;1010struct exclude_list *el;1011struct exclude_stack *stk = NULL;1012struct untracked_cache_dir *untracked;1013int current;10141015 group = &dir->exclude_list_group[EXC_DIRS];10161017/*1018 * Pop the exclude lists from the EXCL_DIRS exclude_list_group1019 * which originate from directories not in the prefix of the1020 * path being checked.1021 */1022while((stk = dir->exclude_stack) != NULL) {1023if(stk->baselen <= baselen &&1024!strncmp(dir->basebuf.buf, base, stk->baselen))1025break;1026 el = &group->el[dir->exclude_stack->exclude_ix];1027 dir->exclude_stack = stk->prev;1028 dir->exclude = NULL;1029free((char*)el->src);/* see strbuf_detach() below */1030clear_exclude_list(el);1031free(stk);1032 group->nr--;1033}10341035/* Skip traversing into sub directories if the parent is excluded */1036if(dir->exclude)1037return;10381039/*1040 * Lazy initialization. All call sites currently just1041 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1042 * them seems lots of work for little benefit.1043 */1044if(!dir->basebuf.buf)1045strbuf_init(&dir->basebuf, PATH_MAX);10461047/* Read from the parent directories and push them down. */1048 current = stk ? stk->baselen : -1;1049strbuf_setlen(&dir->basebuf, current <0?0: current);1050if(dir->untracked)1051 untracked = stk ? stk->ucd : dir->untracked->root;1052else1053 untracked = NULL;10541055while(current < baselen) {1056const char*cp;1057struct sha1_stat sha1_stat;10581059 stk =xcalloc(1,sizeof(*stk));1060if(current <0) {1061 cp = base;1062 current =0;1063}else{1064 cp =strchr(base + current +1,'/');1065if(!cp)1066die("oops in prep_exclude");1067 cp++;1068 untracked =1069lookup_untracked(dir->untracked, untracked,1070 base + current,1071 cp - base - current);1072}1073 stk->prev = dir->exclude_stack;1074 stk->baselen = cp - base;1075 stk->exclude_ix = group->nr;1076 stk->ucd = untracked;1077 el =add_exclude_list(dir, EXC_DIRS, NULL);1078strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1079assert(stk->baselen == dir->basebuf.len);10801081/* Abort if the directory is excluded */1082if(stk->baselen) {1083int dt = DT_DIR;1084 dir->basebuf.buf[stk->baselen -1] =0;1085 dir->exclude =last_exclude_matching_from_lists(dir,1086 dir->basebuf.buf, stk->baselen -1,1087 dir->basebuf.buf + current, &dt);1088 dir->basebuf.buf[stk->baselen -1] ='/';1089if(dir->exclude &&1090 dir->exclude->flags & EXC_FLAG_NEGATIVE)1091 dir->exclude = NULL;1092if(dir->exclude) {1093 dir->exclude_stack = stk;1094return;1095}1096}10971098/* Try to read per-directory file */1099hashclr(sha1_stat.sha1);1100 sha1_stat.valid =0;1101if(dir->exclude_per_dir &&1102/*1103 * If we know that no files have been added in1104 * this directory (i.e. valid_cached_dir() has1105 * been executed and set untracked->valid) ..1106 */1107(!untracked || !untracked->valid ||1108/*1109 * .. and .gitignore does not exist before1110 * (i.e. null exclude_sha1). Then we can skip1111 * loading .gitignore, which would result in1112 * ENOENT anyway.1113 */1114!is_null_sha1(untracked->exclude_sha1))) {1115/*1116 * dir->basebuf gets reused by the traversal, but we1117 * need fname to remain unchanged to ensure the src1118 * member of each struct exclude correctly1119 * back-references its source file. Other invocations1120 * of add_exclude_list provide stable strings, so we1121 * strbuf_detach() and free() here in the caller.1122 */1123struct strbuf sb = STRBUF_INIT;1124strbuf_addbuf(&sb, &dir->basebuf);1125strbuf_addstr(&sb, dir->exclude_per_dir);1126 el->src =strbuf_detach(&sb, NULL);1127add_excludes(el->src, el->src, stk->baselen, el,1,1128 untracked ? &sha1_stat : NULL);1129}1130/*1131 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1132 * will first be called in valid_cached_dir() then maybe many1133 * times more in last_exclude_matching(). When the cache is1134 * used, last_exclude_matching() will not be called and1135 * reading .gitignore content will be a waste.1136 *1137 * So when it's called by valid_cached_dir() and we can get1138 * .gitignore SHA-1 from the index (i.e. .gitignore is not1139 * modified on work tree), we could delay reading the1140 * .gitignore content until we absolutely need it in1141 * last_exclude_matching(). Be careful about ignore rule1142 * order, though, if you do that.1143 */1144if(untracked &&1145hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1146invalidate_gitignore(dir->untracked, untracked);1147hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1148}1149 dir->exclude_stack = stk;1150 current = stk->baselen;1151}1152strbuf_setlen(&dir->basebuf, baselen);1153}11541155/*1156 * Loads the exclude lists for the directory containing pathname, then1157 * scans all exclude lists to determine whether pathname is excluded.1158 * Returns the exclude_list element which matched, or NULL for1159 * undecided.1160 */1161struct exclude *last_exclude_matching(struct dir_struct *dir,1162const char*pathname,1163int*dtype_p)1164{1165int pathlen =strlen(pathname);1166const char*basename =strrchr(pathname,'/');1167 basename = (basename) ? basename+1: pathname;11681169prep_exclude(dir, pathname, basename-pathname);11701171if(dir->exclude)1172return dir->exclude;11731174returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1175 basename, dtype_p);1176}11771178/*1179 * Loads the exclude lists for the directory containing pathname, then1180 * scans all exclude lists to determine whether pathname is excluded.1181 * Returns 1 if true, otherwise 0.1182 */1183intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1184{1185struct exclude *exclude =1186last_exclude_matching(dir, pathname, dtype_p);1187if(exclude)1188return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1189return0;1190}11911192static struct dir_entry *dir_entry_new(const char*pathname,int len)1193{1194struct dir_entry *ent;11951196FLEX_ALLOC_MEM(ent, name, pathname, len);1197 ent->len = len;1198return ent;1199}12001201static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1202{1203if(cache_file_exists(pathname, len, ignore_case))1204return NULL;12051206ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1207return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1208}12091210struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1211{1212if(!cache_name_is_other(pathname, len))1213return NULL;12141215ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1216return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1217}12181219enum exist_status {1220 index_nonexistent =0,1221 index_directory,1222 index_gitdir1223};12241225/*1226 * Do not use the alphabetically sorted index to look up1227 * the directory name; instead, use the case insensitive1228 * directory hash.1229 */1230static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1231{1232struct cache_entry *ce;12331234if(cache_dir_exists(dirname, len))1235return index_directory;12361237 ce =cache_file_exists(dirname, len, ignore_case);1238if(ce &&S_ISGITLINK(ce->ce_mode))1239return index_gitdir;12401241return index_nonexistent;1242}12431244/*1245 * The index sorts alphabetically by entry name, which1246 * means that a gitlink sorts as '\0' at the end, while1247 * a directory (which is defined not as an entry, but as1248 * the files it contains) will sort with the '/' at the1249 * end.1250 */1251static enum exist_status directory_exists_in_index(const char*dirname,int len)1252{1253int pos;12541255if(ignore_case)1256returndirectory_exists_in_index_icase(dirname, len);12571258 pos =cache_name_pos(dirname, len);1259if(pos <0)1260 pos = -pos-1;1261while(pos < active_nr) {1262const struct cache_entry *ce = active_cache[pos++];1263unsigned char endchar;12641265if(strncmp(ce->name, dirname, len))1266break;1267 endchar = ce->name[len];1268if(endchar >'/')1269break;1270if(endchar =='/')1271return index_directory;1272if(!endchar &&S_ISGITLINK(ce->ce_mode))1273return index_gitdir;1274}1275return index_nonexistent;1276}12771278/*1279 * When we find a directory when traversing the filesystem, we1280 * have three distinct cases:1281 *1282 * - ignore it1283 * - see it as a directory1284 * - recurse into it1285 *1286 * and which one we choose depends on a combination of existing1287 * git index contents and the flags passed into the directory1288 * traversal routine.1289 *1290 * Case 1: If we *already* have entries in the index under that1291 * directory name, we always recurse into the directory to see1292 * all the files.1293 *1294 * Case 2: If we *already* have that directory name as a gitlink,1295 * we always continue to see it as a gitlink, regardless of whether1296 * there is an actual git directory there or not (it might not1297 * be checked out as a subproject!)1298 *1299 * Case 3: if we didn't have it in the index previously, we1300 * have a few sub-cases:1301 *1302 * (a) if "show_other_directories" is true, we show it as1303 * just a directory, unless "hide_empty_directories" is1304 * also true, in which case we need to check if it contains any1305 * untracked and / or ignored files.1306 * (b) if it looks like a git directory, and we don't have1307 * 'no_gitlinks' set we treat it as a gitlink, and show it1308 * as a directory.1309 * (c) otherwise, we recurse into it.1310 */1311static enum path_treatment treat_directory(struct dir_struct *dir,1312struct untracked_cache_dir *untracked,1313const char*dirname,int len,int baselen,int exclude,1314const struct pathspec *pathspec)1315{1316/* The "len-1" is to strip the final '/' */1317switch(directory_exists_in_index(dirname, len-1)) {1318case index_directory:1319return path_recurse;13201321case index_gitdir:1322return path_none;13231324case index_nonexistent:1325if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1326break;1327if(!(dir->flags & DIR_NO_GITLINKS)) {1328unsigned char sha1[20];1329if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1330return path_untracked;1331}1332return path_recurse;1333}13341335/* This is the "show_other_directories" case */13361337if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1338return exclude ? path_excluded : path_untracked;13391340 untracked =lookup_untracked(dir->untracked, untracked,1341 dirname + baselen, len - baselen);1342returnread_directory_recursive(dir, dirname, len,1343 untracked,1, pathspec);1344}13451346/*1347 * This is an inexact early pruning of any recursive directory1348 * reading - if the path cannot possibly be in the pathspec,1349 * return true, and we'll skip it early.1350 */1351static intsimplify_away(const char*path,int pathlen,1352const struct pathspec *pathspec)1353{1354int i;13551356if(!pathspec || !pathspec->nr)1357return0;13581359GUARD_PATHSPEC(pathspec,1360 PATHSPEC_FROMTOP |1361 PATHSPEC_MAXDEPTH |1362 PATHSPEC_LITERAL |1363 PATHSPEC_GLOB |1364 PATHSPEC_ICASE |1365 PATHSPEC_EXCLUDE);13661367for(i =0; i < pathspec->nr; i++) {1368const struct pathspec_item *item = &pathspec->items[i];1369int len = item->nowildcard_len;13701371if(len > pathlen)1372 len = pathlen;1373if(!ps_strncmp(item, item->match, path, len))1374return0;1375}13761377return1;1378}13791380/*1381 * This function tells us whether an excluded path matches a1382 * list of "interesting" pathspecs. That is, whether a path matched1383 * by any of the pathspecs could possibly be ignored by excluding1384 * the specified path. This can happen if:1385 *1386 * 1. the path is mentioned explicitly in the pathspec1387 *1388 * 2. the path is a directory prefix of some element in the1389 * pathspec1390 */1391static intexclude_matches_pathspec(const char*path,int pathlen,1392const struct pathspec *pathspec)1393{1394int i;13951396if(!pathspec || !pathspec->nr)1397return0;13981399GUARD_PATHSPEC(pathspec,1400 PATHSPEC_FROMTOP |1401 PATHSPEC_MAXDEPTH |1402 PATHSPEC_LITERAL |1403 PATHSPEC_GLOB |1404 PATHSPEC_ICASE |1405 PATHSPEC_EXCLUDE);14061407for(i =0; i < pathspec->nr; i++) {1408const struct pathspec_item *item = &pathspec->items[i];1409int len = item->nowildcard_len;14101411if(len == pathlen &&1412!ps_strncmp(item, item->match, path, pathlen))1413return1;1414if(len > pathlen &&1415 item->match[pathlen] =='/'&&1416!ps_strncmp(item, item->match, path, pathlen))1417return1;1418}1419return0;1420}14211422static intget_index_dtype(const char*path,int len)1423{1424int pos;1425const struct cache_entry *ce;14261427 ce =cache_file_exists(path, len,0);1428if(ce) {1429if(!ce_uptodate(ce))1430return DT_UNKNOWN;1431if(S_ISGITLINK(ce->ce_mode))1432return DT_DIR;1433/*1434 * Nobody actually cares about the1435 * difference between DT_LNK and DT_REG1436 */1437return DT_REG;1438}14391440/* Try to look it up as a directory */1441 pos =cache_name_pos(path, len);1442if(pos >=0)1443return DT_UNKNOWN;1444 pos = -pos-1;1445while(pos < active_nr) {1446 ce = active_cache[pos++];1447if(strncmp(ce->name, path, len))1448break;1449if(ce->name[len] >'/')1450break;1451if(ce->name[len] <'/')1452continue;1453if(!ce_uptodate(ce))1454break;/* continue? */1455return DT_DIR;1456}1457return DT_UNKNOWN;1458}14591460static intget_dtype(struct dirent *de,const char*path,int len)1461{1462int dtype = de ?DTYPE(de) : DT_UNKNOWN;1463struct stat st;14641465if(dtype != DT_UNKNOWN)1466return dtype;1467 dtype =get_index_dtype(path, len);1468if(dtype != DT_UNKNOWN)1469return dtype;1470if(lstat(path, &st))1471return dtype;1472if(S_ISREG(st.st_mode))1473return DT_REG;1474if(S_ISDIR(st.st_mode))1475return DT_DIR;1476if(S_ISLNK(st.st_mode))1477return DT_LNK;1478return dtype;1479}14801481static enum path_treatment treat_one_path(struct dir_struct *dir,1482struct untracked_cache_dir *untracked,1483struct strbuf *path,1484int baselen,1485const struct pathspec *pathspec,1486int dtype,struct dirent *de)1487{1488int exclude;1489int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);14901491if(dtype == DT_UNKNOWN)1492 dtype =get_dtype(de, path->buf, path->len);14931494/* Always exclude indexed files */1495if(dtype != DT_DIR && has_path_in_index)1496return path_none;14971498/*1499 * When we are looking at a directory P in the working tree,1500 * there are three cases:1501 *1502 * (1) P exists in the index. Everything inside the directory P in1503 * the working tree needs to go when P is checked out from the1504 * index.1505 *1506 * (2) P does not exist in the index, but there is P/Q in the index.1507 * We know P will stay a directory when we check out the contents1508 * of the index, but we do not know yet if there is a directory1509 * P/Q in the working tree to be killed, so we need to recurse.1510 *1511 * (3) P does not exist in the index, and there is no P/Q in the index1512 * to require P to be a directory, either. Only in this case, we1513 * know that everything inside P will not be killed without1514 * recursing.1515 */1516if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1517(dtype == DT_DIR) &&1518!has_path_in_index &&1519(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1520return path_none;15211522 exclude =is_excluded(dir, path->buf, &dtype);15231524/*1525 * Excluded? If we don't explicitly want to show1526 * ignored files, ignore it1527 */1528if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1529return path_excluded;15301531switch(dtype) {1532default:1533return path_none;1534case DT_DIR:1535strbuf_addch(path,'/');1536returntreat_directory(dir, untracked, path->buf, path->len,1537 baselen, exclude, pathspec);1538case DT_REG:1539case DT_LNK:1540return exclude ? path_excluded : path_untracked;1541}1542}15431544static enum path_treatment treat_path_fast(struct dir_struct *dir,1545struct untracked_cache_dir *untracked,1546struct cached_dir *cdir,1547struct strbuf *path,1548int baselen,1549const struct pathspec *pathspec)1550{1551strbuf_setlen(path, baselen);1552if(!cdir->ucd) {1553strbuf_addstr(path, cdir->file);1554return path_untracked;1555}1556strbuf_addstr(path, cdir->ucd->name);1557/* treat_one_path() does this before it calls treat_directory() */1558strbuf_complete(path,'/');1559if(cdir->ucd->check_only)1560/*1561 * check_only is set as a result of treat_directory() getting1562 * to its bottom. Verify again the same set of directories1563 * with check_only set.1564 */1565returnread_directory_recursive(dir, path->buf, path->len,1566 cdir->ucd,1, pathspec);1567/*1568 * We get path_recurse in the first run when1569 * directory_exists_in_index() returns index_nonexistent. We1570 * are sure that new changes in the index does not impact the1571 * outcome. Return now.1572 */1573return path_recurse;1574}15751576static enum path_treatment treat_path(struct dir_struct *dir,1577struct untracked_cache_dir *untracked,1578struct cached_dir *cdir,1579struct strbuf *path,1580int baselen,1581const struct pathspec *pathspec)1582{1583int dtype;1584struct dirent *de = cdir->de;15851586if(!de)1587returntreat_path_fast(dir, untracked, cdir, path,1588 baselen, pathspec);1589if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1590return path_none;1591strbuf_setlen(path, baselen);1592strbuf_addstr(path, de->d_name);1593if(simplify_away(path->buf, path->len, pathspec))1594return path_none;15951596 dtype =DTYPE(de);1597returntreat_one_path(dir, untracked, path, baselen, pathspec, dtype, de);1598}15991600static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1601{1602if(!dir)1603return;1604ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1605 dir->untracked_alloc);1606 dir->untracked[dir->untracked_nr++] =xstrdup(name);1607}16081609static intvalid_cached_dir(struct dir_struct *dir,1610struct untracked_cache_dir *untracked,1611struct strbuf *path,1612int check_only)1613{1614struct stat st;16151616if(!untracked)1617return0;16181619if(stat(path->len ? path->buf :".", &st)) {1620invalidate_directory(dir->untracked, untracked);1621memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1622return0;1623}1624if(!untracked->valid ||1625match_stat_data_racy(&the_index, &untracked->stat_data, &st)) {1626if(untracked->valid)1627invalidate_directory(dir->untracked, untracked);1628fill_stat_data(&untracked->stat_data, &st);1629return0;1630}16311632if(untracked->check_only != !!check_only) {1633invalidate_directory(dir->untracked, untracked);1634return0;1635}16361637/*1638 * prep_exclude will be called eventually on this directory,1639 * but it's called much later in last_exclude_matching(). We1640 * need it now to determine the validity of the cache for this1641 * path. The next calls will be nearly no-op, the way1642 * prep_exclude() is designed.1643 */1644if(path->len && path->buf[path->len -1] !='/') {1645strbuf_addch(path,'/');1646prep_exclude(dir, path->buf, path->len);1647strbuf_setlen(path, path->len -1);1648}else1649prep_exclude(dir, path->buf, path->len);16501651/* hopefully prep_exclude() haven't invalidated this entry... */1652return untracked->valid;1653}16541655static intopen_cached_dir(struct cached_dir *cdir,1656struct dir_struct *dir,1657struct untracked_cache_dir *untracked,1658struct strbuf *path,1659int check_only)1660{1661memset(cdir,0,sizeof(*cdir));1662 cdir->untracked = untracked;1663if(valid_cached_dir(dir, untracked, path, check_only))1664return0;1665 cdir->fdir =opendir(path->len ? path->buf :".");1666if(dir->untracked)1667 dir->untracked->dir_opened++;1668if(!cdir->fdir)1669return-1;1670return0;1671}16721673static intread_cached_dir(struct cached_dir *cdir)1674{1675if(cdir->fdir) {1676 cdir->de =readdir(cdir->fdir);1677if(!cdir->de)1678return-1;1679return0;1680}1681while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1682struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1683if(!d->recurse) {1684 cdir->nr_dirs++;1685continue;1686}1687 cdir->ucd = d;1688 cdir->nr_dirs++;1689return0;1690}1691 cdir->ucd = NULL;1692if(cdir->nr_files < cdir->untracked->untracked_nr) {1693struct untracked_cache_dir *d = cdir->untracked;1694 cdir->file = d->untracked[cdir->nr_files++];1695return0;1696}1697return-1;1698}16991700static voidclose_cached_dir(struct cached_dir *cdir)1701{1702if(cdir->fdir)1703closedir(cdir->fdir);1704/*1705 * We have gone through this directory and found no untracked1706 * entries. Mark it valid.1707 */1708if(cdir->untracked) {1709 cdir->untracked->valid =1;1710 cdir->untracked->recurse =1;1711}1712}17131714/*1715 * Read a directory tree. We currently ignore anything but1716 * directories, regular files and symlinks. That's because git1717 * doesn't handle them at all yet. Maybe that will change some1718 * day.1719 *1720 * Also, we ignore the name ".git" (even if it is not a directory).1721 * That likely will not change.1722 *1723 * Returns the most significant path_treatment value encountered in the scan.1724 */1725static enum path_treatment read_directory_recursive(struct dir_struct *dir,1726const char*base,int baselen,1727struct untracked_cache_dir *untracked,int check_only,1728const struct pathspec *pathspec)1729{1730struct cached_dir cdir;1731enum path_treatment state, subdir_state, dir_state = path_none;1732struct strbuf path = STRBUF_INIT;17331734strbuf_add(&path, base, baselen);17351736if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1737goto out;17381739if(untracked)1740 untracked->check_only = !!check_only;17411742while(!read_cached_dir(&cdir)) {1743/* check how the file or directory should be treated */1744 state =treat_path(dir, untracked, &cdir, &path,1745 baselen, pathspec);17461747if(state > dir_state)1748 dir_state = state;17491750/* recurse into subdir if instructed by treat_path */1751if(state == path_recurse) {1752struct untracked_cache_dir *ud;1753 ud =lookup_untracked(dir->untracked, untracked,1754 path.buf + baselen,1755 path.len - baselen);1756 subdir_state =1757read_directory_recursive(dir, path.buf,1758 path.len, ud,1759 check_only, pathspec);1760if(subdir_state > dir_state)1761 dir_state = subdir_state;1762}17631764if(check_only) {1765/* abort early if maximum state has been reached */1766if(dir_state == path_untracked) {1767if(cdir.fdir)1768add_untracked(untracked, path.buf + baselen);1769break;1770}1771/* skip the dir_add_* part */1772continue;1773}17741775/* add the path to the appropriate result list */1776switch(state) {1777case path_excluded:1778if(dir->flags & DIR_SHOW_IGNORED)1779dir_add_name(dir, path.buf, path.len);1780else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1781((dir->flags & DIR_COLLECT_IGNORED) &&1782exclude_matches_pathspec(path.buf, path.len,1783 pathspec)))1784dir_add_ignored(dir, path.buf, path.len);1785break;17861787case path_untracked:1788if(dir->flags & DIR_SHOW_IGNORED)1789break;1790dir_add_name(dir, path.buf, path.len);1791if(cdir.fdir)1792add_untracked(untracked, path.buf + baselen);1793break;17941795default:1796break;1797}1798}1799close_cached_dir(&cdir);1800 out:1801strbuf_release(&path);18021803return dir_state;1804}18051806static intcmp_name(const void*p1,const void*p2)1807{1808const struct dir_entry *e1 = *(const struct dir_entry **)p1;1809const struct dir_entry *e2 = *(const struct dir_entry **)p2;18101811returnname_compare(e1->name, e1->len, e2->name, e2->len);1812}18131814static inttreat_leading_path(struct dir_struct *dir,1815const char*path,int len,1816const struct pathspec *pathspec)1817{1818struct strbuf sb = STRBUF_INIT;1819int baselen, rc =0;1820const char*cp;1821int old_flags = dir->flags;18221823while(len && path[len -1] =='/')1824 len--;1825if(!len)1826return1;1827 baselen =0;1828 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1829while(1) {1830 cp = path + baselen + !!baselen;1831 cp =memchr(cp,'/', path + len - cp);1832if(!cp)1833 baselen = len;1834else1835 baselen = cp - path;1836strbuf_setlen(&sb,0);1837strbuf_add(&sb, path, baselen);1838if(!is_directory(sb.buf))1839break;1840if(simplify_away(sb.buf, sb.len, pathspec))1841break;1842if(treat_one_path(dir, NULL, &sb, baselen, pathspec,1843 DT_DIR, NULL) == path_none)1844break;/* do not recurse into it */1845if(len <= baselen) {1846 rc =1;1847break;/* finished checking */1848}1849}1850strbuf_release(&sb);1851 dir->flags = old_flags;1852return rc;1853}18541855static const char*get_ident_string(void)1856{1857static struct strbuf sb = STRBUF_INIT;1858struct utsname uts;18591860if(sb.len)1861return sb.buf;1862if(uname(&uts) <0)1863die_errno(_("failed to get kernel name and information"));1864strbuf_addf(&sb,"Location%s, system%s",get_git_work_tree(),1865 uts.sysname);1866return sb.buf;1867}18681869static intident_in_untracked(const struct untracked_cache *uc)1870{1871/*1872 * Previous git versions may have saved many NUL separated1873 * strings in the "ident" field, but it is insane to manage1874 * many locations, so just take care of the first one.1875 */18761877return!strcmp(uc->ident.buf,get_ident_string());1878}18791880static voidset_untracked_ident(struct untracked_cache *uc)1881{1882strbuf_reset(&uc->ident);1883strbuf_addstr(&uc->ident,get_ident_string());18841885/*1886 * This strbuf used to contain a list of NUL separated1887 * strings, so save NUL too for backward compatibility.1888 */1889strbuf_addch(&uc->ident,0);1890}18911892static voidnew_untracked_cache(struct index_state *istate)1893{1894struct untracked_cache *uc =xcalloc(1,sizeof(*uc));1895strbuf_init(&uc->ident,100);1896 uc->exclude_per_dir =".gitignore";1897/* should be the same flags used by git-status */1898 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;1899set_untracked_ident(uc);1900 istate->untracked = uc;1901 istate->cache_changed |= UNTRACKED_CHANGED;1902}19031904voidadd_untracked_cache(struct index_state *istate)1905{1906if(!istate->untracked) {1907new_untracked_cache(istate);1908}else{1909if(!ident_in_untracked(istate->untracked)) {1910free_untracked_cache(istate->untracked);1911new_untracked_cache(istate);1912}1913}1914}19151916voidremove_untracked_cache(struct index_state *istate)1917{1918if(istate->untracked) {1919free_untracked_cache(istate->untracked);1920 istate->untracked = NULL;1921 istate->cache_changed |= UNTRACKED_CHANGED;1922}1923}19241925static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1926int base_len,1927const struct pathspec *pathspec)1928{1929struct untracked_cache_dir *root;19301931if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))1932return NULL;19331934/*1935 * We only support $GIT_DIR/info/exclude and core.excludesfile1936 * as the global ignore rule files. Any other additions1937 * (e.g. from command line) invalidate the cache. This1938 * condition also catches running setup_standard_excludes()1939 * before setting dir->untracked!1940 */1941if(dir->unmanaged_exclude_files)1942return NULL;19431944/*1945 * Optimize for the main use case only: whole-tree git1946 * status. More work involved in treat_leading_path() if we1947 * use cache on just a subset of the worktree. pathspec1948 * support could make the matter even worse.1949 */1950if(base_len || (pathspec && pathspec->nr))1951return NULL;19521953/* Different set of flags may produce different results */1954if(dir->flags != dir->untracked->dir_flags ||1955/*1956 * See treat_directory(), case index_nonexistent. Without1957 * this flag, we may need to also cache .git file content1958 * for the resolve_gitlink_ref() call, which we don't.1959 */1960!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1961/* We don't support collecting ignore files */1962(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |1963 DIR_COLLECT_IGNORED)))1964return NULL;19651966/*1967 * If we use .gitignore in the cache and now you change it to1968 * .gitexclude, everything will go wrong.1969 */1970if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&1971strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))1972return NULL;19731974/*1975 * EXC_CMDL is not considered in the cache. If people set it,1976 * skip the cache.1977 */1978if(dir->exclude_list_group[EXC_CMDL].nr)1979return NULL;19801981if(!ident_in_untracked(dir->untracked)) {1982warning(_("Untracked cache is disabled on this system or location."));1983return NULL;1984}19851986if(!dir->untracked->root) {1987const int len =sizeof(*dir->untracked->root);1988 dir->untracked->root =xmalloc(len);1989memset(dir->untracked->root,0, len);1990}19911992/* Validate $GIT_DIR/info/exclude and core.excludesfile */1993 root = dir->untracked->root;1994if(hashcmp(dir->ss_info_exclude.sha1,1995 dir->untracked->ss_info_exclude.sha1)) {1996invalidate_gitignore(dir->untracked, root);1997 dir->untracked->ss_info_exclude = dir->ss_info_exclude;1998}1999if(hashcmp(dir->ss_excludes_file.sha1,2000 dir->untracked->ss_excludes_file.sha1)) {2001invalidate_gitignore(dir->untracked, root);2002 dir->untracked->ss_excludes_file = dir->ss_excludes_file;2003}20042005/* Make sure this directory is not dropped out at saving phase */2006 root->recurse =1;2007return root;2008}20092010intread_directory(struct dir_struct *dir,const char*path,2011int len,const struct pathspec *pathspec)2012{2013struct untracked_cache_dir *untracked;20142015if(has_symlink_leading_path(path, len))2016return dir->nr;20172018 untracked =validate_untracked_cache(dir, len, pathspec);2019if(!untracked)2020/*2021 * make sure untracked cache code path is disabled,2022 * e.g. prep_exclude()2023 */2024 dir->untracked = NULL;2025if(!len ||treat_leading_path(dir, path, len, pathspec))2026read_directory_recursive(dir, path, len, untracked,0, pathspec);2027QSORT(dir->entries, dir->nr, cmp_name);2028QSORT(dir->ignored, dir->ignored_nr, cmp_name);2029if(dir->untracked) {2030static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);2031trace_printf_key(&trace_untracked_stats,2032"node creation:%u\n"2033"gitignore invalidation:%u\n"2034"directory invalidation:%u\n"2035"opendir:%u\n",2036 dir->untracked->dir_created,2037 dir->untracked->gitignore_invalidated,2038 dir->untracked->dir_invalidated,2039 dir->untracked->dir_opened);2040if(dir->untracked == the_index.untracked &&2041(dir->untracked->dir_opened ||2042 dir->untracked->gitignore_invalidated ||2043 dir->untracked->dir_invalidated))2044 the_index.cache_changed |= UNTRACKED_CHANGED;2045if(dir->untracked != the_index.untracked) {2046free(dir->untracked);2047 dir->untracked = NULL;2048}2049}2050return dir->nr;2051}20522053intfile_exists(const char*f)2054{2055struct stat sb;2056returnlstat(f, &sb) ==0;2057}20582059static intcmp_icase(char a,char b)2060{2061if(a == b)2062return0;2063if(ignore_case)2064returntoupper(a) -toupper(b);2065return a - b;2066}20672068/*2069 * Given two normalized paths (a trailing slash is ok), if subdir is2070 * outside dir, return -1. Otherwise return the offset in subdir that2071 * can be used as relative path to dir.2072 */2073intdir_inside_of(const char*subdir,const char*dir)2074{2075int offset =0;20762077assert(dir && subdir && *dir && *subdir);20782079while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2080 dir++;2081 subdir++;2082 offset++;2083}20842085/* hel[p]/me vs hel[l]/yeah */2086if(*dir && *subdir)2087return-1;20882089if(!*subdir)2090return!*dir ? offset : -1;/* same dir */20912092/* foo/[b]ar vs foo/[] */2093if(is_dir_sep(dir[-1]))2094returnis_dir_sep(subdir[-1]) ? offset : -1;20952096/* foo[/]bar vs foo[] */2097returnis_dir_sep(*subdir) ? offset +1: -1;2098}20992100intis_inside_dir(const char*dir)2101{2102char*cwd;2103int rc;21042105if(!dir)2106return0;21072108 cwd =xgetcwd();2109 rc = (dir_inside_of(cwd, dir) >=0);2110free(cwd);2111return rc;2112}21132114intis_empty_dir(const char*path)2115{2116DIR*dir =opendir(path);2117struct dirent *e;2118int ret =1;21192120if(!dir)2121return0;21222123while((e =readdir(dir)) != NULL)2124if(!is_dot_or_dotdot(e->d_name)) {2125 ret =0;2126break;2127}21282129closedir(dir);2130return ret;2131}21322133static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2134{2135DIR*dir;2136struct dirent *e;2137int ret =0, original_len = path->len, len, kept_down =0;2138int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2139int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2140unsigned char submodule_head[20];21412142if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2143!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2144/* Do not descend and nuke a nested git work tree. */2145if(kept_up)2146*kept_up =1;2147return0;2148}21492150 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2151 dir =opendir(path->buf);2152if(!dir) {2153if(errno == ENOENT)2154return keep_toplevel ? -1:0;2155else if(errno == EACCES && !keep_toplevel)2156/*2157 * An empty dir could be removable even if it2158 * is unreadable:2159 */2160returnrmdir(path->buf);2161else2162return-1;2163}2164strbuf_complete(path,'/');21652166 len = path->len;2167while((e =readdir(dir)) != NULL) {2168struct stat st;2169if(is_dot_or_dotdot(e->d_name))2170continue;21712172strbuf_setlen(path, len);2173strbuf_addstr(path, e->d_name);2174if(lstat(path->buf, &st)) {2175if(errno == ENOENT)2176/*2177 * file disappeared, which is what we2178 * wanted anyway2179 */2180continue;2181/* fall thru */2182}else if(S_ISDIR(st.st_mode)) {2183if(!remove_dir_recurse(path, flag, &kept_down))2184continue;/* happy */2185}else if(!only_empty &&2186(!unlink(path->buf) || errno == ENOENT)) {2187continue;/* happy, too */2188}21892190/* path too long, stat fails, or non-directory still exists */2191 ret = -1;2192break;2193}2194closedir(dir);21952196strbuf_setlen(path, original_len);2197if(!ret && !keep_toplevel && !kept_down)2198 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2199else if(kept_up)2200/*2201 * report the uplevel that it is not an error that we2202 * did not rmdir() our directory.2203 */2204*kept_up = !ret;2205return ret;2206}22072208intremove_dir_recursively(struct strbuf *path,int flag)2209{2210returnremove_dir_recurse(path, flag, NULL);2211}22122213staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")22142215voidsetup_standard_excludes(struct dir_struct *dir)2216{2217 dir->exclude_per_dir =".gitignore";22182219/* core.excludefile defaulting to $XDG_HOME/git/ignore */2220if(!excludes_file)2221 excludes_file =xdg_config_home("ignore");2222if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2223add_excludes_from_file_1(dir, excludes_file,2224 dir->untracked ? &dir->ss_excludes_file : NULL);22252226/* per repository user preference */2227if(startup_info->have_repository) {2228const char*path =git_path_info_exclude();2229if(!access_or_warn(path, R_OK,0))2230add_excludes_from_file_1(dir, path,2231 dir->untracked ? &dir->ss_info_exclude : NULL);2232}2233}22342235intremove_path(const char*name)2236{2237char*slash;22382239if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2240return-1;22412242 slash =strrchr(name,'/');2243if(slash) {2244char*dirs =xstrdup(name);2245 slash = dirs + (slash - name);2246do{2247*slash ='\0';2248}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2249free(dirs);2250}2251return0;2252}22532254/*2255 * Frees memory within dir which was allocated for exclude lists and2256 * the exclude_stack. Does not free dir itself.2257 */2258voidclear_directory(struct dir_struct *dir)2259{2260int i, j;2261struct exclude_list_group *group;2262struct exclude_list *el;2263struct exclude_stack *stk;22642265for(i = EXC_CMDL; i <= EXC_FILE; i++) {2266 group = &dir->exclude_list_group[i];2267for(j =0; j < group->nr; j++) {2268 el = &group->el[j];2269if(i == EXC_DIRS)2270free((char*)el->src);2271clear_exclude_list(el);2272}2273free(group->el);2274}22752276 stk = dir->exclude_stack;2277while(stk) {2278struct exclude_stack *prev = stk->prev;2279free(stk);2280 stk = prev;2281}2282strbuf_release(&dir->basebuf);2283}22842285struct ondisk_untracked_cache {2286struct stat_data info_exclude_stat;2287struct stat_data excludes_file_stat;2288uint32_t dir_flags;2289unsigned char info_exclude_sha1[20];2290unsigned char excludes_file_sha1[20];2291char exclude_per_dir[FLEX_ARRAY];2292};22932294#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)22952296struct write_data {2297int index;/* number of written untracked_cache_dir */2298struct ewah_bitmap *check_only;/* from untracked_cache_dir */2299struct ewah_bitmap *valid;/* from untracked_cache_dir */2300struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2301struct strbuf out;2302struct strbuf sb_stat;2303struct strbuf sb_sha1;2304};23052306static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2307{2308 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2309 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2310 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2311 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2312 to->sd_dev =htonl(from->sd_dev);2313 to->sd_ino =htonl(from->sd_ino);2314 to->sd_uid =htonl(from->sd_uid);2315 to->sd_gid =htonl(from->sd_gid);2316 to->sd_size =htonl(from->sd_size);2317}23182319static voidwrite_one_dir(struct untracked_cache_dir *untracked,2320struct write_data *wd)2321{2322struct stat_data stat_data;2323struct strbuf *out = &wd->out;2324unsigned char intbuf[16];2325unsigned int intlen, value;2326int i = wd->index++;23272328/*2329 * untracked_nr should be reset whenever valid is clear, but2330 * for safety..2331 */2332if(!untracked->valid) {2333 untracked->untracked_nr =0;2334 untracked->check_only =0;2335}23362337if(untracked->check_only)2338ewah_set(wd->check_only, i);2339if(untracked->valid) {2340ewah_set(wd->valid, i);2341stat_data_to_disk(&stat_data, &untracked->stat_data);2342strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2343}2344if(!is_null_sha1(untracked->exclude_sha1)) {2345ewah_set(wd->sha1_valid, i);2346strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2347}23482349 intlen =encode_varint(untracked->untracked_nr, intbuf);2350strbuf_add(out, intbuf, intlen);23512352/* skip non-recurse directories */2353for(i =0, value =0; i < untracked->dirs_nr; i++)2354if(untracked->dirs[i]->recurse)2355 value++;2356 intlen =encode_varint(value, intbuf);2357strbuf_add(out, intbuf, intlen);23582359strbuf_add(out, untracked->name,strlen(untracked->name) +1);23602361for(i =0; i < untracked->untracked_nr; i++)2362strbuf_add(out, untracked->untracked[i],2363strlen(untracked->untracked[i]) +1);23642365for(i =0; i < untracked->dirs_nr; i++)2366if(untracked->dirs[i]->recurse)2367write_one_dir(untracked->dirs[i], wd);2368}23692370voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2371{2372struct ondisk_untracked_cache *ouc;2373struct write_data wd;2374unsigned char varbuf[16];2375int varint_len;2376size_t len =strlen(untracked->exclude_per_dir);23772378FLEX_ALLOC_MEM(ouc, exclude_per_dir, untracked->exclude_per_dir, len);2379stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2380stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2381hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2382hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2383 ouc->dir_flags =htonl(untracked->dir_flags);23842385 varint_len =encode_varint(untracked->ident.len, varbuf);2386strbuf_add(out, varbuf, varint_len);2387strbuf_addbuf(out, &untracked->ident);23882389strbuf_add(out, ouc,ouc_size(len));2390free(ouc);2391 ouc = NULL;23922393if(!untracked->root) {2394 varint_len =encode_varint(0, varbuf);2395strbuf_add(out, varbuf, varint_len);2396return;2397}23982399 wd.index =0;2400 wd.check_only =ewah_new();2401 wd.valid =ewah_new();2402 wd.sha1_valid =ewah_new();2403strbuf_init(&wd.out,1024);2404strbuf_init(&wd.sb_stat,1024);2405strbuf_init(&wd.sb_sha1,1024);2406write_one_dir(untracked->root, &wd);24072408 varint_len =encode_varint(wd.index, varbuf);2409strbuf_add(out, varbuf, varint_len);2410strbuf_addbuf(out, &wd.out);2411ewah_serialize_strbuf(wd.valid, out);2412ewah_serialize_strbuf(wd.check_only, out);2413ewah_serialize_strbuf(wd.sha1_valid, out);2414strbuf_addbuf(out, &wd.sb_stat);2415strbuf_addbuf(out, &wd.sb_sha1);2416strbuf_addch(out,'\0');/* safe guard for string lists */24172418ewah_free(wd.valid);2419ewah_free(wd.check_only);2420ewah_free(wd.sha1_valid);2421strbuf_release(&wd.out);2422strbuf_release(&wd.sb_stat);2423strbuf_release(&wd.sb_sha1);2424}24252426static voidfree_untracked(struct untracked_cache_dir *ucd)2427{2428int i;2429if(!ucd)2430return;2431for(i =0; i < ucd->dirs_nr; i++)2432free_untracked(ucd->dirs[i]);2433for(i =0; i < ucd->untracked_nr; i++)2434free(ucd->untracked[i]);2435free(ucd->untracked);2436free(ucd->dirs);2437free(ucd);2438}24392440voidfree_untracked_cache(struct untracked_cache *uc)2441{2442if(uc)2443free_untracked(uc->root);2444free(uc);2445}24462447struct read_data {2448int index;2449struct untracked_cache_dir **ucd;2450struct ewah_bitmap *check_only;2451struct ewah_bitmap *valid;2452struct ewah_bitmap *sha1_valid;2453const unsigned char*data;2454const unsigned char*end;2455};24562457static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2458{2459 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2460 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2461 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2462 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2463 to->sd_dev =get_be32(&from->sd_dev);2464 to->sd_ino =get_be32(&from->sd_ino);2465 to->sd_uid =get_be32(&from->sd_uid);2466 to->sd_gid =get_be32(&from->sd_gid);2467 to->sd_size =get_be32(&from->sd_size);2468}24692470static intread_one_dir(struct untracked_cache_dir **untracked_,2471struct read_data *rd)2472{2473struct untracked_cache_dir ud, *untracked;2474const unsigned char*next, *data = rd->data, *end = rd->end;2475unsigned int value;2476int i, len;24772478memset(&ud,0,sizeof(ud));24792480 next = data;2481 value =decode_varint(&next);2482if(next > end)2483return-1;2484 ud.recurse =1;2485 ud.untracked_alloc = value;2486 ud.untracked_nr = value;2487if(ud.untracked_nr)2488ALLOC_ARRAY(ud.untracked, ud.untracked_nr);2489 data = next;24902491 next = data;2492 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2493if(next > end)2494return-1;2495ALLOC_ARRAY(ud.dirs, ud.dirs_nr);2496 data = next;24972498 len =strlen((const char*)data);2499 next = data + len +1;2500if(next > rd->end)2501return-1;2502*untracked_ = untracked =xmalloc(st_add(sizeof(*untracked), len));2503memcpy(untracked, &ud,sizeof(ud));2504memcpy(untracked->name, data, len +1);2505 data = next;25062507for(i =0; i < untracked->untracked_nr; i++) {2508 len =strlen((const char*)data);2509 next = data + len +1;2510if(next > rd->end)2511return-1;2512 untracked->untracked[i] =xstrdup((const char*)data);2513 data = next;2514}25152516 rd->ucd[rd->index++] = untracked;2517 rd->data = data;25182519for(i =0; i < untracked->dirs_nr; i++) {2520 len =read_one_dir(untracked->dirs + i, rd);2521if(len <0)2522return-1;2523}2524return0;2525}25262527static voidset_check_only(size_t pos,void*cb)2528{2529struct read_data *rd = cb;2530struct untracked_cache_dir *ud = rd->ucd[pos];2531 ud->check_only =1;2532}25332534static voidread_stat(size_t pos,void*cb)2535{2536struct read_data *rd = cb;2537struct untracked_cache_dir *ud = rd->ucd[pos];2538if(rd->data +sizeof(struct stat_data) > rd->end) {2539 rd->data = rd->end +1;2540return;2541}2542stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2543 rd->data +=sizeof(struct stat_data);2544 ud->valid =1;2545}25462547static voidread_sha1(size_t pos,void*cb)2548{2549struct read_data *rd = cb;2550struct untracked_cache_dir *ud = rd->ucd[pos];2551if(rd->data +20> rd->end) {2552 rd->data = rd->end +1;2553return;2554}2555hashcpy(ud->exclude_sha1, rd->data);2556 rd->data +=20;2557}25582559static voidload_sha1_stat(struct sha1_stat *sha1_stat,2560const struct stat_data *stat,2561const unsigned char*sha1)2562{2563stat_data_from_disk(&sha1_stat->stat, stat);2564hashcpy(sha1_stat->sha1, sha1);2565 sha1_stat->valid =1;2566}25672568struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2569{2570const struct ondisk_untracked_cache *ouc;2571struct untracked_cache *uc;2572struct read_data rd;2573const unsigned char*next = data, *end = (const unsigned char*)data + sz;2574const char*ident;2575int ident_len, len;25762577if(sz <=1|| end[-1] !='\0')2578return NULL;2579 end--;25802581 ident_len =decode_varint(&next);2582if(next + ident_len > end)2583return NULL;2584 ident = (const char*)next;2585 next += ident_len;25862587 ouc = (const struct ondisk_untracked_cache *)next;2588if(next +ouc_size(0) > end)2589return NULL;25902591 uc =xcalloc(1,sizeof(*uc));2592strbuf_init(&uc->ident, ident_len);2593strbuf_add(&uc->ident, ident, ident_len);2594load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2595 ouc->info_exclude_sha1);2596load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2597 ouc->excludes_file_sha1);2598 uc->dir_flags =get_be32(&ouc->dir_flags);2599 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2600/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2601 next +=ouc_size(strlen(ouc->exclude_per_dir));2602if(next >= end)2603goto done2;26042605 len =decode_varint(&next);2606if(next > end || len ==0)2607goto done2;26082609 rd.valid =ewah_new();2610 rd.check_only =ewah_new();2611 rd.sha1_valid =ewah_new();2612 rd.data = next;2613 rd.end = end;2614 rd.index =0;2615ALLOC_ARRAY(rd.ucd, len);26162617if(read_one_dir(&uc->root, &rd) || rd.index != len)2618goto done;26192620 next = rd.data;2621 len =ewah_read_mmap(rd.valid, next, end - next);2622if(len <0)2623goto done;26242625 next += len;2626 len =ewah_read_mmap(rd.check_only, next, end - next);2627if(len <0)2628goto done;26292630 next += len;2631 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2632if(len <0)2633goto done;26342635ewah_each_bit(rd.check_only, set_check_only, &rd);2636 rd.data = next + len;2637ewah_each_bit(rd.valid, read_stat, &rd);2638ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2639 next = rd.data;26402641done:2642free(rd.ucd);2643ewah_free(rd.valid);2644ewah_free(rd.check_only);2645ewah_free(rd.sha1_valid);2646done2:2647if(next != end) {2648free_untracked_cache(uc);2649 uc = NULL;2650}2651return uc;2652}26532654static voidinvalidate_one_directory(struct untracked_cache *uc,2655struct untracked_cache_dir *ucd)2656{2657 uc->dir_invalidated++;2658 ucd->valid =0;2659 ucd->untracked_nr =0;2660}26612662/*2663 * Normally when an entry is added or removed from a directory,2664 * invalidating that directory is enough. No need to touch its2665 * ancestors. When a directory is shown as "foo/bar/" in git-status2666 * however, deleting or adding an entry may have cascading effect.2667 *2668 * Say the "foo/bar/file" has become untracked, we need to tell the2669 * untracked_cache_dir of "foo" that "bar/" is not an untracked2670 * directory any more (because "bar" is managed by foo as an untracked2671 * "file").2672 *2673 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2674 * was the last untracked entry in the entire "foo", we should show2675 * "foo/" instead. Which means we have to invalidate past "bar" up to2676 * "foo".2677 *2678 * This function traverses all directories from root to leaf. If there2679 * is a chance of one of the above cases happening, we invalidate back2680 * to root. Otherwise we just invalidate the leaf. There may be a more2681 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2682 * detect these cases and avoid unnecessary invalidation, for example,2683 * checking for the untracked entry named "bar/" in "foo", but for now2684 * stick to something safe and simple.2685 */2686static intinvalidate_one_component(struct untracked_cache *uc,2687struct untracked_cache_dir *dir,2688const char*path,int len)2689{2690const char*rest =strchr(path,'/');26912692if(rest) {2693int component_len = rest - path;2694struct untracked_cache_dir *d =2695lookup_untracked(uc, dir, path, component_len);2696int ret =2697invalidate_one_component(uc, d, rest +1,2698 len - (component_len +1));2699if(ret)2700invalidate_one_directory(uc, dir);2701return ret;2702}27032704invalidate_one_directory(uc, dir);2705return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2706}27072708voiduntracked_cache_invalidate_path(struct index_state *istate,2709const char*path)2710{2711if(!istate->untracked || !istate->untracked->root)2712return;2713invalidate_one_component(istate->untracked, istate->untracked->root,2714 path,strlen(path));2715}27162717voiduntracked_cache_remove_from_index(struct index_state *istate,2718const char*path)2719{2720untracked_cache_invalidate_path(istate, path);2721}27222723voiduntracked_cache_add_to_index(struct index_state *istate,2724const char*path)2725{2726untracked_cache_invalidate_path(istate, path);2727}27282729/* Update gitfile and core.worktree setting to connect work tree and git dir */2730voidconnect_work_tree_and_git_dir(const char*work_tree_,const char*git_dir_)2731{2732struct strbuf file_name = STRBUF_INIT;2733struct strbuf rel_path = STRBUF_INIT;2734char*git_dir =real_pathdup(git_dir_);2735char*work_tree =real_pathdup(work_tree_);27362737/* Update gitfile */2738strbuf_addf(&file_name,"%s/.git", work_tree);2739write_file(file_name.buf,"gitdir:%s",2740relative_path(git_dir, work_tree, &rel_path));27412742/* Update core.worktree setting */2743strbuf_reset(&file_name);2744strbuf_addf(&file_name,"%s/config", git_dir);2745git_config_set_in_file(file_name.buf,"core.worktree",2746relative_path(work_tree, git_dir, &rel_path));27472748strbuf_release(&file_name);2749strbuf_release(&rel_path);2750free(work_tree);2751free(git_dir);2752}27532754/*2755 * Migrate the git directory of the given path from old_git_dir to new_git_dir.2756 */2757voidrelocate_gitdir(const char*path,const char*old_git_dir,const char*new_git_dir)2758{2759if(rename(old_git_dir, new_git_dir) <0)2760die_errno(_("could not migrate git directory from '%s' to '%s'"),2761 old_git_dir, new_git_dir);27622763connect_work_tree_and_git_dir(path, new_git_dir);2764}