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;
94 unsigned post_context;
97 static void add_pattern(struct grep_opt *opt, const char *pat)
99 struct grep_pat *p = xcalloc(1, sizeof(*p));
101 *opt->pattern_tail = p;
102 opt->pattern_tail = &p->next;
106 static void compile_patterns(struct grep_opt *opt)
109 for (p = opt->pattern_list; p; p = p->next) {
110 int err = regcomp(&p->regexp, p->pattern, opt->regflags);
113 regerror(err, &p->regexp, errbuf, 1024);
115 die("'%s': %s", p->pattern, errbuf);
120 static char *end_of_line(char *cp, unsigned long *left)
122 unsigned long l = *left;
123 while (l && *cp != '\n') {
131 static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
132 const char *name, unsigned lno, char sign)
134 printf("%s%c", name, sign);
136 printf("%d%c", lno, sign);
137 printf("%.*s\n", (int)(eol-bol), bol);
140 static int grep_buffer(struct grep_opt *opt, const char *name,
141 char *buf, unsigned long size)
144 unsigned long left = size;
146 struct pre_context_line {
149 } *prev = NULL, *pcl;
150 unsigned last_hit = 0;
151 unsigned last_shown = 0;
152 const char *hunk_mark = "";
155 if (opt->pre_context)
156 prev = xcalloc(opt->pre_context, sizeof(*prev));
157 if (opt->pre_context || opt->post_context)
161 regmatch_t pmatch[10];
166 eol = end_of_line(bol, &left);
170 for (p = opt->pattern_list; p; p = p->next) {
171 regex_t *exp = &p->regexp;
172 hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
177 /* "grep -v -e foo -e bla" should list lines
178 * that do not have either, so inversion should
185 if (opt->name_only) {
186 printf("%s\n", name);
189 /* Hit at this line. If we haven't shown the
190 * pre-context lines, we would need to show them.
191 * When asked to do "count", this still show
192 * the context which is nonsense, but the user
193 * deserves to get that ;-).
195 if (opt->pre_context) {
197 if (opt->pre_context < lno)
198 from = lno - opt->pre_context;
201 if (from <= last_shown)
202 from = last_shown + 1;
203 if (last_shown && from != last_shown + 1)
206 pcl = &prev[lno-from-1];
207 show_line(opt, pcl->bol, pcl->eol,
213 if (last_shown && lno != last_shown + 1)
216 show_line(opt, bol, eol, name, lno, ':');
217 last_shown = last_hit = lno;
220 lno <= last_hit + opt->post_context) {
221 /* If the last hit is within the post context,
222 * we need to show this line.
224 if (last_shown && lno != last_shown + 1)
226 show_line(opt, bol, eol, name, lno, '-');
229 if (opt->pre_context) {
230 memmove(prev+1, prev,
231 (opt->pre_context-1) * sizeof(*prev));
241 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
242 * which feels mostly useless but sometimes useful. Maybe
243 * make it another option? For now suppress them.
245 if (opt->count && count)
246 printf("%s:%u\n", name, count);
250 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name)
256 data = read_sha1_file(sha1, type, &size);
258 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
261 hit = grep_buffer(opt, name, data, size);
266 static int grep_file(struct grep_opt *opt, const char *filename)
271 if (lstat(filename, &st) < 0) {
274 error("'%s': %s", filename, strerror(errno));
278 return 0; /* empty file -- no grep hit */
279 if (!S_ISREG(st.st_mode))
281 i = open(filename, O_RDONLY);
284 data = xmalloc(st.st_size + 1);
285 if (st.st_size != xread(i, data, st.st_size)) {
286 error("'%s': short read %s", filename, strerror(errno));
292 i = grep_buffer(opt, filename, data, st.st_size);
297 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
303 for (nr = 0; nr < active_nr; nr++) {
304 struct cache_entry *ce = active_cache[nr];
305 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
307 if (!pathspec_matches(paths, ce->name))
310 hit |= grep_sha1(opt, ce->sha1, ce->name);
312 hit |= grep_file(opt, ce->name);
317 static int grep_tree(struct grep_opt *opt, const char **paths,
318 struct tree_desc *tree,
319 const char *tree_name, const char *base)
325 const unsigned char *sha1;
327 char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
330 int offset = sprintf(path_buf, "%s:", tree_name);
331 down = path_buf + offset;
338 len = strlen(path_buf);
342 sha1 = tree_entry_extract(tree, &path, &mode);
343 pathlen = strlen(path);
344 strcpy(path_buf + len, path);
347 /* Match "abc/" against pathspec to
348 * decide if we want to descend into "abc"
351 strcpy(path_buf + len + pathlen, "/");
353 if (!pathspec_matches(paths, down))
355 else if (S_ISREG(mode))
356 hit |= grep_sha1(opt, sha1, path_buf);
357 else if (S_ISDIR(mode)) {
359 struct tree_desc sub;
361 data = read_sha1_file(sha1, type, &sub.size);
363 die("unable to read tree (%s)",
366 hit |= grep_tree(opt, paths, &sub, tree_name, down);
369 update_tree_entry(tree);
374 static int grep_object(struct grep_opt *opt, const char **paths,
375 struct object *obj, const char *name)
377 if (!strcmp(obj->type, blob_type))
378 return grep_sha1(opt, obj->sha1, name);
379 if (!strcmp(obj->type, commit_type) ||
380 !strcmp(obj->type, tree_type)) {
381 struct tree_desc tree;
384 data = read_object_with_reference(obj->sha1, tree_type,
387 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
389 hit = grep_tree(opt, paths, &tree, name, "");
393 die("unable to grep from object of type %s", obj->type);
396 static const char builtin_grep_usage[] =
397 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
399 int cmd_grep(int argc, const char **argv, char **envp)
402 int no_more_flags = 0;
403 int seen_noncommit = 0;
406 struct object_list *list, **tail, *object_list = NULL;
407 const char *prefix = setup_git_directory();
408 const char **paths = NULL;
410 memset(&opt, 0, sizeof(opt));
411 opt.pattern_tail = &opt.pattern_list;
412 opt.regflags = REG_NEWLINE;
415 * No point using rev_info, really.
418 const char *arg = argv[1];
420 if (!strcmp("--cached", arg)) {
424 if (!strcmp("-i", arg) ||
425 !strcmp("--ignore-case", arg)) {
426 opt.regflags |= REG_ICASE;
429 if (!strcmp("-v", arg) ||
430 !strcmp("--invert-match", arg)) {
434 if (!strcmp("-E", arg) ||
435 !strcmp("--extended-regexp", arg)) {
436 opt.regflags |= REG_EXTENDED;
439 if (!strcmp("-G", arg) ||
440 !strcmp("--basic-regexp", arg)) {
441 opt.regflags &= ~REG_EXTENDED;
444 if (!strcmp("-n", arg)) {
448 if (!strcmp("-H", arg)) {
449 /* We always show the pathname, so this
454 if (!strcmp("-l", arg) ||
455 !strcmp("--files-with-matches", arg)) {
459 if (!strcmp("-c", arg) ||
460 !strcmp("--count", arg)) {
464 if (!strncmp("-A", arg, 2) ||
465 !strncmp("-B", arg, 2) ||
466 !strncmp("-C", arg, 2) ||
467 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
471 case 'A': case 'B': case 'C':
474 usage(builtin_grep_usage);
485 if (sscanf(scan, "%u", &num) != 1)
486 usage(builtin_grep_usage);
489 opt.post_context = num;
493 opt.post_context = num;
495 opt.pre_context = num;
500 if (!strcmp("-e", arg)) {
502 add_pattern(&opt, argv[1]);
507 usage(builtin_grep_usage);
509 if (!strcmp("--", arg)) {
513 /* Either unrecognized option or a single pattern */
514 if (!no_more_flags && *arg == '-')
515 usage(builtin_grep_usage);
516 if (!opt.pattern_list) {
517 add_pattern(&opt, arg);
521 /* We are looking at the first path or rev;
522 * it is found at argv[0] after leaving the
529 if (!opt.pattern_list)
530 die("no pattern given.");
531 compile_patterns(&opt);
534 struct object *object;
535 struct object_list *elem;
536 const char *arg = argv[1];
537 unsigned char sha1[20];
538 if (get_sha1(arg, sha1) < 0)
540 object = parse_object(sha1);
542 die("bad object %s", arg);
543 elem = object_list_insert(object, tail);
549 paths = get_pathspec(prefix, argv + 1);
551 paths = xcalloc(2, sizeof(const char *));
557 return !grep_cache(&opt, paths, cached);
559 * Do not walk "grep -e foo master next pu -- Documentation/"
560 * but do walk "grep -e foo master..next -- Documentation/".
561 * Ranged request mixed with a blob or tree object, like
562 * "grep -e foo v1.0.0:Documentation/ master..next"
563 * so detect that and complain.
565 for (list = object_list; list; list = list->next) {
566 struct object *real_obj;
567 real_obj = deref_tag(list->item, NULL, 0);
568 if (strcmp(real_obj->type, commit_type))
572 die("both --cached and revisions given.");
574 for (list = object_list; list; list = list->next) {
575 struct object *real_obj;
576 real_obj = deref_tag(list->item, NULL, 0);
577 if (grep_object(&opt, paths, real_obj, list->name))