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