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;
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));
107 *opt->pattern_tail = p;
108 opt->pattern_tail = &p->next;
112 static void compile_patterns(struct grep_opt *opt)
115 for (p = opt->pattern_list; p; p = p->next) {
116 int err = regcomp(&p->regexp, p->pattern, opt->regflags);
119 regerror(err, &p->regexp, errbuf, 1024);
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') {
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);
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)
155 unsigned long left = size;
157 struct pre_context_line {
160 } *prev = NULL, *pcl;
161 unsigned last_hit = 0;
162 unsigned last_shown = 0;
163 const char *hunk_mark = "";
166 if (opt->pre_context)
167 prev = xcalloc(opt->pre_context, sizeof(*prev));
168 if (opt->pre_context || opt->post_context)
172 regmatch_t pmatch[10];
177 eol = end_of_line(bol, &left);
181 for (p = opt->pattern_list; p; p = p->next) {
182 regex_t *exp = &p->regexp;
183 hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
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 */
207 /* "grep -v -e foo -e bla" should list lines
208 * that do not have either, so inversion should
215 if (opt->name_only) {
216 printf("%s\n", name);
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) {
227 if (opt->pre_context < lno)
228 from = lno - opt->pre_context;
231 if (from <= last_shown)
232 from = last_shown + 1;
233 if (last_shown && from != last_shown + 1)
236 pcl = &prev[lno-from-1];
237 show_line(opt, pcl->bol, pcl->eol,
243 if (last_shown && lno != last_shown + 1)
246 show_line(opt, bol, eol, name, lno, ':');
247 last_shown = last_hit = lno;
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)
256 show_line(opt, bol, eol, name, lno, '-');
259 if (opt->pre_context) {
260 memmove(prev+1, prev,
261 (opt->pre_context-1) * sizeof(*prev));
273 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
274 * which feels mostly useless but sometimes useful. Maybe
275 * make it another option? For now suppress them.
277 if (opt->count && count)
278 printf("%s:%u\n", name, count);
282 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name)
288 data = read_sha1_file(sha1, type, &size);
290 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
293 hit = grep_buffer(opt, name, data, size);
298 static int grep_file(struct grep_opt *opt, const char *filename)
303 if (lstat(filename, &st) < 0) {
306 error("'%s': %s", filename, strerror(errno));
310 return 0; /* empty file -- no grep hit */
311 if (!S_ISREG(st.st_mode))
313 i = open(filename, O_RDONLY);
316 data = xmalloc(st.st_size + 1);
317 if (st.st_size != xread(i, data, st.st_size)) {
318 error("'%s': short read %s", filename, strerror(errno));
324 i = grep_buffer(opt, filename, data, st.st_size);
329 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
335 for (nr = 0; nr < active_nr; nr++) {
336 struct cache_entry *ce = active_cache[nr];
337 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
339 if (!pathspec_matches(paths, ce->name))
342 hit |= grep_sha1(opt, ce->sha1, ce->name);
344 hit |= grep_file(opt, ce->name);
349 static int grep_tree(struct grep_opt *opt, const char **paths,
350 struct tree_desc *tree,
351 const char *tree_name, const char *base)
357 const unsigned char *sha1;
359 char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
362 int offset = sprintf(path_buf, "%s:", tree_name);
363 down = path_buf + offset;
370 len = strlen(path_buf);
374 sha1 = tree_entry_extract(tree, &path, &mode);
375 pathlen = strlen(path);
376 strcpy(path_buf + len, path);
379 /* Match "abc/" against pathspec to
380 * decide if we want to descend into "abc"
383 strcpy(path_buf + len + pathlen, "/");
385 if (!pathspec_matches(paths, down))
387 else if (S_ISREG(mode))
388 hit |= grep_sha1(opt, sha1, path_buf);
389 else if (S_ISDIR(mode)) {
391 struct tree_desc sub;
393 data = read_sha1_file(sha1, type, &sub.size);
395 die("unable to read tree (%s)",
398 hit |= grep_tree(opt, paths, &sub, tree_name, down);
401 update_tree_entry(tree);
406 static int grep_object(struct grep_opt *opt, const char **paths,
407 struct object *obj, const char *name)
409 if (!strcmp(obj->type, blob_type))
410 return grep_sha1(opt, obj->sha1, name);
411 if (!strcmp(obj->type, commit_type) ||
412 !strcmp(obj->type, tree_type)) {
413 struct tree_desc tree;
416 data = read_object_with_reference(obj->sha1, tree_type,
419 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
421 hit = grep_tree(opt, paths, &tree, name, "");
425 die("unable to grep from object of type %s", obj->type);
428 static const char builtin_grep_usage[] =
429 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
431 int cmd_grep(int argc, const char **argv, char **envp)
434 int no_more_flags = 0;
435 int seen_noncommit = 0;
438 struct object_list *list, **tail, *object_list = NULL;
439 const char *prefix = setup_git_directory();
440 const char **paths = NULL;
442 memset(&opt, 0, sizeof(opt));
443 opt.pattern_tail = &opt.pattern_list;
444 opt.regflags = REG_NEWLINE;
447 * No point using rev_info, really.
450 const char *arg = argv[1];
452 if (!strcmp("--cached", arg)) {
456 if (!strcmp("-i", arg) ||
457 !strcmp("--ignore-case", arg)) {
458 opt.regflags |= REG_ICASE;
461 if (!strcmp("-v", arg) ||
462 !strcmp("--invert-match", arg)) {
466 if (!strcmp("-E", arg) ||
467 !strcmp("--extended-regexp", arg)) {
468 opt.regflags |= REG_EXTENDED;
471 if (!strcmp("-G", arg) ||
472 !strcmp("--basic-regexp", arg)) {
473 opt.regflags &= ~REG_EXTENDED;
476 if (!strcmp("-n", arg)) {
480 if (!strcmp("-H", arg)) {
481 /* We always show the pathname, so this
486 if (!strcmp("-l", arg) ||
487 !strcmp("--files-with-matches", arg)) {
491 if (!strcmp("-c", arg) ||
492 !strcmp("--count", arg)) {
496 if (!strcmp("-w", arg) ||
497 !strcmp("--word-regexp", arg)) {
501 if (!strncmp("-A", arg, 2) ||
502 !strncmp("-B", arg, 2) ||
503 !strncmp("-C", arg, 2) ||
504 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
508 case 'A': case 'B': case 'C':
511 usage(builtin_grep_usage);
522 if (sscanf(scan, "%u", &num) != 1)
523 usage(builtin_grep_usage);
526 opt.post_context = num;
530 opt.post_context = num;
532 opt.pre_context = num;
537 if (!strcmp("-e", arg)) {
539 add_pattern(&opt, argv[1]);
544 usage(builtin_grep_usage);
546 if (!strcmp("--", arg)) {
550 /* Either unrecognized option or a single pattern */
551 if (!no_more_flags && *arg == '-')
552 usage(builtin_grep_usage);
553 if (!opt.pattern_list) {
554 add_pattern(&opt, arg);
558 /* We are looking at the first path or rev;
559 * it is found at argv[0] after leaving the
566 if (!opt.pattern_list)
567 die("no pattern given.");
568 compile_patterns(&opt);
571 struct object *object;
572 struct object_list *elem;
573 const char *arg = argv[1];
574 unsigned char sha1[20];
575 if (get_sha1(arg, sha1) < 0)
577 object = parse_object(sha1);
579 die("bad object %s", arg);
580 elem = object_list_insert(object, tail);
586 paths = get_pathspec(prefix, argv + 1);
588 paths = xcalloc(2, sizeof(const char *));
594 return !grep_cache(&opt, paths, cached);
596 * Do not walk "grep -e foo master next pu -- Documentation/"
597 * but do walk "grep -e foo master..next -- Documentation/".
598 * Ranged request mixed with a blob or tree object, like
599 * "grep -e foo v1.0.0:Documentation/ master..next"
600 * so detect that and complain.
602 for (list = object_list; list; list = list->next) {
603 struct object *real_obj;
604 real_obj = deref_tag(list->item, NULL, 0);
605 if (strcmp(real_obj->type, commit_type))
609 die("both --cached and revisions given.");
611 for (list = object_list; list; list = list->next) {
612 struct object *real_obj;
613 real_obj = deref_tag(list->item, NULL, 0);
614 if (grep_object(&opt, paths, real_obj, list->name))