builtin-grep: -F (--fixed-strings)
[git.git] / builtin-grep.c
1 /*
2  * Builtin "git grep"
3  *
4  * Copyright (c) 2006 Junio C Hamano
5  */
6 #include "cache.h"
7 #include "blob.h"
8 #include "tree.h"
9 #include "commit.h"
10 #include "tag.h"
11 #include "tree-walk.h"
12 #include "builtin.h"
13 #include <regex.h>
14 #include <fnmatch.h>
15
16 /*
17  * git grep pathspecs are somewhat different from diff-tree pathspecs;
18  * pathname wildcards are allowed.
19  */
20 static int pathspec_matches(const char **paths, const char *name)
21 {
22         int namelen, i;
23         if (!paths || !*paths)
24                 return 1;
25         namelen = strlen(name);
26         for (i = 0; paths[i]; i++) {
27                 const char *match = paths[i];
28                 int matchlen = strlen(match);
29                 const char *cp, *meta;
30
31                 if ((matchlen <= namelen) &&
32                     !strncmp(name, match, matchlen) &&
33                     (match[matchlen-1] == '/' ||
34                      name[matchlen] == '\0' || name[matchlen] == '/'))
35                         return 1;
36                 if (!fnmatch(match, name, 0))
37                         return 1;
38                 if (name[namelen-1] != '/')
39                         continue;
40
41                 /* We are being asked if the directory ("name") is worth
42                  * descending into.
43                  *
44                  * Find the longest leading directory name that does
45                  * not have metacharacter in the pathspec; the name
46                  * we are looking at must overlap with that directory.
47                  */
48                 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
49                         char ch = *cp;
50                         if (ch == '*' || ch == '[' || ch == '?') {
51                                 meta = cp;
52                                 break;
53                         }
54                 }
55                 if (!meta)
56                         meta = cp; /* fully literal */
57
58                 if (namelen <= meta - match) {
59                         /* Looking at "Documentation/" and
60                          * the pattern says "Documentation/howto/", or
61                          * "Documentation/diff*.txt".  The name we
62                          * have should match prefix.
63                          */
64                         if (!memcmp(match, name, namelen))
65                                 return 1;
66                         continue;
67                 }
68
69                 if (meta - match < namelen) {
70                         /* Looking at "Documentation/howto/" and
71                          * the pattern says "Documentation/h*";
72                          * match up to "Do.../h"; this avoids descending
73                          * into "Documentation/technical/".
74                          */
75                         if (!memcmp(match, name, meta - match))
76                                 return 1;
77                         continue;
78                 }
79         }
80         return 0;
81 }
82
83 struct grep_pat {
84         struct grep_pat *next;
85         const char *origin;
86         int no;
87         const char *pattern;
88         regex_t regexp;
89 };
90
91 struct grep_opt {
92         struct grep_pat *pattern_list;
93         struct grep_pat **pattern_tail;
94         regex_t regexp;
95         unsigned linenum:1;
96         unsigned invert:1;
97         unsigned name_only:1;
98         unsigned unmatch_name_only:1;
99         unsigned count:1;
100         unsigned word_regexp:1;
101         unsigned fixed:1;
102 #define GREP_BINARY_DEFAULT     0
103 #define GREP_BINARY_NOMATCH     1
104 #define GREP_BINARY_TEXT        2
105         unsigned binary:2;
106         int regflags;
107         unsigned pre_context;
108         unsigned post_context;
109 };
110
111 static void add_pattern(struct grep_opt *opt, const char *pat,
112                         const char *origin, int no)
113 {
114         struct grep_pat *p = xcalloc(1, sizeof(*p));
115         p->pattern = pat;
116         p->origin = origin;
117         p->no = no;
118         *opt->pattern_tail = p;
119         opt->pattern_tail = &p->next;
120         p->next = NULL;
121 }
122
123 static void compile_patterns(struct grep_opt *opt)
124 {
125         struct grep_pat *p;
126         for (p = opt->pattern_list; p; p = p->next) {
127                 int err = regcomp(&p->regexp, p->pattern, opt->regflags);
128                 if (err) {
129                         char errbuf[1024];
130                         char where[1024];
131                         if (p->no)
132                                 sprintf(where, "In '%s' at %d, ",
133                                         p->origin, p->no);
134                         else if (p->origin)
135                                 sprintf(where, "%s, ", p->origin);
136                         else
137                                 where[0] = 0;
138                         regerror(err, &p->regexp, errbuf, 1024);
139                         regfree(&p->regexp);
140                         die("%s'%s': %s", where, p->pattern, errbuf);
141                 }
142         }
143 }
144
145 static char *end_of_line(char *cp, unsigned long *left)
146 {
147         unsigned long l = *left;
148         while (l && *cp != '\n') {
149                 l--;
150                 cp++;
151         }
152         *left = l;
153         return cp;
154 }
155
156 static int word_char(char ch)
157 {
158         return isalnum(ch) || ch == '_';
159 }
160
161 static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
162                       const char *name, unsigned lno, char sign)
163 {
164         printf("%s%c", name, sign);
165         if (opt->linenum)
166                 printf("%d%c", lno, sign);
167         printf("%.*s\n", (int)(eol-bol), bol);
168 }
169
170 /*
171  * NEEDSWORK: share code with diff.c
172  */
173 #define FIRST_FEW_BYTES 8000
174 static int buffer_is_binary(const char *ptr, unsigned long size)
175 {
176         if (FIRST_FEW_BYTES < size)
177                 size = FIRST_FEW_BYTES;
178         if (memchr(ptr, 0, size))
179                 return 1;
180         return 0;
181 }
182
183 static int fixmatch(const char *pattern, char *line, regmatch_t *match)
184 {
185         char *hit = strstr(line, pattern);
186         if (!hit) {
187                 match->rm_so = match->rm_eo = -1;
188                 return REG_NOMATCH;
189         }
190         else {
191                 match->rm_so = hit - line;
192                 match->rm_eo = match->rm_so + strlen(pattern);
193                 return 0;
194         }
195 }
196
197 static int grep_buffer(struct grep_opt *opt, const char *name,
198                        char *buf, unsigned long size)
199 {
200         char *bol = buf;
201         unsigned long left = size;
202         unsigned lno = 1;
203         struct pre_context_line {
204                 char *bol;
205                 char *eol;
206         } *prev = NULL, *pcl;
207         unsigned last_hit = 0;
208         unsigned last_shown = 0;
209         int binary_match_only = 0;
210         const char *hunk_mark = "";
211         unsigned count = 0;
212
213         if (buffer_is_binary(buf, size)) {
214                 switch (opt->binary) {
215                 case GREP_BINARY_DEFAULT:
216                         binary_match_only = 1;
217                         break;
218                 case GREP_BINARY_NOMATCH:
219                         return 0; /* Assume unmatch */
220                         break;
221                 default:
222                         break;
223                 }
224         }
225
226         if (opt->pre_context)
227                 prev = xcalloc(opt->pre_context, sizeof(*prev));
228         if (opt->pre_context || opt->post_context)
229                 hunk_mark = "--\n";
230
231         while (left) {
232                 regmatch_t pmatch[10];
233                 char *eol, ch;
234                 int hit = 0;
235                 struct grep_pat *p;
236
237                 eol = end_of_line(bol, &left);
238                 ch = *eol;
239                 *eol = 0;
240
241                 for (p = opt->pattern_list; p; p = p->next) {
242                         if (!opt->fixed) {
243                                 regex_t *exp = &p->regexp;
244                                 hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
245                                                pmatch, 0);
246                         }
247                         else {
248                                 hit = !fixmatch(p->pattern, bol, pmatch);
249                         }
250
251                         if (hit && opt->word_regexp) {
252                                 /* Match beginning must be either
253                                  * beginning of the line, or at word
254                                  * boundary (i.e. the last char must
255                                  * not be alnum or underscore).
256                                  */
257                                 if ((pmatch[0].rm_so < 0) ||
258                                     (eol - bol) <= pmatch[0].rm_so ||
259                                     (pmatch[0].rm_eo < 0) ||
260                                     (eol - bol) < pmatch[0].rm_eo)
261                                         die("regexp returned nonsense");
262                                 if (pmatch[0].rm_so != 0 &&
263                                     word_char(bol[pmatch[0].rm_so-1]))
264                                         hit = 0;
265                                 if (pmatch[0].rm_eo != (eol-bol) &&
266                                     word_char(bol[pmatch[0].rm_eo]))
267                                         hit = 0;
268                         }
269                         if (hit)
270                                 break;
271                 }
272                 /* "grep -v -e foo -e bla" should list lines
273                  * that do not have either, so inversion should
274                  * be done outside.
275                  */
276                 if (opt->invert)
277                         hit = !hit;
278                 if (opt->unmatch_name_only) {
279                         if (hit)
280                                 return 0;
281                         goto next_line;
282                 }
283                 if (hit) {
284                         count++;
285                         if (binary_match_only) {
286                                 printf("Binary file %s matches\n", name);
287                                 return 1;
288                         }
289                         if (opt->name_only) {
290                                 printf("%s\n", name);
291                                 return 1;
292                         }
293                         /* Hit at this line.  If we haven't shown the
294                          * pre-context lines, we would need to show them.
295                          * When asked to do "count", this still show
296                          * the context which is nonsense, but the user
297                          * deserves to get that ;-).
298                          */
299                         if (opt->pre_context) {
300                                 unsigned from;
301                                 if (opt->pre_context < lno)
302                                         from = lno - opt->pre_context;
303                                 else
304                                         from = 1;
305                                 if (from <= last_shown)
306                                         from = last_shown + 1;
307                                 if (last_shown && from != last_shown + 1)
308                                         printf(hunk_mark);
309                                 while (from < lno) {
310                                         pcl = &prev[lno-from-1];
311                                         show_line(opt, pcl->bol, pcl->eol,
312                                                   name, from, '-');
313                                         from++;
314                                 }
315                                 last_shown = lno-1;
316                         }
317                         if (last_shown && lno != last_shown + 1)
318                                 printf(hunk_mark);
319                         if (!opt->count)
320                                 show_line(opt, bol, eol, name, lno, ':');
321                         last_shown = last_hit = lno;
322                 }
323                 else if (last_hit &&
324                          lno <= last_hit + opt->post_context) {
325                         /* If the last hit is within the post context,
326                          * we need to show this line.
327                          */
328                         if (last_shown && lno != last_shown + 1)
329                                 printf(hunk_mark);
330                         show_line(opt, bol, eol, name, lno, '-');
331                         last_shown = lno;
332                 }
333                 if (opt->pre_context) {
334                         memmove(prev+1, prev,
335                                 (opt->pre_context-1) * sizeof(*prev));
336                         prev->bol = bol;
337                         prev->eol = eol;
338                 }
339
340         next_line:
341                 *eol = ch;
342                 bol = eol + 1;
343                 if (!left)
344                         break;
345                 left--;
346                 lno++;
347         }
348
349         if (opt->unmatch_name_only) {
350                 /* We did not see any hit, so we want to show this */
351                 printf("%s\n", name);
352                 return 1;
353         }
354
355         /* NEEDSWORK:
356          * The real "grep -c foo *.c" gives many "bar.c:0" lines,
357          * which feels mostly useless but sometimes useful.  Maybe
358          * make it another option?  For now suppress them.
359          */
360         if (opt->count && count)
361                 printf("%s:%u\n", name, count);
362         return !!last_hit;
363 }
364
365 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name)
366 {
367         unsigned long size;
368         char *data;
369         char type[20];
370         int hit;
371         data = read_sha1_file(sha1, type, &size);
372         if (!data) {
373                 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
374                 return 0;
375         }
376         hit = grep_buffer(opt, name, data, size);
377         free(data);
378         return hit;
379 }
380
381 static int grep_file(struct grep_opt *opt, const char *filename)
382 {
383         struct stat st;
384         int i;
385         char *data;
386         if (lstat(filename, &st) < 0) {
387         err_ret:
388                 if (errno != ENOENT)
389                         error("'%s': %s", filename, strerror(errno));
390                 return 0;
391         }
392         if (!st.st_size)
393                 return 0; /* empty file -- no grep hit */
394         if (!S_ISREG(st.st_mode))
395                 return 0;
396         i = open(filename, O_RDONLY);
397         if (i < 0)
398                 goto err_ret;
399         data = xmalloc(st.st_size + 1);
400         if (st.st_size != xread(i, data, st.st_size)) {
401                 error("'%s': short read %s", filename, strerror(errno));
402                 close(i);
403                 free(data);
404                 return 0;
405         }
406         close(i);
407         i = grep_buffer(opt, filename, data, st.st_size);
408         free(data);
409         return i;
410 }
411
412 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
413 {
414         int hit = 0;
415         int nr;
416         read_cache();
417
418         for (nr = 0; nr < active_nr; nr++) {
419                 struct cache_entry *ce = active_cache[nr];
420                 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
421                         continue;
422                 if (!pathspec_matches(paths, ce->name))
423                         continue;
424                 if (cached)
425                         hit |= grep_sha1(opt, ce->sha1, ce->name);
426                 else
427                         hit |= grep_file(opt, ce->name);
428         }
429         return hit;
430 }
431
432 static int grep_tree(struct grep_opt *opt, const char **paths,
433                      struct tree_desc *tree,
434                      const char *tree_name, const char *base)
435 {
436         unsigned mode;
437         int len;
438         int hit = 0;
439         const char *path;
440         const unsigned char *sha1;
441         char *down;
442         char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
443
444         if (tree_name[0]) {
445                 int offset = sprintf(path_buf, "%s:", tree_name);
446                 down = path_buf + offset;
447                 strcat(down, base);
448         }
449         else {
450                 down = path_buf;
451                 strcpy(down, base);
452         }
453         len = strlen(path_buf);
454
455         while (tree->size) {
456                 int pathlen;
457                 sha1 = tree_entry_extract(tree, &path, &mode);
458                 pathlen = strlen(path);
459                 strcpy(path_buf + len, path);
460
461                 if (S_ISDIR(mode))
462                         /* Match "abc/" against pathspec to
463                          * decide if we want to descend into "abc"
464                          * directory.
465                          */
466                         strcpy(path_buf + len + pathlen, "/");
467
468                 if (!pathspec_matches(paths, down))
469                         ;
470                 else if (S_ISREG(mode))
471                         hit |= grep_sha1(opt, sha1, path_buf);
472                 else if (S_ISDIR(mode)) {
473                         char type[20];
474                         struct tree_desc sub;
475                         void *data;
476                         data = read_sha1_file(sha1, type, &sub.size);
477                         if (!data)
478                                 die("unable to read tree (%s)",
479                                     sha1_to_hex(sha1));
480                         sub.buf = data;
481                         hit |= grep_tree(opt, paths, &sub, tree_name, down);
482                         free(data);
483                 }
484                 update_tree_entry(tree);
485         }
486         return hit;
487 }
488
489 static int grep_object(struct grep_opt *opt, const char **paths,
490                        struct object *obj, const char *name)
491 {
492         if (!strcmp(obj->type, blob_type))
493                 return grep_sha1(opt, obj->sha1, name);
494         if (!strcmp(obj->type, commit_type) ||
495             !strcmp(obj->type, tree_type)) {
496                 struct tree_desc tree;
497                 void *data;
498                 int hit;
499                 data = read_object_with_reference(obj->sha1, tree_type,
500                                                   &tree.size, NULL);
501                 if (!data)
502                         die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
503                 tree.buf = data;
504                 hit = grep_tree(opt, paths, &tree, name, "");
505                 free(data);
506                 return hit;
507         }
508         die("unable to grep from object of type %s", obj->type);
509 }
510
511 static const char builtin_grep_usage[] =
512 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
513
514 int cmd_grep(int argc, const char **argv, char **envp)
515 {
516         int hit = 0;
517         int cached = 0;
518         int seen_dashdash = 0;
519         struct grep_opt opt;
520         struct object_list *list, **tail, *object_list = NULL;
521         const char *prefix = setup_git_directory();
522         const char **paths = NULL;
523         int i;
524
525         memset(&opt, 0, sizeof(opt));
526         opt.pattern_tail = &opt.pattern_list;
527         opt.regflags = REG_NEWLINE;
528
529         /*
530          * If there is no -- then the paths must exist in the working
531          * tree.  If there is no explicit pattern specified with -e or
532          * -f, we take the first unrecognized non option to be the
533          * pattern, but then what follows it must be zero or more
534          * valid refs up to the -- (if exists), and then existing
535          * paths.  If there is an explicit pattern, then the first
536          * unrecocnized non option is the beginning of the refs list
537          * that continues up to the -- (if exists), and then paths.
538          */
539
540         tail = &object_list;
541         while (1 < argc) {
542                 const char *arg = argv[1];
543                 argc--; argv++;
544                 if (!strcmp("--cached", arg)) {
545                         cached = 1;
546                         continue;
547                 }
548                 if (!strcmp("-a", arg) ||
549                     !strcmp("--text", arg)) {
550                         opt.binary = GREP_BINARY_TEXT;
551                         continue;
552                 }
553                 if (!strcmp("-i", arg) ||
554                     !strcmp("--ignore-case", arg)) {
555                         opt.regflags |= REG_ICASE;
556                         continue;
557                 }
558                 if (!strcmp("-I", arg)) {
559                         opt.binary = GREP_BINARY_NOMATCH;
560                         continue;
561                 }
562                 if (!strcmp("-v", arg) ||
563                     !strcmp("--invert-match", arg)) {
564                         opt.invert = 1;
565                         continue;
566                 }
567                 if (!strcmp("-E", arg) ||
568                     !strcmp("--extended-regexp", arg)) {
569                         opt.regflags |= REG_EXTENDED;
570                         continue;
571                 }
572                 if (!strcmp("-F", arg) ||
573                     !strcmp("--fixed-strings", arg)) {
574                         opt.fixed = 1;
575                         continue;
576                 }
577                 if (!strcmp("-G", arg) ||
578                     !strcmp("--basic-regexp", arg)) {
579                         opt.regflags &= ~REG_EXTENDED;
580                         continue;
581                 }
582                 if (!strcmp("-n", arg)) {
583                         opt.linenum = 1;
584                         continue;
585                 }
586                 if (!strcmp("-H", arg)) {
587                         /* We always show the pathname, so this
588                          * is a noop.
589                          */
590                         continue;
591                 }
592                 if (!strcmp("-l", arg) ||
593                     !strcmp("--files-with-matches", arg)) {
594                         opt.name_only = 1;
595                         continue;
596                 }
597                 if (!strcmp("-L", arg) ||
598                     !strcmp("--files-without-match", arg)) {
599                         opt.unmatch_name_only = 1;
600                         continue;
601                 }
602                 if (!strcmp("-c", arg) ||
603                     !strcmp("--count", arg)) {
604                         opt.count = 1;
605                         continue;
606                 }
607                 if (!strcmp("-w", arg) ||
608                     !strcmp("--word-regexp", arg)) {
609                         opt.word_regexp = 1;
610                         continue;
611                 }
612                 if (!strncmp("-A", arg, 2) ||
613                     !strncmp("-B", arg, 2) ||
614                     !strncmp("-C", arg, 2) ||
615                     (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
616                         unsigned num;
617                         const char *scan;
618                         switch (arg[1]) {
619                         case 'A': case 'B': case 'C':
620                                 if (!arg[2]) {
621                                         if (argc <= 1)
622                                                 usage(builtin_grep_usage);
623                                         scan = *++argv;
624                                         argc--;
625                                 }
626                                 else
627                                         scan = arg + 2;
628                                 break;
629                         default:
630                                 scan = arg + 1;
631                                 break;
632                         }
633                         if (sscanf(scan, "%u", &num) != 1)
634                                 usage(builtin_grep_usage);
635                         switch (arg[1]) {
636                         case 'A':
637                                 opt.post_context = num;
638                                 break;
639                         default:
640                         case 'C':
641                                 opt.post_context = num;
642                         case 'B':
643                                 opt.pre_context = num;
644                                 break;
645                         }
646                         continue;
647                 }
648                 if (!strcmp("-f", arg)) {
649                         FILE *patterns;
650                         int lno = 0;
651                         char buf[1024];
652                         if (argc <= 1)
653                                 usage(builtin_grep_usage);
654                         patterns = fopen(argv[1], "r");
655                         if (!patterns)
656                                 die("'%s': %s", argv[1], strerror(errno));
657                         while (fgets(buf, sizeof(buf), patterns)) {
658                                 int len = strlen(buf);
659                                 if (buf[len-1] == '\n')
660                                         buf[len-1] = 0;
661                                 /* ignore empty line like grep does */
662                                 if (!buf[0])
663                                         continue;
664                                 add_pattern(&opt, strdup(buf), argv[1], ++lno);
665                         }
666                         fclose(patterns);
667                         argv++;
668                         argc--;
669                         continue;
670                 }
671                 if (!strcmp("-e", arg)) {
672                         if (1 < argc) {
673                                 add_pattern(&opt, argv[1], "-e option", 0);
674                                 argv++;
675                                 argc--;
676                                 continue;
677                         }
678                         usage(builtin_grep_usage);
679                 }
680                 if (!strcmp("--", arg))
681                         break;
682                 if (*arg == '-')
683                         usage(builtin_grep_usage);
684
685                 /* First unrecognized non-option token */
686                 if (!opt.pattern_list) {
687                         add_pattern(&opt, arg, "command line", 0);
688                         break;
689                 }
690                 else {
691                         /* We are looking at the first path or rev;
692                          * it is found at argv[1] after leaving the
693                          * loop.
694                          */
695                         argc++; argv--;
696                         break;
697                 }
698         }
699
700         if (!opt.pattern_list)
701                 die("no pattern given.");
702         if ((opt.regflags != REG_NEWLINE) && opt.fixed)
703                 die("cannot mix --fixed-strings and regexp");
704         if (!opt.fixed)
705                 compile_patterns(&opt);
706
707         /* Check revs and then paths */
708         for (i = 1; i < argc; i++) {
709                 const char *arg = argv[i];
710                 unsigned char sha1[20];
711                 /* Is it a rev? */
712                 if (!get_sha1(arg, sha1)) {
713                         struct object *object = parse_object(sha1);
714                         struct object_list *elem;
715                         if (!object)
716                                 die("bad object %s", arg);
717                         elem = object_list_insert(object, tail);
718                         elem->name = arg;
719                         tail = &elem->next;
720                         continue;
721                 }
722                 if (!strcmp(arg, "--")) {
723                         i++;
724                         seen_dashdash = 1;
725                 }
726                 break;
727         }
728
729         /* The rest are paths */
730         if (!seen_dashdash) {
731                 int j;
732                 for (j = i; j < argc; j++)
733                         verify_filename(prefix, argv[j]);
734         }
735
736         if (i < argc)
737                 paths = get_pathspec(prefix, argv + i);
738         else if (prefix) {
739                 paths = xcalloc(2, sizeof(const char *));
740                 paths[0] = prefix;
741                 paths[1] = NULL;
742         }
743
744         if (!object_list)
745                 return !grep_cache(&opt, paths, cached);
746
747         if (cached)
748                 die("both --cached and trees are given.");
749
750         for (list = object_list; list; list = list->next) {
751                 struct object *real_obj;
752                 real_obj = deref_tag(list->item, NULL, 0);
753                 if (grep_object(&opt, paths, real_obj, list->name))
754                         hit = 1;
755         }
756         return !hit;
757 }