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