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{ 52returnfnmatch(pattern, string, flags | (ignore_case ? FNM_CASEFOLD :0)); 53} 54 55inlineintgit_fnmatch(const struct pathspec_item *item, 56const char*pattern,const char*string, 57int prefix) 58{ 59if(prefix >0) { 60if(ps_strncmp(item, pattern, string, prefix)) 61return FNM_NOMATCH; 62 pattern += prefix; 63 string += prefix; 64} 65if(item->flags & PATHSPEC_ONESTAR) { 66int pattern_len =strlen(++pattern); 67int string_len =strlen(string); 68return string_len < pattern_len || 69ps_strcmp(item, pattern, 70 string + string_len - pattern_len); 71} 72if(item->magic & PATHSPEC_GLOB) 73returnwildmatch(pattern, string, 74 WM_PATHNAME | 75(item->magic & PATHSPEC_ICASE ? WM_CASEFOLD :0), 76 NULL); 77else 78/* wildmatch has not learned no FNM_PATHNAME mode yet */ 79returnfnmatch(pattern, string, 80 item->magic & PATHSPEC_ICASE ? FNM_CASEFOLD :0); 81} 82 83static intfnmatch_icase_mem(const char*pattern,int patternlen, 84const char*string,int stringlen, 85int flags) 86{ 87int match_status; 88struct strbuf pat_buf = STRBUF_INIT; 89struct strbuf str_buf = STRBUF_INIT; 90const char*use_pat = pattern; 91const char*use_str = string; 92 93if(pattern[patternlen]) { 94strbuf_add(&pat_buf, pattern, patternlen); 95 use_pat = pat_buf.buf; 96} 97if(string[stringlen]) { 98strbuf_add(&str_buf, string, stringlen); 99 use_str = str_buf.buf; 100} 101 102if(ignore_case) 103 flags |= WM_CASEFOLD; 104 match_status =wildmatch(use_pat, use_str, flags, NULL); 105 106strbuf_release(&pat_buf); 107strbuf_release(&str_buf); 108 109return match_status; 110} 111 112static size_tcommon_prefix_len(const struct pathspec *pathspec) 113{ 114int n; 115size_t max =0; 116 117/* 118 * ":(icase)path" is treated as a pathspec full of 119 * wildcard. In other words, only prefix is considered common 120 * prefix. If the pathspec is abc/foo abc/bar, running in 121 * subdir xyz, the common prefix is still xyz, not xuz/abc as 122 * in non-:(icase). 123 */ 124GUARD_PATHSPEC(pathspec, 125 PATHSPEC_FROMTOP | 126 PATHSPEC_MAXDEPTH | 127 PATHSPEC_LITERAL | 128 PATHSPEC_GLOB | 129 PATHSPEC_ICASE | 130 PATHSPEC_EXCLUDE); 131 132for(n =0; n < pathspec->nr; n++) { 133size_t i =0, len =0, item_len; 134if(pathspec->items[n].magic & PATHSPEC_EXCLUDE) 135continue; 136if(pathspec->items[n].magic & PATHSPEC_ICASE) 137 item_len = pathspec->items[n].prefix; 138else 139 item_len = pathspec->items[n].nowildcard_len; 140while(i < item_len && (n ==0|| i < max)) { 141char c = pathspec->items[n].match[i]; 142if(c != pathspec->items[0].match[i]) 143break; 144if(c =='/') 145 len = i +1; 146 i++; 147} 148if(n ==0|| len < max) { 149 max = len; 150if(!max) 151break; 152} 153} 154return max; 155} 156 157/* 158 * Returns a copy of the longest leading path common among all 159 * pathspecs. 160 */ 161char*common_prefix(const struct pathspec *pathspec) 162{ 163unsigned long len =common_prefix_len(pathspec); 164 165return len ?xmemdupz(pathspec->items[0].match, len) : NULL; 166} 167 168intfill_directory(struct dir_struct *dir,const struct pathspec *pathspec) 169{ 170size_t len; 171 172/* 173 * Calculate common prefix for the pathspec, and 174 * use that to optimize the directory walk 175 */ 176 len =common_prefix_len(pathspec); 177 178/* Read the directory and prune it */ 179read_directory(dir, pathspec->nr ? pathspec->_raw[0] :"", len, pathspec); 180return len; 181} 182 183intwithin_depth(const char*name,int namelen, 184int depth,int max_depth) 185{ 186const char*cp = name, *cpe = name + namelen; 187 188while(cp < cpe) { 189if(*cp++ !='/') 190continue; 191 depth++; 192if(depth > max_depth) 193return0; 194} 195return1; 196} 197 198/* 199 * Does 'match' match the given name? 200 * A match is found if 201 * 202 * (1) the 'match' string is leading directory of 'name', or 203 * (2) the 'match' string is a wildcard and matches 'name', or 204 * (3) the 'match' string is exactly the same as 'name'. 205 * 206 * and the return value tells which case it was. 207 * 208 * It returns 0 when there is no match. 209 */ 210static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 211const char*name,int namelen) 212{ 213/* name/namelen has prefix cut off by caller */ 214const char*match = item->match + prefix; 215int matchlen = item->len - prefix; 216 217/* 218 * The normal call pattern is: 219 * 1. prefix = common_prefix_len(ps); 220 * 2. prune something, or fill_directory 221 * 3. match_pathspec_depth() 222 * 223 * 'prefix' at #1 may be shorter than the command's prefix and 224 * it's ok for #2 to match extra files. Those extras will be 225 * trimmed at #3. 226 * 227 * Suppose the pathspec is 'foo' and '../bar' running from 228 * subdir 'xyz'. The common prefix at #1 will be empty, thanks 229 * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The 230 * user does not want XYZ/foo, only the "foo" part should be 231 * case-insensitive. We need to filter out XYZ/foo here. In 232 * other words, we do not trust the caller on comparing the 233 * prefix part when :(icase) is involved. We do exact 234 * comparison ourselves. 235 * 236 * Normally the caller (common_prefix_len() in fact) does 237 * _exact_ matching on name[-prefix+1..-1] and we do not need 238 * to check that part. Be defensive and check it anyway, in 239 * case common_prefix_len is changed, or a new caller is 240 * introduced that does not use common_prefix_len. 241 * 242 * If the penalty turns out too high when prefix is really 243 * long, maybe change it to 244 * strncmp(match, name, item->prefix - prefix) 245 */ 246if(item->prefix && (item->magic & PATHSPEC_ICASE) && 247strncmp(item->match, name - prefix, item->prefix)) 248return0; 249 250/* If the match was just the prefix, we matched */ 251if(!*match) 252return MATCHED_RECURSIVELY; 253 254if(matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) { 255if(matchlen == namelen) 256return MATCHED_EXACTLY; 257 258if(match[matchlen-1] =='/'|| name[matchlen] =='/') 259return MATCHED_RECURSIVELY; 260} 261 262if(item->nowildcard_len < item->len && 263!git_fnmatch(item, match, name, 264 item->nowildcard_len - prefix)) 265return MATCHED_FNMATCH; 266 267return0; 268} 269 270/* 271 * Given a name and a list of pathspecs, returns the nature of the 272 * closest (i.e. most specific) match of the name to any of the 273 * pathspecs. 274 * 275 * The caller typically calls this multiple times with the same 276 * pathspec and seen[] array but with different name/namelen 277 * (e.g. entries from the index) and is interested in seeing if and 278 * how each pathspec matches all the names it calls this function 279 * with. A mark is left in the seen[] array for each pathspec element 280 * indicating the closest type of match that element achieved, so if 281 * seen[n] remains zero after multiple invocations, that means the nth 282 * pathspec did not match any names, which could indicate that the 283 * user mistyped the nth pathspec. 284 */ 285static intmatch_pathspec_depth_1(const struct pathspec *ps, 286const char*name,int namelen, 287int prefix,char*seen, 288int exclude) 289{ 290int i, retval =0; 291 292GUARD_PATHSPEC(ps, 293 PATHSPEC_FROMTOP | 294 PATHSPEC_MAXDEPTH | 295 PATHSPEC_LITERAL | 296 PATHSPEC_GLOB | 297 PATHSPEC_ICASE | 298 PATHSPEC_EXCLUDE); 299 300if(!ps->nr) { 301if(!ps->recursive || 302!(ps->magic & PATHSPEC_MAXDEPTH) || 303 ps->max_depth == -1) 304return MATCHED_RECURSIVELY; 305 306if(within_depth(name, namelen,0, ps->max_depth)) 307return MATCHED_EXACTLY; 308else 309return0; 310} 311 312 name += prefix; 313 namelen -= prefix; 314 315for(i = ps->nr -1; i >=0; i--) { 316int how; 317 318if((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) || 319( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE))) 320continue; 321 322if(seen && seen[i] == MATCHED_EXACTLY) 323continue; 324/* 325 * Make exclude patterns optional and never report 326 * "pathspec ':(exclude)foo' matches no files" 327 */ 328if(seen && ps->items[i].magic & PATHSPEC_EXCLUDE) 329 seen[i] = MATCHED_FNMATCH; 330 how =match_pathspec_item(ps->items+i, prefix, name, namelen); 331if(ps->recursive && 332(ps->magic & PATHSPEC_MAXDEPTH) && 333 ps->max_depth != -1&& 334 how && how != MATCHED_FNMATCH) { 335int len = ps->items[i].len; 336if(name[len] =='/') 337 len++; 338if(within_depth(name+len, namelen-len,0, ps->max_depth)) 339 how = MATCHED_EXACTLY; 340else 341 how =0; 342} 343if(how) { 344if(retval < how) 345 retval = how; 346if(seen && seen[i] < how) 347 seen[i] = how; 348} 349} 350return retval; 351} 352 353intmatch_pathspec_depth(const struct pathspec *ps, 354const char*name,int namelen, 355int prefix,char*seen) 356{ 357int positive, negative; 358 positive =match_pathspec_depth_1(ps, name, namelen, prefix, seen,0); 359if(!(ps->magic & PATHSPEC_EXCLUDE) || !positive) 360return positive; 361 negative =match_pathspec_depth_1(ps, name, namelen, prefix, seen,1); 362return negative ?0: positive; 363} 364 365/* 366 * Return the length of the "simple" part of a path match limiter. 367 */ 368intsimple_length(const char*match) 369{ 370int len = -1; 371 372for(;;) { 373unsigned char c = *match++; 374 len++; 375if(c =='\0'||is_glob_special(c)) 376return len; 377} 378} 379 380intno_wildcard(const char*string) 381{ 382return string[simple_length(string)] =='\0'; 383} 384 385voidparse_exclude_pattern(const char**pattern, 386int*patternlen, 387int*flags, 388int*nowildcardlen) 389{ 390const char*p = *pattern; 391size_t i, len; 392 393*flags =0; 394if(*p =='!') { 395*flags |= EXC_FLAG_NEGATIVE; 396 p++; 397} 398 len =strlen(p); 399if(len && p[len -1] =='/') { 400 len--; 401*flags |= EXC_FLAG_MUSTBEDIR; 402} 403for(i =0; i < len; i++) { 404if(p[i] =='/') 405break; 406} 407if(i == len) 408*flags |= EXC_FLAG_NODIR; 409*nowildcardlen =simple_length(p); 410/* 411 * we should have excluded the trailing slash from 'p' too, 412 * but that's one more allocation. Instead just make sure 413 * nowildcardlen does not exceed real patternlen 414 */ 415if(*nowildcardlen > len) 416*nowildcardlen = len; 417if(*p =='*'&&no_wildcard(p +1)) 418*flags |= EXC_FLAG_ENDSWITH; 419*pattern = p; 420*patternlen = len; 421} 422 423voidadd_exclude(const char*string,const char*base, 424int baselen,struct exclude_list *el,int srcpos) 425{ 426struct exclude *x; 427int patternlen; 428int flags; 429int nowildcardlen; 430 431parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 432if(flags & EXC_FLAG_MUSTBEDIR) { 433char*s; 434 x =xmalloc(sizeof(*x) + patternlen +1); 435 s = (char*)(x+1); 436memcpy(s, string, patternlen); 437 s[patternlen] ='\0'; 438 x->pattern = s; 439}else{ 440 x =xmalloc(sizeof(*x)); 441 x->pattern = string; 442} 443 x->patternlen = patternlen; 444 x->nowildcardlen = nowildcardlen; 445 x->base = base; 446 x->baselen = baselen; 447 x->flags = flags; 448 x->srcpos = srcpos; 449ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 450 el->excludes[el->nr++] = x; 451 x->el = el; 452} 453 454static void*read_skip_worktree_file_from_index(const char*path,size_t*size) 455{ 456int pos, len; 457unsigned long sz; 458enum object_type type; 459void*data; 460 461 len =strlen(path); 462 pos =cache_name_pos(path, len); 463if(pos <0) 464return NULL; 465if(!ce_skip_worktree(active_cache[pos])) 466return NULL; 467 data =read_sha1_file(active_cache[pos]->sha1, &type, &sz); 468if(!data || type != OBJ_BLOB) { 469free(data); 470return NULL; 471} 472*size =xsize_t(sz); 473return data; 474} 475 476/* 477 * Frees memory within el which was allocated for exclude patterns and 478 * the file buffer. Does not free el itself. 479 */ 480voidclear_exclude_list(struct exclude_list *el) 481{ 482int i; 483 484for(i =0; i < el->nr; i++) 485free(el->excludes[i]); 486free(el->excludes); 487free(el->filebuf); 488 489 el->nr =0; 490 el->excludes = NULL; 491 el->filebuf = NULL; 492} 493 494intadd_excludes_from_file_to_list(const char*fname, 495const char*base, 496int baselen, 497struct exclude_list *el, 498int check_index) 499{ 500struct stat st; 501int fd, i, lineno =1; 502size_t size =0; 503char*buf, *entry; 504 505 fd =open(fname, O_RDONLY); 506if(fd <0||fstat(fd, &st) <0) { 507if(errno != ENOENT) 508warn_on_inaccessible(fname); 509if(0<= fd) 510close(fd); 511if(!check_index || 512(buf =read_skip_worktree_file_from_index(fname, &size)) == NULL) 513return-1; 514if(size ==0) { 515free(buf); 516return0; 517} 518if(buf[size-1] !='\n') { 519 buf =xrealloc(buf, size+1); 520 buf[size++] ='\n'; 521} 522} 523else{ 524 size =xsize_t(st.st_size); 525if(size ==0) { 526close(fd); 527return0; 528} 529 buf =xmalloc(size+1); 530if(read_in_full(fd, buf, size) != size) { 531free(buf); 532close(fd); 533return-1; 534} 535 buf[size++] ='\n'; 536close(fd); 537} 538 539 el->filebuf = buf; 540 entry = buf; 541for(i =0; i < size; i++) { 542if(buf[i] =='\n') { 543if(entry != buf + i && entry[0] !='#') { 544 buf[i - (i && buf[i-1] =='\r')] =0; 545add_exclude(entry, base, baselen, el, lineno); 546} 547 lineno++; 548 entry = buf + i +1; 549} 550} 551return0; 552} 553 554struct exclude_list *add_exclude_list(struct dir_struct *dir, 555int group_type,const char*src) 556{ 557struct exclude_list *el; 558struct exclude_list_group *group; 559 560 group = &dir->exclude_list_group[group_type]; 561ALLOC_GROW(group->el, group->nr +1, group->alloc); 562 el = &group->el[group->nr++]; 563memset(el,0,sizeof(*el)); 564 el->src = src; 565return el; 566} 567 568/* 569 * Used to set up core.excludesfile and .git/info/exclude lists. 570 */ 571voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 572{ 573struct exclude_list *el; 574 el =add_exclude_list(dir, EXC_FILE, fname); 575if(add_excludes_from_file_to_list(fname,"",0, el,0) <0) 576die("cannot use%sas an exclude file", fname); 577} 578 579intmatch_basename(const char*basename,int basenamelen, 580const char*pattern,int prefix,int patternlen, 581int flags) 582{ 583if(prefix == patternlen) { 584if(patternlen == basenamelen && 585!strncmp_icase(pattern, basename, basenamelen)) 586return1; 587}else if(flags & EXC_FLAG_ENDSWITH) { 588/* "*literal" matching against "fooliteral" */ 589if(patternlen -1<= basenamelen && 590!strncmp_icase(pattern +1, 591 basename + basenamelen - (patternlen -1), 592 patternlen -1)) 593return1; 594}else{ 595if(fnmatch_icase_mem(pattern, patternlen, 596 basename, basenamelen, 5970) ==0) 598return1; 599} 600return0; 601} 602 603intmatch_pathname(const char*pathname,int pathlen, 604const char*base,int baselen, 605const char*pattern,int prefix,int patternlen, 606int flags) 607{ 608const char*name; 609int namelen; 610 611/* 612 * match with FNM_PATHNAME; the pattern has base implicitly 613 * in front of it. 614 */ 615if(*pattern =='/') { 616 pattern++; 617 patternlen--; 618 prefix--; 619} 620 621/* 622 * baselen does not count the trailing slash. base[] may or 623 * may not end with a trailing slash though. 624 */ 625if(pathlen < baselen +1|| 626(baselen && pathname[baselen] !='/') || 627strncmp_icase(pathname, base, baselen)) 628return0; 629 630 namelen = baselen ? pathlen - baselen -1: pathlen; 631 name = pathname + pathlen - namelen; 632 633if(prefix) { 634/* 635 * if the non-wildcard part is longer than the 636 * remaining pathname, surely it cannot match. 637 */ 638if(prefix > namelen) 639return0; 640 641if(strncmp_icase(pattern, name, prefix)) 642return0; 643 pattern += prefix; 644 patternlen -= prefix; 645 name += prefix; 646 namelen -= prefix; 647 648/* 649 * If the whole pattern did not have a wildcard, 650 * then our prefix match is all we need; we 651 * do not need to call fnmatch at all. 652 */ 653if(!patternlen && !namelen) 654return1; 655} 656 657returnfnmatch_icase_mem(pattern, patternlen, 658 name, namelen, 659 WM_PATHNAME) ==0; 660} 661 662/* 663 * Scan the given exclude list in reverse to see whether pathname 664 * should be ignored. The first match (i.e. the last on the list), if 665 * any, determines the fate. Returns the exclude_list element which 666 * matched, or NULL for undecided. 667 */ 668static struct exclude *last_exclude_matching_from_list(const char*pathname, 669int pathlen, 670const char*basename, 671int*dtype, 672struct exclude_list *el) 673{ 674int i; 675 676if(!el->nr) 677return NULL;/* undefined */ 678 679for(i = el->nr -1;0<= i; i--) { 680struct exclude *x = el->excludes[i]; 681const char*exclude = x->pattern; 682int prefix = x->nowildcardlen; 683 684if(x->flags & EXC_FLAG_MUSTBEDIR) { 685if(*dtype == DT_UNKNOWN) 686*dtype =get_dtype(NULL, pathname, pathlen); 687if(*dtype != DT_DIR) 688continue; 689} 690 691if(x->flags & EXC_FLAG_NODIR) { 692if(match_basename(basename, 693 pathlen - (basename - pathname), 694 exclude, prefix, x->patternlen, 695 x->flags)) 696return x; 697continue; 698} 699 700assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 701if(match_pathname(pathname, pathlen, 702 x->base, x->baselen ? x->baselen -1:0, 703 exclude, prefix, x->patternlen, x->flags)) 704return x; 705} 706return NULL;/* undecided */ 707} 708 709/* 710 * Scan the list and let the last match determine the fate. 711 * Return 1 for exclude, 0 for include and -1 for undecided. 712 */ 713intis_excluded_from_list(const char*pathname, 714int pathlen,const char*basename,int*dtype, 715struct exclude_list *el) 716{ 717struct exclude *exclude; 718 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 719if(exclude) 720return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 721return-1;/* undecided */ 722} 723 724static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir, 725const char*pathname,int pathlen,const char*basename, 726int*dtype_p) 727{ 728int i, j; 729struct exclude_list_group *group; 730struct exclude *exclude; 731for(i = EXC_CMDL; i <= EXC_FILE; i++) { 732 group = &dir->exclude_list_group[i]; 733for(j = group->nr -1; j >=0; j--) { 734 exclude =last_exclude_matching_from_list( 735 pathname, pathlen, basename, dtype_p, 736&group->el[j]); 737if(exclude) 738return exclude; 739} 740} 741return NULL; 742} 743 744/* 745 * Loads the per-directory exclude list for the substring of base 746 * which has a char length of baselen. 747 */ 748static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen) 749{ 750struct exclude_list_group *group; 751struct exclude_list *el; 752struct exclude_stack *stk = NULL; 753int current; 754 755 group = &dir->exclude_list_group[EXC_DIRS]; 756 757/* Pop the exclude lists from the EXCL_DIRS exclude_list_group 758 * which originate from directories not in the prefix of the 759 * path being checked. */ 760while((stk = dir->exclude_stack) != NULL) { 761if(stk->baselen <= baselen && 762!strncmp(dir->basebuf, base, stk->baselen)) 763break; 764 el = &group->el[dir->exclude_stack->exclude_ix]; 765 dir->exclude_stack = stk->prev; 766 dir->exclude = NULL; 767free((char*)el->src);/* see strdup() below */ 768clear_exclude_list(el); 769free(stk); 770 group->nr--; 771} 772 773/* Skip traversing into sub directories if the parent is excluded */ 774if(dir->exclude) 775return; 776 777/* Read from the parent directories and push them down. */ 778 current = stk ? stk->baselen : -1; 779while(current < baselen) { 780struct exclude_stack *stk =xcalloc(1,sizeof(*stk)); 781const char*cp; 782 783if(current <0) { 784 cp = base; 785 current =0; 786} 787else{ 788 cp =strchr(base + current +1,'/'); 789if(!cp) 790die("oops in prep_exclude"); 791 cp++; 792} 793 stk->prev = dir->exclude_stack; 794 stk->baselen = cp - base; 795 stk->exclude_ix = group->nr; 796 el =add_exclude_list(dir, EXC_DIRS, NULL); 797memcpy(dir->basebuf + current, base + current, 798 stk->baselen - current); 799 800/* Abort if the directory is excluded */ 801if(stk->baselen) { 802int dt = DT_DIR; 803 dir->basebuf[stk->baselen -1] =0; 804 dir->exclude =last_exclude_matching_from_lists(dir, 805 dir->basebuf, stk->baselen -1, 806 dir->basebuf + current, &dt); 807 dir->basebuf[stk->baselen -1] ='/'; 808if(dir->exclude && 809 dir->exclude->flags & EXC_FLAG_NEGATIVE) 810 dir->exclude = NULL; 811if(dir->exclude) { 812 dir->basebuf[stk->baselen] =0; 813 dir->exclude_stack = stk; 814return; 815} 816} 817 818/* Try to read per-directory file unless path is too long */ 819if(dir->exclude_per_dir && 820 stk->baselen +strlen(dir->exclude_per_dir) < PATH_MAX) { 821strcpy(dir->basebuf + stk->baselen, 822 dir->exclude_per_dir); 823/* 824 * dir->basebuf gets reused by the traversal, but we 825 * need fname to remain unchanged to ensure the src 826 * member of each struct exclude correctly 827 * back-references its source file. Other invocations 828 * of add_exclude_list provide stable strings, so we 829 * strdup() and free() here in the caller. 830 */ 831 el->src =strdup(dir->basebuf); 832add_excludes_from_file_to_list(dir->basebuf, 833 dir->basebuf, stk->baselen, el,1); 834} 835 dir->exclude_stack = stk; 836 current = stk->baselen; 837} 838 dir->basebuf[baselen] ='\0'; 839} 840 841/* 842 * Loads the exclude lists for the directory containing pathname, then 843 * scans all exclude lists to determine whether pathname is excluded. 844 * Returns the exclude_list element which matched, or NULL for 845 * undecided. 846 */ 847struct exclude *last_exclude_matching(struct dir_struct *dir, 848const char*pathname, 849int*dtype_p) 850{ 851int pathlen =strlen(pathname); 852const char*basename =strrchr(pathname,'/'); 853 basename = (basename) ? basename+1: pathname; 854 855prep_exclude(dir, pathname, basename-pathname); 856 857if(dir->exclude) 858return dir->exclude; 859 860returnlast_exclude_matching_from_lists(dir, pathname, pathlen, 861 basename, dtype_p); 862} 863 864/* 865 * Loads the exclude lists for the directory containing pathname, then 866 * scans all exclude lists to determine whether pathname is excluded. 867 * Returns 1 if true, otherwise 0. 868 */ 869intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p) 870{ 871struct exclude *exclude = 872last_exclude_matching(dir, pathname, dtype_p); 873if(exclude) 874return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 875return0; 876} 877 878static struct dir_entry *dir_entry_new(const char*pathname,int len) 879{ 880struct dir_entry *ent; 881 882 ent =xmalloc(sizeof(*ent) + len +1); 883 ent->len = len; 884memcpy(ent->name, pathname, len); 885 ent->name[len] =0; 886return ent; 887} 888 889static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len) 890{ 891if(cache_file_exists(pathname, len, ignore_case)) 892return NULL; 893 894ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc); 895return dir->entries[dir->nr++] =dir_entry_new(pathname, len); 896} 897 898struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len) 899{ 900if(!cache_name_is_other(pathname, len)) 901return NULL; 902 903ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc); 904return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len); 905} 906 907enum exist_status { 908 index_nonexistent =0, 909 index_directory, 910 index_gitdir 911}; 912 913/* 914 * Do not use the alphabetically sorted index to look up 915 * the directory name; instead, use the case insensitive 916 * directory hash. 917 */ 918static enum exist_status directory_exists_in_index_icase(const char*dirname,int len) 919{ 920const struct cache_entry *ce =cache_dir_exists(dirname, len); 921unsigned char endchar; 922 923if(!ce) 924return index_nonexistent; 925 endchar = ce->name[len]; 926 927/* 928 * The cache_entry structure returned will contain this dirname 929 * and possibly additional path components. 930 */ 931if(endchar =='/') 932return index_directory; 933 934/* 935 * If there are no additional path components, then this cache_entry 936 * represents a submodule. Submodules, despite being directories, 937 * are stored in the cache without a closing slash. 938 */ 939if(!endchar &&S_ISGITLINK(ce->ce_mode)) 940return index_gitdir; 941 942/* This should never be hit, but it exists just in case. */ 943return index_nonexistent; 944} 945 946/* 947 * The index sorts alphabetically by entry name, which 948 * means that a gitlink sorts as '\0' at the end, while 949 * a directory (which is defined not as an entry, but as 950 * the files it contains) will sort with the '/' at the 951 * end. 952 */ 953static enum exist_status directory_exists_in_index(const char*dirname,int len) 954{ 955int pos; 956 957if(ignore_case) 958returndirectory_exists_in_index_icase(dirname, len); 959 960 pos =cache_name_pos(dirname, len); 961if(pos <0) 962 pos = -pos-1; 963while(pos < active_nr) { 964const struct cache_entry *ce = active_cache[pos++]; 965unsigned char endchar; 966 967if(strncmp(ce->name, dirname, len)) 968break; 969 endchar = ce->name[len]; 970if(endchar >'/') 971break; 972if(endchar =='/') 973return index_directory; 974if(!endchar &&S_ISGITLINK(ce->ce_mode)) 975return index_gitdir; 976} 977return index_nonexistent; 978} 979 980/* 981 * When we find a directory when traversing the filesystem, we 982 * have three distinct cases: 983 * 984 * - ignore it 985 * - see it as a directory 986 * - recurse into it 987 * 988 * and which one we choose depends on a combination of existing 989 * git index contents and the flags passed into the directory 990 * traversal routine. 991 * 992 * Case 1: If we *already* have entries in the index under that 993 * directory name, we always recurse into the directory to see 994 * all the files. 995 * 996 * Case 2: If we *already* have that directory name as a gitlink, 997 * we always continue to see it as a gitlink, regardless of whether 998 * there is an actual git directory there or not (it might not 999 * be checked out as a subproject!)1000 *1001 * Case 3: if we didn't have it in the index previously, we1002 * have a few sub-cases:1003 *1004 * (a) if "show_other_directories" is true, we show it as1005 * just a directory, unless "hide_empty_directories" is1006 * also true, in which case we need to check if it contains any1007 * untracked and / or ignored files.1008 * (b) if it looks like a git directory, and we don't have1009 * 'no_gitlinks' set we treat it as a gitlink, and show it1010 * as a directory.1011 * (c) otherwise, we recurse into it.1012 */1013static enum path_treatment treat_directory(struct dir_struct *dir,1014const char*dirname,int len,int exclude,1015const struct path_simplify *simplify)1016{1017/* The "len-1" is to strip the final '/' */1018switch(directory_exists_in_index(dirname, len-1)) {1019case index_directory:1020return path_recurse;10211022case index_gitdir:1023return path_none;10241025case index_nonexistent:1026if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1027break;1028if(!(dir->flags & DIR_NO_GITLINKS)) {1029unsigned char sha1[20];1030if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1031return path_untracked;1032}1033return path_recurse;1034}10351036/* This is the "show_other_directories" case */10371038if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1039return exclude ? path_excluded : path_untracked;10401041returnread_directory_recursive(dir, dirname, len,1, simplify);1042}10431044/*1045 * This is an inexact early pruning of any recursive directory1046 * reading - if the path cannot possibly be in the pathspec,1047 * return true, and we'll skip it early.1048 */1049static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1050{1051if(simplify) {1052for(;;) {1053const char*match = simplify->path;1054int len = simplify->len;10551056if(!match)1057break;1058if(len > pathlen)1059 len = pathlen;1060if(!memcmp(path, match, len))1061return0;1062 simplify++;1063}1064return1;1065}1066return0;1067}10681069/*1070 * This function tells us whether an excluded path matches a1071 * list of "interesting" pathspecs. That is, whether a path matched1072 * by any of the pathspecs could possibly be ignored by excluding1073 * the specified path. This can happen if:1074 *1075 * 1. the path is mentioned explicitly in the pathspec1076 *1077 * 2. the path is a directory prefix of some element in the1078 * pathspec1079 */1080static intexclude_matches_pathspec(const char*path,int len,1081const struct path_simplify *simplify)1082{1083if(simplify) {1084for(; simplify->path; simplify++) {1085if(len == simplify->len1086&& !memcmp(path, simplify->path, len))1087return1;1088if(len < simplify->len1089&& simplify->path[len] =='/'1090&& !memcmp(path, simplify->path, len))1091return1;1092}1093}1094return0;1095}10961097static intget_index_dtype(const char*path,int len)1098{1099int pos;1100const struct cache_entry *ce;11011102 ce =cache_file_exists(path, len,0);1103if(ce) {1104if(!ce_uptodate(ce))1105return DT_UNKNOWN;1106if(S_ISGITLINK(ce->ce_mode))1107return DT_DIR;1108/*1109 * Nobody actually cares about the1110 * difference between DT_LNK and DT_REG1111 */1112return DT_REG;1113}11141115/* Try to look it up as a directory */1116 pos =cache_name_pos(path, len);1117if(pos >=0)1118return DT_UNKNOWN;1119 pos = -pos-1;1120while(pos < active_nr) {1121 ce = active_cache[pos++];1122if(strncmp(ce->name, path, len))1123break;1124if(ce->name[len] >'/')1125break;1126if(ce->name[len] <'/')1127continue;1128if(!ce_uptodate(ce))1129break;/* continue? */1130return DT_DIR;1131}1132return DT_UNKNOWN;1133}11341135static intget_dtype(struct dirent *de,const char*path,int len)1136{1137int dtype = de ?DTYPE(de) : DT_UNKNOWN;1138struct stat st;11391140if(dtype != DT_UNKNOWN)1141return dtype;1142 dtype =get_index_dtype(path, len);1143if(dtype != DT_UNKNOWN)1144return dtype;1145if(lstat(path, &st))1146return dtype;1147if(S_ISREG(st.st_mode))1148return DT_REG;1149if(S_ISDIR(st.st_mode))1150return DT_DIR;1151if(S_ISLNK(st.st_mode))1152return DT_LNK;1153return dtype;1154}11551156static enum path_treatment treat_one_path(struct dir_struct *dir,1157struct strbuf *path,1158const struct path_simplify *simplify,1159int dtype,struct dirent *de)1160{1161int exclude;1162int has_path_in_index = !!cache_file_exists(path->buf, path->len, ignore_case);11631164if(dtype == DT_UNKNOWN)1165 dtype =get_dtype(de, path->buf, path->len);11661167/* Always exclude indexed files */1168if(dtype != DT_DIR && has_path_in_index)1169return path_none;11701171/*1172 * When we are looking at a directory P in the working tree,1173 * there are three cases:1174 *1175 * (1) P exists in the index. Everything inside the directory P in1176 * the working tree needs to go when P is checked out from the1177 * index.1178 *1179 * (2) P does not exist in the index, but there is P/Q in the index.1180 * We know P will stay a directory when we check out the contents1181 * of the index, but we do not know yet if there is a directory1182 * P/Q in the working tree to be killed, so we need to recurse.1183 *1184 * (3) P does not exist in the index, and there is no P/Q in the index1185 * to require P to be a directory, either. Only in this case, we1186 * know that everything inside P will not be killed without1187 * recursing.1188 */1189if((dir->flags & DIR_COLLECT_KILLED_ONLY) &&1190(dtype == DT_DIR) &&1191!has_path_in_index &&1192(directory_exists_in_index(path->buf, path->len) == index_nonexistent))1193return path_none;11941195 exclude =is_excluded(dir, path->buf, &dtype);11961197/*1198 * Excluded? If we don't explicitly want to show1199 * ignored files, ignore it1200 */1201if(exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))1202return path_excluded;12031204switch(dtype) {1205default:1206return path_none;1207case DT_DIR:1208strbuf_addch(path,'/');1209returntreat_directory(dir, path->buf, path->len, exclude,1210 simplify);1211case DT_REG:1212case DT_LNK:1213return exclude ? path_excluded : path_untracked;1214}1215}12161217static enum path_treatment treat_path(struct dir_struct *dir,1218struct dirent *de,1219struct strbuf *path,1220int baselen,1221const struct path_simplify *simplify)1222{1223int dtype;12241225if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1226return path_none;1227strbuf_setlen(path, baselen);1228strbuf_addstr(path, de->d_name);1229if(simplify_away(path->buf, path->len, simplify))1230return path_none;12311232 dtype =DTYPE(de);1233returntreat_one_path(dir, path, simplify, dtype, de);1234}12351236/*1237 * Read a directory tree. We currently ignore anything but1238 * directories, regular files and symlinks. That's because git1239 * doesn't handle them at all yet. Maybe that will change some1240 * day.1241 *1242 * Also, we ignore the name ".git" (even if it is not a directory).1243 * That likely will not change.1244 *1245 * Returns the most significant path_treatment value encountered in the scan.1246 */1247static enum path_treatment read_directory_recursive(struct dir_struct *dir,1248const char*base,int baselen,1249int check_only,1250const struct path_simplify *simplify)1251{1252DIR*fdir;1253enum path_treatment state, subdir_state, dir_state = path_none;1254struct dirent *de;1255struct strbuf path = STRBUF_INIT;12561257strbuf_add(&path, base, baselen);12581259 fdir =opendir(path.len ? path.buf :".");1260if(!fdir)1261goto out;12621263while((de =readdir(fdir)) != NULL) {1264/* check how the file or directory should be treated */1265 state =treat_path(dir, de, &path, baselen, simplify);1266if(state > dir_state)1267 dir_state = state;12681269/* recurse into subdir if instructed by treat_path */1270if(state == path_recurse) {1271 subdir_state =read_directory_recursive(dir, path.buf,1272 path.len, check_only, simplify);1273if(subdir_state > dir_state)1274 dir_state = subdir_state;1275}12761277if(check_only) {1278/* abort early if maximum state has been reached */1279if(dir_state == path_untracked)1280break;1281/* skip the dir_add_* part */1282continue;1283}12841285/* add the path to the appropriate result list */1286switch(state) {1287case path_excluded:1288if(dir->flags & DIR_SHOW_IGNORED)1289dir_add_name(dir, path.buf, path.len);1290else if((dir->flags & DIR_SHOW_IGNORED_TOO) ||1291((dir->flags & DIR_COLLECT_IGNORED) &&1292exclude_matches_pathspec(path.buf, path.len,1293 simplify)))1294dir_add_ignored(dir, path.buf, path.len);1295break;12961297case path_untracked:1298if(!(dir->flags & DIR_SHOW_IGNORED))1299dir_add_name(dir, path.buf, path.len);1300break;13011302default:1303break;1304}1305}1306closedir(fdir);1307 out:1308strbuf_release(&path);13091310return dir_state;1311}13121313static intcmp_name(const void*p1,const void*p2)1314{1315const struct dir_entry *e1 = *(const struct dir_entry **)p1;1316const struct dir_entry *e2 = *(const struct dir_entry **)p2;13171318returncache_name_compare(e1->name, e1->len,1319 e2->name, e2->len);1320}13211322static struct path_simplify *create_simplify(const char**pathspec)1323{1324int nr, alloc =0;1325struct path_simplify *simplify = NULL;13261327if(!pathspec)1328return NULL;13291330for(nr =0; ; nr++) {1331const char*match;1332if(nr >= alloc) {1333 alloc =alloc_nr(alloc);1334 simplify =xrealloc(simplify, alloc *sizeof(*simplify));1335}1336 match = *pathspec++;1337if(!match)1338break;1339 simplify[nr].path = match;1340 simplify[nr].len =simple_length(match);1341}1342 simplify[nr].path = NULL;1343 simplify[nr].len =0;1344return simplify;1345}13461347static voidfree_simplify(struct path_simplify *simplify)1348{1349free(simplify);1350}13511352static inttreat_leading_path(struct dir_struct *dir,1353const char*path,int len,1354const struct path_simplify *simplify)1355{1356struct strbuf sb = STRBUF_INIT;1357int baselen, rc =0;1358const char*cp;1359int old_flags = dir->flags;13601361while(len && path[len -1] =='/')1362 len--;1363if(!len)1364return1;1365 baselen =0;1366 dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;1367while(1) {1368 cp = path + baselen + !!baselen;1369 cp =memchr(cp,'/', path + len - cp);1370if(!cp)1371 baselen = len;1372else1373 baselen = cp - path;1374strbuf_setlen(&sb,0);1375strbuf_add(&sb, path, baselen);1376if(!is_directory(sb.buf))1377break;1378if(simplify_away(sb.buf, sb.len, simplify))1379break;1380if(treat_one_path(dir, &sb, simplify,1381 DT_DIR, NULL) == path_none)1382break;/* do not recurse into it */1383if(len <= baselen) {1384 rc =1;1385break;/* finished checking */1386}1387}1388strbuf_release(&sb);1389 dir->flags = old_flags;1390return rc;1391}13921393intread_directory(struct dir_struct *dir,const char*path,int len,const struct pathspec *pathspec)1394{1395struct path_simplify *simplify;13961397/*1398 * Check out create_simplify()1399 */1400if(pathspec)1401GUARD_PATHSPEC(pathspec,1402 PATHSPEC_FROMTOP |1403 PATHSPEC_MAXDEPTH |1404 PATHSPEC_LITERAL |1405 PATHSPEC_GLOB |1406 PATHSPEC_ICASE |1407 PATHSPEC_EXCLUDE);14081409if(has_symlink_leading_path(path, len))1410return dir->nr;14111412/*1413 * exclude patterns are treated like positive ones in1414 * create_simplify. Usually exclude patterns should be a1415 * subset of positive ones, which has no impacts on1416 * create_simplify().1417 */1418 simplify =create_simplify(pathspec ? pathspec->_raw : NULL);1419if(!len ||treat_leading_path(dir, path, len, simplify))1420read_directory_recursive(dir, path, len,0, simplify);1421free_simplify(simplify);1422qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);1423qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);1424return dir->nr;1425}14261427intfile_exists(const char*f)1428{1429struct stat sb;1430returnlstat(f, &sb) ==0;1431}14321433/*1434 * Given two normalized paths (a trailing slash is ok), if subdir is1435 * outside dir, return -1. Otherwise return the offset in subdir that1436 * can be used as relative path to dir.1437 */1438intdir_inside_of(const char*subdir,const char*dir)1439{1440int offset =0;14411442assert(dir && subdir && *dir && *subdir);14431444while(*dir && *subdir && *dir == *subdir) {1445 dir++;1446 subdir++;1447 offset++;1448}14491450/* hel[p]/me vs hel[l]/yeah */1451if(*dir && *subdir)1452return-1;14531454if(!*subdir)1455return!*dir ? offset : -1;/* same dir */14561457/* foo/[b]ar vs foo/[] */1458if(is_dir_sep(dir[-1]))1459returnis_dir_sep(subdir[-1]) ? offset : -1;14601461/* foo[/]bar vs foo[] */1462returnis_dir_sep(*subdir) ? offset +1: -1;1463}14641465intis_inside_dir(const char*dir)1466{1467char cwd[PATH_MAX];1468if(!dir)1469return0;1470if(!getcwd(cwd,sizeof(cwd)))1471die_errno("can't find the current directory");1472returndir_inside_of(cwd, dir) >=0;1473}14741475intis_empty_dir(const char*path)1476{1477DIR*dir =opendir(path);1478struct dirent *e;1479int ret =1;14801481if(!dir)1482return0;14831484while((e =readdir(dir)) != NULL)1485if(!is_dot_or_dotdot(e->d_name)) {1486 ret =0;1487break;1488}14891490closedir(dir);1491return ret;1492}14931494static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)1495{1496DIR*dir;1497struct dirent *e;1498int ret =0, original_len = path->len, len, kept_down =0;1499int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);1500int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);1501unsigned char submodule_head[20];15021503if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&1504!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {1505/* Do not descend and nuke a nested git work tree. */1506if(kept_up)1507*kept_up =1;1508return0;1509}15101511 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;1512 dir =opendir(path->buf);1513if(!dir) {1514/* an empty dir could be removed even if it is unreadble */1515if(!keep_toplevel)1516returnrmdir(path->buf);1517else1518return-1;1519}1520if(path->buf[original_len -1] !='/')1521strbuf_addch(path,'/');15221523 len = path->len;1524while((e =readdir(dir)) != NULL) {1525struct stat st;1526if(is_dot_or_dotdot(e->d_name))1527continue;15281529strbuf_setlen(path, len);1530strbuf_addstr(path, e->d_name);1531if(lstat(path->buf, &st))1532;/* fall thru */1533else if(S_ISDIR(st.st_mode)) {1534if(!remove_dir_recurse(path, flag, &kept_down))1535continue;/* happy */1536}else if(!only_empty && !unlink(path->buf))1537continue;/* happy, too */15381539/* path too long, stat fails, or non-directory still exists */1540 ret = -1;1541break;1542}1543closedir(dir);15441545strbuf_setlen(path, original_len);1546if(!ret && !keep_toplevel && !kept_down)1547 ret =rmdir(path->buf);1548else if(kept_up)1549/*1550 * report the uplevel that it is not an error that we1551 * did not rmdir() our directory.1552 */1553*kept_up = !ret;1554return ret;1555}15561557intremove_dir_recursively(struct strbuf *path,int flag)1558{1559returnremove_dir_recurse(path, flag, NULL);1560}15611562voidsetup_standard_excludes(struct dir_struct *dir)1563{1564const char*path;1565char*xdg_path;15661567 dir->exclude_per_dir =".gitignore";1568 path =git_path("info/exclude");1569if(!excludes_file) {1570home_config_paths(NULL, &xdg_path,"ignore");1571 excludes_file = xdg_path;1572}1573if(!access_or_warn(path, R_OK,0))1574add_excludes_from_file(dir, path);1575if(excludes_file && !access_or_warn(excludes_file, R_OK,0))1576add_excludes_from_file(dir, excludes_file);1577}15781579intremove_path(const char*name)1580{1581char*slash;15821583if(unlink(name) && errno != ENOENT && errno != ENOTDIR)1584return-1;15851586 slash =strrchr(name,'/');1587if(slash) {1588char*dirs =xstrdup(name);1589 slash = dirs + (slash - name);1590do{1591*slash ='\0';1592}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));1593free(dirs);1594}1595return0;1596}15971598/*1599 * Frees memory within dir which was allocated for exclude lists and1600 * the exclude_stack. Does not free dir itself.1601 */1602voidclear_directory(struct dir_struct *dir)1603{1604int i, j;1605struct exclude_list_group *group;1606struct exclude_list *el;1607struct exclude_stack *stk;16081609for(i = EXC_CMDL; i <= EXC_FILE; i++) {1610 group = &dir->exclude_list_group[i];1611for(j =0; j < group->nr; j++) {1612 el = &group->el[j];1613if(i == EXC_DIRS)1614free((char*)el->src);1615clear_exclude_list(el);1616}1617free(group->el);1618}16191620 stk = dir->exclude_stack;1621while(stk) {1622struct exclude_stack *prev = stk->prev;1623free(stk);1624 stk = prev;1625}1626}