b0599dd6e43c606019a98690ddc59e2d92ecb708
   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 {
  17        int len;
  18        const 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,
  35        const char *path, int len,
  36        int check_only, const struct path_simplify *simplify);
  37static int get_dtype(struct dirent *de, const char *path, int len);
  38
  39/* helper string functions with support for the ignore_case flag */
  40int strcmp_icase(const char *a, const char *b)
  41{
  42        return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
  43}
  44
  45int strncmp_icase(const char *a, const char *b, size_t count)
  46{
  47        return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
  48}
  49
  50int fnmatch_icase(const char *pattern, const char *string, int flags)
  51{
  52        return fnmatch(pattern, string, flags | (ignore_case ? FNM_CASEFOLD : 0));
  53}
  54
  55inline int git_fnmatch(const char *pattern, const char *string,
  56                       int flags, int prefix)
  57{
  58        int fnm_flags = 0;
  59        if (flags & GFNM_PATHNAME)
  60                fnm_flags |= FNM_PATHNAME;
  61        if (prefix > 0) {
  62                if (strncmp(pattern, string, prefix))
  63                        return FNM_NOMATCH;
  64                pattern += prefix;
  65                string += prefix;
  66        }
  67        if (flags & GFNM_ONESTAR) {
  68                int pattern_len = strlen(++pattern);
  69                int string_len = strlen(string);
  70                return string_len < pattern_len ||
  71                       strcmp(pattern,
  72                              string + string_len - pattern_len);
  73        }
  74        return fnmatch(pattern, string, fnm_flags);
  75}
  76
  77static int fnmatch_icase_mem(const char *pattern, int patternlen,
  78                             const char *string, int stringlen,
  79                             int flags)
  80{
  81        int match_status;
  82        struct strbuf pat_buf = STRBUF_INIT;
  83        struct strbuf str_buf = STRBUF_INIT;
  84        const char *use_pat = pattern;
  85        const char *use_str = string;
  86
  87        if (pattern[patternlen]) {
  88                strbuf_add(&pat_buf, pattern, patternlen);
  89                use_pat = pat_buf.buf;
  90        }
  91        if (string[stringlen]) {
  92                strbuf_add(&str_buf, string, stringlen);
  93                use_str = str_buf.buf;
  94        }
  95
  96        if (ignore_case)
  97                flags |= WM_CASEFOLD;
  98        match_status = wildmatch(use_pat, use_str, flags, NULL);
  99
 100        strbuf_release(&pat_buf);
 101        strbuf_release(&str_buf);
 102
 103        return match_status;
 104}
 105
 106static size_t common_prefix_len(const char **pathspec)
 107{
 108        const char *n, *first;
 109        size_t max = 0;
 110        int literal = limit_pathspec_to_literal();
 111
 112        if (!pathspec)
 113                return max;
 114
 115        first = *pathspec;
 116        while ((n = *pathspec++)) {
 117                size_t i, len = 0;
 118                for (i = 0; first == n || i < max; i++) {
 119                        char c = n[i];
 120                        if (!c || c != first[i] || (!literal && is_glob_special(c)))
 121                                break;
 122                        if (c == '/')
 123                                len = i + 1;
 124                }
 125                if (first == n || len < max) {
 126                        max = len;
 127                        if (!max)
 128                                break;
 129                }
 130        }
 131        return max;
 132}
 133
 134/*
 135 * Returns a copy of the longest leading path common among all
 136 * pathspecs.
 137 */
 138char *common_prefix(const char **pathspec)
 139{
 140        unsigned long len = common_prefix_len(pathspec);
 141
 142        return len ? xmemdupz(*pathspec, len) : NULL;
 143}
 144
 145int fill_directory(struct dir_struct *dir, const char **pathspec)
 146{
 147        size_t len;
 148
 149        /*
 150         * Calculate common prefix for the pathspec, and
 151         * use that to optimize the directory walk
 152         */
 153        len = common_prefix_len(pathspec);
 154
 155        /* Read the directory and prune it */
 156        read_directory(dir, pathspec ? *pathspec : "", len, pathspec);
 157        return len;
 158}
 159
 160int within_depth(const char *name, int namelen,
 161                        int depth, int max_depth)
 162{
 163        const char *cp = name, *cpe = name + namelen;
 164
 165        while (cp < cpe) {
 166                if (*cp++ != '/')
 167                        continue;
 168                depth++;
 169                if (depth > max_depth)
 170                        return 0;
 171        }
 172        return 1;
 173}
 174
 175/*
 176 * Does 'match' match the given name?
 177 * A match is found if
 178 *
 179 * (1) the 'match' string is leading directory of 'name', or
 180 * (2) the 'match' string is a wildcard and matches 'name', or
 181 * (3) the 'match' string is exactly the same as 'name'.
 182 *
 183 * and the return value tells which case it was.
 184 *
 185 * It returns 0 when there is no match.
 186 */
 187static int match_one(const char *match, const char *name, int namelen)
 188{
 189        int matchlen;
 190        int literal = limit_pathspec_to_literal();
 191
 192        /* If the match was just the prefix, we matched */
 193        if (!*match)
 194                return MATCHED_RECURSIVELY;
 195
 196        if (ignore_case) {
 197                for (;;) {
 198                        unsigned char c1 = tolower(*match);
 199                        unsigned char c2 = tolower(*name);
 200                        if (c1 == '\0' || (!literal && is_glob_special(c1)))
 201                                break;
 202                        if (c1 != c2)
 203                                return 0;
 204                        match++;
 205                        name++;
 206                        namelen--;
 207                }
 208        } else {
 209                for (;;) {
 210                        unsigned char c1 = *match;
 211                        unsigned char c2 = *name;
 212                        if (c1 == '\0' || (!literal && is_glob_special(c1)))
 213                                break;
 214                        if (c1 != c2)
 215                                return 0;
 216                        match++;
 217                        name++;
 218                        namelen--;
 219                }
 220        }
 221
 222        /*
 223         * If we don't match the matchstring exactly,
 224         * we need to match by fnmatch
 225         */
 226        matchlen = strlen(match);
 227        if (strncmp_icase(match, name, matchlen)) {
 228                if (literal)
 229                        return 0;
 230                return !fnmatch_icase(match, name, 0) ? MATCHED_FNMATCH : 0;
 231        }
 232
 233        if (namelen == matchlen)
 234                return MATCHED_EXACTLY;
 235        if (match[matchlen-1] == '/' || name[matchlen] == '/')
 236                return MATCHED_RECURSIVELY;
 237        return 0;
 238}
 239
 240/*
 241 * Given a name and a list of pathspecs, returns the nature of the
 242 * closest (i.e. most specific) match of the name to any of the
 243 * pathspecs.
 244 *
 245 * The caller typically calls this multiple times with the same
 246 * pathspec and seen[] array but with different name/namelen
 247 * (e.g. entries from the index) and is interested in seeing if and
 248 * how each pathspec matches all the names it calls this function
 249 * with.  A mark is left in the seen[] array for each pathspec element
 250 * indicating the closest type of match that element achieved, so if
 251 * seen[n] remains zero after multiple invocations, that means the nth
 252 * pathspec did not match any names, which could indicate that the
 253 * user mistyped the nth pathspec.
 254 */
 255int match_pathspec(const char **pathspec, const char *name, int namelen,
 256                int prefix, char *seen)
 257{
 258        int i, retval = 0;
 259
 260        if (!pathspec)
 261                return 1;
 262
 263        name += prefix;
 264        namelen -= prefix;
 265
 266        for (i = 0; pathspec[i] != NULL; i++) {
 267                int how;
 268                const char *match = pathspec[i] + prefix;
 269                if (seen && seen[i] == MATCHED_EXACTLY)
 270                        continue;
 271                how = match_one(match, name, namelen);
 272                if (how) {
 273                        if (retval < how)
 274                                retval = how;
 275                        if (seen && seen[i] < how)
 276                                seen[i] = how;
 277                }
 278        }
 279        return retval;
 280}
 281
 282/*
 283 * Does 'match' match the given name?
 284 * A match is found if
 285 *
 286 * (1) the 'match' string is leading directory of 'name', or
 287 * (2) the 'match' string is a wildcard and matches 'name', or
 288 * (3) the 'match' string is exactly the same as 'name'.
 289 *
 290 * and the return value tells which case it was.
 291 *
 292 * It returns 0 when there is no match.
 293 */
 294static int match_pathspec_item(const struct pathspec_item *item, int prefix,
 295                               const char *name, int namelen)
 296{
 297        /* name/namelen has prefix cut off by caller */
 298        const char *match = item->match + prefix;
 299        int matchlen = item->len - prefix;
 300
 301        /* If the match was just the prefix, we matched */
 302        if (!*match)
 303                return MATCHED_RECURSIVELY;
 304
 305        if (matchlen <= namelen && !strncmp(match, name, matchlen)) {
 306                if (matchlen == namelen)
 307                        return MATCHED_EXACTLY;
 308
 309                if (match[matchlen-1] == '/' || name[matchlen] == '/')
 310                        return MATCHED_RECURSIVELY;
 311        }
 312
 313        if (item->nowildcard_len < item->len &&
 314            !git_fnmatch(match, name,
 315                         item->flags & PATHSPEC_ONESTAR ? GFNM_ONESTAR : 0,
 316                         item->nowildcard_len - prefix))
 317                return MATCHED_FNMATCH;
 318
 319        return 0;
 320}
 321
 322/*
 323 * Given a name and a list of pathspecs, returns the nature of the
 324 * closest (i.e. most specific) match of the name to any of the
 325 * pathspecs.
 326 *
 327 * The caller typically calls this multiple times with the same
 328 * pathspec and seen[] array but with different name/namelen
 329 * (e.g. entries from the index) and is interested in seeing if and
 330 * how each pathspec matches all the names it calls this function
 331 * with.  A mark is left in the seen[] array for each pathspec element
 332 * indicating the closest type of match that element achieved, so if
 333 * seen[n] remains zero after multiple invocations, that means the nth
 334 * pathspec did not match any names, which could indicate that the
 335 * user mistyped the nth pathspec.
 336 */
 337int match_pathspec_depth(const struct pathspec *ps,
 338                         const char *name, int namelen,
 339                         int prefix, char *seen)
 340{
 341        int i, retval = 0;
 342
 343        if (!ps->nr) {
 344                if (!ps->recursive || ps->max_depth == -1)
 345                        return MATCHED_RECURSIVELY;
 346
 347                if (within_depth(name, namelen, 0, ps->max_depth))
 348                        return MATCHED_EXACTLY;
 349                else
 350                        return 0;
 351        }
 352
 353        name += prefix;
 354        namelen -= prefix;
 355
 356        for (i = ps->nr - 1; i >= 0; i--) {
 357                int how;
 358                if (seen && seen[i] == MATCHED_EXACTLY)
 359                        continue;
 360                how = match_pathspec_item(ps->items+i, prefix, name, namelen);
 361                if (ps->recursive && ps->max_depth != -1 &&
 362                    how && how != MATCHED_FNMATCH) {
 363                        int len = ps->items[i].len;
 364                        if (name[len] == '/')
 365                                len++;
 366                        if (within_depth(name+len, namelen-len, 0, ps->max_depth))
 367                                how = MATCHED_EXACTLY;
 368                        else
 369                                how = 0;
 370                }
 371                if (how) {
 372                        if (retval < how)
 373                                retval = how;
 374                        if (seen && seen[i] < how)
 375                                seen[i] = how;
 376                }
 377        }
 378        return retval;
 379}
 380
 381/*
 382 * Return the length of the "simple" part of a path match limiter.
 383 */
 384static int simple_length(const char *match)
 385{
 386        int len = -1;
 387
 388        for (;;) {
 389                unsigned char c = *match++;
 390                len++;
 391                if (c == '\0' || is_glob_special(c))
 392                        return len;
 393        }
 394}
 395
 396static int no_wildcard(const char *string)
 397{
 398        return string[simple_length(string)] == '\0';
 399}
 400
 401void parse_exclude_pattern(const char **pattern,
 402                           int *patternlen,
 403                           int *flags,
 404                           int *nowildcardlen)
 405{
 406        const char *p = *pattern;
 407        size_t i, len;
 408
 409        *flags = 0;
 410        if (*p == '!') {
 411                *flags |= EXC_FLAG_NEGATIVE;
 412                p++;
 413        }
 414        len = strlen(p);
 415        if (len && p[len - 1] == '/') {
 416                len--;
 417                *flags |= EXC_FLAG_MUSTBEDIR;
 418        }
 419        for (i = 0; i < len; i++) {
 420                if (p[i] == '/')
 421                        break;
 422        }
 423        if (i == len)
 424                *flags |= EXC_FLAG_NODIR;
 425        *nowildcardlen = simple_length(p);
 426        /*
 427         * we should have excluded the trailing slash from 'p' too,
 428         * but that's one more allocation. Instead just make sure
 429         * nowildcardlen does not exceed real patternlen
 430         */
 431        if (*nowildcardlen > len)
 432                *nowildcardlen = len;
 433        if (*p == '*' && no_wildcard(p + 1))
 434                *flags |= EXC_FLAG_ENDSWITH;
 435        *pattern = p;
 436        *patternlen = len;
 437}
 438
 439void add_exclude(const char *string, const char *base,
 440                 int baselen, struct exclude_list *el, int srcpos)
 441{
 442        struct exclude *x;
 443        int patternlen;
 444        int flags;
 445        int nowildcardlen;
 446
 447        parse_exclude_pattern(&string, &patternlen, &flags, &nowildcardlen);
 448        if (flags & EXC_FLAG_MUSTBEDIR) {
 449                char *s;
 450                x = xmalloc(sizeof(*x) + patternlen + 1);
 451                s = (char *)(x+1);
 452                memcpy(s, string, patternlen);
 453                s[patternlen] = '\0';
 454                x->pattern = s;
 455        } else {
 456                x = xmalloc(sizeof(*x));
 457                x->pattern = string;
 458        }
 459        x->patternlen = patternlen;
 460        x->nowildcardlen = nowildcardlen;
 461        x->base = base;
 462        x->baselen = baselen;
 463        x->flags = flags;
 464        x->srcpos = srcpos;
 465        ALLOC_GROW(el->excludes, el->nr + 1, el->alloc);
 466        el->excludes[el->nr++] = x;
 467        x->el = el;
 468}
 469
 470static void *read_skip_worktree_file_from_index(const char *path, size_t *size)
 471{
 472        int pos, len;
 473        unsigned long sz;
 474        enum object_type type;
 475        void *data;
 476        struct index_state *istate = &the_index;
 477
 478        len = strlen(path);
 479        pos = index_name_pos(istate, path, len);
 480        if (pos < 0)
 481                return NULL;
 482        if (!ce_skip_worktree(istate->cache[pos]))
 483                return NULL;
 484        data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
 485        if (!data || type != OBJ_BLOB) {
 486                free(data);
 487                return NULL;
 488        }
 489        *size = xsize_t(sz);
 490        return data;
 491}
 492
 493/*
 494 * Frees memory within el which was allocated for exclude patterns and
 495 * the file buffer.  Does not free el itself.
 496 */
 497void clear_exclude_list(struct exclude_list *el)
 498{
 499        int i;
 500
 501        for (i = 0; i < el->nr; i++)
 502                free(el->excludes[i]);
 503        free(el->excludes);
 504        free(el->filebuf);
 505
 506        el->nr = 0;
 507        el->excludes = NULL;
 508        el->filebuf = NULL;
 509}
 510
 511int add_excludes_from_file_to_list(const char *fname,
 512                                   const char *base,
 513                                   int baselen,
 514                                   struct exclude_list *el,
 515                                   int check_index)
 516{
 517        struct stat st;
 518        int fd, i, lineno = 1;
 519        size_t size = 0;
 520        char *buf, *entry;
 521
 522        fd = open(fname, O_RDONLY);
 523        if (fd < 0 || fstat(fd, &st) < 0) {
 524                if (errno != ENOENT)
 525                        warn_on_inaccessible(fname);
 526                if (0 <= fd)
 527                        close(fd);
 528                if (!check_index ||
 529                    (buf = read_skip_worktree_file_from_index(fname, &size)) == NULL)
 530                        return -1;
 531                if (size == 0) {
 532                        free(buf);
 533                        return 0;
 534                }
 535                if (buf[size-1] != '\n') {
 536                        buf = xrealloc(buf, size+1);
 537                        buf[size++] = '\n';
 538                }
 539        }
 540        else {
 541                size = xsize_t(st.st_size);
 542                if (size == 0) {
 543                        close(fd);
 544                        return 0;
 545                }
 546                buf = xmalloc(size+1);
 547                if (read_in_full(fd, buf, size) != size) {
 548                        free(buf);
 549                        close(fd);
 550                        return -1;
 551                }
 552                buf[size++] = '\n';
 553                close(fd);
 554        }
 555
 556        el->filebuf = buf;
 557        entry = buf;
 558        for (i = 0; i < size; i++) {
 559                if (buf[i] == '\n') {
 560                        if (entry != buf + i && entry[0] != '#') {
 561                                buf[i - (i && buf[i-1] == '\r')] = 0;
 562                                add_exclude(entry, base, baselen, el, lineno);
 563                        }
 564                        lineno++;
 565                        entry = buf + i + 1;
 566                }
 567        }
 568        return 0;
 569}
 570
 571struct exclude_list *add_exclude_list(struct dir_struct *dir,
 572                                      int group_type, const char *src)
 573{
 574        struct exclude_list *el;
 575        struct exclude_list_group *group;
 576
 577        group = &dir->exclude_list_group[group_type];
 578        ALLOC_GROW(group->el, group->nr + 1, group->alloc);
 579        el = &group->el[group->nr++];
 580        memset(el, 0, sizeof(*el));
 581        el->src = src;
 582        return el;
 583}
 584
 585/*
 586 * Used to set up core.excludesfile and .git/info/exclude lists.
 587 */
 588void add_excludes_from_file(struct dir_struct *dir, const char *fname)
 589{
 590        struct exclude_list *el;
 591        el = add_exclude_list(dir, EXC_FILE, fname);
 592        if (add_excludes_from_file_to_list(fname, "", 0, el, 0) < 0)
 593                die("cannot use %s as an exclude file", fname);
 594}
 595
 596int match_basename(const char *basename, int basenamelen,
 597                   const char *pattern, int prefix, int patternlen,
 598                   int flags)
 599{
 600        if (prefix == patternlen) {
 601                if (patternlen == basenamelen &&
 602                    !strncmp_icase(pattern, basename, basenamelen))
 603                        return 1;
 604        } else if (flags & EXC_FLAG_ENDSWITH) {
 605                /* "*literal" matching against "fooliteral" */
 606                if (patternlen - 1 <= basenamelen &&
 607                    !strncmp_icase(pattern + 1,
 608                                   basename + basenamelen - (patternlen - 1),
 609                                   patternlen - 1))
 610                        return 1;
 611        } else {
 612                if (fnmatch_icase_mem(pattern, patternlen,
 613                                      basename, basenamelen,
 614                                      0) == 0)
 615                        return 1;
 616        }
 617        return 0;
 618}
 619
 620int match_pathname(const char *pathname, int pathlen,
 621                   const char *base, int baselen,
 622                   const char *pattern, int prefix, int patternlen,
 623                   int flags)
 624{
 625        const char *name;
 626        int namelen;
 627
 628        /*
 629         * match with FNM_PATHNAME; the pattern has base implicitly
 630         * in front of it.
 631         */
 632        if (*pattern == '/') {
 633                pattern++;
 634                patternlen--;
 635                prefix--;
 636        }
 637
 638        /*
 639         * baselen does not count the trailing slash. base[] may or
 640         * may not end with a trailing slash though.
 641         */
 642        if (pathlen < baselen + 1 ||
 643            (baselen && pathname[baselen] != '/') ||
 644            strncmp_icase(pathname, base, baselen))
 645                return 0;
 646
 647        namelen = baselen ? pathlen - baselen - 1 : pathlen;
 648        name = pathname + pathlen - namelen;
 649
 650        if (prefix) {
 651                /*
 652                 * if the non-wildcard part is longer than the
 653                 * remaining pathname, surely it cannot match.
 654                 */
 655                if (prefix > namelen)
 656                        return 0;
 657
 658                if (strncmp_icase(pattern, name, prefix))
 659                        return 0;
 660                pattern += prefix;
 661                patternlen -= prefix;
 662                name    += prefix;
 663                namelen -= prefix;
 664
 665                /*
 666                 * If the whole pattern did not have a wildcard,
 667                 * then our prefix match is all we need; we
 668                 * do not need to call fnmatch at all.
 669                 */
 670                if (!patternlen && !namelen)
 671                        return 1;
 672        }
 673
 674        return fnmatch_icase_mem(pattern, patternlen,
 675                                 name, namelen,
 676                                 WM_PATHNAME) == 0;
 677}
 678
 679/*
 680 * Scan the given exclude list in reverse to see whether pathname
 681 * should be ignored.  The first match (i.e. the last on the list), if
 682 * any, determines the fate.  Returns the exclude_list element which
 683 * matched, or NULL for undecided.
 684 */
 685static struct exclude *last_exclude_matching_from_list(const char *pathname,
 686                                                       int pathlen,
 687                                                       const char *basename,
 688                                                       int *dtype,
 689                                                       struct exclude_list *el)
 690{
 691        int i;
 692
 693        if (!el->nr)
 694                return NULL;    /* undefined */
 695
 696        for (i = el->nr - 1; 0 <= i; i--) {
 697                struct exclude *x = el->excludes[i];
 698                const char *exclude = x->pattern;
 699                int prefix = x->nowildcardlen;
 700
 701                if (x->flags & EXC_FLAG_MUSTBEDIR) {
 702                        if (*dtype == DT_UNKNOWN)
 703                                *dtype = get_dtype(NULL, pathname, pathlen);
 704                        if (*dtype != DT_DIR)
 705                                continue;
 706                }
 707
 708                if (x->flags & EXC_FLAG_NODIR) {
 709                        if (match_basename(basename,
 710                                           pathlen - (basename - pathname),
 711                                           exclude, prefix, x->patternlen,
 712                                           x->flags))
 713                                return x;
 714                        continue;
 715                }
 716
 717                assert(x->baselen == 0 || x->base[x->baselen - 1] == '/');
 718                if (match_pathname(pathname, pathlen,
 719                                   x->base, x->baselen ? x->baselen - 1 : 0,
 720                                   exclude, prefix, x->patternlen, x->flags))
 721                        return x;
 722        }
 723        return NULL; /* undecided */
 724}
 725
 726/*
 727 * Scan the list and let the last match determine the fate.
 728 * Return 1 for exclude, 0 for include and -1 for undecided.
 729 */
 730int is_excluded_from_list(const char *pathname,
 731                          int pathlen, const char *basename, int *dtype,
 732                          struct exclude_list *el)
 733{
 734        struct exclude *exclude;
 735        exclude = last_exclude_matching_from_list(pathname, pathlen, basename, dtype, el);
 736        if (exclude)
 737                return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
 738        return -1; /* undecided */
 739}
 740
 741static struct exclude *last_exclude_matching_from_lists(struct dir_struct *dir,
 742                const char *pathname, int pathlen, const char *basename,
 743                int *dtype_p)
 744{
 745        int i, j;
 746        struct exclude_list_group *group;
 747        struct exclude *exclude;
 748        for (i = EXC_CMDL; i <= EXC_FILE; i++) {
 749                group = &dir->exclude_list_group[i];
 750                for (j = group->nr - 1; j >= 0; j--) {
 751                        exclude = last_exclude_matching_from_list(
 752                                pathname, pathlen, basename, dtype_p,
 753                                &group->el[j]);
 754                        if (exclude)
 755                                return exclude;
 756                }
 757        }
 758        return NULL;
 759}
 760
 761/*
 762 * Loads the per-directory exclude list for the substring of base
 763 * which has a char length of baselen.
 764 */
 765static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
 766{
 767        struct exclude_list_group *group;
 768        struct exclude_list *el;
 769        struct exclude_stack *stk = NULL;
 770        int current;
 771
 772        group = &dir->exclude_list_group[EXC_DIRS];
 773
 774        /* Pop the exclude lists from the EXCL_DIRS exclude_list_group
 775         * which originate from directories not in the prefix of the
 776         * path being checked. */
 777        while ((stk = dir->exclude_stack) != NULL) {
 778                if (stk->baselen <= baselen &&
 779                    !strncmp(dir->basebuf, base, stk->baselen))
 780                        break;
 781                el = &group->el[dir->exclude_stack->exclude_ix];
 782                dir->exclude_stack = stk->prev;
 783                dir->exclude = NULL;
 784                free((char *)el->src); /* see strdup() below */
 785                clear_exclude_list(el);
 786                free(stk);
 787                group->nr--;
 788        }
 789
 790        /* Skip traversing into sub directories if the parent is excluded */
 791        if (dir->exclude)
 792                return;
 793
 794        /* Read from the parent directories and push them down. */
 795        current = stk ? stk->baselen : -1;
 796        while (current < baselen) {
 797                struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
 798                const char *cp;
 799
 800                if (current < 0) {
 801                        cp = base;
 802                        current = 0;
 803                }
 804                else {
 805                        cp = strchr(base + current + 1, '/');
 806                        if (!cp)
 807                                die("oops in prep_exclude");
 808                        cp++;
 809                }
 810                stk->prev = dir->exclude_stack;
 811                stk->baselen = cp - base;
 812                stk->exclude_ix = group->nr;
 813                el = add_exclude_list(dir, EXC_DIRS, NULL);
 814                memcpy(dir->basebuf + current, base + current,
 815                       stk->baselen - current);
 816
 817                /* Abort if the directory is excluded */
 818                if (stk->baselen) {
 819                        int dt = DT_DIR;
 820                        dir->basebuf[stk->baselen - 1] = 0;
 821                        dir->exclude = last_exclude_matching_from_lists(dir,
 822                                dir->basebuf, stk->baselen - 1,
 823                                dir->basebuf + current, &dt);
 824                        dir->basebuf[stk->baselen - 1] = '/';
 825                        if (dir->exclude &&
 826                            dir->exclude->flags & EXC_FLAG_NEGATIVE)
 827                                dir->exclude = NULL;
 828                        if (dir->exclude) {
 829                                dir->basebuf[stk->baselen] = 0;
 830                                dir->exclude_stack = stk;
 831                                return;
 832                        }
 833                }
 834
 835                /* Try to read per-directory file unless path is too long */
 836                if (dir->exclude_per_dir &&
 837                    stk->baselen + strlen(dir->exclude_per_dir) < PATH_MAX) {
 838                        strcpy(dir->basebuf + stk->baselen,
 839                                        dir->exclude_per_dir);
 840                        /*
 841                         * dir->basebuf gets reused by the traversal, but we
 842                         * need fname to remain unchanged to ensure the src
 843                         * member of each struct exclude correctly
 844                         * back-references its source file.  Other invocations
 845                         * of add_exclude_list provide stable strings, so we
 846                         * strdup() and free() here in the caller.
 847                         */
 848                        el->src = strdup(dir->basebuf);
 849                        add_excludes_from_file_to_list(dir->basebuf,
 850                                        dir->basebuf, stk->baselen, el, 1);
 851                }
 852                dir->exclude_stack = stk;
 853                current = stk->baselen;
 854        }
 855        dir->basebuf[baselen] = '\0';
 856}
 857
 858/*
 859 * Loads the exclude lists for the directory containing pathname, then
 860 * scans all exclude lists to determine whether pathname is excluded.
 861 * Returns the exclude_list element which matched, or NULL for
 862 * undecided.
 863 */
 864struct exclude *last_exclude_matching(struct dir_struct *dir,
 865                                             const char *pathname,
 866                                             int *dtype_p)
 867{
 868        int pathlen = strlen(pathname);
 869        const char *basename = strrchr(pathname, '/');
 870        basename = (basename) ? basename+1 : pathname;
 871
 872        prep_exclude(dir, pathname, basename-pathname);
 873
 874        if (dir->exclude)
 875                return dir->exclude;
 876
 877        return last_exclude_matching_from_lists(dir, pathname, pathlen,
 878                        basename, dtype_p);
 879}
 880
 881/*
 882 * Loads the exclude lists for the directory containing pathname, then
 883 * scans all exclude lists to determine whether pathname is excluded.
 884 * Returns 1 if true, otherwise 0.
 885 */
 886int is_excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
 887{
 888        struct exclude *exclude =
 889                last_exclude_matching(dir, pathname, dtype_p);
 890        if (exclude)
 891                return exclude->flags & EXC_FLAG_NEGATIVE ? 0 : 1;
 892        return 0;
 893}
 894
 895static struct dir_entry *dir_entry_new(const char *pathname, int len)
 896{
 897        struct dir_entry *ent;
 898
 899        ent = xmalloc(sizeof(*ent) + len + 1);
 900        ent->len = len;
 901        memcpy(ent->name, pathname, len);
 902        ent->name[len] = 0;
 903        return ent;
 904}
 905
 906static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
 907{
 908        if (cache_name_exists(pathname, len, ignore_case))
 909                return NULL;
 910
 911        ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
 912        return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
 913}
 914
 915struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
 916{
 917        if (!cache_name_is_other(pathname, len))
 918                return NULL;
 919
 920        ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
 921        return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
 922}
 923
 924enum exist_status {
 925        index_nonexistent = 0,
 926        index_directory,
 927        index_gitdir
 928};
 929
 930/*
 931 * Do not use the alphabetically stored index to look up
 932 * the directory name; instead, use the case insensitive
 933 * name hash.
 934 */
 935static enum exist_status directory_exists_in_index_icase(const char *dirname, int len)
 936{
 937        struct cache_entry *ce = index_name_exists(&the_index, dirname, len + 1, ignore_case);
 938        unsigned char endchar;
 939
 940        if (!ce)
 941                return index_nonexistent;
 942        endchar = ce->name[len];
 943
 944        /*
 945         * The cache_entry structure returned will contain this dirname
 946         * and possibly additional path components.
 947         */
 948        if (endchar == '/')
 949                return index_directory;
 950
 951        /*
 952         * If there are no additional path components, then this cache_entry
 953         * represents a submodule.  Submodules, despite being directories,
 954         * are stored in the cache without a closing slash.
 955         */
 956        if (!endchar && S_ISGITLINK(ce->ce_mode))
 957                return index_gitdir;
 958
 959        /* This should never be hit, but it exists just in case. */
 960        return index_nonexistent;
 961}
 962
 963/*
 964 * The index sorts alphabetically by entry name, which
 965 * means that a gitlink sorts as '\0' at the end, while
 966 * a directory (which is defined not as an entry, but as
 967 * the files it contains) will sort with the '/' at the
 968 * end.
 969 */
 970static enum exist_status directory_exists_in_index(const char *dirname, int len)
 971{
 972        int pos;
 973
 974        if (ignore_case)
 975                return directory_exists_in_index_icase(dirname, len);
 976
 977        pos = cache_name_pos(dirname, len);
 978        if (pos < 0)
 979                pos = -pos-1;
 980        while (pos < active_nr) {
 981                struct cache_entry *ce = active_cache[pos++];
 982                unsigned char endchar;
 983
 984                if (strncmp(ce->name, dirname, len))
 985                        break;
 986                endchar = ce->name[len];
 987                if (endchar > '/')
 988                        break;
 989                if (endchar == '/')
 990                        return index_directory;
 991                if (!endchar && S_ISGITLINK(ce->ce_mode))
 992                        return index_gitdir;
 993        }
 994        return index_nonexistent;
 995}
 996
 997/*
 998 * When we find a directory when traversing the filesystem, we
 999 * have three distinct cases:
1000 *
1001 *  - ignore it
1002 *  - see it as a directory
1003 *  - recurse into it
1004 *
1005 * and which one we choose depends on a combination of existing
1006 * git index contents and the flags passed into the directory
1007 * traversal routine.
1008 *
1009 * Case 1: If we *already* have entries in the index under that
1010 * directory name, we always recurse into the directory to see
1011 * all the files.
1012 *
1013 * Case 2: If we *already* have that directory name as a gitlink,
1014 * we always continue to see it as a gitlink, regardless of whether
1015 * there is an actual git directory there or not (it might not
1016 * be checked out as a subproject!)
1017 *
1018 * Case 3: if we didn't have it in the index previously, we
1019 * have a few sub-cases:
1020 *
1021 *  (a) if "show_other_directories" is true, we show it as
1022 *      just a directory, unless "hide_empty_directories" is
1023 *      also true, in which case we need to check if it contains any
1024 *      untracked and / or ignored files.
1025 *  (b) if it looks like a git directory, and we don't have
1026 *      'no_gitlinks' set we treat it as a gitlink, and show it
1027 *      as a directory.
1028 *  (c) otherwise, we recurse into it.
1029 */
1030static enum path_treatment treat_directory(struct dir_struct *dir,
1031        const char *dirname, int len, int exclude,
1032        const struct path_simplify *simplify)
1033{
1034        /* The "len-1" is to strip the final '/' */
1035        switch (directory_exists_in_index(dirname, len-1)) {
1036        case index_directory:
1037                return path_recurse;
1038
1039        case index_gitdir:
1040                return path_none;
1041
1042        case index_nonexistent:
1043                if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
1044                        break;
1045                if (!(dir->flags & DIR_NO_GITLINKS)) {
1046                        unsigned char sha1[20];
1047                        if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
1048                                return path_untracked;
1049                }
1050                return path_recurse;
1051        }
1052
1053        /* This is the "show_other_directories" case */
1054
1055        if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
1056                return exclude ? path_excluded : path_untracked;
1057
1058        return read_directory_recursive(dir, dirname, len, 1, simplify);
1059}
1060
1061/*
1062 * This is an inexact early pruning of any recursive directory
1063 * reading - if the path cannot possibly be in the pathspec,
1064 * return true, and we'll skip it early.
1065 */
1066static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
1067{
1068        if (simplify) {
1069                for (;;) {
1070                        const char *match = simplify->path;
1071                        int len = simplify->len;
1072
1073                        if (!match)
1074                                break;
1075                        if (len > pathlen)
1076                                len = pathlen;
1077                        if (!memcmp(path, match, len))
1078                                return 0;
1079                        simplify++;
1080                }
1081                return 1;
1082        }
1083        return 0;
1084}
1085
1086/*
1087 * This function tells us whether an excluded path matches a
1088 * list of "interesting" pathspecs. That is, whether a path matched
1089 * by any of the pathspecs could possibly be ignored by excluding
1090 * the specified path. This can happen if:
1091 *
1092 *   1. the path is mentioned explicitly in the pathspec
1093 *
1094 *   2. the path is a directory prefix of some element in the
1095 *      pathspec
1096 */
1097static int exclude_matches_pathspec(const char *path, int len,
1098                const struct path_simplify *simplify)
1099{
1100        if (simplify) {
1101                for (; simplify->path; simplify++) {
1102                        if (len == simplify->len
1103                            && !memcmp(path, simplify->path, len))
1104                                return 1;
1105                        if (len < simplify->len
1106                            && simplify->path[len] == '/'
1107                            && !memcmp(path, simplify->path, len))
1108                                return 1;
1109                }
1110        }
1111        return 0;
1112}
1113
1114static int get_index_dtype(const char *path, int len)
1115{
1116        int pos;
1117        struct cache_entry *ce;
1118
1119        ce = cache_name_exists(path, len, 0);
1120        if (ce) {
1121                if (!ce_uptodate(ce))
1122                        return DT_UNKNOWN;
1123                if (S_ISGITLINK(ce->ce_mode))
1124                        return DT_DIR;
1125                /*
1126                 * Nobody actually cares about the
1127                 * difference between DT_LNK and DT_REG
1128                 */
1129                return DT_REG;
1130        }
1131
1132        /* Try to look it up as a directory */
1133        pos = cache_name_pos(path, len);
1134        if (pos >= 0)
1135                return DT_UNKNOWN;
1136        pos = -pos-1;
1137        while (pos < active_nr) {
1138                ce = active_cache[pos++];
1139                if (strncmp(ce->name, path, len))
1140                        break;
1141                if (ce->name[len] > '/')
1142                        break;
1143                if (ce->name[len] < '/')
1144                        continue;
1145                if (!ce_uptodate(ce))
1146                        break;  /* continue? */
1147                return DT_DIR;
1148        }
1149        return DT_UNKNOWN;
1150}
1151
1152static int get_dtype(struct dirent *de, const char *path, int len)
1153{
1154        int dtype = de ? DTYPE(de) : DT_UNKNOWN;
1155        struct stat st;
1156
1157        if (dtype != DT_UNKNOWN)
1158                return dtype;
1159        dtype = get_index_dtype(path, len);
1160        if (dtype != DT_UNKNOWN)
1161                return dtype;
1162        if (lstat(path, &st))
1163                return dtype;
1164        if (S_ISREG(st.st_mode))
1165                return DT_REG;
1166        if (S_ISDIR(st.st_mode))
1167                return DT_DIR;
1168        if (S_ISLNK(st.st_mode))
1169                return DT_LNK;
1170        return dtype;
1171}
1172
1173static enum path_treatment treat_one_path(struct dir_struct *dir,
1174                                          struct strbuf *path,
1175                                          const struct path_simplify *simplify,
1176                                          int dtype, struct dirent *de)
1177{
1178        int exclude;
1179        if (dtype == DT_UNKNOWN)
1180                dtype = get_dtype(de, path->buf, path->len);
1181
1182        /* Always exclude indexed files */
1183        if (dtype != DT_DIR &&
1184            cache_name_exists(path->buf, path->len, ignore_case))
1185                return path_none;
1186
1187        exclude = is_excluded(dir, path->buf, &dtype);
1188
1189        /*
1190         * Excluded? If we don't explicitly want to show
1191         * ignored files, ignore it
1192         */
1193        if (exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
1194                return path_excluded;
1195
1196        switch (dtype) {
1197        default:
1198                return path_none;
1199        case DT_DIR:
1200                strbuf_addch(path, '/');
1201                return treat_directory(dir, path->buf, path->len, exclude,
1202                        simplify);
1203        case DT_REG:
1204        case DT_LNK:
1205                return exclude ? path_excluded : path_untracked;
1206        }
1207}
1208
1209static enum path_treatment treat_path(struct dir_struct *dir,
1210                                      struct dirent *de,
1211                                      struct strbuf *path,
1212                                      int baselen,
1213                                      const struct path_simplify *simplify)
1214{
1215        int dtype;
1216
1217        if (is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name, ".git"))
1218                return path_none;
1219        strbuf_setlen(path, baselen);
1220        strbuf_addstr(path, de->d_name);
1221        if (simplify_away(path->buf, path->len, simplify))
1222                return path_none;
1223
1224        dtype = DTYPE(de);
1225        return treat_one_path(dir, path, simplify, dtype, de);
1226}
1227
1228/*
1229 * Read a directory tree. We currently ignore anything but
1230 * directories, regular files and symlinks. That's because git
1231 * doesn't handle them at all yet. Maybe that will change some
1232 * day.
1233 *
1234 * Also, we ignore the name ".git" (even if it is not a directory).
1235 * That likely will not change.
1236 *
1237 * Returns the most significant path_treatment value encountered in the scan.
1238 */
1239static enum path_treatment read_directory_recursive(struct dir_struct *dir,
1240                                    const char *base, int baselen,
1241                                    int check_only,
1242                                    const struct path_simplify *simplify)
1243{
1244        DIR *fdir;
1245        enum path_treatment state, subdir_state, dir_state = path_none;
1246        struct dirent *de;
1247        struct strbuf path = STRBUF_INIT;
1248
1249        strbuf_add(&path, base, baselen);
1250
1251        fdir = opendir(path.len ? path.buf : ".");
1252        if (!fdir)
1253                goto out;
1254
1255        while ((de = readdir(fdir)) != NULL) {
1256                /* check how the file or directory should be treated */
1257                state = treat_path(dir, de, &path, baselen, simplify);
1258                if (state > dir_state)
1259                        dir_state = state;
1260
1261                /* recurse into subdir if instructed by treat_path */
1262                if (state == path_recurse) {
1263                        subdir_state = read_directory_recursive(dir, path.buf,
1264                                path.len, check_only, simplify);
1265                        if (subdir_state > dir_state)
1266                                dir_state = subdir_state;
1267                }
1268
1269                if (check_only) {
1270                        /* abort early if maximum state has been reached */
1271                        if (dir_state == path_untracked)
1272                                break;
1273                        /* skip the dir_add_* part */
1274                        continue;
1275                }
1276
1277                /* add the path to the appropriate result list */
1278                switch (state) {
1279                case path_excluded:
1280                        if (dir->flags & DIR_SHOW_IGNORED)
1281                                dir_add_name(dir, path.buf, path.len);
1282                        else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
1283                                ((dir->flags & DIR_COLLECT_IGNORED) &&
1284                                exclude_matches_pathspec(path.buf, path.len,
1285                                        simplify)))
1286                                dir_add_ignored(dir, path.buf, path.len);
1287                        break;
1288
1289                case path_untracked:
1290                        if (!(dir->flags & DIR_SHOW_IGNORED))
1291                                dir_add_name(dir, path.buf, path.len);
1292                        break;
1293
1294                default:
1295                        break;
1296                }
1297        }
1298        closedir(fdir);
1299 out:
1300        strbuf_release(&path);
1301
1302        return dir_state;
1303}
1304
1305static int cmp_name(const void *p1, const void *p2)
1306{
1307        const struct dir_entry *e1 = *(const struct dir_entry **)p1;
1308        const struct dir_entry *e2 = *(const struct dir_entry **)p2;
1309
1310        return cache_name_compare(e1->name, e1->len,
1311                                  e2->name, e2->len);
1312}
1313
1314static struct path_simplify *create_simplify(const char **pathspec)
1315{
1316        int nr, alloc = 0;
1317        struct path_simplify *simplify = NULL;
1318
1319        if (!pathspec)
1320                return NULL;
1321
1322        for (nr = 0 ; ; nr++) {
1323                const char *match;
1324                if (nr >= alloc) {
1325                        alloc = alloc_nr(alloc);
1326                        simplify = xrealloc(simplify, alloc * sizeof(*simplify));
1327                }
1328                match = *pathspec++;
1329                if (!match)
1330                        break;
1331                simplify[nr].path = match;
1332                simplify[nr].len = simple_length(match);
1333        }
1334        simplify[nr].path = NULL;
1335        simplify[nr].len = 0;
1336        return simplify;
1337}
1338
1339static void free_simplify(struct path_simplify *simplify)
1340{
1341        free(simplify);
1342}
1343
1344static int treat_leading_path(struct dir_struct *dir,
1345                              const char *path, int len,
1346                              const struct path_simplify *simplify)
1347{
1348        struct strbuf sb = STRBUF_INIT;
1349        int baselen, rc = 0;
1350        const char *cp;
1351        int old_flags = dir->flags;
1352
1353        while (len && path[len - 1] == '/')
1354                len--;
1355        if (!len)
1356                return 1;
1357        baselen = 0;
1358        dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;
1359        while (1) {
1360                cp = path + baselen + !!baselen;
1361                cp = memchr(cp, '/', path + len - cp);
1362                if (!cp)
1363                        baselen = len;
1364                else
1365                        baselen = cp - path;
1366                strbuf_setlen(&sb, 0);
1367                strbuf_add(&sb, path, baselen);
1368                if (!is_directory(sb.buf))
1369                        break;
1370                if (simplify_away(sb.buf, sb.len, simplify))
1371                        break;
1372                if (treat_one_path(dir, &sb, simplify,
1373                                   DT_DIR, NULL) == path_none)
1374                        break; /* do not recurse into it */
1375                if (len <= baselen) {
1376                        rc = 1;
1377                        break; /* finished checking */
1378                }
1379        }
1380        strbuf_release(&sb);
1381        dir->flags = old_flags;
1382        return rc;
1383}
1384
1385int read_directory(struct dir_struct *dir, const char *path, int len, const char **pathspec)
1386{
1387        struct path_simplify *simplify;
1388
1389        if (has_symlink_leading_path(path, len))
1390                return dir->nr;
1391
1392        simplify = create_simplify(pathspec);
1393        if (!len || treat_leading_path(dir, path, len, simplify))
1394                read_directory_recursive(dir, path, len, 0, simplify);
1395        free_simplify(simplify);
1396        qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
1397        qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
1398        return dir->nr;
1399}
1400
1401int file_exists(const char *f)
1402{
1403        struct stat sb;
1404        return lstat(f, &sb) == 0;
1405}
1406
1407/*
1408 * Given two normalized paths (a trailing slash is ok), if subdir is
1409 * outside dir, return -1.  Otherwise return the offset in subdir that
1410 * can be used as relative path to dir.
1411 */
1412int dir_inside_of(const char *subdir, const char *dir)
1413{
1414        int offset = 0;
1415
1416        assert(dir && subdir && *dir && *subdir);
1417
1418        while (*dir && *subdir && *dir == *subdir) {
1419                dir++;
1420                subdir++;
1421                offset++;
1422        }
1423
1424        /* hel[p]/me vs hel[l]/yeah */
1425        if (*dir && *subdir)
1426                return -1;
1427
1428        if (!*subdir)
1429                return !*dir ? offset : -1; /* same dir */
1430
1431        /* foo/[b]ar vs foo/[] */
1432        if (is_dir_sep(dir[-1]))
1433                return is_dir_sep(subdir[-1]) ? offset : -1;
1434
1435        /* foo[/]bar vs foo[] */
1436        return is_dir_sep(*subdir) ? offset + 1 : -1;
1437}
1438
1439int is_inside_dir(const char *dir)
1440{
1441        char cwd[PATH_MAX];
1442        if (!dir)
1443                return 0;
1444        if (!getcwd(cwd, sizeof(cwd)))
1445                die_errno("can't find the current directory");
1446        return dir_inside_of(cwd, dir) >= 0;
1447}
1448
1449int is_empty_dir(const char *path)
1450{
1451        DIR *dir = opendir(path);
1452        struct dirent *e;
1453        int ret = 1;
1454
1455        if (!dir)
1456                return 0;
1457
1458        while ((e = readdir(dir)) != NULL)
1459                if (!is_dot_or_dotdot(e->d_name)) {
1460                        ret = 0;
1461                        break;
1462                }
1463
1464        closedir(dir);
1465        return ret;
1466}
1467
1468static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
1469{
1470        DIR *dir;
1471        struct dirent *e;
1472        int ret = 0, original_len = path->len, len, kept_down = 0;
1473        int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
1474        int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
1475        unsigned char submodule_head[20];
1476
1477        if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
1478            !resolve_gitlink_ref(path->buf, "HEAD", submodule_head)) {
1479                /* Do not descend and nuke a nested git work tree. */
1480                if (kept_up)
1481                        *kept_up = 1;
1482                return 0;
1483        }
1484
1485        flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
1486        dir = opendir(path->buf);
1487        if (!dir) {
1488                /* an empty dir could be removed even if it is unreadble */
1489                if (!keep_toplevel)
1490                        return rmdir(path->buf);
1491                else
1492                        return -1;
1493        }
1494        if (path->buf[original_len - 1] != '/')
1495                strbuf_addch(path, '/');
1496
1497        len = path->len;
1498        while ((e = readdir(dir)) != NULL) {
1499                struct stat st;
1500                if (is_dot_or_dotdot(e->d_name))
1501                        continue;
1502
1503                strbuf_setlen(path, len);
1504                strbuf_addstr(path, e->d_name);
1505                if (lstat(path->buf, &st))
1506                        ; /* fall thru */
1507                else if (S_ISDIR(st.st_mode)) {
1508                        if (!remove_dir_recurse(path, flag, &kept_down))
1509                                continue; /* happy */
1510                } else if (!only_empty && !unlink(path->buf))
1511                        continue; /* happy, too */
1512
1513                /* path too long, stat fails, or non-directory still exists */
1514                ret = -1;
1515                break;
1516        }
1517        closedir(dir);
1518
1519        strbuf_setlen(path, original_len);
1520        if (!ret && !keep_toplevel && !kept_down)
1521                ret = rmdir(path->buf);
1522        else if (kept_up)
1523                /*
1524                 * report the uplevel that it is not an error that we
1525                 * did not rmdir() our directory.
1526                 */
1527                *kept_up = !ret;
1528        return ret;
1529}
1530
1531int remove_dir_recursively(struct strbuf *path, int flag)
1532{
1533        return remove_dir_recurse(path, flag, NULL);
1534}
1535
1536void setup_standard_excludes(struct dir_struct *dir)
1537{
1538        const char *path;
1539        char *xdg_path;
1540
1541        dir->exclude_per_dir = ".gitignore";
1542        path = git_path("info/exclude");
1543        if (!excludes_file) {
1544                home_config_paths(NULL, &xdg_path, "ignore");
1545                excludes_file = xdg_path;
1546        }
1547        if (!access_or_warn(path, R_OK, 0))
1548                add_excludes_from_file(dir, path);
1549        if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
1550                add_excludes_from_file(dir, excludes_file);
1551}
1552
1553int remove_path(const char *name)
1554{
1555        char *slash;
1556
1557        if (unlink(name) && errno != ENOENT && errno != ENOTDIR)
1558                return -1;
1559
1560        slash = strrchr(name, '/');
1561        if (slash) {
1562                char *dirs = xstrdup(name);
1563                slash = dirs + (slash - name);
1564                do {
1565                        *slash = '\0';
1566                } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
1567                free(dirs);
1568        }
1569        return 0;
1570}
1571
1572static int pathspec_item_cmp(const void *a_, const void *b_)
1573{
1574        struct pathspec_item *a, *b;
1575
1576        a = (struct pathspec_item *)a_;
1577        b = (struct pathspec_item *)b_;
1578        return strcmp(a->match, b->match);
1579}
1580
1581int init_pathspec(struct pathspec *pathspec, const char **paths)
1582{
1583        const char **p = paths;
1584        int i;
1585
1586        memset(pathspec, 0, sizeof(*pathspec));
1587        if (!p)
1588                return 0;
1589        while (*p)
1590                p++;
1591        pathspec->raw = paths;
1592        pathspec->nr = p - paths;
1593        if (!pathspec->nr)
1594                return 0;
1595
1596        pathspec->items = xmalloc(sizeof(struct pathspec_item)*pathspec->nr);
1597        for (i = 0; i < pathspec->nr; i++) {
1598                struct pathspec_item *item = pathspec->items+i;
1599                const char *path = paths[i];
1600
1601                item->match = path;
1602                item->len = strlen(path);
1603                item->flags = 0;
1604                if (limit_pathspec_to_literal()) {
1605                        item->nowildcard_len = item->len;
1606                } else {
1607                        item->nowildcard_len = simple_length(path);
1608                        if (item->nowildcard_len < item->len) {
1609                                pathspec->has_wildcard = 1;
1610                                if (path[item->nowildcard_len] == '*' &&
1611                                    no_wildcard(path + item->nowildcard_len + 1))
1612                                        item->flags |= PATHSPEC_ONESTAR;
1613                        }
1614                }
1615        }
1616
1617        qsort(pathspec->items, pathspec->nr,
1618              sizeof(struct pathspec_item), pathspec_item_cmp);
1619
1620        return 0;
1621}
1622
1623void free_pathspec(struct pathspec *pathspec)
1624{
1625        free(pathspec->items);
1626        pathspec->items = NULL;
1627}
1628
1629int limit_pathspec_to_literal(void)
1630{
1631        static int flag = -1;
1632        if (flag < 0)
1633                flag = git_env_bool(GIT_LITERAL_PATHSPECS_ENVIRONMENT, 0);
1634        return flag;
1635}
1636
1637/*
1638 * Frees memory within dir which was allocated for exclude lists and
1639 * the exclude_stack.  Does not free dir itself.
1640 */
1641void clear_directory(struct dir_struct *dir)
1642{
1643        int i, j;
1644        struct exclude_list_group *group;
1645        struct exclude_list *el;
1646        struct exclude_stack *stk;
1647
1648        for (i = EXC_CMDL; i <= EXC_FILE; i++) {
1649                group = &dir->exclude_list_group[i];
1650                for (j = 0; j < group->nr; j++) {
1651                        el = &group->el[j];
1652                        if (i == EXC_DIRS)
1653                                free((char *)el->src);
1654                        clear_exclude_list(el);
1655                }
1656                free(group->el);
1657        }
1658
1659        stk = dir->exclude_stack;
1660        while (stk) {
1661                struct exclude_stack *prev = stk->prev;
1662                free(stk);
1663                stk = prev;
1664        }
1665}