builtin-grep: allow more than one patterns.
[git.git] / builtin-grep.c
blobb8351200dd61868a60d97a5a491960957b002c61
1 /*
2 * Builtin "git grep"
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>
17 * git grep pathspecs are somewhat different from diff-tree pathspecs;
18 * pathname wildcards are allowed.
20 static int pathspec_matches(const char **paths, const char *name)
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;
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;
41 /* We are being asked if the name directory is worth
42 * descending into.
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.
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;
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".
64 if (!memcmp(match, name, namelen))
65 return 1;
67 else {
68 /* Looking at "Documentation/howto/" and
69 * the pattern says "Documentation/h*".
71 if (!memcmp(match, name, slash - match))
72 return 1;
75 return 0;
78 struct grep_pat {
79 struct grep_pat *next;
80 const char *pattern;
81 regex_t regexp;
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 int regflags;
92 unsigned pre_context;
93 unsigned post_context;
96 static void add_pattern(struct grep_opt *opt, const char *pat)
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;
105 static void compile_patterns(struct grep_opt *opt)
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);
119 static char *end_of_line(char *cp, unsigned long *left)
121 unsigned long l = *left;
122 while (l && *cp != '\n') {
123 l--;
124 cp++;
126 *left = l;
127 return cp;
130 static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
131 const char *name, unsigned lno, char sign)
133 printf("%s%c", name, sign);
134 if (opt->linenum)
135 printf("%d%c", lno, sign);
136 printf("%.*s\n", (int)(eol-bol), bol);
139 static int grep_buffer(struct grep_opt *opt, const char *name,
140 char *buf, unsigned long size)
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 = "";
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";
158 while (left) {
159 regmatch_t pmatch[10];
160 char *eol, ch;
161 int hit = 0;
162 struct grep_pat *p;
164 eol = end_of_line(bol, &left);
165 ch = *eol;
166 *eol = 0;
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;
175 /* "grep -v -e foo -e bla" should list lines
176 * that do not have either, so inversion should
177 * be done outside.
179 if (opt->invert)
180 hit = !hit;
181 if (hit) {
182 if (opt->name_only) {
183 printf("%s\n", name);
184 return 1;
186 /* Hit at this line. If we haven't shown the
187 * pre-context lines, we would need to show them.
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++;
205 last_shown = lno-1;
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;
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.
217 if (last_shown && lno != last_shown + 1)
218 printf(hunk_mark);
219 show_line(opt, bol, eol, name, lno, '-');
220 last_shown = lno;
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;
228 *eol = ch;
229 bol = eol + 1;
230 left--;
231 lno++;
233 return !!last_hit;
236 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name)
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;
247 hit = grep_buffer(opt, name, data, size);
248 free(data);
249 return hit;
252 static int grep_file(struct grep_opt *opt, const char *filename)
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;
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;
277 close(i);
278 i = grep_buffer(opt, filename, data, st.st_size);
279 free(data);
280 return i;
283 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
285 int hit = 0;
286 int nr;
287 read_cache();
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;
293 if (!pathspec_matches(paths, ce->name))
294 continue;
295 if (cached)
296 hit |= grep_sha1(opt, ce->sha1, ce->name);
297 else
298 hit |= grep_file(opt, ce->name);
300 return hit;
303 static int grep_tree(struct grep_opt *opt, const char **paths,
304 struct tree_desc *tree,
305 const char *tree_name, const char *base)
307 unsigned mode;
308 int len;
309 int hit = 0;
310 const char *path;
311 const unsigned char *sha1;
312 char *down;
313 char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
315 if (tree_name[0]) {
316 int offset = sprintf(path_buf, "%s:", tree_name);
317 down = path_buf + offset;
318 strcat(down, base);
320 else {
321 down = path_buf;
322 strcpy(down, base);
324 len = strlen(path_buf);
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);
332 if (S_ISDIR(mode))
333 /* Match "abc/" against pathspec to
334 * decide if we want to descend into "abc"
335 * directory.
337 strcpy(path_buf + len + pathlen, "/");
339 if (!pathspec_matches(paths, down))
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));
351 sub.buf = data;
352 hit |= grep_tree(opt, paths, &sub, tree_name, down);
353 free(data);
355 update_tree_entry(tree);
357 return hit;
360 static int grep_object(struct grep_opt *opt, const char **paths,
361 struct object *obj, const char *name)
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;
375 hit = grep_tree(opt, paths, &tree, name, "");
376 free(data);
377 return hit;
379 die("unable to grep from object of type %s", obj->type);
382 static const char builtin_grep_usage[] =
383 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
385 int cmd_grep(int argc, const char **argv, char **envp)
387 int hit = 0;
388 int no_more_flags = 0;
389 int seen_noncommit = 0;
390 int cached = 0;
391 struct grep_opt opt;
392 struct object_list *list, **tail, *object_list = NULL;
393 const char *prefix = setup_git_directory();
394 const char **paths = NULL;
396 memset(&opt, 0, sizeof(opt));
397 opt.pattern_tail = &opt.pattern_list;
398 opt.regflags = REG_NEWLINE;
401 * No point using rev_info, really.
403 while (1 < argc) {
404 const char *arg = argv[1];
405 argc--; argv++;
406 if (!strcmp("--cached", arg)) {
407 cached = 1;
408 continue;
410 if (!strcmp("-i", arg) ||
411 !strcmp("--ignore-case", arg)) {
412 opt.regflags |= REG_ICASE;
413 continue;
415 if (!strcmp("-v", arg) ||
416 !strcmp("--invert-match", arg)) {
417 opt.invert = 1;
418 continue;
420 if (!strcmp("-E", arg) ||
421 !strcmp("--extended-regexp", arg)) {
422 opt.regflags |= REG_EXTENDED;
423 continue;
425 if (!strcmp("-G", arg) ||
426 !strcmp("--basic-regexp", arg)) {
427 opt.regflags &= ~REG_EXTENDED;
428 continue;
430 if (!strcmp("-n", arg)) {
431 opt.linenum = 1;
432 continue;
434 if (!strcmp("-H", arg)) {
435 /* We always show the pathname, so this
436 * is a noop.
438 continue;
440 if (!strcmp("-l", arg) ||
441 !strcmp("--files-with-matches", arg)) {
442 opt.name_only = 1;
443 continue;
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')) {
449 unsigned num;
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--;
459 else
460 scan = arg + 2;
461 break;
462 default:
463 scan = arg + 1;
464 break;
466 if (sscanf(scan, "%u", &num) != 1)
467 usage(builtin_grep_usage);
468 switch (arg[1]) {
469 case 'A':
470 opt.post_context = num;
471 break;
472 default:
473 case 'C':
474 opt.post_context = num;
475 case 'B':
476 opt.pre_context = num;
477 break;
479 continue;
481 if (!strcmp("-e", arg)) {
482 if (1 < argc) {
483 add_pattern(&opt, argv[1]);
484 argv++;
485 argc--;
486 continue;
488 usage(builtin_grep_usage);
490 if (!strcmp("--", arg)) {
491 no_more_flags = 1;
492 continue;
494 /* Either unrecognized option or a single pattern */
495 if (!no_more_flags && *arg == '-')
496 usage(builtin_grep_usage);
497 if (!opt.pattern_list) {
498 add_pattern(&opt, arg);
499 break;
501 else {
502 /* We are looking at the first path or rev;
503 * it is found at argv[0] after leaving the
504 * loop.
506 argc++; argv--;
507 break;
510 if (!opt.pattern_list)
511 die("no pattern given.");
512 compile_patterns(&opt);
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++;
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;
537 if (!object_list)
538 return !grep_cache(&opt, paths, cached);
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.
546 for (list = object_list; list; list = list->next) {
547 struct object *real_obj;
548 real_obj = deref_tag(list->item, NULL, 0);
549 if (strcmp(real_obj->type, commit_type))
550 seen_noncommit = 1;
552 if (cached)
553 die("both --cached and revisions given.");
555 for (list = object_list; list; list = list->next) {
556 struct object *real_obj;
557 real_obj = deref_tag(list->item, NULL, 0);
558 if (grep_object(&opt, paths, real_obj, list->name))
559 hit = 1;
561 return !hit;