1/* 2 * This handles recursive filename detection with exclude 3 * files, index knowledge etc.. 4 * 5 * See Documentation/technical/api-directory-listing.txt 6 * 7 * Copyright (C) Linus Torvalds, 2005-2006 8 * Junio Hamano, 2005-2006 9 */ 10#include"cache.h" 11#include"dir.h" 12#include"refs.h" 13#include"wildmatch.h" 14#include"pathspec.h" 15 16struct path_simplify { 17int len; 18const char*path; 19}; 20 21/* 22 * Tells read_directory_recursive how a file or directory should be treated. 23 * Values are ordered by significance, e.g. if a directory contains both 24 * excluded and untracked files, it is listed as untracked because 25 * path_untracked > path_excluded. 26 */ 27enum path_treatment { 28 path_none =0, 29 path_recurse, 30 path_excluded, 31 path_untracked 32}; 33 34static enum path_treatment read_directory_recursive(struct dir_struct *dir, 35const char*path,int len, 36int check_only,const struct path_simplify *simplify); 37static intget_dtype(struct dirent *de,const char*path,int len); 38 39/* helper string functions with support for the ignore_case flag */ 40intstrcmp_icase(const char*a,const char*b) 41{ 42return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 43} 44 45intstrncmp_icase(const char*a,const char*b,size_t count) 46{ 47return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 48} 49 50intfnmatch_icase(const char*pattern,const char*string,int flags) 51{ 52returnwildmatch(pattern, string, 53 flags | (ignore_case ? WM_CASEFOLD :0), 54 NULL); 55} 56 57inlineintgit_fnmatch(const struct pathspec_item *item, 58const char*pattern,const char*string, 59int prefix) 60{ 61if(prefix >0) { 62if(ps_strncmp(item, pattern, string, prefix)) 63return WM_NOMATCH; 64 pattern += prefix; 65 string += prefix; 66} 67if(item->flags & PATHSPEC_ONESTAR) { 68int pattern_len =strlen(++pattern); 69int string_len =strlen(string); 70return string_len < pattern_len || 71ps_strcmp(item, pattern, 72 string + string_len - pattern_len); 73} 74if(item->magic & PATHSPEC_GLOB) 75returnwildmatch(pattern, string, 76 WM_PATHNAME | 77(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 78 NULL); 79else 80/* wildmatch has not learned no FNM_PATHNAME mode yet */ 81returnwildmatch(pattern, string, 82 item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0, 83 NULL); 84} 85 86static intfnmatch_icase_mem(const char*pattern,int patternlen, 87const char*string,int stringlen, 88int flags) 89{ 90int match_status; 91struct strbuf pat_buf = STRBUF_INIT; 92struct strbuf str_buf = STRBUF_INIT; 93const char*use_pat = pattern; 94const char*use_str = string; 95 96if(pattern[patternlen]) { 97strbuf_add(&pat_buf, pattern, patternlen); 98 use_pat = pat_buf.buf; 99} 100if(string[stringlen]) { 101strbuf_add(&str_buf, string, stringlen); 102 use_str = str_buf.buf; 103} 104 105if(ignore_case) 106 flags |= WM_CASEFOLD; 107 match_status =wildmatch(use_pat, use_str, flags, NULL); 108 109strbuf_release(&pat_buf); 110strbuf_release(&str_buf); 111 112return match_status; 113} 114 115static size_tcommon_prefix_len(const struct pathspec *pathspec) 116{ 117int n; 118size_t max =0; 119 120/* 121 * ":(icase)path" is treated as a pathspec full of 122 * wildcard. In other words, only prefix is considered common 123 * prefix. If the pathspec is abc/foo abc/bar, running in 124 * subdir xyz, the common prefix is still xyz, not xuz/abc as 125 * in non-:(icase). 126 */ 127GUARD_PATHSPEC(pathspec, 128 PATHSPEC_FROMTOP | 129 PATHSPEC_MAXDEPTH | 130 PATHSPEC_LITERAL | 131 PATHSPEC_GLOB | 132 PATHSPEC_ICASE | 133 PATHSPEC_EXCLUDE); 134 135for(n =0; n < pathspec->nr; n++) { 136size_t i =0, len =0, item_len; 137if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 138continue; 139if(pathspec->items[n].magic & PATHSPEC_ICASE) 140 item_len = pathspec->items[n].prefix; 141else 142 item_len = pathspec->items[n].nowildcard_len; 143while(i < item_len && (n ==0|| i < max)) { 144char c = pathspec->items[n].match[i]; 145if(c != pathspec->items[0].match[i]) 146break; 147if(c =='/') 148 len = i +1; 149 i++; 150} 151if(n ==0|| len < max) { 152 max = len; 153if(!max) 154break; 155} 156} 157return max; 158} 159 160/* 161 * Returns a copy of the longest leading path common among all 162 * pathspecs. 163 */ 164char*common_prefix(const struct pathspec *pathspec) 165{ 166unsigned long len =common_prefix_len(pathspec); 167 168return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 169} 170 171intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 172{ 173size_t len; 174 175/* 176 * Calculate common prefix for the pathspec, and 177 * use that to optimize the directory walk 178 */ 179 len =common_prefix_len(pathspec); 180 181/* Read the directory and prune it */ 182read_directory(dir, pathspec->nr ? pathspec->_raw[0] :"", len, pathspec); 183return len; 184} 185 186intwithin_depth(const char*name,int namelen, 187int depth,int max_depth) 188{ 189const char*cp = name, *cpe = name + namelen; 190 191while(cp < cpe) { 192if(*cp++ !='/') 193continue; 194 depth++; 195if(depth > max_depth) 196return0; 197} 198return1; 199} 200 201/* 202 * Does 'match' match the given name? 203 * A match is found if 204 * 205 * (1) the 'match' string is leading directory of 'name', or 206 * (2) the 'match' string is a wildcard and matches 'name', or 207 * (3) the 'match' string is exactly the same as 'name'. 208 * 209 * and the return value tells which case it was. 210 * 211 * It returns 0 when there is no match. 212 */ 213static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 214const char*name,int namelen) 215{ 216/* name/namelen has prefix cut off by caller */ 217const char*match = item->match + prefix; 218int matchlen = item->len - prefix; 219 220/* 221 * The normal call pattern is: 222 * 1. prefix = common_prefix_len(ps); 223 * 2. prune something, or fill_directory 224 * 3. match_pathspec_depth() 225 * 226 * 'prefix' at #1 may be shorter than the command's prefix and 227 * it's ok for #2 to match extra files. Those extras will be 228 * trimmed at #3. 229 * 230 * Suppose the pathspec is 'foo' and '../bar' running from 231 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 232 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 233 * user does not want XYZ/foo, only the "foo" part should be 234 * case-insensitive. We need to filter out XYZ/foo here. In 235 * other words, we do not trust the caller on comparing the 236 * prefix part when :(icase) is involved. We do exact 237 * comparison ourselves. 238 * 239 * Normally the caller (common_prefix_len() in fact) does 240 * _exact_ matching on name[-prefix+1..-1] and we do not need 241 * to check that part. Be defensive and check it anyway, in 242 * case common_prefix_len is changed, or a new caller is 243 * introduced that does not use common_prefix_len. 244 * 245 * If the penalty turns out too high when prefix is really 246 * long, maybe change it to 247 * strncmp(match, name, item->prefix - prefix) 248 */ 249if(item->prefix && (item->magic & PATHSPEC_ICASE) && 250strncmp(item->match, name - prefix, item->prefix)) 251return0; 252 253/* If the match was just the prefix, we matched */ 254if(!*match) 255return MATCHED_RECURSIVELY; 256 257if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 258if(matchlen == namelen) 259return MATCHED_EXACTLY; 260 261if(match[matchlen-1] =='/'|| name[matchlen] =='/') 262return MATCHED_RECURSIVELY; 263} 264 265if(item->nowildcard_len < item->len && 266!git_fnmatch(item, match, name, 267 item->nowildcard_len - prefix)) 268return MATCHED_FNMATCH; 269 270return0; 271} 272 273/* 274 * Given a name and a list of pathspecs, returns the nature of the 275 * closest (i.e. most specific) match of the name to any of the 276 * pathspecs. 277 * 278 * The caller typically calls this multiple times with the same 279 * pathspec and seen[] array but with different name/namelen 280 * (e.g. entries from the index) and is interested in seeing if and 281 * how each pathspec matches all the names it calls this function 282 * with. A mark is left in the seen[] array for each pathspec element 283 * indicating the closest type of match that element achieved, so if 284 * seen[n] remains zero after multiple invocations, that means the nth 285 * pathspec did not match any names, which could indicate that the 286 * user mistyped the nth pathspec. 287 */ 288static intmatch_pathspec_depth_1(const struct pathspec *ps, 289const char*name,int namelen, 290int prefix,char*seen, 291int exclude) 292{ 293int i, retval =0; 294 295GUARD_PATHSPEC(ps, 296 PATHSPEC_FROMTOP | 297 PATHSPEC_MAXDEPTH | 298 PATHSPEC_LITERAL | 299 PATHSPEC_GLOB | 300 PATHSPEC_ICASE | 301 PATHSPEC_EXCLUDE); 302 303if(!ps->nr) { 304if(!ps->recursive || 305!(ps->magic & PATHSPEC_MAXDEPTH) || 306 ps->max_depth == -1) 307return MATCHED_RECURSIVELY; 308 309if(within_depth(name, namelen,0, ps->max_depth)) 310return MATCHED_EXACTLY; 311else 312return0; 313} 314 315 name += prefix; 316 namelen -= prefix; 317 318for(i = ps->nr -1; i >=0; i--) { 319int how; 320 321if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 322( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 323continue; 324 325if(seen && seen[i] == MATCHED_EXACTLY) 326continue; 327/* 328 * Make exclude patterns optional and never report 329 * "pathspec ':(exclude)foo' matches no files" 330 */ 331if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 332 seen[i] = MATCHED_FNMATCH; 333 how =match_pathspec_item(ps->items+i, prefix, name, namelen); 334if(ps->recursive && 335(ps->magic & PATHSPEC_MAXDEPTH) && 336 ps->max_depth != -1&& 337 how && how != MATCHED_FNMATCH) { 338int len = ps->items[i].len; 339if(name[len] =='/') 340 len++; 341if(within_depth(name+len, namelen-len,0, ps->max_depth)) 342 how = MATCHED_EXACTLY; 343else 344 how =0; 345} 346if(how) { 347if(retval < how) 348 retval = how; 349if(seen && seen[i] < how) 350 seen[i] = how; 351} 352} 353return retval; 354} 355 356intmatch_pathspec_depth(const struct pathspec *ps, 357const char*name,int namelen, 358int prefix,char*seen) 359{ 360int positive, negative; 361 positive =match_pathspec_depth_1(ps, name, namelen, prefix, seen,0); 362if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 363return positive; 364 negative =match_pathspec_depth_1(ps, name, namelen, prefix, seen,1); 365return negative ?0: positive; 366} 367 368/* 369 * Return the length of the "simple" part of a path match limiter. 370 */ 371intsimple_length(const char*match) 372{ 373int len = -1; 374 375for(;;) { 376unsigned char c = *match++; 377 len++; 378if(c =='\0'||is_glob_special(c)) 379return len; 380} 381} 382 383intno_wildcard(const char*string) 384{ 385return string[simple_length(string)] =='\0'; 386} 387 388voidparse_exclude_pattern(const char**pattern, 389int*patternlen, 390int*flags, 391int*nowildcardlen) 392{ 393const char*p = *pattern; 394size_t i, len; 395 396*flags =0; 397if(*p =='!') { 398*flags |= EXC_FLAG_NEGATIVE; 399 p++; 400} 401 len =strlen(p); 402if(len && p[len -1] =='/') { 403 len--; 404*flags |= EXC_FLAG_MUSTBEDIR; 405} 406for(i =0; i < len; i++) { 407if(p[i] =='/') 408break; 409} 410if(i == len) 411*flags |= EXC_FLAG_NODIR; 412*nowildcardlen =simple_length(p); 413/* 414 * we should have excluded the trailing slash from 'p' too, 415 * but that's one more allocation. Instead just make sure 416 * nowildcardlen does not exceed real patternlen 417 */ 418if(*nowildcardlen > len) 419*nowildcardlen = len; 420if(*p =='*'&&no_wildcard(p +1)) 421*flags |= EXC_FLAG_ENDSWITH; 422*pattern = p; 423*patternlen = len; 424} 425 426voidadd_exclude(const char*string,const char*base, 427int baselen,struct exclude_list *el,int srcpos) 428{ 429struct exclude *x; 430int patternlen; 431int flags; 432int nowildcardlen; 433 434parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 435if(flags & EXC_FLAG_MUSTBEDIR) { 436char*s; 437 x =xmalloc(sizeof(*x) + patternlen +1); 438 s = (char*)(x+1); 439memcpy(s, string, patternlen); 440 s[patternlen] ='\0'; 441 x->pattern = s; 442}else{ 443 x =xmalloc(sizeof(*x)); 444 x->pattern = string; 445} 446 x->patternlen = patternlen; 447 x->nowildcardlen = nowildcardlen; 448 x->base = base; 449 x->baselen = baselen; 450 x->flags = flags; 451 x->srcpos = srcpos; 452ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 453 el->excludes[el->nr++] = x; 454 x->el = el; 455} 456 457static void*read_skip_worktree_file_from_index(const char*path,size_t*size) 458{ 459int pos, len; 460unsigned long sz; 461enum object_type type; 462void*data; 463 464 len =strlen(path); 465 pos =cache_name_pos(path, len); 466if(pos <0) 467return NULL; 468if(!ce_skip_worktree(active_cache[pos])) 469return NULL; 470 data =read_sha1_file(active_cache[pos]->sha1, &type, &sz); 471if(!data || type != OBJ_BLOB) { 472free(data); 473return NULL; 474} 475*size =xsize_t(sz); 476return data; 477} 478 479/* 480 * Frees memory within el which was allocated for exclude patterns and 481 * the file buffer. Does not free el itself. 482 */ 483voidclear_exclude_list(struct exclude_list *el) 484{ 485int i; 486 487for(i =0; i < el->nr; i++) 488free(el->excludes[i]); 489free(el->excludes); 490free(el->filebuf); 491 492 el->nr =0; 493 el->excludes = NULL; 494 el->filebuf = NULL; 495} 496 497intadd_excludes_from_file_to_list(const char*fname, 498const char*base, 499int baselen, 500struct exclude_list *el, 501int check_index) 502{ 503struct stat st; 504int fd, i, lineno =1; 505size_t size =0; 506char*buf, *entry; 507 508 fd =open(fname, O_RDONLY); 509if(fd <0||fstat(fd, &st) <0) { 510if(errno != ENOENT) 511warn_on_inaccessible(fname); 512if(0<= fd) 513close(fd); 514if(!check_index || 515(buf =read_skip_worktree_file_from_index(fname, &size)) == NULL) 516return-1; 517if(size ==0) { 518free(buf); 519return0; 520} 521if(buf[size-1] !='\n') { 522 buf =xrealloc(buf, size+1); 523 buf[size++] ='\n'; 524} 525} 526else{ 527 size =xsize_t(st.st_size); 528if(size ==0) { 529close(fd); 530return0; 531} 532 buf =xmalloc(size+1); 533if(read_in_full(fd, buf, size) != size) { 534free(buf); 535close(fd); 536return-1; 537} 538 buf[size++] ='\n'; 539close(fd); 540} 541 542 el->filebuf = buf; 543 entry = buf; 544for(i =0; i < size; i++) { 545if(buf[i] =='\n') { 546if(entry != buf + i && entry[0] !='#') { 547 buf[i - (i && buf[i-1] =='\r')] =0; 548add_exclude(entry, base, baselen, el, lineno); 549} 550 lineno++; 551 entry = buf + i +1; 552} 553} 554return0; 555} 556 557struct exclude_list *add_exclude_list(struct dir_struct *dir, 558int group_type,const char*src) 559{ 560struct exclude_list *el; 561struct exclude_list_group *group; 562 563 group = &dir->exclude_list_group[group_type]; 564ALLOC_GROW(group->el, group->nr +1, group->alloc); 565 el = &group->el[group->nr++]; 566memset(el,0,sizeof(*el)); 567 el->src = src; 568return el; 569} 570 571/* 572 * Used to set up core.excludesfile and .git/info/exclude lists. 573 */ 574voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 575{ 576struct exclude_list *el; 577 el =add_exclude_list(dir, EXC_FILE, fname); 578if(add_excludes_from_file_to_list(fname,"",0, el,0) <0) 579die("cannot use%sas an exclude file", fname); 580} 581 582intmatch_basename(const char*basename,int basenamelen, 583const char*pattern,int prefix,int patternlen, 584int flags) 585{ 586if(prefix == patternlen) { 587if(patternlen == basenamelen && 588!strncmp_icase(pattern, basename, basenamelen)) 589return1; 590}else if(flags & EXC_FLAG_ENDSWITH) { 591/* "*literal" matching against "fooliteral" */ 592if(patternlen -1<= basenamelen && 593!strncmp_icase(pattern +1, 594 basename + basenamelen - (patternlen -1), 595 patternlen -1)) 596return1; 597}else{ 598if(fnmatch_icase_mem(pattern, patternlen, 599 basename, basenamelen, 6000) ==0) 601return1; 602} 603return0; 604} 605 606intmatch_pathname(const char*pathname,int pathlen, 607const char*base,int baselen, 608const char*pattern,int prefix,int patternlen, 609int flags) 610{ 611const char*name; 612int namelen; 613 614/* 615 * match with FNM_PATHNAME; the pattern has base implicitly 616 * in front of it. 617 */ 618if(*pattern =='/') { 619 pattern++; 620 patternlen--; 621 prefix--; 622} 623 624/* 625 * baselen does not count the trailing slash. base[] may or 626 * may not end with a trailing slash though. 627 */ 628if(pathlen < baselen +1|| 629(baselen && pathname[baselen] !='/') || 630strncmp_icase(pathname, base, baselen)) 631return0; 632 633 namelen = baselen ? pathlen - baselen -1: pathlen; 634 name = pathname + pathlen - namelen; 635 636if(prefix) { 637/* 638 * if the non-wildcard part is longer than the 639 * remaining pathname, surely it cannot match. 640 */ 641if(prefix > namelen) 642return0; 643 644if(strncmp_icase(pattern, name, prefix)) 645return0; 646 pattern += prefix; 647 patternlen -= prefix; 648 name += prefix; 649 namelen -= prefix; 650 651/* 652 * If the whole pattern did not have a wildcard, 653 * then our prefix match is all we need; we 654 * do not need to call fnmatch at all. 655 */ 656if(!patternlen && !namelen) 657return1; 658} 659 660returnfnmatch_icase_mem(pattern, patternlen, 661 name, namelen, 662 WM_PATHNAME) ==0; 663} 664 665/* 666 * Scan the given exclude list in reverse to see whether pathname 667 * should be ignored. The first match (i.e. the last on the list), if 668 * any, determines the fate. Returns the exclude_list element which 669 * matched, or NULL for undecided. 670 */ 671static struct exclude *last_exclude_matching_from_list(const char*pathname, 672int pathlen, 673const char*basename, 674int*dtype, 675struct exclude_list *el) 676{ 677int i; 678 679if(!el->nr) 680return NULL;/* undefined */ 681 682for(i = el->nr -1;0<= i; i--) { 683struct exclude *x = el->excludes[i]; 684const char*exclude = x->pattern; 685int prefix = x->nowildcardlen; 686 687if(x->flags & EXC_FLAG_MUSTBEDIR) { 688if(*dtype == DT_UNKNOWN) 689*dtype =get_dtype(NULL, pathname, pathlen); 690if(*dtype != DT_DIR) 691continue; 692} 693 694if(x->flags & EXC_FLAG_NODIR) { 695if(match_basename(basename, 696 pathlen - (basename - pathname), 697 exclude, prefix, x->patternlen, 698 x->flags)) 699return x; 700continue; 701} 702 703assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 704if(match_pathname(pathname, pathlen, 705 x->base, x->baselen ? x->baselen -1:0, 706 exclude, prefix, x->patternlen, x->flags)) 707return x; 708} 709return NULL;/* undecided */ 710} 711 712/* 713 * Scan the list and let the last match determine the fate. 714 * Return 1 for exclude, 0 for include and -1 for undecided. 715 */ 716intis_excluded_from_list(const char*pathname, 717int pathlen,const char*basename,int*dtype, 718struct exclude_list *el) 719{ 720struct exclude *exclude; 721 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 722if(exclude) 723return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 724return-1;/* undecided */ 725} 726 727static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 728const char*pathname,int pathlen,const char*basename, 729int*dtype_p) 730{ 731int i, j; 732struct exclude_list_group *group; 733struct exclude *exclude; 734for(i = EXC_CMDL; i <= EXC_FILE; i++) { 735 group = &dir->exclude_list_group[i]; 736for(j = group->nr -1; j >=0; j--) { 737 exclude =last_exclude_matching_from_list( 738 pathname, pathlen, basename, dtype_p, 739&group->el[j]); 740if(exclude) 741return exclude; 742} 743} 744return NULL; 745} 746 747/* 748 * Loads the per-directory exclude list for the substring of base 749 * which has a char length of baselen. 750 */ 751static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen) 752{ 753struct exclude_list_group *group; 754struct exclude_list *el; 755struct exclude_stack *stk = NULL; 756int current; 757 758 group = &dir->exclude_list_group[EXC_DIRS]; 759 760/* Pop the exclude lists from the EXCL_DIRS exclude_list_group 761 * which originate from directories not in the prefix of the 762 * path being checked. */ 763while((stk = dir->exclude_stack) != NULL) { 764if(stk->baselen <= baselen && 765!strncmp(dir->basebuf, base, stk->baselen)) 766break; 767 el = &group->el[dir->exclude_stack->exclude_ix]; 768 dir->exclude_stack = stk->prev; 769 dir->exclude = NULL; 770free((char*)el->src);/* see strdup() below */ 771clear_exclude_list(el); 772free(stk); 773 group->nr--; 774} 775 776/* Skip traversing into sub directories if the parent is excluded */ 777if(dir->exclude) 778return; 779 780/* Read from the parent directories and push them down. */ 781 current = stk ? stk->baselen : -1; 782while(current < baselen) { 783struct exclude_stack *stk =xcalloc(1,sizeof(*stk)); 784const char*cp; 785 786if(current <0) { 787 cp = base; 788 current =0; 789} 790else{ 791 cp =strchr(base + current +1,'/'); 792if(!cp) 793die("oops in prep_exclude"); 794 cp++; 795} 796 stk->prev = dir->exclude_stack; 797 stk->baselen = cp - base; 798 stk->exclude_ix = group->nr; 799 el =add_exclude_list(dir, EXC_DIRS, NULL); 800memcpy(dir->basebuf + current, base + current, 801 stk->baselen - current); 802 803/* Abort if the directory is excluded */ 804if(stk->baselen) { 805int dt = DT_DIR; 806 dir->basebuf[stk->baselen -1] =0; 807 dir->exclude =last_exclude_matching_from_lists(dir, 808 dir->basebuf, stk->baselen -1, 809 dir->basebuf + current, &dt); 810 dir->basebuf[stk->baselen -1] ='/'; 811if(dir->exclude && 812 dir->exclude->flags & EXC_FLAG_NEGATIVE) 813 dir->exclude = NULL; 814if(dir->exclude) { 815 dir->basebuf[stk->baselen] =0; 816 dir->exclude_stack = stk; 817return; 818} 819} 820 821/* Try to read per-directory file unless path is too long */ 822if(dir->exclude_per_dir && 823 stk->baselen +strlen(dir->exclude_per_dir) < PATH_MAX) { 824strcpy(dir->basebuf + stk->baselen, 825 dir->exclude_per_dir); 826/* 827 * dir->basebuf gets reused by the traversal, but we 828 * need fname to remain unchanged to ensure the src 829 * member of each struct exclude correctly 830 * back-references its source file. Other invocations 831 * of add_exclude_list provide stable strings, so we 832 * strdup() and free() here in the caller. 833 */ 834 el->src =strdup(dir->basebuf); 835add_excludes_from_file_to_list(dir->basebuf, 836 dir->basebuf, stk->baselen, el,1); 837} 838 dir->exclude_stack = stk; 839 current = stk->baselen; 840} 841 dir->basebuf[baselen] ='\0'; 842} 843 844/* 845 * Loads the exclude lists for the directory containing pathname, then 846 * scans all exclude lists to determine whether pathname is excluded. 847 * Returns the exclude_list element which matched, or NULL for 848 * undecided. 849 */ 850struct exclude *last_exclude_matching(struct dir_struct *dir, 851const char*pathname, 852int*dtype_p) 853{ 854int pathlen =strlen(pathname); 855const char*basename =strrchr(pathname,'/'); 856 basename = (basename) ? basename+1: pathname; 857 858prep_exclude(dir, pathname, basename-pathname); 859 860if(dir->exclude) 861return dir->exclude; 862 863returnlast_exclude_matching_from_lists(dir, pathname, pathlen, 864 basename, dtype_p); 865} 866 867/* 868 * Loads the exclude lists for the directory containing pathname, then 869 * scans all exclude lists to determine whether pathname is excluded. 870 * Returns 1 if true, otherwise 0. 871 */ 872intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p) 873{ 874struct exclude *exclude = 875last_exclude_matching(dir, pathname, dtype_p); 876if(exclude) 877return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 878return0; 879} 880 881static struct dir_entry *dir_entry_new(const char*pathname,int len) 882{ 883struct dir_entry *ent; 884 885 ent =xmalloc(sizeof(*ent) + len +1); 886 ent->len = len; 887memcpy(ent->name, pathname, len); 888 ent->name[len] =0; 889return ent; 890} 891 892static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len) 893{ 894if(cache_file_exists(pathname, len, ignore_case)) 895return NULL; 896 897ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc); 898return dir->entries[dir->nr++] =dir_entry_new(pathname, len); 899} 900 901struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len) 902{ 903if(!cache_name_is_other(pathname, len)) 904return NULL; 905 906ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc); 907return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len); 908} 909 910enum exist_status { 911 index_nonexistent =0, 912 index_directory, 913 index_gitdir 914}; 915 916/* 917 * Do not use the alphabetically sorted index to look up 918 * the directory name; instead, use the case insensitive 919 * directory hash. 920 */ 921static enum exist_status directory_exists_in_index_icase(const char*dirname,int len) 922{ 923const struct cache_entry *ce =cache_dir_exists(dirname, len); 924unsigned char endchar; 925 926if(!ce) 927return index_nonexistent; 928 endchar = ce->name[len]; 929 930/* 931 * The cache_entry structure returned will contain this dirname 932 * and possibly additional path components. 933 */ 934if(endchar =='/') 935return index_directory; 936 937/* 938 * If there are no additional path components, then this cache_entry 939 * represents a submodule. Submodules, despite being directories, 940 * are stored in the cache without a closing slash. 941 */ 942if(!endchar &&S_ISGITLINK(ce->ce_mode)) 943return index_gitdir; 944 945/* This should never be hit, but it exists just in case. */ 946return index_nonexistent; 947} 948 949/* 950 * The index sorts alphabetically by entry name, which 951 * means that a gitlink sorts as '\0' at the end, while 952 * a directory (which is defined not as an entry, but as 953 * the files it contains) will sort with the '/' at the 954 * end. 955 */ 956static enum exist_status directory_exists_in_index(const char*dirname,int len) 957{ 958int pos; 959 960if(ignore_case) 961returndirectory_exists_in_index_icase(dirname, len); 962 963 pos =cache_name_pos(dirname, len); 964if(pos <0) 965 pos = -pos-1; 966while(pos < active_nr) { 967const struct cache_entry *ce = active_cache[pos++]; 968unsigned char endchar; 969 970if(strncmp(ce->name, dirname, len)) 971break; 972 endchar = ce->name[len]; 973if(endchar >'/') 974break; 975if(endchar =='/') 976return index_directory; 977if(!endchar &&S_ISGITLINK(ce->ce_mode)) 978return index_gitdir; 979} 980return index_nonexistent; 981} 982 983/* 984 * When we find a directory when traversing the filesystem, we 985 * have three distinct cases: 986 * 987 * - ignore it 988 * - see it as a directory 989 * - recurse into it 990 * 991 * and which one we choose depends on a combination of existing 992 * git index contents and the flags passed into the directory 993 * traversal routine. 994 * 995 * Case 1: If we *already* have entries in the index under that 996 * directory name, we always recurse into the directory to see 997 * all the files. 998 * 999 * Case 2: If we *already* have that directory name as a gitlink,1000 * we always continue to see it as a gitlink, regardless of whether1001 * there is an actual git directory there or not (it might not1002 * be checked out as a subproject!)1003 *1004 * Case 3: if we didn't have it in the index previously, we1005 * have a few sub-cases:1006 *1007 * (a) if "show_other_directories" is true, we show it as1008 * just a directory, unless "hide_empty_directories" is1009 * also true, in which case we need to check if it contains any1010 * untracked and / or ignored files.1011 * (b) if it looks like a git directory, and we don't have1012 * 'no_gitlinks' set we treat it as a gitlink, and show it1013 * as a directory.1014 * (c) otherwise, we recurse into it.1015 */1016static enum path_treatment treat_directory(struct dir_struct *dir,1017const char*dirname,int len,int exclude,1018const struct path_simplify *simplify)1019{1020/* The "len-1" is to strip the final '/' */1021switch(directory_exists_in_index(dirname, len-1)) {1022case index_directory:1023return path_recurse;10241025case index_gitdir:1026return path_none;10271028case index_nonexistent:1029if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1030break;1031if(!(dir->flags & DIR_NO_GITLINKS)) {1032unsigned char sha1[20];1033if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1034return path_untracked;1035}1036return path_recurse;1037}10381039/* This is the "show_other_directories" case */10401041if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1042return exclude ? path_excluded : path_untracked;10431044returnread_directory_recursive(dir, dirname, len,1, simplify);1045}10461047/*1048 * This is an inexact early pruning of any recursive directory1049 * reading - if the path cannot possibly be in the pathspec,1050 * return true, and we'll skip it early.1051 */1052static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1053{1054if(simplify) {1055for(;;) {1056const char*match = simplify->path;1057int len = simplify->len;10581059if(!match)1060break;1061if(len > pathlen)1062 len = pathlen;1063if(!memcmp(path, match, len))1064return0;1065 simplify++;1066}1067return1;1068}1069return0;1070}10711072/*1073 * This function tells us whether an excluded path matches a1074 * list of "interesting" pathspecs. That is, whether a path matched1075 * by any of the pathspecs could possibly be ignored by excluding1076 * the specified path. This can happen if:1077 *1078 * 1. the path is mentioned explicitly in the pathspec1079 *1080 * 2. the path is a directory prefix of some element in the1081 * pathspec1082 */1083static intexclude_matches_pathspec(const char*path,int len,1084const struct path_simplify *simplify)1085{1086if(simplify) {1087for(; simplify->path; simplify++) {1088if(len == simplify->len1089&& !memcmp(path, simplify->path, len))1090return1;1091if(len < simplify->len1092&& simplify->path[len] =='/'1093&& !memcmp(path, simplify->path, len))1094return1;1095}1096}1097return0;1098}10991100static intget_index_dtype(const char*path,int len)1101{1102int pos;1103const struct cache_entry *ce;11041105 ce =cache_file_exists(path, len,0);1106if(ce) {1107if(!ce_uptodate(ce))1108return DT_UNKNOWN;1109if(S_ISGITLINK(ce->ce_mode))1110return DT_DIR;1111/*1112 * Nobody actually cares about the1113 * difference between DT_LNK and DT_REG1114 */1115return DT_REG;1116}11171118/* Try to look it up as a directory */1119 pos =cache_name_pos(path, len);1120if(pos >=0)1121return DT_UNKNOWN;1122 pos = -pos-1;1123while(pos < active_nr) {1124 ce = active_cache[pos++];1125if(strncmp(ce->name, path, len))1126break;1127if(ce->name[len] >'/')1128break;1129if(ce->name[len] <'/')1130continue;1131if(!ce_uptodate(ce))1132break;/* continue? */1133return DT_DIR;1134}1135return DT_UNKNOWN;1136}11371138static intget_dtype(struct dirent *de,const char*path,int len)1139{1140int dtype = de ?DTYPE(de) : DT_UNKNOWN;1141struct stat st;11421143if(dtype != DT_UNKNOWN)1144return dtype;1145 dtype =get_index_dtype(path, len);1146if(dtype != DT_UNKNOWN)1147return dtype;1148if(lstat(path, &st))1149return dtype;1150if(S_ISREG(st.st_mode))1151return DT_REG;1152if(S_ISDIR(st.st_mode))1153return DT_DIR;1154if(S_ISLNK(st.st_mode))1155return DT_LNK;1156return dtype;1157}11581159static enum path_treatment treat_one_path(struct dir_struct *dir,1160struct strbuf *path,1161const struct path_simplify *simplify,1162int dtype,struct dirent *de)1163{1164int exclude;1165int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);11661167if(dtype == DT_UNKNOWN)1168 dtype =get_dtype(de, path->buf, path->len);11691170/* Always exclude indexed files */1171if(dtype != DT_DIR && has_path_in_index)1172return path_none;11731174/*1175 * When we are looking at a directory P in the working tree,1176 * there are three cases:1177 *1178 * (1) P exists in the index. Everything inside the directory P in1179 * the working tree needs to go when P is checked out from the1180 * index.1181 *1182 * (2) P does not exist in the index, but there is P/Q in the index.1183 * We know P will stay a directory when we check out the contents1184 * of the index, but we do not know yet if there is a directory1185 * P/Q in the working tree to be killed, so we need to recurse.1186 *1187 * (3) P does not exist in the index, and there is no P/Q in the index1188 * to require P to be a directory, either. Only in this case, we1189 * know that everything inside P will not be killed without1190 * recursing.1191 */1192if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1193(dtype == DT_DIR) &&1194!has_path_in_index &&1195(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1196return path_none;11971198 exclude =is_excluded(dir, path->buf, &dtype);11991200/*1201 * Excluded? If we don't explicitly want to show1202 * ignored files, ignore it1203 */1204if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1205return path_excluded;12061207switch(dtype) {1208default:1209return path_none;1210case DT_DIR:1211strbuf_addch(path,'/');1212returntreat_directory(dir, path->buf, path->len, exclude,1213 simplify);1214case DT_REG:1215case DT_LNK:1216return exclude ? path_excluded : path_untracked;1217}1218}12191220static enum path_treatment treat_path(struct dir_struct *dir,1221struct dirent *de,1222struct strbuf *path,1223int baselen,1224const struct path_simplify *simplify)1225{1226int dtype;12271228if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1229return path_none;1230strbuf_setlen(path, baselen);1231strbuf_addstr(path, de->d_name);1232if(simplify_away(path->buf, path->len, simplify))1233return path_none;12341235 dtype =DTYPE(de);1236returntreat_one_path(dir, path, simplify, dtype, de);1237}12381239/*1240 * Read a directory tree. We currently ignore anything but1241 * directories, regular files and symlinks. That's because git1242 * doesn't handle them at all yet. Maybe that will change some1243 * day.1244 *1245 * Also, we ignore the name ".git" (even if it is not a directory).1246 * That likely will not change.1247 *1248 * Returns the most significant path_treatment value encountered in the scan.1249 */1250static enum path_treatment read_directory_recursive(struct dir_struct *dir,1251const char*base,int baselen,1252int check_only,1253const struct path_simplify *simplify)1254{1255DIR*fdir;1256enum path_treatment state, subdir_state, dir_state = path_none;1257struct dirent *de;1258struct strbuf path = STRBUF_INIT;12591260strbuf_add(&path, base, baselen);12611262 fdir =opendir(path.len ? path.buf :".");1263if(!fdir)1264goto out;12651266while((de =readdir(fdir)) != NULL) {1267/* check how the file or directory should be treated */1268 state =treat_path(dir, de, &path, baselen, simplify);1269if(state > dir_state)1270 dir_state = state;12711272/* recurse into subdir if instructed by treat_path */1273if(state == path_recurse) {1274 subdir_state =read_directory_recursive(dir, path.buf,1275 path.len, check_only, simplify);1276if(subdir_state > dir_state)1277 dir_state = subdir_state;1278}12791280if(check_only) {1281/* abort early if maximum state has been reached */1282if(dir_state == path_untracked)1283break;1284/* skip the dir_add_* part */1285continue;1286}12871288/* add the path to the appropriate result list */1289switch(state) {1290case path_excluded:1291if(dir->flags & DIR_SHOW_IGNORED)1292dir_add_name(dir, path.buf, path.len);1293else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1294((dir->flags & DIR_COLLECT_IGNORED) &&1295exclude_matches_pathspec(path.buf, path.len,1296 simplify)))1297dir_add_ignored(dir, path.buf, path.len);1298break;12991300case path_untracked:1301if(!(dir->flags & DIR_SHOW_IGNORED))1302dir_add_name(dir, path.buf, path.len);1303break;13041305default:1306break;1307}1308}1309closedir(fdir);1310 out:1311strbuf_release(&path);13121313return dir_state;1314}13151316static intcmp_name(const void*p1,const void*p2)1317{1318const struct dir_entry *e1 = *(const struct dir_entry **)p1;1319const struct dir_entry *e2 = *(const struct dir_entry **)p2;13201321returncache_name_compare(e1->name, e1->len,1322 e2->name, e2->len);1323}13241325static struct path_simplify *create_simplify(const char**pathspec)1326{1327int nr, alloc =0;1328struct path_simplify *simplify = NULL;13291330if(!pathspec)1331return NULL;13321333for(nr =0; ; nr++) {1334const char*match;1335if(nr >= alloc) {1336 alloc =alloc_nr(alloc);1337 simplify =xrealloc(simplify, alloc *sizeof(*simplify));1338}1339 match = *pathspec++;1340if(!match)1341break;1342 simplify[nr].path = match;1343 simplify[nr].len =simple_length(match);1344}1345 simplify[nr].path = NULL;1346 simplify[nr].len =0;1347return simplify;1348}13491350static voidfree_simplify(struct path_simplify *simplify)1351{1352free(simplify);1353}13541355static inttreat_leading_path(struct dir_struct *dir,1356const char*path,int len,1357const struct path_simplify *simplify)1358{1359struct strbuf sb = STRBUF_INIT;1360int baselen, rc =0;1361const char*cp;1362int old_flags = dir->flags;13631364while(len && path[len -1] =='/')1365 len--;1366if(!len)1367return1;1368 baselen =0;1369 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1370while(1) {1371 cp = path + baselen + !!baselen;1372 cp =memchr(cp,'/', path + len - cp);1373if(!cp)1374 baselen = len;1375else1376 baselen = cp - path;1377strbuf_setlen(&sb,0);1378strbuf_add(&sb, path, baselen);1379if(!is_directory(sb.buf))1380break;1381if(simplify_away(sb.buf, sb.len, simplify))1382break;1383if(treat_one_path(dir, &sb, simplify,1384 DT_DIR, NULL) == path_none)1385break;/* do not recurse into it */1386if(len <= baselen) {1387 rc =1;1388break;/* finished checking */1389}1390}1391strbuf_release(&sb);1392 dir->flags = old_flags;1393return rc;1394}13951396intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)1397{1398struct path_simplify *simplify;13991400/*1401 * Check out create_simplify()1402 */1403if(pathspec)1404GUARD_PATHSPEC(pathspec,1405 PATHSPEC_FROMTOP |1406 PATHSPEC_MAXDEPTH |1407 PATHSPEC_LITERAL |1408 PATHSPEC_GLOB |1409 PATHSPEC_ICASE |1410 PATHSPEC_EXCLUDE);14111412if(has_symlink_leading_path(path, len))1413return dir->nr;14141415/*1416 * exclude patterns are treated like positive ones in1417 * create_simplify. Usually exclude patterns should be a1418 * subset of positive ones, which has no impacts on1419 * create_simplify().1420 */1421 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);1422if(!len ||treat_leading_path(dir, path, len, simplify))1423read_directory_recursive(dir, path, len,0, simplify);1424free_simplify(simplify);1425qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);1426qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);1427return dir->nr;1428}14291430intfile_exists(const char*f)1431{1432struct stat sb;1433returnlstat(f, &sb) ==0;1434}14351436/*1437 * Given two normalized paths (a trailing slash is ok), if subdir is1438 * outside dir, return -1. Otherwise return the offset in subdir that1439 * can be used as relative path to dir.1440 */1441intdir_inside_of(const char*subdir,const char*dir)1442{1443int offset =0;14441445assert(dir && subdir && *dir && *subdir);14461447while(*dir && *subdir && *dir == *subdir) {1448 dir++;1449 subdir++;1450 offset++;1451}14521453/* hel[p]/me vs hel[l]/yeah */1454if(*dir && *subdir)1455return-1;14561457if(!*subdir)1458return!*dir ? offset : -1;/* same dir */14591460/* foo/[b]ar vs foo/[] */1461if(is_dir_sep(dir[-1]))1462returnis_dir_sep(subdir[-1]) ? offset : -1;14631464/* foo[/]bar vs foo[] */1465returnis_dir_sep(*subdir) ? offset +1: -1;1466}14671468intis_inside_dir(const char*dir)1469{1470char cwd[PATH_MAX];1471if(!dir)1472return0;1473if(!getcwd(cwd,sizeof(cwd)))1474die_errno("can't find the current directory");1475returndir_inside_of(cwd, dir) >=0;1476}14771478intis_empty_dir(const char*path)1479{1480DIR*dir =opendir(path);1481struct dirent *e;1482int ret =1;14831484if(!dir)1485return0;14861487while((e =readdir(dir)) != NULL)1488if(!is_dot_or_dotdot(e->d_name)) {1489 ret =0;1490break;1491}14921493closedir(dir);1494return ret;1495}14961497static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)1498{1499DIR*dir;1500struct dirent *e;1501int ret =0, original_len = path->len, len, kept_down =0;1502int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);1503int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);1504unsigned char submodule_head[20];15051506if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&1507!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {1508/* Do not descend and nuke a nested git work tree. */1509if(kept_up)1510*kept_up =1;1511return0;1512}15131514 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;1515 dir =opendir(path->buf);1516if(!dir) {1517if(errno == ENOENT)1518return keep_toplevel ? -1:0;1519else if(errno == EACCES && !keep_toplevel)1520/*1521 * An empty dir could be removable even if it1522 * is unreadable:1523 */1524returnrmdir(path->buf);1525else1526return-1;1527}1528if(path->buf[original_len -1] !='/')1529strbuf_addch(path,'/');15301531 len = path->len;1532while((e =readdir(dir)) != NULL) {1533struct stat st;1534if(is_dot_or_dotdot(e->d_name))1535continue;15361537strbuf_setlen(path, len);1538strbuf_addstr(path, e->d_name);1539if(lstat(path->buf, &st)) {1540if(errno == ENOENT)1541/*1542 * file disappeared, which is what we1543 * wanted anyway1544 */1545continue;1546/* fall thru */1547}else if(S_ISDIR(st.st_mode)) {1548if(!remove_dir_recurse(path, flag, &kept_down))1549continue;/* happy */1550}else if(!only_empty &&1551(!unlink(path->buf) || errno == ENOENT)) {1552continue;/* happy, too */1553}15541555/* path too long, stat fails, or non-directory still exists */1556 ret = -1;1557break;1558}1559closedir(dir);15601561strbuf_setlen(path, original_len);1562if(!ret && !keep_toplevel && !kept_down)1563 ret = (!rmdir(path->buf) || errno == ENOENT) ?0: -1;1564else if(kept_up)1565/*1566 * report the uplevel that it is not an error that we1567 * did not rmdir() our directory.1568 */1569*kept_up = !ret;1570return ret;1571}15721573intremove_dir_recursively(struct strbuf *path,int flag)1574{1575returnremove_dir_recurse(path, flag, NULL);1576}15771578voidsetup_standard_excludes(struct dir_struct *dir)1579{1580const char*path;1581char*xdg_path;15821583 dir->exclude_per_dir =".gitignore";1584 path =git_path("info/exclude");1585if(!excludes_file) {1586home_config_paths(NULL, &xdg_path,"ignore");1587 excludes_file = xdg_path;1588}1589if(!access_or_warn(path, R_OK,0))1590add_excludes_from_file(dir, path);1591if(excludes_file && !access_or_warn(excludes_file, R_OK,0))1592add_excludes_from_file(dir, excludes_file);1593}15941595intremove_path(const char*name)1596{1597char*slash;15981599if(unlink(name) && errno != ENOENT && errno != ENOTDIR)1600return-1;16011602 slash =strrchr(name,'/');1603if(slash) {1604char*dirs =xstrdup(name);1605 slash = dirs + (slash - name);1606do{1607*slash ='\0';1608}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));1609free(dirs);1610}1611return0;1612}16131614/*1615 * Frees memory within dir which was allocated for exclude lists and1616 * the exclude_stack. Does not free dir itself.1617 */1618voidclear_directory(struct dir_struct *dir)1619{1620int i, j;1621struct exclude_list_group *group;1622struct exclude_list *el;1623struct exclude_stack *stk;16241625for(i = EXC_CMDL; i <= EXC_FILE; i++) {1626 group = &dir->exclude_list_group[i];1627for(j =0; j < group->nr; j++) {1628 el = &group->el[j];1629if(i == EXC_DIRS)1630free((char*)el->src);1631clear_exclude_list(el);1632}1633free(group->el);1634}16351636 stk = dir->exclude_stack;1637while(stk) {1638struct exclude_stack *prev = stk->prev;1639free(stk);1640 stk = prev;1641}1642}