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