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
));
271 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
272 * which feels mostly useless but sometimes useful. Maybe
273 * make it another option? For now suppress them.
275 if (opt
->count
&& count
)
276 printf("%s:%u\n", name
, count
);
280 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
, const char *name
)
286 data
= read_sha1_file(sha1
, type
, &size
);
288 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
291 hit
= grep_buffer(opt
, name
, data
, size
);
296 static int grep_file(struct grep_opt
*opt
, const char *filename
)
301 if (lstat(filename
, &st
) < 0) {
304 error("'%s': %s", filename
, strerror(errno
));
308 return 0; /* empty file -- no grep hit */
309 if (!S_ISREG(st
.st_mode
))
311 i
= open(filename
, O_RDONLY
);
314 data
= xmalloc(st
.st_size
+ 1);
315 if (st
.st_size
!= xread(i
, data
, st
.st_size
)) {
316 error("'%s': short read %s", filename
, strerror(errno
));
322 i
= grep_buffer(opt
, filename
, data
, st
.st_size
);
327 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
)
333 for (nr
= 0; nr
< active_nr
; nr
++) {
334 struct cache_entry
*ce
= active_cache
[nr
];
335 if (ce_stage(ce
) || !S_ISREG(ntohl(ce
->ce_mode
)))
337 if (!pathspec_matches(paths
, ce
->name
))
340 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
);
342 hit
|= grep_file(opt
, ce
->name
);
347 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
348 struct tree_desc
*tree
,
349 const char *tree_name
, const char *base
)
355 const unsigned char *sha1
;
357 char *path_buf
= xmalloc(PATH_MAX
+ strlen(tree_name
) + 100);
360 int offset
= sprintf(path_buf
, "%s:", tree_name
);
361 down
= path_buf
+ offset
;
368 len
= strlen(path_buf
);
372 sha1
= tree_entry_extract(tree
, &path
, &mode
);
373 pathlen
= strlen(path
);
374 strcpy(path_buf
+ len
, path
);
377 /* Match "abc/" against pathspec to
378 * decide if we want to descend into "abc"
381 strcpy(path_buf
+ len
+ pathlen
, "/");
383 if (!pathspec_matches(paths
, down
))
385 else if (S_ISREG(mode
))
386 hit
|= grep_sha1(opt
, sha1
, path_buf
);
387 else if (S_ISDIR(mode
)) {
389 struct tree_desc sub
;
391 data
= read_sha1_file(sha1
, type
, &sub
.size
);
393 die("unable to read tree (%s)",
396 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
399 update_tree_entry(tree
);
404 static int grep_object(struct grep_opt
*opt
, const char **paths
,
405 struct object
*obj
, const char *name
)
407 if (!strcmp(obj
->type
, blob_type
))
408 return grep_sha1(opt
, obj
->sha1
, name
);
409 if (!strcmp(obj
->type
, commit_type
) ||
410 !strcmp(obj
->type
, tree_type
)) {
411 struct tree_desc tree
;
414 data
= read_object_with_reference(obj
->sha1
, tree_type
,
417 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
419 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
423 die("unable to grep from object of type %s", obj
->type
);
426 static const char builtin_grep_usage
[] =
427 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
429 int cmd_grep(int argc
, const char **argv
, char **envp
)
432 int no_more_flags
= 0;
433 int seen_noncommit
= 0;
436 struct object_list
*list
, **tail
, *object_list
= NULL
;
437 const char *prefix
= setup_git_directory();
438 const char **paths
= NULL
;
440 memset(&opt
, 0, sizeof(opt
));
441 opt
.pattern_tail
= &opt
.pattern_list
;
442 opt
.regflags
= REG_NEWLINE
;
445 * No point using rev_info, really.
448 const char *arg
= argv
[1];
450 if (!strcmp("--cached", arg
)) {
454 if (!strcmp("-i", arg
) ||
455 !strcmp("--ignore-case", arg
)) {
456 opt
.regflags
|= REG_ICASE
;
459 if (!strcmp("-v", arg
) ||
460 !strcmp("--invert-match", arg
)) {
464 if (!strcmp("-E", arg
) ||
465 !strcmp("--extended-regexp", arg
)) {
466 opt
.regflags
|= REG_EXTENDED
;
469 if (!strcmp("-G", arg
) ||
470 !strcmp("--basic-regexp", arg
)) {
471 opt
.regflags
&= ~REG_EXTENDED
;
474 if (!strcmp("-n", arg
)) {
478 if (!strcmp("-H", arg
)) {
479 /* We always show the pathname, so this
484 if (!strcmp("-l", arg
) ||
485 !strcmp("--files-with-matches", arg
)) {
489 if (!strcmp("-c", arg
) ||
490 !strcmp("--count", arg
)) {
494 if (!strcmp("-w", arg
) ||
495 !strcmp("--word-regexp", arg
)) {
499 if (!strncmp("-A", arg
, 2) ||
500 !strncmp("-B", arg
, 2) ||
501 !strncmp("-C", arg
, 2) ||
502 (arg
[0] == '-' && '1' <= arg
[1] && arg
[1] <= '9')) {
506 case 'A': case 'B': case 'C':
509 usage(builtin_grep_usage
);
520 if (sscanf(scan
, "%u", &num
) != 1)
521 usage(builtin_grep_usage
);
524 opt
.post_context
= num
;
528 opt
.post_context
= num
;
530 opt
.pre_context
= num
;
535 if (!strcmp("-e", arg
)) {
537 add_pattern(&opt
, argv
[1]);
542 usage(builtin_grep_usage
);
544 if (!strcmp("--", arg
)) {
548 /* Either unrecognized option or a single pattern */
549 if (!no_more_flags
&& *arg
== '-')
550 usage(builtin_grep_usage
);
551 if (!opt
.pattern_list
) {
552 add_pattern(&opt
, arg
);
556 /* We are looking at the first path or rev;
557 * it is found at argv[0] after leaving the
564 if (!opt
.pattern_list
)
565 die("no pattern given.");
566 compile_patterns(&opt
);
569 struct object
*object
;
570 struct object_list
*elem
;
571 const char *arg
= argv
[1];
572 unsigned char sha1
[20];
573 if (get_sha1(arg
, sha1
) < 0)
575 object
= parse_object(sha1
);
577 die("bad object %s", arg
);
578 elem
= object_list_insert(object
, tail
);
584 paths
= get_pathspec(prefix
, argv
+ 1);
586 paths
= xcalloc(2, sizeof(const char *));
592 return !grep_cache(&opt
, paths
, cached
);
594 * Do not walk "grep -e foo master next pu -- Documentation/"
595 * but do walk "grep -e foo master..next -- Documentation/".
596 * Ranged request mixed with a blob or tree object, like
597 * "grep -e foo v1.0.0:Documentation/ master..next"
598 * so detect that and complain.
600 for (list
= object_list
; list
; list
= list
->next
) {
601 struct object
*real_obj
;
602 real_obj
= deref_tag(list
->item
, NULL
, 0);
603 if (strcmp(real_obj
->type
, commit_type
))
607 die("both --cached and revisions given.");
609 for (list
= object_list
; list
; list
= list
->next
) {
610 struct object
*real_obj
;
611 real_obj
= deref_tag(list
->item
, NULL
, 0);
612 if (grep_object(&opt
, paths
, real_obj
, list
->name
))