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#include "resolve-undo.h"
15#include "string-list.h"
16#include "pathspec.h"
17#include "run-command.h"
18
19static int abbrev;
20static int show_deleted;
21static int show_cached;
22static int show_others;
23static int show_stage;
24static int show_unmerged;
25static int show_resolve_undo;
26static int show_modified;
27static int show_killed;
28static int show_valid_bit;
29static int line_terminator = '\n';
30static int debug_mode;
31static int show_eol;
32static int recurse_submodules;
33static struct argv_array submodule_options = ARGV_ARRAY_INIT;
34
35static const char *prefix;
36static const char *super_prefix;
37static int max_prefix_len;
38static int prefix_len;
39static struct pathspec pathspec;
40static int error_unmatch;
41static char *ps_matched;
42static const char *with_tree;
43static int exc_given;
44static int exclude_args;
45
46static const char *tag_cached = "";
47static const char *tag_unmerged = "";
48static const char *tag_removed = "";
49static const char *tag_other = "";
50static const char *tag_killed = "";
51static const char *tag_modified = "";
52static const char *tag_skip_worktree = "";
53static const char *tag_resolve_undo = "";
54
55static void write_eolinfo(const struct cache_entry *ce, const char *path)
56{
57 if (!show_eol)
58 return;
59 else {
60 struct stat st;
61 const char *i_txt = "";
62 const char *w_txt = "";
63 const char *a_txt = get_convert_attr_ascii(path);
64 if (ce && S_ISREG(ce->ce_mode))
65 i_txt = get_cached_convert_stats_ascii(ce->name);
66 if (!lstat(path, &st) && S_ISREG(st.st_mode))
67 w_txt = get_wt_convert_stats_ascii(path);
68 printf("i/%-5s w/%-5s attr/%-17s\t", i_txt, w_txt, a_txt);
69 }
70}
71
72static void write_name(const char *name)
73{
74 /*
75 * Prepend the super_prefix to name to construct the full_name to be
76 * written.
77 */
78 struct strbuf full_name = STRBUF_INIT;
79 if (super_prefix) {
80 strbuf_addstr(&full_name, super_prefix);
81 strbuf_addstr(&full_name, name);
82 name = full_name.buf;
83 }
84
85 /*
86 * With "--full-name", prefix_len=0; this caller needs to pass
87 * an empty string in that case (a NULL is good for "").
88 */
89 write_name_quoted_relative(name, prefix_len ? prefix : NULL,
90 stdout, line_terminator);
91
92 strbuf_release(&full_name);
93}
94
95static void show_dir_entry(const char *tag, struct dir_entry *ent)
96{
97 int len = max_prefix_len;
98
99 if (len >= ent->len)
100 die("git ls-files: internal error - directory entry not superset of prefix");
101
102 if (!dir_path_match(ent, &pathspec, len, ps_matched))
103 return;
104
105 fputs(tag, stdout);
106 write_eolinfo(NULL, ent->name);
107 write_name(ent->name);
108}
109
110static void show_other_files(struct dir_struct *dir)
111{
112 int i;
113
114 for (i = 0; i < dir->nr; i++) {
115 struct dir_entry *ent = dir->entries[i];
116 if (!cache_name_is_other(ent->name, ent->len))
117 continue;
118 show_dir_entry(tag_other, ent);
119 }
120}
121
122static void show_killed_files(struct dir_struct *dir)
123{
124 int i;
125 for (i = 0; i < dir->nr; i++) {
126 struct dir_entry *ent = dir->entries[i];
127 char *cp, *sp;
128 int pos, len, killed = 0;
129
130 for (cp = ent->name; cp - ent->name < ent->len; cp = sp + 1) {
131 sp = strchr(cp, '/');
132 if (!sp) {
133 /* If ent->name is prefix of an entry in the
134 * cache, it will be killed.
135 */
136 pos = cache_name_pos(ent->name, ent->len);
137 if (0 <= pos)
138 die("BUG: killed-file %.*s not found",
139 ent->len, ent->name);
140 pos = -pos - 1;
141 while (pos < active_nr &&
142 ce_stage(active_cache[pos]))
143 pos++; /* skip unmerged */
144 if (active_nr <= pos)
145 break;
146 /* pos points at a name immediately after
147 * ent->name in the cache. Does it expect
148 * ent->name to be a directory?
149 */
150 len = ce_namelen(active_cache[pos]);
151 if ((ent->len < len) &&
152 !strncmp(active_cache[pos]->name,
153 ent->name, ent->len) &&
154 active_cache[pos]->name[ent->len] == '/')
155 killed = 1;
156 break;
157 }
158 if (0 <= cache_name_pos(ent->name, sp - ent->name)) {
159 /* If any of the leading directories in
160 * ent->name is registered in the cache,
161 * ent->name will be killed.
162 */
163 killed = 1;
164 break;
165 }
166 }
167 if (killed)
168 show_dir_entry(tag_killed, dir->entries[i]);
169 }
170}
171
172/*
173 * Compile an argv_array with all of the options supported by --recurse_submodules
174 */
175static void compile_submodule_options(const char **argv,
176 const struct dir_struct *dir,
177 int show_tag)
178{
179 if (line_terminator == '\0')
180 argv_array_push(&submodule_options, "-z");
181 if (show_tag)
182 argv_array_push(&submodule_options, "-t");
183 if (show_valid_bit)
184 argv_array_push(&submodule_options, "-v");
185 if (show_cached)
186 argv_array_push(&submodule_options, "--cached");
187 if (show_eol)
188 argv_array_push(&submodule_options, "--eol");
189 if (debug_mode)
190 argv_array_push(&submodule_options, "--debug");
191
192 /* Add Pathspecs */
193 argv_array_push(&submodule_options, "--");
194 for (; *argv; argv++)
195 argv_array_push(&submodule_options, *argv);
196}
197
198/**
199 * Recursively call ls-files on a submodule
200 */
201static void show_gitlink(const struct cache_entry *ce)
202{
203 struct child_process cp = CHILD_PROCESS_INIT;
204 int status;
205
206 if (prefix_len)
207 argv_array_pushf(&cp.env_array, "%s=%s",
208 GIT_TOPLEVEL_PREFIX_ENVIRONMENT,
209 prefix);
210 argv_array_pushf(&cp.args, "--super-prefix=%s%s/",
211 super_prefix ? super_prefix : "",
212 ce->name);
213 argv_array_push(&cp.args, "ls-files");
214 argv_array_push(&cp.args, "--recurse-submodules");
215
216 /* add supported options */
217 argv_array_pushv(&cp.args, submodule_options.argv);
218
219 cp.git_cmd = 1;
220 cp.dir = ce->name;
221 status = run_command(&cp);
222 if (status)
223 exit(status);
224}
225
226static void show_ce_entry(const char *tag, const struct cache_entry *ce)
227{
228 struct strbuf name = STRBUF_INIT;
229 int len = max_prefix_len;
230 if (super_prefix)
231 strbuf_addstr(&name, super_prefix);
232 strbuf_addstr(&name, ce->name);
233
234 if (len >= ce_namelen(ce))
235 die("git ls-files: internal error - cache entry not superset of prefix");
236
237 if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
238 submodule_path_match(&pathspec, name.buf, ps_matched)) {
239 show_gitlink(ce);
240 } else if (match_pathspec(&pathspec, name.buf, name.len,
241 len, ps_matched,
242 S_ISDIR(ce->ce_mode) ||
243 S_ISGITLINK(ce->ce_mode))) {
244 if (tag && *tag && show_valid_bit &&
245 (ce->ce_flags & CE_VALID)) {
246 static char alttag[4];
247 memcpy(alttag, tag, 3);
248 if (isalpha(tag[0]))
249 alttag[0] = tolower(tag[0]);
250 else if (tag[0] == '?')
251 alttag[0] = '!';
252 else {
253 alttag[0] = 'v';
254 alttag[1] = tag[0];
255 alttag[2] = ' ';
256 alttag[3] = 0;
257 }
258 tag = alttag;
259 }
260
261 if (!show_stage) {
262 fputs(tag, stdout);
263 } else {
264 printf("%s%06o %s %d\t",
265 tag,
266 ce->ce_mode,
267 find_unique_abbrev(ce->oid.hash, abbrev),
268 ce_stage(ce));
269 }
270 write_eolinfo(ce, ce->name);
271 write_name(ce->name);
272 if (debug_mode) {
273 const struct stat_data *sd = &ce->ce_stat_data;
274
275 printf(" ctime: %d:%d\n", sd->sd_ctime.sec, sd->sd_ctime.nsec);
276 printf(" mtime: %d:%d\n", sd->sd_mtime.sec, sd->sd_mtime.nsec);
277 printf(" dev: %d\tino: %d\n", sd->sd_dev, sd->sd_ino);
278 printf(" uid: %d\tgid: %d\n", sd->sd_uid, sd->sd_gid);
279 printf(" size: %d\tflags: %x\n", sd->sd_size, ce->ce_flags);
280 }
281 }
282
283 strbuf_release(&name);
284}
285
286static void show_ru_info(void)
287{
288 struct string_list_item *item;
289
290 if (!the_index.resolve_undo)
291 return;
292
293 for_each_string_list_item(item, the_index.resolve_undo) {
294 const char *path = item->string;
295 struct resolve_undo_info *ui = item->util;
296 int i, len;
297
298 len = strlen(path);
299 if (len < max_prefix_len)
300 continue; /* outside of the prefix */
301 if (!match_pathspec(&pathspec, path, len,
302 max_prefix_len, ps_matched, 0))
303 continue; /* uninterested */
304 for (i = 0; i < 3; i++) {
305 if (!ui->mode[i])
306 continue;
307 printf("%s%06o %s %d\t", tag_resolve_undo, ui->mode[i],
308 find_unique_abbrev(ui->sha1[i], abbrev),
309 i + 1);
310 write_name(path);
311 }
312 }
313}
314
315static int ce_excluded(struct dir_struct *dir, const struct cache_entry *ce)
316{
317 int dtype = ce_to_dtype(ce);
318 return is_excluded(dir, ce->name, &dtype);
319}
320
321static void show_files(struct dir_struct *dir)
322{
323 int i;
324
325 /* For cached/deleted files we don't need to even do the readdir */
326 if (show_others || show_killed) {
327 if (!show_others)
328 dir->flags |= DIR_COLLECT_KILLED_ONLY;
329 fill_directory(dir, &pathspec);
330 if (show_others)
331 show_other_files(dir);
332 if (show_killed)
333 show_killed_files(dir);
334 }
335 if (show_cached || show_stage) {
336 for (i = 0; i < active_nr; i++) {
337 const struct cache_entry *ce = active_cache[i];
338 if ((dir->flags & DIR_SHOW_IGNORED) &&
339 !ce_excluded(dir, ce))
340 continue;
341 if (show_unmerged && !ce_stage(ce))
342 continue;
343 if (ce->ce_flags & CE_UPDATE)
344 continue;
345 show_ce_entry(ce_stage(ce) ? tag_unmerged :
346 (ce_skip_worktree(ce) ? tag_skip_worktree : tag_cached), ce);
347 }
348 }
349 if (show_deleted || show_modified) {
350 for (i = 0; i < active_nr; i++) {
351 const struct cache_entry *ce = active_cache[i];
352 struct stat st;
353 int err;
354 if ((dir->flags & DIR_SHOW_IGNORED) &&
355 !ce_excluded(dir, ce))
356 continue;
357 if (ce->ce_flags & CE_UPDATE)
358 continue;
359 if (ce_skip_worktree(ce))
360 continue;
361 err = lstat(ce->name, &st);
362 if (show_deleted && err)
363 show_ce_entry(tag_removed, ce);
364 if (show_modified && ce_modified(ce, &st, 0))
365 show_ce_entry(tag_modified, ce);
366 }
367 }
368}
369
370/*
371 * Prune the index to only contain stuff starting with "prefix"
372 */
373static void prune_cache(const char *prefix, size_t prefixlen)
374{
375 int pos;
376 unsigned int first, last;
377
378 if (!prefix)
379 return;
380 pos = cache_name_pos(prefix, prefixlen);
381 if (pos < 0)
382 pos = -pos-1;
383 first = pos;
384 last = active_nr;
385 while (last > first) {
386 int next = (last + first) >> 1;
387 const struct cache_entry *ce = active_cache[next];
388 if (!strncmp(ce->name, prefix, prefixlen)) {
389 first = next+1;
390 continue;
391 }
392 last = next;
393 }
394 memmove(active_cache, active_cache + pos,
395 (last - pos) * sizeof(struct cache_entry *));
396 active_nr = last - pos;
397}
398
399/*
400 * Read the tree specified with --with-tree option
401 * (typically, HEAD) into stage #1 and then
402 * squash them down to stage #0. This is used for
403 * --error-unmatch to list and check the path patterns
404 * that were given from the command line. We are not
405 * going to write this index out.
406 */
407void overlay_tree_on_cache(const char *tree_name, const char *prefix)
408{
409 struct tree *tree;
410 unsigned char sha1[20];
411 struct pathspec pathspec;
412 struct cache_entry *last_stage0 = NULL;
413 int i;
414
415 if (get_sha1(tree_name, sha1))
416 die("tree-ish %s not found.", tree_name);
417 tree = parse_tree_indirect(sha1);
418 if (!tree)
419 die("bad tree-ish %s", tree_name);
420
421 /* Hoist the unmerged entries up to stage #3 to make room */
422 for (i = 0; i < active_nr; i++) {
423 struct cache_entry *ce = active_cache[i];
424 if (!ce_stage(ce))
425 continue;
426 ce->ce_flags |= CE_STAGEMASK;
427 }
428
429 if (prefix) {
430 static const char *(matchbuf[1]);
431 matchbuf[0] = NULL;
432 parse_pathspec(&pathspec, PATHSPEC_ALL_MAGIC,
433 PATHSPEC_PREFER_CWD, prefix, matchbuf);
434 } else
435 memset(&pathspec, 0, sizeof(pathspec));
436 if (read_tree(tree, 1, &pathspec))
437 die("unable to read tree entries %s", tree_name);
438
439 for (i = 0; i < active_nr; i++) {
440 struct cache_entry *ce = active_cache[i];
441 switch (ce_stage(ce)) {
442 case 0:
443 last_stage0 = ce;
444 /* fallthru */
445 default:
446 continue;
447 case 1:
448 /*
449 * If there is stage #0 entry for this, we do not
450 * need to show it. We use CE_UPDATE bit to mark
451 * such an entry.
452 */
453 if (last_stage0 &&
454 !strcmp(last_stage0->name, ce->name))
455 ce->ce_flags |= CE_UPDATE;
456 }
457 }
458}
459
460static const char * const ls_files_usage[] = {
461 N_("git ls-files [<options>] [<file>...]"),
462 NULL
463};
464
465static int option_parse_exclude(const struct option *opt,
466 const char *arg, int unset)
467{
468 struct string_list *exclude_list = opt->value;
469
470 exc_given = 1;
471 string_list_append(exclude_list, arg);
472
473 return 0;
474}
475
476static int option_parse_exclude_from(const struct option *opt,
477 const char *arg, int unset)
478{
479 struct dir_struct *dir = opt->value;
480
481 exc_given = 1;
482 add_excludes_from_file(dir, arg);
483
484 return 0;
485}
486
487static int option_parse_exclude_standard(const struct option *opt,
488 const char *arg, int unset)
489{
490 struct dir_struct *dir = opt->value;
491
492 exc_given = 1;
493 setup_standard_excludes(dir);
494
495 return 0;
496}
497
498int cmd_ls_files(int argc, const char **argv, const char *cmd_prefix)
499{
500 int require_work_tree = 0, show_tag = 0, i;
501 const char *max_prefix;
502 struct dir_struct dir;
503 struct exclude_list *el;
504 struct string_list exclude_list = STRING_LIST_INIT_NODUP;
505 struct option builtin_ls_files_options[] = {
506 /* Think twice before adding "--nul" synonym to this */
507 OPT_SET_INT('z', NULL, &line_terminator,
508 N_("paths are separated with NUL character"), '\0'),
509 OPT_BOOL('t', NULL, &show_tag,
510 N_("identify the file status with tags")),
511 OPT_BOOL('v', NULL, &show_valid_bit,
512 N_("use lowercase letters for 'assume unchanged' files")),
513 OPT_BOOL('c', "cached", &show_cached,
514 N_("show cached files in the output (default)")),
515 OPT_BOOL('d', "deleted", &show_deleted,
516 N_("show deleted files in the output")),
517 OPT_BOOL('m', "modified", &show_modified,
518 N_("show modified files in the output")),
519 OPT_BOOL('o', "others", &show_others,
520 N_("show other files in the output")),
521 OPT_BIT('i', "ignored", &dir.flags,
522 N_("show ignored files in the output"),
523 DIR_SHOW_IGNORED),
524 OPT_BOOL('s', "stage", &show_stage,
525 N_("show staged contents' object name in the output")),
526 OPT_BOOL('k', "killed", &show_killed,
527 N_("show files on the filesystem that need to be removed")),
528 OPT_BIT(0, "directory", &dir.flags,
529 N_("show 'other' directories' names only"),
530 DIR_SHOW_OTHER_DIRECTORIES),
531 OPT_BOOL(0, "eol", &show_eol, N_("show line endings of files")),
532 OPT_NEGBIT(0, "empty-directory", &dir.flags,
533 N_("don't show empty directories"),
534 DIR_HIDE_EMPTY_DIRECTORIES),
535 OPT_BOOL('u', "unmerged", &show_unmerged,
536 N_("show unmerged files in the output")),
537 OPT_BOOL(0, "resolve-undo", &show_resolve_undo,
538 N_("show resolve-undo information")),
539 { OPTION_CALLBACK, 'x', "exclude", &exclude_list, N_("pattern"),
540 N_("skip files matching pattern"),
541 0, option_parse_exclude },
542 { OPTION_CALLBACK, 'X', "exclude-from", &dir, N_("file"),
543 N_("exclude patterns are read from <file>"),
544 0, option_parse_exclude_from },
545 OPT_STRING(0, "exclude-per-directory", &dir.exclude_per_dir, N_("file"),
546 N_("read additional per-directory exclude patterns in <file>")),
547 { OPTION_CALLBACK, 0, "exclude-standard", &dir, NULL,
548 N_("add the standard git exclusions"),
549 PARSE_OPT_NOARG, option_parse_exclude_standard },
550 { OPTION_SET_INT, 0, "full-name", &prefix_len, NULL,
551 N_("make the output relative to the project top directory"),
552 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL },
553 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
554 N_("recurse through submodules")),
555 OPT_BOOL(0, "error-unmatch", &error_unmatch,
556 N_("if any <file> is not in the index, treat this as an error")),
557 OPT_STRING(0, "with-tree", &with_tree, N_("tree-ish"),
558 N_("pretend that paths removed since <tree-ish> are still present")),
559 OPT__ABBREV(&abbrev),
560 OPT_BOOL(0, "debug", &debug_mode, N_("show debugging data")),
561 OPT_END()
562 };
563
564 if (argc == 2 && !strcmp(argv[1], "-h"))
565 usage_with_options(ls_files_usage, builtin_ls_files_options);
566
567 memset(&dir, 0, sizeof(dir));
568 prefix = cmd_prefix;
569 if (prefix)
570 prefix_len = strlen(prefix);
571 super_prefix = get_super_prefix();
572 git_config(git_default_config, NULL);
573
574 if (read_cache() < 0)
575 die("index file corrupt");
576
577 argc = parse_options(argc, argv, prefix, builtin_ls_files_options,
578 ls_files_usage, 0);
579 el = add_exclude_list(&dir, EXC_CMDL, "--exclude option");
580 for (i = 0; i < exclude_list.nr; i++) {
581 add_exclude(exclude_list.items[i].string, "", 0, el, --exclude_args);
582 }
583 if (show_tag || show_valid_bit) {
584 tag_cached = "H ";
585 tag_unmerged = "M ";
586 tag_removed = "R ";
587 tag_modified = "C ";
588 tag_other = "? ";
589 tag_killed = "K ";
590 tag_skip_worktree = "S ";
591 tag_resolve_undo = "U ";
592 }
593 if (show_modified || show_others || show_deleted || (dir.flags & DIR_SHOW_IGNORED) || show_killed)
594 require_work_tree = 1;
595 if (show_unmerged)
596 /*
597 * There's no point in showing unmerged unless
598 * you also show the stage information.
599 */
600 show_stage = 1;
601 if (dir.exclude_per_dir)
602 exc_given = 1;
603
604 if (require_work_tree && !is_inside_work_tree())
605 setup_work_tree();
606
607 if (recurse_submodules)
608 compile_submodule_options(argv, &dir, show_tag);
609
610 if (recurse_submodules &&
611 (show_stage || show_deleted || show_others || show_unmerged ||
612 show_killed || show_modified || show_resolve_undo || with_tree))
613 die("ls-files --recurse-submodules unsupported mode");
614
615 if (recurse_submodules && error_unmatch)
616 die("ls-files --recurse-submodules does not support "
617 "--error-unmatch");
618
619 parse_pathspec(&pathspec, 0,
620 PATHSPEC_PREFER_CWD |
621 PATHSPEC_STRIP_SUBMODULE_SLASH_CHEAP,
622 prefix, argv);
623
624 /*
625 * Find common prefix for all pathspec's
626 * This is used as a performance optimization which unfortunately cannot
627 * be done when recursing into submodules
628 */
629 if (recurse_submodules)
630 max_prefix = NULL;
631 else
632 max_prefix = common_prefix(&pathspec);
633 max_prefix_len = max_prefix ? strlen(max_prefix) : 0;
634
635 /* Treat unmatching pathspec elements as errors */
636 if (pathspec.nr && error_unmatch)
637 ps_matched = xcalloc(pathspec.nr, 1);
638
639 if ((dir.flags & DIR_SHOW_IGNORED) && !exc_given)
640 die("ls-files --ignored needs some exclude pattern");
641
642 /* With no flags, we default to showing the cached files */
643 if (!(show_stage || show_deleted || show_others || show_unmerged ||
644 show_killed || show_modified || show_resolve_undo))
645 show_cached = 1;
646
647 prune_cache(max_prefix, max_prefix_len);
648 if (with_tree) {
649 /*
650 * Basic sanity check; show-stages and show-unmerged
651 * would not make any sense with this option.
652 */
653 if (show_stage || show_unmerged)
654 die("ls-files --with-tree is incompatible with -s or -u");
655 overlay_tree_on_cache(with_tree, max_prefix);
656 }
657 show_files(&dir);
658 if (show_resolve_undo)
659 show_ru_info();
660
661 if (ps_matched) {
662 int bad;
663 bad = report_path_error(ps_matched, &pathspec, prefix);
664 if (bad)
665 fprintf(stderr, "Did you forget to 'git add'?\n");
666
667 return bad ? 1 : 0;
668 }
669
670 return 0;
671}