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