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