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