4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.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)
23 if (!paths || !*paths)
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] == '/'))
36 if (!fnmatch(match, name, 0))
38 if (name[namelen-1] != '/')
41 /* We are being asked if the directory ("name") is worth
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++) {
50 if (ch == '*' || ch == '[' || ch == '?') {
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))
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))
84 struct grep_pat *next;
90 struct grep_pat *pattern_list;
91 struct grep_pat **pattern_tail;
97 unsigned word_regexp:1;
98 #define GREP_BINARY_DEFAULT 0
99 #define GREP_BINARY_NOMATCH 1
100 #define GREP_BINARY_TEXT 2
103 unsigned pre_context;
104 unsigned post_context;
107 static void add_pattern(struct grep_opt *opt, const char *pat)
109 struct grep_pat *p = xcalloc(1, sizeof(*p));
111 *opt->pattern_tail = p;
112 opt->pattern_tail = &p->next;
116 static void compile_patterns(struct grep_opt *opt)
119 for (p = opt->pattern_list; p; p = p->next) {
120 int err = regcomp(&p->regexp, p->pattern, opt->regflags);
123 regerror(err, &p->regexp, errbuf, 1024);
125 die("'%s': %s", p->pattern, errbuf);
130 static char *end_of_line(char *cp, unsigned long *left)
132 unsigned long l = *left;
133 while (l && *cp != '\n') {
141 static int word_char(char ch)
143 return isalnum(ch) || ch == '_';
146 static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
147 const char *name, unsigned lno, char sign)
149 printf("%s%c", name, sign);
151 printf("%d%c", lno, sign);
152 printf("%.*s\n", (int)(eol-bol), bol);
156 * NEEDSWORK: share code with diff.c
158 #define FIRST_FEW_BYTES 8000
159 static int buffer_is_binary(const char *ptr, unsigned long size)
161 if (FIRST_FEW_BYTES < size)
162 size = FIRST_FEW_BYTES;
163 if (memchr(ptr, 0, size))
168 static int grep_buffer(struct grep_opt *opt, const char *name,
169 char *buf, unsigned long size)
172 unsigned long left = size;
174 struct pre_context_line {
177 } *prev = NULL, *pcl;
178 unsigned last_hit = 0;
179 unsigned last_shown = 0;
180 int binary_match_only = 0;
181 const char *hunk_mark = "";
184 if (buffer_is_binary(buf, size)) {
185 switch (opt->binary) {
186 case GREP_BINARY_DEFAULT:
187 binary_match_only = 1;
189 case GREP_BINARY_NOMATCH:
190 return 0; /* Assume unmatch */
197 if (opt->pre_context)
198 prev = xcalloc(opt->pre_context, sizeof(*prev));
199 if (opt->pre_context || opt->post_context)
203 regmatch_t pmatch[10];
208 eol = end_of_line(bol, &left);
212 for (p = opt->pattern_list; p; p = p->next) {
213 regex_t *exp = &p->regexp;
214 hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
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).
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 */
238 /* "grep -v -e foo -e bla" should list lines
239 * that do not have either, so inversion should
246 if (binary_match_only) {
247 printf("Binary file %s matches\n", name);
250 if (opt->name_only) {
251 printf("%s\n", name);
254 /* Hit at this line. If we haven't shown the
255 * pre-context lines, we would need to show them.
256 * When asked to do "count", this still show
257 * the context which is nonsense, but the user
258 * deserves to get that ;-).
260 if (opt->pre_context) {
262 if (opt->pre_context < lno)
263 from = lno - opt->pre_context;
266 if (from <= last_shown)
267 from = last_shown + 1;
268 if (last_shown && from != last_shown + 1)
271 pcl = &prev[lno-from-1];
272 show_line(opt, pcl->bol, pcl->eol,
278 if (last_shown && lno != last_shown + 1)
281 show_line(opt, bol, eol, name, lno, ':');
282 last_shown = last_hit = lno;
285 lno <= last_hit + opt->post_context) {
286 /* If the last hit is within the post context,
287 * we need to show this line.
289 if (last_shown && lno != last_shown + 1)
291 show_line(opt, bol, eol, name, lno, '-');
294 if (opt->pre_context) {
295 memmove(prev+1, prev,
296 (opt->pre_context-1) * sizeof(*prev));
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.
312 if (opt->count && count)
313 printf("%s:%u\n", name, count);
317 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name)
323 data = read_sha1_file(sha1, type, &size);
325 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
328 hit = grep_buffer(opt, name, data, size);
333 static int grep_file(struct grep_opt *opt, const char *filename)
338 if (lstat(filename, &st) < 0) {
341 error("'%s': %s", filename, strerror(errno));
345 return 0; /* empty file -- no grep hit */
346 if (!S_ISREG(st.st_mode))
348 i = open(filename, O_RDONLY);
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));
359 i = grep_buffer(opt, filename, data, st.st_size);
364 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
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)))
374 if (!pathspec_matches(paths, ce->name))
377 hit |= grep_sha1(opt, ce->sha1, ce->name);
379 hit |= grep_file(opt, ce->name);
384 static int grep_tree(struct grep_opt *opt, const char **paths,
385 struct tree_desc *tree,
386 const char *tree_name, const char *base)
392 const unsigned char *sha1;
394 char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
397 int offset = sprintf(path_buf, "%s:", tree_name);
398 down = path_buf + offset;
405 len = strlen(path_buf);
409 sha1 = tree_entry_extract(tree, &path, &mode);
410 pathlen = strlen(path);
411 strcpy(path_buf + len, path);
414 /* Match "abc/" against pathspec to
415 * decide if we want to descend into "abc"
418 strcpy(path_buf + len + pathlen, "/");
420 if (!pathspec_matches(paths, down))
422 else if (S_ISREG(mode))
423 hit |= grep_sha1(opt, sha1, path_buf);
424 else if (S_ISDIR(mode)) {
426 struct tree_desc sub;
428 data = read_sha1_file(sha1, type, &sub.size);
430 die("unable to read tree (%s)",
433 hit |= grep_tree(opt, paths, &sub, tree_name, down);
436 update_tree_entry(tree);
441 static int grep_object(struct grep_opt *opt, const char **paths,
442 struct object *obj, const char *name)
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;
451 data = read_object_with_reference(obj->sha1, tree_type,
454 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
456 hit = grep_tree(opt, paths, &tree, name, "");
460 die("unable to grep from object of type %s", obj->type);
463 static const char builtin_grep_usage[] =
464 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
466 int cmd_grep(int argc, const char **argv, char **envp)
469 int no_more_flags = 0;
470 int seen_noncommit = 0;
473 struct object_list *list, **tail, *object_list = NULL;
474 const char *prefix = setup_git_directory();
475 const char **paths = NULL;
477 memset(&opt, 0, sizeof(opt));
478 opt.pattern_tail = &opt.pattern_list;
479 opt.regflags = REG_NEWLINE;
482 * No point using rev_info, really.
485 const char *arg = argv[1];
487 if (!strcmp("--cached", arg)) {
491 if (!strcmp("-a", arg) ||
492 !strcmp("--text", arg)) {
493 opt.binary = GREP_BINARY_TEXT;
496 if (!strcmp("-i", arg) ||
497 !strcmp("--ignore-case", arg)) {
498 opt.regflags |= REG_ICASE;
501 if (!strcmp("-I", arg)) {
502 opt.binary = GREP_BINARY_NOMATCH;
505 if (!strcmp("-v", arg) ||
506 !strcmp("--invert-match", arg)) {
510 if (!strcmp("-E", arg) ||
511 !strcmp("--extended-regexp", arg)) {
512 opt.regflags |= REG_EXTENDED;
515 if (!strcmp("-G", arg) ||
516 !strcmp("--basic-regexp", arg)) {
517 opt.regflags &= ~REG_EXTENDED;
520 if (!strcmp("-n", arg)) {
524 if (!strcmp("-H", arg)) {
525 /* We always show the pathname, so this
530 if (!strcmp("-l", arg) ||
531 !strcmp("--files-with-matches", arg)) {
535 if (!strcmp("-c", arg) ||
536 !strcmp("--count", arg)) {
540 if (!strcmp("-w", arg) ||
541 !strcmp("--word-regexp", arg)) {
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')) {
552 case 'A': case 'B': case 'C':
555 usage(builtin_grep_usage);
566 if (sscanf(scan, "%u", &num) != 1)
567 usage(builtin_grep_usage);
570 opt.post_context = num;
574 opt.post_context = num;
576 opt.pre_context = num;
581 if (!strcmp("-e", arg)) {
583 add_pattern(&opt, argv[1]);
588 usage(builtin_grep_usage);
590 if (!strcmp("--", arg)) {
594 /* Either unrecognized option or a single pattern */
595 if (!no_more_flags && *arg == '-')
596 usage(builtin_grep_usage);
597 if (!opt.pattern_list) {
598 add_pattern(&opt, arg);
602 /* We are looking at the first path or rev;
603 * it is found at argv[0] after leaving the
610 if (!opt.pattern_list)
611 die("no pattern given.");
612 compile_patterns(&opt);
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)
621 object = parse_object(sha1);
623 die("bad object %s", arg);
624 elem = object_list_insert(object, tail);
630 paths = get_pathspec(prefix, argv + 1);
632 paths = xcalloc(2, sizeof(const char *));
638 return !grep_cache(&opt, paths, cached);
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.
646 for (list = object_list; list; list = list->next) {
647 struct object *real_obj;
648 real_obj = deref_tag(list->item, NULL, 0);
649 if (strcmp(real_obj->type, commit_type))
653 die("both --cached and revisions given.");
655 for (list = object_list; list; list = list->next) {
656 struct object *real_obj;
657 real_obj = deref_tag(list->item, NULL, 0);
658 if (grep_object(&opt, paths, real_obj, list->name))