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