ls-files.con commit Merge branch 'fixes' (82ed2bc)
   1/*
   2 * This merges the file listing in the directory cache index
   3 * with the actual working directory list, and shows different
   4 * combinations of the two.
   5 *
   6 * Copyright (C) Linus Torvalds, 2005
   7 */
   8#include <dirent.h>
   9#include <fnmatch.h>
  10
  11#include "cache.h"
  12
  13static int show_deleted = 0;
  14static int show_cached = 0;
  15static int show_others = 0;
  16static int show_ignored = 0;
  17static int show_stage = 0;
  18static int show_unmerged = 0;
  19static int show_modified = 0;
  20static int show_killed = 0;
  21static int line_terminator = '\n';
  22
  23static int prefix_len = 0, prefix_offset = 0;
  24static const char *prefix = NULL;
  25static const char **pathspec = NULL;
  26
  27static const char *tag_cached = "";
  28static const char *tag_unmerged = "";
  29static const char *tag_removed = "";
  30static const char *tag_other = "";
  31static const char *tag_killed = "";
  32static const char *tag_modified = "";
  33
  34static const char *exclude_per_dir = NULL;
  35
  36/* We maintain three exclude pattern lists:
  37 * EXC_CMDL lists patterns explicitly given on the command line.
  38 * EXC_DIRS lists patterns obtained from per-directory ignore files.
  39 * EXC_FILE lists patterns from fallback ignore files.
  40 */
  41#define EXC_CMDL 0
  42#define EXC_DIRS 1
  43#define EXC_FILE 2
  44static struct exclude_list {
  45        int nr;
  46        int alloc;
  47        struct exclude {
  48                const char *pattern;
  49                const char *base;
  50                int baselen;
  51        } **excludes;
  52} exclude_list[3];
  53
  54static void add_exclude(const char *string, const char *base,
  55                        int baselen, struct exclude_list *which)
  56{
  57        struct exclude *x = xmalloc(sizeof (*x));
  58
  59        x->pattern = string;
  60        x->base = base;
  61        x->baselen = baselen;
  62        if (which->nr == which->alloc) {
  63                which->alloc = alloc_nr(which->alloc);
  64                which->excludes = realloc(which->excludes,
  65                                          which->alloc * sizeof(x));
  66        }
  67        which->excludes[which->nr++] = x;
  68}
  69
  70static int add_excludes_from_file_1(const char *fname,
  71                                    const char *base,
  72                                    int baselen,
  73                                    struct exclude_list *which)
  74{
  75        int fd, i;
  76        long size;
  77        char *buf, *entry;
  78
  79        fd = open(fname, O_RDONLY);
  80        if (fd < 0)
  81                goto err;
  82        size = lseek(fd, 0, SEEK_END);
  83        if (size < 0)
  84                goto err;
  85        lseek(fd, 0, SEEK_SET);
  86        if (size == 0) {
  87                close(fd);
  88                return 0;
  89        }
  90        buf = xmalloc(size);
  91        if (read(fd, buf, size) != size)
  92                goto err;
  93        close(fd);
  94
  95        entry = buf;
  96        for (i = 0; i < size; i++) {
  97                if (buf[i] == '\n') {
  98                        if (entry != buf + i && entry[0] != '#') {
  99                                buf[i] = 0;
 100                                add_exclude(entry, base, baselen, which);
 101                        }
 102                        entry = buf + i + 1;
 103                }
 104        }
 105        return 0;
 106
 107 err:
 108        if (0 <= fd)
 109                close(fd);
 110        return -1;
 111}
 112
 113static void add_excludes_from_file(const char *fname)
 114{
 115        if (add_excludes_from_file_1(fname, "", 0,
 116                                     &exclude_list[EXC_FILE]) < 0)
 117                die("cannot use %s as an exclude file", fname);
 118}
 119
 120static int push_exclude_per_directory(const char *base, int baselen)
 121{
 122        char exclude_file[PATH_MAX];
 123        struct exclude_list *el = &exclude_list[EXC_DIRS];
 124        int current_nr = el->nr;
 125
 126        if (exclude_per_dir) {
 127                memcpy(exclude_file, base, baselen);
 128                strcpy(exclude_file + baselen, exclude_per_dir);
 129                add_excludes_from_file_1(exclude_file, base, baselen, el);
 130        }
 131        return current_nr;
 132}
 133
 134static void pop_exclude_per_directory(int stk)
 135{
 136        struct exclude_list *el = &exclude_list[EXC_DIRS];
 137
 138        while (stk < el->nr)
 139                free(el->excludes[--el->nr]);
 140}
 141
 142/* Scan the list and let the last match determines the fate.
 143 * Return 1 for exclude, 0 for include and -1 for undecided.
 144 */
 145static int excluded_1(const char *pathname,
 146                      int pathlen,
 147                      struct exclude_list *el)
 148{
 149        int i;
 150
 151        if (el->nr) {
 152                for (i = el->nr - 1; 0 <= i; i--) {
 153                        struct exclude *x = el->excludes[i];
 154                        const char *exclude = x->pattern;
 155                        int to_exclude = 1;
 156
 157                        if (*exclude == '!') {
 158                                to_exclude = 0;
 159                                exclude++;
 160                        }
 161
 162                        if (!strchr(exclude, '/')) {
 163                                /* match basename */
 164                                const char *basename = strrchr(pathname, '/');
 165                                basename = (basename) ? basename+1 : pathname;
 166                                if (fnmatch(exclude, basename, 0) == 0)
 167                                        return to_exclude;
 168                        }
 169                        else {
 170                                /* match with FNM_PATHNAME:
 171                                 * exclude has base (baselen long) inplicitly
 172                                 * in front of it.
 173                                 */
 174                                int baselen = x->baselen;
 175                                if (*exclude == '/')
 176                                        exclude++;
 177
 178                                if (pathlen < baselen ||
 179                                    (baselen && pathname[baselen-1] != '/') ||
 180                                    strncmp(pathname, x->base, baselen))
 181                                    continue;
 182
 183                                if (fnmatch(exclude, pathname+baselen,
 184                                            FNM_PATHNAME) == 0)
 185                                        return to_exclude;
 186                        }
 187                }
 188        }
 189        return -1; /* undecided */
 190}
 191
 192static int excluded(const char *pathname)
 193{
 194        int pathlen = strlen(pathname);
 195        int st;
 196
 197        for (st = EXC_CMDL; st <= EXC_FILE; st++) {
 198                switch (excluded_1(pathname, pathlen, &exclude_list[st])) {
 199                case 0:
 200                        return 0;
 201                case 1:
 202                        return 1;
 203                }
 204        }
 205        return 0;
 206}
 207
 208struct nond_on_fs {
 209        int len;
 210        char name[0];
 211};
 212
 213static struct nond_on_fs **dir;
 214static int nr_dir;
 215static int dir_alloc;
 216
 217static void add_name(const char *pathname, int len)
 218{
 219        struct nond_on_fs *ent;
 220
 221        if (cache_name_pos(pathname, len) >= 0)
 222                return;
 223
 224        if (nr_dir == dir_alloc) {
 225                dir_alloc = alloc_nr(dir_alloc);
 226                dir = xrealloc(dir, dir_alloc*sizeof(ent));
 227        }
 228        ent = xmalloc(sizeof(*ent) + len + 1);
 229        ent->len = len;
 230        memcpy(ent->name, pathname, len);
 231        ent->name[len] = 0;
 232        dir[nr_dir++] = ent;
 233}
 234
 235/*
 236 * Read a directory tree. We currently ignore anything but
 237 * directories, regular files and symlinks. That's because git
 238 * doesn't handle them at all yet. Maybe that will change some
 239 * day.
 240 *
 241 * Also, we ignore the name ".git" (even if it is not a directory).
 242 * That likely will not change.
 243 */
 244static void read_directory(const char *path, const char *base, int baselen)
 245{
 246        DIR *dir = opendir(path);
 247
 248        if (dir) {
 249                int exclude_stk;
 250                struct dirent *de;
 251                char fullname[MAXPATHLEN + 1];
 252                memcpy(fullname, base, baselen);
 253
 254                exclude_stk = push_exclude_per_directory(base, baselen);
 255
 256                while ((de = readdir(dir)) != NULL) {
 257                        int len;
 258
 259                        if ((de->d_name[0] == '.') &&
 260                            (de->d_name[1] == 0 ||
 261                             !strcmp(de->d_name + 1, ".") ||
 262                             !strcmp(de->d_name + 1, "git")))
 263                                continue;
 264                        len = strlen(de->d_name);
 265                        memcpy(fullname + baselen, de->d_name, len+1);
 266                        if (excluded(fullname) != show_ignored)
 267                                continue;
 268
 269                        switch (DTYPE(de)) {
 270                        struct stat st;
 271                        default:
 272                                continue;
 273                        case DT_UNKNOWN:
 274                                if (lstat(fullname, &st))
 275                                        continue;
 276                                if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
 277                                        break;
 278                                if (!S_ISDIR(st.st_mode))
 279                                        continue;
 280                                /* fallthrough */
 281                        case DT_DIR:
 282                                memcpy(fullname + baselen + len, "/", 2);
 283                                read_directory(fullname, fullname,
 284                                               baselen + len + 1);
 285                                continue;
 286                        case DT_REG:
 287                        case DT_LNK:
 288                                break;
 289                        }
 290                        add_name(fullname, baselen + len);
 291                }
 292                closedir(dir);
 293
 294                pop_exclude_per_directory(exclude_stk);
 295        }
 296}
 297
 298static int cmp_name(const void *p1, const void *p2)
 299{
 300        const struct nond_on_fs *e1 = *(const struct nond_on_fs **)p1;
 301        const struct nond_on_fs *e2 = *(const struct nond_on_fs **)p2;
 302
 303        return cache_name_compare(e1->name, e1->len,
 304                                  e2->name, e2->len);
 305}
 306
 307/*
 308 * Match a pathspec against a filename. The first "len" characters
 309 * are the common prefix
 310 */
 311static int match(const char **spec, const char *filename, int len)
 312{
 313        const char *m;
 314
 315        while ((m = *spec++) != NULL) {
 316                int matchlen = strlen(m + len);
 317
 318                if (!matchlen)
 319                        return 1;
 320                if (!strncmp(m + len, filename + len, matchlen)) {
 321                        if (m[len + matchlen - 1] == '/')
 322                                return 1;
 323                        switch (filename[len + matchlen]) {
 324                        case '/': case '\0':
 325                                return 1;
 326                        }
 327                }
 328                if (!fnmatch(m + len, filename + len, 0))
 329                        return 1;
 330        }
 331        return 0;
 332}
 333
 334static void show_dir_entry(const char *tag, struct nond_on_fs *ent)
 335{
 336        int len = prefix_len;
 337        int offset = prefix_offset;
 338
 339        if (len >= ent->len)
 340                die("git-ls-files: internal error - directory entry not superset of prefix");
 341
 342        if (pathspec && !match(pathspec, ent->name, len))
 343                return;
 344
 345        printf("%s%s%c", tag, ent->name + offset, line_terminator);
 346}
 347
 348static void show_killed_files(void)
 349{
 350        int i;
 351        for (i = 0; i < nr_dir; i++) {
 352                struct nond_on_fs *ent = dir[i];
 353                char *cp, *sp;
 354                int pos, len, killed = 0;
 355
 356                for (cp = ent->name; cp - ent->name < ent->len; cp = sp + 1) {
 357                        sp = strchr(cp, '/');
 358                        if (!sp) {
 359                                /* If ent->name is prefix of an entry in the
 360                                 * cache, it will be killed.
 361                                 */
 362                                pos = cache_name_pos(ent->name, ent->len);
 363                                if (0 <= pos)
 364                                        die("bug in show-killed-files");
 365                                pos = -pos - 1;
 366                                while (pos < active_nr &&
 367                                       ce_stage(active_cache[pos]))
 368                                        pos++; /* skip unmerged */
 369                                if (active_nr <= pos)
 370                                        break;
 371                                /* pos points at a name immediately after
 372                                 * ent->name in the cache.  Does it expect
 373                                 * ent->name to be a directory?
 374                                 */
 375                                len = ce_namelen(active_cache[pos]);
 376                                if ((ent->len < len) &&
 377                                    !strncmp(active_cache[pos]->name,
 378                                             ent->name, ent->len) &&
 379                                    active_cache[pos]->name[ent->len] == '/')
 380                                        killed = 1;
 381                                break;
 382                        }
 383                        if (0 <= cache_name_pos(ent->name, sp - ent->name)) {
 384                                /* If any of the leading directories in
 385                                 * ent->name is registered in the cache,
 386                                 * ent->name will be killed.
 387                                 */
 388                                killed = 1;
 389                                break;
 390                        }
 391                }
 392                if (killed)
 393                        show_dir_entry(tag_killed, dir[i]);
 394        }
 395}
 396
 397static void show_ce_entry(const char *tag, struct cache_entry *ce)
 398{
 399        int len = prefix_len;
 400        int offset = prefix_offset;
 401
 402        if (len >= ce_namelen(ce))
 403                die("git-ls-files: internal error - cache entry not superset of prefix");
 404
 405        if (pathspec && !match(pathspec, ce->name, len))
 406                return;
 407
 408        if (!show_stage)
 409                printf("%s%s%c", tag, ce->name + offset, line_terminator);
 410        else
 411                printf("%s%06o %s %d\t%s%c",
 412                       tag,
 413                       ntohl(ce->ce_mode),
 414                       sha1_to_hex(ce->sha1),
 415                       ce_stage(ce),
 416                       ce->name + offset, line_terminator); 
 417}
 418
 419static void show_files(void)
 420{
 421        int i;
 422
 423        /* For cached/deleted files we don't need to even do the readdir */
 424        if (show_others || show_killed) {
 425                const char *path = ".", *base = "";
 426                int baselen = prefix_len;
 427
 428                if (baselen)
 429                        path = base = prefix;
 430                read_directory(path, base, baselen);
 431                qsort(dir, nr_dir, sizeof(struct nond_on_fs *), cmp_name);
 432                if (show_others)
 433                        for (i = 0; i < nr_dir; i++)
 434                                show_dir_entry(tag_other, dir[i]);
 435                if (show_killed)
 436                        show_killed_files();
 437        }
 438        if (show_cached | show_stage) {
 439                for (i = 0; i < active_nr; i++) {
 440                        struct cache_entry *ce = active_cache[i];
 441                        if (excluded(ce->name) != show_ignored)
 442                                continue;
 443                        if (show_unmerged && !ce_stage(ce))
 444                                continue;
 445                        show_ce_entry(ce_stage(ce) ? tag_unmerged : tag_cached, ce);
 446                }
 447        }
 448        if (show_deleted | show_modified) {
 449                for (i = 0; i < active_nr; i++) {
 450                        struct cache_entry *ce = active_cache[i];
 451                        struct stat st;
 452                        int err;
 453                        if (excluded(ce->name) != show_ignored)
 454                                continue;
 455                        err = lstat(ce->name, &st);
 456                        if (show_deleted && err)
 457                                show_ce_entry(tag_removed, ce);
 458                        if (show_modified && ce_modified(ce, &st))
 459                                show_ce_entry(tag_modified, ce);
 460                }
 461        }
 462}
 463
 464/*
 465 * Prune the index to only contain stuff starting with "prefix"
 466 */
 467static void prune_cache(void)
 468{
 469        int pos = cache_name_pos(prefix, prefix_len);
 470        unsigned int first, last;
 471
 472        if (pos < 0)
 473                pos = -pos-1;
 474        active_cache += pos;
 475        active_nr -= pos;
 476        first = 0;
 477        last = active_nr;
 478        while (last > first) {
 479                int next = (last + first) >> 1;
 480                struct cache_entry *ce = active_cache[next];
 481                if (!strncmp(ce->name, prefix, prefix_len)) {
 482                        first = next+1;
 483                        continue;
 484                }
 485                last = next;
 486        }
 487        active_nr = last;
 488}
 489
 490static void verify_pathspec(void)
 491{
 492        const char **p, *n, *prev;
 493        char *real_prefix;
 494        unsigned long max;
 495
 496        prev = NULL;
 497        max = PATH_MAX;
 498        for (p = pathspec; (n = *p) != NULL; p++) {
 499                int i, len = 0;
 500                for (i = 0; i < max; i++) {
 501                        char c = n[i];
 502                        if (prev && prev[i] != c)
 503                                break;
 504                        if (!c || c == '*' || c == '?')
 505                                break;
 506                        if (c == '/')
 507                                len = i+1;
 508                }
 509                prev = n;
 510                if (len < max) {
 511                        max = len;
 512                        if (!max)
 513                                break;
 514                }
 515        }
 516
 517        if (prefix_offset > max || memcmp(prev, prefix, prefix_offset))
 518                die("git-ls-files: cannot generate relative filenames containing '..'");
 519
 520        real_prefix = NULL;
 521        prefix_len = max;
 522        if (max) {
 523                real_prefix = xmalloc(max + 1);
 524                memcpy(real_prefix, prev, max);
 525                real_prefix[max] = 0;
 526        }
 527        prefix = real_prefix;
 528}
 529
 530static const char ls_files_usage[] =
 531        "git-ls-files [-z] [-t] (--[cached|deleted|others|stage|unmerged|killed|modified])* "
 532        "[ --ignored ] [--exclude=<pattern>] [--exclude-from=<file>] "
 533        "[ --exclude-per-directory=<filename> ] [--] [<file>]*";
 534
 535int main(int argc, const char **argv)
 536{
 537        int i;
 538        int exc_given = 0;
 539
 540        prefix = setup_git_directory();
 541        if (prefix)
 542                prefix_offset = strlen(prefix);
 543
 544        for (i = 1; i < argc; i++) {
 545                const char *arg = argv[i];
 546
 547                if (!strcmp(arg, "--")) {
 548                        i++;
 549                        break;
 550                }
 551                if (!strcmp(arg, "-z")) {
 552                        line_terminator = 0;
 553                        continue;
 554                }
 555                if (!strcmp(arg, "-t")) {
 556                        tag_cached = "H ";
 557                        tag_unmerged = "M ";
 558                        tag_removed = "R ";
 559                        tag_modified = "C ";
 560                        tag_other = "? ";
 561                        tag_killed = "K ";
 562                        continue;
 563                }
 564                if (!strcmp(arg, "-c") || !strcmp(arg, "--cached")) {
 565                        show_cached = 1;
 566                        continue;
 567                }
 568                if (!strcmp(arg, "-d") || !strcmp(arg, "--deleted")) {
 569                        show_deleted = 1;
 570                        continue;
 571                }
 572                if (!strcmp(arg, "-m") || !strcmp(arg, "--modified")) {
 573                        show_modified = 1;
 574                        continue;
 575                }
 576                if (!strcmp(arg, "-o") || !strcmp(arg, "--others")) {
 577                        show_others = 1;
 578                        continue;
 579                }
 580                if (!strcmp(arg, "-i") || !strcmp(arg, "--ignored")) {
 581                        show_ignored = 1;
 582                        continue;
 583                }
 584                if (!strcmp(arg, "-s") || !strcmp(arg, "--stage")) {
 585                        show_stage = 1;
 586                        continue;
 587                }
 588                if (!strcmp(arg, "-k") || !strcmp(arg, "--killed")) {
 589                        show_killed = 1;
 590                        continue;
 591                }
 592                if (!strcmp(arg, "-u") || !strcmp(arg, "--unmerged")) {
 593                        /* There's no point in showing unmerged unless
 594                         * you also show the stage information.
 595                         */
 596                        show_stage = 1;
 597                        show_unmerged = 1;
 598                        continue;
 599                }
 600                if (!strcmp(arg, "-x") && i+1 < argc) {
 601                        exc_given = 1;
 602                        add_exclude(argv[++i], "", 0, &exclude_list[EXC_CMDL]);
 603                        continue;
 604                }
 605                if (!strncmp(arg, "--exclude=", 10)) {
 606                        exc_given = 1;
 607                        add_exclude(arg+10, "", 0, &exclude_list[EXC_CMDL]);
 608                        continue;
 609                }
 610                if (!strcmp(arg, "-X") && i+1 < argc) {
 611                        exc_given = 1;
 612                        add_excludes_from_file(argv[++i]);
 613                        continue;
 614                }
 615                if (!strncmp(arg, "--exclude-from=", 15)) {
 616                        exc_given = 1;
 617                        add_excludes_from_file(arg+15);
 618                        continue;
 619                }
 620                if (!strncmp(arg, "--exclude-per-directory=", 24)) {
 621                        exc_given = 1;
 622                        exclude_per_dir = arg + 24;
 623                        continue;
 624                }
 625                if (!strcmp(arg, "--full-name")) {
 626                        prefix_offset = 0;
 627                        continue;
 628                }
 629                if (*arg == '-')
 630                        usage(ls_files_usage);
 631                break;
 632        }
 633
 634        pathspec = get_pathspec(prefix, argv + i);
 635
 636        /* Verify that the pathspec matches the prefix */
 637        if (pathspec)
 638                verify_pathspec();
 639
 640        if (show_ignored && !exc_given) {
 641                fprintf(stderr, "%s: --ignored needs some exclude pattern\n",
 642                        argv[0]);
 643                exit(1);
 644        }
 645
 646        /* With no flags, we default to showing the cached files */
 647        if (!(show_stage | show_deleted | show_others | show_unmerged |
 648              show_killed | show_modified))
 649                show_cached = 1;
 650
 651        read_cache();
 652        if (prefix)
 653                prune_cache();
 654        show_files();
 655        return 0;
 656}