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 56intfspathcmp(const char*a,const char*b) 57{ 58return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 59} 60 61intfspathncmp(const char*a,const char*b,size_t count) 62{ 63return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 64} 65 66intgit_fnmatch(const struct pathspec_item *item, 67const char*pattern,const char*string, 68int prefix) 69{ 70if(prefix >0) { 71if(ps_strncmp(item, pattern, string, prefix)) 72return WM_NOMATCH; 73 pattern += prefix; 74 string += prefix; 75} 76if(item->flags & PATHSPEC_ONESTAR) { 77int pattern_len =strlen(++pattern); 78int string_len =strlen(string); 79return string_len < pattern_len || 80ps_strcmp(item, pattern, 81 string + string_len - pattern_len); 82} 83if(item->magic & PATHSPEC_GLOB) 84returnwildmatch(pattern, string, 85 WM_PATHNAME | 86(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 87 NULL); 88else 89/* wildmatch has not learned no FNM_PATHNAME mode yet */ 90returnwildmatch(pattern, string, 91 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 92 NULL); 93} 94 95static intfnmatch_icase_mem(const char*pattern,int patternlen, 96const char*string,int stringlen, 97int flags) 98{ 99int match_status; 100struct strbuf pat_buf = STRBUF_INIT; 101struct strbuf str_buf = STRBUF_INIT; 102const char*use_pat = pattern; 103const char*use_str = string; 104 105if(pattern[patternlen]) { 106strbuf_add(&pat_buf, pattern, patternlen); 107 use_pat = pat_buf.buf; 108} 109if(string[stringlen]) { 110strbuf_add(&str_buf, string, stringlen); 111 use_str = str_buf.buf; 112} 113 114if(ignore_case) 115 flags |= WM_CASEFOLD; 116 match_status =wildmatch(use_pat, use_str, flags, NULL); 117 118strbuf_release(&pat_buf); 119strbuf_release(&str_buf); 120 121return match_status; 122} 123 124static size_tcommon_prefix_len(const struct pathspec *pathspec) 125{ 126int n; 127size_t max =0; 128 129/* 130 * ":(icase)path" is treated as a pathspec full of 131 * wildcard. In other words, only prefix is considered common 132 * prefix. If the pathspec is abc/foo abc/bar, running in 133 * subdir xyz, the common prefix is still xyz, not xuz/abc as 134 * in non-:(icase). 135 */ 136GUARD_PATHSPEC(pathspec, 137 PATHSPEC_FROMTOP | 138 PATHSPEC_MAXDEPTH | 139 PATHSPEC_LITERAL | 140 PATHSPEC_GLOB | 141 PATHSPEC_ICASE | 142 PATHSPEC_EXCLUDE | 143 PATHSPEC_ATTR); 144 145for(n =0; n < pathspec->nr; n++) { 146size_t i =0, len =0, item_len; 147if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 148continue; 149if(pathspec->items[n].magic & PATHSPEC_ICASE) 150 item_len = pathspec->items[n].prefix; 151else 152 item_len = pathspec->items[n].nowildcard_len; 153while(i < item_len && (n ==0|| i < max)) { 154char c = pathspec->items[n].match[i]; 155if(c != pathspec->items[0].match[i]) 156break; 157if(c =='/') 158 len = i +1; 159 i++; 160} 161if(n ==0|| len < max) { 162 max = len; 163if(!max) 164break; 165} 166} 167return max; 168} 169 170/* 171 * Returns a copy of the longest leading path common among all 172 * pathspecs. 173 */ 174char*common_prefix(const struct pathspec *pathspec) 175{ 176unsigned long len =common_prefix_len(pathspec); 177 178return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 179} 180 181intfill_directory(struct dir_struct *dir, 182struct index_state *istate, 183const struct pathspec *pathspec) 184{ 185const char*prefix; 186size_t prefix_len; 187 188/* 189 * Calculate common prefix for the pathspec, and 190 * use that to optimize the directory walk 191 */ 192 prefix_len =common_prefix_len(pathspec); 193 prefix = prefix_len ? pathspec->items[0].match :""; 194 195/* Read the directory and prune it */ 196read_directory(dir, istate, prefix, prefix_len, pathspec); 197 198return prefix_len; 199} 200 201intwithin_depth(const char*name,int namelen, 202int depth,int max_depth) 203{ 204const char*cp = name, *cpe = name + namelen; 205 206while(cp < cpe) { 207if(*cp++ !='/') 208continue; 209 depth++; 210if(depth > max_depth) 211return0; 212} 213return1; 214} 215 216#define DO_MATCH_EXCLUDE (1<<0) 217#define DO_MATCH_DIRECTORY (1<<1) 218#define DO_MATCH_SUBMODULE (1<<2) 219 220static intmatch_attrs(const char*name,int namelen, 221const struct pathspec_item *item) 222{ 223int i; 224 225git_check_attr(name, item->attr_check); 226for(i =0; i < item->attr_match_nr; i++) { 227const char*value; 228int matched; 229enum attr_match_mode match_mode; 230 231 value = item->attr_check->items[i].value; 232 match_mode = item->attr_match[i].match_mode; 233 234if(ATTR_TRUE(value)) 235 matched = (match_mode == MATCH_SET); 236else if(ATTR_FALSE(value)) 237 matched = (match_mode == MATCH_UNSET); 238else if(ATTR_UNSET(value)) 239 matched = (match_mode == MATCH_UNSPECIFIED); 240else 241 matched = (match_mode == MATCH_VALUE && 242!strcmp(item->attr_match[i].value, value)); 243if(!matched) 244return0; 245} 246 247return1; 248} 249 250/* 251 * Does 'match' match the given name? 252 * A match is found if 253 * 254 * (1) the 'match' string is leading directory of 'name', or 255 * (2) the 'match' string is a wildcard and matches 'name', or 256 * (3) the 'match' string is exactly the same as 'name'. 257 * 258 * and the return value tells which case it was. 259 * 260 * It returns 0 when there is no match. 261 */ 262static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 263const char*name,int namelen,unsigned flags) 264{ 265/* name/namelen has prefix cut off by caller */ 266const char*match = item->match + prefix; 267int matchlen = item->len - prefix; 268 269/* 270 * The normal call pattern is: 271 * 1. prefix = common_prefix_len(ps); 272 * 2. prune something, or fill_directory 273 * 3. match_pathspec() 274 * 275 * 'prefix' at #1 may be shorter than the command's prefix and 276 * it's ok for #2 to match extra files. Those extras will be 277 * trimmed at #3. 278 * 279 * Suppose the pathspec is 'foo' and '../bar' running from 280 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 281 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 282 * user does not want XYZ/foo, only the "foo" part should be 283 * case-insensitive. We need to filter out XYZ/foo here. In 284 * other words, we do not trust the caller on comparing the 285 * prefix part when :(icase) is involved. We do exact 286 * comparison ourselves. 287 * 288 * Normally the caller (common_prefix_len() in fact) does 289 * _exact_ matching on name[-prefix+1..-1] and we do not need 290 * to check that part. Be defensive and check it anyway, in 291 * case common_prefix_len is changed, or a new caller is 292 * introduced that does not use common_prefix_len. 293 * 294 * If the penalty turns out too high when prefix is really 295 * long, maybe change it to 296 * strncmp(match, name, item->prefix - prefix) 297 */ 298if(item->prefix && (item->magic & PATHSPEC_ICASE) && 299strncmp(item->match, name - prefix, item->prefix)) 300return0; 301 302if(item->attr_match_nr && !match_attrs(name, namelen, item)) 303return0; 304 305/* If the match was just the prefix, we matched */ 306if(!*match) 307return MATCHED_RECURSIVELY; 308 309if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 310if(matchlen == namelen) 311return MATCHED_EXACTLY; 312 313if(match[matchlen-1] =='/'|| name[matchlen] =='/') 314return MATCHED_RECURSIVELY; 315}else if((flags & DO_MATCH_DIRECTORY) && 316 match[matchlen -1] =='/'&& 317 namelen == matchlen -1&& 318!ps_strncmp(item, match, name, namelen)) 319return MATCHED_EXACTLY; 320 321if(item->nowildcard_len < item->len && 322!git_fnmatch(item, match, name, 323 item->nowildcard_len - prefix)) 324return MATCHED_FNMATCH; 325 326/* Perform checks to see if "name" is a super set of the pathspec */ 327if(flags & DO_MATCH_SUBMODULE) { 328/* name is a literal prefix of the pathspec */ 329if((namelen < matchlen) && 330(match[namelen] =='/') && 331!ps_strncmp(item, match, name, namelen)) 332return MATCHED_RECURSIVELY; 333 334/* name" doesn't match up to the first wild character */ 335if(item->nowildcard_len < item->len && 336ps_strncmp(item, match, name, 337 item->nowildcard_len - prefix)) 338return0; 339 340/* 341 * Here is where we would perform a wildmatch to check if 342 * "name" can be matched as a directory (or a prefix) against 343 * the pathspec. Since wildmatch doesn't have this capability 344 * at the present we have to punt and say that it is a match, 345 * potentially returning a false positive 346 * The submodules themselves will be able to perform more 347 * accurate matching to determine if the pathspec matches. 348 */ 349return MATCHED_RECURSIVELY; 350} 351 352return0; 353} 354 355/* 356 * Given a name and a list of pathspecs, returns the nature of the 357 * closest (i.e. most specific) match of the name to any of the 358 * pathspecs. 359 * 360 * The caller typically calls this multiple times with the same 361 * pathspec and seen[] array but with different name/namelen 362 * (e.g. entries from the index) and is interested in seeing if and 363 * how each pathspec matches all the names it calls this function 364 * with. A mark is left in the seen[] array for each pathspec element 365 * indicating the closest type of match that element achieved, so if 366 * seen[n] remains zero after multiple invocations, that means the nth 367 * pathspec did not match any names, which could indicate that the 368 * user mistyped the nth pathspec. 369 */ 370static intdo_match_pathspec(const struct pathspec *ps, 371const char*name,int namelen, 372int prefix,char*seen, 373unsigned flags) 374{ 375int i, retval =0, exclude = flags & DO_MATCH_EXCLUDE; 376 377GUARD_PATHSPEC(ps, 378 PATHSPEC_FROMTOP | 379 PATHSPEC_MAXDEPTH | 380 PATHSPEC_LITERAL | 381 PATHSPEC_GLOB | 382 PATHSPEC_ICASE | 383 PATHSPEC_EXCLUDE | 384 PATHSPEC_ATTR); 385 386if(!ps->nr) { 387if(!ps->recursive || 388!(ps->magic & PATHSPEC_MAXDEPTH) || 389 ps->max_depth == -1) 390return MATCHED_RECURSIVELY; 391 392if(within_depth(name, namelen,0, ps->max_depth)) 393return MATCHED_EXACTLY; 394else 395return0; 396} 397 398 name += prefix; 399 namelen -= prefix; 400 401for(i = ps->nr -1; i >=0; i--) { 402int how; 403 404if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 405( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 406continue; 407 408if(seen && seen[i] == MATCHED_EXACTLY) 409continue; 410/* 411 * Make exclude patterns optional and never report 412 * "pathspec ':(exclude)foo' matches no files" 413 */ 414if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 415 seen[i] = MATCHED_FNMATCH; 416 how =match_pathspec_item(ps->items+i, prefix, name, 417 namelen, flags); 418if(ps->recursive && 419(ps->magic & PATHSPEC_MAXDEPTH) && 420 ps->max_depth != -1&& 421 how && how != MATCHED_FNMATCH) { 422int len = ps->items[i].len; 423if(name[len] =='/') 424 len++; 425if(within_depth(name+len, namelen-len,0, ps->max_depth)) 426 how = MATCHED_EXACTLY; 427else 428 how =0; 429} 430if(how) { 431if(retval < how) 432 retval = how; 433if(seen && seen[i] < how) 434 seen[i] = how; 435} 436} 437return retval; 438} 439 440intmatch_pathspec(const struct pathspec *ps, 441const char*name,int namelen, 442int prefix,char*seen,int is_dir) 443{ 444int positive, negative; 445unsigned flags = is_dir ? DO_MATCH_DIRECTORY :0; 446 positive =do_match_pathspec(ps, name, namelen, 447 prefix, seen, flags); 448if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 449return positive; 450 negative =do_match_pathspec(ps, name, namelen, 451 prefix, seen, 452 flags | DO_MATCH_EXCLUDE); 453return negative ?0: positive; 454} 455 456/** 457 * Check if a submodule is a superset of the pathspec 458 */ 459intsubmodule_path_match(const struct pathspec *ps, 460const char*submodule_name, 461char*seen) 462{ 463int matched =do_match_pathspec(ps, submodule_name, 464strlen(submodule_name), 4650, seen, 466 DO_MATCH_DIRECTORY | 467 DO_MATCH_SUBMODULE); 468return matched; 469} 470 471intreport_path_error(const char*ps_matched, 472const struct pathspec *pathspec, 473const char*prefix) 474{ 475/* 476 * Make sure all pathspec matched; otherwise it is an error. 477 */ 478int num, errors =0; 479for(num =0; num < pathspec->nr; num++) { 480int other, found_dup; 481 482if(ps_matched[num]) 483continue; 484/* 485 * The caller might have fed identical pathspec 486 * twice. Do not barf on such a mistake. 487 * FIXME: parse_pathspec should have eliminated 488 * duplicate pathspec. 489 */ 490for(found_dup = other =0; 491!found_dup && other < pathspec->nr; 492 other++) { 493if(other == num || !ps_matched[other]) 494continue; 495if(!strcmp(pathspec->items[other].original, 496 pathspec->items[num].original)) 497/* 498 * Ok, we have a match already. 499 */ 500 found_dup =1; 501} 502if(found_dup) 503continue; 504 505error("pathspec '%s' did not match any file(s) known to git.", 506 pathspec->items[num].original); 507 errors++; 508} 509return errors; 510} 511 512/* 513 * Return the length of the "simple" part of a path match limiter. 514 */ 515intsimple_length(const char*match) 516{ 517int len = -1; 518 519for(;;) { 520unsigned char c = *match++; 521 len++; 522if(c =='\0'||is_glob_special(c)) 523return len; 524} 525} 526 527intno_wildcard(const char*string) 528{ 529return string[simple_length(string)] =='\0'; 530} 531 532voidparse_exclude_pattern(const char**pattern, 533int*patternlen, 534unsigned*flags, 535int*nowildcardlen) 536{ 537const char*p = *pattern; 538size_t i, len; 539 540*flags =0; 541if(*p =='!') { 542*flags |= EXC_FLAG_NEGATIVE; 543 p++; 544} 545 len =strlen(p); 546if(len && p[len -1] =='/') { 547 len--; 548*flags |= EXC_FLAG_MUSTBEDIR; 549} 550for(i =0; i < len; i++) { 551if(p[i] =='/') 552break; 553} 554if(i == len) 555*flags |= EXC_FLAG_NODIR; 556*nowildcardlen =simple_length(p); 557/* 558 * we should have excluded the trailing slash from 'p' too, 559 * but that's one more allocation. Instead just make sure 560 * nowildcardlen does not exceed real patternlen 561 */ 562if(*nowildcardlen > len) 563*nowildcardlen = len; 564if(*p =='*'&&no_wildcard(p +1)) 565*flags |= EXC_FLAG_ENDSWITH; 566*pattern = p; 567*patternlen = len; 568} 569 570voidadd_exclude(const char*string,const char*base, 571int baselen,struct exclude_list *el,int srcpos) 572{ 573struct exclude *x; 574int patternlen; 575unsigned flags; 576int nowildcardlen; 577 578parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 579if(flags & EXC_FLAG_MUSTBEDIR) { 580FLEXPTR_ALLOC_MEM(x, pattern, string, patternlen); 581}else{ 582 x =xmalloc(sizeof(*x)); 583 x->pattern = string; 584} 585 x->patternlen = patternlen; 586 x->nowildcardlen = nowildcardlen; 587 x->base = base; 588 x->baselen = baselen; 589 x->flags = flags; 590 x->srcpos = srcpos; 591ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 592 el->excludes[el->nr++] = x; 593 x->el = el; 594} 595 596static void*read_skip_worktree_file_from_index(const struct index_state *istate, 597const char*path,size_t*size, 598struct sha1_stat *sha1_stat) 599{ 600int pos, len; 601unsigned long sz; 602enum object_type type; 603void*data; 604 605 len =strlen(path); 606 pos =index_name_pos(istate, path, len); 607if(pos <0) 608return NULL; 609if(!ce_skip_worktree(istate->cache[pos])) 610return NULL; 611 data =read_sha1_file(istate->cache[pos]->oid.hash, &type, &sz); 612if(!data || type != OBJ_BLOB) { 613free(data); 614return NULL; 615} 616*size =xsize_t(sz); 617if(sha1_stat) { 618memset(&sha1_stat->stat,0,sizeof(sha1_stat->stat)); 619hashcpy(sha1_stat->sha1, istate->cache[pos]->oid.hash); 620} 621return data; 622} 623 624/* 625 * Frees memory within el which was allocated for exclude patterns and 626 * the file buffer. Does not free el itself. 627 */ 628voidclear_exclude_list(struct exclude_list *el) 629{ 630int i; 631 632for(i =0; i < el->nr; i++) 633free(el->excludes[i]); 634free(el->excludes); 635free(el->filebuf); 636 637memset(el,0,sizeof(*el)); 638} 639 640static voidtrim_trailing_spaces(char*buf) 641{ 642char*p, *last_space = NULL; 643 644for(p = buf; *p; p++) 645switch(*p) { 646case' ': 647if(!last_space) 648 last_space = p; 649break; 650case'\\': 651 p++; 652if(!*p) 653return; 654/* fallthrough */ 655default: 656 last_space = NULL; 657} 658 659if(last_space) 660*last_space ='\0'; 661} 662 663/* 664 * Given a subdirectory name and "dir" of the current directory, 665 * search the subdir in "dir" and return it, or create a new one if it 666 * does not exist in "dir". 667 * 668 * If "name" has the trailing slash, it'll be excluded in the search. 669 */ 670static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc, 671struct untracked_cache_dir *dir, 672const char*name,int len) 673{ 674int first, last; 675struct untracked_cache_dir *d; 676if(!dir) 677return NULL; 678if(len && name[len -1] =='/') 679 len--; 680 first =0; 681 last = dir->dirs_nr; 682while(last > first) { 683int cmp, next = (last + first) >>1; 684 d = dir->dirs[next]; 685 cmp =strncmp(name, d->name, len); 686if(!cmp &&strlen(d->name) > len) 687 cmp = -1; 688if(!cmp) 689return d; 690if(cmp <0) { 691 last = next; 692continue; 693} 694 first = next+1; 695} 696 697 uc->dir_created++; 698FLEX_ALLOC_MEM(d, name, name, len); 699 700ALLOC_GROW(dir->dirs, dir->dirs_nr +1, dir->dirs_alloc); 701memmove(dir->dirs + first +1, dir->dirs + first, 702(dir->dirs_nr - first) *sizeof(*dir->dirs)); 703 dir->dirs_nr++; 704 dir->dirs[first] = d; 705return d; 706} 707 708static voiddo_invalidate_gitignore(struct untracked_cache_dir *dir) 709{ 710int i; 711 dir->valid =0; 712 dir->untracked_nr =0; 713for(i =0; i < dir->dirs_nr; i++) 714do_invalidate_gitignore(dir->dirs[i]); 715} 716 717static voidinvalidate_gitignore(struct untracked_cache *uc, 718struct untracked_cache_dir *dir) 719{ 720 uc->gitignore_invalidated++; 721do_invalidate_gitignore(dir); 722} 723 724static voidinvalidate_directory(struct untracked_cache *uc, 725struct untracked_cache_dir *dir) 726{ 727int i; 728 uc->dir_invalidated++; 729 dir->valid =0; 730 dir->untracked_nr =0; 731for(i =0; i < dir->dirs_nr; i++) 732 dir->dirs[i]->recurse =0; 733} 734 735/* 736 * Given a file with name "fname", read it (either from disk, or from 737 * an index if 'istate' is non-null), parse it and store the 738 * exclude rules in "el". 739 * 740 * If "ss" is not NULL, compute SHA-1 of the exclude file and fill 741 * stat data from disk (only valid if add_excludes returns zero). If 742 * ss_valid is non-zero, "ss" must contain good value as input. 743 */ 744static intadd_excludes(const char*fname,const char*base,int baselen, 745struct exclude_list *el, 746struct index_state *istate, 747struct sha1_stat *sha1_stat) 748{ 749struct stat st; 750int fd, i, lineno =1; 751size_t size =0; 752char*buf, *entry; 753 754 fd =open(fname, O_RDONLY); 755if(fd <0||fstat(fd, &st) <0) { 756if(fd <0) 757warn_on_fopen_errors(fname); 758else 759close(fd); 760if(!istate || 761(buf =read_skip_worktree_file_from_index(istate, fname, &size, sha1_stat)) == NULL) 762return-1; 763if(size ==0) { 764free(buf); 765return0; 766} 767if(buf[size-1] !='\n') { 768 buf =xrealloc(buf,st_add(size,1)); 769 buf[size++] ='\n'; 770} 771}else{ 772 size =xsize_t(st.st_size); 773if(size ==0) { 774if(sha1_stat) { 775fill_stat_data(&sha1_stat->stat, &st); 776hashcpy(sha1_stat->sha1, EMPTY_BLOB_SHA1_BIN); 777 sha1_stat->valid =1; 778} 779close(fd); 780return0; 781} 782 buf =xmallocz(size); 783if(read_in_full(fd, buf, size) != size) { 784free(buf); 785close(fd); 786return-1; 787} 788 buf[size++] ='\n'; 789close(fd); 790if(sha1_stat) { 791int pos; 792if(sha1_stat->valid && 793!match_stat_data_racy(istate, &sha1_stat->stat, &st)) 794;/* no content change, ss->sha1 still good */ 795else if(istate && 796(pos =index_name_pos(istate, fname,strlen(fname))) >=0&& 797!ce_stage(istate->cache[pos]) && 798ce_uptodate(istate->cache[pos]) && 799!would_convert_to_git(istate, fname)) 800hashcpy(sha1_stat->sha1, 801 istate->cache[pos]->oid.hash); 802else 803hash_sha1_file(buf, size,"blob", sha1_stat->sha1); 804fill_stat_data(&sha1_stat->stat, &st); 805 sha1_stat->valid =1; 806} 807} 808 809 el->filebuf = buf; 810 811if(skip_utf8_bom(&buf, size)) 812 size -= buf - el->filebuf; 813 814 entry = buf; 815 816for(i =0; i < size; i++) { 817if(buf[i] =='\n') { 818if(entry != buf + i && entry[0] !='#') { 819 buf[i - (i && buf[i-1] =='\r')] =0; 820trim_trailing_spaces(entry); 821add_exclude(entry, base, baselen, el, lineno); 822} 823 lineno++; 824 entry = buf + i +1; 825} 826} 827return0; 828} 829 830intadd_excludes_from_file_to_list(const char*fname,const char*base, 831int baselen,struct exclude_list *el, 832struct index_state *istate) 833{ 834returnadd_excludes(fname, base, baselen, el, istate, NULL); 835} 836 837struct exclude_list *add_exclude_list(struct dir_struct *dir, 838int group_type,const char*src) 839{ 840struct exclude_list *el; 841struct exclude_list_group *group; 842 843 group = &dir->exclude_list_group[group_type]; 844ALLOC_GROW(group->el, group->nr +1, group->alloc); 845 el = &group->el[group->nr++]; 846memset(el,0,sizeof(*el)); 847 el->src = src; 848return el; 849} 850 851/* 852 * Used to set up core.excludesfile and .git/info/exclude lists. 853 */ 854static voidadd_excludes_from_file_1(struct dir_struct *dir,const char*fname, 855struct sha1_stat *sha1_stat) 856{ 857struct exclude_list *el; 858/* 859 * catch setup_standard_excludes() that's called before 860 * dir->untracked is assigned. That function behaves 861 * differently when dir->untracked is non-NULL. 862 */ 863if(!dir->untracked) 864 dir->unmanaged_exclude_files++; 865 el =add_exclude_list(dir, EXC_FILE, fname); 866if(add_excludes(fname,"",0, el, NULL, sha1_stat) <0) 867die("cannot use%sas an exclude file", fname); 868} 869 870voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 871{ 872 dir->unmanaged_exclude_files++;/* see validate_untracked_cache() */ 873add_excludes_from_file_1(dir, fname, NULL); 874} 875 876intmatch_basename(const char*basename,int basenamelen, 877const char*pattern,int prefix,int patternlen, 878unsigned flags) 879{ 880if(prefix == patternlen) { 881if(patternlen == basenamelen && 882!fspathncmp(pattern, basename, basenamelen)) 883return1; 884}else if(flags & EXC_FLAG_ENDSWITH) { 885/* "*literal" matching against "fooliteral" */ 886if(patternlen -1<= basenamelen && 887!fspathncmp(pattern +1, 888 basename + basenamelen - (patternlen -1), 889 patternlen -1)) 890return1; 891}else{ 892if(fnmatch_icase_mem(pattern, patternlen, 893 basename, basenamelen, 8940) ==0) 895return1; 896} 897return0; 898} 899 900intmatch_pathname(const char*pathname,int pathlen, 901const char*base,int baselen, 902const char*pattern,int prefix,int patternlen, 903unsigned flags) 904{ 905const char*name; 906int namelen; 907 908/* 909 * match with FNM_PATHNAME; the pattern has base implicitly 910 * in front of it. 911 */ 912if(*pattern =='/') { 913 pattern++; 914 patternlen--; 915 prefix--; 916} 917 918/* 919 * baselen does not count the trailing slash. base[] may or 920 * may not end with a trailing slash though. 921 */ 922if(pathlen < baselen +1|| 923(baselen && pathname[baselen] !='/') || 924fspathncmp(pathname, base, baselen)) 925return0; 926 927 namelen = baselen ? pathlen - baselen -1: pathlen; 928 name = pathname + pathlen - namelen; 929 930if(prefix) { 931/* 932 * if the non-wildcard part is longer than the 933 * remaining pathname, surely it cannot match. 934 */ 935if(prefix > namelen) 936return0; 937 938if(fspathncmp(pattern, name, prefix)) 939return0; 940 pattern += prefix; 941 patternlen -= prefix; 942 name += prefix; 943 namelen -= prefix; 944 945/* 946 * If the whole pattern did not have a wildcard, 947 * then our prefix match is all we need; we 948 * do not need to call fnmatch at all. 949 */ 950if(!patternlen && !namelen) 951return1; 952} 953 954returnfnmatch_icase_mem(pattern, patternlen, 955 name, namelen, 956 WM_PATHNAME) ==0; 957} 958 959/* 960 * Scan the given exclude list in reverse to see whether pathname 961 * should be ignored. The first match (i.e. the last on the list), if 962 * any, determines the fate. Returns the exclude_list element which 963 * matched, or NULL for undecided. 964 */ 965static struct exclude *last_exclude_matching_from_list(const char*pathname, 966int pathlen, 967const char*basename, 968int*dtype, 969struct exclude_list *el, 970struct index_state *istate) 971{ 972struct exclude *exc = NULL;/* undecided */ 973int i; 974 975if(!el->nr) 976return NULL;/* undefined */ 977 978for(i = el->nr -1;0<= i; i--) { 979struct exclude *x = el->excludes[i]; 980const char*exclude = x->pattern; 981int prefix = x->nowildcardlen; 982 983if(x->flags & EXC_FLAG_MUSTBEDIR) { 984if(*dtype == DT_UNKNOWN) 985*dtype =get_dtype(NULL, istate, pathname, pathlen); 986if(*dtype != DT_DIR) 987continue; 988} 989 990if(x->flags & EXC_FLAG_NODIR) { 991if(match_basename(basename, 992 pathlen - (basename - pathname), 993 exclude, prefix, x->patternlen, 994 x->flags)) { 995 exc = x; 996break; 997} 998continue; 999}10001001assert(x->baselen ==0|| x->base[x->baselen -1] =='/');1002if(match_pathname(pathname, pathlen,1003 x->base, x->baselen ? x->baselen -1:0,1004 exclude, prefix, x->patternlen, x->flags)) {1005 exc = x;1006break;1007}1008}1009return exc;1010}10111012/*1013 * Scan the list and let the last match determine the fate.1014 * Return 1 for exclude, 0 for include and -1 for undecided.1015 */1016intis_excluded_from_list(const char*pathname,1017int pathlen,const char*basename,int*dtype,1018struct exclude_list *el,struct index_state *istate)1019{1020struct exclude *exclude;1021 exclude =last_exclude_matching_from_list(pathname, pathlen, basename,1022 dtype, el, istate);1023if(exclude)1024return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1025return-1;/* undecided */1026}10271028static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir,1029struct index_state *istate,1030const char*pathname,int pathlen,const char*basename,1031int*dtype_p)1032{1033int i, j;1034struct exclude_list_group *group;1035struct exclude *exclude;1036for(i = EXC_CMDL; i <= EXC_FILE; i++) {1037 group = &dir->exclude_list_group[i];1038for(j = group->nr -1; j >=0; j--) {1039 exclude =last_exclude_matching_from_list(1040 pathname, pathlen, basename, dtype_p,1041&group->el[j], istate);1042if(exclude)1043return exclude;1044}1045}1046return NULL;1047}10481049/*1050 * Loads the per-directory exclude list for the substring of base1051 * which has a char length of baselen.1052 */1053static voidprep_exclude(struct dir_struct *dir,1054struct index_state *istate,1055const char*base,int baselen)1056{1057struct exclude_list_group *group;1058struct exclude_list *el;1059struct exclude_stack *stk = NULL;1060struct untracked_cache_dir *untracked;1061int current;10621063 group = &dir->exclude_list_group[EXC_DIRS];10641065/*1066 * Pop the exclude lists from the EXCL_DIRS exclude_list_group1067 * which originate from directories not in the prefix of the1068 * path being checked.1069 */1070while((stk = dir->exclude_stack) != NULL) {1071if(stk->baselen <= baselen &&1072!strncmp(dir->basebuf.buf, base, stk->baselen))1073break;1074 el = &group->el[dir->exclude_stack->exclude_ix];1075 dir->exclude_stack = stk->prev;1076 dir->exclude = NULL;1077free((char*)el->src);/* see strbuf_detach() below */1078clear_exclude_list(el);1079free(stk);1080 group->nr--;1081}10821083/* Skip traversing into sub directories if the parent is excluded */1084if(dir->exclude)1085return;10861087/*1088 * Lazy initialization. All call sites currently just1089 * memset(dir, 0, sizeof(*dir)) before use. Changing all of1090 * them seems lots of work for little benefit.1091 */1092if(!dir->basebuf.buf)1093strbuf_init(&dir->basebuf, PATH_MAX);10941095/* Read from the parent directories and push them down. */1096 current = stk ? stk->baselen : -1;1097strbuf_setlen(&dir->basebuf, current <0?0: current);1098if(dir->untracked)1099 untracked = stk ? stk->ucd : dir->untracked->root;1100else1101 untracked = NULL;11021103while(current < baselen) {1104const char*cp;1105struct sha1_stat sha1_stat;11061107 stk =xcalloc(1,sizeof(*stk));1108if(current <0) {1109 cp = base;1110 current =0;1111}else{1112 cp =strchr(base + current +1,'/');1113if(!cp)1114die("oops in prep_exclude");1115 cp++;1116 untracked =1117lookup_untracked(dir->untracked, untracked,1118 base + current,1119 cp - base - current);1120}1121 stk->prev = dir->exclude_stack;1122 stk->baselen = cp - base;1123 stk->exclude_ix = group->nr;1124 stk->ucd = untracked;1125 el =add_exclude_list(dir, EXC_DIRS, NULL);1126strbuf_add(&dir->basebuf, base + current, stk->baselen - current);1127assert(stk->baselen == dir->basebuf.len);11281129/* Abort if the directory is excluded */1130if(stk->baselen) {1131int dt = DT_DIR;1132 dir->basebuf.buf[stk->baselen -1] =0;1133 dir->exclude =last_exclude_matching_from_lists(dir,1134 istate,1135 dir->basebuf.buf, stk->baselen -1,1136 dir->basebuf.buf + current, &dt);1137 dir->basebuf.buf[stk->baselen -1] ='/';1138if(dir->exclude &&1139 dir->exclude->flags & EXC_FLAG_NEGATIVE)1140 dir->exclude = NULL;1141if(dir->exclude) {1142 dir->exclude_stack = stk;1143return;1144}1145}11461147/* Try to read per-directory file */1148hashclr(sha1_stat.sha1);1149 sha1_stat.valid =0;1150if(dir->exclude_per_dir &&1151/*1152 * If we know that no files have been added in1153 * this directory (i.e. valid_cached_dir() has1154 * been executed and set untracked->valid) ..1155 */1156(!untracked || !untracked->valid ||1157/*1158 * .. and .gitignore does not exist before1159 * (i.e. null exclude_sha1). Then we can skip1160 * loading .gitignore, which would result in1161 * ENOENT anyway.1162 */1163!is_null_sha1(untracked->exclude_sha1))) {1164/*1165 * dir->basebuf gets reused by the traversal, but we1166 * need fname to remain unchanged to ensure the src1167 * member of each struct exclude correctly1168 * back-references its source file. Other invocations1169 * of add_exclude_list provide stable strings, so we1170 * strbuf_detach() and free() here in the caller.1171 */1172struct strbuf sb = STRBUF_INIT;1173strbuf_addbuf(&sb, &dir->basebuf);1174strbuf_addstr(&sb, dir->exclude_per_dir);1175 el->src =strbuf_detach(&sb, NULL);1176add_excludes(el->src, el->src, stk->baselen, el, istate,1177 untracked ? &sha1_stat : NULL);1178}1179/*1180 * NEEDSWORK: when untracked cache is enabled, prep_exclude()1181 * will first be called in valid_cached_dir() then maybe many1182 * times more in last_exclude_matching(). When the cache is1183 * used, last_exclude_matching() will not be called and1184 * reading .gitignore content will be a waste.1185 *1186 * So when it's called by valid_cached_dir() and we can get1187 * .gitignore SHA-1 from the index (i.e. .gitignore is not1188 * modified on work tree), we could delay reading the1189 * .gitignore content until we absolutely need it in1190 * last_exclude_matching(). Be careful about ignore rule1191 * order, though, if you do that.1192 */1193if(untracked &&1194hashcmp(sha1_stat.sha1, untracked->exclude_sha1)) {1195invalidate_gitignore(dir->untracked, untracked);1196hashcpy(untracked->exclude_sha1, sha1_stat.sha1);1197}1198 dir->exclude_stack = stk;1199 current = stk->baselen;1200}1201strbuf_setlen(&dir->basebuf, baselen);1202}12031204/*1205 * Loads the exclude lists for the directory containing pathname, then1206 * scans all exclude lists to determine whether pathname is excluded.1207 * Returns the exclude_list element which matched, or NULL for1208 * undecided.1209 */1210struct exclude *last_exclude_matching(struct dir_struct *dir,1211struct index_state *istate,1212const char*pathname,1213int*dtype_p)1214{1215int pathlen =strlen(pathname);1216const char*basename =strrchr(pathname,'/');1217 basename = (basename) ? basename+1: pathname;12181219prep_exclude(dir, istate, pathname, basename-pathname);12201221if(dir->exclude)1222return dir->exclude;12231224returnlast_exclude_matching_from_lists(dir, istate, pathname, pathlen,1225 basename, dtype_p);1226}12271228/*1229 * Loads the exclude lists for the directory containing pathname, then1230 * scans all exclude lists to determine whether pathname is excluded.1231 * Returns 1 if true, otherwise 0.1232 */1233intis_excluded(struct dir_struct *dir,struct index_state *istate,1234const char*pathname,int*dtype_p)1235{1236struct exclude *exclude =1237last_exclude_matching(dir, istate, pathname, dtype_p);1238if(exclude)1239return exclude->flags & EXC_FLAG_NEGATIVE ?0:1;1240return0;1241}12421243static struct dir_entry *dir_entry_new(const char*pathname,int len)1244{1245struct dir_entry *ent;12461247FLEX_ALLOC_MEM(ent, name, pathname, len);1248 ent->len = len;1249return ent;1250}12511252static struct dir_entry *dir_add_name(struct dir_struct *dir,1253struct index_state *istate,1254const char*pathname,int len)1255{1256if(index_file_exists(istate, pathname, len, ignore_case))1257return NULL;12581259ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);1260return dir->entries[dir->nr++] =dir_entry_new(pathname, len);1261}12621263struct dir_entry *dir_add_ignored(struct dir_struct *dir,1264struct index_state *istate,1265const char*pathname,int len)1266{1267if(!index_name_is_other(istate, pathname, len))1268return NULL;12691270ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);1271return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len);1272}12731274enum exist_status {1275 index_nonexistent =0,1276 index_directory,1277 index_gitdir1278};12791280/*1281 * Do not use the alphabetically sorted index to look up1282 * the directory name; instead, use the case insensitive1283 * directory hash.1284 */1285static enum exist_status directory_exists_in_index_icase(struct index_state *istate,1286const char*dirname,int len)1287{1288struct cache_entry *ce;12891290if(index_dir_exists(istate, dirname, len))1291return index_directory;12921293 ce =index_file_exists(istate, dirname, len, ignore_case);1294if(ce &&S_ISGITLINK(ce->ce_mode))1295return index_gitdir;12961297return index_nonexistent;1298}12991300/*1301 * The index sorts alphabetically by entry name, which1302 * means that a gitlink sorts as '\0' at the end, while1303 * a directory (which is defined not as an entry, but as1304 * the files it contains) will sort with the '/' at the1305 * end.1306 */1307static enum exist_status directory_exists_in_index(struct index_state *istate,1308const char*dirname,int len)1309{1310int pos;13111312if(ignore_case)1313returndirectory_exists_in_index_icase(istate, dirname, len);13141315 pos =index_name_pos(istate, dirname, len);1316if(pos <0)1317 pos = -pos-1;1318while(pos < istate->cache_nr) {1319const struct cache_entry *ce = istate->cache[pos++];1320unsigned char endchar;13211322if(strncmp(ce->name, dirname, len))1323break;1324 endchar = ce->name[len];1325if(endchar >'/')1326break;1327if(endchar =='/')1328return index_directory;1329if(!endchar &&S_ISGITLINK(ce->ce_mode))1330return index_gitdir;1331}1332return index_nonexistent;1333}13341335/*1336 * When we find a directory when traversing the filesystem, we1337 * have three distinct cases:1338 *1339 * - ignore it1340 * - see it as a directory1341 * - recurse into it1342 *1343 * and which one we choose depends on a combination of existing1344 * git index contents and the flags passed into the directory1345 * traversal routine.1346 *1347 * Case 1: If we *already* have entries in the index under that1348 * directory name, we always recurse into the directory to see1349 * all the files.1350 *1351 * Case 2: If we *already* have that directory name as a gitlink,1352 * we always continue to see it as a gitlink, regardless of whether1353 * there is an actual git directory there or not (it might not1354 * be checked out as a subproject!)1355 *1356 * Case 3: if we didn't have it in the index previously, we1357 * have a few sub-cases:1358 *1359 * (a) if "show_other_directories" is true, we show it as1360 * just a directory, unless "hide_empty_directories" is1361 * also true, in which case we need to check if it contains any1362 * untracked and / or ignored files.1363 * (b) if it looks like a git directory, and we don't have1364 * 'no_gitlinks' set we treat it as a gitlink, and show it1365 * as a directory.1366 * (c) otherwise, we recurse into it.1367 */1368static enum path_treatment treat_directory(struct dir_struct *dir,1369struct index_state *istate,1370struct untracked_cache_dir *untracked,1371const char*dirname,int len,int baselen,int exclude,1372const struct pathspec *pathspec)1373{1374/* The "len-1" is to strip the final '/' */1375switch(directory_exists_in_index(istate, dirname, len-1)) {1376case index_directory:1377return path_recurse;13781379case index_gitdir:1380return path_none;13811382case index_nonexistent:1383if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1384break;1385if(!(dir->flags & DIR_NO_GITLINKS)) {1386unsigned char sha1[20];1387if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1388return path_untracked;1389}1390return path_recurse;1391}13921393/* This is the "show_other_directories" case */13941395if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1396return exclude ? path_excluded : path_untracked;13971398 untracked =lookup_untracked(dir->untracked, untracked,1399 dirname + baselen, len - baselen);1400returnread_directory_recursive(dir, istate, dirname, len,1401 untracked,1, pathspec);1402}14031404/*1405 * This is an inexact early pruning of any recursive directory1406 * reading - if the path cannot possibly be in the pathspec,1407 * return true, and we'll skip it early.1408 */1409static intsimplify_away(const char*path,int pathlen,1410const struct pathspec *pathspec)1411{1412int i;14131414if(!pathspec || !pathspec->nr)1415return0;14161417GUARD_PATHSPEC(pathspec,1418 PATHSPEC_FROMTOP |1419 PATHSPEC_MAXDEPTH |1420 PATHSPEC_LITERAL |1421 PATHSPEC_GLOB |1422 PATHSPEC_ICASE |1423 PATHSPEC_EXCLUDE |1424 PATHSPEC_ATTR);14251426for(i =0; i < pathspec->nr; i++) {1427const struct pathspec_item *item = &pathspec->items[i];1428int len = item->nowildcard_len;14291430if(len > pathlen)1431 len = pathlen;1432if(!ps_strncmp(item, item->match, path, len))1433return0;1434}14351436return1;1437}14381439/*1440 * This function tells us whether an excluded path matches a1441 * list of "interesting" pathspecs. That is, whether a path matched1442 * by any of the pathspecs could possibly be ignored by excluding1443 * the specified path. This can happen if:1444 *1445 * 1. the path is mentioned explicitly in the pathspec1446 *1447 * 2. the path is a directory prefix of some element in the1448 * pathspec1449 */1450static intexclude_matches_pathspec(const char*path,int pathlen,1451const struct pathspec *pathspec)1452{1453int i;14541455if(!pathspec || !pathspec->nr)1456return0;14571458GUARD_PATHSPEC(pathspec,1459 PATHSPEC_FROMTOP |1460 PATHSPEC_MAXDEPTH |1461 PATHSPEC_LITERAL |1462 PATHSPEC_GLOB |1463 PATHSPEC_ICASE |1464 PATHSPEC_EXCLUDE);14651466for(i =0; i < pathspec->nr; i++) {1467const struct pathspec_item *item = &pathspec->items[i];1468int len = item->nowildcard_len;14691470if(len == pathlen &&1471!ps_strncmp(item, item->match, path, pathlen))1472return1;1473if(len > pathlen &&1474 item->match[pathlen] =='/'&&1475!ps_strncmp(item, item->match, path, pathlen))1476return1;1477}1478return0;1479}14801481static intget_index_dtype(struct index_state *istate,1482const char*path,int len)1483{1484int pos;1485const struct cache_entry *ce;14861487 ce =index_file_exists(istate, path, len,0);1488if(ce) {1489if(!ce_uptodate(ce))1490return DT_UNKNOWN;1491if(S_ISGITLINK(ce->ce_mode))1492return DT_DIR;1493/*1494 * Nobody actually cares about the1495 * difference between DT_LNK and DT_REG1496 */1497return DT_REG;1498}14991500/* Try to look it up as a directory */1501 pos =index_name_pos(istate, path, len);1502if(pos >=0)1503return DT_UNKNOWN;1504 pos = -pos-1;1505while(pos < istate->cache_nr) {1506 ce = istate->cache[pos++];1507if(strncmp(ce->name, path, len))1508break;1509if(ce->name[len] >'/')1510break;1511if(ce->name[len] <'/')1512continue;1513if(!ce_uptodate(ce))1514break;/* continue? */1515return DT_DIR;1516}1517return DT_UNKNOWN;1518}15191520static intget_dtype(struct dirent *de,struct index_state *istate,1521const char*path,int len)1522{1523int dtype = de ?DTYPE(de) : DT_UNKNOWN;1524struct stat st;15251526if(dtype != DT_UNKNOWN)1527return dtype;1528 dtype =get_index_dtype(istate, path, len);1529if(dtype != DT_UNKNOWN)1530return dtype;1531if(lstat(path, &st))1532return dtype;1533if(S_ISREG(st.st_mode))1534return DT_REG;1535if(S_ISDIR(st.st_mode))1536return DT_DIR;1537if(S_ISLNK(st.st_mode))1538return DT_LNK;1539return dtype;1540}15411542static enum path_treatment treat_one_path(struct dir_struct *dir,1543struct untracked_cache_dir *untracked,1544struct index_state *istate,1545struct strbuf *path,1546int baselen,1547const struct pathspec *pathspec,1548int dtype,struct dirent *de)1549{1550int exclude;1551int has_path_in_index = !!index_file_exists(istate, path->buf, path->len, ignore_case);15521553if(dtype == DT_UNKNOWN)1554 dtype =get_dtype(de, istate, path->buf, path->len);15551556/* Always exclude indexed files */1557if(dtype != DT_DIR && has_path_in_index)1558return path_none;15591560/*1561 * When we are looking at a directory P in the working tree,1562 * there are three cases:1563 *1564 * (1) P exists in the index. Everything inside the directory P in1565 * the working tree needs to go when P is checked out from the1566 * index.1567 *1568 * (2) P does not exist in the index, but there is P/Q in the index.1569 * We know P will stay a directory when we check out the contents1570 * of the index, but we do not know yet if there is a directory1571 * P/Q in the working tree to be killed, so we need to recurse.1572 *1573 * (3) P does not exist in the index, and there is no P/Q in the index1574 * to require P to be a directory, either. Only in this case, we1575 * know that everything inside P will not be killed without1576 * recursing.1577 */1578if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1579(dtype == DT_DIR) &&1580!has_path_in_index &&1581(directory_exists_in_index(istate, path->buf, path->len) == index_nonexistent))1582return path_none;15831584 exclude =is_excluded(dir, istate, path->buf, &dtype);15851586/*1587 * Excluded? If we don't explicitly want to show1588 * ignored files, ignore it1589 */1590if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1591return path_excluded;15921593switch(dtype) {1594default:1595return path_none;1596case DT_DIR:1597strbuf_addch(path,'/');1598returntreat_directory(dir, istate, untracked, path->buf, path->len,1599 baselen, exclude, pathspec);1600case DT_REG:1601case DT_LNK:1602return exclude ? path_excluded : path_untracked;1603}1604}16051606static enum path_treatment treat_path_fast(struct dir_struct *dir,1607struct untracked_cache_dir *untracked,1608struct cached_dir *cdir,1609struct index_state *istate,1610struct strbuf *path,1611int baselen,1612const struct pathspec *pathspec)1613{1614strbuf_setlen(path, baselen);1615if(!cdir->ucd) {1616strbuf_addstr(path, cdir->file);1617return path_untracked;1618}1619strbuf_addstr(path, cdir->ucd->name);1620/* treat_one_path() does this before it calls treat_directory() */1621strbuf_complete(path,'/');1622if(cdir->ucd->check_only)1623/*1624 * check_only is set as a result of treat_directory() getting1625 * to its bottom. Verify again the same set of directories1626 * with check_only set.1627 */1628returnread_directory_recursive(dir, istate, path->buf, path->len,1629 cdir->ucd,1, pathspec);1630/*1631 * We get path_recurse in the first run when1632 * directory_exists_in_index() returns index_nonexistent. We1633 * are sure that new changes in the index does not impact the1634 * outcome. Return now.1635 */1636return path_recurse;1637}16381639static enum path_treatment treat_path(struct dir_struct *dir,1640struct untracked_cache_dir *untracked,1641struct cached_dir *cdir,1642struct index_state *istate,1643struct strbuf *path,1644int baselen,1645const struct pathspec *pathspec)1646{1647int dtype;1648struct dirent *de = cdir->de;16491650if(!de)1651returntreat_path_fast(dir, untracked, cdir, istate, path,1652 baselen, pathspec);1653if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1654return path_none;1655strbuf_setlen(path, baselen);1656strbuf_addstr(path, de->d_name);1657if(simplify_away(path->buf, path->len, pathspec))1658return path_none;16591660 dtype =DTYPE(de);1661returntreat_one_path(dir, untracked, istate, path, baselen, pathspec, dtype, de);1662}16631664static voidadd_untracked(struct untracked_cache_dir *dir,const char*name)1665{1666if(!dir)1667return;1668ALLOC_GROW(dir->untracked, dir->untracked_nr +1,1669 dir->untracked_alloc);1670 dir->untracked[dir->untracked_nr++] =xstrdup(name);1671}16721673static intvalid_cached_dir(struct dir_struct *dir,1674struct untracked_cache_dir *untracked,1675struct index_state *istate,1676struct strbuf *path,1677int check_only)1678{1679struct stat st;16801681if(!untracked)1682return0;16831684if(stat(path->len ? path->buf :".", &st)) {1685invalidate_directory(dir->untracked, untracked);1686memset(&untracked->stat_data,0,sizeof(untracked->stat_data));1687return0;1688}1689if(!untracked->valid ||1690match_stat_data_racy(istate, &untracked->stat_data, &st)) {1691if(untracked->valid)1692invalidate_directory(dir->untracked, untracked);1693fill_stat_data(&untracked->stat_data, &st);1694return0;1695}16961697if(untracked->check_only != !!check_only) {1698invalidate_directory(dir->untracked, untracked);1699return0;1700}17011702/*1703 * prep_exclude will be called eventually on this directory,1704 * but it's called much later in last_exclude_matching(). We1705 * need it now to determine the validity of the cache for this1706 * path. The next calls will be nearly no-op, the way1707 * prep_exclude() is designed.1708 */1709if(path->len && path->buf[path->len -1] !='/') {1710strbuf_addch(path,'/');1711prep_exclude(dir, istate, path->buf, path->len);1712strbuf_setlen(path, path->len -1);1713}else1714prep_exclude(dir, istate, path->buf, path->len);17151716/* hopefully prep_exclude() haven't invalidated this entry... */1717return untracked->valid;1718}17191720static intopen_cached_dir(struct cached_dir *cdir,1721struct dir_struct *dir,1722struct untracked_cache_dir *untracked,1723struct index_state *istate,1724struct strbuf *path,1725int check_only)1726{1727memset(cdir,0,sizeof(*cdir));1728 cdir->untracked = untracked;1729if(valid_cached_dir(dir, untracked, istate, path, check_only))1730return0;1731 cdir->fdir =opendir(path->len ? path->buf :".");1732if(dir->untracked)1733 dir->untracked->dir_opened++;1734if(!cdir->fdir)1735return-1;1736return0;1737}17381739static intread_cached_dir(struct cached_dir *cdir)1740{1741if(cdir->fdir) {1742 cdir->de =readdir(cdir->fdir);1743if(!cdir->de)1744return-1;1745return0;1746}1747while(cdir->nr_dirs < cdir->untracked->dirs_nr) {1748struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];1749if(!d->recurse) {1750 cdir->nr_dirs++;1751continue;1752}1753 cdir->ucd = d;1754 cdir->nr_dirs++;1755return0;1756}1757 cdir->ucd = NULL;1758if(cdir->nr_files < cdir->untracked->untracked_nr) {1759struct untracked_cache_dir *d = cdir->untracked;1760 cdir->file = d->untracked[cdir->nr_files++];1761return0;1762}1763return-1;1764}17651766static voidclose_cached_dir(struct cached_dir *cdir)1767{1768if(cdir->fdir)1769closedir(cdir->fdir);1770/*1771 * We have gone through this directory and found no untracked1772 * entries. Mark it valid.1773 */1774if(cdir->untracked) {1775 cdir->untracked->valid =1;1776 cdir->untracked->recurse =1;1777}1778}17791780/*1781 * Read a directory tree. We currently ignore anything but1782 * directories, regular files and symlinks. That's because git1783 * doesn't handle them at all yet. Maybe that will change some1784 * day.1785 *1786 * Also, we ignore the name ".git" (even if it is not a directory).1787 * That likely will not change.1788 *1789 * Returns the most significant path_treatment value encountered in the scan.1790 */1791static enum path_treatment read_directory_recursive(struct dir_struct *dir,1792struct index_state *istate,const char*base,int baselen,1793struct untracked_cache_dir *untracked,int check_only,1794const struct pathspec *pathspec)1795{1796struct cached_dir cdir;1797enum path_treatment state, subdir_state, dir_state = path_none;1798struct strbuf path = STRBUF_INIT;17991800strbuf_add(&path, base, baselen);18011802if(open_cached_dir(&cdir, dir, untracked, istate, &path, check_only))1803goto out;18041805if(untracked)1806 untracked->check_only = !!check_only;18071808while(!read_cached_dir(&cdir)) {1809/* check how the file or directory should be treated */1810 state =treat_path(dir, untracked, &cdir, istate, &path,1811 baselen, pathspec);18121813if(state > dir_state)1814 dir_state = state;18151816/* recurse into subdir if instructed by treat_path */1817if((state == path_recurse) ||1818((state == path_untracked) &&1819(dir->flags & DIR_SHOW_IGNORED_TOO) &&1820(get_dtype(cdir.de, istate, path.buf, path.len) == DT_DIR))) {1821struct untracked_cache_dir *ud;1822 ud =lookup_untracked(dir->untracked, untracked,1823 path.buf + baselen,1824 path.len - baselen);1825 subdir_state =1826read_directory_recursive(dir, istate, path.buf,1827 path.len, ud,1828 check_only, pathspec);1829if(subdir_state > dir_state)1830 dir_state = subdir_state;1831}18321833if(check_only) {1834/* abort early if maximum state has been reached */1835if(dir_state == path_untracked) {1836if(cdir.fdir)1837add_untracked(untracked, path.buf + baselen);1838break;1839}1840/* skip the dir_add_* part */1841continue;1842}18431844/* add the path to the appropriate result list */1845switch(state) {1846case path_excluded:1847if(dir->flags & DIR_SHOW_IGNORED)1848dir_add_name(dir, istate, path.buf, path.len);1849else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1850((dir->flags & DIR_COLLECT_IGNORED) &&1851exclude_matches_pathspec(path.buf, path.len,1852 pathspec)))1853dir_add_ignored(dir, istate, path.buf, path.len);1854break;18551856case path_untracked:1857if(dir->flags & DIR_SHOW_IGNORED)1858break;1859dir_add_name(dir, istate, path.buf, path.len);1860if(cdir.fdir)1861add_untracked(untracked, path.buf + baselen);1862break;18631864default:1865break;1866}1867}1868close_cached_dir(&cdir);1869 out:1870strbuf_release(&path);18711872return dir_state;1873}18741875intcmp_dir_entry(const void*p1,const void*p2)1876{1877const struct dir_entry *e1 = *(const struct dir_entry **)p1;1878const struct dir_entry *e2 = *(const struct dir_entry **)p2;18791880returnname_compare(e1->name, e1->len, e2->name, e2->len);1881}18821883/* check if *out lexically strictly contains *in */1884intcheck_dir_entry_contains(const struct dir_entry *out,const struct dir_entry *in)1885{1886return(out->len < in->len) &&1887(out->name[out->len -1] =='/') &&1888!memcmp(out->name, in->name, out->len);1889}18901891static inttreat_leading_path(struct dir_struct *dir,1892struct index_state *istate,1893const char*path,int len,1894const struct pathspec *pathspec)1895{1896struct strbuf sb = STRBUF_INIT;1897int baselen, rc =0;1898const char*cp;1899int old_flags = dir->flags;19001901while(len && path[len -1] =='/')1902 len--;1903if(!len)1904return1;1905 baselen =0;1906 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1907while(1) {1908 cp = path + baselen + !!baselen;1909 cp =memchr(cp,'/', path + len - cp);1910if(!cp)1911 baselen = len;1912else1913 baselen = cp - path;1914strbuf_setlen(&sb,0);1915strbuf_add(&sb, path, baselen);1916if(!is_directory(sb.buf))1917break;1918if(simplify_away(sb.buf, sb.len, pathspec))1919break;1920if(treat_one_path(dir, NULL, istate, &sb, baselen, pathspec,1921 DT_DIR, NULL) == path_none)1922break;/* do not recurse into it */1923if(len <= baselen) {1924 rc =1;1925break;/* finished checking */1926}1927}1928strbuf_release(&sb);1929 dir->flags = old_flags;1930return rc;1931}19321933static const char*get_ident_string(void)1934{1935static struct strbuf sb = STRBUF_INIT;1936struct utsname uts;19371938if(sb.len)1939return sb.buf;1940if(uname(&uts) <0)1941die_errno(_("failed to get kernel name and information"));1942strbuf_addf(&sb,"Location%s, system%s",get_git_work_tree(),1943 uts.sysname);1944return sb.buf;1945}19461947static intident_in_untracked(const struct untracked_cache *uc)1948{1949/*1950 * Previous git versions may have saved many NUL separated1951 * strings in the "ident" field, but it is insane to manage1952 * many locations, so just take care of the first one.1953 */19541955return!strcmp(uc->ident.buf,get_ident_string());1956}19571958static voidset_untracked_ident(struct untracked_cache *uc)1959{1960strbuf_reset(&uc->ident);1961strbuf_addstr(&uc->ident,get_ident_string());19621963/*1964 * This strbuf used to contain a list of NUL separated1965 * strings, so save NUL too for backward compatibility.1966 */1967strbuf_addch(&uc->ident,0);1968}19691970static voidnew_untracked_cache(struct index_state *istate)1971{1972struct untracked_cache *uc =xcalloc(1,sizeof(*uc));1973strbuf_init(&uc->ident,100);1974 uc->exclude_per_dir =".gitignore";1975/* should be the same flags used by git-status */1976 uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;1977set_untracked_ident(uc);1978 istate->untracked = uc;1979 istate->cache_changed |= UNTRACKED_CHANGED;1980}19811982voidadd_untracked_cache(struct index_state *istate)1983{1984if(!istate->untracked) {1985new_untracked_cache(istate);1986}else{1987if(!ident_in_untracked(istate->untracked)) {1988free_untracked_cache(istate->untracked);1989new_untracked_cache(istate);1990}1991}1992}19931994voidremove_untracked_cache(struct index_state *istate)1995{1996if(istate->untracked) {1997free_untracked_cache(istate->untracked);1998 istate->untracked = NULL;1999 istate->cache_changed |= UNTRACKED_CHANGED;2000}2001}20022003static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,2004int base_len,2005const struct pathspec *pathspec)2006{2007struct untracked_cache_dir *root;20082009if(!dir->untracked ||getenv("GIT_DISABLE_UNTRACKED_CACHE"))2010return NULL;20112012/*2013 * We only support $GIT_DIR/info/exclude and core.excludesfile2014 * as the global ignore rule files. Any other additions2015 * (e.g. from command line) invalidate the cache. This2016 * condition also catches running setup_standard_excludes()2017 * before setting dir->untracked!2018 */2019if(dir->unmanaged_exclude_files)2020return NULL;20212022/*2023 * Optimize for the main use case only: whole-tree git2024 * status. More work involved in treat_leading_path() if we2025 * use cache on just a subset of the worktree. pathspec2026 * support could make the matter even worse.2027 */2028if(base_len || (pathspec && pathspec->nr))2029return NULL;20302031/* Different set of flags may produce different results */2032if(dir->flags != dir->untracked->dir_flags ||2033/*2034 * See treat_directory(), case index_nonexistent. Without2035 * this flag, we may need to also cache .git file content2036 * for the resolve_gitlink_ref() call, which we don't.2037 */2038!(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||2039/* We don't support collecting ignore files */2040(dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |2041 DIR_COLLECT_IGNORED)))2042return NULL;20432044/*2045 * If we use .gitignore in the cache and now you change it to2046 * .gitexclude, everything will go wrong.2047 */2048if(dir->exclude_per_dir != dir->untracked->exclude_per_dir &&2049strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))2050return NULL;20512052/*2053 * EXC_CMDL is not considered in the cache. If people set it,2054 * skip the cache.2055 */2056if(dir->exclude_list_group[EXC_CMDL].nr)2057return NULL;20582059if(!ident_in_untracked(dir->untracked)) {2060warning(_("Untracked cache is disabled on this system or location."));2061return NULL;2062}20632064if(!dir->untracked->root) {2065const int len =sizeof(*dir->untracked->root);2066 dir->untracked->root =xmalloc(len);2067memset(dir->untracked->root,0, len);2068}20692070/* Validate $GIT_DIR/info/exclude and core.excludesfile */2071 root = dir->untracked->root;2072if(hashcmp(dir->ss_info_exclude.sha1,2073 dir->untracked->ss_info_exclude.sha1)) {2074invalidate_gitignore(dir->untracked, root);2075 dir->untracked->ss_info_exclude = dir->ss_info_exclude;2076}2077if(hashcmp(dir->ss_excludes_file.sha1,2078 dir->untracked->ss_excludes_file.sha1)) {2079invalidate_gitignore(dir->untracked, root);2080 dir->untracked->ss_excludes_file = dir->ss_excludes_file;2081}20822083/* Make sure this directory is not dropped out at saving phase */2084 root->recurse =1;2085return root;2086}20872088intread_directory(struct dir_struct *dir,struct index_state *istate,2089const char*path,int len,const struct pathspec *pathspec)2090{2091struct untracked_cache_dir *untracked;20922093if(has_symlink_leading_path(path, len))2094return dir->nr;20952096 untracked =validate_untracked_cache(dir, len, pathspec);2097if(!untracked)2098/*2099 * make sure untracked cache code path is disabled,2100 * e.g. prep_exclude()2101 */2102 dir->untracked = NULL;2103if(!len ||treat_leading_path(dir, istate, path, len, pathspec))2104read_directory_recursive(dir, istate, path, len, untracked,0, pathspec);2105QSORT(dir->entries, dir->nr, cmp_dir_entry);2106QSORT(dir->ignored, dir->ignored_nr, cmp_dir_entry);21072108/*2109 * If DIR_SHOW_IGNORED_TOO is set, read_directory_recursive() will2110 * also pick up untracked contents of untracked dirs; by default2111 * we discard these, but given DIR_KEEP_UNTRACKED_CONTENTS we do not.2112 */2113if((dir->flags & DIR_SHOW_IGNORED_TOO) &&2114!(dir->flags & DIR_KEEP_UNTRACKED_CONTENTS)) {2115int i, j;21162117/* remove from dir->entries untracked contents of untracked dirs */2118for(i = j =0; j < dir->nr; j++) {2119if(i &&2120check_dir_entry_contains(dir->entries[i -1], dir->entries[j])) {2121free(dir->entries[j]);2122 dir->entries[j] = NULL;2123}else{2124 dir->entries[i++] = dir->entries[j];2125}2126}21272128 dir->nr = i;2129}21302131if(dir->untracked) {2132static struct trace_key trace_untracked_stats =TRACE_KEY_INIT(UNTRACKED_STATS);2133trace_printf_key(&trace_untracked_stats,2134"node creation:%u\n"2135"gitignore invalidation:%u\n"2136"directory invalidation:%u\n"2137"opendir:%u\n",2138 dir->untracked->dir_created,2139 dir->untracked->gitignore_invalidated,2140 dir->untracked->dir_invalidated,2141 dir->untracked->dir_opened);2142if(dir->untracked == istate->untracked &&2143(dir->untracked->dir_opened ||2144 dir->untracked->gitignore_invalidated ||2145 dir->untracked->dir_invalidated))2146 istate->cache_changed |= UNTRACKED_CHANGED;2147if(dir->untracked != istate->untracked) {2148free(dir->untracked);2149 dir->untracked = NULL;2150}2151}2152return dir->nr;2153}21542155intfile_exists(const char*f)2156{2157struct stat sb;2158returnlstat(f, &sb) ==0;2159}21602161static intcmp_icase(char a,char b)2162{2163if(a == b)2164return0;2165if(ignore_case)2166returntoupper(a) -toupper(b);2167return a - b;2168}21692170/*2171 * Given two normalized paths (a trailing slash is ok), if subdir is2172 * outside dir, return -1. Otherwise return the offset in subdir that2173 * can be used as relative path to dir.2174 */2175intdir_inside_of(const char*subdir,const char*dir)2176{2177int offset =0;21782179assert(dir && subdir && *dir && *subdir);21802181while(*dir && *subdir && !cmp_icase(*dir, *subdir)) {2182 dir++;2183 subdir++;2184 offset++;2185}21862187/* hel[p]/me vs hel[l]/yeah */2188if(*dir && *subdir)2189return-1;21902191if(!*subdir)2192return!*dir ? offset : -1;/* same dir */21932194/* foo/[b]ar vs foo/[] */2195if(is_dir_sep(dir[-1]))2196returnis_dir_sep(subdir[-1]) ? offset : -1;21972198/* foo[/]bar vs foo[] */2199returnis_dir_sep(*subdir) ? offset +1: -1;2200}22012202intis_inside_dir(const char*dir)2203{2204char*cwd;2205int rc;22062207if(!dir)2208return0;22092210 cwd =xgetcwd();2211 rc = (dir_inside_of(cwd, dir) >=0);2212free(cwd);2213return rc;2214}22152216intis_empty_dir(const char*path)2217{2218DIR*dir =opendir(path);2219struct dirent *e;2220int ret =1;22212222if(!dir)2223return0;22242225while((e =readdir(dir)) != NULL)2226if(!is_dot_or_dotdot(e->d_name)) {2227 ret =0;2228break;2229}22302231closedir(dir);2232return ret;2233}22342235static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)2236{2237DIR*dir;2238struct dirent *e;2239int ret =0, original_len = path->len, len, kept_down =0;2240int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);2241int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);2242unsigned char submodule_head[20];22432244if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&2245!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {2246/* Do not descend and nuke a nested git work tree. */2247if(kept_up)2248*kept_up =1;2249return0;2250}22512252 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;2253 dir =opendir(path->buf);2254if(!dir) {2255if(errno == ENOENT)2256return keep_toplevel ? -1:0;2257else if(errno == EACCES && !keep_toplevel)2258/*2259 * An empty dir could be removable even if it2260 * is unreadable:2261 */2262returnrmdir(path->buf);2263else2264return-1;2265}2266strbuf_complete(path,'/');22672268 len = path->len;2269while((e =readdir(dir)) != NULL) {2270struct stat st;2271if(is_dot_or_dotdot(e->d_name))2272continue;22732274strbuf_setlen(path, len);2275strbuf_addstr(path, e->d_name);2276if(lstat(path->buf, &st)) {2277if(errno == ENOENT)2278/*2279 * file disappeared, which is what we2280 * wanted anyway2281 */2282continue;2283/* fall thru */2284}else if(S_ISDIR(st.st_mode)) {2285if(!remove_dir_recurse(path, flag, &kept_down))2286continue;/* happy */2287}else if(!only_empty &&2288(!unlink(path->buf) || errno == ENOENT)) {2289continue;/* happy, too */2290}22912292/* path too long, stat fails, or non-directory still exists */2293 ret = -1;2294break;2295}2296closedir(dir);22972298strbuf_setlen(path, original_len);2299if(!ret && !keep_toplevel && !kept_down)2300 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;2301else if(kept_up)2302/*2303 * report the uplevel that it is not an error that we2304 * did not rmdir() our directory.2305 */2306*kept_up = !ret;2307return ret;2308}23092310intremove_dir_recursively(struct strbuf *path,int flag)2311{2312returnremove_dir_recurse(path, flag, NULL);2313}23142315staticGIT_PATH_FUNC(git_path_info_exclude,"info/exclude")23162317voidsetup_standard_excludes(struct dir_struct *dir)2318{2319 dir->exclude_per_dir =".gitignore";23202321/* core.excludefile defaulting to $XDG_HOME/git/ignore */2322if(!excludes_file)2323 excludes_file =xdg_config_home("ignore");2324if(excludes_file && !access_or_warn(excludes_file, R_OK,0))2325add_excludes_from_file_1(dir, excludes_file,2326 dir->untracked ? &dir->ss_excludes_file : NULL);23272328/* per repository user preference */2329if(startup_info->have_repository) {2330const char*path =git_path_info_exclude();2331if(!access_or_warn(path, R_OK,0))2332add_excludes_from_file_1(dir, path,2333 dir->untracked ? &dir->ss_info_exclude : NULL);2334}2335}23362337intremove_path(const char*name)2338{2339char*slash;23402341if(unlink(name) && !is_missing_file_error(errno))2342return-1;23432344 slash =strrchr(name,'/');2345if(slash) {2346char*dirs =xstrdup(name);2347 slash = dirs + (slash - name);2348do{2349*slash ='\0';2350}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));2351free(dirs);2352}2353return0;2354}23552356/*2357 * Frees memory within dir which was allocated for exclude lists and2358 * the exclude_stack. Does not free dir itself.2359 */2360voidclear_directory(struct dir_struct *dir)2361{2362int i, j;2363struct exclude_list_group *group;2364struct exclude_list *el;2365struct exclude_stack *stk;23662367for(i = EXC_CMDL; i <= EXC_FILE; i++) {2368 group = &dir->exclude_list_group[i];2369for(j =0; j < group->nr; j++) {2370 el = &group->el[j];2371if(i == EXC_DIRS)2372free((char*)el->src);2373clear_exclude_list(el);2374}2375free(group->el);2376}23772378 stk = dir->exclude_stack;2379while(stk) {2380struct exclude_stack *prev = stk->prev;2381free(stk);2382 stk = prev;2383}2384strbuf_release(&dir->basebuf);2385}23862387struct ondisk_untracked_cache {2388struct stat_data info_exclude_stat;2389struct stat_data excludes_file_stat;2390uint32_t dir_flags;2391unsigned char info_exclude_sha1[20];2392unsigned char excludes_file_sha1[20];2393char exclude_per_dir[FLEX_ARRAY];2394};23952396#define ouc_size(len) (offsetof(struct ondisk_untracked_cache, exclude_per_dir) + len + 1)23972398struct write_data {2399int index;/* number of written untracked_cache_dir */2400struct ewah_bitmap *check_only;/* from untracked_cache_dir */2401struct ewah_bitmap *valid;/* from untracked_cache_dir */2402struct ewah_bitmap *sha1_valid;/* set if exclude_sha1 is not null */2403struct strbuf out;2404struct strbuf sb_stat;2405struct strbuf sb_sha1;2406};24072408static voidstat_data_to_disk(struct stat_data *to,const struct stat_data *from)2409{2410 to->sd_ctime.sec =htonl(from->sd_ctime.sec);2411 to->sd_ctime.nsec =htonl(from->sd_ctime.nsec);2412 to->sd_mtime.sec =htonl(from->sd_mtime.sec);2413 to->sd_mtime.nsec =htonl(from->sd_mtime.nsec);2414 to->sd_dev =htonl(from->sd_dev);2415 to->sd_ino =htonl(from->sd_ino);2416 to->sd_uid =htonl(from->sd_uid);2417 to->sd_gid =htonl(from->sd_gid);2418 to->sd_size =htonl(from->sd_size);2419}24202421static voidwrite_one_dir(struct untracked_cache_dir *untracked,2422struct write_data *wd)2423{2424struct stat_data stat_data;2425struct strbuf *out = &wd->out;2426unsigned char intbuf[16];2427unsigned int intlen, value;2428int i = wd->index++;24292430/*2431 * untracked_nr should be reset whenever valid is clear, but2432 * for safety..2433 */2434if(!untracked->valid) {2435 untracked->untracked_nr =0;2436 untracked->check_only =0;2437}24382439if(untracked->check_only)2440ewah_set(wd->check_only, i);2441if(untracked->valid) {2442ewah_set(wd->valid, i);2443stat_data_to_disk(&stat_data, &untracked->stat_data);2444strbuf_add(&wd->sb_stat, &stat_data,sizeof(stat_data));2445}2446if(!is_null_sha1(untracked->exclude_sha1)) {2447ewah_set(wd->sha1_valid, i);2448strbuf_add(&wd->sb_sha1, untracked->exclude_sha1,20);2449}24502451 intlen =encode_varint(untracked->untracked_nr, intbuf);2452strbuf_add(out, intbuf, intlen);24532454/* skip non-recurse directories */2455for(i =0, value =0; i < untracked->dirs_nr; i++)2456if(untracked->dirs[i]->recurse)2457 value++;2458 intlen =encode_varint(value, intbuf);2459strbuf_add(out, intbuf, intlen);24602461strbuf_add(out, untracked->name,strlen(untracked->name) +1);24622463for(i =0; i < untracked->untracked_nr; i++)2464strbuf_add(out, untracked->untracked[i],2465strlen(untracked->untracked[i]) +1);24662467for(i =0; i < untracked->dirs_nr; i++)2468if(untracked->dirs[i]->recurse)2469write_one_dir(untracked->dirs[i], wd);2470}24712472voidwrite_untracked_extension(struct strbuf *out,struct untracked_cache *untracked)2473{2474struct ondisk_untracked_cache *ouc;2475struct write_data wd;2476unsigned char varbuf[16];2477int varint_len;2478size_t len =strlen(untracked->exclude_per_dir);24792480FLEX_ALLOC_MEM(ouc, exclude_per_dir, untracked->exclude_per_dir, len);2481stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);2482stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);2483hashcpy(ouc->info_exclude_sha1, untracked->ss_info_exclude.sha1);2484hashcpy(ouc->excludes_file_sha1, untracked->ss_excludes_file.sha1);2485 ouc->dir_flags =htonl(untracked->dir_flags);24862487 varint_len =encode_varint(untracked->ident.len, varbuf);2488strbuf_add(out, varbuf, varint_len);2489strbuf_addbuf(out, &untracked->ident);24902491strbuf_add(out, ouc,ouc_size(len));2492free(ouc);2493 ouc = NULL;24942495if(!untracked->root) {2496 varint_len =encode_varint(0, varbuf);2497strbuf_add(out, varbuf, varint_len);2498return;2499}25002501 wd.index =0;2502 wd.check_only =ewah_new();2503 wd.valid =ewah_new();2504 wd.sha1_valid =ewah_new();2505strbuf_init(&wd.out,1024);2506strbuf_init(&wd.sb_stat,1024);2507strbuf_init(&wd.sb_sha1,1024);2508write_one_dir(untracked->root, &wd);25092510 varint_len =encode_varint(wd.index, varbuf);2511strbuf_add(out, varbuf, varint_len);2512strbuf_addbuf(out, &wd.out);2513ewah_serialize_strbuf(wd.valid, out);2514ewah_serialize_strbuf(wd.check_only, out);2515ewah_serialize_strbuf(wd.sha1_valid, out);2516strbuf_addbuf(out, &wd.sb_stat);2517strbuf_addbuf(out, &wd.sb_sha1);2518strbuf_addch(out,'\0');/* safe guard for string lists */25192520ewah_free(wd.valid);2521ewah_free(wd.check_only);2522ewah_free(wd.sha1_valid);2523strbuf_release(&wd.out);2524strbuf_release(&wd.sb_stat);2525strbuf_release(&wd.sb_sha1);2526}25272528static voidfree_untracked(struct untracked_cache_dir *ucd)2529{2530int i;2531if(!ucd)2532return;2533for(i =0; i < ucd->dirs_nr; i++)2534free_untracked(ucd->dirs[i]);2535for(i =0; i < ucd->untracked_nr; i++)2536free(ucd->untracked[i]);2537free(ucd->untracked);2538free(ucd->dirs);2539free(ucd);2540}25412542voidfree_untracked_cache(struct untracked_cache *uc)2543{2544if(uc)2545free_untracked(uc->root);2546free(uc);2547}25482549struct read_data {2550int index;2551struct untracked_cache_dir **ucd;2552struct ewah_bitmap *check_only;2553struct ewah_bitmap *valid;2554struct ewah_bitmap *sha1_valid;2555const unsigned char*data;2556const unsigned char*end;2557};25582559static voidstat_data_from_disk(struct stat_data *to,const struct stat_data *from)2560{2561 to->sd_ctime.sec =get_be32(&from->sd_ctime.sec);2562 to->sd_ctime.nsec =get_be32(&from->sd_ctime.nsec);2563 to->sd_mtime.sec =get_be32(&from->sd_mtime.sec);2564 to->sd_mtime.nsec =get_be32(&from->sd_mtime.nsec);2565 to->sd_dev =get_be32(&from->sd_dev);2566 to->sd_ino =get_be32(&from->sd_ino);2567 to->sd_uid =get_be32(&from->sd_uid);2568 to->sd_gid =get_be32(&from->sd_gid);2569 to->sd_size =get_be32(&from->sd_size);2570}25712572static intread_one_dir(struct untracked_cache_dir **untracked_,2573struct read_data *rd)2574{2575struct untracked_cache_dir ud, *untracked;2576const unsigned char*next, *data = rd->data, *end = rd->end;2577unsigned int value;2578int i, len;25792580memset(&ud,0,sizeof(ud));25812582 next = data;2583 value =decode_varint(&next);2584if(next > end)2585return-1;2586 ud.recurse =1;2587 ud.untracked_alloc = value;2588 ud.untracked_nr = value;2589if(ud.untracked_nr)2590ALLOC_ARRAY(ud.untracked, ud.untracked_nr);2591 data = next;25922593 next = data;2594 ud.dirs_alloc = ud.dirs_nr =decode_varint(&next);2595if(next > end)2596return-1;2597ALLOC_ARRAY(ud.dirs, ud.dirs_nr);2598 data = next;25992600 len =strlen((const char*)data);2601 next = data + len +1;2602if(next > rd->end)2603return-1;2604*untracked_ = untracked =xmalloc(st_add(sizeof(*untracked), len));2605memcpy(untracked, &ud,sizeof(ud));2606memcpy(untracked->name, data, len +1);2607 data = next;26082609for(i =0; i < untracked->untracked_nr; i++) {2610 len =strlen((const char*)data);2611 next = data + len +1;2612if(next > rd->end)2613return-1;2614 untracked->untracked[i] =xstrdup((const char*)data);2615 data = next;2616}26172618 rd->ucd[rd->index++] = untracked;2619 rd->data = data;26202621for(i =0; i < untracked->dirs_nr; i++) {2622 len =read_one_dir(untracked->dirs + i, rd);2623if(len <0)2624return-1;2625}2626return0;2627}26282629static voidset_check_only(size_t pos,void*cb)2630{2631struct read_data *rd = cb;2632struct untracked_cache_dir *ud = rd->ucd[pos];2633 ud->check_only =1;2634}26352636static voidread_stat(size_t pos,void*cb)2637{2638struct read_data *rd = cb;2639struct untracked_cache_dir *ud = rd->ucd[pos];2640if(rd->data +sizeof(struct stat_data) > rd->end) {2641 rd->data = rd->end +1;2642return;2643}2644stat_data_from_disk(&ud->stat_data, (struct stat_data *)rd->data);2645 rd->data +=sizeof(struct stat_data);2646 ud->valid =1;2647}26482649static voidread_sha1(size_t pos,void*cb)2650{2651struct read_data *rd = cb;2652struct untracked_cache_dir *ud = rd->ucd[pos];2653if(rd->data +20> rd->end) {2654 rd->data = rd->end +1;2655return;2656}2657hashcpy(ud->exclude_sha1, rd->data);2658 rd->data +=20;2659}26602661static voidload_sha1_stat(struct sha1_stat *sha1_stat,2662const struct stat_data *stat,2663const unsigned char*sha1)2664{2665stat_data_from_disk(&sha1_stat->stat, stat);2666hashcpy(sha1_stat->sha1, sha1);2667 sha1_stat->valid =1;2668}26692670struct untracked_cache *read_untracked_extension(const void*data,unsigned long sz)2671{2672const struct ondisk_untracked_cache *ouc;2673struct untracked_cache *uc;2674struct read_data rd;2675const unsigned char*next = data, *end = (const unsigned char*)data + sz;2676const char*ident;2677int ident_len, len;26782679if(sz <=1|| end[-1] !='\0')2680return NULL;2681 end--;26822683 ident_len =decode_varint(&next);2684if(next + ident_len > end)2685return NULL;2686 ident = (const char*)next;2687 next += ident_len;26882689 ouc = (const struct ondisk_untracked_cache *)next;2690if(next +ouc_size(0) > end)2691return NULL;26922693 uc =xcalloc(1,sizeof(*uc));2694strbuf_init(&uc->ident, ident_len);2695strbuf_add(&uc->ident, ident, ident_len);2696load_sha1_stat(&uc->ss_info_exclude, &ouc->info_exclude_stat,2697 ouc->info_exclude_sha1);2698load_sha1_stat(&uc->ss_excludes_file, &ouc->excludes_file_stat,2699 ouc->excludes_file_sha1);2700 uc->dir_flags =get_be32(&ouc->dir_flags);2701 uc->exclude_per_dir =xstrdup(ouc->exclude_per_dir);2702/* NUL after exclude_per_dir is covered by sizeof(*ouc) */2703 next +=ouc_size(strlen(ouc->exclude_per_dir));2704if(next >= end)2705goto done2;27062707 len =decode_varint(&next);2708if(next > end || len ==0)2709goto done2;27102711 rd.valid =ewah_new();2712 rd.check_only =ewah_new();2713 rd.sha1_valid =ewah_new();2714 rd.data = next;2715 rd.end = end;2716 rd.index =0;2717ALLOC_ARRAY(rd.ucd, len);27182719if(read_one_dir(&uc->root, &rd) || rd.index != len)2720goto done;27212722 next = rd.data;2723 len =ewah_read_mmap(rd.valid, next, end - next);2724if(len <0)2725goto done;27262727 next += len;2728 len =ewah_read_mmap(rd.check_only, next, end - next);2729if(len <0)2730goto done;27312732 next += len;2733 len =ewah_read_mmap(rd.sha1_valid, next, end - next);2734if(len <0)2735goto done;27362737ewah_each_bit(rd.check_only, set_check_only, &rd);2738 rd.data = next + len;2739ewah_each_bit(rd.valid, read_stat, &rd);2740ewah_each_bit(rd.sha1_valid, read_sha1, &rd);2741 next = rd.data;27422743done:2744free(rd.ucd);2745ewah_free(rd.valid);2746ewah_free(rd.check_only);2747ewah_free(rd.sha1_valid);2748done2:2749if(next != end) {2750free_untracked_cache(uc);2751 uc = NULL;2752}2753return uc;2754}27552756static voidinvalidate_one_directory(struct untracked_cache *uc,2757struct untracked_cache_dir *ucd)2758{2759 uc->dir_invalidated++;2760 ucd->valid =0;2761 ucd->untracked_nr =0;2762}27632764/*2765 * Normally when an entry is added or removed from a directory,2766 * invalidating that directory is enough. No need to touch its2767 * ancestors. When a directory is shown as "foo/bar/" in git-status2768 * however, deleting or adding an entry may have cascading effect.2769 *2770 * Say the "foo/bar/file" has become untracked, we need to tell the2771 * untracked_cache_dir of "foo" that "bar/" is not an untracked2772 * directory any more (because "bar" is managed by foo as an untracked2773 * "file").2774 *2775 * Similarly, if "foo/bar/file" moves from untracked to tracked and it2776 * was the last untracked entry in the entire "foo", we should show2777 * "foo/" instead. Which means we have to invalidate past "bar" up to2778 * "foo".2779 *2780 * This function traverses all directories from root to leaf. If there2781 * is a chance of one of the above cases happening, we invalidate back2782 * to root. Otherwise we just invalidate the leaf. There may be a more2783 * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to2784 * detect these cases and avoid unnecessary invalidation, for example,2785 * checking for the untracked entry named "bar/" in "foo", but for now2786 * stick to something safe and simple.2787 */2788static intinvalidate_one_component(struct untracked_cache *uc,2789struct untracked_cache_dir *dir,2790const char*path,int len)2791{2792const char*rest =strchr(path,'/');27932794if(rest) {2795int component_len = rest - path;2796struct untracked_cache_dir *d =2797lookup_untracked(uc, dir, path, component_len);2798int ret =2799invalidate_one_component(uc, d, rest +1,2800 len - (component_len +1));2801if(ret)2802invalidate_one_directory(uc, dir);2803return ret;2804}28052806invalidate_one_directory(uc, dir);2807return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;2808}28092810voiduntracked_cache_invalidate_path(struct index_state *istate,2811const char*path)2812{2813if(!istate->untracked || !istate->untracked->root)2814return;2815invalidate_one_component(istate->untracked, istate->untracked->root,2816 path,strlen(path));2817}28182819voiduntracked_cache_remove_from_index(struct index_state *istate,2820const char*path)2821{2822untracked_cache_invalidate_path(istate, path);2823}28242825voiduntracked_cache_add_to_index(struct index_state *istate,2826const char*path)2827{2828untracked_cache_invalidate_path(istate, path);2829}28302831/* Update gitfile and core.worktree setting to connect work tree and git dir */2832voidconnect_work_tree_and_git_dir(const char*work_tree_,const char*git_dir_)2833{2834struct strbuf gitfile_sb = STRBUF_INIT;2835struct strbuf cfg_sb = STRBUF_INIT;2836struct strbuf rel_path = STRBUF_INIT;2837char*git_dir, *work_tree;28382839/* Prepare .git file */2840strbuf_addf(&gitfile_sb,"%s/.git", work_tree_);2841if(safe_create_leading_directories_const(gitfile_sb.buf))2842die(_("could not create directories for%s"), gitfile_sb.buf);28432844/* Prepare config file */2845strbuf_addf(&cfg_sb,"%s/config", git_dir_);2846if(safe_create_leading_directories_const(cfg_sb.buf))2847die(_("could not create directories for%s"), cfg_sb.buf);28482849 git_dir =real_pathdup(git_dir_,1);2850 work_tree =real_pathdup(work_tree_,1);28512852/* Write .git file */2853write_file(gitfile_sb.buf,"gitdir:%s",2854relative_path(git_dir, work_tree, &rel_path));2855/* Update core.worktree setting */2856git_config_set_in_file(cfg_sb.buf,"core.worktree",2857relative_path(work_tree, git_dir, &rel_path));28582859strbuf_release(&gitfile_sb);2860strbuf_release(&cfg_sb);2861strbuf_release(&rel_path);2862free(work_tree);2863free(git_dir);2864}28652866/*2867 * Migrate the git directory of the given path from old_git_dir to new_git_dir.2868 */2869voidrelocate_gitdir(const char*path,const char*old_git_dir,const char*new_git_dir)2870{2871if(rename(old_git_dir, new_git_dir) <0)2872die_errno(_("could not migrate git directory from '%s' to '%s'"),2873 old_git_dir, new_git_dir);28742875connect_work_tree_and_git_dir(path, new_git_dir);2876}