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"config.h" 12#include"dir.h" 13#include"attr.h" 14#include"refs.h" 15#include"wildmatch.h" 16#include"pathspec.h" 17#include"utf8.h" 18#include"varint.h" 19#include"ewah/ewok.h" 20 21/* 22 * Tells read_directory_recursive how a file or directory should be treated. 23 * Values are ordered by significance, e.g. if a directory contains both 24 * excluded and untracked files, it is listed as untracked because 25 * path_untracked > path_excluded. 26 */ 27enum path_treatment { 28 path_none =0, 29 path_recurse, 30 path_excluded, 31 path_untracked 32}; 33 34/* 35 * Support data structure for our opendir/readdir/closedir wrappers 36 */ 37struct cached_dir { 38DIR*fdir; 39struct untracked_cache_dir *untracked; 40int nr_files; 41int nr_dirs; 42 43struct dirent *de; 44const char*file; 45struct untracked_cache_dir *ucd; 46}; 47 48static enum path_treatment read_directory_recursive(struct dir_struct *dir, 49const char*path,int len,struct untracked_cache_dir *untracked, 50int check_only,const struct pathspec *pathspec); 51static intget_dtype(struct dirent *de,const char*path,int len); 52 53intfspathcmp(const char*a,const char*b) 54{ 55return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 56} 57 58intfspathncmp(const char*a,const char*b,size_t count) 59{ 60return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 61} 62 63intgit_fnmatch(const struct pathspec_item *item, 64const char*pattern,const char*string, 65int prefix) 66{ 67if(prefix >0) { 68if(ps_strncmp(item, pattern, string, prefix)) 69return WM_NOMATCH; 70 pattern += prefix; 71 string += prefix; 72} 73if(item->flags & PATHSPEC_ONESTAR) { 74int pattern_len =strlen(++pattern); 75int string_len =strlen(string); 76return string_len < pattern_len || 77ps_strcmp(item, pattern, 78 string + string_len - pattern_len); 79} 80if(item->magic & PATHSPEC_GLOB) 81returnwildmatch(pattern, string, 82 WM_PATHNAME | 83(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 84 NULL); 85else 86/* wildmatch has not learned no FNM_PATHNAME mode yet */ 87returnwildmatch(pattern, string, 88 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 89 NULL); 90} 91 92static intfnmatch_icase_mem(const char*pattern,int patternlen, 93const char*string,int stringlen, 94int flags) 95{ 96int match_status; 97struct strbuf pat_buf = STRBUF_INIT; 98struct strbuf str_buf = STRBUF_INIT; 99const char*use_pat = pattern; 100const char*use_str = string; 101 102if(pattern[patternlen]) { 103strbuf_add(&pat_buf, pattern, patternlen); 104 use_pat = pat_buf.buf; 105} 106if(string[stringlen]) { 107strbuf_add(&str_buf, string, stringlen); 108 use_str = str_buf.buf; 109} 110 111if(ignore_case) 112 flags |= WM_CASEFOLD; 113 match_status =wildmatch(use_pat, use_str, flags, NULL); 114 115strbuf_release(&pat_buf); 116strbuf_release(&str_buf); 117 118return match_status; 119} 120 121static size_tcommon_prefix_len(const struct pathspec *pathspec) 122{ 123int n; 124size_t max =0; 125 126/* 127 * ":(icase)path" is treated as a pathspec full of 128 * wildcard. In other words, only prefix is considered common 129 * prefix. If the pathspec is abc/foo abc/bar, running in 130 * subdir xyz, the common prefix is still xyz, not xuz/abc as 131 * in non-:(icase). 132 */ 133GUARD_PATHSPEC(pathspec, 134 PATHSPEC_FROMTOP | 135 PATHSPEC_MAXDEPTH | 136 PATHSPEC_LITERAL | 137 PATHSPEC_GLOB | 138 PATHSPEC_ICASE | 139 PATHSPEC_EXCLUDE | 140 PATHSPEC_ATTR); 141 142for(n =0; n < pathspec->nr; n++) { 143size_t i =0, len =0, item_len; 144if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 145continue; 146if(pathspec->items[n].magic & PATHSPEC_ICASE) 147 item_len = pathspec->items[n].prefix; 148else 149 item_len = pathspec->items[n].nowildcard_len; 150while(i < item_len && (n ==0|| i < max)) { 151char c = pathspec->items[n].match[i]; 152if(c != pathspec->items[0].match[i]) 153break; 154if(c =='/') 155 len = i +1; 156 i++; 157} 158if(n ==0|| len < max) { 159 max = len; 160if(!max) 161break; 162} 163} 164return max; 165} 166 167/* 168 * Returns a copy of the longest leading path common among all 169 * pathspecs. 170 */ 171char*common_prefix(const struct pathspec *pathspec) 172{ 173unsigned long len =common_prefix_len(pathspec); 174 175return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 176} 177 178intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 179{ 180const char*prefix; 181size_t prefix_len; 182 183/* 184 * Calculate common prefix for the pathspec, and 185 * use that to optimize the directory walk 186 */ 187 prefix_len =common_prefix_len(pathspec); 188 prefix = prefix_len ? pathspec->items[0].match :""; 189 190/* Read the directory and prune it */ 191read_directory(dir, prefix, prefix_len, pathspec); 192 193return prefix_len; 194} 195 196intwithin_depth(const char*name,int namelen, 197int depth,int max_depth) 198{ 199const char*cp = name, *cpe = name + namelen; 200 201while(cp < cpe) { 202if(*cp++ !='/') 203continue; 204 depth++; 205if(depth > max_depth) 206return0; 207} 208return1; 209} 210 211#define DO_MATCH_EXCLUDE (1<<0) 212#define DO_MATCH_DIRECTORY (1<<1) 213#define DO_MATCH_SUBMODULE (1<<2) 214 215static intmatch_attrs(const char*name,int namelen, 216const struct pathspec_item *item) 217{ 218int i; 219 220git_check_attr(name, item->attr_check); 221for(i =0; i < item->attr_match_nr; i++) { 222const char*value; 223int matched; 224enum attr_match_mode match_mode; 225 226 value = item->attr_check->items[i].value; 227 match_mode = item->attr_match[i].match_mode; 228 229if(ATTR_TRUE(value)) 230 matched = (match_mode == MATCH_SET); 231else if(ATTR_FALSE(value)) 232 matched = (match_mode == MATCH_UNSET); 233else if(ATTR_UNSET(value)) 234 matched = (match_mode == MATCH_UNSPECIFIED); 235else 236 matched = (match_mode == MATCH_VALUE && 237!strcmp(item->attr_match[i].value, value)); 238if(!matched) 239return0; 240} 241 242return1; 243} 244 245/* 246 * Does 'match' match the given name? 247 * A match is found if 248 * 249 * (1) the 'match' string is leading directory of 'name', or 250 * (2) the 'match' string is a wildcard and matches 'name', or 251 * (3) the 'match' string is exactly the same as 'name'. 252 * 253 * and the return value tells which case it was. 254 * 255 * It returns 0 when there is no match. 256 */ 257static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 258const char*name,int namelen,unsigned flags) 259{ 260/* name/namelen has prefix cut off by caller */ 261const char*match = item->match + prefix; 262int matchlen = item->len - prefix; 263 264/* 265 * The normal call pattern is: 266 * 1. prefix = common_prefix_len(ps); 267 * 2. prune something, or fill_directory 268 * 3. match_pathspec() 269 * 270 * 'prefix' at #1 may be shorter than the command's prefix and 271 * it's ok for #2 to match extra files. Those extras will be 272 * trimmed at #3. 273 * 274 * Suppose the pathspec is 'foo' and '../bar' running from 275 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 276 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 277 * user does not want XYZ/foo, only the "foo" part should be 278 * case-insensitive. We need to filter out XYZ/foo here. In 279 * other words, we do not trust the caller on comparing the 280 * prefix part when :(icase) is involved. We do exact 281 * comparison ourselves. 282 * 283 * Normally the caller (common_prefix_len() in fact) does 284 * _exact_ matching on name[-prefix+1..-1] and we do not need 285 * to check that part. Be defensive and check it anyway, in 286 * case common_prefix_len is changed, or a new caller is 287 * introduced that does not use common_prefix_len. 288 * 289 * If the penalty turns out too high when prefix is really 290 * long, maybe change it to 291 * strncmp(match, name, item->prefix - prefix) 292 */ 293if(item->prefix && (item->magic & PATHSPEC_ICASE) && 294strncmp(item->match, name - prefix, item->prefix)) 295return0; 296 297if(item->attr_match_nr && !match_attrs(name, namelen, item)) 298return0; 299 300/* If the match was just the prefix, we matched */ 301if(!*match) 302return MATCHED_RECURSIVELY; 303 304if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 305if(matchlen == namelen) 306return MATCHED_EXACTLY; 307 308if(match[matchlen-1] =='/'|| name[matchlen] =='/') 309return MATCHED_RECURSIVELY; 310}else if((flags & DO_MATCH_DIRECTORY) && 311 match[matchlen -1] =='/'&& 312 namelen == matchlen -1&& 313!ps_strncmp(item, match, name, namelen)) 314return MATCHED_EXACTLY; 315 316if(item->nowildcard_len < item->len && 317!git_fnmatch(item, match, name, 318 item->nowildcard_len - prefix)) 319return MATCHED_FNMATCH; 320 321/* Perform checks to see if "name" is a super set of the pathspec */ 322if(flags & DO_MATCH_SUBMODULE) { 323/* name is a literal prefix of the pathspec */ 324if((namelen < matchlen) && 325(match[namelen] =='/') && 326!ps_strncmp(item, match, name, namelen)) 327return MATCHED_RECURSIVELY; 328 329/* name" doesn't match up to the first wild character */ 330if(item->nowildcard_len < item->len && 331ps_strncmp(item, match, name, 332 item->nowildcard_len - prefix)) 333return0; 334 335/* 336 * Here is where we would perform a wildmatch to check if 337 * "name" can be matched as a directory (or a prefix) against 338 * the pathspec. Since wildmatch doesn't have this capability 339 * at the present we have to punt and say that it is a match, 340 * potentially returning a false positive 341 * The submodules themselves will be able to perform more 342 * accurate matching to determine if the pathspec matches. 343 */ 344return MATCHED_RECURSIVELY; 345} 346 347return0; 348} 349 350/* 351 * Given a name and a list of pathspecs, returns the nature of the 352 * closest (i.e. most specific) match of the name to any of the 353 * pathspecs. 354 * 355 * The caller typically calls this multiple times with the same 356 * pathspec and seen[] array but with different name/namelen 357 * (e.g. entries from the index) and is interested in seeing if and 358 * how each pathspec matches all the names it calls this function 359 * with. A mark is left in the seen[] array for each pathspec element 360 * indicating the closest type of match that element achieved, so if 361 * seen[n] remains zero after multiple invocations, that means the nth 362 * pathspec did not match any names, which could indicate that the 363 * user mistyped the nth pathspec. 364 */ 365static intdo_match_pathspec(const struct pathspec *ps, 366const char*name,int namelen, 367int prefix,char*seen, 368unsigned flags) 369{ 370int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 371 372GUARD_PATHSPEC(ps, 373 PATHSPEC_FROMTOP | 374 PATHSPEC_MAXDEPTH | 375 PATHSPEC_LITERAL | 376 PATHSPEC_GLOB | 377 PATHSPEC_ICASE | 378 PATHSPEC_EXCLUDE | 379 PATHSPEC_ATTR); 380 381if(!ps->nr) { 382if(!ps->recursive || 383!(ps->magic & PATHSPEC_MAXDEPTH) || 384 ps->max_depth == -1) 385return MATCHED_RECURSIVELY; 386 387if(within_depth(name, namelen,0, ps->max_depth)) 388return MATCHED_EXACTLY; 389else 390return0; 391} 392 393 name += prefix; 394 namelen -= prefix; 395 396for(i = ps->nr -1; i >=0; i--) { 397int how; 398 399if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 400( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 401continue; 402 403if(seen && seen[i] == MATCHED_EXACTLY) 404continue; 405/* 406 * Make exclude patterns optional and never report 407 * "pathspec ':(exclude)foo' matches no files" 408 */ 409if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 410 seen[i] = MATCHED_FNMATCH; 411 how =match_pathspec_item(ps->items+i, prefix, name, 412 namelen, flags); 413if(ps->recursive && 414(ps->magic & PATHSPEC_MAXDEPTH) && 415 ps->max_depth != -1&& 416 how && how != MATCHED_FNMATCH) { 417int len = ps->items[i].len; 418if(name[len] =='/') 419 len++; 420if(within_depth(name+len, namelen-len,0, ps->max_depth)) 421 how = MATCHED_EXACTLY; 422else 423 how =0; 424} 425if(how) { 426if(retval < how) 427 retval = how; 428if(seen && seen[i] < how) 429 seen[i] = how; 430} 431} 432return retval; 433} 434 435intmatch_pathspec(const struct pathspec *ps, 436const char*name,int namelen, 437int prefix,char*seen,int is_dir) 438{ 439int positive, negative; 440unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 441 positive =do_match_pathspec(ps, name, namelen, 442 prefix, seen, flags); 443if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 444return positive; 445 negative =do_match_pathspec(ps, name, namelen, 446 prefix, seen, 447 flags | DO_MATCH_EXCLUDE); 448return negative ?0: positive; 449} 450 451/** 452 * Check if a submodule is a superset of the pathspec 453 */ 454intsubmodule_path_match(const struct pathspec *ps, 455const char*submodule_name, 456char*seen) 457{ 458int matched =do_match_pathspec(ps, submodule_name, 459strlen(submodule_name), 4600, seen, 461 DO_MATCH_DIRECTORY | 462 DO_MATCH_SUBMODULE); 463return matched; 464} 465 466intreport_path_error(const char*ps_matched, 467const struct pathspec *pathspec, 468const char*prefix) 469{ 470/* 471 * Make sure all pathspec matched; otherwise it is an error. 472 */ 473int num, errors =0; 474for(num =0; num < pathspec->nr; num++) { 475int other, found_dup; 476 477if(ps_matched[num]) 478continue; 479/* 480 * The caller might have fed identical pathspec 481 * twice. Do not barf on such a mistake. 482 * FIXME: parse_pathspec should have eliminated 483 * duplicate pathspec. 484 */ 485for(found_dup = other =0; 486!found_dup && other < pathspec->nr; 487 other++) { 488if(other == num || !ps_matched[other]) 489continue; 490if(!strcmp(pathspec->items[other].original, 491 pathspec->items[num].original)) 492/* 493 * Ok, we have a match already. 494 */ 495 found_dup =1; 496} 497if(found_dup) 498continue; 499 500error("pathspec '%s' did not match any file(s) known to git.", 501 pathspec->items[num].original); 502 errors++; 503} 504return errors; 505} 506 507/* 508 * Return the length of the "simple" part of a path match limiter. 509 */ 510intsimple_length(const char*match) 511{ 512int len = -1; 513 514for(;;) { 515unsigned char c = *match++; 516 len++; 517if(c =='\0'||is_glob_special(c)) 518return len; 519} 520} 521 522intno_wildcard(const char*string) 523{ 524return string[simple_length(string)] =='\0'; 525} 526 527voidparse_exclude_pattern(const char**pattern, 528int*patternlen, 529unsigned*flags, 530int*nowildcardlen) 531{ 532const char*p = *pattern; 533size_t i, len; 534 535*flags =0; 536if(*p =='!') { 537*flags |= EXC_FLAG_NEGATIVE; 538 p++; 539} 540 len =strlen(p); 541if(len && p[len -1] =='/') { 542 len--; 543*flags |= EXC_FLAG_MUSTBEDIR; 544} 545for(i =0; i < len; i++) { 546if(p[i] =='/') 547break; 548} 549if(i == len) 550*flags |= EXC_FLAG_NODIR; 551*nowildcardlen =simple_length(p); 552/* 553 * we should have excluded the trailing slash from 'p' too, 554 * but that's one more allocation. Instead just make sure 555 * nowildcardlen does not exceed real patternlen 556 */ 557if(*nowildcardlen > len) 558*nowildcardlen = len; 559if(*p =='*'&&no_wildcard(p +1)) 560*flags |= EXC_FLAG_ENDSWITH; 561*pattern = p; 562*patternlen = len; 563} 564 565voidadd_exclude(const char*string,const char*base, 566int baselen,struct exclude_list *el,int srcpos) 567{ 568struct exclude *x; 569int patternlen; 570unsigned flags; 571int nowildcardlen; 572 573parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 574if(flags & EXC_FLAG_MUSTBEDIR) { 575FLEXPTR_ALLOC_MEM(x, pattern, string, patternlen); 576}else{ 577 x =xmalloc(sizeof(*x)); 578 x->pattern = string; 579} 580 x->patternlen = patternlen; 581 x->nowildcardlen = nowildcardlen; 582 x->base = base; 583 x->baselen = baselen; 584 x->flags = flags; 585 x->srcpos = srcpos; 586ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 587 el->excludes[el->nr++] = x; 588 x->el = el; 589} 590 591static void*read_skip_worktree_file_from_index(const char*path,size_t*size, 592struct sha1_stat *sha1_stat) 593{ 594int pos, len; 595unsigned long sz; 596enum object_type type; 597void*data; 598 599 len =strlen(path); 600 pos =cache_name_pos(path, len); 601if(pos <0) 602return NULL; 603if(!ce_skip_worktree(active_cache[pos])) 604return NULL; 605 data =read_sha1_file(active_cache[pos]->oid.hash, &type, &sz); 606if(!data || type != OBJ_BLOB) { 607free(data); 608return NULL; 609} 610*size =xsize_t(sz); 611if(sha1_stat) { 612memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 613hashcpy(sha1_stat->sha1, active_cache[pos]->oid.hash); 614} 615return data; 616} 617 618/* 619 * Frees memory within el which was allocated for exclude patterns and 620 * the file buffer. Does not free el itself. 621 */ 622voidclear_exclude_list(struct exclude_list *el) 623{ 624int i; 625 626for(i =0; i < el->nr; i++) 627free(el->excludes[i]); 628free(el->excludes); 629free(el->filebuf); 630 631memset(el,0,sizeof(*el)); 632} 633 634static voidtrim_trailing_spaces(char*buf) 635{ 636char*p, *last_space = NULL; 637 638for(p = buf; *p; p++) 639switch(*p) { 640case' ': 641if(!last_space) 642 last_space = p; 643break; 644case'\\': 645 p++; 646if(!*p) 647return; 648/* fallthrough */ 649default: 650 last_space = NULL; 651} 652 653if(last_space) 654*last_space ='\0'; 655} 656 657/* 658 * Given a subdirectory name and "dir" of the current directory, 659 * search the subdir in "dir" and return it, or create a new one if it 660 * does not exist in "dir". 661 * 662 * If "name" has the trailing slash, it'll be excluded in the search. 663 */ 664static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 665struct untracked_cache_dir *dir, 666const char*name,int len) 667{ 668int first, last; 669struct untracked_cache_dir *d; 670if(!dir) 671return NULL; 672if(len && name[len -1] =='/') 673 len--; 674 first =0; 675 last = dir->dirs_nr; 676while(last > first) { 677int cmp, next = (last + first) >>1; 678 d = dir->dirs[next]; 679 cmp =strncmp(name, d->name, len); 680if(!cmp &&strlen(d->name) > len) 681 cmp = -1; 682if(!cmp) 683return d; 684if(cmp <0) { 685 last = next; 686continue; 687} 688 first = next+1; 689} 690 691 uc->dir_created++; 692FLEX_ALLOC_MEM(d, name, name, len); 693 694ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 695memmove(dir->dirs + first +1, dir->dirs + first, 696(dir->dirs_nr - first) *sizeof(*dir->dirs)); 697 dir->dirs_nr++; 698 dir->dirs[first] = d; 699return d; 700} 701 702static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 703{ 704int i; 705 dir->valid =0; 706 dir->untracked_nr =0; 707for(i =0; i < dir->dirs_nr; i++) 708do_invalidate_gitignore(dir->dirs[i]); 709} 710 711static voidinvalidate_gitignore(struct untracked_cache *uc, 712struct untracked_cache_dir *dir) 713{ 714 uc->gitignore_invalidated++; 715do_invalidate_gitignore(dir); 716} 717 718static voidinvalidate_directory(struct untracked_cache *uc, 719struct untracked_cache_dir *dir) 720{ 721int i; 722 uc->dir_invalidated++; 723 dir->valid =0; 724 dir->untracked_nr =0; 725for(i =0; i < dir->dirs_nr; i++) 726 dir->dirs[i]->recurse =0; 727} 728 729/* 730 * Given a file with name "fname", read it (either from disk, or from 731 * the index if "check_index" is non-zero), parse it and store the 732 * exclude rules in "el". 733 * 734 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 735 * stat data from disk (only valid if add_excludes returns zero). If 736 * ss_valid is non-zero, "ss" must contain good value as input. 737 */ 738static intadd_excludes(const char*fname,const char*base,int baselen, 739struct exclude_list *el,int check_index, 740struct sha1_stat *sha1_stat) 741{ 742struct stat st; 743int fd, i, lineno =1; 744size_t size =0; 745char*buf, *entry; 746 747 fd =open(fname, O_RDONLY); 748if(fd <0||fstat(fd, &st) <0) { 749if(errno != ENOENT) 750warn_on_inaccessible(fname); 751if(0<= fd) 752close(fd); 753if(!check_index || 754(buf =read_skip_worktree_file_from_index(fname, &size, sha1_stat)) == NULL) 755return-1; 756if(size ==0) { 757free(buf); 758return0; 759} 760if(buf[size-1] !='\n') { 761 buf =xrealloc(buf,st_add(size,1)); 762 buf[size++] ='\n'; 763} 764}else{ 765 size =xsize_t(st.st_size); 766if(size ==0) { 767if(sha1_stat) { 768fill_stat_data(&sha1_stat->stat, &st); 769hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 770 sha1_stat->valid =1; 771} 772close(fd); 773return0; 774} 775 buf =xmallocz(size); 776if(read_in_full(fd, buf, size) != size) { 777free(buf); 778close(fd); 779return-1; 780} 781 buf[size++] ='\n'; 782close(fd); 783if(sha1_stat) { 784int pos; 785if(sha1_stat->valid && 786!match_stat_data_racy(&the_index, &sha1_stat->stat, &st)) 787;/* no content change, ss->sha1 still good */ 788else if(check_index && 789(pos =cache_name_pos(fname,strlen(fname))) >=0&& 790!ce_stage(active_cache[pos]) && 791ce_uptodate(active_cache[pos]) && 792!would_convert_to_git(fname)) 793hashcpy(sha1_stat->sha1, 794 active_cache[pos]->oid.hash); 795else 796hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 797fill_stat_data(&sha1_stat->stat, &st); 798 sha1_stat->valid =1; 799} 800} 801 802 el->filebuf = buf; 803 804if(skip_utf8_bom(&buf, size)) 805 size -= buf - el->filebuf; 806 807 entry = buf; 808 809for(i =0; i < size; i++) { 810if(buf[i] =='\n') { 811if(entry != buf + i && entry[0] !='#') { 812 buf[i - (i && buf[i-1] =='\r')] =0; 813trim_trailing_spaces(entry); 814add_exclude(entry, base, baselen, el, lineno); 815} 816 lineno++; 817 entry = buf + i +1; 818} 819} 820return0; 821} 822 823intadd_excludes_from_file_to_list(const char*fname,const char*base, 824int baselen,struct exclude_list *el, 825int check_index) 826{ 827returnadd_excludes(fname, base, baselen, el, check_index, NULL); 828} 829 830struct exclude_list *add_exclude_list(struct dir_struct *dir, 831int group_type,const char*src) 832{ 833struct exclude_list *el; 834struct exclude_list_group *group; 835 836 group = &dir->exclude_list_group[group_type]; 837ALLOC_GROW(group->el, group->nr +1, group->alloc); 838 el = &group->el[group->nr++]; 839memset(el,0,sizeof(*el)); 840 el->src = src; 841return el; 842} 843 844/* 845 * Used to set up core.excludesfile and .git/info/exclude lists. 846 */ 847static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 848struct sha1_stat *sha1_stat) 849{ 850struct exclude_list *el; 851/* 852 * catch setup_standard_excludes() that's called before 853 * dir->untracked is assigned. That function behaves 854 * differently when dir->untracked is non-NULL. 855 */ 856if(!dir->untracked) 857 dir->unmanaged_exclude_files++; 858 el =add_exclude_list(dir, EXC_FILE, fname); 859if(add_excludes(fname,"",0, el,0, sha1_stat) <0) 860die("cannot use%sas an exclude file", fname); 861} 862 863voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 864{ 865 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 866add_excludes_from_file_1(dir, fname, NULL); 867} 868 869intmatch_basename(const char*basename,int basenamelen, 870const char*pattern,int prefix,int patternlen, 871unsigned flags) 872{ 873if(prefix == patternlen) { 874if(patternlen == basenamelen && 875!fspathncmp(pattern, basename, basenamelen)) 876return1; 877}else if(flags & EXC_FLAG_ENDSWITH) { 878/* "*literal" matching against "fooliteral" */ 879if(patternlen -1<= basenamelen && 880!fspathncmp(pattern +1, 881 basename + basenamelen - (patternlen -1), 882 patternlen -1)) 883return1; 884}else{ 885if(fnmatch_icase_mem(pattern, patternlen, 886 basename, basenamelen, 8870) ==0) 888return1; 889} 890return0; 891} 892 893intmatch_pathname(const char*pathname,int pathlen, 894const char*base,int baselen, 895const char*pattern,int prefix,int patternlen, 896unsigned flags) 897{ 898const char*name; 899int namelen; 900 901/* 902 * match with FNM_PATHNAME; the pattern has base implicitly 903 * in front of it. 904 */ 905if(*pattern =='/') { 906 pattern++; 907 patternlen--; 908 prefix--; 909} 910 911/* 912 * baselen does not count the trailing slash. base[] may or 913 * may not end with a trailing slash though. 914 */ 915if(pathlen < baselen +1|| 916(baselen && pathname[baselen] !='/') || 917fspathncmp(pathname, base, baselen)) 918return0; 919 920 namelen = baselen ? pathlen - baselen -1: pathlen; 921 name = pathname + pathlen - namelen; 922 923if(prefix) { 924/* 925 * if the non-wildcard part is longer than the 926 * remaining pathname, surely it cannot match. 927 */ 928if(prefix > namelen) 929return0; 930 931if(fspathncmp(pattern, name, prefix)) 932return0; 933 pattern += prefix; 934 patternlen -= prefix; 935 name += prefix; 936 namelen -= prefix; 937 938/* 939 * If the whole pattern did not have a wildcard, 940 * then our prefix match is all we need; we 941 * do not need to call fnmatch at all. 942 */ 943if(!patternlen && !namelen) 944return1; 945} 946 947returnfnmatch_icase_mem(pattern, patternlen, 948 name, namelen, 949 WM_PATHNAME) ==0; 950} 951 952/* 953 * Scan the given exclude list in reverse to see whether pathname 954 * should be ignored. The first match (i.e. the last on the list), if 955 * any, determines the fate. Returns the exclude_list element which 956 * matched, or NULL for undecided. 957 */ 958static struct exclude *last_exclude_matching_from_list(const char*pathname, 959int pathlen, 960const char*basename, 961int*dtype, 962struct exclude_list *el) 963{ 964struct exclude *exc = NULL;/* undecided */ 965int i; 966 967if(!el->nr) 968return NULL;/* undefined */ 969 970for(i = el->nr -1;0<= i; i--) { 971struct exclude *x = el->excludes[i]; 972const char*exclude = x->pattern; 973int prefix = x->nowildcardlen; 974 975if(x->flags & EXC_FLAG_MUSTBEDIR) { 976if(*dtype == DT_UNKNOWN) 977*dtype =get_dtype(NULL, pathname, pathlen); 978if(*dtype != DT_DIR) 979continue; 980} 981 982if(x->flags & EXC_FLAG_NODIR) { 983if(match_basename(basename, 984 pathlen - (basename - pathname), 985 exclude, prefix, x->patternlen, 986 x->flags)) { 987 exc = x; 988break; 989} 990continue; 991} 992 993assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 994if(match_pathname(pathname, pathlen, 995 x->base, x->baselen ? x->baselen -1:0, 996 exclude, prefix, x->patternlen, x->flags)) { 997 exc = x; 998break; 999}1000}1001return exc;1002}10031004/*1005 * Scan the list and let the last match determine the fate.1006 * Return 1 for exclude, 0 for include and -1 for undecided.1007 */1008intis_excluded_from_list(const char*pathname,1009int pathlen,const char*basename,int*dtype,1010struct exclude_list *el)1011{1012struct exclude *exclude;1013 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el);1014if(exclude)1015return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1016return-1;/* undecided */1017}10181019static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir,1020const char*pathname,int pathlen,const char*basename,1021int*dtype_p)1022{1023int i, j;1024struct exclude_list_group *group;1025struct exclude *exclude;1026for(i = EXC_CMDL; i <= EXC_FILE; i++) {1027 group = &dir->exclude_list_group[i];1028for(j = group->nr -1; j >=0; j--) {1029 exclude =last_exclude_matching_from_list(1030 pathname, pathlen, basename, dtype_p,1031&group->el[j]);1032if(exclude)1033return exclude;1034}1035}1036return NULL;1037}10381039/*1040 * Loads the per-directory exclude list for the substring of base1041 * which has a char length of baselen.1042 */1043static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen)1044{1045struct exclude_list_group *group;1046struct exclude_list *el;1047struct exclude_stack *stk = NULL;1048struct untracked_cache_dir *untracked;1049int current;10501051 group = &dir->exclude_list_group[EXC_DIRS];10521053/*1054 * Pop the exclude lists from the EXCL_DIRS exclude_list_group1055 * which originate from directories not in the prefix of the1056 * path being checked.1057 */1058while((stk = dir->exclude_stack) != NULL) {1059if(stk->baselen <= baselen &&1060!strncmp(dir->basebuf.buf, base, stk->baselen))1061break;1062 el = &group->el[dir->exclude_stack->exclude_ix];1063 dir->exclude_stack = stk->prev;1064 dir->exclude = NULL;1065free((char*)el->src);/* see strbuf_detach() below */1066clear_exclude_list(el);1067free(stk);1068 group->nr--;1069}10701071/* Skip traversing into sub directories if the parent is excluded */1072if(dir->exclude)1073return;10741075/*1076 * Lazy initialization. All call sites currently just1077 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1078 * them seems lots of work for little benefit.1079 */1080if(!dir->basebuf.buf)1081strbuf_init(&dir->basebuf, PATH_MAX);10821083/* Read from the parent directories and push them down. */1084 current = stk ? stk->baselen : -1;1085strbuf_setlen(&dir->basebuf, current <0?0: current);1086if(dir->untracked)1087 untracked = stk ? stk->ucd : dir->untracked->root;1088else1089 untracked = NULL;10901091while(current < baselen) {1092const char*cp;1093struct sha1_stat sha1_stat;10941095 stk =xcalloc(1,sizeof(*stk));1096if(current <0) {1097 cp = base;1098 current =0;1099}else{1100 cp =strchr(base + current +1,'/');1101if(!cp)1102die("oops in prep_exclude");1103 cp++;1104 untracked =1105lookup_untracked(dir->untracked, untracked,1106 base + current,1107 cp - base - current);1108}1109 stk->prev = dir->exclude_stack;1110 stk->baselen = cp - base;1111 stk->exclude_ix = group->nr;1112 stk->ucd = untracked;1113 el =add_exclude_list(dir, EXC_DIRS, NULL);1114strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1115assert(stk->baselen == dir->basebuf.len);11161117/* Abort if the directory is excluded */1118if(stk->baselen) {1119int dt = DT_DIR;1120 dir->basebuf.buf[stk->baselen -1] =0;1121 dir->exclude =last_exclude_matching_from_lists(dir,1122 dir->basebuf.buf, stk->baselen -1,1123 dir->basebuf.buf + current, &dt);1124 dir->basebuf.buf[stk->baselen -1] ='/';1125if(dir->exclude &&1126 dir->exclude->flags & EXC_FLAG_NEGATIVE)1127 dir->exclude = NULL;1128if(dir->exclude) {1129 dir->exclude_stack = stk;1130return;1131}1132}11331134/* Try to read per-directory file */1135hashclr(sha1_stat.sha1);1136 sha1_stat.valid =0;1137if(dir->exclude_per_dir &&1138/*1139 * If we know that no files have been added in1140 * this directory (i.e. valid_cached_dir() has1141 * been executed and set untracked->valid) ..1142 */1143(!untracked || !untracked->valid ||1144/*1145 * .. and .gitignore does not exist before1146 * (i.e. null exclude_sha1). Then we can skip1147 * loading .gitignore, which would result in1148 * ENOENT anyway.1149 */1150!is_null_sha1(untracked->exclude_sha1))) {1151/*1152 * dir->basebuf gets reused by the traversal, but we1153 * need fname to remain unchanged to ensure the src1154 * member of each struct exclude correctly1155 * back-references its source file. Other invocations1156 * of add_exclude_list provide stable strings, so we1157 * strbuf_detach() and free() here in the caller.1158 */1159struct strbuf sb = STRBUF_INIT;1160strbuf_addbuf(&sb, &dir->basebuf);1161strbuf_addstr(&sb, dir->exclude_per_dir);1162 el->src =strbuf_detach(&sb, NULL);1163add_excludes(el->src, el->src, stk->baselen, el,1,1164 untracked ? &sha1_stat : NULL);1165}1166/*1167 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1168 * will first be called in valid_cached_dir() then maybe many1169 * times more in last_exclude_matching(). When the cache is1170 * used, last_exclude_matching() will not be called and1171 * reading .gitignore content will be a waste.1172 *1173 * So when it's called by valid_cached_dir() and we can get1174 * .gitignore SHA-1 from the index (i.e. .gitignore is not1175 * modified on work tree), we could delay reading the1176 * .gitignore content until we absolutely need it in1177 * last_exclude_matching(). Be careful about ignore rule1178 * order, though, if you do that.1179 */1180if(untracked &&1181hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1182invalidate_gitignore(dir->untracked, untracked);1183hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1184}1185 dir->exclude_stack = stk;1186 current = stk->baselen;1187}1188strbuf_setlen(&dir->basebuf, baselen);1189}11901191/*1192 * Loads the exclude lists for the directory containing pathname, then1193 * scans all exclude lists to determine whether pathname is excluded.1194 * Returns the exclude_list element which matched, or NULL for1195 * undecided.1196 */1197struct exclude *last_exclude_matching(struct dir_struct *dir,1198const char*pathname,1199int*dtype_p)1200{1201int pathlen =strlen(pathname);1202const char*basename =strrchr(pathname,'/');1203 basename = (basename) ? basename+1: pathname;12041205prep_exclude(dir, pathname, basename-pathname);12061207if(dir->exclude)1208return dir->exclude;12091210returnlast_exclude_matching_from_lists(dir, pathname, pathlen,1211 basename, dtype_p);1212}12131214/*1215 * Loads the exclude lists for the directory containing pathname, then1216 * scans all exclude lists to determine whether pathname is excluded.1217 * Returns 1 if true, otherwise 0.1218 */1219intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p)1220{1221struct exclude *exclude =1222last_exclude_matching(dir, pathname, dtype_p);1223if(exclude)1224return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1225return0;1226}12271228static struct dir_entry *dir_entry_new(const char*pathname,int len)1229{1230struct dir_entry *ent;12311232FLEX_ALLOC_MEM(ent, name, pathname, len);1233 ent->len = len;1234return ent;1235}12361237static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len)1238{1239if(cache_file_exists(pathname, len, ignore_case))1240return NULL;12411242ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1243return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1244}12451246struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len)1247{1248if(!cache_name_is_other(pathname, len))1249return NULL;12501251ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1252return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1253}12541255enum exist_status {1256 index_nonexistent =0,1257 index_directory,1258 index_gitdir1259};12601261/*1262 * Do not use the alphabetically sorted index to look up1263 * the directory name; instead, use the case insensitive1264 * directory hash.1265 */1266static enum exist_status directory_exists_in_index_icase(const char*dirname,int len)1267{1268struct cache_entry *ce;12691270if(cache_dir_exists(dirname, len))1271return index_directory;12721273 ce =cache_file_exists(dirname, len, ignore_case);1274if(ce &&S_ISGITLINK(ce->ce_mode))1275return index_gitdir;12761277return index_nonexistent;1278}12791280/*1281 * The index sorts alphabetically by entry name, which1282 * means that a gitlink sorts as '\0' at the end, while1283 * a directory (which is defined not as an entry, but as1284 * the files it contains) will sort with the '/' at the1285 * end.1286 */1287static enum exist_status directory_exists_in_index(const char*dirname,int len)1288{1289int pos;12901291if(ignore_case)1292returndirectory_exists_in_index_icase(dirname, len);12931294 pos =cache_name_pos(dirname, len);1295if(pos <0)1296 pos = -pos-1;1297while(pos < active_nr) {1298const struct cache_entry *ce = active_cache[pos++];1299unsigned char endchar;13001301if(strncmp(ce->name, dirname, len))1302break;1303 endchar = ce->name[len];1304if(endchar >'/')1305break;1306if(endchar =='/')1307return index_directory;1308if(!endchar &&S_ISGITLINK(ce->ce_mode))1309return index_gitdir;1310}1311return index_nonexistent;1312}13131314/*1315 * When we find a directory when traversing the filesystem, we1316 * have three distinct cases:1317 *1318 * - ignore it1319 * - see it as a directory1320 * - recurse into it1321 *1322 * and which one we choose depends on a combination of existing1323 * git index contents and the flags passed into the directory1324 * traversal routine.1325 *1326 * Case 1: If we *already* have entries in the index under that1327 * directory name, we always recurse into the directory to see1328 * all the files.1329 *1330 * Case 2: If we *already* have that directory name as a gitlink,1331 * we always continue to see it as a gitlink, regardless of whether1332 * there is an actual git directory there or not (it might not1333 * be checked out as a subproject!)1334 *1335 * Case 3: if we didn't have it in the index previously, we1336 * have a few sub-cases:1337 *1338 * (a) if "show_other_directories" is true, we show it as1339 * just a directory, unless "hide_empty_directories" is1340 * also true, in which case we need to check if it contains any1341 * untracked and / or ignored files.1342 * (b) if it looks like a git directory, and we don't have1343 * 'no_gitlinks' set we treat it as a gitlink, and show it1344 * as a directory.1345 * (c) otherwise, we recurse into it.1346 */1347static enum path_treatment treat_directory(struct dir_struct *dir,1348struct untracked_cache_dir *untracked,1349const char*dirname,int len,int baselen,int exclude,1350const struct pathspec *pathspec)1351{1352/* The "len-1" is to strip the final '/' */1353switch(directory_exists_in_index(dirname, len-1)) {1354case index_directory:1355return path_recurse;13561357case index_gitdir:1358return path_none;13591360case index_nonexistent:1361if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1362break;1363if(!(dir->flags & DIR_NO_GITLINKS)) {1364unsigned char sha1[20];1365if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1366return path_untracked;1367}1368return path_recurse;1369}13701371/* This is the "show_other_directories" case */13721373if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1374return exclude ? path_excluded : path_untracked;13751376 untracked =lookup_untracked(dir->untracked, untracked,1377 dirname + baselen, len - baselen);1378returnread_directory_recursive(dir, dirname, len,1379 untracked,1, pathspec);1380}13811382/*1383 * This is an inexact early pruning of any recursive directory1384 * reading - if the path cannot possibly be in the pathspec,1385 * return true, and we'll skip it early.1386 */1387static intsimplify_away(const char*path,int pathlen,1388const struct pathspec *pathspec)1389{1390int i;13911392if(!pathspec || !pathspec->nr)1393return0;13941395GUARD_PATHSPEC(pathspec,1396 PATHSPEC_FROMTOP |1397 PATHSPEC_MAXDEPTH |1398 PATHSPEC_LITERAL |1399 PATHSPEC_GLOB |1400 PATHSPEC_ICASE |1401 PATHSPEC_EXCLUDE |1402 PATHSPEC_ATTR);14031404for(i =0; i < pathspec->nr; i++) {1405const struct pathspec_item *item = &pathspec->items[i];1406int len = item->nowildcard_len;14071408if(len > pathlen)1409 len = pathlen;1410if(!ps_strncmp(item, item->match, path, len))1411return0;1412}14131414return1;1415}14161417/*1418 * This function tells us whether an excluded path matches a1419 * list of "interesting" pathspecs. That is, whether a path matched1420 * by any of the pathspecs could possibly be ignored by excluding1421 * the specified path. This can happen if:1422 *1423 * 1. the path is mentioned explicitly in the pathspec1424 *1425 * 2. the path is a directory prefix of some element in the1426 * pathspec1427 */1428static intexclude_matches_pathspec(const char*path,int pathlen,1429const struct pathspec *pathspec)1430{1431int i;14321433if(!pathspec || !pathspec->nr)1434return0;14351436GUARD_PATHSPEC(pathspec,1437 PATHSPEC_FROMTOP |1438 PATHSPEC_MAXDEPTH |1439 PATHSPEC_LITERAL |1440 PATHSPEC_GLOB |1441 PATHSPEC_ICASE |1442 PATHSPEC_EXCLUDE);14431444for(i =0; i < pathspec->nr; i++) {1445const struct pathspec_item *item = &pathspec->items[i];1446int len = item->nowildcard_len;14471448if(len == pathlen &&1449!ps_strncmp(item, item->match, path, pathlen))1450return1;1451if(len > pathlen &&1452 item->match[pathlen] =='/'&&1453!ps_strncmp(item, item->match, path, pathlen))1454return1;1455}1456return0;1457}14581459static intget_index_dtype(const char*path,int len)1460{1461int pos;1462const struct cache_entry *ce;14631464 ce =cache_file_exists(path, len,0);1465if(ce) {1466if(!ce_uptodate(ce))1467return DT_UNKNOWN;1468if(S_ISGITLINK(ce->ce_mode))1469return DT_DIR;1470/*1471 * Nobody actually cares about the1472 * difference between DT_LNK and DT_REG1473 */1474return DT_REG;1475}14761477/* Try to look it up as a directory */1478 pos =cache_name_pos(path, len);1479if(pos >=0)1480return DT_UNKNOWN;1481 pos = -pos-1;1482while(pos < active_nr) {1483 ce = active_cache[pos++];1484if(strncmp(ce->name, path, len))1485break;1486if(ce->name[len] >'/')1487break;1488if(ce->name[len] <'/')1489continue;1490if(!ce_uptodate(ce))1491break;/* continue? */1492return DT_DIR;1493}1494return DT_UNKNOWN;1495}14961497static intget_dtype(struct dirent *de,const char*path,int len)1498{1499int dtype = de ?DTYPE(de) : DT_UNKNOWN;1500struct stat st;15011502if(dtype != DT_UNKNOWN)1503return dtype;1504 dtype =get_index_dtype(path, len);1505if(dtype != DT_UNKNOWN)1506return dtype;1507if(lstat(path, &st))1508return dtype;1509if(S_ISREG(st.st_mode))1510return DT_REG;1511if(S_ISDIR(st.st_mode))1512return DT_DIR;1513if(S_ISLNK(st.st_mode))1514return DT_LNK;1515return dtype;1516}15171518static enum path_treatment treat_one_path(struct dir_struct *dir,1519struct untracked_cache_dir *untracked,1520struct strbuf *path,1521int baselen,1522const struct pathspec *pathspec,1523int dtype,struct dirent *de)1524{1525int exclude;1526int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);15271528if(dtype == DT_UNKNOWN)1529 dtype =get_dtype(de, path->buf, path->len);15301531/* Always exclude indexed files */1532if(dtype != DT_DIR && has_path_in_index)1533return path_none;15341535/*1536 * When we are looking at a directory P in the working tree,1537 * there are three cases:1538 *1539 * (1) P exists in the index. Everything inside the directory P in1540 * the working tree needs to go when P is checked out from the1541 * index.1542 *1543 * (2) P does not exist in the index, but there is P/Q in the index.1544 * We know P will stay a directory when we check out the contents1545 * of the index, but we do not know yet if there is a directory1546 * P/Q in the working tree to be killed, so we need to recurse.1547 *1548 * (3) P does not exist in the index, and there is no P/Q in the index1549 * to require P to be a directory, either. Only in this case, we1550 * know that everything inside P will not be killed without1551 * recursing.1552 */1553if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1554(dtype == DT_DIR) &&1555!has_path_in_index &&1556(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1557return path_none;15581559 exclude =is_excluded(dir, path->buf, &dtype);15601561/*1562 * Excluded? If we don't explicitly want to show1563 * ignored files, ignore it1564 */1565if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1566return path_excluded;15671568switch(dtype) {1569default:1570return path_none;1571case DT_DIR:1572strbuf_addch(path,'/');1573returntreat_directory(dir, untracked, path->buf, path->len,1574 baselen, exclude, pathspec);1575case DT_REG:1576case DT_LNK:1577return exclude ? path_excluded : path_untracked;1578}1579}15801581static enum path_treatment treat_path_fast(struct dir_struct *dir,1582struct untracked_cache_dir *untracked,1583struct cached_dir *cdir,1584struct strbuf *path,1585int baselen,1586const struct pathspec *pathspec)1587{1588strbuf_setlen(path, baselen);1589if(!cdir->ucd) {1590strbuf_addstr(path, cdir->file);1591return path_untracked;1592}1593strbuf_addstr(path, cdir->ucd->name);1594/* treat_one_path() does this before it calls treat_directory() */1595strbuf_complete(path,'/');1596if(cdir->ucd->check_only)1597/*1598 * check_only is set as a result of treat_directory() getting1599 * to its bottom. Verify again the same set of directories1600 * with check_only set.1601 */1602returnread_directory_recursive(dir, path->buf, path->len,1603 cdir->ucd,1, pathspec);1604/*1605 * We get path_recurse in the first run when1606 * directory_exists_in_index() returns index_nonexistent. We1607 * are sure that new changes in the index does not impact the1608 * outcome. Return now.1609 */1610return path_recurse;1611}16121613static enum path_treatment treat_path(struct dir_struct *dir,1614struct untracked_cache_dir *untracked,1615struct cached_dir *cdir,1616struct strbuf *path,1617int baselen,1618const struct pathspec *pathspec)1619{1620int dtype;1621struct dirent *de = cdir->de;16221623if(!de)1624returntreat_path_fast(dir, untracked, cdir, path,1625 baselen, pathspec);1626if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1627return path_none;1628strbuf_setlen(path, baselen);1629strbuf_addstr(path, de->d_name);1630if(simplify_away(path->buf, path->len, pathspec))1631return path_none;16321633 dtype =DTYPE(de);1634returntreat_one_path(dir, untracked, path, baselen, pathspec, dtype, de);1635}16361637static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1638{1639if(!dir)1640return;1641ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1642 dir->untracked_alloc);1643 dir->untracked[dir->untracked_nr++] =xstrdup(name);1644}16451646static intvalid_cached_dir(struct dir_struct *dir,1647struct untracked_cache_dir *untracked,1648struct strbuf *path,1649int check_only)1650{1651struct stat st;16521653if(!untracked)1654return0;16551656if(stat(path->len ? path->buf :".", &st)) {1657invalidate_directory(dir->untracked, untracked);1658memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1659return0;1660}1661if(!untracked->valid ||1662match_stat_data_racy(&the_index, &untracked->stat_data, &st)) {1663if(untracked->valid)1664invalidate_directory(dir->untracked, untracked);1665fill_stat_data(&untracked->stat_data, &st);1666return0;1667}16681669if(untracked->check_only != !!check_only) {1670invalidate_directory(dir->untracked, untracked);1671return0;1672}16731674/*1675 * prep_exclude will be called eventually on this directory,1676 * but it's called much later in last_exclude_matching(). We1677 * need it now to determine the validity of the cache for this1678 * path. The next calls will be nearly no-op, the way1679 * prep_exclude() is designed.1680 */1681if(path->len && path->buf[path->len -1] !='/') {1682strbuf_addch(path,'/');1683prep_exclude(dir, path->buf, path->len);1684strbuf_setlen(path, path->len -1);1685}else1686prep_exclude(dir, path->buf, path->len);16871688/* hopefully prep_exclude() haven't invalidated this entry... */1689return untracked->valid;1690}16911692static intopen_cached_dir(struct cached_dir *cdir,1693struct dir_struct *dir,1694struct untracked_cache_dir *untracked,1695struct strbuf *path,1696int check_only)1697{1698memset(cdir,0,sizeof(*cdir));1699 cdir->untracked = untracked;1700if(valid_cached_dir(dir, untracked, path, check_only))1701return0;1702 cdir->fdir =opendir(path->len ? path->buf :".");1703if(dir->untracked)1704 dir->untracked->dir_opened++;1705if(!cdir->fdir)1706return-1;1707return0;1708}17091710static intread_cached_dir(struct cached_dir *cdir)1711{1712if(cdir->fdir) {1713 cdir->de =readdir(cdir->fdir);1714if(!cdir->de)1715return-1;1716return0;1717}1718while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1719struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1720if(!d->recurse) {1721 cdir->nr_dirs++;1722continue;1723}1724 cdir->ucd = d;1725 cdir->nr_dirs++;1726return0;1727}1728 cdir->ucd = NULL;1729if(cdir->nr_files < cdir->untracked->untracked_nr) {1730struct untracked_cache_dir *d = cdir->untracked;1731 cdir->file = d->untracked[cdir->nr_files++];1732return0;1733}1734return-1;1735}17361737static voidclose_cached_dir(struct cached_dir *cdir)1738{1739if(cdir->fdir)1740closedir(cdir->fdir);1741/*1742 * We have gone through this directory and found no untracked1743 * entries. Mark it valid.1744 */1745if(cdir->untracked) {1746 cdir->untracked->valid =1;1747 cdir->untracked->recurse =1;1748}1749}17501751/*1752 * Read a directory tree. We currently ignore anything but1753 * directories, regular files and symlinks. That's because git1754 * doesn't handle them at all yet. Maybe that will change some1755 * day.1756 *1757 * Also, we ignore the name ".git" (even if it is not a directory).1758 * That likely will not change.1759 *1760 * Returns the most significant path_treatment value encountered in the scan.1761 */1762static enum path_treatment read_directory_recursive(struct dir_struct *dir,1763const char*base,int baselen,1764struct untracked_cache_dir *untracked,int check_only,1765const struct pathspec *pathspec)1766{1767struct cached_dir cdir;1768enum path_treatment state, subdir_state, dir_state = path_none;1769struct strbuf path = STRBUF_INIT;17701771strbuf_add(&path, base, baselen);17721773if(open_cached_dir(&cdir, dir, untracked, &path, check_only))1774goto out;17751776if(untracked)1777 untracked->check_only = !!check_only;17781779while(!read_cached_dir(&cdir)) {1780/* check how the file or directory should be treated */1781 state =treat_path(dir, untracked, &cdir, &path,1782 baselen, pathspec);17831784if(state > dir_state)1785 dir_state = state;17861787/* recurse into subdir if instructed by treat_path */1788if(state == path_recurse) {1789struct untracked_cache_dir *ud;1790 ud =lookup_untracked(dir->untracked, untracked,1791 path.buf + baselen,1792 path.len - baselen);1793 subdir_state =1794read_directory_recursive(dir, path.buf,1795 path.len, ud,1796 check_only, pathspec);1797if(subdir_state > dir_state)1798 dir_state = subdir_state;1799}18001801if(check_only) {1802/* abort early if maximum state has been reached */1803if(dir_state == path_untracked) {1804if(cdir.fdir)1805add_untracked(untracked, path.buf + baselen);1806break;1807}1808/* skip the dir_add_* part */1809continue;1810}18111812/* add the path to the appropriate result list */1813switch(state) {1814case path_excluded:1815if(dir->flags & DIR_SHOW_IGNORED)1816dir_add_name(dir, path.buf, path.len);1817else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1818((dir->flags & DIR_COLLECT_IGNORED) &&1819exclude_matches_pathspec(path.buf, path.len,1820 pathspec)))1821dir_add_ignored(dir, path.buf, path.len);1822break;18231824case path_untracked:1825if(dir->flags & DIR_SHOW_IGNORED)1826break;1827dir_add_name(dir, path.buf, path.len);1828if(cdir.fdir)1829add_untracked(untracked, path.buf + baselen);1830break;18311832default:1833break;1834}1835}1836close_cached_dir(&cdir);1837 out:1838strbuf_release(&path);18391840return dir_state;1841}18421843static intcmp_name(const void*p1,const void*p2)1844{1845const struct dir_entry *e1 = *(const struct dir_entry **)p1;1846const struct dir_entry *e2 = *(const struct dir_entry **)p2;18471848returnname_compare(e1->name, e1->len, e2->name, e2->len);1849}18501851static inttreat_leading_path(struct dir_struct *dir,1852const char*path,int len,1853const struct pathspec *pathspec)1854{1855struct strbuf sb = STRBUF_INIT;1856int baselen, rc =0;1857const char*cp;1858int old_flags = dir->flags;18591860while(len && path[len -1] =='/')1861 len--;1862if(!len)1863return1;1864 baselen =0;1865 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1866while(1) {1867 cp = path + baselen + !!baselen;1868 cp =memchr(cp,'/', path + len - cp);1869if(!cp)1870 baselen = len;1871else1872 baselen = cp - path;1873strbuf_setlen(&sb,0);1874strbuf_add(&sb, path, baselen);1875if(!is_directory(sb.buf))1876break;1877if(simplify_away(sb.buf, sb.len, pathspec))1878break;1879if(treat_one_path(dir, NULL, &sb, baselen, pathspec,1880 DT_DIR, NULL) == path_none)1881break;/* do not recurse into it */1882if(len <= baselen) {1883 rc =1;1884break;/* finished checking */1885}1886}1887strbuf_release(&sb);1888 dir->flags = old_flags;1889return rc;1890}18911892static const char*get_ident_string(void)1893{1894static struct strbuf sb = STRBUF_INIT;1895struct utsname uts;18961897if(sb.len)1898return sb.buf;1899if(uname(&uts) <0)1900die_errno(_("failed to get kernel name and information"));1901strbuf_addf(&sb,"Location%s, system%s",get_git_work_tree(),1902 uts.sysname);1903return sb.buf;1904}19051906static intident_in_untracked(const struct untracked_cache *uc)1907{1908/*1909 * Previous git versions may have saved many NUL separated1910 * strings in the "ident" field, but it is insane to manage1911 * many locations, so just take care of the first one.1912 */19131914return!strcmp(uc->ident.buf,get_ident_string());1915}19161917static voidset_untracked_ident(struct untracked_cache *uc)1918{1919strbuf_reset(&uc->ident);1920strbuf_addstr(&uc->ident,get_ident_string());19211922/*1923 * This strbuf used to contain a list of NUL separated1924 * strings, so save NUL too for backward compatibility.1925 */1926strbuf_addch(&uc->ident,0);1927}19281929static voidnew_untracked_cache(struct index_state *istate)1930{1931struct untracked_cache *uc =xcalloc(1,sizeof(*uc));1932strbuf_init(&uc->ident,100);1933 uc->exclude_per_dir =".gitignore";1934/* should be the same flags used by git-status */1935 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;1936set_untracked_ident(uc);1937 istate->untracked = uc;1938 istate->cache_changed |= UNTRACKED_CHANGED;1939}19401941voidadd_untracked_cache(struct index_state *istate)1942{1943if(!istate->untracked) {1944new_untracked_cache(istate);1945}else{1946if(!ident_in_untracked(istate->untracked)) {1947free_untracked_cache(istate->untracked);1948new_untracked_cache(istate);1949}1950}1951}19521953voidremove_untracked_cache(struct index_state *istate)1954{1955if(istate->untracked) {1956free_untracked_cache(istate->untracked);1957 istate->untracked = NULL;1958 istate->cache_changed |= UNTRACKED_CHANGED;1959}1960}19611962static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,1963int base_len,1964const struct pathspec *pathspec)1965{1966struct untracked_cache_dir *root;19671968if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))1969return NULL;19701971/*1972 * We only support $GIT_DIR/info/exclude and core.excludesfile1973 * as the global ignore rule files. Any other additions1974 * (e.g. from command line) invalidate the cache. This1975 * condition also catches running setup_standard_excludes()1976 * before setting dir->untracked!1977 */1978if(dir->unmanaged_exclude_files)1979return NULL;19801981/*1982 * Optimize for the main use case only: whole-tree git1983 * status. More work involved in treat_leading_path() if we1984 * use cache on just a subset of the worktree. pathspec1985 * support could make the matter even worse.1986 */1987if(base_len || (pathspec && pathspec->nr))1988return NULL;19891990/* Different set of flags may produce different results */1991if(dir->flags != dir->untracked->dir_flags ||1992/*1993 * See treat_directory(), case index_nonexistent. Without1994 * this flag, we may need to also cache .git file content1995 * for the resolve_gitlink_ref() call, which we don't.1996 */1997!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||1998/* We don't support collecting ignore files */1999(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |2000 DIR_COLLECT_IGNORED)))2001return NULL;20022003/*2004 * If we use .gitignore in the cache and now you change it to2005 * .gitexclude, everything will go wrong.2006 */2007if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&2008strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))2009return NULL;20102011/*2012 * EXC_CMDL is not considered in the cache. If people set it,2013 * skip the cache.2014 */2015if(dir->exclude_list_group[EXC_CMDL].nr)2016return NULL;20172018if(!ident_in_untracked(dir->untracked)) {2019warning(_("Untracked cache is disabled on this system or location."));2020return NULL;2021}20222023if(!dir->untracked->root) {2024const int len =sizeof(*dir->untracked->root);2025 dir->untracked->root =xmalloc(len);2026memset(dir->untracked->root,0, len);2027}20282029/* Validate $GIT_DIR/info/exclude and core.excludesfile */2030 root = dir->untracked->root;2031if(hashcmp(dir->ss_info_exclude.sha1,2032 dir->untracked->ss_info_exclude.sha1)) {2033invalidate_gitignore(dir->untracked, root);2034 dir->untracked->ss_info_exclude = dir->ss_info_exclude;2035}2036if(hashcmp(dir->ss_excludes_file.sha1,2037 dir->untracked->ss_excludes_file.sha1)) {2038invalidate_gitignore(dir->untracked, root);2039 dir->untracked->ss_excludes_file = dir->ss_excludes_file;2040}20412042/* Make sure this directory is not dropped out at saving phase */2043 root->recurse =1;2044return root;2045}20462047intread_directory(struct dir_struct *dir,const char*path,2048int len,const struct pathspec *pathspec)2049{2050struct untracked_cache_dir *untracked;20512052if(has_symlink_leading_path(path, len))2053return dir->nr;20542055 untracked =validate_untracked_cache(dir, len, pathspec);2056if(!untracked)2057/*2058 * make sure untracked cache code path is disabled,2059 * e.g. prep_exclude()2060 */2061 dir->untracked = NULL;2062if(!len ||treat_leading_path(dir, path, len, pathspec))2063read_directory_recursive(dir, path, len, untracked,0, pathspec);2064QSORT(dir->entries, dir->nr, cmp_name);2065QSORT(dir->ignored, dir->ignored_nr, cmp_name);2066if(dir->untracked) {2067static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);2068trace_printf_key(&trace_untracked_stats,2069"node creation:%u\n"2070"gitignore invalidation:%u\n"2071"directory invalidation:%u\n"2072"opendir:%u\n",2073 dir->untracked->dir_created,2074 dir->untracked->gitignore_invalidated,2075 dir->untracked->dir_invalidated,2076 dir->untracked->dir_opened);2077if(dir->untracked == the_index.untracked &&2078(dir->untracked->dir_opened ||2079 dir->untracked->gitignore_invalidated ||2080 dir->untracked->dir_invalidated))2081 the_index.cache_changed |= UNTRACKED_CHANGED;2082if(dir->untracked != the_index.untracked) {2083free(dir->untracked);2084 dir->untracked = NULL;2085}2086}2087return dir->nr;2088}20892090intfile_exists(const char*f)2091{2092struct stat sb;2093returnlstat(f, &sb) ==0;2094}20952096static intcmp_icase(char a,char b)2097{2098if(a == b)2099return0;2100if(ignore_case)2101returntoupper(a) -toupper(b);2102return a - b;2103}21042105/*2106 * Given two normalized paths (a trailing slash is ok), if subdir is2107 * outside dir, return -1. Otherwise return the offset in subdir that2108 * can be used as relative path to dir.2109 */2110intdir_inside_of(const char*subdir,const char*dir)2111{2112int offset =0;21132114assert(dir && subdir && *dir && *subdir);21152116while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2117 dir++;2118 subdir++;2119 offset++;2120}21212122/* hel[p]/me vs hel[l]/yeah */2123if(*dir && *subdir)2124return-1;21252126if(!*subdir)2127return!*dir ? offset : -1;/* same dir */21282129/* foo/[b]ar vs foo/[] */2130if(is_dir_sep(dir[-1]))2131returnis_dir_sep(subdir[-1]) ? offset : -1;21322133/* foo[/]bar vs foo[] */2134returnis_dir_sep(*subdir) ? offset +1: -1;2135}21362137intis_inside_dir(const char*dir)2138{2139char*cwd;2140int rc;21412142if(!dir)2143return0;21442145 cwd =xgetcwd();2146 rc = (dir_inside_of(cwd, dir) >=0);2147free(cwd);2148return rc;2149}21502151intis_empty_dir(const char*path)2152{2153DIR*dir =opendir(path);2154struct dirent *e;2155int ret =1;21562157if(!dir)2158return0;21592160while((e =readdir(dir)) != NULL)2161if(!is_dot_or_dotdot(e->d_name)) {2162 ret =0;2163break;2164}21652166closedir(dir);2167return ret;2168}21692170static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2171{2172DIR*dir;2173struct dirent *e;2174int ret =0, original_len = path->len, len, kept_down =0;2175int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2176int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2177unsigned char submodule_head[20];21782179if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2180!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2181/* Do not descend and nuke a nested git work tree. */2182if(kept_up)2183*kept_up =1;2184return0;2185}21862187 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2188 dir =opendir(path->buf);2189if(!dir) {2190if(errno == ENOENT)2191return keep_toplevel ? -1:0;2192else if(errno == EACCES && !keep_toplevel)2193/*2194 * An empty dir could be removable even if it2195 * is unreadable:2196 */2197returnrmdir(path->buf);2198else2199return-1;2200}2201strbuf_complete(path,'/');22022203 len = path->len;2204while((e =readdir(dir)) != NULL) {2205struct stat st;2206if(is_dot_or_dotdot(e->d_name))2207continue;22082209strbuf_setlen(path, len);2210strbuf_addstr(path, e->d_name);2211if(lstat(path->buf, &st)) {2212if(errno == ENOENT)2213/*2214 * file disappeared, which is what we2215 * wanted anyway2216 */2217continue;2218/* fall thru */2219}else if(S_ISDIR(st.st_mode)) {2220if(!remove_dir_recurse(path, flag, &kept_down))2221continue;/* happy */2222}else if(!only_empty &&2223(!unlink(path->buf) || errno == ENOENT)) {2224continue;/* happy, too */2225}22262227/* path too long, stat fails, or non-directory still exists */2228 ret = -1;2229break;2230}2231closedir(dir);22322233strbuf_setlen(path, original_len);2234if(!ret && !keep_toplevel && !kept_down)2235 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2236else if(kept_up)2237/*2238 * report the uplevel that it is not an error that we2239 * did not rmdir() our directory.2240 */2241*kept_up = !ret;2242return ret;2243}22442245intremove_dir_recursively(struct strbuf *path,int flag)2246{2247returnremove_dir_recurse(path, flag, NULL);2248}22492250staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")22512252voidsetup_standard_excludes(struct dir_struct *dir)2253{2254 dir->exclude_per_dir =".gitignore";22552256/* core.excludefile defaulting to $XDG_HOME/git/ignore */2257if(!excludes_file)2258 excludes_file =xdg_config_home("ignore");2259if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2260add_excludes_from_file_1(dir, excludes_file,2261 dir->untracked ? &dir->ss_excludes_file : NULL);22622263/* per repository user preference */2264if(startup_info->have_repository) {2265const char*path =git_path_info_exclude();2266if(!access_or_warn(path, R_OK,0))2267add_excludes_from_file_1(dir, path,2268 dir->untracked ? &dir->ss_info_exclude : NULL);2269}2270}22712272intremove_path(const char*name)2273{2274char*slash;22752276if(unlink(name) && errno != ENOENT && errno != ENOTDIR)2277return-1;22782279 slash =strrchr(name,'/');2280if(slash) {2281char*dirs =xstrdup(name);2282 slash = dirs + (slash - name);2283do{2284*slash ='\0';2285}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2286free(dirs);2287}2288return0;2289}22902291/*2292 * Frees memory within dir which was allocated for exclude lists and2293 * the exclude_stack. Does not free dir itself.2294 */2295voidclear_directory(struct dir_struct *dir)2296{2297int i, j;2298struct exclude_list_group *group;2299struct exclude_list *el;2300struct exclude_stack *stk;23012302for(i = EXC_CMDL; i <= EXC_FILE; i++) {2303 group = &dir->exclude_list_group[i];2304for(j =0; j < group->nr; j++) {2305 el = &group->el[j];2306if(i == EXC_DIRS)2307free((char*)el->src);2308clear_exclude_list(el);2309}2310free(group->el);2311}23122313 stk = dir->exclude_stack;2314while(stk) {2315struct exclude_stack *prev = stk->prev;2316free(stk);2317 stk = prev;2318}2319strbuf_release(&dir->basebuf);2320}23212322struct ondisk_untracked_cache {2323struct stat_data info_exclude_stat;2324struct stat_data excludes_file_stat;2325uint32_t dir_flags;2326unsigned char info_exclude_sha1[20];2327unsigned char excludes_file_sha1[20];2328char exclude_per_dir[FLEX_ARRAY];2329};23302331#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)23322333struct write_data {2334int index;/* number of written untracked_cache_dir */2335struct ewah_bitmap *check_only;/* from untracked_cache_dir */2336struct ewah_bitmap *valid;/* from untracked_cache_dir */2337struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2338struct strbuf out;2339struct strbuf sb_stat;2340struct strbuf sb_sha1;2341};23422343static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2344{2345 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2346 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2347 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2348 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2349 to->sd_dev =htonl(from->sd_dev);2350 to->sd_ino =htonl(from->sd_ino);2351 to->sd_uid =htonl(from->sd_uid);2352 to->sd_gid =htonl(from->sd_gid);2353 to->sd_size =htonl(from->sd_size);2354}23552356static voidwrite_one_dir(struct untracked_cache_dir *untracked,2357struct write_data *wd)2358{2359struct stat_data stat_data;2360struct strbuf *out = &wd->out;2361unsigned char intbuf[16];2362unsigned int intlen, value;2363int i = wd->index++;23642365/*2366 * untracked_nr should be reset whenever valid is clear, but2367 * for safety..2368 */2369if(!untracked->valid) {2370 untracked->untracked_nr =0;2371 untracked->check_only =0;2372}23732374if(untracked->check_only)2375ewah_set(wd->check_only, i);2376if(untracked->valid) {2377ewah_set(wd->valid, i);2378stat_data_to_disk(&stat_data, &untracked->stat_data);2379strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2380}2381if(!is_null_sha1(untracked->exclude_sha1)) {2382ewah_set(wd->sha1_valid, i);2383strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2384}23852386 intlen =encode_varint(untracked->untracked_nr, intbuf);2387strbuf_add(out, intbuf, intlen);23882389/* skip non-recurse directories */2390for(i =0, value =0; i < untracked->dirs_nr; i++)2391if(untracked->dirs[i]->recurse)2392 value++;2393 intlen =encode_varint(value, intbuf);2394strbuf_add(out, intbuf, intlen);23952396strbuf_add(out, untracked->name,strlen(untracked->name) +1);23972398for(i =0; i < untracked->untracked_nr; i++)2399strbuf_add(out, untracked->untracked[i],2400strlen(untracked->untracked[i]) +1);24012402for(i =0; i < untracked->dirs_nr; i++)2403if(untracked->dirs[i]->recurse)2404write_one_dir(untracked->dirs[i], wd);2405}24062407voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2408{2409struct ondisk_untracked_cache *ouc;2410struct write_data wd;2411unsigned char varbuf[16];2412int varint_len;2413size_t len =strlen(untracked->exclude_per_dir);24142415FLEX_ALLOC_MEM(ouc, exclude_per_dir, untracked->exclude_per_dir, len);2416stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2417stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2418hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2419hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2420 ouc->dir_flags =htonl(untracked->dir_flags);24212422 varint_len =encode_varint(untracked->ident.len, varbuf);2423strbuf_add(out, varbuf, varint_len);2424strbuf_addbuf(out, &untracked->ident);24252426strbuf_add(out, ouc,ouc_size(len));2427free(ouc);2428 ouc = NULL;24292430if(!untracked->root) {2431 varint_len =encode_varint(0, varbuf);2432strbuf_add(out, varbuf, varint_len);2433return;2434}24352436 wd.index =0;2437 wd.check_only =ewah_new();2438 wd.valid =ewah_new();2439 wd.sha1_valid =ewah_new();2440strbuf_init(&wd.out,1024);2441strbuf_init(&wd.sb_stat,1024);2442strbuf_init(&wd.sb_sha1,1024);2443write_one_dir(untracked->root, &wd);24442445 varint_len =encode_varint(wd.index, varbuf);2446strbuf_add(out, varbuf, varint_len);2447strbuf_addbuf(out, &wd.out);2448ewah_serialize_strbuf(wd.valid, out);2449ewah_serialize_strbuf(wd.check_only, out);2450ewah_serialize_strbuf(wd.sha1_valid, out);2451strbuf_addbuf(out, &wd.sb_stat);2452strbuf_addbuf(out, &wd.sb_sha1);2453strbuf_addch(out,'\0');/* safe guard for string lists */24542455ewah_free(wd.valid);2456ewah_free(wd.check_only);2457ewah_free(wd.sha1_valid);2458strbuf_release(&wd.out);2459strbuf_release(&wd.sb_stat);2460strbuf_release(&wd.sb_sha1);2461}24622463static voidfree_untracked(struct untracked_cache_dir *ucd)2464{2465int i;2466if(!ucd)2467return;2468for(i =0; i < ucd->dirs_nr; i++)2469free_untracked(ucd->dirs[i]);2470for(i =0; i < ucd->untracked_nr; i++)2471free(ucd->untracked[i]);2472free(ucd->untracked);2473free(ucd->dirs);2474free(ucd);2475}24762477voidfree_untracked_cache(struct untracked_cache *uc)2478{2479if(uc)2480free_untracked(uc->root);2481free(uc);2482}24832484struct read_data {2485int index;2486struct untracked_cache_dir **ucd;2487struct ewah_bitmap *check_only;2488struct ewah_bitmap *valid;2489struct ewah_bitmap *sha1_valid;2490const unsigned char*data;2491const unsigned char*end;2492};24932494static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2495{2496 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2497 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2498 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2499 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2500 to->sd_dev =get_be32(&from->sd_dev);2501 to->sd_ino =get_be32(&from->sd_ino);2502 to->sd_uid =get_be32(&from->sd_uid);2503 to->sd_gid =get_be32(&from->sd_gid);2504 to->sd_size =get_be32(&from->sd_size);2505}25062507static intread_one_dir(struct untracked_cache_dir **untracked_,2508struct read_data *rd)2509{2510struct untracked_cache_dir ud, *untracked;2511const unsigned char*next, *data = rd->data, *end = rd->end;2512unsigned int value;2513int i, len;25142515memset(&ud,0,sizeof(ud));25162517 next = data;2518 value =decode_varint(&next);2519if(next > end)2520return-1;2521 ud.recurse =1;2522 ud.untracked_alloc = value;2523 ud.untracked_nr = value;2524if(ud.untracked_nr)2525ALLOC_ARRAY(ud.untracked, ud.untracked_nr);2526 data = next;25272528 next = data;2529 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2530if(next > end)2531return-1;2532ALLOC_ARRAY(ud.dirs, ud.dirs_nr);2533 data = next;25342535 len =strlen((const char*)data);2536 next = data + len +1;2537if(next > rd->end)2538return-1;2539*untracked_ = untracked =xmalloc(st_add(sizeof(*untracked), len));2540memcpy(untracked, &ud,sizeof(ud));2541memcpy(untracked->name, data, len +1);2542 data = next;25432544for(i =0; i < untracked->untracked_nr; i++) {2545 len =strlen((const char*)data);2546 next = data + len +1;2547if(next > rd->end)2548return-1;2549 untracked->untracked[i] =xstrdup((const char*)data);2550 data = next;2551}25522553 rd->ucd[rd->index++] = untracked;2554 rd->data = data;25552556for(i =0; i < untracked->dirs_nr; i++) {2557 len =read_one_dir(untracked->dirs + i, rd);2558if(len <0)2559return-1;2560}2561return0;2562}25632564static voidset_check_only(size_t pos,void*cb)2565{2566struct read_data *rd = cb;2567struct untracked_cache_dir *ud = rd->ucd[pos];2568 ud->check_only =1;2569}25702571static voidread_stat(size_t pos,void*cb)2572{2573struct read_data *rd = cb;2574struct untracked_cache_dir *ud = rd->ucd[pos];2575if(rd->data +sizeof(struct stat_data) > rd->end) {2576 rd->data = rd->end +1;2577return;2578}2579stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2580 rd->data +=sizeof(struct stat_data);2581 ud->valid =1;2582}25832584static voidread_sha1(size_t pos,void*cb)2585{2586struct read_data *rd = cb;2587struct untracked_cache_dir *ud = rd->ucd[pos];2588if(rd->data +20> rd->end) {2589 rd->data = rd->end +1;2590return;2591}2592hashcpy(ud->exclude_sha1, rd->data);2593 rd->data +=20;2594}25952596static voidload_sha1_stat(struct sha1_stat *sha1_stat,2597const struct stat_data *stat,2598const unsigned char*sha1)2599{2600stat_data_from_disk(&sha1_stat->stat, stat);2601hashcpy(sha1_stat->sha1, sha1);2602 sha1_stat->valid =1;2603}26042605struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2606{2607const struct ondisk_untracked_cache *ouc;2608struct untracked_cache *uc;2609struct read_data rd;2610const unsigned char*next = data, *end = (const unsigned char*)data + sz;2611const char*ident;2612int ident_len, len;26132614if(sz <=1|| end[-1] !='\0')2615return NULL;2616 end--;26172618 ident_len =decode_varint(&next);2619if(next + ident_len > end)2620return NULL;2621 ident = (const char*)next;2622 next += ident_len;26232624 ouc = (const struct ondisk_untracked_cache *)next;2625if(next +ouc_size(0) > end)2626return NULL;26272628 uc =xcalloc(1,sizeof(*uc));2629strbuf_init(&uc->ident, ident_len);2630strbuf_add(&uc->ident, ident, ident_len);2631load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2632 ouc->info_exclude_sha1);2633load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2634 ouc->excludes_file_sha1);2635 uc->dir_flags =get_be32(&ouc->dir_flags);2636 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2637/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2638 next +=ouc_size(strlen(ouc->exclude_per_dir));2639if(next >= end)2640goto done2;26412642 len =decode_varint(&next);2643if(next > end || len ==0)2644goto done2;26452646 rd.valid =ewah_new();2647 rd.check_only =ewah_new();2648 rd.sha1_valid =ewah_new();2649 rd.data = next;2650 rd.end = end;2651 rd.index =0;2652ALLOC_ARRAY(rd.ucd, len);26532654if(read_one_dir(&uc->root, &rd) || rd.index != len)2655goto done;26562657 next = rd.data;2658 len =ewah_read_mmap(rd.valid, next, end - next);2659if(len <0)2660goto done;26612662 next += len;2663 len =ewah_read_mmap(rd.check_only, next, end - next);2664if(len <0)2665goto done;26662667 next += len;2668 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2669if(len <0)2670goto done;26712672ewah_each_bit(rd.check_only, set_check_only, &rd);2673 rd.data = next + len;2674ewah_each_bit(rd.valid, read_stat, &rd);2675ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2676 next = rd.data;26772678done:2679free(rd.ucd);2680ewah_free(rd.valid);2681ewah_free(rd.check_only);2682ewah_free(rd.sha1_valid);2683done2:2684if(next != end) {2685free_untracked_cache(uc);2686 uc = NULL;2687}2688return uc;2689}26902691static voidinvalidate_one_directory(struct untracked_cache *uc,2692struct untracked_cache_dir *ucd)2693{2694 uc->dir_invalidated++;2695 ucd->valid =0;2696 ucd->untracked_nr =0;2697}26982699/*2700 * Normally when an entry is added or removed from a directory,2701 * invalidating that directory is enough. No need to touch its2702 * ancestors. When a directory is shown as "foo/bar/" in git-status2703 * however, deleting or adding an entry may have cascading effect.2704 *2705 * Say the "foo/bar/file" has become untracked, we need to tell the2706 * untracked_cache_dir of "foo" that "bar/" is not an untracked2707 * directory any more (because "bar" is managed by foo as an untracked2708 * "file").2709 *2710 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2711 * was the last untracked entry in the entire "foo", we should show2712 * "foo/" instead. Which means we have to invalidate past "bar" up to2713 * "foo".2714 *2715 * This function traverses all directories from root to leaf. If there2716 * is a chance of one of the above cases happening, we invalidate back2717 * to root. Otherwise we just invalidate the leaf. There may be a more2718 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2719 * detect these cases and avoid unnecessary invalidation, for example,2720 * checking for the untracked entry named "bar/" in "foo", but for now2721 * stick to something safe and simple.2722 */2723static intinvalidate_one_component(struct untracked_cache *uc,2724struct untracked_cache_dir *dir,2725const char*path,int len)2726{2727const char*rest =strchr(path,'/');27282729if(rest) {2730int component_len = rest - path;2731struct untracked_cache_dir *d =2732lookup_untracked(uc, dir, path, component_len);2733int ret =2734invalidate_one_component(uc, d, rest +1,2735 len - (component_len +1));2736if(ret)2737invalidate_one_directory(uc, dir);2738return ret;2739}27402741invalidate_one_directory(uc, dir);2742return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2743}27442745voiduntracked_cache_invalidate_path(struct index_state *istate,2746const char*path)2747{2748if(!istate->untracked || !istate->untracked->root)2749return;2750invalidate_one_component(istate->untracked, istate->untracked->root,2751 path,strlen(path));2752}27532754voiduntracked_cache_remove_from_index(struct index_state *istate,2755const char*path)2756{2757untracked_cache_invalidate_path(istate, path);2758}27592760voiduntracked_cache_add_to_index(struct index_state *istate,2761const char*path)2762{2763untracked_cache_invalidate_path(istate, path);2764}27652766/* Update gitfile and core.worktree setting to connect work tree and git dir */2767voidconnect_work_tree_and_git_dir(const char*work_tree_,const char*git_dir_)2768{2769struct strbuf gitfile_sb = STRBUF_INIT;2770struct strbuf cfg_sb = STRBUF_INIT;2771struct strbuf rel_path = STRBUF_INIT;2772char*git_dir, *work_tree;27732774/* Prepare .git file */2775strbuf_addf(&gitfile_sb,"%s/.git", work_tree_);2776if(safe_create_leading_directories_const(gitfile_sb.buf))2777die(_("could not create directories for%s"), gitfile_sb.buf);27782779/* Prepare config file */2780strbuf_addf(&cfg_sb,"%s/config", git_dir_);2781if(safe_create_leading_directories_const(cfg_sb.buf))2782die(_("could not create directories for%s"), cfg_sb.buf);27832784 git_dir =real_pathdup(git_dir_,1);2785 work_tree =real_pathdup(work_tree_,1);27862787/* Write .git file */2788write_file(gitfile_sb.buf,"gitdir:%s",2789relative_path(git_dir, work_tree, &rel_path));2790/* Update core.worktree setting */2791git_config_set_in_file(cfg_sb.buf,"core.worktree",2792relative_path(work_tree, git_dir, &rel_path));27932794strbuf_release(&gitfile_sb);2795strbuf_release(&cfg_sb);2796strbuf_release(&rel_path);2797free(work_tree);2798free(git_dir);2799}28002801/*2802 * Migrate the git directory of the given path from old_git_dir to new_git_dir.2803 */2804voidrelocate_gitdir(const char*path,const char*old_git_dir,const char*new_git_dir)2805{2806if(rename(old_git_dir, new_git_dir) <0)2807die_errno(_("could not migrate git directory from '%s' to '%s'"),2808 old_git_dir, new_git_dir);28092810connect_work_tree_and_git_dir(path, new_git_dir);2811}