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 14struct path_simplify { 15int len; 16const char*path; 17}; 18 19static intread_directory_recursive(struct dir_struct *dir,const char*path,int len, 20int check_only,const struct path_simplify *simplify); 21static intget_dtype(struct dirent *de,const char*path,int len); 22 23/* helper string functions with support for the ignore_case flag */ 24intstrcmp_icase(const char*a,const char*b) 25{ 26return ignore_case ?strcasecmp(a, b) :strcmp(a, b); 27} 28 29intstrncmp_icase(const char*a,const char*b,size_t count) 30{ 31return ignore_case ?strncasecmp(a, b, count) :strncmp(a, b, count); 32} 33 34intfnmatch_icase(const char*pattern,const char*string,int flags) 35{ 36returnfnmatch(pattern, string, flags | (ignore_case ? FNM_CASEFOLD :0)); 37} 38 39static size_tcommon_prefix_len(const char**pathspec) 40{ 41const char*n, *first; 42size_t max =0; 43 44if(!pathspec) 45return max; 46 47 first = *pathspec; 48while((n = *pathspec++)) { 49size_t i, len =0; 50for(i =0; first == n || i < max; i++) { 51char c = n[i]; 52if(!c || c != first[i] ||is_glob_special(c)) 53break; 54if(c =='/') 55 len = i +1; 56} 57if(first == n || len < max) { 58 max = len; 59if(!max) 60break; 61} 62} 63return max; 64} 65 66/* 67 * Returns a copy of the longest leading path common among all 68 * pathspecs. 69 */ 70char*common_prefix(const char**pathspec) 71{ 72unsigned long len =common_prefix_len(pathspec); 73 74return len ?xmemdupz(*pathspec, len) : NULL; 75} 76 77intfill_directory(struct dir_struct *dir,const char**pathspec) 78{ 79size_t len; 80 81/* 82 * Calculate common prefix for the pathspec, and 83 * use that to optimize the directory walk 84 */ 85 len =common_prefix_len(pathspec); 86 87/* Read the directory and prune it */ 88read_directory(dir, pathspec ? *pathspec :"", len, pathspec); 89return len; 90} 91 92intwithin_depth(const char*name,int namelen, 93int depth,int max_depth) 94{ 95const char*cp = name, *cpe = name + namelen; 96 97while(cp < cpe) { 98if(*cp++ !='/') 99continue; 100 depth++; 101if(depth > max_depth) 102return0; 103} 104return1; 105} 106 107/* 108 * Does 'match' match the given name? 109 * A match is found if 110 * 111 * (1) the 'match' string is leading directory of 'name', or 112 * (2) the 'match' string is a wildcard and matches 'name', or 113 * (3) the 'match' string is exactly the same as 'name'. 114 * 115 * and the return value tells which case it was. 116 * 117 * It returns 0 when there is no match. 118 */ 119static intmatch_one(const char*match,const char*name,int namelen) 120{ 121int matchlen; 122 123/* If the match was just the prefix, we matched */ 124if(!*match) 125return MATCHED_RECURSIVELY; 126 127if(ignore_case) { 128for(;;) { 129unsigned char c1 =tolower(*match); 130unsigned char c2 =tolower(*name); 131if(c1 =='\0'||is_glob_special(c1)) 132break; 133if(c1 != c2) 134return0; 135 match++; 136 name++; 137 namelen--; 138} 139}else{ 140for(;;) { 141unsigned char c1 = *match; 142unsigned char c2 = *name; 143if(c1 =='\0'||is_glob_special(c1)) 144break; 145if(c1 != c2) 146return0; 147 match++; 148 name++; 149 namelen--; 150} 151} 152 153 154/* 155 * If we don't match the matchstring exactly, 156 * we need to match by fnmatch 157 */ 158 matchlen =strlen(match); 159if(strncmp_icase(match, name, matchlen)) 160return!fnmatch_icase(match, name,0) ? MATCHED_FNMATCH :0; 161 162if(namelen == matchlen) 163return MATCHED_EXACTLY; 164if(match[matchlen-1] =='/'|| name[matchlen] =='/') 165return MATCHED_RECURSIVELY; 166return0; 167} 168 169/* 170 * Given a name and a list of pathspecs, returns the nature of the 171 * closest (i.e. most specific) match of the name to any of the 172 * pathspecs. 173 * 174 * The caller typically calls this multiple times with the same 175 * pathspec and seen[] array but with different name/namelen 176 * (e.g. entries from the index) and is interested in seeing if and 177 * how each pathspec matches all the names it calls this function 178 * with. A mark is left in the seen[] array for each pathspec element 179 * indicating the closest type of match that element achieved, so if 180 * seen[n] remains zero after multiple invocations, that means the nth 181 * pathspec did not match any names, which could indicate that the 182 * user mistyped the nth pathspec. 183 */ 184intmatch_pathspec(const char**pathspec,const char*name,int namelen, 185int prefix,char*seen) 186{ 187int i, retval =0; 188 189if(!pathspec) 190return1; 191 192 name += prefix; 193 namelen -= prefix; 194 195for(i =0; pathspec[i] != NULL; i++) { 196int how; 197const char*match = pathspec[i] + prefix; 198if(seen && seen[i] == MATCHED_EXACTLY) 199continue; 200 how =match_one(match, name, namelen); 201if(how) { 202if(retval < how) 203 retval = how; 204if(seen && seen[i] < how) 205 seen[i] = how; 206} 207} 208return retval; 209} 210 211/* 212 * Does 'match' match the given name? 213 * A match is found if 214 * 215 * (1) the 'match' string is leading directory of 'name', or 216 * (2) the 'match' string is a wildcard and matches 'name', or 217 * (3) the 'match' string is exactly the same as 'name'. 218 * 219 * and the return value tells which case it was. 220 * 221 * It returns 0 when there is no match. 222 */ 223static intmatch_pathspec_item(const struct pathspec_item *item,int prefix, 224const char*name,int namelen) 225{ 226/* name/namelen has prefix cut off by caller */ 227const char*match = item->match + prefix; 228int matchlen = item->len - prefix; 229 230/* If the match was just the prefix, we matched */ 231if(!*match) 232return MATCHED_RECURSIVELY; 233 234if(matchlen <= namelen && !strncmp(match, name, matchlen)) { 235if(matchlen == namelen) 236return MATCHED_EXACTLY; 237 238if(match[matchlen-1] =='/'|| name[matchlen] =='/') 239return MATCHED_RECURSIVELY; 240} 241 242if(item->use_wildcard && !fnmatch(match, name,0)) 243return MATCHED_FNMATCH; 244 245return0; 246} 247 248/* 249 * Given a name and a list of pathspecs, returns the nature of the 250 * closest (i.e. most specific) match of the name to any of the 251 * pathspecs. 252 * 253 * The caller typically calls this multiple times with the same 254 * pathspec and seen[] array but with different name/namelen 255 * (e.g. entries from the index) and is interested in seeing if and 256 * how each pathspec matches all the names it calls this function 257 * with. A mark is left in the seen[] array for each pathspec element 258 * indicating the closest type of match that element achieved, so if 259 * seen[n] remains zero after multiple invocations, that means the nth 260 * pathspec did not match any names, which could indicate that the 261 * user mistyped the nth pathspec. 262 */ 263intmatch_pathspec_depth(const struct pathspec *ps, 264const char*name,int namelen, 265int prefix,char*seen) 266{ 267int i, retval =0; 268 269if(!ps->nr) { 270if(!ps->recursive || ps->max_depth == -1) 271return MATCHED_RECURSIVELY; 272 273if(within_depth(name, namelen,0, ps->max_depth)) 274return MATCHED_EXACTLY; 275else 276return0; 277} 278 279 name += prefix; 280 namelen -= prefix; 281 282for(i = ps->nr -1; i >=0; i--) { 283int how; 284if(seen && seen[i] == MATCHED_EXACTLY) 285continue; 286 how =match_pathspec_item(ps->items+i, prefix, name, namelen); 287if(ps->recursive && ps->max_depth != -1&& 288 how && how != MATCHED_FNMATCH) { 289int len = ps->items[i].len; 290if(name[len] =='/') 291 len++; 292if(within_depth(name+len, namelen-len,0, ps->max_depth)) 293 how = MATCHED_EXACTLY; 294else 295 how =0; 296} 297if(how) { 298if(retval < how) 299 retval = how; 300if(seen && seen[i] < how) 301 seen[i] = how; 302} 303} 304return retval; 305} 306 307/* 308 * Return the length of the "simple" part of a path match limiter. 309 */ 310static intsimple_length(const char*match) 311{ 312int len = -1; 313 314for(;;) { 315unsigned char c = *match++; 316 len++; 317if(c =='\0'||is_glob_special(c)) 318return len; 319} 320} 321 322static intno_wildcard(const char*string) 323{ 324return string[simple_length(string)] =='\0'; 325} 326 327voidparse_exclude_pattern(const char**pattern, 328int*patternlen, 329int*flags, 330int*nowildcardlen) 331{ 332const char*p = *pattern; 333size_t i, len; 334 335*flags =0; 336if(*p =='!') { 337*flags |= EXC_FLAG_NEGATIVE; 338 p++; 339} 340 len =strlen(p); 341if(len && p[len -1] =='/') { 342 len--; 343*flags |= EXC_FLAG_MUSTBEDIR; 344} 345for(i =0; i < len; i++) { 346if(p[i] =='/') 347break; 348} 349if(i == len) 350*flags |= EXC_FLAG_NODIR; 351*nowildcardlen =simple_length(p); 352/* 353 * we should have excluded the trailing slash from 'p' too, 354 * but that's one more allocation. Instead just make sure 355 * nowildcardlen does not exceed real patternlen 356 */ 357if(*nowildcardlen > len) 358*nowildcardlen = len; 359if(*p =='*'&&no_wildcard(p +1)) 360*flags |= EXC_FLAG_ENDSWITH; 361*pattern = p; 362*patternlen = len; 363} 364 365voidadd_exclude(const char*string,const char*base, 366int baselen,struct exclude_list *el,int srcpos) 367{ 368struct exclude *x; 369int patternlen; 370int flags; 371int nowildcardlen; 372 373parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen); 374if(flags & EXC_FLAG_MUSTBEDIR) { 375char*s; 376 x =xmalloc(sizeof(*x) + patternlen +1); 377 s = (char*)(x+1); 378memcpy(s, string, patternlen); 379 s[patternlen] ='\0'; 380 x->pattern = s; 381}else{ 382 x =xmalloc(sizeof(*x)); 383 x->pattern = string; 384} 385 x->patternlen = patternlen; 386 x->nowildcardlen = nowildcardlen; 387 x->base = base; 388 x->baselen = baselen; 389 x->flags = flags; 390 x->srcpos = srcpos; 391ALLOC_GROW(el->excludes, el->nr +1, el->alloc); 392 el->excludes[el->nr++] = x; 393 x->el = el; 394} 395 396static void*read_skip_worktree_file_from_index(const char*path,size_t*size) 397{ 398int pos, len; 399unsigned long sz; 400enum object_type type; 401void*data; 402struct index_state *istate = &the_index; 403 404 len =strlen(path); 405 pos =index_name_pos(istate, path, len); 406if(pos <0) 407return NULL; 408if(!ce_skip_worktree(istate->cache[pos])) 409return NULL; 410 data =read_sha1_file(istate->cache[pos]->sha1, &type, &sz); 411if(!data || type != OBJ_BLOB) { 412free(data); 413return NULL; 414} 415*size =xsize_t(sz); 416return data; 417} 418 419/* 420 * Frees memory within el which was allocated for exclude patterns and 421 * the file buffer. Does not free el itself. 422 */ 423voidclear_exclude_list(struct exclude_list *el) 424{ 425int i; 426 427for(i =0; i < el->nr; i++) 428free(el->excludes[i]); 429free(el->excludes); 430free(el->filebuf); 431 432 el->nr =0; 433 el->excludes = NULL; 434 el->filebuf = NULL; 435} 436 437intadd_excludes_from_file_to_list(const char*fname, 438const char*base, 439int baselen, 440struct exclude_list *el, 441int check_index) 442{ 443struct stat st; 444int fd, i, lineno =1; 445size_t size =0; 446char*buf, *entry; 447 448 fd =open(fname, O_RDONLY); 449if(fd <0||fstat(fd, &st) <0) { 450if(0<= fd) 451close(fd); 452if(!check_index || 453(buf =read_skip_worktree_file_from_index(fname, &size)) == NULL) 454return-1; 455if(size ==0) { 456free(buf); 457return0; 458} 459if(buf[size-1] !='\n') { 460 buf =xrealloc(buf, size+1); 461 buf[size++] ='\n'; 462} 463} 464else{ 465 size =xsize_t(st.st_size); 466if(size ==0) { 467close(fd); 468return0; 469} 470 buf =xmalloc(size+1); 471if(read_in_full(fd, buf, size) != size) { 472free(buf); 473close(fd); 474return-1; 475} 476 buf[size++] ='\n'; 477close(fd); 478} 479 480 el->filebuf = buf; 481 entry = buf; 482for(i =0; i < size; i++) { 483if(buf[i] =='\n') { 484if(entry != buf + i && entry[0] !='#') { 485 buf[i - (i && buf[i-1] =='\r')] =0; 486add_exclude(entry, base, baselen, el, lineno); 487} 488 lineno++; 489 entry = buf + i +1; 490} 491} 492return0; 493} 494 495struct exclude_list *add_exclude_list(struct dir_struct *dir, 496int group_type,const char*src) 497{ 498struct exclude_list *el; 499struct exclude_list_group *group; 500 501 group = &dir->exclude_list_group[group_type]; 502ALLOC_GROW(group->el, group->nr +1, group->alloc); 503 el = &group->el[group->nr++]; 504memset(el,0,sizeof(*el)); 505 el->src = src; 506return el; 507} 508 509/* 510 * Used to set up core.excludesfile and .git/info/exclude lists. 511 */ 512voidadd_excludes_from_file(struct dir_struct *dir,const char*fname) 513{ 514struct exclude_list *el; 515 el =add_exclude_list(dir, EXC_FILE, fname); 516if(add_excludes_from_file_to_list(fname,"",0, el,0) <0) 517die("cannot use%sas an exclude file", fname); 518} 519 520/* 521 * Loads the per-directory exclude list for the substring of base 522 * which has a char length of baselen. 523 */ 524static voidprep_exclude(struct dir_struct *dir,const char*base,int baselen) 525{ 526struct exclude_list_group *group; 527struct exclude_list *el; 528struct exclude_stack *stk = NULL; 529int current; 530 531if((!dir->exclude_per_dir) || 532(baselen +strlen(dir->exclude_per_dir) >= PATH_MAX)) 533return;/* too long a path -- ignore */ 534 535 group = &dir->exclude_list_group[EXC_DIRS]; 536 537/* Pop the exclude lists from the EXCL_DIRS exclude_list_group 538 * which originate from directories not in the prefix of the 539 * path being checked. */ 540while((stk = dir->exclude_stack) != NULL) { 541if(stk->baselen <= baselen && 542!strncmp(dir->basebuf, base, stk->baselen)) 543break; 544 el = &group->el[dir->exclude_stack->exclude_ix]; 545 dir->exclude_stack = stk->prev; 546free((char*)el->src);/* see strdup() below */ 547clear_exclude_list(el); 548free(stk); 549 group->nr--; 550} 551 552/* Read from the parent directories and push them down. */ 553 current = stk ? stk->baselen : -1; 554while(current < baselen) { 555struct exclude_stack *stk =xcalloc(1,sizeof(*stk)); 556const char*cp; 557 558if(current <0) { 559 cp = base; 560 current =0; 561} 562else{ 563 cp =strchr(base + current +1,'/'); 564if(!cp) 565die("oops in prep_exclude"); 566 cp++; 567} 568 stk->prev = dir->exclude_stack; 569 stk->baselen = cp - base; 570memcpy(dir->basebuf + current, base + current, 571 stk->baselen - current); 572strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir); 573/* 574 * dir->basebuf gets reused by the traversal, but we 575 * need fname to remain unchanged to ensure the src 576 * member of each struct exclude correctly 577 * back-references its source file. Other invocations 578 * of add_exclude_list provide stable strings, so we 579 * strdup() and free() here in the caller. 580 */ 581 el =add_exclude_list(dir, EXC_DIRS,strdup(dir->basebuf)); 582 stk->exclude_ix = group->nr -1; 583add_excludes_from_file_to_list(dir->basebuf, 584 dir->basebuf, stk->baselen, 585 el,1); 586 dir->exclude_stack = stk; 587 current = stk->baselen; 588} 589 dir->basebuf[baselen] ='\0'; 590} 591 592intmatch_basename(const char*basename,int basenamelen, 593const char*pattern,int prefix,int patternlen, 594int flags) 595{ 596if(prefix == patternlen) { 597if(!strcmp_icase(pattern, basename)) 598return1; 599}else if(flags & EXC_FLAG_ENDSWITH) { 600if(patternlen -1<= basenamelen && 601!strcmp_icase(pattern +1, 602 basename + basenamelen - patternlen +1)) 603return1; 604}else{ 605if(fnmatch_icase(pattern, basename,0) ==0) 606return1; 607} 608return0; 609} 610 611intmatch_pathname(const char*pathname,int pathlen, 612const char*base,int baselen, 613const char*pattern,int prefix,int patternlen, 614int flags) 615{ 616const char*name; 617int namelen; 618 619/* 620 * match with FNM_PATHNAME; the pattern has base implicitly 621 * in front of it. 622 */ 623if(*pattern =='/') { 624 pattern++; 625 prefix--; 626} 627 628/* 629 * baselen does not count the trailing slash. base[] may or 630 * may not end with a trailing slash though. 631 */ 632if(pathlen < baselen +1|| 633(baselen && pathname[baselen] !='/') || 634strncmp_icase(pathname, base, baselen)) 635return0; 636 637 namelen = baselen ? pathlen - baselen -1: pathlen; 638 name = pathname + pathlen - namelen; 639 640if(prefix) { 641/* 642 * if the non-wildcard part is longer than the 643 * remaining pathname, surely it cannot match. 644 */ 645if(prefix > namelen) 646return0; 647 648if(strncmp_icase(pattern, name, prefix)) 649return0; 650 pattern += prefix; 651 name += prefix; 652 namelen -= prefix; 653} 654 655returnfnmatch_icase(pattern, name, FNM_PATHNAME) ==0; 656} 657 658/* 659 * Scan the given exclude list in reverse to see whether pathname 660 * should be ignored. The first match (i.e. the last on the list), if 661 * any, determines the fate. Returns the exclude_list element which 662 * matched, or NULL for undecided. 663 */ 664static struct exclude *last_exclude_matching_from_list(const char*pathname, 665int pathlen, 666const char*basename, 667int*dtype, 668struct exclude_list *el) 669{ 670int i; 671 672if(!el->nr) 673return NULL;/* undefined */ 674 675for(i = el->nr -1;0<= i; i--) { 676struct exclude *x = el->excludes[i]; 677const char*exclude = x->pattern; 678int prefix = x->nowildcardlen; 679 680if(x->flags & EXC_FLAG_MUSTBEDIR) { 681if(*dtype == DT_UNKNOWN) 682*dtype =get_dtype(NULL, pathname, pathlen); 683if(*dtype != DT_DIR) 684continue; 685} 686 687if(x->flags & EXC_FLAG_NODIR) { 688if(match_basename(basename, 689 pathlen - (basename - pathname), 690 exclude, prefix, x->patternlen, 691 x->flags)) 692return x; 693continue; 694} 695 696assert(x->baselen ==0|| x->base[x->baselen -1] =='/'); 697if(match_pathname(pathname, pathlen, 698 x->base, x->baselen ? x->baselen -1:0, 699 exclude, prefix, x->patternlen, x->flags)) 700return x; 701} 702return NULL;/* undecided */ 703} 704 705/* 706 * Scan the list and let the last match determine the fate. 707 * Return 1 for exclude, 0 for include and -1 for undecided. 708 */ 709intis_excluded_from_list(const char*pathname, 710int pathlen,const char*basename,int*dtype, 711struct exclude_list *el) 712{ 713struct exclude *exclude; 714 exclude =last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el); 715if(exclude) 716return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 717return-1;/* undecided */ 718} 719 720/* 721 * Loads the exclude lists for the directory containing pathname, then 722 * scans all exclude lists to determine whether pathname is excluded. 723 * Returns the exclude_list element which matched, or NULL for 724 * undecided. 725 */ 726static struct exclude *last_exclude_matching(struct dir_struct *dir, 727const char*pathname, 728int*dtype_p) 729{ 730int pathlen =strlen(pathname); 731int i, j; 732struct exclude_list_group *group; 733struct exclude *exclude; 734const char*basename =strrchr(pathname,'/'); 735 basename = (basename) ? basename+1: pathname; 736 737prep_exclude(dir, pathname, basename-pathname); 738 739for(i = EXC_CMDL; i <= EXC_FILE; i++) { 740 group = &dir->exclude_list_group[i]; 741for(j = group->nr -1; j >=0; j--) { 742 exclude =last_exclude_matching_from_list( 743 pathname, pathlen, basename, dtype_p, 744&group->el[j]); 745if(exclude) 746return exclude; 747} 748} 749return NULL; 750} 751 752/* 753 * Loads the exclude lists for the directory containing pathname, then 754 * scans all exclude lists to determine whether pathname is excluded. 755 * Returns 1 if true, otherwise 0. 756 */ 757static intis_excluded(struct dir_struct *dir,const char*pathname,int*dtype_p) 758{ 759struct exclude *exclude = 760last_exclude_matching(dir, pathname, dtype_p); 761if(exclude) 762return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 763return0; 764} 765 766voidpath_exclude_check_init(struct path_exclude_check *check, 767struct dir_struct *dir) 768{ 769 check->dir = dir; 770 check->exclude = NULL; 771strbuf_init(&check->path,256); 772} 773 774voidpath_exclude_check_clear(struct path_exclude_check *check) 775{ 776strbuf_release(&check->path); 777} 778 779/* 780 * For each subdirectory in name, starting with the top-most, checks 781 * to see if that subdirectory is excluded, and if so, returns the 782 * corresponding exclude structure. Otherwise, checks whether name 783 * itself (which is presumably a file) is excluded. 784 * 785 * A path to a directory known to be excluded is left in check->path to 786 * optimize for repeated checks for files in the same excluded directory. 787 */ 788struct exclude *last_exclude_matching_path(struct path_exclude_check *check, 789const char*name,int namelen, 790int*dtype) 791{ 792int i; 793struct strbuf *path = &check->path; 794struct exclude *exclude; 795 796/* 797 * we allow the caller to pass namelen as an optimization; it 798 * must match the length of the name, as we eventually call 799 * is_excluded() on the whole name string. 800 */ 801if(namelen <0) 802 namelen =strlen(name); 803 804/* 805 * If path is non-empty, and name is equal to path or a 806 * subdirectory of path, name should be excluded, because 807 * it's inside a directory which is already known to be 808 * excluded and was previously left in check->path. 809 */ 810if(path->len && 811 path->len <= namelen && 812!memcmp(name, path->buf, path->len) && 813(!name[path->len] || name[path->len] =='/')) 814return check->exclude; 815 816strbuf_setlen(path,0); 817for(i =0; name[i]; i++) { 818int ch = name[i]; 819 820if(ch =='/') { 821int dt = DT_DIR; 822 exclude =last_exclude_matching(check->dir, 823 path->buf, &dt); 824if(exclude) { 825 check->exclude = exclude; 826return exclude; 827} 828} 829strbuf_addch(path, ch); 830} 831 832/* An entry in the index; cannot be a directory with subentries */ 833strbuf_setlen(path,0); 834 835returnlast_exclude_matching(check->dir, name, dtype); 836} 837 838/* 839 * Is this name excluded? This is for a caller like show_files() that 840 * do not honor directory hierarchy and iterate through paths that are 841 * possibly in an ignored directory. 842 */ 843intis_path_excluded(struct path_exclude_check *check, 844const char*name,int namelen,int*dtype) 845{ 846struct exclude *exclude = 847last_exclude_matching_path(check, name, namelen, dtype); 848if(exclude) 849return exclude->flags & EXC_FLAG_NEGATIVE ?0:1; 850return0; 851} 852 853static struct dir_entry *dir_entry_new(const char*pathname,int len) 854{ 855struct dir_entry *ent; 856 857 ent =xmalloc(sizeof(*ent) + len +1); 858 ent->len = len; 859memcpy(ent->name, pathname, len); 860 ent->name[len] =0; 861return ent; 862} 863 864static struct dir_entry *dir_add_name(struct dir_struct *dir,const char*pathname,int len) 865{ 866if(cache_name_exists(pathname, len, ignore_case)) 867return NULL; 868 869ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc); 870return dir->entries[dir->nr++] =dir_entry_new(pathname, len); 871} 872 873struct dir_entry *dir_add_ignored(struct dir_struct *dir,const char*pathname,int len) 874{ 875if(!cache_name_is_other(pathname, len)) 876return NULL; 877 878ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc); 879return dir->ignored[dir->ignored_nr++] =dir_entry_new(pathname, len); 880} 881 882enum exist_status { 883 index_nonexistent =0, 884 index_directory, 885 index_gitdir 886}; 887 888/* 889 * Do not use the alphabetically stored index to look up 890 * the directory name; instead, use the case insensitive 891 * name hash. 892 */ 893static enum exist_status directory_exists_in_index_icase(const char*dirname,int len) 894{ 895struct cache_entry *ce =index_name_exists(&the_index, dirname, len +1, ignore_case); 896unsigned char endchar; 897 898if(!ce) 899return index_nonexistent; 900 endchar = ce->name[len]; 901 902/* 903 * The cache_entry structure returned will contain this dirname 904 * and possibly additional path components. 905 */ 906if(endchar =='/') 907return index_directory; 908 909/* 910 * If there are no additional path components, then this cache_entry 911 * represents a submodule. Submodules, despite being directories, 912 * are stored in the cache without a closing slash. 913 */ 914if(!endchar &&S_ISGITLINK(ce->ce_mode)) 915return index_gitdir; 916 917/* This should never be hit, but it exists just in case. */ 918return index_nonexistent; 919} 920 921/* 922 * The index sorts alphabetically by entry name, which 923 * means that a gitlink sorts as '\0' at the end, while 924 * a directory (which is defined not as an entry, but as 925 * the files it contains) will sort with the '/' at the 926 * end. 927 */ 928static enum exist_status directory_exists_in_index(const char*dirname,int len) 929{ 930int pos; 931 932if(ignore_case) 933returndirectory_exists_in_index_icase(dirname, len); 934 935 pos =cache_name_pos(dirname, len); 936if(pos <0) 937 pos = -pos-1; 938while(pos < active_nr) { 939struct cache_entry *ce = active_cache[pos++]; 940unsigned char endchar; 941 942if(strncmp(ce->name, dirname, len)) 943break; 944 endchar = ce->name[len]; 945if(endchar >'/') 946break; 947if(endchar =='/') 948return index_directory; 949if(!endchar &&S_ISGITLINK(ce->ce_mode)) 950return index_gitdir; 951} 952return index_nonexistent; 953} 954 955/* 956 * When we find a directory when traversing the filesystem, we 957 * have three distinct cases: 958 * 959 * - ignore it 960 * - see it as a directory 961 * - recurse into it 962 * 963 * and which one we choose depends on a combination of existing 964 * git index contents and the flags passed into the directory 965 * traversal routine. 966 * 967 * Case 1: If we *already* have entries in the index under that 968 * directory name, we always recurse into the directory to see 969 * all the files. 970 * 971 * Case 2: If we *already* have that directory name as a gitlink, 972 * we always continue to see it as a gitlink, regardless of whether 973 * there is an actual git directory there or not (it might not 974 * be checked out as a subproject!) 975 * 976 * Case 3: if we didn't have it in the index previously, we 977 * have a few sub-cases: 978 * 979 * (a) if "show_other_directories" is true, we show it as 980 * just a directory, unless "hide_empty_directories" is 981 * also true and the directory is empty, in which case 982 * we just ignore it entirely. 983 * (b) if it looks like a git directory, and we don't have 984 * 'no_gitlinks' set we treat it as a gitlink, and show it 985 * as a directory. 986 * (c) otherwise, we recurse into it. 987 */ 988enum directory_treatment { 989 show_directory, 990 ignore_directory, 991 recurse_into_directory 992}; 993 994static enum directory_treatment treat_directory(struct dir_struct *dir, 995const char*dirname,int len, 996const struct path_simplify *simplify) 997{ 998/* The "len-1" is to strip the final '/' */ 999switch(directory_exists_in_index(dirname, len-1)) {1000case index_directory:1001return recurse_into_directory;10021003case index_gitdir:1004if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1005return ignore_directory;1006return show_directory;10071008case index_nonexistent:1009if(dir->flags & DIR_SHOW_OTHER_DIRECTORIES)1010break;1011if(!(dir->flags & DIR_NO_GITLINKS)) {1012unsigned char sha1[20];1013if(resolve_gitlink_ref(dirname,"HEAD", sha1) ==0)1014return show_directory;1015}1016return recurse_into_directory;1017}10181019/* This is the "show_other_directories" case */1020if(!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))1021return show_directory;1022if(!read_directory_recursive(dir, dirname, len,1, simplify))1023return ignore_directory;1024return show_directory;1025}10261027/*1028 * This is an inexact early pruning of any recursive directory1029 * reading - if the path cannot possibly be in the pathspec,1030 * return true, and we'll skip it early.1031 */1032static intsimplify_away(const char*path,int pathlen,const struct path_simplify *simplify)1033{1034if(simplify) {1035for(;;) {1036const char*match = simplify->path;1037int len = simplify->len;10381039if(!match)1040break;1041if(len > pathlen)1042 len = pathlen;1043if(!memcmp(path, match, len))1044return0;1045 simplify++;1046}1047return1;1048}1049return0;1050}10511052/*1053 * This function tells us whether an excluded path matches a1054 * list of "interesting" pathspecs. That is, whether a path matched1055 * by any of the pathspecs could possibly be ignored by excluding1056 * the specified path. This can happen if:1057 *1058 * 1. the path is mentioned explicitly in the pathspec1059 *1060 * 2. the path is a directory prefix of some element in the1061 * pathspec1062 */1063static intexclude_matches_pathspec(const char*path,int len,1064const struct path_simplify *simplify)1065{1066if(simplify) {1067for(; simplify->path; simplify++) {1068if(len == simplify->len1069&& !memcmp(path, simplify->path, len))1070return1;1071if(len < simplify->len1072&& simplify->path[len] =='/'1073&& !memcmp(path, simplify->path, len))1074return1;1075}1076}1077return0;1078}10791080static intget_index_dtype(const char*path,int len)1081{1082int pos;1083struct cache_entry *ce;10841085 ce =cache_name_exists(path, len,0);1086if(ce) {1087if(!ce_uptodate(ce))1088return DT_UNKNOWN;1089if(S_ISGITLINK(ce->ce_mode))1090return DT_DIR;1091/*1092 * Nobody actually cares about the1093 * difference between DT_LNK and DT_REG1094 */1095return DT_REG;1096}10971098/* Try to look it up as a directory */1099 pos =cache_name_pos(path, len);1100if(pos >=0)1101return DT_UNKNOWN;1102 pos = -pos-1;1103while(pos < active_nr) {1104 ce = active_cache[pos++];1105if(strncmp(ce->name, path, len))1106break;1107if(ce->name[len] >'/')1108break;1109if(ce->name[len] <'/')1110continue;1111if(!ce_uptodate(ce))1112break;/* continue? */1113return DT_DIR;1114}1115return DT_UNKNOWN;1116}11171118static intget_dtype(struct dirent *de,const char*path,int len)1119{1120int dtype = de ?DTYPE(de) : DT_UNKNOWN;1121struct stat st;11221123if(dtype != DT_UNKNOWN)1124return dtype;1125 dtype =get_index_dtype(path, len);1126if(dtype != DT_UNKNOWN)1127return dtype;1128if(lstat(path, &st))1129return dtype;1130if(S_ISREG(st.st_mode))1131return DT_REG;1132if(S_ISDIR(st.st_mode))1133return DT_DIR;1134if(S_ISLNK(st.st_mode))1135return DT_LNK;1136return dtype;1137}11381139enum path_treatment {1140 path_ignored,1141 path_handled,1142 path_recurse1143};11441145static enum path_treatment treat_one_path(struct dir_struct *dir,1146struct strbuf *path,1147const struct path_simplify *simplify,1148int dtype,struct dirent *de)1149{1150int exclude =is_excluded(dir, path->buf, &dtype);1151if(exclude && (dir->flags & DIR_COLLECT_IGNORED)1152&&exclude_matches_pathspec(path->buf, path->len, simplify))1153dir_add_ignored(dir, path->buf, path->len);11541155/*1156 * Excluded? If we don't explicitly want to show1157 * ignored files, ignore it1158 */1159if(exclude && !(dir->flags & DIR_SHOW_IGNORED))1160return path_ignored;11611162if(dtype == DT_UNKNOWN)1163 dtype =get_dtype(de, path->buf, path->len);11641165/*1166 * Do we want to see just the ignored files?1167 * We still need to recurse into directories,1168 * even if we don't ignore them, since the1169 * directory may contain files that we do..1170 */1171if(!exclude && (dir->flags & DIR_SHOW_IGNORED)) {1172if(dtype != DT_DIR)1173return path_ignored;1174}11751176switch(dtype) {1177default:1178return path_ignored;1179case DT_DIR:1180strbuf_addch(path,'/');1181switch(treat_directory(dir, path->buf, path->len, simplify)) {1182case show_directory:1183if(exclude != !!(dir->flags1184& DIR_SHOW_IGNORED))1185return path_ignored;1186break;1187case recurse_into_directory:1188return path_recurse;1189case ignore_directory:1190return path_ignored;1191}1192break;1193case DT_REG:1194case DT_LNK:1195break;1196}1197return path_handled;1198}11991200static enum path_treatment treat_path(struct dir_struct *dir,1201struct dirent *de,1202struct strbuf *path,1203int baselen,1204const struct path_simplify *simplify)1205{1206int dtype;12071208if(is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name,".git"))1209return path_ignored;1210strbuf_setlen(path, baselen);1211strbuf_addstr(path, de->d_name);1212if(simplify_away(path->buf, path->len, simplify))1213return path_ignored;12141215 dtype =DTYPE(de);1216returntreat_one_path(dir, path, simplify, dtype, de);1217}12181219/*1220 * Read a directory tree. We currently ignore anything but1221 * directories, regular files and symlinks. That's because git1222 * doesn't handle them at all yet. Maybe that will change some1223 * day.1224 *1225 * Also, we ignore the name ".git" (even if it is not a directory).1226 * That likely will not change.1227 */1228static intread_directory_recursive(struct dir_struct *dir,1229const char*base,int baselen,1230int check_only,1231const struct path_simplify *simplify)1232{1233DIR*fdir;1234int contents =0;1235struct dirent *de;1236struct strbuf path = STRBUF_INIT;12371238strbuf_add(&path, base, baselen);12391240 fdir =opendir(path.len ? path.buf :".");1241if(!fdir)1242goto out;12431244while((de =readdir(fdir)) != NULL) {1245switch(treat_path(dir, de, &path, baselen, simplify)) {1246case path_recurse:1247 contents +=read_directory_recursive(dir, path.buf,1248 path.len,0,1249 simplify);1250continue;1251case path_ignored:1252continue;1253case path_handled:1254break;1255}1256 contents++;1257if(check_only)1258break;1259dir_add_name(dir, path.buf, path.len);1260}1261closedir(fdir);1262 out:1263strbuf_release(&path);12641265return contents;1266}12671268static intcmp_name(const void*p1,const void*p2)1269{1270const struct dir_entry *e1 = *(const struct dir_entry **)p1;1271const struct dir_entry *e2 = *(const struct dir_entry **)p2;12721273returncache_name_compare(e1->name, e1->len,1274 e2->name, e2->len);1275}12761277static struct path_simplify *create_simplify(const char**pathspec)1278{1279int nr, alloc =0;1280struct path_simplify *simplify = NULL;12811282if(!pathspec)1283return NULL;12841285for(nr =0; ; nr++) {1286const char*match;1287if(nr >= alloc) {1288 alloc =alloc_nr(alloc);1289 simplify =xrealloc(simplify, alloc *sizeof(*simplify));1290}1291 match = *pathspec++;1292if(!match)1293break;1294 simplify[nr].path = match;1295 simplify[nr].len =simple_length(match);1296}1297 simplify[nr].path = NULL;1298 simplify[nr].len =0;1299return simplify;1300}13011302static voidfree_simplify(struct path_simplify *simplify)1303{1304free(simplify);1305}13061307static inttreat_leading_path(struct dir_struct *dir,1308const char*path,int len,1309const struct path_simplify *simplify)1310{1311struct strbuf sb = STRBUF_INIT;1312int baselen, rc =0;1313const char*cp;13141315while(len && path[len -1] =='/')1316 len--;1317if(!len)1318return1;1319 baselen =0;1320while(1) {1321 cp = path + baselen + !!baselen;1322 cp =memchr(cp,'/', path + len - cp);1323if(!cp)1324 baselen = len;1325else1326 baselen = cp - path;1327strbuf_setlen(&sb,0);1328strbuf_add(&sb, path, baselen);1329if(!is_directory(sb.buf))1330break;1331if(simplify_away(sb.buf, sb.len, simplify))1332break;1333if(treat_one_path(dir, &sb, simplify,1334 DT_DIR, NULL) == path_ignored)1335break;/* do not recurse into it */1336if(len <= baselen) {1337 rc =1;1338break;/* finished checking */1339}1340}1341strbuf_release(&sb);1342return rc;1343}13441345intread_directory(struct dir_struct *dir,const char*path,int len,const char**pathspec)1346{1347struct path_simplify *simplify;13481349if(has_symlink_leading_path(path, len))1350return dir->nr;13511352 simplify =create_simplify(pathspec);1353if(!len ||treat_leading_path(dir, path, len, simplify))1354read_directory_recursive(dir, path, len,0, simplify);1355free_simplify(simplify);1356qsort(dir->entries, dir->nr,sizeof(struct dir_entry *), cmp_name);1357qsort(dir->ignored, dir->ignored_nr,sizeof(struct dir_entry *), cmp_name);1358return dir->nr;1359}13601361intfile_exists(const char*f)1362{1363struct stat sb;1364returnlstat(f, &sb) ==0;1365}13661367/*1368 * Given two normalized paths (a trailing slash is ok), if subdir is1369 * outside dir, return -1. Otherwise return the offset in subdir that1370 * can be used as relative path to dir.1371 */1372intdir_inside_of(const char*subdir,const char*dir)1373{1374int offset =0;13751376assert(dir && subdir && *dir && *subdir);13771378while(*dir && *subdir && *dir == *subdir) {1379 dir++;1380 subdir++;1381 offset++;1382}13831384/* hel[p]/me vs hel[l]/yeah */1385if(*dir && *subdir)1386return-1;13871388if(!*subdir)1389return!*dir ? offset : -1;/* same dir */13901391/* foo/[b]ar vs foo/[] */1392if(is_dir_sep(dir[-1]))1393returnis_dir_sep(subdir[-1]) ? offset : -1;13941395/* foo[/]bar vs foo[] */1396returnis_dir_sep(*subdir) ? offset +1: -1;1397}13981399intis_inside_dir(const char*dir)1400{1401char cwd[PATH_MAX];1402if(!dir)1403return0;1404if(!getcwd(cwd,sizeof(cwd)))1405die_errno("can't find the current directory");1406returndir_inside_of(cwd, dir) >=0;1407}14081409intis_empty_dir(const char*path)1410{1411DIR*dir =opendir(path);1412struct dirent *e;1413int ret =1;14141415if(!dir)1416return0;14171418while((e =readdir(dir)) != NULL)1419if(!is_dot_or_dotdot(e->d_name)) {1420 ret =0;1421break;1422}14231424closedir(dir);1425return ret;1426}14271428static intremove_dir_recurse(struct strbuf *path,int flag,int*kept_up)1429{1430DIR*dir;1431struct dirent *e;1432int ret =0, original_len = path->len, len, kept_down =0;1433int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);1434int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);1435unsigned char submodule_head[20];14361437if((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&1438!resolve_gitlink_ref(path->buf,"HEAD", submodule_head)) {1439/* Do not descend and nuke a nested git work tree. */1440if(kept_up)1441*kept_up =1;1442return0;1443}14441445 flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;1446 dir =opendir(path->buf);1447if(!dir) {1448/* an empty dir could be removed even if it is unreadble */1449if(!keep_toplevel)1450returnrmdir(path->buf);1451else1452return-1;1453}1454if(path->buf[original_len -1] !='/')1455strbuf_addch(path,'/');14561457 len = path->len;1458while((e =readdir(dir)) != NULL) {1459struct stat st;1460if(is_dot_or_dotdot(e->d_name))1461continue;14621463strbuf_setlen(path, len);1464strbuf_addstr(path, e->d_name);1465if(lstat(path->buf, &st))1466;/* fall thru */1467else if(S_ISDIR(st.st_mode)) {1468if(!remove_dir_recurse(path, flag, &kept_down))1469continue;/* happy */1470}else if(!only_empty && !unlink(path->buf))1471continue;/* happy, too */14721473/* path too long, stat fails, or non-directory still exists */1474 ret = -1;1475break;1476}1477closedir(dir);14781479strbuf_setlen(path, original_len);1480if(!ret && !keep_toplevel && !kept_down)1481 ret =rmdir(path->buf);1482else if(kept_up)1483/*1484 * report the uplevel that it is not an error that we1485 * did not rmdir() our directory.1486 */1487*kept_up = !ret;1488return ret;1489}14901491intremove_dir_recursively(struct strbuf *path,int flag)1492{1493returnremove_dir_recurse(path, flag, NULL);1494}14951496voidsetup_standard_excludes(struct dir_struct *dir)1497{1498const char*path;14991500 dir->exclude_per_dir =".gitignore";1501 path =git_path("info/exclude");1502if(!access(path, R_OK))1503add_excludes_from_file(dir, path);1504if(excludes_file && !access(excludes_file, R_OK))1505add_excludes_from_file(dir, excludes_file);1506}15071508intremove_path(const char*name)1509{1510char*slash;15111512if(unlink(name) && errno != ENOENT)1513return-1;15141515 slash =strrchr(name,'/');1516if(slash) {1517char*dirs =xstrdup(name);1518 slash = dirs + (slash - name);1519do{1520*slash ='\0';1521}while(rmdir(dirs) ==0&& (slash =strrchr(dirs,'/')));1522free(dirs);1523}1524return0;1525}15261527static intpathspec_item_cmp(const void*a_,const void*b_)1528{1529struct pathspec_item *a, *b;15301531 a = (struct pathspec_item *)a_;1532 b = (struct pathspec_item *)b_;1533returnstrcmp(a->match, b->match);1534}15351536intinit_pathspec(struct pathspec *pathspec,const char**paths)1537{1538const char**p = paths;1539int i;15401541memset(pathspec,0,sizeof(*pathspec));1542if(!p)1543return0;1544while(*p)1545 p++;1546 pathspec->raw = paths;1547 pathspec->nr = p - paths;1548if(!pathspec->nr)1549return0;15501551 pathspec->items =xmalloc(sizeof(struct pathspec_item)*pathspec->nr);1552for(i =0; i < pathspec->nr; i++) {1553struct pathspec_item *item = pathspec->items+i;1554const char*path = paths[i];15551556 item->match = path;1557 item->len =strlen(path);1558 item->use_wildcard = !no_wildcard(path);1559if(item->use_wildcard)1560 pathspec->has_wildcard =1;1561}15621563qsort(pathspec->items, pathspec->nr,1564sizeof(struct pathspec_item), pathspec_item_cmp);15651566return0;1567}15681569voidfree_pathspec(struct pathspec *pathspec)1570{1571free(pathspec->items);1572 pathspec->items = NULL;1573}15741575/*1576 * Frees memory within dir which was allocated for exclude lists and1577 * the exclude_stack. Does not free dir itself.1578 */1579voidclear_directory(struct dir_struct *dir)1580{1581int i, j;1582struct exclude_list_group *group;1583struct exclude_list *el;1584struct exclude_stack *stk;15851586for(i = EXC_CMDL; i <= EXC_FILE; i++) {1587 group = &dir->exclude_list_group[i];1588for(j =0; j < group->nr; j++) {1589 el = &group->el[j];1590if(i == EXC_DIRS)1591free((char*)el->src);1592clear_exclude_list(el);1593}1594free(group->el);1595}15961597 stk = dir->exclude_stack;1598while(stk) {1599struct exclude_stack *prev = stk->prev;1600free(stk);1601 stk = prev;1602}1603}