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
;
92 struct grep_pat
*pattern_list
;
93 struct grep_pat
**pattern_tail
;
98 unsigned unmatch_name_only
:1;
100 unsigned word_regexp
:1;
101 #define GREP_BINARY_DEFAULT 0
102 #define GREP_BINARY_NOMATCH 1
103 #define GREP_BINARY_TEXT 2
106 unsigned pre_context
;
107 unsigned post_context
;
110 static void add_pattern(struct grep_opt
*opt
, const char *pat
,
111 const char *origin
, int no
)
113 struct grep_pat
*p
= xcalloc(1, sizeof(*p
));
117 *opt
->pattern_tail
= p
;
118 opt
->pattern_tail
= &p
->next
;
122 static void compile_patterns(struct grep_opt
*opt
)
125 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
126 int err
= regcomp(&p
->regexp
, p
->pattern
, opt
->regflags
);
131 sprintf(where
, "In '%s' at %d, ",
134 sprintf(where
, "%s, ", p
->origin
);
137 regerror(err
, &p
->regexp
, errbuf
, 1024);
139 die("%s'%s': %s", where
, p
->pattern
, errbuf
);
144 static char *end_of_line(char *cp
, unsigned long *left
)
146 unsigned long l
= *left
;
147 while (l
&& *cp
!= '\n') {
155 static int word_char(char ch
)
157 return isalnum(ch
) || ch
== '_';
160 static void show_line(struct grep_opt
*opt
, const char *bol
, const char *eol
,
161 const char *name
, unsigned lno
, char sign
)
163 printf("%s%c", name
, sign
);
165 printf("%d%c", lno
, sign
);
166 printf("%.*s\n", (int)(eol
-bol
), bol
);
170 * NEEDSWORK: share code with diff.c
172 #define FIRST_FEW_BYTES 8000
173 static int buffer_is_binary(const char *ptr
, unsigned long size
)
175 if (FIRST_FEW_BYTES
< size
)
176 size
= FIRST_FEW_BYTES
;
177 if (memchr(ptr
, 0, size
))
182 static int grep_buffer(struct grep_opt
*opt
, const char *name
,
183 char *buf
, unsigned long size
)
186 unsigned long left
= size
;
188 struct pre_context_line
{
191 } *prev
= NULL
, *pcl
;
192 unsigned last_hit
= 0;
193 unsigned last_shown
= 0;
194 int binary_match_only
= 0;
195 const char *hunk_mark
= "";
198 if (buffer_is_binary(buf
, size
)) {
199 switch (opt
->binary
) {
200 case GREP_BINARY_DEFAULT
:
201 binary_match_only
= 1;
203 case GREP_BINARY_NOMATCH
:
204 return 0; /* Assume unmatch */
211 if (opt
->pre_context
)
212 prev
= xcalloc(opt
->pre_context
, sizeof(*prev
));
213 if (opt
->pre_context
|| opt
->post_context
)
217 regmatch_t pmatch
[10];
222 eol
= end_of_line(bol
, &left
);
226 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
227 regex_t
*exp
= &p
->regexp
;
228 hit
= !regexec(exp
, bol
, ARRAY_SIZE(pmatch
),
231 if (hit
&& opt
->word_regexp
) {
232 /* Match beginning must be either
233 * beginning of the line, or at word
234 * boundary (i.e. the last char must
235 * not be alnum or underscore).
237 if ((pmatch
[0].rm_so
< 0) ||
238 (eol
- bol
) <= pmatch
[0].rm_so
||
239 (pmatch
[0].rm_eo
< 0) ||
240 (eol
- bol
) < pmatch
[0].rm_eo
)
241 die("regexp returned nonsense");
242 if (pmatch
[0].rm_so
!= 0 &&
243 word_char(bol
[pmatch
[0].rm_so
-1]))
244 continue; /* not a word boundary */
245 if ((eol
-bol
) < pmatch
[0].rm_eo
&&
246 word_char(bol
[pmatch
[0].rm_eo
]))
247 continue; /* not a word boundary */
252 /* "grep -v -e foo -e bla" should list lines
253 * that do not have either, so inversion should
258 if (opt
->unmatch_name_only
) {
265 if (binary_match_only
) {
266 printf("Binary file %s matches\n", name
);
269 if (opt
->name_only
) {
270 printf("%s\n", name
);
273 /* Hit at this line. If we haven't shown the
274 * pre-context lines, we would need to show them.
275 * When asked to do "count", this still show
276 * the context which is nonsense, but the user
277 * deserves to get that ;-).
279 if (opt
->pre_context
) {
281 if (opt
->pre_context
< lno
)
282 from
= lno
- opt
->pre_context
;
285 if (from
<= last_shown
)
286 from
= last_shown
+ 1;
287 if (last_shown
&& from
!= last_shown
+ 1)
290 pcl
= &prev
[lno
-from
-1];
291 show_line(opt
, pcl
->bol
, pcl
->eol
,
297 if (last_shown
&& lno
!= last_shown
+ 1)
300 show_line(opt
, bol
, eol
, name
, lno
, ':');
301 last_shown
= last_hit
= lno
;
304 lno
<= last_hit
+ opt
->post_context
) {
305 /* If the last hit is within the post context,
306 * we need to show this line.
308 if (last_shown
&& lno
!= last_shown
+ 1)
310 show_line(opt
, bol
, eol
, name
, lno
, '-');
313 if (opt
->pre_context
) {
314 memmove(prev
+1, prev
,
315 (opt
->pre_context
-1) * sizeof(*prev
));
329 if (opt
->unmatch_name_only
) {
330 /* We did not see any hit, so we want to show this */
331 printf("%s\n", name
);
336 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
337 * which feels mostly useless but sometimes useful. Maybe
338 * make it another option? For now suppress them.
340 if (opt
->count
&& count
)
341 printf("%s:%u\n", name
, count
);
345 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
, const char *name
)
351 data
= read_sha1_file(sha1
, type
, &size
);
353 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
356 hit
= grep_buffer(opt
, name
, data
, size
);
361 static int grep_file(struct grep_opt
*opt
, const char *filename
)
366 if (lstat(filename
, &st
) < 0) {
369 error("'%s': %s", filename
, strerror(errno
));
373 return 0; /* empty file -- no grep hit */
374 if (!S_ISREG(st
.st_mode
))
376 i
= open(filename
, O_RDONLY
);
379 data
= xmalloc(st
.st_size
+ 1);
380 if (st
.st_size
!= xread(i
, data
, st
.st_size
)) {
381 error("'%s': short read %s", filename
, strerror(errno
));
387 i
= grep_buffer(opt
, filename
, data
, st
.st_size
);
392 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
)
398 for (nr
= 0; nr
< active_nr
; nr
++) {
399 struct cache_entry
*ce
= active_cache
[nr
];
400 if (ce_stage(ce
) || !S_ISREG(ntohl(ce
->ce_mode
)))
402 if (!pathspec_matches(paths
, ce
->name
))
405 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
);
407 hit
|= grep_file(opt
, ce
->name
);
412 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
413 struct tree_desc
*tree
,
414 const char *tree_name
, const char *base
)
420 const unsigned char *sha1
;
422 char *path_buf
= xmalloc(PATH_MAX
+ strlen(tree_name
) + 100);
425 int offset
= sprintf(path_buf
, "%s:", tree_name
);
426 down
= path_buf
+ offset
;
433 len
= strlen(path_buf
);
437 sha1
= tree_entry_extract(tree
, &path
, &mode
);
438 pathlen
= strlen(path
);
439 strcpy(path_buf
+ len
, path
);
442 /* Match "abc/" against pathspec to
443 * decide if we want to descend into "abc"
446 strcpy(path_buf
+ len
+ pathlen
, "/");
448 if (!pathspec_matches(paths
, down
))
450 else if (S_ISREG(mode
))
451 hit
|= grep_sha1(opt
, sha1
, path_buf
);
452 else if (S_ISDIR(mode
)) {
454 struct tree_desc sub
;
456 data
= read_sha1_file(sha1
, type
, &sub
.size
);
458 die("unable to read tree (%s)",
461 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
464 update_tree_entry(tree
);
469 static int grep_object(struct grep_opt
*opt
, const char **paths
,
470 struct object
*obj
, const char *name
)
472 if (!strcmp(obj
->type
, blob_type
))
473 return grep_sha1(opt
, obj
->sha1
, name
);
474 if (!strcmp(obj
->type
, commit_type
) ||
475 !strcmp(obj
->type
, tree_type
)) {
476 struct tree_desc tree
;
479 data
= read_object_with_reference(obj
->sha1
, tree_type
,
482 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
484 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
488 die("unable to grep from object of type %s", obj
->type
);
491 static const char builtin_grep_usage
[] =
492 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
494 int cmd_grep(int argc
, const char **argv
, char **envp
)
498 int seen_dashdash
= 0;
500 struct object_list
*list
, **tail
, *object_list
= NULL
;
501 const char *prefix
= setup_git_directory();
502 const char **paths
= NULL
;
505 memset(&opt
, 0, sizeof(opt
));
506 opt
.pattern_tail
= &opt
.pattern_list
;
507 opt
.regflags
= REG_NEWLINE
;
510 * If there is no -- then the paths must exist in the working
511 * tree. If there is no explicit pattern specified with -e or
512 * -f, we take the first unrecognized non option to be the
513 * pattern, but then what follows it must be zero or more
514 * valid refs up to the -- (if exists), and then existing
515 * paths. If there is an explicit pattern, then the first
516 * unrecocnized non option is the beginning of the refs list
517 * that continues up to the -- (if exists), and then paths.
522 const char *arg
= argv
[1];
524 if (!strcmp("--cached", arg
)) {
528 if (!strcmp("-a", arg
) ||
529 !strcmp("--text", arg
)) {
530 opt
.binary
= GREP_BINARY_TEXT
;
533 if (!strcmp("-i", arg
) ||
534 !strcmp("--ignore-case", arg
)) {
535 opt
.regflags
|= REG_ICASE
;
538 if (!strcmp("-I", arg
)) {
539 opt
.binary
= GREP_BINARY_NOMATCH
;
542 if (!strcmp("-v", arg
) ||
543 !strcmp("--invert-match", arg
)) {
547 if (!strcmp("-E", arg
) ||
548 !strcmp("--extended-regexp", arg
)) {
549 opt
.regflags
|= REG_EXTENDED
;
552 if (!strcmp("-G", arg
) ||
553 !strcmp("--basic-regexp", arg
)) {
554 opt
.regflags
&= ~REG_EXTENDED
;
557 if (!strcmp("-n", arg
)) {
561 if (!strcmp("-H", arg
)) {
562 /* We always show the pathname, so this
567 if (!strcmp("-l", arg
) ||
568 !strcmp("--files-with-matches", arg
)) {
572 if (!strcmp("-L", arg
) ||
573 !strcmp("--files-without-match", arg
)) {
574 opt
.unmatch_name_only
= 1;
577 if (!strcmp("-c", arg
) ||
578 !strcmp("--count", arg
)) {
582 if (!strcmp("-w", arg
) ||
583 !strcmp("--word-regexp", arg
)) {
587 if (!strncmp("-A", arg
, 2) ||
588 !strncmp("-B", arg
, 2) ||
589 !strncmp("-C", arg
, 2) ||
590 (arg
[0] == '-' && '1' <= arg
[1] && arg
[1] <= '9')) {
594 case 'A': case 'B': case 'C':
597 usage(builtin_grep_usage
);
608 if (sscanf(scan
, "%u", &num
) != 1)
609 usage(builtin_grep_usage
);
612 opt
.post_context
= num
;
616 opt
.post_context
= num
;
618 opt
.pre_context
= num
;
623 if (!strcmp("-f", arg
)) {
628 usage(builtin_grep_usage
);
629 patterns
= fopen(argv
[1], "r");
631 die("'%s': %s", argv
[1], strerror(errno
));
632 while (fgets(buf
, sizeof(buf
), patterns
)) {
633 int len
= strlen(buf
);
634 if (buf
[len
-1] == '\n')
636 /* ignore empty line like grep does */
639 add_pattern(&opt
, strdup(buf
), argv
[1], ++lno
);
646 if (!strcmp("-e", arg
)) {
648 add_pattern(&opt
, argv
[1], "-e option", 0);
653 usage(builtin_grep_usage
);
655 if (!strcmp("--", arg
))
658 usage(builtin_grep_usage
);
660 /* First unrecognized non-option token */
661 if (!opt
.pattern_list
) {
662 add_pattern(&opt
, arg
, "command line", 0);
666 /* We are looking at the first path or rev;
667 * it is found at argv[1] after leaving the
675 if (!opt
.pattern_list
)
676 die("no pattern given.");
677 compile_patterns(&opt
);
679 /* Check revs and then paths */
680 for (i
= 1; i
< argc
; i
++) {
681 const char *arg
= argv
[i
];
682 unsigned char sha1
[20];
684 if (!get_sha1(arg
, sha1
)) {
685 struct object
*object
= parse_object(sha1
);
686 struct object_list
*elem
;
688 die("bad object %s", arg
);
689 elem
= object_list_insert(object
, tail
);
694 if (!strcmp(arg
, "--")) {
701 /* The rest are paths */
702 if (!seen_dashdash
) {
704 for (j
= i
; j
< argc
; i
++)
705 verify_filename(prefix
, argv
[j
]);
709 paths
= get_pathspec(prefix
, argv
+ i
);
711 paths
= xcalloc(2, sizeof(const char *));
717 return !grep_cache(&opt
, paths
, cached
);
720 die("both --cached and trees are given.");
722 for (list
= object_list
; list
; list
= list
->next
) {
723 struct object
*real_obj
;
724 real_obj
= deref_tag(list
->item
, NULL
, 0);
725 if (grep_object(&opt
, paths
, real_obj
, list
->name
))