Code

Make show_entry void
[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 #include <sys/wait.h>
17 /*
18  * git grep pathspecs are somewhat different from diff-tree pathspecs;
19  * pathname wildcards are allowed.
20  */
21 static int pathspec_matches(const char **paths, const char *name)
22 {
23         int namelen, i;
24         if (!paths || !*paths)
25                 return 1;
26         namelen = strlen(name);
27         for (i = 0; paths[i]; i++) {
28                 const char *match = paths[i];
29                 int matchlen = strlen(match);
30                 const char *cp, *meta;
32                 if (!matchlen ||
33                     ((matchlen <= namelen) &&
34                      !strncmp(name, match, matchlen) &&
35                      (match[matchlen-1] == '/' ||
36                       name[matchlen] == '\0' || name[matchlen] == '/')))
37                         return 1;
38                 if (!fnmatch(match, name, 0))
39                         return 1;
40                 if (name[namelen-1] != '/')
41                         continue;
43                 /* We are being asked if the directory ("name") is worth
44                  * descending into.
45                  *
46                  * Find the longest leading directory name that does
47                  * not have metacharacter in the pathspec; the name
48                  * we are looking at must overlap with that directory.
49                  */
50                 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
51                         char ch = *cp;
52                         if (ch == '*' || ch == '[' || ch == '?') {
53                                 meta = cp;
54                                 break;
55                         }
56                 }
57                 if (!meta)
58                         meta = cp; /* fully literal */
60                 if (namelen <= meta - match) {
61                         /* Looking at "Documentation/" and
62                          * the pattern says "Documentation/howto/", or
63                          * "Documentation/diff*.txt".  The name we
64                          * have should match prefix.
65                          */
66                         if (!memcmp(match, name, namelen))
67                                 return 1;
68                         continue;
69                 }
71                 if (meta - match < namelen) {
72                         /* Looking at "Documentation/howto/" and
73                          * the pattern says "Documentation/h*";
74                          * match up to "Do.../h"; this avoids descending
75                          * into "Documentation/technical/".
76                          */
77                         if (!memcmp(match, name, meta - match))
78                                 return 1;
79                         continue;
80                 }
81         }
82         return 0;
83 }
85 enum grep_pat_token {
86         GREP_PATTERN,
87         GREP_AND,
88         GREP_OPEN_PAREN,
89         GREP_CLOSE_PAREN,
90         GREP_NOT,
91         GREP_OR,
92 };
94 struct grep_pat {
95         struct grep_pat *next;
96         const char *origin;
97         int no;
98         enum grep_pat_token token;
99         const char *pattern;
100         regex_t regexp;
101 };
103 enum grep_expr_node {
104         GREP_NODE_ATOM,
105         GREP_NODE_NOT,
106         GREP_NODE_AND,
107         GREP_NODE_OR,
108 };
110 struct grep_expr {
111         enum grep_expr_node node;
112         union {
113                 struct grep_pat *atom;
114                 struct grep_expr *unary;
115                 struct {
116                         struct grep_expr *left;
117                         struct grep_expr *right;
118                 } binary;
119         } u;
120 };
122 struct grep_opt {
123         struct grep_pat *pattern_list;
124         struct grep_pat **pattern_tail;
125         struct grep_expr *pattern_expression;
126         int prefix_length;
127         regex_t regexp;
128         unsigned linenum:1;
129         unsigned invert:1;
130         unsigned name_only:1;
131         unsigned unmatch_name_only:1;
132         unsigned count:1;
133         unsigned word_regexp:1;
134         unsigned fixed:1;
135 #define GREP_BINARY_DEFAULT     0
136 #define GREP_BINARY_NOMATCH     1
137 #define GREP_BINARY_TEXT        2
138         unsigned binary:2;
139         unsigned extended:1;
140         unsigned relative:1;
141         int regflags;
142         unsigned pre_context;
143         unsigned post_context;
144 };
146 static void add_pattern(struct grep_opt *opt, const char *pat,
147                         const char *origin, int no, enum grep_pat_token t)
149         struct grep_pat *p = xcalloc(1, sizeof(*p));
150         p->pattern = pat;
151         p->origin = origin;
152         p->no = no;
153         p->token = t;
154         *opt->pattern_tail = p;
155         opt->pattern_tail = &p->next;
156         p->next = NULL;
159 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
161         int err = regcomp(&p->regexp, p->pattern, opt->regflags);
162         if (err) {
163                 char errbuf[1024];
164                 char where[1024];
165                 if (p->no)
166                         sprintf(where, "In '%s' at %d, ",
167                                 p->origin, p->no);
168                 else if (p->origin)
169                         sprintf(where, "%s, ", p->origin);
170                 else
171                         where[0] = 0;
172                 regerror(err, &p->regexp, errbuf, 1024);
173                 regfree(&p->regexp);
174                 die("%s'%s': %s", where, p->pattern, errbuf);
175         }
178 #if DEBUG
179 static inline void indent(int in)
181         int i;
182         for (i = 0; i < in; i++) putchar(' ');
185 static void dump_pattern_exp(struct grep_expr *x, int in)
187         switch (x->node) {
188         case GREP_NODE_ATOM:
189                 indent(in);
190                 puts(x->u.atom->pattern);
191                 break;
192         case GREP_NODE_NOT:
193                 indent(in);
194                 puts("--not");
195                 dump_pattern_exp(x->u.unary, in+1);
196                 break;
197         case GREP_NODE_AND:
198                 dump_pattern_exp(x->u.binary.left, in+1);
199                 indent(in);
200                 puts("--and");
201                 dump_pattern_exp(x->u.binary.right, in+1);
202                 break;
203         case GREP_NODE_OR:
204                 dump_pattern_exp(x->u.binary.left, in+1);
205                 indent(in);
206                 puts("--or");
207                 dump_pattern_exp(x->u.binary.right, in+1);
208                 break;
209         }
212 static void looking_at(const char *msg, struct grep_pat **list)
214         struct grep_pat *p = *list;
215         fprintf(stderr, "%s: looking at ", msg);
216         if (!p)
217                 fprintf(stderr, "empty\n");
218         else
219                 fprintf(stderr, "<%s>\n", p->pattern);
221 #else
222 #define looking_at(a,b) do {} while(0)
223 #endif
225 static struct grep_expr *compile_pattern_expr(struct grep_pat **);
226 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
228         struct grep_pat *p;
229         struct grep_expr *x;
231         looking_at("atom", list);
233         p = *list;
234         switch (p->token) {
235         case GREP_PATTERN: /* atom */
236                 x = xcalloc(1, sizeof (struct grep_expr));
237                 x->node = GREP_NODE_ATOM;
238                 x->u.atom = p;
239                 *list = p->next;
240                 return x;
241         case GREP_OPEN_PAREN:
242                 *list = p->next;
243                 x = compile_pattern_expr(list);
244                 if (!x)
245                         return NULL;
246                 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
247                         die("unmatched parenthesis");
248                 *list = (*list)->next;
249                 return x;
250         default:
251                 return NULL;
252         }
255 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
257         struct grep_pat *p;
258         struct grep_expr *x;
260         looking_at("not", list);
262         p = *list;
263         switch (p->token) {
264         case GREP_NOT:
265                 if (!p->next)
266                         die("--not not followed by pattern expression");
267                 *list = p->next;
268                 x = xcalloc(1, sizeof (struct grep_expr));
269                 x->node = GREP_NODE_NOT;
270                 x->u.unary = compile_pattern_not(list);
271                 if (!x->u.unary)
272                         die("--not followed by non pattern expression");
273                 return x;
274         default:
275                 return compile_pattern_atom(list);
276         }
279 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
281         struct grep_pat *p;
282         struct grep_expr *x, *y, *z;
284         looking_at("and", list);
286         x = compile_pattern_not(list);
287         p = *list;
288         if (p && p->token == GREP_AND) {
289                 if (!p->next)
290                         die("--and not followed by pattern expression");
291                 *list = p->next;
292                 y = compile_pattern_and(list);
293                 if (!y)
294                         die("--and not followed by pattern expression");
295                 z = xcalloc(1, sizeof (struct grep_expr));
296                 z->node = GREP_NODE_AND;
297                 z->u.binary.left = x;
298                 z->u.binary.right = y;
299                 return z;
300         }
301         return x;
304 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
306         struct grep_pat *p;
307         struct grep_expr *x, *y, *z;
309         looking_at("or", list);
311         x = compile_pattern_and(list);
312         p = *list;
313         if (x && p && p->token != GREP_CLOSE_PAREN) {
314                 y = compile_pattern_or(list);
315                 if (!y)
316                         die("not a pattern expression %s", p->pattern);
317                 z = xcalloc(1, sizeof (struct grep_expr));
318                 z->node = GREP_NODE_OR;
319                 z->u.binary.left = x;
320                 z->u.binary.right = y;
321                 return z;
322         }
323         return x;
326 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
328         looking_at("expr", list);
330         return compile_pattern_or(list);
333 static void compile_patterns(struct grep_opt *opt)
335         struct grep_pat *p;
337         /* First compile regexps */
338         for (p = opt->pattern_list; p; p = p->next) {
339                 if (p->token == GREP_PATTERN)
340                         compile_regexp(p, opt);
341                 else
342                         opt->extended = 1;
343         }
345         if (!opt->extended)
346                 return;
348         /* Then bundle them up in an expression.
349          * A classic recursive descent parser would do.
350          */
351         p = opt->pattern_list;
352         opt->pattern_expression = compile_pattern_expr(&p);
353 #if DEBUG
354         dump_pattern_exp(opt->pattern_expression, 0);
355 #endif
356         if (p)
357                 die("incomplete pattern expression: %s", p->pattern);
360 static char *end_of_line(char *cp, unsigned long *left)
362         unsigned long l = *left;
363         while (l && *cp != '\n') {
364                 l--;
365                 cp++;
366         }
367         *left = l;
368         return cp;
371 static int word_char(char ch)
373         return isalnum(ch) || ch == '_';
376 static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
377                       const char *name, unsigned lno, char sign)
379         printf("%s%c", name, sign);
380         if (opt->linenum)
381                 printf("%d%c", lno, sign);
382         printf("%.*s\n", (int)(eol-bol), bol);
385 /*
386  * NEEDSWORK: share code with diff.c
387  */
388 #define FIRST_FEW_BYTES 8000
389 static int buffer_is_binary(const char *ptr, unsigned long size)
391         if (FIRST_FEW_BYTES < size)
392                 size = FIRST_FEW_BYTES;
393         return !!memchr(ptr, 0, size);
396 static int fixmatch(const char *pattern, char *line, regmatch_t *match)
398         char *hit = strstr(line, pattern);
399         if (!hit) {
400                 match->rm_so = match->rm_eo = -1;
401                 return REG_NOMATCH;
402         }
403         else {
404                 match->rm_so = hit - line;
405                 match->rm_eo = match->rm_so + strlen(pattern);
406                 return 0;
407         }
410 static int match_one_pattern(struct grep_opt *opt, struct grep_pat *p, char *bol, char *eol)
412         int hit = 0;
413         int at_true_bol = 1;
414         regmatch_t pmatch[10];
416  again:
417         if (!opt->fixed) {
418                 regex_t *exp = &p->regexp;
419                 hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
420                                pmatch, 0);
421         }
422         else {
423                 hit = !fixmatch(p->pattern, bol, pmatch);
424         }
426         if (hit && opt->word_regexp) {
427                 if ((pmatch[0].rm_so < 0) ||
428                     (eol - bol) <= pmatch[0].rm_so ||
429                     (pmatch[0].rm_eo < 0) ||
430                     (eol - bol) < pmatch[0].rm_eo)
431                         die("regexp returned nonsense");
433                 /* Match beginning must be either beginning of the
434                  * line, or at word boundary (i.e. the last char must
435                  * not be a word char).  Similarly, match end must be
436                  * either end of the line, or at word boundary
437                  * (i.e. the next char must not be a word char).
438                  */
439                 if ( ((pmatch[0].rm_so == 0 && at_true_bol) ||
440                       !word_char(bol[pmatch[0].rm_so-1])) &&
441                      ((pmatch[0].rm_eo == (eol-bol)) ||
442                       !word_char(bol[pmatch[0].rm_eo])) )
443                         ;
444                 else
445                         hit = 0;
447                 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
448                         /* There could be more than one match on the
449                          * line, and the first match might not be
450                          * strict word match.  But later ones could be!
451                          */
452                         bol = pmatch[0].rm_so + bol + 1;
453                         at_true_bol = 0;
454                         goto again;
455                 }
456         }
457         return hit;
460 static int match_expr_eval(struct grep_opt *opt,
461                            struct grep_expr *x,
462                            char *bol, char *eol)
464         switch (x->node) {
465         case GREP_NODE_ATOM:
466                 return match_one_pattern(opt, x->u.atom, bol, eol);
467                 break;
468         case GREP_NODE_NOT:
469                 return !match_expr_eval(opt, x->u.unary, bol, eol);
470         case GREP_NODE_AND:
471                 return (match_expr_eval(opt, x->u.binary.left, bol, eol) &&
472                         match_expr_eval(opt, x->u.binary.right, bol, eol));
473         case GREP_NODE_OR:
474                 return (match_expr_eval(opt, x->u.binary.left, bol, eol) ||
475                         match_expr_eval(opt, x->u.binary.right, bol, eol));
476         }
477         die("Unexpected node type (internal error) %d\n", x->node);
480 static int match_expr(struct grep_opt *opt, char *bol, char *eol)
482         struct grep_expr *x = opt->pattern_expression;
483         return match_expr_eval(opt, x, bol, eol);
486 static int match_line(struct grep_opt *opt, char *bol, char *eol)
488         struct grep_pat *p;
489         if (opt->extended)
490                 return match_expr(opt, bol, eol);
491         for (p = opt->pattern_list; p; p = p->next) {
492                 if (match_one_pattern(opt, p, bol, eol))
493                         return 1;
494         }
495         return 0;
498 static int grep_buffer(struct grep_opt *opt, const char *name,
499                        char *buf, unsigned long size)
501         char *bol = buf;
502         unsigned long left = size;
503         unsigned lno = 1;
504         struct pre_context_line {
505                 char *bol;
506                 char *eol;
507         } *prev = NULL, *pcl;
508         unsigned last_hit = 0;
509         unsigned last_shown = 0;
510         int binary_match_only = 0;
511         const char *hunk_mark = "";
512         unsigned count = 0;
514         if (buffer_is_binary(buf, size)) {
515                 switch (opt->binary) {
516                 case GREP_BINARY_DEFAULT:
517                         binary_match_only = 1;
518                         break;
519                 case GREP_BINARY_NOMATCH:
520                         return 0; /* Assume unmatch */
521                         break;
522                 default:
523                         break;
524                 }
525         }
527         if (opt->pre_context)
528                 prev = xcalloc(opt->pre_context, sizeof(*prev));
529         if (opt->pre_context || opt->post_context)
530                 hunk_mark = "--\n";
532         while (left) {
533                 char *eol, ch;
534                 int hit = 0;
536                 eol = end_of_line(bol, &left);
537                 ch = *eol;
538                 *eol = 0;
540                 hit = match_line(opt, bol, eol);
542                 /* "grep -v -e foo -e bla" should list lines
543                  * that do not have either, so inversion should
544                  * be done outside.
545                  */
546                 if (opt->invert)
547                         hit = !hit;
548                 if (opt->unmatch_name_only) {
549                         if (hit)
550                                 return 0;
551                         goto next_line;
552                 }
553                 if (hit) {
554                         count++;
555                         if (binary_match_only) {
556                                 printf("Binary file %s matches\n", name);
557                                 return 1;
558                         }
559                         if (opt->name_only) {
560                                 printf("%s\n", name);
561                                 return 1;
562                         }
563                         /* Hit at this line.  If we haven't shown the
564                          * pre-context lines, we would need to show them.
565                          * When asked to do "count", this still show
566                          * the context which is nonsense, but the user
567                          * deserves to get that ;-).
568                          */
569                         if (opt->pre_context) {
570                                 unsigned from;
571                                 if (opt->pre_context < lno)
572                                         from = lno - opt->pre_context;
573                                 else
574                                         from = 1;
575                                 if (from <= last_shown)
576                                         from = last_shown + 1;
577                                 if (last_shown && from != last_shown + 1)
578                                         printf(hunk_mark);
579                                 while (from < lno) {
580                                         pcl = &prev[lno-from-1];
581                                         show_line(opt, pcl->bol, pcl->eol,
582                                                   name, from, '-');
583                                         from++;
584                                 }
585                                 last_shown = lno-1;
586                         }
587                         if (last_shown && lno != last_shown + 1)
588                                 printf(hunk_mark);
589                         if (!opt->count)
590                                 show_line(opt, bol, eol, name, lno, ':');
591                         last_shown = last_hit = lno;
592                 }
593                 else if (last_hit &&
594                          lno <= last_hit + opt->post_context) {
595                         /* If the last hit is within the post context,
596                          * we need to show this line.
597                          */
598                         if (last_shown && lno != last_shown + 1)
599                                 printf(hunk_mark);
600                         show_line(opt, bol, eol, name, lno, '-');
601                         last_shown = lno;
602                 }
603                 if (opt->pre_context) {
604                         memmove(prev+1, prev,
605                                 (opt->pre_context-1) * sizeof(*prev));
606                         prev->bol = bol;
607                         prev->eol = eol;
608                 }
610         next_line:
611                 *eol = ch;
612                 bol = eol + 1;
613                 if (!left)
614                         break;
615                 left--;
616                 lno++;
617         }
619         if (opt->unmatch_name_only) {
620                 /* We did not see any hit, so we want to show this */
621                 printf("%s\n", name);
622                 return 1;
623         }
625         /* NEEDSWORK:
626          * The real "grep -c foo *.c" gives many "bar.c:0" lines,
627          * which feels mostly useless but sometimes useful.  Maybe
628          * make it another option?  For now suppress them.
629          */
630         if (opt->count && count)
631                 printf("%s:%u\n", name, count);
632         return !!last_hit;
635 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
637         unsigned long size;
638         char *data;
639         char type[20];
640         char *to_free = NULL;
641         int hit;
643         data = read_sha1_file(sha1, type, &size);
644         if (!data) {
645                 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
646                 return 0;
647         }
648         if (opt->relative && opt->prefix_length) {
649                 static char name_buf[PATH_MAX];
650                 char *cp;
651                 int name_len = strlen(name) - opt->prefix_length + 1;
653                 if (!tree_name_len)
654                         name += opt->prefix_length;
655                 else {
656                         if (ARRAY_SIZE(name_buf) <= name_len)
657                                 cp = to_free = xmalloc(name_len);
658                         else
659                                 cp = name_buf;
660                         memcpy(cp, name, tree_name_len);
661                         strcpy(cp + tree_name_len,
662                                name + tree_name_len + opt->prefix_length);
663                         name = cp;
664                 }
665         }
666         hit = grep_buffer(opt, name, data, size);
667         free(data);
668         free(to_free);
669         return hit;
672 static int grep_file(struct grep_opt *opt, const char *filename)
674         struct stat st;
675         int i;
676         char *data;
677         if (lstat(filename, &st) < 0) {
678         err_ret:
679                 if (errno != ENOENT)
680                         error("'%s': %s", filename, strerror(errno));
681                 return 0;
682         }
683         if (!st.st_size)
684                 return 0; /* empty file -- no grep hit */
685         if (!S_ISREG(st.st_mode))
686                 return 0;
687         i = open(filename, O_RDONLY);
688         if (i < 0)
689                 goto err_ret;
690         data = xmalloc(st.st_size + 1);
691         if (st.st_size != xread(i, data, st.st_size)) {
692                 error("'%s': short read %s", filename, strerror(errno));
693                 close(i);
694                 free(data);
695                 return 0;
696         }
697         close(i);
698         if (opt->relative && opt->prefix_length)
699                 filename += opt->prefix_length;
700         i = grep_buffer(opt, filename, data, st.st_size);
701         free(data);
702         return i;
705 static int exec_grep(int argc, const char **argv)
707         pid_t pid;
708         int status;
710         argv[argc] = NULL;
711         pid = fork();
712         if (pid < 0)
713                 return pid;
714         if (!pid) {
715                 execvp("grep", (char **) argv);
716                 exit(255);
717         }
718         while (waitpid(pid, &status, 0) < 0) {
719                 if (errno == EINTR)
720                         continue;
721                 return -1;
722         }
723         if (WIFEXITED(status)) {
724                 if (!WEXITSTATUS(status))
725                         return 1;
726                 return 0;
727         }
728         return -1;
731 #define MAXARGS 1000
732 #define ARGBUF 4096
733 #define push_arg(a) do { \
734         if (nr < MAXARGS) argv[nr++] = (a); \
735         else die("maximum number of args exceeded"); \
736         } while (0)
738 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
740         int i, nr, argc, hit, len, status;
741         const char *argv[MAXARGS+1];
742         char randarg[ARGBUF];
743         char *argptr = randarg;
744         struct grep_pat *p;
746         if (opt->extended || (opt->relative && opt->prefix_length))
747                 return -1;
748         len = nr = 0;
749         push_arg("grep");
750         if (opt->fixed)
751                 push_arg("-F");
752         if (opt->linenum)
753                 push_arg("-n");
754         if (opt->regflags & REG_EXTENDED)
755                 push_arg("-E");
756         if (opt->regflags & REG_ICASE)
757                 push_arg("-i");
758         if (opt->word_regexp)
759                 push_arg("-w");
760         if (opt->name_only)
761                 push_arg("-l");
762         if (opt->unmatch_name_only)
763                 push_arg("-L");
764         if (opt->count)
765                 push_arg("-c");
766         if (opt->post_context || opt->pre_context) {
767                 if (opt->post_context != opt->pre_context) {
768                         if (opt->pre_context) {
769                                 push_arg("-B");
770                                 len += snprintf(argptr, sizeof(randarg)-len,
771                                                 "%u", opt->pre_context);
772                                 if (sizeof(randarg) <= len)
773                                         die("maximum length of args exceeded");
774                                 push_arg(argptr);
775                                 argptr += len;
776                         }
777                         if (opt->post_context) {
778                                 push_arg("-A");
779                                 len += snprintf(argptr, sizeof(randarg)-len,
780                                                 "%u", opt->post_context);
781                                 if (sizeof(randarg) <= len)
782                                         die("maximum length of args exceeded");
783                                 push_arg(argptr);
784                                 argptr += len;
785                         }
786                 }
787                 else {
788                         push_arg("-C");
789                         len += snprintf(argptr, sizeof(randarg)-len,
790                                         "%u", opt->post_context);
791                         if (sizeof(randarg) <= len)
792                                 die("maximum length of args exceeded");
793                         push_arg(argptr);
794                         argptr += len;
795                 }
796         }
797         for (p = opt->pattern_list; p; p = p->next) {
798                 push_arg("-e");
799                 push_arg(p->pattern);
800         }
802         /*
803          * To make sure we get the header printed out when we want it,
804          * add /dev/null to the paths to grep.  This is unnecessary
805          * (and wrong) with "-l" or "-L", which always print out the
806          * name anyway.
807          *
808          * GNU grep has "-H", but this is portable.
809          */
810         if (!opt->name_only && !opt->unmatch_name_only)
811                 push_arg("/dev/null");
813         hit = 0;
814         argc = nr;
815         for (i = 0; i < active_nr; i++) {
816                 struct cache_entry *ce = active_cache[i];
817                 char *name;
818                 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
819                         continue;
820                 if (!pathspec_matches(paths, ce->name))
821                         continue;
822                 name = ce->name;
823                 if (name[0] == '-') {
824                         int len = ce_namelen(ce);
825                         name = xmalloc(len + 3);
826                         memcpy(name, "./", 2);
827                         memcpy(name + 2, ce->name, len + 1);
828                 }
829                 argv[argc++] = name;
830                 if (argc < MAXARGS)
831                         continue;
832                 status = exec_grep(argc, argv);
833                 if (0 < status)
834                         hit = 1;
835                 argc = nr;
836         }
837         if (argc > nr) {
838                 status = exec_grep(argc, argv);
839                 if (0 < status)
840                         hit = 1;
841         }
842         return hit;
845 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
847         int hit = 0;
848         int nr;
849         read_cache();
851 #ifdef __unix__
852         /*
853          * Use the external "grep" command for the case where
854          * we grep through the checked-out files. It tends to
855          * be a lot more optimized
856          */
857         if (!cached) {
858                 hit = external_grep(opt, paths, cached);
859                 if (hit >= 0)
860                         return hit;
861         }
862 #endif
864         for (nr = 0; nr < active_nr; nr++) {
865                 struct cache_entry *ce = active_cache[nr];
866                 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
867                         continue;
868                 if (!pathspec_matches(paths, ce->name))
869                         continue;
870                 if (cached)
871                         hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
872                 else
873                         hit |= grep_file(opt, ce->name);
874         }
875         return hit;
878 static int grep_tree(struct grep_opt *opt, const char **paths,
879                      struct tree_desc *tree,
880                      const char *tree_name, const char *base)
882         int len;
883         int hit = 0;
884         struct name_entry entry;
885         char *down;
886         int tn_len = strlen(tree_name);
887         char *path_buf = xmalloc(PATH_MAX + tn_len + 100);
889         if (tn_len) {
890                 tn_len = sprintf(path_buf, "%s:", tree_name);
891                 down = path_buf + tn_len;
892                 strcat(down, base);
893         }
894         else {
895                 down = path_buf;
896                 strcpy(down, base);
897         }
898         len = strlen(path_buf);
900         while (tree_entry(tree, &entry)) {
901                 strcpy(path_buf + len, entry.path);
903                 if (S_ISDIR(entry.mode))
904                         /* Match "abc/" against pathspec to
905                          * decide if we want to descend into "abc"
906                          * directory.
907                          */
908                         strcpy(path_buf + len + entry.pathlen, "/");
910                 if (!pathspec_matches(paths, down))
911                         ;
912                 else if (S_ISREG(entry.mode))
913                         hit |= grep_sha1(opt, entry.sha1, path_buf, tn_len);
914                 else if (S_ISDIR(entry.mode)) {
915                         char type[20];
916                         struct tree_desc sub;
917                         void *data;
918                         data = read_sha1_file(entry.sha1, type, &sub.size);
919                         if (!data)
920                                 die("unable to read tree (%s)",
921                                     sha1_to_hex(entry.sha1));
922                         sub.buf = data;
923                         hit |= grep_tree(opt, paths, &sub, tree_name, down);
924                         free(data);
925                 }
926         }
927         return hit;
930 static int grep_object(struct grep_opt *opt, const char **paths,
931                        struct object *obj, const char *name)
933         if (obj->type == OBJ_BLOB)
934                 return grep_sha1(opt, obj->sha1, name, 0);
935         if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
936                 struct tree_desc tree;
937                 void *data;
938                 int hit;
939                 data = read_object_with_reference(obj->sha1, tree_type,
940                                                   &tree.size, NULL);
941                 if (!data)
942                         die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
943                 tree.buf = data;
944                 hit = grep_tree(opt, paths, &tree, name, "");
945                 free(data);
946                 return hit;
947         }
948         die("unable to grep from object of type %s", typename(obj->type));
951 static const char builtin_grep_usage[] =
952 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
954 static const char emsg_invalid_context_len[] =
955 "%s: invalid context length argument";
956 static const char emsg_missing_context_len[] =
957 "missing context length argument";
958 static const char emsg_missing_argument[] =
959 "option requires an argument -%s";
961 int cmd_grep(int argc, const char **argv, const char *prefix)
963         int hit = 0;
964         int cached = 0;
965         int seen_dashdash = 0;
966         struct grep_opt opt;
967         struct object_array list = { 0, 0, NULL };
968         const char **paths = NULL;
969         int i;
971         memset(&opt, 0, sizeof(opt));
972         opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
973         opt.relative = 1;
974         opt.pattern_tail = &opt.pattern_list;
975         opt.regflags = REG_NEWLINE;
977         /*
978          * If there is no -- then the paths must exist in the working
979          * tree.  If there is no explicit pattern specified with -e or
980          * -f, we take the first unrecognized non option to be the
981          * pattern, but then what follows it must be zero or more
982          * valid refs up to the -- (if exists), and then existing
983          * paths.  If there is an explicit pattern, then the first
984          * unrecognized non option is the beginning of the refs list
985          * that continues up to the -- (if exists), and then paths.
986          */
988         while (1 < argc) {
989                 const char *arg = argv[1];
990                 argc--; argv++;
991                 if (!strcmp("--cached", arg)) {
992                         cached = 1;
993                         continue;
994                 }
995                 if (!strcmp("-a", arg) ||
996                     !strcmp("--text", arg)) {
997                         opt.binary = GREP_BINARY_TEXT;
998                         continue;
999                 }
1000                 if (!strcmp("-i", arg) ||
1001                     !strcmp("--ignore-case", arg)) {
1002                         opt.regflags |= REG_ICASE;
1003                         continue;
1004                 }
1005                 if (!strcmp("-I", arg)) {
1006                         opt.binary = GREP_BINARY_NOMATCH;
1007                         continue;
1008                 }
1009                 if (!strcmp("-v", arg) ||
1010                     !strcmp("--invert-match", arg)) {
1011                         opt.invert = 1;
1012                         continue;
1013                 }
1014                 if (!strcmp("-E", arg) ||
1015                     !strcmp("--extended-regexp", arg)) {
1016                         opt.regflags |= REG_EXTENDED;
1017                         continue;
1018                 }
1019                 if (!strcmp("-F", arg) ||
1020                     !strcmp("--fixed-strings", arg)) {
1021                         opt.fixed = 1;
1022                         continue;
1023                 }
1024                 if (!strcmp("-G", arg) ||
1025                     !strcmp("--basic-regexp", arg)) {
1026                         opt.regflags &= ~REG_EXTENDED;
1027                         continue;
1028                 }
1029                 if (!strcmp("-n", arg)) {
1030                         opt.linenum = 1;
1031                         continue;
1032                 }
1033                 if (!strcmp("-H", arg)) {
1034                         /* We always show the pathname, so this
1035                          * is a noop.
1036                          */
1037                         continue;
1038                 }
1039                 if (!strcmp("-l", arg) ||
1040                     !strcmp("--files-with-matches", arg)) {
1041                         opt.name_only = 1;
1042                         continue;
1043                 }
1044                 if (!strcmp("-L", arg) ||
1045                     !strcmp("--files-without-match", arg)) {
1046                         opt.unmatch_name_only = 1;
1047                         continue;
1048                 }
1049                 if (!strcmp("-c", arg) ||
1050                     !strcmp("--count", arg)) {
1051                         opt.count = 1;
1052                         continue;
1053                 }
1054                 if (!strcmp("-w", arg) ||
1055                     !strcmp("--word-regexp", arg)) {
1056                         opt.word_regexp = 1;
1057                         continue;
1058                 }
1059                 if (!strncmp("-A", arg, 2) ||
1060                     !strncmp("-B", arg, 2) ||
1061                     !strncmp("-C", arg, 2) ||
1062                     (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
1063                         unsigned num;
1064                         const char *scan;
1065                         switch (arg[1]) {
1066                         case 'A': case 'B': case 'C':
1067                                 if (!arg[2]) {
1068                                         if (argc <= 1)
1069                                                 die(emsg_missing_context_len);
1070                                         scan = *++argv;
1071                                         argc--;
1072                                 }
1073                                 else
1074                                         scan = arg + 2;
1075                                 break;
1076                         default:
1077                                 scan = arg + 1;
1078                                 break;
1079                         }
1080                         if (sscanf(scan, "%u", &num) != 1)
1081                                 die(emsg_invalid_context_len, scan);
1082                         switch (arg[1]) {
1083                         case 'A':
1084                                 opt.post_context = num;
1085                                 break;
1086                         default:
1087                         case 'C':
1088                                 opt.post_context = num;
1089                         case 'B':
1090                                 opt.pre_context = num;
1091                                 break;
1092                         }
1093                         continue;
1094                 }
1095                 if (!strcmp("-f", arg)) {
1096                         FILE *patterns;
1097                         int lno = 0;
1098                         char buf[1024];
1099                         if (argc <= 1)
1100                                 die(emsg_missing_argument, arg);
1101                         patterns = fopen(argv[1], "r");
1102                         if (!patterns)
1103                                 die("'%s': %s", argv[1], strerror(errno));
1104                         while (fgets(buf, sizeof(buf), patterns)) {
1105                                 int len = strlen(buf);
1106                                 if (buf[len-1] == '\n')
1107                                         buf[len-1] = 0;
1108                                 /* ignore empty line like grep does */
1109                                 if (!buf[0])
1110                                         continue;
1111                                 add_pattern(&opt, strdup(buf), argv[1], ++lno,
1112                                             GREP_PATTERN);
1113                         }
1114                         fclose(patterns);
1115                         argv++;
1116                         argc--;
1117                         continue;
1118                 }
1119                 if (!strcmp("--not", arg)) {
1120                         add_pattern(&opt, arg, "command line", 0, GREP_NOT);
1121                         continue;
1122                 }
1123                 if (!strcmp("--and", arg)) {
1124                         add_pattern(&opt, arg, "command line", 0, GREP_AND);
1125                         continue;
1126                 }
1127                 if (!strcmp("--or", arg))
1128                         continue; /* no-op */
1129                 if (!strcmp("(", arg)) {
1130                         add_pattern(&opt, arg, "command line", 0, GREP_OPEN_PAREN);
1131                         continue;
1132                 }
1133                 if (!strcmp(")", arg)) {
1134                         add_pattern(&opt, arg, "command line", 0, GREP_CLOSE_PAREN);
1135                         continue;
1136                 }
1137                 if (!strcmp("-e", arg)) {
1138                         if (1 < argc) {
1139                                 add_pattern(&opt, argv[1], "-e option", 0,
1140                                             GREP_PATTERN);
1141                                 argv++;
1142                                 argc--;
1143                                 continue;
1144                         }
1145                         die(emsg_missing_argument, arg);
1146                 }
1147                 if (!strcmp("--full-name", arg)) {
1148                         opt.relative = 0;
1149                         continue;
1150                 }
1151                 if (!strcmp("--", arg)) {
1152                         /* later processing wants to have this at argv[1] */
1153                         argv--;
1154                         argc++;
1155                         break;
1156                 }
1157                 if (*arg == '-')
1158                         usage(builtin_grep_usage);
1160                 /* First unrecognized non-option token */
1161                 if (!opt.pattern_list) {
1162                         add_pattern(&opt, arg, "command line", 0,
1163                                     GREP_PATTERN);
1164                         break;
1165                 }
1166                 else {
1167                         /* We are looking at the first path or rev;
1168                          * it is found at argv[1] after leaving the
1169                          * loop.
1170                          */
1171                         argc++; argv--;
1172                         break;
1173                 }
1174         }
1176         if (!opt.pattern_list)
1177                 die("no pattern given.");
1178         if ((opt.regflags != REG_NEWLINE) && opt.fixed)
1179                 die("cannot mix --fixed-strings and regexp");
1180         if (!opt.fixed)
1181                 compile_patterns(&opt);
1183         /* Check revs and then paths */
1184         for (i = 1; i < argc; i++) {
1185                 const char *arg = argv[i];
1186                 unsigned char sha1[20];
1187                 /* Is it a rev? */
1188                 if (!get_sha1(arg, sha1)) {
1189                         struct object *object = parse_object(sha1);
1190                         if (!object)
1191                                 die("bad object %s", arg);
1192                         add_object_array(object, arg, &list);
1193                         continue;
1194                 }
1195                 if (!strcmp(arg, "--")) {
1196                         i++;
1197                         seen_dashdash = 1;
1198                 }
1199                 break;
1200         }
1202         /* The rest are paths */
1203         if (!seen_dashdash) {
1204                 int j;
1205                 for (j = i; j < argc; j++)
1206                         verify_filename(prefix, argv[j]);
1207         }
1209         if (i < argc) {
1210                 paths = get_pathspec(prefix, argv + i);
1211                 if (opt.prefix_length && opt.relative) {
1212                         /* Make sure we do not get outside of paths */
1213                         for (i = 0; paths[i]; i++)
1214                                 if (strncmp(prefix, paths[i], opt.prefix_length))
1215                                         die("git-grep: cannot generate relative filenames containing '..'");
1216                 }
1217         }
1218         else if (prefix) {
1219                 paths = xcalloc(2, sizeof(const char *));
1220                 paths[0] = prefix;
1221                 paths[1] = NULL;
1222         }
1224         if (!list.nr)
1225                 return !grep_cache(&opt, paths, cached);
1227         if (cached)
1228                 die("both --cached and trees are given.");
1230         for (i = 0; i < list.nr; i++) {
1231                 struct object *real_obj;
1232                 real_obj = deref_tag(list.objects[i].item, NULL, 0);
1233                 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
1234                         hit = 1;
1235         }
1236         return !hit;