6ed9eda954a85ab1052b9499b4b72a78457a6cbb
   1/*
   2 * This handles recursive filename detection with exclude
   3 * files, index knowledge etc..
   4 *
   5 * Copyright (C) Linus Torvalds, 2005-2006
   6 *               Junio Hamano, 2005-2006
   7 */
   8#include "cache.h"
   9#include "dir.h"
  10#include "refs.h"
  11
  12struct path_simplify {
  13        int len;
  14        const char *path;
  15};
  16
  17static int read_directory_recursive(struct dir_struct *dir,
  18        const char *path, const char *base, int baselen,
  19        int check_only, const struct path_simplify *simplify);
  20
  21int common_prefix(const char **pathspec)
  22{
  23        const char *path, *slash, *next;
  24        int prefix;
  25
  26        if (!pathspec)
  27                return 0;
  28
  29        path = *pathspec;
  30        slash = strrchr(path, '/');
  31        if (!slash)
  32                return 0;
  33
  34        prefix = slash - path + 1;
  35        while ((next = *++pathspec) != NULL) {
  36                int len = strlen(next);
  37                if (len >= prefix && !memcmp(path, next, prefix))
  38                        continue;
  39                len = prefix - 1;
  40                for (;;) {
  41                        if (!len)
  42                                return 0;
  43                        if (next[--len] != '/')
  44                                continue;
  45                        if (memcmp(path, next, len+1))
  46                                continue;
  47                        prefix = len + 1;
  48                        break;
  49                }
  50        }
  51        return prefix;
  52}
  53
  54/*
  55 * Does 'match' matches the given name?
  56 * A match is found if
  57 *
  58 * (1) the 'match' string is leading directory of 'name', or
  59 * (2) the 'match' string is a wildcard and matches 'name', or
  60 * (3) the 'match' string is exactly the same as 'name'.
  61 *
  62 * and the return value tells which case it was.
  63 *
  64 * It returns 0 when there is no match.
  65 */
  66static int match_one(const char *match, const char *name, int namelen)
  67{
  68        int matchlen;
  69
  70        /* If the match was just the prefix, we matched */
  71        matchlen = strlen(match);
  72        if (!matchlen)
  73                return MATCHED_RECURSIVELY;
  74
  75        /*
  76         * If we don't match the matchstring exactly,
  77         * we need to match by fnmatch
  78         */
  79        if (strncmp(match, name, matchlen))
  80                return !fnmatch(match, name, 0) ? MATCHED_FNMATCH : 0;
  81
  82        if (!name[matchlen])
  83                return MATCHED_EXACTLY;
  84        if (match[matchlen-1] == '/' || name[matchlen] == '/')
  85                return MATCHED_RECURSIVELY;
  86        return 0;
  87}
  88
  89/*
  90 * Given a name and a list of pathspecs, see if the name matches
  91 * any of the pathspecs.  The caller is also interested in seeing
  92 * all pathspec matches some names it calls this function with
  93 * (otherwise the user could have mistyped the unmatched pathspec),
  94 * and a mark is left in seen[] array for pathspec element that
  95 * actually matched anything.
  96 */
  97int match_pathspec(const char **pathspec, const char *name, int namelen, int prefix, char *seen)
  98{
  99        int retval;
 100        const char *match;
 101
 102        name += prefix;
 103        namelen -= prefix;
 104
 105        for (retval = 0; (match = *pathspec++) != NULL; seen++) {
 106                int how;
 107                if (retval && *seen == MATCHED_EXACTLY)
 108                        continue;
 109                match += prefix;
 110                how = match_one(match, name, namelen);
 111                if (how) {
 112                        if (retval < how)
 113                                retval = how;
 114                        if (*seen < how)
 115                                *seen = how;
 116                }
 117        }
 118        return retval;
 119}
 120
 121void add_exclude(const char *string, const char *base,
 122                 int baselen, struct exclude_list *which)
 123{
 124        struct exclude *x = xmalloc(sizeof (*x));
 125
 126        x->pattern = string;
 127        x->base = base;
 128        x->baselen = baselen;
 129        if (which->nr == which->alloc) {
 130                which->alloc = alloc_nr(which->alloc);
 131                which->excludes = xrealloc(which->excludes,
 132                                           which->alloc * sizeof(x));
 133        }
 134        which->excludes[which->nr++] = x;
 135}
 136
 137static int add_excludes_from_file_1(const char *fname,
 138                                    const char *base,
 139                                    int baselen,
 140                                    struct exclude_list *which)
 141{
 142        struct stat st;
 143        int fd, i;
 144        size_t size;
 145        char *buf, *entry;
 146
 147        fd = open(fname, O_RDONLY);
 148        if (fd < 0 || fstat(fd, &st) < 0)
 149                goto err;
 150        size = xsize_t(st.st_size);
 151        if (size == 0) {
 152                close(fd);
 153                return 0;
 154        }
 155        buf = xmalloc(size+1);
 156        if (read_in_full(fd, buf, size) != size)
 157                goto err;
 158        close(fd);
 159
 160        buf[size++] = '\n';
 161        entry = buf;
 162        for (i = 0; i < size; i++) {
 163                if (buf[i] == '\n') {
 164                        if (entry != buf + i && entry[0] != '#') {
 165                                buf[i - (i && buf[i-1] == '\r')] = 0;
 166                                add_exclude(entry, base, baselen, which);
 167                        }
 168                        entry = buf + i + 1;
 169                }
 170        }
 171        return 0;
 172
 173 err:
 174        if (0 <= fd)
 175                close(fd);
 176        return -1;
 177}
 178
 179void add_excludes_from_file(struct dir_struct *dir, const char *fname)
 180{
 181        if (add_excludes_from_file_1(fname, "", 0,
 182                                     &dir->exclude_list[EXC_FILE]) < 0)
 183                die("cannot use %s as an exclude file", fname);
 184}
 185
 186int push_exclude_per_directory(struct dir_struct *dir, const char *base, int baselen)
 187{
 188        char exclude_file[PATH_MAX];
 189        struct exclude_list *el = &dir->exclude_list[EXC_DIRS];
 190        int current_nr = el->nr;
 191
 192        if (dir->exclude_per_dir) {
 193                memcpy(exclude_file, base, baselen);
 194                strcpy(exclude_file + baselen, dir->exclude_per_dir);
 195                add_excludes_from_file_1(exclude_file, base, baselen, el);
 196        }
 197        return current_nr;
 198}
 199
 200void pop_exclude_per_directory(struct dir_struct *dir, int stk)
 201{
 202        struct exclude_list *el = &dir->exclude_list[EXC_DIRS];
 203
 204        while (stk < el->nr)
 205                free(el->excludes[--el->nr]);
 206}
 207
 208/* Scan the list and let the last match determines the fate.
 209 * Return 1 for exclude, 0 for include and -1 for undecided.
 210 */
 211static int excluded_1(const char *pathname,
 212                      int pathlen,
 213                      struct exclude_list *el)
 214{
 215        int i;
 216
 217        if (el->nr) {
 218                for (i = el->nr - 1; 0 <= i; i--) {
 219                        struct exclude *x = el->excludes[i];
 220                        const char *exclude = x->pattern;
 221                        int to_exclude = 1;
 222
 223                        if (*exclude == '!') {
 224                                to_exclude = 0;
 225                                exclude++;
 226                        }
 227
 228                        if (!strchr(exclude, '/')) {
 229                                /* match basename */
 230                                const char *basename = strrchr(pathname, '/');
 231                                basename = (basename) ? basename+1 : pathname;
 232                                if (fnmatch(exclude, basename, 0) == 0)
 233                                        return to_exclude;
 234                        }
 235                        else {
 236                                /* match with FNM_PATHNAME:
 237                                 * exclude has base (baselen long) implicitly
 238                                 * in front of it.
 239                                 */
 240                                int baselen = x->baselen;
 241                                if (*exclude == '/')
 242                                        exclude++;
 243
 244                                if (pathlen < baselen ||
 245                                    (baselen && pathname[baselen-1] != '/') ||
 246                                    strncmp(pathname, x->base, baselen))
 247                                    continue;
 248
 249                                if (fnmatch(exclude, pathname+baselen,
 250                                            FNM_PATHNAME) == 0)
 251                                        return to_exclude;
 252                        }
 253                }
 254        }
 255        return -1; /* undecided */
 256}
 257
 258int excluded(struct dir_struct *dir, const char *pathname)
 259{
 260        int pathlen = strlen(pathname);
 261        int st;
 262
 263        for (st = EXC_CMDL; st <= EXC_FILE; st++) {
 264                switch (excluded_1(pathname, pathlen, &dir->exclude_list[st])) {
 265                case 0:
 266                        return 0;
 267                case 1:
 268                        return 1;
 269                }
 270        }
 271        return 0;
 272}
 273
 274static struct dir_entry *dir_entry_new(const char *pathname, int len) {
 275        struct dir_entry *ent;
 276
 277        ent = xmalloc(sizeof(*ent) + len + 1);
 278        ent->ignored = ent->ignored_dir = 0;
 279        ent->len = len;
 280        memcpy(ent->name, pathname, len);
 281        ent->name[len] = 0;
 282        return ent;
 283}
 284
 285struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
 286{
 287        if (cache_name_pos(pathname, len) >= 0)
 288                return NULL;
 289
 290        ALLOC_GROW(dir->entries, dir->nr, dir->alloc);
 291        return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
 292}
 293
 294struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
 295{
 296        if (cache_name_pos(pathname, len) >= 0)
 297                return NULL;
 298
 299        ALLOC_GROW(dir->ignored, dir->ignored_nr, dir->ignored_alloc);
 300        return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
 301}
 302
 303enum exist_status {
 304        index_nonexistent = 0,
 305        index_directory,
 306        index_gitdir,
 307};
 308
 309/*
 310 * The index sorts alphabetically by entry name, which
 311 * means that a gitlink sorts as '\0' at the end, while
 312 * a directory (which is defined not as an entry, but as
 313 * the files it contains) will sort with the '/' at the
 314 * end.
 315 */
 316static enum exist_status directory_exists_in_index(const char *dirname, int len)
 317{
 318        int pos = cache_name_pos(dirname, len);
 319        if (pos < 0)
 320                pos = -pos-1;
 321        while (pos < active_nr) {
 322                struct cache_entry *ce = active_cache[pos++];
 323                unsigned char endchar;
 324
 325                if (strncmp(ce->name, dirname, len))
 326                        break;
 327                endchar = ce->name[len];
 328                if (endchar > '/')
 329                        break;
 330                if (endchar == '/')
 331                        return index_directory;
 332                if (!endchar && S_ISGITLINK(ntohl(ce->ce_mode)))
 333                        return index_gitdir;
 334        }
 335        return index_nonexistent;
 336}
 337
 338/*
 339 * When we find a directory when traversing the filesystem, we
 340 * have three distinct cases:
 341 *
 342 *  - ignore it
 343 *  - see it as a directory
 344 *  - recurse into it
 345 *
 346 * and which one we choose depends on a combination of existing
 347 * git index contents and the flags passed into the directory
 348 * traversal routine.
 349 *
 350 * Case 1: If we *already* have entries in the index under that
 351 * directory name, we always recurse into the directory to see
 352 * all the files.
 353 *
 354 * Case 2: If we *already* have that directory name as a gitlink,
 355 * we always continue to see it as a gitlink, regardless of whether
 356 * there is an actual git directory there or not (it might not
 357 * be checked out as a subproject!)
 358 *
 359 * Case 3: if we didn't have it in the index previously, we
 360 * have a few sub-cases:
 361 *
 362 *  (a) if "show_other_directories" is true, we show it as
 363 *      just a directory, unless "hide_empty_directories" is
 364 *      also true and the directory is empty, in which case
 365 *      we just ignore it entirely.
 366 *  (b) if it looks like a git directory, and we don't have
 367 *      'no_gitlinks' set we treat it as a gitlink, and show it
 368 *      as a directory.
 369 *  (c) otherwise, we recurse into it.
 370 */
 371enum directory_treatment {
 372        show_directory,
 373        ignore_directory,
 374        recurse_into_directory,
 375};
 376
 377static enum directory_treatment treat_directory(struct dir_struct *dir,
 378        const char *dirname, int len,
 379        const struct path_simplify *simplify)
 380{
 381        /* The "len-1" is to strip the final '/' */
 382        switch (directory_exists_in_index(dirname, len-1)) {
 383        case index_directory:
 384                return recurse_into_directory;
 385
 386        case index_gitdir:
 387                if (dir->show_other_directories)
 388                        return ignore_directory;
 389                return show_directory;
 390
 391        case index_nonexistent:
 392                if (dir->show_other_directories)
 393                        break;
 394                if (!dir->no_gitlinks) {
 395                        unsigned char sha1[20];
 396                        if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
 397                                return show_directory;
 398                }
 399                return recurse_into_directory;
 400        }
 401
 402        /* This is the "show_other_directories" case */
 403        if (!dir->hide_empty_directories)
 404                return show_directory;
 405        if (!read_directory_recursive(dir, dirname, dirname, len, 1, simplify))
 406                return ignore_directory;
 407        return show_directory;
 408}
 409
 410/*
 411 * This is an inexact early pruning of any recursive directory
 412 * reading - if the path cannot possibly be in the pathspec,
 413 * return true, and we'll skip it early.
 414 */
 415static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
 416{
 417        if (simplify) {
 418                for (;;) {
 419                        const char *match = simplify->path;
 420                        int len = simplify->len;
 421
 422                        if (!match)
 423                                break;
 424                        if (len > pathlen)
 425                                len = pathlen;
 426                        if (!memcmp(path, match, len))
 427                                return 0;
 428                        simplify++;
 429                }
 430                return 1;
 431        }
 432        return 0;
 433}
 434
 435/*
 436 * Read a directory tree. We currently ignore anything but
 437 * directories, regular files and symlinks. That's because git
 438 * doesn't handle them at all yet. Maybe that will change some
 439 * day.
 440 *
 441 * Also, we ignore the name ".git" (even if it is not a directory).
 442 * That likely will not change.
 443 */
 444static int read_directory_recursive(struct dir_struct *dir, const char *path, const char *base, int baselen, int check_only, const struct path_simplify *simplify)
 445{
 446        DIR *fdir = opendir(path);
 447        int contents = 0;
 448
 449        if (fdir) {
 450                int exclude_stk;
 451                struct dirent *de;
 452                char fullname[PATH_MAX + 1];
 453                memcpy(fullname, base, baselen);
 454
 455                exclude_stk = push_exclude_per_directory(dir, base, baselen);
 456
 457                while ((de = readdir(fdir)) != NULL) {
 458                        int len;
 459                        int exclude;
 460
 461                        if ((de->d_name[0] == '.') &&
 462                            (de->d_name[1] == 0 ||
 463                             !strcmp(de->d_name + 1, ".") ||
 464                             !strcmp(de->d_name + 1, "git")))
 465                                continue;
 466                        len = strlen(de->d_name);
 467                        /* Ignore overly long pathnames! */
 468                        if (len + baselen + 8 > sizeof(fullname))
 469                                continue;
 470                        memcpy(fullname + baselen, de->d_name, len+1);
 471                        if (simplify_away(fullname, baselen + len, simplify))
 472                                continue;
 473
 474                        exclude = excluded(dir, fullname);
 475                        if (exclude && dir->collect_ignored)
 476                                dir_add_ignored(dir, fullname, baselen + len);
 477                        if (exclude != dir->show_ignored) {
 478                                if (!dir->show_ignored || DTYPE(de) != DT_DIR) {
 479                                        continue;
 480                                }
 481                        }
 482
 483                        switch (DTYPE(de)) {
 484                        struct stat st;
 485                        default:
 486                                continue;
 487                        case DT_UNKNOWN:
 488                                if (lstat(fullname, &st))
 489                                        continue;
 490                                if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
 491                                        break;
 492                                if (!S_ISDIR(st.st_mode))
 493                                        continue;
 494                                /* fallthrough */
 495                        case DT_DIR:
 496                                memcpy(fullname + baselen + len, "/", 2);
 497                                len++;
 498                                switch (treat_directory(dir, fullname, baselen + len, simplify)) {
 499                                case show_directory:
 500                                        if (exclude != dir->show_ignored)
 501                                                continue;
 502                                        break;
 503                                case recurse_into_directory:
 504                                        contents += read_directory_recursive(dir,
 505                                                fullname, fullname, baselen + len, 0, simplify);
 506                                        continue;
 507                                case ignore_directory:
 508                                        continue;
 509                                }
 510                                break;
 511                        case DT_REG:
 512                        case DT_LNK:
 513                                break;
 514                        }
 515                        contents++;
 516                        if (check_only)
 517                                goto exit_early;
 518                        else
 519                                dir_add_name(dir, fullname, baselen + len);
 520                }
 521exit_early:
 522                closedir(fdir);
 523
 524                pop_exclude_per_directory(dir, exclude_stk);
 525        }
 526
 527        return contents;
 528}
 529
 530static int cmp_name(const void *p1, const void *p2)
 531{
 532        const struct dir_entry *e1 = *(const struct dir_entry **)p1;
 533        const struct dir_entry *e2 = *(const struct dir_entry **)p2;
 534
 535        return cache_name_compare(e1->name, e1->len,
 536                                  e2->name, e2->len);
 537}
 538
 539/*
 540 * Return the length of the "simple" part of a path match limiter.
 541 */
 542static int simple_length(const char *match)
 543{
 544        const char special[256] = {
 545                [0] = 1, ['?'] = 1,
 546                ['\\'] = 1, ['*'] = 1,
 547                ['['] = 1
 548        };
 549        int len = -1;
 550
 551        for (;;) {
 552                unsigned char c = *match++;
 553                len++;
 554                if (special[c])
 555                        return len;
 556        }
 557}
 558
 559static struct path_simplify *create_simplify(const char **pathspec)
 560{
 561        int nr, alloc = 0;
 562        struct path_simplify *simplify = NULL;
 563
 564        if (!pathspec)
 565                return NULL;
 566
 567        for (nr = 0 ; ; nr++) {
 568                const char *match;
 569                if (nr >= alloc) {
 570                        alloc = alloc_nr(alloc);
 571                        simplify = xrealloc(simplify, alloc * sizeof(*simplify));
 572                }
 573                match = *pathspec++;
 574                if (!match)
 575                        break;
 576                simplify[nr].path = match;
 577                simplify[nr].len = simple_length(match);
 578        }
 579        simplify[nr].path = NULL;
 580        simplify[nr].len = 0;
 581        return simplify;
 582}
 583
 584static void free_simplify(struct path_simplify *simplify)
 585{
 586        if (simplify)
 587                free(simplify);
 588}
 589
 590int read_directory(struct dir_struct *dir, const char *path, const char *base, int baselen, const char **pathspec)
 591{
 592        struct path_simplify *simplify = create_simplify(pathspec);
 593
 594        /*
 595         * Make sure to do the per-directory exclude for all the
 596         * directories leading up to our base.
 597         */
 598        if (baselen) {
 599                if (dir->exclude_per_dir) {
 600                        char *p, *pp = xmalloc(baselen+1);
 601                        memcpy(pp, base, baselen+1);
 602                        p = pp;
 603                        while (1) {
 604                                char save = *p;
 605                                *p = 0;
 606                                push_exclude_per_directory(dir, pp, p-pp);
 607                                *p++ = save;
 608                                if (!save)
 609                                        break;
 610                                p = strchr(p, '/');
 611                                if (p)
 612                                        p++;
 613                                else
 614                                        p = pp + baselen;
 615                        }
 616                        free(pp);
 617                }
 618        }
 619
 620        read_directory_recursive(dir, path, base, baselen, 0, simplify);
 621        free_simplify(simplify);
 622        qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
 623        qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
 624        return dir->nr;
 625}
 626
 627int
 628file_exists(const char *f)
 629{
 630  struct stat sb;
 631  return stat(f, &sb) == 0;
 632}