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