c1afbad453ae967efbe735b3f763ef17b3562d2e
   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 "cache.h"
   9#include "quote.h"
  10#include "dir.h"
  11#include "builtin.h"
  12#include "tree.h"
  13#include "parse-options.h"
  14
  15static int abbrev;
  16static int show_deleted;
  17static int show_cached;
  18static int show_others;
  19static int show_stage;
  20static int show_unmerged;
  21static int show_modified;
  22static int show_killed;
  23static int show_valid_bit;
  24static int line_terminator = '\n';
  25
  26static int prefix_len;
  27static int prefix_offset;
  28static const char **pathspec;
  29static int error_unmatch;
  30static char *ps_matched;
  31static const char *with_tree;
  32static int exc_given;
  33
  34static const char *tag_cached = "";
  35static const char *tag_unmerged = "";
  36static const char *tag_removed = "";
  37static const char *tag_other = "";
  38static const char *tag_killed = "";
  39static const char *tag_modified = "";
  40static const char *tag_skip_worktree = "";
  41
  42static void show_dir_entry(const char *tag, struct dir_entry *ent)
  43{
  44        int len = prefix_len;
  45        int offset = prefix_offset;
  46
  47        if (len >= ent->len)
  48                die("git ls-files: internal error - directory entry not superset of prefix");
  49
  50        if (!match_pathspec(pathspec, ent->name, ent->len, len, ps_matched))
  51                return;
  52
  53        fputs(tag, stdout);
  54        write_name_quoted(ent->name + offset, stdout, line_terminator);
  55}
  56
  57static void show_other_files(struct dir_struct *dir)
  58{
  59        int i;
  60
  61        for (i = 0; i < dir->nr; i++) {
  62                struct dir_entry *ent = dir->entries[i];
  63                if (!cache_name_is_other(ent->name, ent->len))
  64                        continue;
  65                show_dir_entry(tag_other, ent);
  66        }
  67}
  68
  69static void show_killed_files(struct dir_struct *dir)
  70{
  71        int i;
  72        for (i = 0; i < dir->nr; i++) {
  73                struct dir_entry *ent = dir->entries[i];
  74                char *cp, *sp;
  75                int pos, len, killed = 0;
  76
  77                for (cp = ent->name; cp - ent->name < ent->len; cp = sp + 1) {
  78                        sp = strchr(cp, '/');
  79                        if (!sp) {
  80                                /* If ent->name is prefix of an entry in the
  81                                 * cache, it will be killed.
  82                                 */
  83                                pos = cache_name_pos(ent->name, ent->len);
  84                                if (0 <= pos)
  85                                        die("bug in show-killed-files");
  86                                pos = -pos - 1;
  87                                while (pos < active_nr &&
  88                                       ce_stage(active_cache[pos]))
  89                                        pos++; /* skip unmerged */
  90                                if (active_nr <= pos)
  91                                        break;
  92                                /* pos points at a name immediately after
  93                                 * ent->name in the cache.  Does it expect
  94                                 * ent->name to be a directory?
  95                                 */
  96                                len = ce_namelen(active_cache[pos]);
  97                                if ((ent->len < len) &&
  98                                    !strncmp(active_cache[pos]->name,
  99                                             ent->name, ent->len) &&
 100                                    active_cache[pos]->name[ent->len] == '/')
 101                                        killed = 1;
 102                                break;
 103                        }
 104                        if (0 <= cache_name_pos(ent->name, sp - ent->name)) {
 105                                /* If any of the leading directories in
 106                                 * ent->name is registered in the cache,
 107                                 * ent->name will be killed.
 108                                 */
 109                                killed = 1;
 110                                break;
 111                        }
 112                }
 113                if (killed)
 114                        show_dir_entry(tag_killed, dir->entries[i]);
 115        }
 116}
 117
 118static void show_ce_entry(const char *tag, struct cache_entry *ce)
 119{
 120        int len = prefix_len;
 121        int offset = prefix_offset;
 122
 123        if (len >= ce_namelen(ce))
 124                die("git ls-files: internal error - cache entry not superset of prefix");
 125
 126        if (!match_pathspec(pathspec, ce->name, ce_namelen(ce), len, ps_matched))
 127                return;
 128
 129        if (tag && *tag && show_valid_bit &&
 130            (ce->ce_flags & CE_VALID)) {
 131                static char alttag[4];
 132                memcpy(alttag, tag, 3);
 133                if (isalpha(tag[0]))
 134                        alttag[0] = tolower(tag[0]);
 135                else if (tag[0] == '?')
 136                        alttag[0] = '!';
 137                else {
 138                        alttag[0] = 'v';
 139                        alttag[1] = tag[0];
 140                        alttag[2] = ' ';
 141                        alttag[3] = 0;
 142                }
 143                tag = alttag;
 144        }
 145
 146        if (!show_stage) {
 147                fputs(tag, stdout);
 148        } else {
 149                printf("%s%06o %s %d\t",
 150                       tag,
 151                       ce->ce_mode,
 152                       abbrev ? find_unique_abbrev(ce->sha1,abbrev)
 153                                : sha1_to_hex(ce->sha1),
 154                       ce_stage(ce));
 155        }
 156        write_name_quoted(ce->name + offset, stdout, line_terminator);
 157}
 158
 159static void show_files(struct dir_struct *dir, const char *prefix)
 160{
 161        int i;
 162
 163        /* For cached/deleted files we don't need to even do the readdir */
 164        if (show_others || show_killed) {
 165                fill_directory(dir, pathspec);
 166                if (show_others)
 167                        show_other_files(dir);
 168                if (show_killed)
 169                        show_killed_files(dir);
 170        }
 171        if (show_cached | show_stage) {
 172                for (i = 0; i < active_nr; i++) {
 173                        struct cache_entry *ce = active_cache[i];
 174                        int dtype = ce_to_dtype(ce);
 175                        if (excluded(dir, ce->name, &dtype) !=
 176                                        !!(dir->flags & DIR_SHOW_IGNORED))
 177                                continue;
 178                        if (show_unmerged && !ce_stage(ce))
 179                                continue;
 180                        if (ce->ce_flags & CE_UPDATE)
 181                                continue;
 182                        show_ce_entry(ce_stage(ce) ? tag_unmerged :
 183                                (ce_skip_worktree(ce) ? tag_skip_worktree : tag_cached), ce);
 184                }
 185        }
 186        if (show_deleted | show_modified) {
 187                for (i = 0; i < active_nr; i++) {
 188                        struct cache_entry *ce = active_cache[i];
 189                        struct stat st;
 190                        int err;
 191                        int dtype = ce_to_dtype(ce);
 192                        if (excluded(dir, ce->name, &dtype) !=
 193                                        !!(dir->flags & DIR_SHOW_IGNORED))
 194                                continue;
 195                        if (ce->ce_flags & CE_UPDATE)
 196                                continue;
 197                        err = lstat(ce->name, &st);
 198                        if (show_deleted && err)
 199                                show_ce_entry(tag_removed, ce);
 200                        if (show_modified && ce_modified(ce, &st, 0))
 201                                show_ce_entry(tag_modified, ce);
 202                }
 203        }
 204}
 205
 206/*
 207 * Prune the index to only contain stuff starting with "prefix"
 208 */
 209static void prune_cache(const char *prefix)
 210{
 211        int pos = cache_name_pos(prefix, prefix_len);
 212        unsigned int first, last;
 213
 214        if (pos < 0)
 215                pos = -pos-1;
 216        memmove(active_cache, active_cache + pos,
 217                (active_nr - pos) * sizeof(struct cache_entry *));
 218        active_nr -= pos;
 219        first = 0;
 220        last = active_nr;
 221        while (last > first) {
 222                int next = (last + first) >> 1;
 223                struct cache_entry *ce = active_cache[next];
 224                if (!strncmp(ce->name, prefix, prefix_len)) {
 225                        first = next+1;
 226                        continue;
 227                }
 228                last = next;
 229        }
 230        active_nr = last;
 231}
 232
 233static const char *verify_pathspec(const char *prefix)
 234{
 235        const char **p, *n, *prev;
 236        unsigned long max;
 237
 238        prev = NULL;
 239        max = PATH_MAX;
 240        for (p = pathspec; (n = *p) != NULL; p++) {
 241                int i, len = 0;
 242                for (i = 0; i < max; i++) {
 243                        char c = n[i];
 244                        if (prev && prev[i] != c)
 245                                break;
 246                        if (!c || c == '*' || c == '?')
 247                                break;
 248                        if (c == '/')
 249                                len = i+1;
 250                }
 251                prev = n;
 252                if (len < max) {
 253                        max = len;
 254                        if (!max)
 255                                break;
 256                }
 257        }
 258
 259        if (prefix_offset > max || memcmp(prev, prefix, prefix_offset))
 260                die("git ls-files: cannot generate relative filenames containing '..'");
 261
 262        prefix_len = max;
 263        return max ? xmemdupz(prev, max) : NULL;
 264}
 265
 266static void strip_trailing_slash_from_submodules(void)
 267{
 268        const char **p;
 269
 270        for (p = pathspec; *p != NULL; p++) {
 271                int len = strlen(*p), pos;
 272
 273                if (len < 1 || (*p)[len - 1] != '/')
 274                        continue;
 275                pos = cache_name_pos(*p, len - 1);
 276                if (pos >= 0 && S_ISGITLINK(active_cache[pos]->ce_mode))
 277                        *p = xstrndup(*p, len - 1);
 278        }
 279}
 280
 281/*
 282 * Read the tree specified with --with-tree option
 283 * (typically, HEAD) into stage #1 and then
 284 * squash them down to stage #0.  This is used for
 285 * --error-unmatch to list and check the path patterns
 286 * that were given from the command line.  We are not
 287 * going to write this index out.
 288 */
 289void overlay_tree_on_cache(const char *tree_name, const char *prefix)
 290{
 291        struct tree *tree;
 292        unsigned char sha1[20];
 293        const char **match;
 294        struct cache_entry *last_stage0 = NULL;
 295        int i;
 296
 297        if (get_sha1(tree_name, sha1))
 298                die("tree-ish %s not found.", tree_name);
 299        tree = parse_tree_indirect(sha1);
 300        if (!tree)
 301                die("bad tree-ish %s", tree_name);
 302
 303        /* Hoist the unmerged entries up to stage #3 to make room */
 304        for (i = 0; i < active_nr; i++) {
 305                struct cache_entry *ce = active_cache[i];
 306                if (!ce_stage(ce))
 307                        continue;
 308                ce->ce_flags |= CE_STAGEMASK;
 309        }
 310
 311        if (prefix) {
 312                static const char *(matchbuf[2]);
 313                matchbuf[0] = prefix;
 314                matchbuf[1] = NULL;
 315                match = matchbuf;
 316        } else
 317                match = NULL;
 318        if (read_tree(tree, 1, match))
 319                die("unable to read tree entries %s", tree_name);
 320
 321        for (i = 0; i < active_nr; i++) {
 322                struct cache_entry *ce = active_cache[i];
 323                switch (ce_stage(ce)) {
 324                case 0:
 325                        last_stage0 = ce;
 326                        /* fallthru */
 327                default:
 328                        continue;
 329                case 1:
 330                        /*
 331                         * If there is stage #0 entry for this, we do not
 332                         * need to show it.  We use CE_UPDATE bit to mark
 333                         * such an entry.
 334                         */
 335                        if (last_stage0 &&
 336                            !strcmp(last_stage0->name, ce->name))
 337                                ce->ce_flags |= CE_UPDATE;
 338                }
 339        }
 340}
 341
 342int report_path_error(const char *ps_matched, const char **pathspec, int prefix_offset)
 343{
 344        /*
 345         * Make sure all pathspec matched; otherwise it is an error.
 346         */
 347        int num, errors = 0;
 348        for (num = 0; pathspec[num]; num++) {
 349                int other, found_dup;
 350
 351                if (ps_matched[num])
 352                        continue;
 353                /*
 354                 * The caller might have fed identical pathspec
 355                 * twice.  Do not barf on such a mistake.
 356                 */
 357                for (found_dup = other = 0;
 358                     !found_dup && pathspec[other];
 359                     other++) {
 360                        if (other == num || !ps_matched[other])
 361                                continue;
 362                        if (!strcmp(pathspec[other], pathspec[num]))
 363                                /*
 364                                 * Ok, we have a match already.
 365                                 */
 366                                found_dup = 1;
 367                }
 368                if (found_dup)
 369                        continue;
 370
 371                error("pathspec '%s' did not match any file(s) known to git.",
 372                      pathspec[num] + prefix_offset);
 373                errors++;
 374        }
 375        return errors;
 376}
 377
 378static const char * const ls_files_usage[] = {
 379        "git ls-files [options] [<file>]*",
 380        NULL
 381};
 382
 383static int option_parse_z(const struct option *opt,
 384                          const char *arg, int unset)
 385{
 386        line_terminator = unset ? '\n' : '\0';
 387
 388        return 0;
 389}
 390
 391static int option_parse_exclude(const struct option *opt,
 392                                const char *arg, int unset)
 393{
 394        struct exclude_list *list = opt->value;
 395
 396        exc_given = 1;
 397        add_exclude(arg, "", 0, list);
 398
 399        return 0;
 400}
 401
 402static int option_parse_exclude_from(const struct option *opt,
 403                                     const char *arg, int unset)
 404{
 405        struct dir_struct *dir = opt->value;
 406
 407        exc_given = 1;
 408        add_excludes_from_file(dir, arg);
 409
 410        return 0;
 411}
 412
 413static int option_parse_exclude_standard(const struct option *opt,
 414                                         const char *arg, int unset)
 415{
 416        struct dir_struct *dir = opt->value;
 417
 418        exc_given = 1;
 419        setup_standard_excludes(dir);
 420
 421        return 0;
 422}
 423
 424int cmd_ls_files(int argc, const char **argv, const char *prefix)
 425{
 426        int require_work_tree = 0, show_tag = 0;
 427        struct dir_struct dir;
 428        struct option builtin_ls_files_options[] = {
 429                { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
 430                        "paths are separated with NUL character",
 431                        PARSE_OPT_NOARG, option_parse_z },
 432                OPT_BOOLEAN('t', NULL, &show_tag,
 433                        "identify the file status with tags"),
 434                OPT_BOOLEAN('v', NULL, &show_valid_bit,
 435                        "use lowercase letters for 'assume unchanged' files"),
 436                OPT_BOOLEAN('c', "cached", &show_cached,
 437                        "show cached files in the output (default)"),
 438                OPT_BOOLEAN('d', "deleted", &show_deleted,
 439                        "show deleted files in the output"),
 440                OPT_BOOLEAN('m', "modified", &show_modified,
 441                        "show modified files in the output"),
 442                OPT_BOOLEAN('o', "others", &show_others,
 443                        "show other files in the output"),
 444                OPT_BIT('i', "ignored", &dir.flags,
 445                        "show ignored files in the output",
 446                        DIR_SHOW_IGNORED),
 447                OPT_BOOLEAN('s', "stage", &show_stage,
 448                        "show staged contents' object name in the output"),
 449                OPT_BOOLEAN('k', "killed", &show_killed,
 450                        "show files on the filesystem that need to be removed"),
 451                OPT_BIT(0, "directory", &dir.flags,
 452                        "show 'other' directories' name only",
 453                        DIR_SHOW_OTHER_DIRECTORIES),
 454                OPT_NEGBIT(0, "empty-directory", &dir.flags,
 455                        "don't show empty directories",
 456                        DIR_HIDE_EMPTY_DIRECTORIES),
 457                OPT_BOOLEAN('u', "unmerged", &show_unmerged,
 458                        "show unmerged files in the output"),
 459                { OPTION_CALLBACK, 'x', "exclude", &dir.exclude_list[EXC_CMDL], "pattern",
 460                        "skip files matching pattern",
 461                        0, option_parse_exclude },
 462                { OPTION_CALLBACK, 'X', "exclude-from", &dir, "file",
 463                        "exclude patterns are read from <file>",
 464                        0, option_parse_exclude_from },
 465                OPT_STRING(0, "exclude-per-directory", &dir.exclude_per_dir, "file",
 466                        "read additional per-directory exclude patterns in <file>"),
 467                { OPTION_CALLBACK, 0, "exclude-standard", &dir, NULL,
 468                        "add the standard git exclusions",
 469                        PARSE_OPT_NOARG, option_parse_exclude_standard },
 470                { OPTION_SET_INT, 0, "full-name", &prefix_offset, NULL,
 471                        "make the output relative to the project top directory",
 472                        PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL },
 473                OPT_BOOLEAN(0, "error-unmatch", &error_unmatch,
 474                        "if any <file> is not in the index, treat this as an error"),
 475                OPT_STRING(0, "with-tree", &with_tree, "tree-ish",
 476                        "pretend that paths removed since <tree-ish> are still present"),
 477                OPT__ABBREV(&abbrev),
 478                OPT_END()
 479        };
 480
 481        memset(&dir, 0, sizeof(dir));
 482        if (prefix)
 483                prefix_offset = strlen(prefix);
 484        git_config(git_default_config, NULL);
 485
 486        argc = parse_options(argc, argv, prefix, builtin_ls_files_options,
 487                        ls_files_usage, 0);
 488        if (show_tag || show_valid_bit) {
 489                tag_cached = "H ";
 490                tag_unmerged = "M ";
 491                tag_removed = "R ";
 492                tag_modified = "C ";
 493                tag_other = "? ";
 494                tag_killed = "K ";
 495                tag_skip_worktree = "S ";
 496        }
 497        if (show_modified || show_others || show_deleted || (dir.flags & DIR_SHOW_IGNORED) || show_killed)
 498                require_work_tree = 1;
 499        if (show_unmerged)
 500                /*
 501                 * There's no point in showing unmerged unless
 502                 * you also show the stage information.
 503                 */
 504                show_stage = 1;
 505        if (dir.exclude_per_dir)
 506                exc_given = 1;
 507
 508        if (require_work_tree && !is_inside_work_tree())
 509                setup_work_tree();
 510
 511        pathspec = get_pathspec(prefix, argv);
 512
 513        /* be nice with submodule paths ending in a slash */
 514        read_cache();
 515        if (pathspec)
 516                strip_trailing_slash_from_submodules();
 517
 518        /* Verify that the pathspec matches the prefix */
 519        if (pathspec)
 520                prefix = verify_pathspec(prefix);
 521
 522        /* Treat unmatching pathspec elements as errors */
 523        if (pathspec && error_unmatch) {
 524                int num;
 525                for (num = 0; pathspec[num]; num++)
 526                        ;
 527                ps_matched = xcalloc(1, num);
 528        }
 529
 530        if ((dir.flags & DIR_SHOW_IGNORED) && !exc_given) {
 531                fprintf(stderr, "%s: --ignored needs some exclude pattern\n",
 532                        argv[0]);
 533                exit(1);
 534        }
 535
 536        /* With no flags, we default to showing the cached files */
 537        if (!(show_stage | show_deleted | show_others | show_unmerged |
 538              show_killed | show_modified))
 539                show_cached = 1;
 540
 541        if (prefix)
 542                prune_cache(prefix);
 543        if (with_tree) {
 544                /*
 545                 * Basic sanity check; show-stages and show-unmerged
 546                 * would not make any sense with this option.
 547                 */
 548                if (show_stage || show_unmerged)
 549                        die("ls-files --with-tree is incompatible with -s or -u");
 550                overlay_tree_on_cache(with_tree, prefix);
 551        }
 552        show_files(&dir, prefix);
 553
 554        if (ps_matched) {
 555                int bad;
 556                bad = report_path_error(ps_matched, pathspec, prefix_offset);
 557                if (bad)
 558                        fprintf(stderr, "Did you forget to 'git add'?\n");
 559
 560                return bad ? 1 : 0;
 561        }
 562
 563        return 0;
 564}