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