builtin-grep: support -w (--word-regexp).
[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 *slash, *cp;
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 name directory 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, slash = NULL; cp - match < matchlen; cp++) {
49                         char ch = *cp;
50                         if (ch == '/')
51                                 slash = cp;
52                         if (ch == '*' || ch == '[')
53                                 break;
54                 }
55                 if (!slash)
56                         slash = match; /* toplevel */
57                 else
58                         slash++;
59                 if (namelen <= slash - match) {
60                         /* Looking at "Documentation/" and
61                          * the pattern says "Documentation/howto/", or
62                          * "Documentation/diff*.txt".
63                          */
64                         if (!memcmp(match, name, namelen))
65                                 return 1;
66                 }
67                 else {
68                         /* Looking at "Documentation/howto/" and
69                          * the pattern says "Documentation/h*".
70                          */
71                         if (!memcmp(match, name, slash - match))
72                                 return 1;
73                 }
74         }
75         return 0;
76 }
77
78 struct grep_pat {
79         struct grep_pat *next;
80         const char *pattern;
81         regex_t regexp;
82 };
83
84 struct grep_opt {
85         struct grep_pat *pattern_list;
86         struct grep_pat **pattern_tail;
87         regex_t regexp;
88         unsigned linenum:1;
89         unsigned invert:1;
90         unsigned name_only:1;
91         unsigned count:1;
92         unsigned word_regexp:1;
93         int regflags;
94         unsigned pre_context;
95         unsigned post_context;
96 };
97
98 static void add_pattern(struct grep_opt *opt, const char *pat)
99 {
100         struct grep_pat *p = xcalloc(1, sizeof(*p));
101         p->pattern = pat;
102         *opt->pattern_tail = p;
103         opt->pattern_tail = &p->next;
104         p->next = NULL;
105 }
106
107 static void compile_patterns(struct grep_opt *opt)
108 {
109         struct grep_pat *p;
110         for (p = opt->pattern_list; p; p = p->next) {
111                 int err = regcomp(&p->regexp, p->pattern, opt->regflags);
112                 if (err) {
113                         char errbuf[1024];
114                         regerror(err, &p->regexp, errbuf, 1024);
115                         regfree(&p->regexp);
116                         die("'%s': %s", p->pattern, errbuf);
117                 }
118         }
119 }
120
121 static char *end_of_line(char *cp, unsigned long *left)
122 {
123         unsigned long l = *left;
124         while (l && *cp != '\n') {
125                 l--;
126                 cp++;
127         }
128         *left = l;
129         return cp;
130 }
131
132 static int word_char(char ch)
133 {
134         return isalnum(ch) || ch == '_';
135 }
136
137 static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
138                       const char *name, unsigned lno, char sign)
139 {
140         printf("%s%c", name, sign);
141         if (opt->linenum)
142                 printf("%d%c", lno, sign);
143         printf("%.*s\n", (int)(eol-bol), bol);
144 }
145
146 static int grep_buffer(struct grep_opt *opt, const char *name,
147                        char *buf, unsigned long size)
148 {
149         char *bol = buf;
150         unsigned long left = size;
151         unsigned lno = 1;
152         struct pre_context_line {
153                 char *bol;
154                 char *eol;
155         } *prev = NULL, *pcl;
156         unsigned last_hit = 0;
157         unsigned last_shown = 0;
158         const char *hunk_mark = "";
159         unsigned count = 0;
160
161         if (opt->pre_context)
162                 prev = xcalloc(opt->pre_context, sizeof(*prev));
163         if (opt->pre_context || opt->post_context)
164                 hunk_mark = "--\n";
165
166         while (left) {
167                 regmatch_t pmatch[10];
168                 char *eol, ch;
169                 int hit = 0;
170                 struct grep_pat *p;
171
172                 eol = end_of_line(bol, &left);
173                 ch = *eol;
174                 *eol = 0;
175
176                 for (p = opt->pattern_list; p; p = p->next) {
177                         regex_t *exp = &p->regexp;
178                         hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
179                                        pmatch, 0);
180
181                         if (hit && opt->word_regexp) {
182                                 /* Match beginning must be either
183                                  * beginning of the line, or at word
184                                  * boundary (i.e. the last char must
185                                  * not be alnum or underscore).
186                                  */
187                                 if ((pmatch[0].rm_so < 0) ||
188                                     (eol - bol) <= pmatch[0].rm_so ||
189                                     (pmatch[0].rm_eo < 0) ||
190                                     (eol - bol) < pmatch[0].rm_eo)
191                                         die("regexp returned nonsense");
192                                 if (pmatch[0].rm_so != 0 &&
193                                     word_char(bol[pmatch[0].rm_so-1]))
194                                         continue; /* not a word boundary */
195                                 if ((eol-bol) < pmatch[0].rm_eo &&
196                                     word_char(bol[pmatch[0].rm_eo]))
197                                         continue; /* not a word boundary */
198                         }
199                         if (hit)
200                                 break;
201                 }
202                 /* "grep -v -e foo -e bla" should list lines
203                  * that do not have either, so inversion should
204                  * be done outside.
205                  */
206                 if (opt->invert)
207                         hit = !hit;
208                 if (hit) {
209                         count++;
210                         if (opt->name_only) {
211                                 printf("%s\n", name);
212                                 return 1;
213                         }
214                         /* Hit at this line.  If we haven't shown the
215                          * pre-context lines, we would need to show them.
216                          * When asked to do "count", this still show
217                          * the context which is nonsense, but the user
218                          * deserves to get that ;-).
219                          */
220                         if (opt->pre_context) {
221                                 unsigned from;
222                                 if (opt->pre_context < lno)
223                                         from = lno - opt->pre_context;
224                                 else
225                                         from = 1;
226                                 if (from <= last_shown)
227                                         from = last_shown + 1;
228                                 if (last_shown && from != last_shown + 1)
229                                         printf(hunk_mark);
230                                 while (from < lno) {
231                                         pcl = &prev[lno-from-1];
232                                         show_line(opt, pcl->bol, pcl->eol,
233                                                   name, from, '-');
234                                         from++;
235                                 }
236                                 last_shown = lno-1;
237                         }
238                         if (last_shown && lno != last_shown + 1)
239                                 printf(hunk_mark);
240                         if (!opt->count)
241                                 show_line(opt, bol, eol, name, lno, ':');
242                         last_shown = last_hit = lno;
243                 }
244                 else if (last_hit &&
245                          lno <= last_hit + opt->post_context) {
246                         /* If the last hit is within the post context,
247                          * we need to show this line.
248                          */
249                         if (last_shown && lno != last_shown + 1)
250                                 printf(hunk_mark);
251                         show_line(opt, bol, eol, name, lno, '-');
252                         last_shown = lno;
253                 }
254                 if (opt->pre_context) {
255                         memmove(prev+1, prev,
256                                 (opt->pre_context-1) * sizeof(*prev));
257                         prev->bol = bol;
258                         prev->eol = eol;
259                 }
260                 *eol = ch;
261                 bol = eol + 1;
262                 left--;
263                 lno++;
264         }
265         /* NEEDSWORK:
266          * The real "grep -c foo *.c" gives many "bar.c:0" lines,
267          * which feels mostly useless but sometimes useful.  Maybe
268          * make it another option?  For now suppress them.
269          */
270         if (opt->count && count)
271                 printf("%s:%u\n", name, count);
272         return !!last_hit;
273 }
274
275 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name)
276 {
277         unsigned long size;
278         char *data;
279         char type[20];
280         int hit;
281         data = read_sha1_file(sha1, type, &size);
282         if (!data) {
283                 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
284                 return 0;
285         }
286         hit = grep_buffer(opt, name, data, size);
287         free(data);
288         return hit;
289 }
290
291 static int grep_file(struct grep_opt *opt, const char *filename)
292 {
293         struct stat st;
294         int i;
295         char *data;
296         if (lstat(filename, &st) < 0) {
297         err_ret:
298                 if (errno != ENOENT)
299                         error("'%s': %s", filename, strerror(errno));
300                 return 0;
301         }
302         if (!st.st_size)
303                 return 0; /* empty file -- no grep hit */
304         if (!S_ISREG(st.st_mode))
305                 return 0;
306         i = open(filename, O_RDONLY);
307         if (i < 0)
308                 goto err_ret;
309         data = xmalloc(st.st_size + 1);
310         if (st.st_size != xread(i, data, st.st_size)) {
311                 error("'%s': short read %s", filename, strerror(errno));
312                 close(i);
313                 free(data);
314                 return 0;
315         }
316         close(i);
317         i = grep_buffer(opt, filename, data, st.st_size);
318         free(data);
319         return i;
320 }
321
322 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
323 {
324         int hit = 0;
325         int nr;
326         read_cache();
327
328         for (nr = 0; nr < active_nr; nr++) {
329                 struct cache_entry *ce = active_cache[nr];
330                 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
331                         continue;
332                 if (!pathspec_matches(paths, ce->name))
333                         continue;
334                 if (cached)
335                         hit |= grep_sha1(opt, ce->sha1, ce->name);
336                 else
337                         hit |= grep_file(opt, ce->name);
338         }
339         return hit;
340 }
341
342 static int grep_tree(struct grep_opt *opt, const char **paths,
343                      struct tree_desc *tree,
344                      const char *tree_name, const char *base)
345 {
346         unsigned mode;
347         int len;
348         int hit = 0;
349         const char *path;
350         const unsigned char *sha1;
351         char *down;
352         char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
353
354         if (tree_name[0]) {
355                 int offset = sprintf(path_buf, "%s:", tree_name);
356                 down = path_buf + offset;
357                 strcat(down, base);
358         }
359         else {
360                 down = path_buf;
361                 strcpy(down, base);
362         }
363         len = strlen(path_buf);
364
365         while (tree->size) {
366                 int pathlen;
367                 sha1 = tree_entry_extract(tree, &path, &mode);
368                 pathlen = strlen(path);
369                 strcpy(path_buf + len, path);
370
371                 if (S_ISDIR(mode))
372                         /* Match "abc/" against pathspec to
373                          * decide if we want to descend into "abc"
374                          * directory.
375                          */
376                         strcpy(path_buf + len + pathlen, "/");
377
378                 if (!pathspec_matches(paths, down))
379                         ;
380                 else if (S_ISREG(mode))
381                         hit |= grep_sha1(opt, sha1, path_buf);
382                 else if (S_ISDIR(mode)) {
383                         char type[20];
384                         struct tree_desc sub;
385                         void *data;
386                         data = read_sha1_file(sha1, type, &sub.size);
387                         if (!data)
388                                 die("unable to read tree (%s)",
389                                     sha1_to_hex(sha1));
390                         sub.buf = data;
391                         hit |= grep_tree(opt, paths, &sub, tree_name, down);
392                         free(data);
393                 }
394                 update_tree_entry(tree);
395         }
396         return hit;
397 }
398
399 static int grep_object(struct grep_opt *opt, const char **paths,
400                        struct object *obj, const char *name)
401 {
402         if (!strcmp(obj->type, blob_type))
403                 return grep_sha1(opt, obj->sha1, name);
404         if (!strcmp(obj->type, commit_type) ||
405             !strcmp(obj->type, tree_type)) {
406                 struct tree_desc tree;
407                 void *data;
408                 int hit;
409                 data = read_object_with_reference(obj->sha1, tree_type,
410                                                   &tree.size, NULL);
411                 if (!data)
412                         die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
413                 tree.buf = data;
414                 hit = grep_tree(opt, paths, &tree, name, "");
415                 free(data);
416                 return hit;
417         }
418         die("unable to grep from object of type %s", obj->type);
419 }
420
421 static const char builtin_grep_usage[] =
422 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
423
424 int cmd_grep(int argc, const char **argv, char **envp)
425 {
426         int hit = 0;
427         int no_more_flags = 0;
428         int seen_noncommit = 0;
429         int cached = 0;
430         struct grep_opt opt;
431         struct object_list *list, **tail, *object_list = NULL;
432         const char *prefix = setup_git_directory();
433         const char **paths = NULL;
434
435         memset(&opt, 0, sizeof(opt));
436         opt.pattern_tail = &opt.pattern_list;
437         opt.regflags = REG_NEWLINE;
438
439         /*
440          * No point using rev_info, really.
441          */
442         while (1 < argc) {
443                 const char *arg = argv[1];
444                 argc--; argv++;
445                 if (!strcmp("--cached", arg)) {
446                         cached = 1;
447                         continue;
448                 }
449                 if (!strcmp("-i", arg) ||
450                     !strcmp("--ignore-case", arg)) {
451                         opt.regflags |= REG_ICASE;
452                         continue;
453                 }
454                 if (!strcmp("-v", arg) ||
455                     !strcmp("--invert-match", arg)) {
456                         opt.invert = 1;
457                         continue;
458                 }
459                 if (!strcmp("-E", arg) ||
460                     !strcmp("--extended-regexp", arg)) {
461                         opt.regflags |= REG_EXTENDED;
462                         continue;
463                 }
464                 if (!strcmp("-G", arg) ||
465                     !strcmp("--basic-regexp", arg)) {
466                         opt.regflags &= ~REG_EXTENDED;
467                         continue;
468                 }
469                 if (!strcmp("-n", arg)) {
470                         opt.linenum = 1;
471                         continue;
472                 }
473                 if (!strcmp("-H", arg)) {
474                         /* We always show the pathname, so this
475                          * is a noop.
476                          */
477                         continue;
478                 }
479                 if (!strcmp("-l", arg) ||
480                     !strcmp("--files-with-matches", arg)) {
481                         opt.name_only = 1;
482                         continue;
483                 }
484                 if (!strcmp("-c", arg) ||
485                     !strcmp("--count", arg)) {
486                         opt.count = 1;
487                         continue;
488                 }
489                 if (!strcmp("-w", arg) ||
490                     !strcmp("--word-regexp", arg)) {
491                         opt.word_regexp = 1;
492                         continue;
493                 }
494                 if (!strncmp("-A", arg, 2) ||
495                     !strncmp("-B", arg, 2) ||
496                     !strncmp("-C", arg, 2) ||
497                     (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
498                         unsigned num;
499                         const char *scan;
500                         switch (arg[1]) {
501                         case 'A': case 'B': case 'C':
502                                 if (!arg[2]) {
503                                         if (argc <= 1)
504                                                 usage(builtin_grep_usage);
505                                         scan = *++argv;
506                                         argc--;
507                                 }
508                                 else
509                                         scan = arg + 2;
510                                 break;
511                         default:
512                                 scan = arg + 1;
513                                 break;
514                         }
515                         if (sscanf(scan, "%u", &num) != 1)
516                                 usage(builtin_grep_usage);
517                         switch (arg[1]) {
518                         case 'A':
519                                 opt.post_context = num;
520                                 break;
521                         default:
522                         case 'C':
523                                 opt.post_context = num;
524                         case 'B':
525                                 opt.pre_context = num;
526                                 break;
527                         }
528                         continue;
529                 }
530                 if (!strcmp("-e", arg)) {
531                         if (1 < argc) {
532                                 add_pattern(&opt, argv[1]);
533                                 argv++;
534                                 argc--;
535                                 continue;
536                         }
537                         usage(builtin_grep_usage);
538                 }
539                 if (!strcmp("--", arg)) {
540                         no_more_flags = 1;
541                         continue;
542                 }
543                 /* Either unrecognized option or a single pattern */
544                 if (!no_more_flags && *arg == '-')
545                         usage(builtin_grep_usage);
546                 if (!opt.pattern_list) {
547                         add_pattern(&opt, arg);
548                         break;
549                 }
550                 else {
551                         /* We are looking at the first path or rev;
552                          * it is found at argv[0] after leaving the
553                          * loop.
554                          */
555                         argc++; argv--;
556                         break;
557                 }
558         }
559         if (!opt.pattern_list)
560                 die("no pattern given.");
561         compile_patterns(&opt);
562         tail = &object_list;
563         while (1 < argc) {
564                 struct object *object;
565                 struct object_list *elem;
566                 const char *arg = argv[1];
567                 unsigned char sha1[20];
568                 if (get_sha1(arg, sha1) < 0)
569                         break;
570                 object = parse_object(sha1);
571                 if (!object)
572                         die("bad object %s", arg);
573                 elem = object_list_insert(object, tail);
574                 elem->name = arg;
575                 tail = &elem->next;
576                 argc--; argv++;
577         }
578         if (1 < argc)
579                 paths = get_pathspec(prefix, argv + 1);
580         else if (prefix) {
581                 paths = xcalloc(2, sizeof(const char *));
582                 paths[0] = prefix;
583                 paths[1] = NULL;
584         }
585
586         if (!object_list)
587                 return !grep_cache(&opt, paths, cached);
588         /*
589          * Do not walk "grep -e foo master next pu -- Documentation/"
590          * but do walk "grep -e foo master..next -- Documentation/".
591          * Ranged request mixed with a blob or tree object, like
592          * "grep -e foo v1.0.0:Documentation/ master..next"
593          * so detect that and complain.
594          */
595         for (list = object_list; list; list = list->next) {
596                 struct object *real_obj;
597                 real_obj = deref_tag(list->item, NULL, 0);
598                 if (strcmp(real_obj->type, commit_type))
599                         seen_noncommit = 1;
600         }
601         if (cached)
602                 die("both --cached and revisions given.");
603
604         for (list = object_list; list; list = list->next) {
605                 struct object *real_obj;
606                 real_obj = deref_tag(list->item, NULL, 0);
607                 if (grep_object(&opt, paths, real_obj, list->name))
608                         hit = 1;
609         }
610         return !hit;
611 }