1/* 2 * This handles recursive filename detection with exclude 3 * files, index knowledge etc.. 4 * 5 * See Documentation/technical/api-directory-listing.txt 6 * 7 * Copyright (C) Linus Torvalds, 2005-2006 8 * Junio Hamano, 2005-2006 9 */ 10#define NO_THE_INDEX_COMPATIBILITY_MACROS 11#include"cache.h" 12#include"config.h" 13#include"dir.h" 14#include"attr.h" 15#include"refs.h" 16#include"wildmatch.h" 17#include"pathspec.h" 18#include"utf8.h" 19#include"varint.h" 20#include"ewah/ewok.h" 21 22/* 23 * Tells read_directory_recursive how a file or directory should be treated. 24 * Values are ordered by significance, e.g. if a directory contains both 25 * excluded and untracked files, it is listed as untracked because 26 * path_untracked > path_excluded. 27 */ 28enum path_treatment { 29 path_none =0, 30 path_recurse, 31 path_excluded, 32 path_untracked 33}; 34 35/* 36 * Support data structure for our opendir/readdir/closedir wrappers 37 */ 38struct cached_dir { 39DIR*fdir; 40struct untracked_cache_dir *untracked; 41int nr_files; 42int nr_dirs; 43 44struct dirent *de; 45const char*file; 46struct untracked_cache_dir *ucd; 47}; 48 49static enum path_treatment read_directory_recursive(struct dir_struct *dir, 50struct index_state *istate,const char*path,int len, 51struct untracked_cache_dir *untracked, 52int check_only,const struct pathspec *pathspec); 53static intget_dtype(struct dirent *de,struct index_state *istate, 54const char*path,int len); 55 56intcount_slashes(const char*s) 57{ 58int cnt =0; 59while(*s) 60if(*s++ =='/') 61 cnt++; 62return cnt; 63} 64 65intfspathcmp(const char*a,const char*b) 66{ 67return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 68} 69 70intfspathncmp(const char*a,const char*b,size_t count) 71{ 72return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 73} 74 75intgit_fnmatch(const struct pathspec_item *item, 76const char*pattern,const char*string, 77int prefix) 78{ 79if(prefix >0) { 80if(ps_strncmp(item, pattern, string, prefix)) 81return WM_NOMATCH; 82 pattern += prefix; 83 string += prefix; 84} 85if(item->flags & PATHSPEC_ONESTAR) { 86int pattern_len =strlen(++pattern); 87int string_len =strlen(string); 88return string_len < pattern_len || 89ps_strcmp(item, pattern, 90 string + string_len - pattern_len); 91} 92if(item->magic & PATHSPEC_GLOB) 93returnwildmatch(pattern, string, 94 WM_PATHNAME | 95(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 96 NULL); 97else 98/* wildmatch has not learned no FNM_PATHNAME mode yet */ 99returnwildmatch(pattern, string, 100 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 101 NULL); 102} 103 104static intfnmatch_icase_mem(const char*pattern,int patternlen, 105const char*string,int stringlen, 106int flags) 107{ 108int match_status; 109struct strbuf pat_buf = STRBUF_INIT; 110struct strbuf str_buf = STRBUF_INIT; 111const char*use_pat = pattern; 112const char*use_str = string; 113 114if(pattern[patternlen]) { 115strbuf_add(&pat_buf, pattern, patternlen); 116 use_pat = pat_buf.buf; 117} 118if(string[stringlen]) { 119strbuf_add(&str_buf, string, stringlen); 120 use_str = str_buf.buf; 121} 122 123if(ignore_case) 124 flags |= WM_CASEFOLD; 125 match_status =wildmatch(use_pat, use_str, flags, NULL); 126 127strbuf_release(&pat_buf); 128strbuf_release(&str_buf); 129 130return match_status; 131} 132 133static size_tcommon_prefix_len(const struct pathspec *pathspec) 134{ 135int n; 136size_t max =0; 137 138/* 139 * ":(icase)path" is treated as a pathspec full of 140 * wildcard. In other words, only prefix is considered common 141 * prefix. If the pathspec is abc/foo abc/bar, running in 142 * subdir xyz, the common prefix is still xyz, not xuz/abc as 143 * in non-:(icase). 144 */ 145GUARD_PATHSPEC(pathspec, 146 PATHSPEC_FROMTOP | 147 PATHSPEC_MAXDEPTH | 148 PATHSPEC_LITERAL | 149 PATHSPEC_GLOB | 150 PATHSPEC_ICASE | 151 PATHSPEC_EXCLUDE | 152 PATHSPEC_ATTR); 153 154for(n =0; n < pathspec->nr; n++) { 155size_t i =0, len =0, item_len; 156if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 157continue; 158if(pathspec->items[n].magic & PATHSPEC_ICASE) 159 item_len = pathspec->items[n].prefix; 160else 161 item_len = pathspec->items[n].nowildcard_len; 162while(i < item_len && (n ==0|| i < max)) { 163char c = pathspec->items[n].match[i]; 164if(c != pathspec->items[0].match[i]) 165break; 166if(c =='/') 167 len = i +1; 168 i++; 169} 170if(n ==0|| len < max) { 171 max = len; 172if(!max) 173break; 174} 175} 176return max; 177} 178 179/* 180 * Returns a copy of the longest leading path common among all 181 * pathspecs. 182 */ 183char*common_prefix(const struct pathspec *pathspec) 184{ 185unsigned long len =common_prefix_len(pathspec); 186 187return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 188} 189 190intfill_directory(struct dir_struct *dir, 191struct index_state *istate, 192const struct pathspec *pathspec) 193{ 194const char*prefix; 195size_t prefix_len; 196 197/* 198 * Calculate common prefix for the pathspec, and 199 * use that to optimize the directory walk 200 */ 201 prefix_len =common_prefix_len(pathspec); 202 prefix = prefix_len ? pathspec->items[0].match :""; 203 204/* Read the directory and prune it */ 205read_directory(dir, istate, prefix, prefix_len, pathspec); 206 207return prefix_len; 208} 209 210intwithin_depth(const char*name,int namelen, 211int depth,int max_depth) 212{ 213const char*cp = name, *cpe = name + namelen; 214 215while(cp < cpe) { 216if(*cp++ !='/') 217continue; 218 depth++; 219if(depth > max_depth) 220return0; 221} 222return1; 223} 224 225#define DO_MATCH_EXCLUDE (1<<0) 226#define DO_MATCH_DIRECTORY (1<<1) 227#define DO_MATCH_SUBMODULE (1<<2) 228 229static intmatch_attrs(const char*name,int namelen, 230const struct pathspec_item *item) 231{ 232int i; 233 234git_check_attr(name, item->attr_check); 235for(i =0; i < item->attr_match_nr; i++) { 236const char*value; 237int matched; 238enum attr_match_mode match_mode; 239 240 value = item->attr_check->items[i].value; 241 match_mode = item->attr_match[i].match_mode; 242 243if(ATTR_TRUE(value)) 244 matched = (match_mode == MATCH_SET); 245else if(ATTR_FALSE(value)) 246 matched = (match_mode == MATCH_UNSET); 247else if(ATTR_UNSET(value)) 248 matched = (match_mode == MATCH_UNSPECIFIED); 249else 250 matched = (match_mode == MATCH_VALUE && 251!strcmp(item->attr_match[i].value, value)); 252if(!matched) 253return0; 254} 255 256return1; 257} 258 259/* 260 * Does 'match' match the given name? 261 * A match is found if 262 * 263 * (1) the 'match' string is leading directory of 'name', or 264 * (2) the 'match' string is a wildcard and matches 'name', or 265 * (3) the 'match' string is exactly the same as 'name'. 266 * 267 * and the return value tells which case it was. 268 * 269 * It returns 0 when there is no match. 270 */ 271static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 272const char*name,int namelen,unsigned flags) 273{ 274/* name/namelen has prefix cut off by caller */ 275const char*match = item->match + prefix; 276int matchlen = item->len - prefix; 277 278/* 279 * The normal call pattern is: 280 * 1. prefix = common_prefix_len(ps); 281 * 2. prune something, or fill_directory 282 * 3. match_pathspec() 283 * 284 * 'prefix' at #1 may be shorter than the command's prefix and 285 * it's ok for #2 to match extra files. Those extras will be 286 * trimmed at #3. 287 * 288 * Suppose the pathspec is 'foo' and '../bar' running from 289 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 290 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 291 * user does not want XYZ/foo, only the "foo" part should be 292 * case-insensitive. We need to filter out XYZ/foo here. In 293 * other words, we do not trust the caller on comparing the 294 * prefix part when :(icase) is involved. We do exact 295 * comparison ourselves. 296 * 297 * Normally the caller (common_prefix_len() in fact) does 298 * _exact_ matching on name[-prefix+1..-1] and we do not need 299 * to check that part. Be defensive and check it anyway, in 300 * case common_prefix_len is changed, or a new caller is 301 * introduced that does not use common_prefix_len. 302 * 303 * If the penalty turns out too high when prefix is really 304 * long, maybe change it to 305 * strncmp(match, name, item->prefix - prefix) 306 */ 307if(item->prefix && (item->magic & PATHSPEC_ICASE) && 308strncmp(item->match, name - prefix, item->prefix)) 309return0; 310 311if(item->attr_match_nr && !match_attrs(name, namelen, item)) 312return0; 313 314/* If the match was just the prefix, we matched */ 315if(!*match) 316return MATCHED_RECURSIVELY; 317 318if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 319if(matchlen == namelen) 320return MATCHED_EXACTLY; 321 322if(match[matchlen-1] =='/'|| name[matchlen] =='/') 323return MATCHED_RECURSIVELY; 324}else if((flags & DO_MATCH_DIRECTORY) && 325 match[matchlen -1] =='/'&& 326 namelen == matchlen -1&& 327!ps_strncmp(item, match, name, namelen)) 328return MATCHED_EXACTLY; 329 330if(item->nowildcard_len < item->len && 331!git_fnmatch(item, match, name, 332 item->nowildcard_len - prefix)) 333return MATCHED_FNMATCH; 334 335/* Perform checks to see if "name" is a super set of the pathspec */ 336if(flags & DO_MATCH_SUBMODULE) { 337/* name is a literal prefix of the pathspec */ 338if((namelen < matchlen) && 339(match[namelen] =='/') && 340!ps_strncmp(item, match, name, namelen)) 341return MATCHED_RECURSIVELY; 342 343/* name" doesn't match up to the first wild character */ 344if(item->nowildcard_len < item->len && 345ps_strncmp(item, match, name, 346 item->nowildcard_len - prefix)) 347return0; 348 349/* 350 * Here is where we would perform a wildmatch to check if 351 * "name" can be matched as a directory (or a prefix) against 352 * the pathspec. Since wildmatch doesn't have this capability 353 * at the present we have to punt and say that it is a match, 354 * potentially returning a false positive 355 * The submodules themselves will be able to perform more 356 * accurate matching to determine if the pathspec matches. 357 */ 358return MATCHED_RECURSIVELY; 359} 360 361return0; 362} 363 364/* 365 * Given a name and a list of pathspecs, returns the nature of the 366 * closest (i.e. most specific) match of the name to any of the 367 * pathspecs. 368 * 369 * The caller typically calls this multiple times with the same 370 * pathspec and seen[] array but with different name/namelen 371 * (e.g. entries from the index) and is interested in seeing if and 372 * how each pathspec matches all the names it calls this function 373 * with. A mark is left in the seen[] array for each pathspec element 374 * indicating the closest type of match that element achieved, so if 375 * seen[n] remains zero after multiple invocations, that means the nth 376 * pathspec did not match any names, which could indicate that the 377 * user mistyped the nth pathspec. 378 */ 379static intdo_match_pathspec(const struct pathspec *ps, 380const char*name,int namelen, 381int prefix,char*seen, 382unsigned flags) 383{ 384int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 385 386GUARD_PATHSPEC(ps, 387 PATHSPEC_FROMTOP | 388 PATHSPEC_MAXDEPTH | 389 PATHSPEC_LITERAL | 390 PATHSPEC_GLOB | 391 PATHSPEC_ICASE | 392 PATHSPEC_EXCLUDE | 393 PATHSPEC_ATTR); 394 395if(!ps->nr) { 396if(!ps->recursive || 397!(ps->magic & PATHSPEC_MAXDEPTH) || 398 ps->max_depth == -1) 399return MATCHED_RECURSIVELY; 400 401if(within_depth(name, namelen,0, ps->max_depth)) 402return MATCHED_EXACTLY; 403else 404return0; 405} 406 407 name += prefix; 408 namelen -= prefix; 409 410for(i = ps->nr -1; i >=0; i--) { 411int how; 412 413if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 414( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 415continue; 416 417if(seen && seen[i] == MATCHED_EXACTLY) 418continue; 419/* 420 * Make exclude patterns optional and never report 421 * "pathspec ':(exclude)foo' matches no files" 422 */ 423if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 424 seen[i] = MATCHED_FNMATCH; 425 how =match_pathspec_item(ps->items+i, prefix, name, 426 namelen, flags); 427if(ps->recursive && 428(ps->magic & PATHSPEC_MAXDEPTH) && 429 ps->max_depth != -1&& 430 how && how != MATCHED_FNMATCH) { 431int len = ps->items[i].len; 432if(name[len] =='/') 433 len++; 434if(within_depth(name+len, namelen-len,0, ps->max_depth)) 435 how = MATCHED_EXACTLY; 436else 437 how =0; 438} 439if(how) { 440if(retval < how) 441 retval = how; 442if(seen && seen[i] < how) 443 seen[i] = how; 444} 445} 446return retval; 447} 448 449intmatch_pathspec(const struct pathspec *ps, 450const char*name,int namelen, 451int prefix,char*seen,int is_dir) 452{ 453int positive, negative; 454unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 455 positive =do_match_pathspec(ps, name, namelen, 456 prefix, seen, flags); 457if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 458return positive; 459 negative =do_match_pathspec(ps, name, namelen, 460 prefix, seen, 461 flags | DO_MATCH_EXCLUDE); 462return negative ?0: positive; 463} 464 465/** 466 * Check if a submodule is a superset of the pathspec 467 */ 468intsubmodule_path_match(const struct pathspec *ps, 469const char*submodule_name, 470char*seen) 471{ 472int matched =do_match_pathspec(ps, submodule_name, 473strlen(submodule_name), 4740, seen, 475 DO_MATCH_DIRECTORY | 476 DO_MATCH_SUBMODULE); 477return matched; 478} 479 480intreport_path_error(const char*ps_matched, 481const struct pathspec *pathspec, 482const char*prefix) 483{ 484/* 485 * Make sure all pathspec matched; otherwise it is an error. 486 */ 487int num, errors =0; 488for(num =0; num < pathspec->nr; num++) { 489int other, found_dup; 490 491if(ps_matched[num]) 492continue; 493/* 494 * The caller might have fed identical pathspec 495 * twice. Do not barf on such a mistake. 496 * FIXME: parse_pathspec should have eliminated 497 * duplicate pathspec. 498 */ 499for(found_dup = other =0; 500!found_dup && other < pathspec->nr; 501 other++) { 502if(other == num || !ps_matched[other]) 503continue; 504if(!strcmp(pathspec->items[other].original, 505 pathspec->items[num].original)) 506/* 507 * Ok, we have a match already. 508 */ 509 found_dup =1; 510} 511if(found_dup) 512continue; 513 514error("pathspec '%s' did not match any file(s) known to git.", 515 pathspec->items[num].original); 516 errors++; 517} 518return errors; 519} 520 521/* 522 * Return the length of the "simple" part of a path match limiter. 523 */ 524intsimple_length(const char*match) 525{ 526int len = -1; 527 528for(;;) { 529unsigned char c = *match++; 530 len++; 531if(c =='\0'||is_glob_special(c)) 532return len; 533} 534} 535 536intno_wildcard(const char*string) 537{ 538return string[simple_length(string)] =='\0'; 539} 540 541voidparse_exclude_pattern(const char**pattern, 542int*patternlen, 543unsigned*flags, 544int*nowildcardlen) 545{ 546const char*p = *pattern; 547size_t i, len; 548 549*flags =0; 550if(*p =='!') { 551*flags |= EXC_FLAG_NEGATIVE; 552 p++; 553} 554 len =strlen(p); 555if(len && p[len -1] =='/') { 556 len--; 557*flags |= EXC_FLAG_MUSTBEDIR; 558} 559for(i =0; i < len; i++) { 560if(p[i] =='/') 561break; 562} 563if(i == len) 564*flags |= EXC_FLAG_NODIR; 565*nowildcardlen =simple_length(p); 566/* 567 * we should have excluded the trailing slash from 'p' too, 568 * but that's one more allocation. Instead just make sure 569 * nowildcardlen does not exceed real patternlen 570 */ 571if(*nowildcardlen > len) 572*nowildcardlen = len; 573if(*p =='*'&&no_wildcard(p +1)) 574*flags |= EXC_FLAG_ENDSWITH; 575*pattern = p; 576*patternlen = len; 577} 578 579voidadd_exclude(const char*string,const char*base, 580int baselen,struct exclude_list *el,int srcpos) 581{ 582struct exclude *x; 583int patternlen; 584unsigned flags; 585int nowildcardlen; 586 587parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 588if(flags & EXC_FLAG_MUSTBEDIR) { 589FLEXPTR_ALLOC_MEM(x, pattern, string, patternlen); 590}else{ 591 x =xmalloc(sizeof(*x)); 592 x->pattern = string; 593} 594 x->patternlen = patternlen; 595 x->nowildcardlen = nowildcardlen; 596 x->base = base; 597 x->baselen = baselen; 598 x->flags = flags; 599 x->srcpos = srcpos; 600ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 601 el->excludes[el->nr++] = x; 602 x->el = el; 603} 604 605static void*read_skip_worktree_file_from_index(const struct index_state *istate, 606const char*path,size_t*size, 607struct sha1_stat *sha1_stat) 608{ 609int pos, len; 610unsigned long sz; 611enum object_type type; 612void*data; 613 614 len =strlen(path); 615 pos =index_name_pos(istate, path, len); 616if(pos <0) 617return NULL; 618if(!ce_skip_worktree(istate->cache[pos])) 619return NULL; 620 data =read_sha1_file(istate->cache[pos]->oid.hash, &type, &sz); 621if(!data || type != OBJ_BLOB) { 622free(data); 623return NULL; 624} 625*size =xsize_t(sz); 626if(sha1_stat) { 627memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 628hashcpy(sha1_stat->sha1, istate->cache[pos]->oid.hash); 629} 630return data; 631} 632 633/* 634 * Frees memory within el which was allocated for exclude patterns and 635 * the file buffer. Does not free el itself. 636 */ 637voidclear_exclude_list(struct exclude_list *el) 638{ 639int i; 640 641for(i =0; i < el->nr; i++) 642free(el->excludes[i]); 643free(el->excludes); 644free(el->filebuf); 645 646memset(el,0,sizeof(*el)); 647} 648 649static voidtrim_trailing_spaces(char*buf) 650{ 651char*p, *last_space = NULL; 652 653for(p = buf; *p; p++) 654switch(*p) { 655case' ': 656if(!last_space) 657 last_space = p; 658break; 659case'\\': 660 p++; 661if(!*p) 662return; 663/* fallthrough */ 664default: 665 last_space = NULL; 666} 667 668if(last_space) 669*last_space ='\0'; 670} 671 672/* 673 * Given a subdirectory name and "dir" of the current directory, 674 * search the subdir in "dir" and return it, or create a new one if it 675 * does not exist in "dir". 676 * 677 * If "name" has the trailing slash, it'll be excluded in the search. 678 */ 679static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 680struct untracked_cache_dir *dir, 681const char*name,int len) 682{ 683int first, last; 684struct untracked_cache_dir *d; 685if(!dir) 686return NULL; 687if(len && name[len -1] =='/') 688 len--; 689 first =0; 690 last = dir->dirs_nr; 691while(last > first) { 692int cmp, next = (last + first) >>1; 693 d = dir->dirs[next]; 694 cmp =strncmp(name, d->name, len); 695if(!cmp &&strlen(d->name) > len) 696 cmp = -1; 697if(!cmp) 698return d; 699if(cmp <0) { 700 last = next; 701continue; 702} 703 first = next+1; 704} 705 706 uc->dir_created++; 707FLEX_ALLOC_MEM(d, name, name, len); 708 709ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 710memmove(dir->dirs + first +1, dir->dirs + first, 711(dir->dirs_nr - first) *sizeof(*dir->dirs)); 712 dir->dirs_nr++; 713 dir->dirs[first] = d; 714return d; 715} 716 717static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 718{ 719int i; 720 dir->valid =0; 721 dir->untracked_nr =0; 722for(i =0; i < dir->dirs_nr; i++) 723do_invalidate_gitignore(dir->dirs[i]); 724} 725 726static voidinvalidate_gitignore(struct untracked_cache *uc, 727struct untracked_cache_dir *dir) 728{ 729 uc->gitignore_invalidated++; 730do_invalidate_gitignore(dir); 731} 732 733static voidinvalidate_directory(struct untracked_cache *uc, 734struct untracked_cache_dir *dir) 735{ 736int i; 737 uc->dir_invalidated++; 738 dir->valid =0; 739 dir->untracked_nr =0; 740for(i =0; i < dir->dirs_nr; i++) 741 dir->dirs[i]->recurse =0; 742} 743 744/* 745 * Given a file with name "fname", read it (either from disk, or from 746 * an index if 'istate' is non-null), parse it and store the 747 * exclude rules in "el". 748 * 749 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 750 * stat data from disk (only valid if add_excludes returns zero). If 751 * ss_valid is non-zero, "ss" must contain good value as input. 752 */ 753static intadd_excludes(const char*fname,const char*base,int baselen, 754struct exclude_list *el, 755struct index_state *istate, 756struct sha1_stat *sha1_stat) 757{ 758struct stat st; 759int fd, i, lineno =1; 760size_t size =0; 761char*buf, *entry; 762 763 fd =open(fname, O_RDONLY); 764if(fd <0||fstat(fd, &st) <0) { 765if(fd <0) 766warn_on_fopen_errors(fname); 767else 768close(fd); 769if(!istate || 770(buf =read_skip_worktree_file_from_index(istate, fname, &size, sha1_stat)) == NULL) 771return-1; 772if(size ==0) { 773free(buf); 774return0; 775} 776if(buf[size-1] !='\n') { 777 buf =xrealloc(buf,st_add(size,1)); 778 buf[size++] ='\n'; 779} 780}else{ 781 size =xsize_t(st.st_size); 782if(size ==0) { 783if(sha1_stat) { 784fill_stat_data(&sha1_stat->stat, &st); 785hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 786 sha1_stat->valid =1; 787} 788close(fd); 789return0; 790} 791 buf =xmallocz(size); 792if(read_in_full(fd, buf, size) != size) { 793free(buf); 794close(fd); 795return-1; 796} 797 buf[size++] ='\n'; 798close(fd); 799if(sha1_stat) { 800int pos; 801if(sha1_stat->valid && 802!match_stat_data_racy(istate, &sha1_stat->stat, &st)) 803;/* no content change, ss->sha1 still good */ 804else if(istate && 805(pos =index_name_pos(istate, fname,strlen(fname))) >=0&& 806!ce_stage(istate->cache[pos]) && 807ce_uptodate(istate->cache[pos]) && 808!would_convert_to_git(istate, fname)) 809hashcpy(sha1_stat->sha1, 810 istate->cache[pos]->oid.hash); 811else 812hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 813fill_stat_data(&sha1_stat->stat, &st); 814 sha1_stat->valid =1; 815} 816} 817 818 el->filebuf = buf; 819 820if(skip_utf8_bom(&buf, size)) 821 size -= buf - el->filebuf; 822 823 entry = buf; 824 825for(i =0; i < size; i++) { 826if(buf[i] =='\n') { 827if(entry != buf + i && entry[0] !='#') { 828 buf[i - (i && buf[i-1] =='\r')] =0; 829trim_trailing_spaces(entry); 830add_exclude(entry, base, baselen, el, lineno); 831} 832 lineno++; 833 entry = buf + i +1; 834} 835} 836return0; 837} 838 839intadd_excludes_from_file_to_list(const char*fname,const char*base, 840int baselen,struct exclude_list *el, 841struct index_state *istate) 842{ 843returnadd_excludes(fname, base, baselen, el, istate, NULL); 844} 845 846struct exclude_list *add_exclude_list(struct dir_struct *dir, 847int group_type,const char*src) 848{ 849struct exclude_list *el; 850struct exclude_list_group *group; 851 852 group = &dir->exclude_list_group[group_type]; 853ALLOC_GROW(group->el, group->nr +1, group->alloc); 854 el = &group->el[group->nr++]; 855memset(el,0,sizeof(*el)); 856 el->src = src; 857return el; 858} 859 860/* 861 * Used to set up core.excludesfile and .git/info/exclude lists. 862 */ 863static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 864struct sha1_stat *sha1_stat) 865{ 866struct exclude_list *el; 867/* 868 * catch setup_standard_excludes() that's called before 869 * dir->untracked is assigned. That function behaves 870 * differently when dir->untracked is non-NULL. 871 */ 872if(!dir->untracked) 873 dir->unmanaged_exclude_files++; 874 el =add_exclude_list(dir, EXC_FILE, fname); 875if(add_excludes(fname,"",0, el, NULL, sha1_stat) <0) 876die("cannot use%sas an exclude file", fname); 877} 878 879voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 880{ 881 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 882add_excludes_from_file_1(dir, fname, NULL); 883} 884 885intmatch_basename(const char*basename,int basenamelen, 886const char*pattern,int prefix,int patternlen, 887unsigned flags) 888{ 889if(prefix == patternlen) { 890if(patternlen == basenamelen && 891!fspathncmp(pattern, basename, basenamelen)) 892return1; 893}else if(flags & EXC_FLAG_ENDSWITH) { 894/* "*literal" matching against "fooliteral" */ 895if(patternlen -1<= basenamelen && 896!fspathncmp(pattern +1, 897 basename + basenamelen - (patternlen -1), 898 patternlen -1)) 899return1; 900}else{ 901if(fnmatch_icase_mem(pattern, patternlen, 902 basename, basenamelen, 9030) ==0) 904return1; 905} 906return0; 907} 908 909intmatch_pathname(const char*pathname,int pathlen, 910const char*base,int baselen, 911const char*pattern,int prefix,int patternlen, 912unsigned flags) 913{ 914const char*name; 915int namelen; 916 917/* 918 * match with FNM_PATHNAME; the pattern has base implicitly 919 * in front of it. 920 */ 921if(*pattern =='/') { 922 pattern++; 923 patternlen--; 924 prefix--; 925} 926 927/* 928 * baselen does not count the trailing slash. base[] may or 929 * may not end with a trailing slash though. 930 */ 931if(pathlen < baselen +1|| 932(baselen && pathname[baselen] !='/') || 933fspathncmp(pathname, base, baselen)) 934return0; 935 936 namelen = baselen ? pathlen - baselen -1: pathlen; 937 name = pathname + pathlen - namelen; 938 939if(prefix) { 940/* 941 * if the non-wildcard part is longer than the 942 * remaining pathname, surely it cannot match. 943 */ 944if(prefix > namelen) 945return0; 946 947if(fspathncmp(pattern, name, prefix)) 948return0; 949 pattern += prefix; 950 patternlen -= prefix; 951 name += prefix; 952 namelen -= prefix; 953 954/* 955 * If the whole pattern did not have a wildcard, 956 * then our prefix match is all we need; we 957 * do not need to call fnmatch at all. 958 */ 959if(!patternlen && !namelen) 960return1; 961} 962 963returnfnmatch_icase_mem(pattern, patternlen, 964 name, namelen, 965 WM_PATHNAME) ==0; 966} 967 968/* 969 * Scan the given exclude list in reverse to see whether pathname 970 * should be ignored. The first match (i.e. the last on the list), if 971 * any, determines the fate. Returns the exclude_list element which 972 * matched, or NULL for undecided. 973 */ 974static struct exclude *last_exclude_matching_from_list(const char*pathname, 975int pathlen, 976const char*basename, 977int*dtype, 978struct exclude_list *el, 979struct index_state *istate) 980{ 981struct exclude *exc = NULL;/* undecided */ 982int i; 983 984if(!el->nr) 985return NULL;/* undefined */ 986 987for(i = el->nr -1;0<= i; i--) { 988struct exclude *x = el->excludes[i]; 989const char*exclude = x->pattern; 990int prefix = x->nowildcardlen; 991 992if(x->flags & EXC_FLAG_MUSTBEDIR) { 993if(*dtype == DT_UNKNOWN) 994*dtype =get_dtype(NULL, istate, pathname, pathlen); 995if(*dtype != DT_DIR) 996continue; 997} 998 999if(x->flags & EXC_FLAG_NODIR) {1000if(match_basename(basename,1001 pathlen - (basename - pathname),1002 exclude, prefix, x->patternlen,1003 x->flags)) {1004 exc = x;1005break;1006}1007continue;1008}10091010assert(x->baselen ==0|| x->base[x->baselen -1] =='/');1011if(match_pathname(pathname, pathlen,1012 x->base, x->baselen ? x->baselen -1:0,1013 exclude, prefix, x->patternlen, x->flags)) {1014 exc = x;1015break;1016}1017}1018return exc;1019}10201021/*1022 * Scan the list and let the last match determine the fate.1023 * Return 1 for exclude, 0 for include and -1 for undecided.1024 */1025intis_excluded_from_list(const char*pathname,1026int pathlen,const char*basename,int*dtype,1027struct exclude_list *el,struct index_state *istate)1028{1029struct exclude *exclude;1030 exclude =last_exclude_matching_from_list(pathname, pathlen, basename,1031 dtype, el, istate);1032if(exclude)1033return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1034return-1;/* undecided */1035}10361037static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir,1038struct index_state *istate,1039const char*pathname,int pathlen,const char*basename,1040int*dtype_p)1041{1042int i, j;1043struct exclude_list_group *group;1044struct exclude *exclude;1045for(i = EXC_CMDL; i <= EXC_FILE; i++) {1046 group = &dir->exclude_list_group[i];1047for(j = group->nr -1; j >=0; j--) {1048 exclude =last_exclude_matching_from_list(1049 pathname, pathlen, basename, dtype_p,1050&group->el[j], istate);1051if(exclude)1052return exclude;1053}1054}1055return NULL;1056}10571058/*1059 * Loads the per-directory exclude list for the substring of base1060 * which has a char length of baselen.1061 */1062static voidprep_exclude(struct dir_struct *dir,1063struct index_state *istate,1064const char*base,int baselen)1065{1066struct exclude_list_group *group;1067struct exclude_list *el;1068struct exclude_stack *stk = NULL;1069struct untracked_cache_dir *untracked;1070int current;10711072 group = &dir->exclude_list_group[EXC_DIRS];10731074/*1075 * Pop the exclude lists from the EXCL_DIRS exclude_list_group1076 * which originate from directories not in the prefix of the1077 * path being checked.1078 */1079while((stk = dir->exclude_stack) != NULL) {1080if(stk->baselen <= baselen &&1081!strncmp(dir->basebuf.buf, base, stk->baselen))1082break;1083 el = &group->el[dir->exclude_stack->exclude_ix];1084 dir->exclude_stack = stk->prev;1085 dir->exclude = NULL;1086free((char*)el->src);/* see strbuf_detach() below */1087clear_exclude_list(el);1088free(stk);1089 group->nr--;1090}10911092/* Skip traversing into sub directories if the parent is excluded */1093if(dir->exclude)1094return;10951096/*1097 * Lazy initialization. All call sites currently just1098 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1099 * them seems lots of work for little benefit.1100 */1101if(!dir->basebuf.buf)1102strbuf_init(&dir->basebuf, PATH_MAX);11031104/* Read from the parent directories and push them down. */1105 current = stk ? stk->baselen : -1;1106strbuf_setlen(&dir->basebuf, current <0?0: current);1107if(dir->untracked)1108 untracked = stk ? stk->ucd : dir->untracked->root;1109else1110 untracked = NULL;11111112while(current < baselen) {1113const char*cp;1114struct sha1_stat sha1_stat;11151116 stk =xcalloc(1,sizeof(*stk));1117if(current <0) {1118 cp = base;1119 current =0;1120}else{1121 cp =strchr(base + current +1,'/');1122if(!cp)1123die("oops in prep_exclude");1124 cp++;1125 untracked =1126lookup_untracked(dir->untracked, untracked,1127 base + current,1128 cp - base - current);1129}1130 stk->prev = dir->exclude_stack;1131 stk->baselen = cp - base;1132 stk->exclude_ix = group->nr;1133 stk->ucd = untracked;1134 el =add_exclude_list(dir, EXC_DIRS, NULL);1135strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1136assert(stk->baselen == dir->basebuf.len);11371138/* Abort if the directory is excluded */1139if(stk->baselen) {1140int dt = DT_DIR;1141 dir->basebuf.buf[stk->baselen -1] =0;1142 dir->exclude =last_exclude_matching_from_lists(dir,1143 istate,1144 dir->basebuf.buf, stk->baselen -1,1145 dir->basebuf.buf + current, &dt);1146 dir->basebuf.buf[stk->baselen -1] ='/';1147if(dir->exclude &&1148 dir->exclude->flags & EXC_FLAG_NEGATIVE)1149 dir->exclude = NULL;1150if(dir->exclude) {1151 dir->exclude_stack = stk;1152return;1153}1154}11551156/* Try to read per-directory file */1157hashclr(sha1_stat.sha1);1158 sha1_stat.valid =0;1159if(dir->exclude_per_dir &&1160/*1161 * If we know that no files have been added in1162 * this directory (i.e. valid_cached_dir() has1163 * been executed and set untracked->valid) ..1164 */1165(!untracked || !untracked->valid ||1166/*1167 * .. and .gitignore does not exist before1168 * (i.e. null exclude_sha1). Then we can skip1169 * loading .gitignore, which would result in1170 * ENOENT anyway.1171 */1172!is_null_sha1(untracked->exclude_sha1))) {1173/*1174 * dir->basebuf gets reused by the traversal, but we1175 * need fname to remain unchanged to ensure the src1176 * member of each struct exclude correctly1177 * back-references its source file. Other invocations1178 * of add_exclude_list provide stable strings, so we1179 * strbuf_detach() and free() here in the caller.1180 */1181struct strbuf sb = STRBUF_INIT;1182strbuf_addbuf(&sb, &dir->basebuf);1183strbuf_addstr(&sb, dir->exclude_per_dir);1184 el->src =strbuf_detach(&sb, NULL);1185add_excludes(el->src, el->src, stk->baselen, el, istate,1186 untracked ? &sha1_stat : NULL);1187}1188/*1189 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1190 * will first be called in valid_cached_dir() then maybe many1191 * times more in last_exclude_matching(). When the cache is1192 * used, last_exclude_matching() will not be called and1193 * reading .gitignore content will be a waste.1194 *1195 * So when it's called by valid_cached_dir() and we can get1196 * .gitignore SHA-1 from the index (i.e. .gitignore is not1197 * modified on work tree), we could delay reading the1198 * .gitignore content until we absolutely need it in1199 * last_exclude_matching(). Be careful about ignore rule1200 * order, though, if you do that.1201 */1202if(untracked &&1203hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1204invalidate_gitignore(dir->untracked, untracked);1205hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1206}1207 dir->exclude_stack = stk;1208 current = stk->baselen;1209}1210strbuf_setlen(&dir->basebuf, baselen);1211}12121213/*1214 * Loads the exclude lists for the directory containing pathname, then1215 * scans all exclude lists to determine whether pathname is excluded.1216 * Returns the exclude_list element which matched, or NULL for1217 * undecided.1218 */1219struct exclude *last_exclude_matching(struct dir_struct *dir,1220struct index_state *istate,1221const char*pathname,1222int*dtype_p)1223{1224int pathlen =strlen(pathname);1225const char*basename =strrchr(pathname,'/');1226 basename = (basename) ? basename+1: pathname;12271228prep_exclude(dir, istate, pathname, basename-pathname);12291230if(dir->exclude)1231return dir->exclude;12321233returnlast_exclude_matching_from_lists(dir, istate, pathname, pathlen,1234 basename, dtype_p);1235}12361237/*1238 * Loads the exclude lists for the directory containing pathname, then1239 * scans all exclude lists to determine whether pathname is excluded.1240 * Returns 1 if true, otherwise 0.1241 */1242intis_excluded(struct dir_struct *dir,struct index_state *istate,1243const char*pathname,int*dtype_p)1244{1245struct exclude *exclude =1246last_exclude_matching(dir, istate, pathname, dtype_p);1247if(exclude)1248return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1249return0;1250}12511252static struct dir_entry *dir_entry_new(const char*pathname,int len)1253{1254struct dir_entry *ent;12551256FLEX_ALLOC_MEM(ent, name, pathname, len);1257 ent->len = len;1258return ent;1259}12601261static struct dir_entry *dir_add_name(struct dir_struct *dir,1262struct index_state *istate,1263const char*pathname,int len)1264{1265if(index_file_exists(istate, pathname, len, ignore_case))1266return NULL;12671268ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1269return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1270}12711272struct dir_entry *dir_add_ignored(struct dir_struct *dir,1273struct index_state *istate,1274const char*pathname,int len)1275{1276if(!index_name_is_other(istate, pathname, len))1277return NULL;12781279ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1280return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1281}12821283enum exist_status {1284 index_nonexistent =0,1285 index_directory,1286 index_gitdir1287};12881289/*1290 * Do not use the alphabetically sorted index to look up1291 * the directory name; instead, use the case insensitive1292 * directory hash.1293 */1294static enum exist_status directory_exists_in_index_icase(struct index_state *istate,1295const char*dirname,int len)1296{1297struct cache_entry *ce;12981299if(index_dir_exists(istate, dirname, len))1300return index_directory;13011302 ce =index_file_exists(istate, dirname, len, ignore_case);1303if(ce &&S_ISGITLINK(ce->ce_mode))1304return index_gitdir;13051306return index_nonexistent;1307}13081309/*1310 * The index sorts alphabetically by entry name, which1311 * means that a gitlink sorts as '\0' at the end, while1312 * a directory (which is defined not as an entry, but as1313 * the files it contains) will sort with the '/' at the1314 * end.1315 */1316static enum exist_status directory_exists_in_index(struct index_state *istate,1317const char*dirname,int len)1318{1319int pos;13201321if(ignore_case)1322returndirectory_exists_in_index_icase(istate, dirname, len);13231324 pos =index_name_pos(istate, dirname, len);1325if(pos <0)1326 pos = -pos-1;1327while(pos < istate->cache_nr) {1328const struct cache_entry *ce = istate->cache[pos++];1329unsigned char endchar;13301331if(strncmp(ce->name, dirname, len))1332break;1333 endchar = ce->name[len];1334if(endchar >'/')1335break;1336if(endchar =='/')1337return index_directory;1338if(!endchar &&S_ISGITLINK(ce->ce_mode))1339return index_gitdir;1340}1341return index_nonexistent;1342}13431344/*1345 * When we find a directory when traversing the filesystem, we1346 * have three distinct cases:1347 *1348 * - ignore it1349 * - see it as a directory1350 * - recurse into it1351 *1352 * and which one we choose depends on a combination of existing1353 * git index contents and the flags passed into the directory1354 * traversal routine.1355 *1356 * Case 1: If we *already* have entries in the index under that1357 * directory name, we always recurse into the directory to see1358 * all the files.1359 *1360 * Case 2: If we *already* have that directory name as a gitlink,1361 * we always continue to see it as a gitlink, regardless of whether1362 * there is an actual git directory there or not (it might not1363 * be checked out as a subproject!)1364 *1365 * Case 3: if we didn't have it in the index previously, we1366 * have a few sub-cases:1367 *1368 * (a) if "show_other_directories" is true, we show it as1369 * just a directory, unless "hide_empty_directories" is1370 * also true, in which case we need to check if it contains any1371 * untracked and / or ignored files.1372 * (b) if it looks like a git directory, and we don't have1373 * 'no_gitlinks' set we treat it as a gitlink, and show it1374 * as a directory.1375 * (c) otherwise, we recurse into it.1376 */1377static enum path_treatment treat_directory(struct dir_struct *dir,1378struct index_state *istate,1379struct untracked_cache_dir *untracked,1380const char*dirname,int len,int baselen,int exclude,1381const struct pathspec *pathspec)1382{1383/* The "len-1" is to strip the final '/' */1384switch(directory_exists_in_index(istate, dirname, len-1)) {1385case index_directory:1386return path_recurse;13871388case index_gitdir:1389return path_none;13901391case index_nonexistent:1392if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1393break;1394if(!(dir->flags & DIR_NO_GITLINKS)) {1395unsigned char sha1[20];1396if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1397return path_untracked;1398}1399return path_recurse;1400}14011402/* This is the "show_other_directories" case */14031404if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1405return exclude ? path_excluded : path_untracked;14061407 untracked =lookup_untracked(dir->untracked, untracked,1408 dirname + baselen, len - baselen);1409returnread_directory_recursive(dir, istate, dirname, len,1410 untracked,1, pathspec);1411}14121413/*1414 * This is an inexact early pruning of any recursive directory1415 * reading - if the path cannot possibly be in the pathspec,1416 * return true, and we'll skip it early.1417 */1418static intsimplify_away(const char*path,int pathlen,1419const struct pathspec *pathspec)1420{1421int i;14221423if(!pathspec || !pathspec->nr)1424return0;14251426GUARD_PATHSPEC(pathspec,1427 PATHSPEC_FROMTOP |1428 PATHSPEC_MAXDEPTH |1429 PATHSPEC_LITERAL |1430 PATHSPEC_GLOB |1431 PATHSPEC_ICASE |1432 PATHSPEC_EXCLUDE |1433 PATHSPEC_ATTR);14341435for(i =0; i < pathspec->nr; i++) {1436const struct pathspec_item *item = &pathspec->items[i];1437int len = item->nowildcard_len;14381439if(len > pathlen)1440 len = pathlen;1441if(!ps_strncmp(item, item->match, path, len))1442return0;1443}14441445return1;1446}14471448/*1449 * This function tells us whether an excluded path matches a1450 * list of "interesting" pathspecs. That is, whether a path matched1451 * by any of the pathspecs could possibly be ignored by excluding1452 * the specified path. This can happen if:1453 *1454 * 1. the path is mentioned explicitly in the pathspec1455 *1456 * 2. the path is a directory prefix of some element in the1457 * pathspec1458 */1459static intexclude_matches_pathspec(const char*path,int pathlen,1460const struct pathspec *pathspec)1461{1462int i;14631464if(!pathspec || !pathspec->nr)1465return0;14661467GUARD_PATHSPEC(pathspec,1468 PATHSPEC_FROMTOP |1469 PATHSPEC_MAXDEPTH |1470 PATHSPEC_LITERAL |1471 PATHSPEC_GLOB |1472 PATHSPEC_ICASE |1473 PATHSPEC_EXCLUDE);14741475for(i =0; i < pathspec->nr; i++) {1476const struct pathspec_item *item = &pathspec->items[i];1477int len = item->nowildcard_len;14781479if(len == pathlen &&1480!ps_strncmp(item, item->match, path, pathlen))1481return1;1482if(len > pathlen &&1483 item->match[pathlen] =='/'&&1484!ps_strncmp(item, item->match, path, pathlen))1485return1;1486}1487return0;1488}14891490static intget_index_dtype(struct index_state *istate,1491const char*path,int len)1492{1493int pos;1494const struct cache_entry *ce;14951496 ce =index_file_exists(istate, path, len,0);1497if(ce) {1498if(!ce_uptodate(ce))1499return DT_UNKNOWN;1500if(S_ISGITLINK(ce->ce_mode))1501return DT_DIR;1502/*1503 * Nobody actually cares about the1504 * difference between DT_LNK and DT_REG1505 */1506return DT_REG;1507}15081509/* Try to look it up as a directory */1510 pos =index_name_pos(istate, path, len);1511if(pos >=0)1512return DT_UNKNOWN;1513 pos = -pos-1;1514while(pos < istate->cache_nr) {1515 ce = istate->cache[pos++];1516if(strncmp(ce->name, path, len))1517break;1518if(ce->name[len] >'/')1519break;1520if(ce->name[len] <'/')1521continue;1522if(!ce_uptodate(ce))1523break;/* continue? */1524return DT_DIR;1525}1526return DT_UNKNOWN;1527}15281529static intget_dtype(struct dirent *de,struct index_state *istate,1530const char*path,int len)1531{1532int dtype = de ?DTYPE(de) : DT_UNKNOWN;1533struct stat st;15341535if(dtype != DT_UNKNOWN)1536return dtype;1537 dtype =get_index_dtype(istate, path, len);1538if(dtype != DT_UNKNOWN)1539return dtype;1540if(lstat(path, &st))1541return dtype;1542if(S_ISREG(st.st_mode))1543return DT_REG;1544if(S_ISDIR(st.st_mode))1545return DT_DIR;1546if(S_ISLNK(st.st_mode))1547return DT_LNK;1548return dtype;1549}15501551static enum path_treatment treat_one_path(struct dir_struct *dir,1552struct untracked_cache_dir *untracked,1553struct index_state *istate,1554struct strbuf *path,1555int baselen,1556const struct pathspec *pathspec,1557int dtype,struct dirent *de)1558{1559int exclude;1560int has_path_in_index = !!index_file_exists(istate, path->buf, path->len, ignore_case);15611562if(dtype == DT_UNKNOWN)1563 dtype =get_dtype(de, istate, path->buf, path->len);15641565/* Always exclude indexed files */1566if(dtype != DT_DIR && has_path_in_index)1567return path_none;15681569/*1570 * When we are looking at a directory P in the working tree,1571 * there are three cases:1572 *1573 * (1) P exists in the index. Everything inside the directory P in1574 * the working tree needs to go when P is checked out from the1575 * index.1576 *1577 * (2) P does not exist in the index, but there is P/Q in the index.1578 * We know P will stay a directory when we check out the contents1579 * of the index, but we do not know yet if there is a directory1580 * P/Q in the working tree to be killed, so we need to recurse.1581 *1582 * (3) P does not exist in the index, and there is no P/Q in the index1583 * to require P to be a directory, either. Only in this case, we1584 * know that everything inside P will not be killed without1585 * recursing.1586 */1587if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1588(dtype == DT_DIR) &&1589!has_path_in_index &&1590(directory_exists_in_index(istate, path->buf, path->len) == index_nonexistent))1591return path_none;15921593 exclude =is_excluded(dir, istate, path->buf, &dtype);15941595/*1596 * Excluded? If we don't explicitly want to show1597 * ignored files, ignore it1598 */1599if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1600return path_excluded;16011602switch(dtype) {1603default:1604return path_none;1605case DT_DIR:1606strbuf_addch(path,'/');1607returntreat_directory(dir, istate, untracked, path->buf, path->len,1608 baselen, exclude, pathspec);1609case DT_REG:1610case DT_LNK:1611return exclude ? path_excluded : path_untracked;1612}1613}16141615static enum path_treatment treat_path_fast(struct dir_struct *dir,1616struct untracked_cache_dir *untracked,1617struct cached_dir *cdir,1618struct index_state *istate,1619struct strbuf *path,1620int baselen,1621const struct pathspec *pathspec)1622{1623strbuf_setlen(path, baselen);1624if(!cdir->ucd) {1625strbuf_addstr(path, cdir->file);1626return path_untracked;1627}1628strbuf_addstr(path, cdir->ucd->name);1629/* treat_one_path() does this before it calls treat_directory() */1630strbuf_complete(path,'/');1631if(cdir->ucd->check_only)1632/*1633 * check_only is set as a result of treat_directory() getting1634 * to its bottom. Verify again the same set of directories1635 * with check_only set.1636 */1637returnread_directory_recursive(dir, istate, path->buf, path->len,1638 cdir->ucd,1, pathspec);1639/*1640 * We get path_recurse in the first run when1641 * directory_exists_in_index() returns index_nonexistent. We1642 * are sure that new changes in the index does not impact the1643 * outcome. Return now.1644 */1645return path_recurse;1646}16471648static enum path_treatment treat_path(struct dir_struct *dir,1649struct untracked_cache_dir *untracked,1650struct cached_dir *cdir,1651struct index_state *istate,1652struct strbuf *path,1653int baselen,1654const struct pathspec *pathspec)1655{1656int dtype;1657struct dirent *de = cdir->de;16581659if(!de)1660returntreat_path_fast(dir, untracked, cdir, istate, path,1661 baselen, pathspec);1662if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1663return path_none;1664strbuf_setlen(path, baselen);1665strbuf_addstr(path, de->d_name);1666if(simplify_away(path->buf, path->len, pathspec))1667return path_none;16681669 dtype =DTYPE(de);1670returntreat_one_path(dir, untracked, istate, path, baselen, pathspec, dtype, de);1671}16721673static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1674{1675if(!dir)1676return;1677ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1678 dir->untracked_alloc);1679 dir->untracked[dir->untracked_nr++] =xstrdup(name);1680}16811682static intvalid_cached_dir(struct dir_struct *dir,1683struct untracked_cache_dir *untracked,1684struct index_state *istate,1685struct strbuf *path,1686int check_only)1687{1688struct stat st;16891690if(!untracked)1691return0;16921693if(stat(path->len ? path->buf :".", &st)) {1694invalidate_directory(dir->untracked, untracked);1695memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1696return0;1697}1698if(!untracked->valid ||1699match_stat_data_racy(istate, &untracked->stat_data, &st)) {1700if(untracked->valid)1701invalidate_directory(dir->untracked, untracked);1702fill_stat_data(&untracked->stat_data, &st);1703return0;1704}17051706if(untracked->check_only != !!check_only) {1707invalidate_directory(dir->untracked, untracked);1708return0;1709}17101711/*1712 * prep_exclude will be called eventually on this directory,1713 * but it's called much later in last_exclude_matching(). We1714 * need it now to determine the validity of the cache for this1715 * path. The next calls will be nearly no-op, the way1716 * prep_exclude() is designed.1717 */1718if(path->len && path->buf[path->len -1] !='/') {1719strbuf_addch(path,'/');1720prep_exclude(dir, istate, path->buf, path->len);1721strbuf_setlen(path, path->len -1);1722}else1723prep_exclude(dir, istate, path->buf, path->len);17241725/* hopefully prep_exclude() haven't invalidated this entry... */1726return untracked->valid;1727}17281729static intopen_cached_dir(struct cached_dir *cdir,1730struct dir_struct *dir,1731struct untracked_cache_dir *untracked,1732struct index_state *istate,1733struct strbuf *path,1734int check_only)1735{1736memset(cdir,0,sizeof(*cdir));1737 cdir->untracked = untracked;1738if(valid_cached_dir(dir, untracked, istate, path, check_only))1739return0;1740 cdir->fdir =opendir(path->len ? path->buf :".");1741if(dir->untracked)1742 dir->untracked->dir_opened++;1743if(!cdir->fdir)1744return-1;1745return0;1746}17471748static intread_cached_dir(struct cached_dir *cdir)1749{1750if(cdir->fdir) {1751 cdir->de =readdir(cdir->fdir);1752if(!cdir->de)1753return-1;1754return0;1755}1756while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1757struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1758if(!d->recurse) {1759 cdir->nr_dirs++;1760continue;1761}1762 cdir->ucd = d;1763 cdir->nr_dirs++;1764return0;1765}1766 cdir->ucd = NULL;1767if(cdir->nr_files < cdir->untracked->untracked_nr) {1768struct untracked_cache_dir *d = cdir->untracked;1769 cdir->file = d->untracked[cdir->nr_files++];1770return0;1771}1772return-1;1773}17741775static voidclose_cached_dir(struct cached_dir *cdir)1776{1777if(cdir->fdir)1778closedir(cdir->fdir);1779/*1780 * We have gone through this directory and found no untracked1781 * entries. Mark it valid.1782 */1783if(cdir->untracked) {1784 cdir->untracked->valid =1;1785 cdir->untracked->recurse =1;1786}1787}17881789/*1790 * Read a directory tree. We currently ignore anything but1791 * directories, regular files and symlinks. That's because git1792 * doesn't handle them at all yet. Maybe that will change some1793 * day.1794 *1795 * Also, we ignore the name ".git" (even if it is not a directory).1796 * That likely will not change.1797 *1798 * Returns the most significant path_treatment value encountered in the scan.1799 */1800static enum path_treatment read_directory_recursive(struct dir_struct *dir,1801struct index_state *istate,const char*base,int baselen,1802struct untracked_cache_dir *untracked,int check_only,1803const struct pathspec *pathspec)1804{1805struct cached_dir cdir;1806enum path_treatment state, subdir_state, dir_state = path_none;1807struct strbuf path = STRBUF_INIT;18081809strbuf_add(&path, base, baselen);18101811if(open_cached_dir(&cdir, dir, untracked, istate, &path, check_only))1812goto out;18131814if(untracked)1815 untracked->check_only = !!check_only;18161817while(!read_cached_dir(&cdir)) {1818/* check how the file or directory should be treated */1819 state =treat_path(dir, untracked, &cdir, istate, &path,1820 baselen, pathspec);18211822if(state > dir_state)1823 dir_state = state;18241825/* recurse into subdir if instructed by treat_path */1826if((state == path_recurse) ||1827((state == path_untracked) &&1828(dir->flags & DIR_SHOW_IGNORED_TOO) &&1829(get_dtype(cdir.de, istate, path.buf, path.len) == DT_DIR))) {1830struct untracked_cache_dir *ud;1831 ud =lookup_untracked(dir->untracked, untracked,1832 path.buf + baselen,1833 path.len - baselen);1834 subdir_state =1835read_directory_recursive(dir, istate, path.buf,1836 path.len, ud,1837 check_only, pathspec);1838if(subdir_state > dir_state)1839 dir_state = subdir_state;1840}18411842if(check_only) {1843/* abort early if maximum state has been reached */1844if(dir_state == path_untracked) {1845if(cdir.fdir)1846add_untracked(untracked, path.buf + baselen);1847break;1848}1849/* skip the dir_add_* part */1850continue;1851}18521853/* add the path to the appropriate result list */1854switch(state) {1855case path_excluded:1856if(dir->flags & DIR_SHOW_IGNORED)1857dir_add_name(dir, istate, path.buf, path.len);1858else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1859((dir->flags & DIR_COLLECT_IGNORED) &&1860exclude_matches_pathspec(path.buf, path.len,1861 pathspec)))1862dir_add_ignored(dir, istate, path.buf, path.len);1863break;18641865case path_untracked:1866if(dir->flags & DIR_SHOW_IGNORED)1867break;1868dir_add_name(dir, istate, path.buf, path.len);1869if(cdir.fdir)1870add_untracked(untracked, path.buf + baselen);1871break;18721873default:1874break;1875}1876}1877close_cached_dir(&cdir);1878 out:1879strbuf_release(&path);18801881return dir_state;1882}18831884intcmp_dir_entry(const void*p1,const void*p2)1885{1886const struct dir_entry *e1 = *(const struct dir_entry **)p1;1887const struct dir_entry *e2 = *(const struct dir_entry **)p2;18881889returnname_compare(e1->name, e1->len, e2->name, e2->len);1890}18911892/* check if *out lexically strictly contains *in */1893intcheck_dir_entry_contains(const struct dir_entry *out,const struct dir_entry *in)1894{1895return(out->len < in->len) &&1896(out->name[out->len -1] =='/') &&1897!memcmp(out->name, in->name, out->len);1898}18991900static inttreat_leading_path(struct dir_struct *dir,1901struct index_state *istate,1902const char*path,int len,1903const struct pathspec *pathspec)1904{1905struct strbuf sb = STRBUF_INIT;1906int baselen, rc =0;1907const char*cp;1908int old_flags = dir->flags;19091910while(len && path[len -1] =='/')1911 len--;1912if(!len)1913return1;1914 baselen =0;1915 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1916while(1) {1917 cp = path + baselen + !!baselen;1918 cp =memchr(cp,'/', path + len - cp);1919if(!cp)1920 baselen = len;1921else1922 baselen = cp - path;1923strbuf_setlen(&sb,0);1924strbuf_add(&sb, path, baselen);1925if(!is_directory(sb.buf))1926break;1927if(simplify_away(sb.buf, sb.len, pathspec))1928break;1929if(treat_one_path(dir, NULL, istate, &sb, baselen, pathspec,1930 DT_DIR, NULL) == path_none)1931break;/* do not recurse into it */1932if(len <= baselen) {1933 rc =1;1934break;/* finished checking */1935}1936}1937strbuf_release(&sb);1938 dir->flags = old_flags;1939return rc;1940}19411942static const char*get_ident_string(void)1943{1944static struct strbuf sb = STRBUF_INIT;1945struct utsname uts;19461947if(sb.len)1948return sb.buf;1949if(uname(&uts) <0)1950die_errno(_("failed to get kernel name and information"));1951strbuf_addf(&sb,"Location%s, system%s",get_git_work_tree(),1952 uts.sysname);1953return sb.buf;1954}19551956static intident_in_untracked(const struct untracked_cache *uc)1957{1958/*1959 * Previous git versions may have saved many NUL separated1960 * strings in the "ident" field, but it is insane to manage1961 * many locations, so just take care of the first one.1962 */19631964return!strcmp(uc->ident.buf,get_ident_string());1965}19661967static voidset_untracked_ident(struct untracked_cache *uc)1968{1969strbuf_reset(&uc->ident);1970strbuf_addstr(&uc->ident,get_ident_string());19711972/*1973 * This strbuf used to contain a list of NUL separated1974 * strings, so save NUL too for backward compatibility.1975 */1976strbuf_addch(&uc->ident,0);1977}19781979static voidnew_untracked_cache(struct index_state *istate)1980{1981struct untracked_cache *uc =xcalloc(1,sizeof(*uc));1982strbuf_init(&uc->ident,100);1983 uc->exclude_per_dir =".gitignore";1984/* should be the same flags used by git-status */1985 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;1986set_untracked_ident(uc);1987 istate->untracked = uc;1988 istate->cache_changed |= UNTRACKED_CHANGED;1989}19901991voidadd_untracked_cache(struct index_state *istate)1992{1993if(!istate->untracked) {1994new_untracked_cache(istate);1995}else{1996if(!ident_in_untracked(istate->untracked)) {1997free_untracked_cache(istate->untracked);1998new_untracked_cache(istate);1999}2000}2001}20022003voidremove_untracked_cache(struct index_state *istate)2004{2005if(istate->untracked) {2006free_untracked_cache(istate->untracked);2007 istate->untracked = NULL;2008 istate->cache_changed |= UNTRACKED_CHANGED;2009}2010}20112012static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,2013int base_len,2014const struct pathspec *pathspec)2015{2016struct untracked_cache_dir *root;20172018if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))2019return NULL;20202021/*2022 * We only support $GIT_DIR/info/exclude and core.excludesfile2023 * as the global ignore rule files. Any other additions2024 * (e.g. from command line) invalidate the cache. This2025 * condition also catches running setup_standard_excludes()2026 * before setting dir->untracked!2027 */2028if(dir->unmanaged_exclude_files)2029return NULL;20302031/*2032 * Optimize for the main use case only: whole-tree git2033 * status. More work involved in treat_leading_path() if we2034 * use cache on just a subset of the worktree. pathspec2035 * support could make the matter even worse.2036 */2037if(base_len || (pathspec && pathspec->nr))2038return NULL;20392040/* Different set of flags may produce different results */2041if(dir->flags != dir->untracked->dir_flags ||2042/*2043 * See treat_directory(), case index_nonexistent. Without2044 * this flag, we may need to also cache .git file content2045 * for the resolve_gitlink_ref() call, which we don't.2046 */2047!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||2048/* We don't support collecting ignore files */2049(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |2050 DIR_COLLECT_IGNORED)))2051return NULL;20522053/*2054 * If we use .gitignore in the cache and now you change it to2055 * .gitexclude, everything will go wrong.2056 */2057if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&2058strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))2059return NULL;20602061/*2062 * EXC_CMDL is not considered in the cache. If people set it,2063 * skip the cache.2064 */2065if(dir->exclude_list_group[EXC_CMDL].nr)2066return NULL;20672068if(!ident_in_untracked(dir->untracked)) {2069warning(_("Untracked cache is disabled on this system or location."));2070return NULL;2071}20722073if(!dir->untracked->root) {2074const int len =sizeof(*dir->untracked->root);2075 dir->untracked->root =xmalloc(len);2076memset(dir->untracked->root,0, len);2077}20782079/* Validate $GIT_DIR/info/exclude and core.excludesfile */2080 root = dir->untracked->root;2081if(hashcmp(dir->ss_info_exclude.sha1,2082 dir->untracked->ss_info_exclude.sha1)) {2083invalidate_gitignore(dir->untracked, root);2084 dir->untracked->ss_info_exclude = dir->ss_info_exclude;2085}2086if(hashcmp(dir->ss_excludes_file.sha1,2087 dir->untracked->ss_excludes_file.sha1)) {2088invalidate_gitignore(dir->untracked, root);2089 dir->untracked->ss_excludes_file = dir->ss_excludes_file;2090}20912092/* Make sure this directory is not dropped out at saving phase */2093 root->recurse =1;2094return root;2095}20962097intread_directory(struct dir_struct *dir,struct index_state *istate,2098const char*path,int len,const struct pathspec *pathspec)2099{2100struct untracked_cache_dir *untracked;21012102if(has_symlink_leading_path(path, len))2103return dir->nr;21042105 untracked =validate_untracked_cache(dir, len, pathspec);2106if(!untracked)2107/*2108 * make sure untracked cache code path is disabled,2109 * e.g. prep_exclude()2110 */2111 dir->untracked = NULL;2112if(!len ||treat_leading_path(dir, istate, path, len, pathspec))2113read_directory_recursive(dir, istate, path, len, untracked,0, pathspec);2114QSORT(dir->entries, dir->nr, cmp_dir_entry);2115QSORT(dir->ignored, dir->ignored_nr, cmp_dir_entry);21162117/*2118 * If DIR_SHOW_IGNORED_TOO is set, read_directory_recursive() will2119 * also pick up untracked contents of untracked dirs; by default2120 * we discard these, but given DIR_KEEP_UNTRACKED_CONTENTS we do not.2121 */2122if((dir->flags & DIR_SHOW_IGNORED_TOO) &&2123!(dir->flags & DIR_KEEP_UNTRACKED_CONTENTS)) {2124int i, j;21252126/* remove from dir->entries untracked contents of untracked dirs */2127for(i = j =0; j < dir->nr; j++) {2128if(i &&2129check_dir_entry_contains(dir->entries[i -1], dir->entries[j])) {2130FREE_AND_NULL(dir->entries[j]);2131}else{2132 dir->entries[i++] = dir->entries[j];2133}2134}21352136 dir->nr = i;2137}21382139if(dir->untracked) {2140static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);2141trace_printf_key(&trace_untracked_stats,2142"node creation:%u\n"2143"gitignore invalidation:%u\n"2144"directory invalidation:%u\n"2145"opendir:%u\n",2146 dir->untracked->dir_created,2147 dir->untracked->gitignore_invalidated,2148 dir->untracked->dir_invalidated,2149 dir->untracked->dir_opened);2150if(dir->untracked == istate->untracked &&2151(dir->untracked->dir_opened ||2152 dir->untracked->gitignore_invalidated ||2153 dir->untracked->dir_invalidated))2154 istate->cache_changed |= UNTRACKED_CHANGED;2155if(dir->untracked != istate->untracked) {2156FREE_AND_NULL(dir->untracked);2157}2158}2159return dir->nr;2160}21612162intfile_exists(const char*f)2163{2164struct stat sb;2165returnlstat(f, &sb) ==0;2166}21672168static intcmp_icase(char a,char b)2169{2170if(a == b)2171return0;2172if(ignore_case)2173returntoupper(a) -toupper(b);2174return a - b;2175}21762177/*2178 * Given two normalized paths (a trailing slash is ok), if subdir is2179 * outside dir, return -1. Otherwise return the offset in subdir that2180 * can be used as relative path to dir.2181 */2182intdir_inside_of(const char*subdir,const char*dir)2183{2184int offset =0;21852186assert(dir && subdir && *dir && *subdir);21872188while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2189 dir++;2190 subdir++;2191 offset++;2192}21932194/* hel[p]/me vs hel[l]/yeah */2195if(*dir && *subdir)2196return-1;21972198if(!*subdir)2199return!*dir ? offset : -1;/* same dir */22002201/* foo/[b]ar vs foo/[] */2202if(is_dir_sep(dir[-1]))2203returnis_dir_sep(subdir[-1]) ? offset : -1;22042205/* foo[/]bar vs foo[] */2206returnis_dir_sep(*subdir) ? offset +1: -1;2207}22082209intis_inside_dir(const char*dir)2210{2211char*cwd;2212int rc;22132214if(!dir)2215return0;22162217 cwd =xgetcwd();2218 rc = (dir_inside_of(cwd, dir) >=0);2219free(cwd);2220return rc;2221}22222223intis_empty_dir(const char*path)2224{2225DIR*dir =opendir(path);2226struct dirent *e;2227int ret =1;22282229if(!dir)2230return0;22312232while((e =readdir(dir)) != NULL)2233if(!is_dot_or_dotdot(e->d_name)) {2234 ret =0;2235break;2236}22372238closedir(dir);2239return ret;2240}22412242static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2243{2244DIR*dir;2245struct dirent *e;2246int ret =0, original_len = path->len, len, kept_down =0;2247int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2248int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2249unsigned char submodule_head[20];22502251if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2252!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2253/* Do not descend and nuke a nested git work tree. */2254if(kept_up)2255*kept_up =1;2256return0;2257}22582259 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2260 dir =opendir(path->buf);2261if(!dir) {2262if(errno == ENOENT)2263return keep_toplevel ? -1:0;2264else if(errno == EACCES && !keep_toplevel)2265/*2266 * An empty dir could be removable even if it2267 * is unreadable:2268 */2269returnrmdir(path->buf);2270else2271return-1;2272}2273strbuf_complete(path,'/');22742275 len = path->len;2276while((e =readdir(dir)) != NULL) {2277struct stat st;2278if(is_dot_or_dotdot(e->d_name))2279continue;22802281strbuf_setlen(path, len);2282strbuf_addstr(path, e->d_name);2283if(lstat(path->buf, &st)) {2284if(errno == ENOENT)2285/*2286 * file disappeared, which is what we2287 * wanted anyway2288 */2289continue;2290/* fall thru */2291}else if(S_ISDIR(st.st_mode)) {2292if(!remove_dir_recurse(path, flag, &kept_down))2293continue;/* happy */2294}else if(!only_empty &&2295(!unlink(path->buf) || errno == ENOENT)) {2296continue;/* happy, too */2297}22982299/* path too long, stat fails, or non-directory still exists */2300 ret = -1;2301break;2302}2303closedir(dir);23042305strbuf_setlen(path, original_len);2306if(!ret && !keep_toplevel && !kept_down)2307 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2308else if(kept_up)2309/*2310 * report the uplevel that it is not an error that we2311 * did not rmdir() our directory.2312 */2313*kept_up = !ret;2314return ret;2315}23162317intremove_dir_recursively(struct strbuf *path,int flag)2318{2319returnremove_dir_recurse(path, flag, NULL);2320}23212322staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")23232324voidsetup_standard_excludes(struct dir_struct *dir)2325{2326 dir->exclude_per_dir =".gitignore";23272328/* core.excludefile defaulting to $XDG_HOME/git/ignore */2329if(!excludes_file)2330 excludes_file =xdg_config_home("ignore");2331if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2332add_excludes_from_file_1(dir, excludes_file,2333 dir->untracked ? &dir->ss_excludes_file : NULL);23342335/* per repository user preference */2336if(startup_info->have_repository) {2337const char*path =git_path_info_exclude();2338if(!access_or_warn(path, R_OK,0))2339add_excludes_from_file_1(dir, path,2340 dir->untracked ? &dir->ss_info_exclude : NULL);2341}2342}23432344intremove_path(const char*name)2345{2346char*slash;23472348if(unlink(name) && !is_missing_file_error(errno))2349return-1;23502351 slash =strrchr(name,'/');2352if(slash) {2353char*dirs =xstrdup(name);2354 slash = dirs + (slash - name);2355do{2356*slash ='\0';2357}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2358free(dirs);2359}2360return0;2361}23622363/*2364 * Frees memory within dir which was allocated for exclude lists and2365 * the exclude_stack. Does not free dir itself.2366 */2367voidclear_directory(struct dir_struct *dir)2368{2369int i, j;2370struct exclude_list_group *group;2371struct exclude_list *el;2372struct exclude_stack *stk;23732374for(i = EXC_CMDL; i <= EXC_FILE; i++) {2375 group = &dir->exclude_list_group[i];2376for(j =0; j < group->nr; j++) {2377 el = &group->el[j];2378if(i == EXC_DIRS)2379free((char*)el->src);2380clear_exclude_list(el);2381}2382free(group->el);2383}23842385 stk = dir->exclude_stack;2386while(stk) {2387struct exclude_stack *prev = stk->prev;2388free(stk);2389 stk = prev;2390}2391strbuf_release(&dir->basebuf);2392}23932394struct ondisk_untracked_cache {2395struct stat_data info_exclude_stat;2396struct stat_data excludes_file_stat;2397uint32_t dir_flags;2398unsigned char info_exclude_sha1[20];2399unsigned char excludes_file_sha1[20];2400char exclude_per_dir[FLEX_ARRAY];2401};24022403#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)24042405struct write_data {2406int index;/* number of written untracked_cache_dir */2407struct ewah_bitmap *check_only;/* from untracked_cache_dir */2408struct ewah_bitmap *valid;/* from untracked_cache_dir */2409struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2410struct strbuf out;2411struct strbuf sb_stat;2412struct strbuf sb_sha1;2413};24142415static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2416{2417 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2418 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2419 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2420 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2421 to->sd_dev =htonl(from->sd_dev);2422 to->sd_ino =htonl(from->sd_ino);2423 to->sd_uid =htonl(from->sd_uid);2424 to->sd_gid =htonl(from->sd_gid);2425 to->sd_size =htonl(from->sd_size);2426}24272428static voidwrite_one_dir(struct untracked_cache_dir *untracked,2429struct write_data *wd)2430{2431struct stat_data stat_data;2432struct strbuf *out = &wd->out;2433unsigned char intbuf[16];2434unsigned int intlen, value;2435int i = wd->index++;24362437/*2438 * untracked_nr should be reset whenever valid is clear, but2439 * for safety..2440 */2441if(!untracked->valid) {2442 untracked->untracked_nr =0;2443 untracked->check_only =0;2444}24452446if(untracked->check_only)2447ewah_set(wd->check_only, i);2448if(untracked->valid) {2449ewah_set(wd->valid, i);2450stat_data_to_disk(&stat_data, &untracked->stat_data);2451strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2452}2453if(!is_null_sha1(untracked->exclude_sha1)) {2454ewah_set(wd->sha1_valid, i);2455strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2456}24572458 intlen =encode_varint(untracked->untracked_nr, intbuf);2459strbuf_add(out, intbuf, intlen);24602461/* skip non-recurse directories */2462for(i =0, value =0; i < untracked->dirs_nr; i++)2463if(untracked->dirs[i]->recurse)2464 value++;2465 intlen =encode_varint(value, intbuf);2466strbuf_add(out, intbuf, intlen);24672468strbuf_add(out, untracked->name,strlen(untracked->name) +1);24692470for(i =0; i < untracked->untracked_nr; i++)2471strbuf_add(out, untracked->untracked[i],2472strlen(untracked->untracked[i]) +1);24732474for(i =0; i < untracked->dirs_nr; i++)2475if(untracked->dirs[i]->recurse)2476write_one_dir(untracked->dirs[i], wd);2477}24782479voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2480{2481struct ondisk_untracked_cache *ouc;2482struct write_data wd;2483unsigned char varbuf[16];2484int varint_len;2485size_t len =strlen(untracked->exclude_per_dir);24862487FLEX_ALLOC_MEM(ouc, exclude_per_dir, untracked->exclude_per_dir, len);2488stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2489stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2490hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2491hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2492 ouc->dir_flags =htonl(untracked->dir_flags);24932494 varint_len =encode_varint(untracked->ident.len, varbuf);2495strbuf_add(out, varbuf, varint_len);2496strbuf_addbuf(out, &untracked->ident);24972498strbuf_add(out, ouc,ouc_size(len));2499FREE_AND_NULL(ouc);25002501if(!untracked->root) {2502 varint_len =encode_varint(0, varbuf);2503strbuf_add(out, varbuf, varint_len);2504return;2505}25062507 wd.index =0;2508 wd.check_only =ewah_new();2509 wd.valid =ewah_new();2510 wd.sha1_valid =ewah_new();2511strbuf_init(&wd.out,1024);2512strbuf_init(&wd.sb_stat,1024);2513strbuf_init(&wd.sb_sha1,1024);2514write_one_dir(untracked->root, &wd);25152516 varint_len =encode_varint(wd.index, varbuf);2517strbuf_add(out, varbuf, varint_len);2518strbuf_addbuf(out, &wd.out);2519ewah_serialize_strbuf(wd.valid, out);2520ewah_serialize_strbuf(wd.check_only, out);2521ewah_serialize_strbuf(wd.sha1_valid, out);2522strbuf_addbuf(out, &wd.sb_stat);2523strbuf_addbuf(out, &wd.sb_sha1);2524strbuf_addch(out,'\0');/* safe guard for string lists */25252526ewah_free(wd.valid);2527ewah_free(wd.check_only);2528ewah_free(wd.sha1_valid);2529strbuf_release(&wd.out);2530strbuf_release(&wd.sb_stat);2531strbuf_release(&wd.sb_sha1);2532}25332534static voidfree_untracked(struct untracked_cache_dir *ucd)2535{2536int i;2537if(!ucd)2538return;2539for(i =0; i < ucd->dirs_nr; i++)2540free_untracked(ucd->dirs[i]);2541for(i =0; i < ucd->untracked_nr; i++)2542free(ucd->untracked[i]);2543free(ucd->untracked);2544free(ucd->dirs);2545free(ucd);2546}25472548voidfree_untracked_cache(struct untracked_cache *uc)2549{2550if(uc)2551free_untracked(uc->root);2552free(uc);2553}25542555struct read_data {2556int index;2557struct untracked_cache_dir **ucd;2558struct ewah_bitmap *check_only;2559struct ewah_bitmap *valid;2560struct ewah_bitmap *sha1_valid;2561const unsigned char*data;2562const unsigned char*end;2563};25642565static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2566{2567 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2568 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2569 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2570 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2571 to->sd_dev =get_be32(&from->sd_dev);2572 to->sd_ino =get_be32(&from->sd_ino);2573 to->sd_uid =get_be32(&from->sd_uid);2574 to->sd_gid =get_be32(&from->sd_gid);2575 to->sd_size =get_be32(&from->sd_size);2576}25772578static intread_one_dir(struct untracked_cache_dir **untracked_,2579struct read_data *rd)2580{2581struct untracked_cache_dir ud, *untracked;2582const unsigned char*next, *data = rd->data, *end = rd->end;2583unsigned int value;2584int i, len;25852586memset(&ud,0,sizeof(ud));25872588 next = data;2589 value =decode_varint(&next);2590if(next > end)2591return-1;2592 ud.recurse =1;2593 ud.untracked_alloc = value;2594 ud.untracked_nr = value;2595if(ud.untracked_nr)2596ALLOC_ARRAY(ud.untracked, ud.untracked_nr);2597 data = next;25982599 next = data;2600 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2601if(next > end)2602return-1;2603ALLOC_ARRAY(ud.dirs, ud.dirs_nr);2604 data = next;26052606 len =strlen((const char*)data);2607 next = data + len +1;2608if(next > rd->end)2609return-1;2610*untracked_ = untracked =xmalloc(st_add(sizeof(*untracked), len));2611memcpy(untracked, &ud,sizeof(ud));2612memcpy(untracked->name, data, len +1);2613 data = next;26142615for(i =0; i < untracked->untracked_nr; i++) {2616 len =strlen((const char*)data);2617 next = data + len +1;2618if(next > rd->end)2619return-1;2620 untracked->untracked[i] =xstrdup((const char*)data);2621 data = next;2622}26232624 rd->ucd[rd->index++] = untracked;2625 rd->data = data;26262627for(i =0; i < untracked->dirs_nr; i++) {2628 len =read_one_dir(untracked->dirs + i, rd);2629if(len <0)2630return-1;2631}2632return0;2633}26342635static voidset_check_only(size_t pos,void*cb)2636{2637struct read_data *rd = cb;2638struct untracked_cache_dir *ud = rd->ucd[pos];2639 ud->check_only =1;2640}26412642static voidread_stat(size_t pos,void*cb)2643{2644struct read_data *rd = cb;2645struct untracked_cache_dir *ud = rd->ucd[pos];2646if(rd->data +sizeof(struct stat_data) > rd->end) {2647 rd->data = rd->end +1;2648return;2649}2650stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2651 rd->data +=sizeof(struct stat_data);2652 ud->valid =1;2653}26542655static voidread_sha1(size_t pos,void*cb)2656{2657struct read_data *rd = cb;2658struct untracked_cache_dir *ud = rd->ucd[pos];2659if(rd->data +20> rd->end) {2660 rd->data = rd->end +1;2661return;2662}2663hashcpy(ud->exclude_sha1, rd->data);2664 rd->data +=20;2665}26662667static voidload_sha1_stat(struct sha1_stat *sha1_stat,2668const struct stat_data *stat,2669const unsigned char*sha1)2670{2671stat_data_from_disk(&sha1_stat->stat, stat);2672hashcpy(sha1_stat->sha1, sha1);2673 sha1_stat->valid =1;2674}26752676struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2677{2678const struct ondisk_untracked_cache *ouc;2679struct untracked_cache *uc;2680struct read_data rd;2681const unsigned char*next = data, *end = (const unsigned char*)data + sz;2682const char*ident;2683int ident_len, len;26842685if(sz <=1|| end[-1] !='\0')2686return NULL;2687 end--;26882689 ident_len =decode_varint(&next);2690if(next + ident_len > end)2691return NULL;2692 ident = (const char*)next;2693 next += ident_len;26942695 ouc = (const struct ondisk_untracked_cache *)next;2696if(next +ouc_size(0) > end)2697return NULL;26982699 uc =xcalloc(1,sizeof(*uc));2700strbuf_init(&uc->ident, ident_len);2701strbuf_add(&uc->ident, ident, ident_len);2702load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2703 ouc->info_exclude_sha1);2704load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2705 ouc->excludes_file_sha1);2706 uc->dir_flags =get_be32(&ouc->dir_flags);2707 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2708/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2709 next +=ouc_size(strlen(ouc->exclude_per_dir));2710if(next >= end)2711goto done2;27122713 len =decode_varint(&next);2714if(next > end || len ==0)2715goto done2;27162717 rd.valid =ewah_new();2718 rd.check_only =ewah_new();2719 rd.sha1_valid =ewah_new();2720 rd.data = next;2721 rd.end = end;2722 rd.index =0;2723ALLOC_ARRAY(rd.ucd, len);27242725if(read_one_dir(&uc->root, &rd) || rd.index != len)2726goto done;27272728 next = rd.data;2729 len =ewah_read_mmap(rd.valid, next, end - next);2730if(len <0)2731goto done;27322733 next += len;2734 len =ewah_read_mmap(rd.check_only, next, end - next);2735if(len <0)2736goto done;27372738 next += len;2739 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2740if(len <0)2741goto done;27422743ewah_each_bit(rd.check_only, set_check_only, &rd);2744 rd.data = next + len;2745ewah_each_bit(rd.valid, read_stat, &rd);2746ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2747 next = rd.data;27482749done:2750free(rd.ucd);2751ewah_free(rd.valid);2752ewah_free(rd.check_only);2753ewah_free(rd.sha1_valid);2754done2:2755if(next != end) {2756free_untracked_cache(uc);2757 uc = NULL;2758}2759return uc;2760}27612762static voidinvalidate_one_directory(struct untracked_cache *uc,2763struct untracked_cache_dir *ucd)2764{2765 uc->dir_invalidated++;2766 ucd->valid =0;2767 ucd->untracked_nr =0;2768}27692770/*2771 * Normally when an entry is added or removed from a directory,2772 * invalidating that directory is enough. No need to touch its2773 * ancestors. When a directory is shown as "foo/bar/" in git-status2774 * however, deleting or adding an entry may have cascading effect.2775 *2776 * Say the "foo/bar/file" has become untracked, we need to tell the2777 * untracked_cache_dir of "foo" that "bar/" is not an untracked2778 * directory any more (because "bar" is managed by foo as an untracked2779 * "file").2780 *2781 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2782 * was the last untracked entry in the entire "foo", we should show2783 * "foo/" instead. Which means we have to invalidate past "bar" up to2784 * "foo".2785 *2786 * This function traverses all directories from root to leaf. If there2787 * is a chance of one of the above cases happening, we invalidate back2788 * to root. Otherwise we just invalidate the leaf. There may be a more2789 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2790 * detect these cases and avoid unnecessary invalidation, for example,2791 * checking for the untracked entry named "bar/" in "foo", but for now2792 * stick to something safe and simple.2793 */2794static intinvalidate_one_component(struct untracked_cache *uc,2795struct untracked_cache_dir *dir,2796const char*path,int len)2797{2798const char*rest =strchr(path,'/');27992800if(rest) {2801int component_len = rest - path;2802struct untracked_cache_dir *d =2803lookup_untracked(uc, dir, path, component_len);2804int ret =2805invalidate_one_component(uc, d, rest +1,2806 len - (component_len +1));2807if(ret)2808invalidate_one_directory(uc, dir);2809return ret;2810}28112812invalidate_one_directory(uc, dir);2813return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2814}28152816voiduntracked_cache_invalidate_path(struct index_state *istate,2817const char*path)2818{2819if(!istate->untracked || !istate->untracked->root)2820return;2821invalidate_one_component(istate->untracked, istate->untracked->root,2822 path,strlen(path));2823}28242825voiduntracked_cache_remove_from_index(struct index_state *istate,2826const char*path)2827{2828untracked_cache_invalidate_path(istate, path);2829}28302831voiduntracked_cache_add_to_index(struct index_state *istate,2832const char*path)2833{2834untracked_cache_invalidate_path(istate, path);2835}28362837/* Update gitfile and core.worktree setting to connect work tree and git dir */2838voidconnect_work_tree_and_git_dir(const char*work_tree_,const char*git_dir_)2839{2840struct strbuf gitfile_sb = STRBUF_INIT;2841struct strbuf cfg_sb = STRBUF_INIT;2842struct strbuf rel_path = STRBUF_INIT;2843char*git_dir, *work_tree;28442845/* Prepare .git file */2846strbuf_addf(&gitfile_sb,"%s/.git", work_tree_);2847if(safe_create_leading_directories_const(gitfile_sb.buf))2848die(_("could not create directories for%s"), gitfile_sb.buf);28492850/* Prepare config file */2851strbuf_addf(&cfg_sb,"%s/config", git_dir_);2852if(safe_create_leading_directories_const(cfg_sb.buf))2853die(_("could not create directories for%s"), cfg_sb.buf);28542855 git_dir =real_pathdup(git_dir_,1);2856 work_tree =real_pathdup(work_tree_,1);28572858/* Write .git file */2859write_file(gitfile_sb.buf,"gitdir:%s",2860relative_path(git_dir, work_tree, &rel_path));2861/* Update core.worktree setting */2862git_config_set_in_file(cfg_sb.buf,"core.worktree",2863relative_path(work_tree, git_dir, &rel_path));28642865strbuf_release(&gitfile_sb);2866strbuf_release(&cfg_sb);2867strbuf_release(&rel_path);2868free(work_tree);2869free(git_dir);2870}28712872/*2873 * Migrate the git directory of the given path from old_git_dir to new_git_dir.2874 */2875voidrelocate_gitdir(const char*path,const char*old_git_dir,const char*new_git_dir)2876{2877if(rename(old_git_dir, new_git_dir) <0)2878die_errno(_("could not migrate git directory from '%s' to '%s'"),2879 old_git_dir, new_git_dir);28802881connect_work_tree_and_git_dir(path, new_git_dir);2882}