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