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 *slash, *cp;
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 name directory 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, slash = NULL; cp - match < matchlen; cp++) {
52 if (ch == '*' || ch == '[')
56 slash = match; /* toplevel */
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))
68 /* Looking at "Documentation/howto/" and
69 * the pattern says "Documentation/h*".
71 if (!memcmp(match, name, slash - match))
79 struct grep_pat *next;
85 struct grep_pat *pattern_list;
86 struct grep_pat **pattern_tail;
92 unsigned word_regexp:1;
95 unsigned post_context;
98 static void add_pattern(struct grep_opt *opt, const char *pat)
100 struct grep_pat *p = xcalloc(1, sizeof(*p));
102 *opt->pattern_tail = p;
103 opt->pattern_tail = &p->next;
107 static void compile_patterns(struct grep_opt *opt)
110 for (p = opt->pattern_list; p; p = p->next) {
111 int err = regcomp(&p->regexp, p->pattern, opt->regflags);
114 regerror(err, &p->regexp, errbuf, 1024);
116 die("'%s': %s", p->pattern, errbuf);
121 static char *end_of_line(char *cp, unsigned long *left)
123 unsigned long l = *left;
124 while (l && *cp != '\n') {
132 static int word_char(char ch)
134 return isalnum(ch) || ch == '_';
137 static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
138 const char *name, unsigned lno, char sign)
140 printf("%s%c", name, sign);
142 printf("%d%c", lno, sign);
143 printf("%.*s\n", (int)(eol-bol), bol);
146 static int grep_buffer(struct grep_opt *opt, const char *name,
147 char *buf, unsigned long size)
150 unsigned long left = size;
152 struct pre_context_line {
155 } *prev = NULL, *pcl;
156 unsigned last_hit = 0;
157 unsigned last_shown = 0;
158 const char *hunk_mark = "";
161 if (opt->pre_context)
162 prev = xcalloc(opt->pre_context, sizeof(*prev));
163 if (opt->pre_context || opt->post_context)
167 regmatch_t pmatch[10];
172 eol = end_of_line(bol, &left);
176 for (p = opt->pattern_list; p; p = p->next) {
177 regex_t *exp = &p->regexp;
178 hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
181 if (hit && opt->word_regexp) {
182 /* Match beginning must be either
183 * beginning of the line, or at word
184 * boundary (i.e. the last char must
185 * not be alnum or underscore).
187 if ((pmatch[0].rm_so < 0) ||
188 (eol - bol) <= pmatch[0].rm_so ||
189 (pmatch[0].rm_eo < 0) ||
190 (eol - bol) < pmatch[0].rm_eo)
191 die("regexp returned nonsense");
192 if (pmatch[0].rm_so != 0 &&
193 word_char(bol[pmatch[0].rm_so-1]))
194 continue; /* not a word boundary */
195 if ((eol-bol) < pmatch[0].rm_eo &&
196 word_char(bol[pmatch[0].rm_eo]))
197 continue; /* not a word boundary */
202 /* "grep -v -e foo -e bla" should list lines
203 * that do not have either, so inversion should
210 if (opt->name_only) {
211 printf("%s\n", name);
214 /* Hit at this line. If we haven't shown the
215 * pre-context lines, we would need to show them.
216 * When asked to do "count", this still show
217 * the context which is nonsense, but the user
218 * deserves to get that ;-).
220 if (opt->pre_context) {
222 if (opt->pre_context < lno)
223 from = lno - opt->pre_context;
226 if (from <= last_shown)
227 from = last_shown + 1;
228 if (last_shown && from != last_shown + 1)
231 pcl = &prev[lno-from-1];
232 show_line(opt, pcl->bol, pcl->eol,
238 if (last_shown && lno != last_shown + 1)
241 show_line(opt, bol, eol, name, lno, ':');
242 last_shown = last_hit = lno;
245 lno <= last_hit + opt->post_context) {
246 /* If the last hit is within the post context,
247 * we need to show this line.
249 if (last_shown && lno != last_shown + 1)
251 show_line(opt, bol, eol, name, lno, '-');
254 if (opt->pre_context) {
255 memmove(prev+1, prev,
256 (opt->pre_context-1) * sizeof(*prev));
266 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
267 * which feels mostly useless but sometimes useful. Maybe
268 * make it another option? For now suppress them.
270 if (opt->count && count)
271 printf("%s:%u\n", name, count);
275 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name)
281 data = read_sha1_file(sha1, type, &size);
283 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
286 hit = grep_buffer(opt, name, data, size);
291 static int grep_file(struct grep_opt *opt, const char *filename)
296 if (lstat(filename, &st) < 0) {
299 error("'%s': %s", filename, strerror(errno));
303 return 0; /* empty file -- no grep hit */
304 if (!S_ISREG(st.st_mode))
306 i = open(filename, O_RDONLY);
309 data = xmalloc(st.st_size + 1);
310 if (st.st_size != xread(i, data, st.st_size)) {
311 error("'%s': short read %s", filename, strerror(errno));
317 i = grep_buffer(opt, filename, data, st.st_size);
322 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
328 for (nr = 0; nr < active_nr; nr++) {
329 struct cache_entry *ce = active_cache[nr];
330 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
332 if (!pathspec_matches(paths, ce->name))
335 hit |= grep_sha1(opt, ce->sha1, ce->name);
337 hit |= grep_file(opt, ce->name);
342 static int grep_tree(struct grep_opt *opt, const char **paths,
343 struct tree_desc *tree,
344 const char *tree_name, const char *base)
350 const unsigned char *sha1;
352 char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
355 int offset = sprintf(path_buf, "%s:", tree_name);
356 down = path_buf + offset;
363 len = strlen(path_buf);
367 sha1 = tree_entry_extract(tree, &path, &mode);
368 pathlen = strlen(path);
369 strcpy(path_buf + len, path);
372 /* Match "abc/" against pathspec to
373 * decide if we want to descend into "abc"
376 strcpy(path_buf + len + pathlen, "/");
378 if (!pathspec_matches(paths, down))
380 else if (S_ISREG(mode))
381 hit |= grep_sha1(opt, sha1, path_buf);
382 else if (S_ISDIR(mode)) {
384 struct tree_desc sub;
386 data = read_sha1_file(sha1, type, &sub.size);
388 die("unable to read tree (%s)",
391 hit |= grep_tree(opt, paths, &sub, tree_name, down);
394 update_tree_entry(tree);
399 static int grep_object(struct grep_opt *opt, const char **paths,
400 struct object *obj, const char *name)
402 if (!strcmp(obj->type, blob_type))
403 return grep_sha1(opt, obj->sha1, name);
404 if (!strcmp(obj->type, commit_type) ||
405 !strcmp(obj->type, tree_type)) {
406 struct tree_desc tree;
409 data = read_object_with_reference(obj->sha1, tree_type,
412 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
414 hit = grep_tree(opt, paths, &tree, name, "");
418 die("unable to grep from object of type %s", obj->type);
421 static const char builtin_grep_usage[] =
422 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
424 int cmd_grep(int argc, const char **argv, char **envp)
427 int no_more_flags = 0;
428 int seen_noncommit = 0;
431 struct object_list *list, **tail, *object_list = NULL;
432 const char *prefix = setup_git_directory();
433 const char **paths = NULL;
435 memset(&opt, 0, sizeof(opt));
436 opt.pattern_tail = &opt.pattern_list;
437 opt.regflags = REG_NEWLINE;
440 * No point using rev_info, really.
443 const char *arg = argv[1];
445 if (!strcmp("--cached", arg)) {
449 if (!strcmp("-i", arg) ||
450 !strcmp("--ignore-case", arg)) {
451 opt.regflags |= REG_ICASE;
454 if (!strcmp("-v", arg) ||
455 !strcmp("--invert-match", arg)) {
459 if (!strcmp("-E", arg) ||
460 !strcmp("--extended-regexp", arg)) {
461 opt.regflags |= REG_EXTENDED;
464 if (!strcmp("-G", arg) ||
465 !strcmp("--basic-regexp", arg)) {
466 opt.regflags &= ~REG_EXTENDED;
469 if (!strcmp("-n", arg)) {
473 if (!strcmp("-H", arg)) {
474 /* We always show the pathname, so this
479 if (!strcmp("-l", arg) ||
480 !strcmp("--files-with-matches", arg)) {
484 if (!strcmp("-c", arg) ||
485 !strcmp("--count", arg)) {
489 if (!strcmp("-w", arg) ||
490 !strcmp("--word-regexp", arg)) {
494 if (!strncmp("-A", arg, 2) ||
495 !strncmp("-B", arg, 2) ||
496 !strncmp("-C", arg, 2) ||
497 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
501 case 'A': case 'B': case 'C':
504 usage(builtin_grep_usage);
515 if (sscanf(scan, "%u", &num) != 1)
516 usage(builtin_grep_usage);
519 opt.post_context = num;
523 opt.post_context = num;
525 opt.pre_context = num;
530 if (!strcmp("-e", arg)) {
532 add_pattern(&opt, argv[1]);
537 usage(builtin_grep_usage);
539 if (!strcmp("--", arg)) {
543 /* Either unrecognized option or a single pattern */
544 if (!no_more_flags && *arg == '-')
545 usage(builtin_grep_usage);
546 if (!opt.pattern_list) {
547 add_pattern(&opt, arg);
551 /* We are looking at the first path or rev;
552 * it is found at argv[0] after leaving the
559 if (!opt.pattern_list)
560 die("no pattern given.");
561 compile_patterns(&opt);
564 struct object *object;
565 struct object_list *elem;
566 const char *arg = argv[1];
567 unsigned char sha1[20];
568 if (get_sha1(arg, sha1) < 0)
570 object = parse_object(sha1);
572 die("bad object %s", arg);
573 elem = object_list_insert(object, tail);
579 paths = get_pathspec(prefix, argv + 1);
581 paths = xcalloc(2, sizeof(const char *));
587 return !grep_cache(&opt, paths, cached);
589 * Do not walk "grep -e foo master next pu -- Documentation/"
590 * but do walk "grep -e foo master..next -- Documentation/".
591 * Ranged request mixed with a blob or tree object, like
592 * "grep -e foo v1.0.0:Documentation/ master..next"
593 * so detect that and complain.
595 for (list = object_list; list; list = list->next) {
596 struct object *real_obj;
597 real_obj = deref_tag(list->item, NULL, 0);
598 if (strcmp(real_obj->type, commit_type))
602 die("both --cached and revisions given.");
604 for (list = object_list; list; list = list->next) {
605 struct object *real_obj;
606 real_obj = deref_tag(list->item, NULL, 0);
607 if (grep_object(&opt, paths, real_obj, list->name))