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;
93 unsigned post_context;
96 static void add_pattern(struct grep_opt *opt, const char *pat)
98 struct grep_pat *p = xcalloc(1, sizeof(*p));
100 *opt->pattern_tail = p;
101 opt->pattern_tail = &p->next;
105 static void compile_patterns(struct grep_opt *opt)
108 for (p = opt->pattern_list; p; p = p->next) {
109 int err = regcomp(&p->regexp, p->pattern, opt->regflags);
112 regerror(err, &p->regexp, errbuf, 1024);
114 die("'%s': %s", p->pattern, errbuf);
119 static char *end_of_line(char *cp, unsigned long *left)
121 unsigned long l = *left;
122 while (l && *cp != '\n') {
130 static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
131 const char *name, unsigned lno, char sign)
133 printf("%s%c", name, sign);
135 printf("%d%c", lno, sign);
136 printf("%.*s\n", (int)(eol-bol), bol);
139 static int grep_buffer(struct grep_opt *opt, const char *name,
140 char *buf, unsigned long size)
143 unsigned long left = size;
145 struct pre_context_line {
148 } *prev = NULL, *pcl;
149 unsigned last_hit = 0;
150 unsigned last_shown = 0;
151 const char *hunk_mark = "";
153 if (opt->pre_context)
154 prev = xcalloc(opt->pre_context, sizeof(*prev));
155 if (opt->pre_context || opt->post_context)
159 regmatch_t pmatch[10];
164 eol = end_of_line(bol, &left);
168 for (p = opt->pattern_list; p; p = p->next) {
169 regex_t *exp = &p->regexp;
170 hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
175 /* "grep -v -e foo -e bla" should list lines
176 * that do not have either, so inversion should
182 if (opt->name_only) {
183 printf("%s\n", name);
186 /* Hit at this line. If we haven't shown the
187 * pre-context lines, we would need to show them.
189 if (opt->pre_context) {
191 if (opt->pre_context < lno)
192 from = lno - opt->pre_context;
195 if (from <= last_shown)
196 from = last_shown + 1;
197 if (last_shown && from != last_shown + 1)
200 pcl = &prev[lno-from-1];
201 show_line(opt, pcl->bol, pcl->eol,
207 if (last_shown && lno != last_shown + 1)
209 show_line(opt, bol, eol, name, lno, ':');
210 last_shown = last_hit = lno;
213 lno <= last_hit + opt->post_context) {
214 /* If the last hit is within the post context,
215 * we need to show this line.
217 if (last_shown && lno != last_shown + 1)
219 show_line(opt, bol, eol, name, lno, '-');
222 if (opt->pre_context) {
223 memmove(prev+1, prev,
224 (opt->pre_context-1) * sizeof(*prev));
236 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name)
242 data = read_sha1_file(sha1, type, &size);
244 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
247 hit = grep_buffer(opt, name, data, size);
252 static int grep_file(struct grep_opt *opt, const char *filename)
257 if (lstat(filename, &st) < 0) {
260 error("'%s': %s", filename, strerror(errno));
264 return 0; /* empty file -- no grep hit */
265 if (!S_ISREG(st.st_mode))
267 i = open(filename, O_RDONLY);
270 data = xmalloc(st.st_size + 1);
271 if (st.st_size != xread(i, data, st.st_size)) {
272 error("'%s': short read %s", filename, strerror(errno));
278 i = grep_buffer(opt, filename, data, st.st_size);
283 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
289 for (nr = 0; nr < active_nr; nr++) {
290 struct cache_entry *ce = active_cache[nr];
291 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
293 if (!pathspec_matches(paths, ce->name))
296 hit |= grep_sha1(opt, ce->sha1, ce->name);
298 hit |= grep_file(opt, ce->name);
303 static int grep_tree(struct grep_opt *opt, const char **paths,
304 struct tree_desc *tree,
305 const char *tree_name, const char *base)
311 const unsigned char *sha1;
313 char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
316 int offset = sprintf(path_buf, "%s:", tree_name);
317 down = path_buf + offset;
324 len = strlen(path_buf);
328 sha1 = tree_entry_extract(tree, &path, &mode);
329 pathlen = strlen(path);
330 strcpy(path_buf + len, path);
333 /* Match "abc/" against pathspec to
334 * decide if we want to descend into "abc"
337 strcpy(path_buf + len + pathlen, "/");
339 if (!pathspec_matches(paths, down))
341 else if (S_ISREG(mode))
342 hit |= grep_sha1(opt, sha1, path_buf);
343 else if (S_ISDIR(mode)) {
345 struct tree_desc sub;
347 data = read_sha1_file(sha1, type, &sub.size);
349 die("unable to read tree (%s)",
352 hit |= grep_tree(opt, paths, &sub, tree_name, down);
355 update_tree_entry(tree);
360 static int grep_object(struct grep_opt *opt, const char **paths,
361 struct object *obj, const char *name)
363 if (!strcmp(obj->type, blob_type))
364 return grep_sha1(opt, obj->sha1, name);
365 if (!strcmp(obj->type, commit_type) ||
366 !strcmp(obj->type, tree_type)) {
367 struct tree_desc tree;
370 data = read_object_with_reference(obj->sha1, tree_type,
373 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
375 hit = grep_tree(opt, paths, &tree, name, "");
379 die("unable to grep from object of type %s", obj->type);
382 static const char builtin_grep_usage[] =
383 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
385 int cmd_grep(int argc, const char **argv, char **envp)
388 int no_more_flags = 0;
389 int seen_noncommit = 0;
392 struct object_list *list, **tail, *object_list = NULL;
393 const char *prefix = setup_git_directory();
394 const char **paths = NULL;
396 memset(&opt, 0, sizeof(opt));
397 opt.pattern_tail = &opt.pattern_list;
398 opt.regflags = REG_NEWLINE;
401 * No point using rev_info, really.
404 const char *arg = argv[1];
406 if (!strcmp("--cached", arg)) {
410 if (!strcmp("-i", arg) ||
411 !strcmp("--ignore-case", arg)) {
412 opt.regflags |= REG_ICASE;
415 if (!strcmp("-v", arg) ||
416 !strcmp("--invert-match", arg)) {
420 if (!strcmp("-E", arg) ||
421 !strcmp("--extended-regexp", arg)) {
422 opt.regflags |= REG_EXTENDED;
425 if (!strcmp("-G", arg) ||
426 !strcmp("--basic-regexp", arg)) {
427 opt.regflags &= ~REG_EXTENDED;
430 if (!strcmp("-n", arg)) {
434 if (!strcmp("-H", arg)) {
435 /* We always show the pathname, so this
440 if (!strcmp("-l", arg) ||
441 !strcmp("--files-with-matches", arg)) {
445 if (!strncmp("-A", arg, 2) ||
446 !strncmp("-B", arg, 2) ||
447 !strncmp("-C", arg, 2) ||
448 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
452 case 'A': case 'B': case 'C':
455 usage(builtin_grep_usage);
466 if (sscanf(scan, "%u", &num) != 1)
467 usage(builtin_grep_usage);
470 opt.post_context = num;
474 opt.post_context = num;
476 opt.pre_context = num;
481 if (!strcmp("-e", arg)) {
483 add_pattern(&opt, argv[1]);
488 usage(builtin_grep_usage);
490 if (!strcmp("--", arg)) {
494 /* Either unrecognized option or a single pattern */
495 if (!no_more_flags && *arg == '-')
496 usage(builtin_grep_usage);
497 if (!opt.pattern_list) {
498 add_pattern(&opt, arg);
502 /* We are looking at the first path or rev;
503 * it is found at argv[0] after leaving the
510 if (!opt.pattern_list)
511 die("no pattern given.");
512 compile_patterns(&opt);
515 struct object *object;
516 struct object_list *elem;
517 const char *arg = argv[1];
518 unsigned char sha1[20];
519 if (get_sha1(arg, sha1) < 0)
521 object = parse_object(sha1);
523 die("bad object %s", arg);
524 elem = object_list_insert(object, tail);
530 paths = get_pathspec(prefix, argv + 1);
532 paths = xcalloc(2, sizeof(const char *));
538 return !grep_cache(&opt, paths, cached);
540 * Do not walk "grep -e foo master next pu -- Documentation/"
541 * but do walk "grep -e foo master..next -- Documentation/".
542 * Ranged request mixed with a blob or tree object, like
543 * "grep -e foo v1.0.0:Documentation/ master..next"
544 * so detect that and complain.
546 for (list = object_list; list; list = list->next) {
547 struct object *real_obj;
548 real_obj = deref_tag(list->item, NULL, 0);
549 if (strcmp(real_obj->type, commit_type))
553 die("both --cached and revisions given.");
555 for (list = object_list; list; list = list->next) {
556 struct object *real_obj;
557 real_obj = deref_tag(list->item, NULL, 0);
558 if (grep_object(&opt, paths, real_obj, list->name))