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