4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
18 * git grep pathspecs are somewhat different from diff-tree pathspecs;
19 * pathname wildcards are allowed.
21 static int pathspec_matches(const char **paths
, const char *name
)
24 if (!paths
|| !*paths
)
26 namelen
= strlen(name
);
27 for (i
= 0; paths
[i
]; i
++) {
28 const char *match
= paths
[i
];
29 int matchlen
= strlen(match
);
30 const char *cp
, *meta
;
32 if ((matchlen
<= namelen
) &&
33 !strncmp(name
, match
, matchlen
) &&
34 (match
[matchlen
-1] == '/' ||
35 name
[matchlen
] == '\0' || name
[matchlen
] == '/'))
37 if (!fnmatch(match
, name
, 0))
39 if (name
[namelen
-1] != '/')
42 /* We are being asked if the directory ("name") is worth
45 * Find the longest leading directory name that does
46 * not have metacharacter in the pathspec; the name
47 * we are looking at must overlap with that directory.
49 for (cp
= match
, meta
= NULL
; cp
- match
< matchlen
; cp
++) {
51 if (ch
== '*' || ch
== '[' || ch
== '?') {
57 meta
= cp
; /* fully literal */
59 if (namelen
<= meta
- match
) {
60 /* Looking at "Documentation/" and
61 * the pattern says "Documentation/howto/", or
62 * "Documentation/diff*.txt". The name we
63 * have should match prefix.
65 if (!memcmp(match
, name
, namelen
))
70 if (meta
- match
< namelen
) {
71 /* Looking at "Documentation/howto/" and
72 * the pattern says "Documentation/h*";
73 * match up to "Do.../h"; this avoids descending
74 * into "Documentation/technical/".
76 if (!memcmp(match
, name
, meta
- match
))
85 struct grep_pat
*next
;
93 struct grep_pat
*pattern_list
;
94 struct grep_pat
**pattern_tail
;
99 unsigned unmatch_name_only
:1;
101 unsigned word_regexp
:1;
103 #define GREP_BINARY_DEFAULT 0
104 #define GREP_BINARY_NOMATCH 1
105 #define GREP_BINARY_TEXT 2
108 unsigned pre_context
;
109 unsigned post_context
;
112 static void add_pattern(struct grep_opt
*opt
, const char *pat
,
113 const char *origin
, int no
)
115 struct grep_pat
*p
= xcalloc(1, sizeof(*p
));
119 *opt
->pattern_tail
= p
;
120 opt
->pattern_tail
= &p
->next
;
124 static void compile_patterns(struct grep_opt
*opt
)
127 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
128 int err
= regcomp(&p
->regexp
, p
->pattern
, opt
->regflags
);
133 sprintf(where
, "In '%s' at %d, ",
136 sprintf(where
, "%s, ", p
->origin
);
139 regerror(err
, &p
->regexp
, errbuf
, 1024);
141 die("%s'%s': %s", where
, p
->pattern
, errbuf
);
146 static char *end_of_line(char *cp
, unsigned long *left
)
148 unsigned long l
= *left
;
149 while (l
&& *cp
!= '\n') {
157 static int word_char(char ch
)
159 return isalnum(ch
) || ch
== '_';
162 static void show_line(struct grep_opt
*opt
, const char *bol
, const char *eol
,
163 const char *name
, unsigned lno
, char sign
)
165 printf("%s%c", name
, sign
);
167 printf("%d%c", lno
, sign
);
168 printf("%.*s\n", (int)(eol
-bol
), bol
);
172 * NEEDSWORK: share code with diff.c
174 #define FIRST_FEW_BYTES 8000
175 static int buffer_is_binary(const char *ptr
, unsigned long size
)
177 if (FIRST_FEW_BYTES
< size
)
178 size
= FIRST_FEW_BYTES
;
179 if (memchr(ptr
, 0, size
))
184 static int fixmatch(const char *pattern
, char *line
, regmatch_t
*match
)
186 char *hit
= strstr(line
, pattern
);
188 match
->rm_so
= match
->rm_eo
= -1;
192 match
->rm_so
= hit
- line
;
193 match
->rm_eo
= match
->rm_so
+ strlen(pattern
);
198 static int grep_buffer(struct grep_opt
*opt
, const char *name
,
199 char *buf
, unsigned long size
)
202 unsigned long left
= size
;
204 struct pre_context_line
{
207 } *prev
= NULL
, *pcl
;
208 unsigned last_hit
= 0;
209 unsigned last_shown
= 0;
210 int binary_match_only
= 0;
211 const char *hunk_mark
= "";
214 if (buffer_is_binary(buf
, size
)) {
215 switch (opt
->binary
) {
216 case GREP_BINARY_DEFAULT
:
217 binary_match_only
= 1;
219 case GREP_BINARY_NOMATCH
:
220 return 0; /* Assume unmatch */
227 if (opt
->pre_context
)
228 prev
= xcalloc(opt
->pre_context
, sizeof(*prev
));
229 if (opt
->pre_context
|| opt
->post_context
)
233 regmatch_t pmatch
[10];
238 eol
= end_of_line(bol
, &left
);
242 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
244 regex_t
*exp
= &p
->regexp
;
245 hit
= !regexec(exp
, bol
, ARRAY_SIZE(pmatch
),
249 hit
= !fixmatch(p
->pattern
, bol
, pmatch
);
252 if (hit
&& opt
->word_regexp
) {
253 /* Match beginning must be either
254 * beginning of the line, or at word
255 * boundary (i.e. the last char must
256 * not be alnum or underscore).
258 if ((pmatch
[0].rm_so
< 0) ||
259 (eol
- bol
) <= pmatch
[0].rm_so
||
260 (pmatch
[0].rm_eo
< 0) ||
261 (eol
- bol
) < pmatch
[0].rm_eo
)
262 die("regexp returned nonsense");
263 if (pmatch
[0].rm_so
!= 0 &&
264 word_char(bol
[pmatch
[0].rm_so
-1]))
266 if (pmatch
[0].rm_eo
!= (eol
-bol
) &&
267 word_char(bol
[pmatch
[0].rm_eo
]))
273 /* "grep -v -e foo -e bla" should list lines
274 * that do not have either, so inversion should
279 if (opt
->unmatch_name_only
) {
286 if (binary_match_only
) {
287 printf("Binary file %s matches\n", name
);
290 if (opt
->name_only
) {
291 printf("%s\n", name
);
294 /* Hit at this line. If we haven't shown the
295 * pre-context lines, we would need to show them.
296 * When asked to do "count", this still show
297 * the context which is nonsense, but the user
298 * deserves to get that ;-).
300 if (opt
->pre_context
) {
302 if (opt
->pre_context
< lno
)
303 from
= lno
- opt
->pre_context
;
306 if (from
<= last_shown
)
307 from
= last_shown
+ 1;
308 if (last_shown
&& from
!= last_shown
+ 1)
311 pcl
= &prev
[lno
-from
-1];
312 show_line(opt
, pcl
->bol
, pcl
->eol
,
318 if (last_shown
&& lno
!= last_shown
+ 1)
321 show_line(opt
, bol
, eol
, name
, lno
, ':');
322 last_shown
= last_hit
= lno
;
325 lno
<= last_hit
+ opt
->post_context
) {
326 /* If the last hit is within the post context,
327 * we need to show this line.
329 if (last_shown
&& lno
!= last_shown
+ 1)
331 show_line(opt
, bol
, eol
, name
, lno
, '-');
334 if (opt
->pre_context
) {
335 memmove(prev
+1, prev
,
336 (opt
->pre_context
-1) * sizeof(*prev
));
350 if (opt
->unmatch_name_only
) {
351 /* We did not see any hit, so we want to show this */
352 printf("%s\n", name
);
357 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
358 * which feels mostly useless but sometimes useful. Maybe
359 * make it another option? For now suppress them.
361 if (opt
->count
&& count
)
362 printf("%s:%u\n", name
, count
);
366 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
, const char *name
)
372 data
= read_sha1_file(sha1
, type
, &size
);
374 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
377 hit
= grep_buffer(opt
, name
, data
, size
);
382 static int grep_file(struct grep_opt
*opt
, const char *filename
)
387 if (lstat(filename
, &st
) < 0) {
390 error("'%s': %s", filename
, strerror(errno
));
394 return 0; /* empty file -- no grep hit */
395 if (!S_ISREG(st
.st_mode
))
397 i
= open(filename
, O_RDONLY
);
400 data
= xmalloc(st
.st_size
+ 1);
401 if (st
.st_size
!= xread(i
, data
, st
.st_size
)) {
402 error("'%s': short read %s", filename
, strerror(errno
));
408 i
= grep_buffer(opt
, filename
, data
, st
.st_size
);
413 static int exec_grep(int argc
, const char **argv
)
423 execvp("grep", (char **) argv
);
426 while (waitpid(pid
, &status
, 0) < 0) {
431 if (WIFEXITED(status
)) {
432 if (!WEXITSTATUS(status
))
441 #define push_arg(a) do { \
442 if (nr < MAXARGS) argv[nr++] = (a); \
443 else die("maximum number of args exceeded"); \
446 static int external_grep(struct grep_opt
*opt
, const char **paths
, int cached
)
448 int i
, nr
, argc
, hit
, len
;
449 const char *argv
[MAXARGS
+1];
450 char randarg
[ARGBUF
];
451 char *argptr
= randarg
;
460 if (opt
->regflags
& REG_EXTENDED
)
462 if (opt
->regflags
& REG_ICASE
)
464 if (opt
->word_regexp
)
468 if (opt
->unmatch_name_only
)
472 if (opt
->post_context
|| opt
->pre_context
) {
473 if (opt
->post_context
!= opt
->pre_context
) {
474 if (opt
->pre_context
) {
476 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
477 "%u", opt
->pre_context
);
478 if (sizeof(randarg
) <= len
)
479 die("maximum length of args exceeded");
483 if (opt
->post_context
) {
485 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
486 "%u", opt
->post_context
);
487 if (sizeof(randarg
) <= len
)
488 die("maximum length of args exceeded");
495 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
496 "%u", opt
->post_context
);
497 if (sizeof(randarg
) <= len
)
498 die("maximum length of args exceeded");
503 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
505 push_arg(p
->pattern
);
509 * To make sure we get the header printed out when we want it,
510 * add /dev/null to the paths to grep. This is unnecessary
511 * (and wrong) with "-l" or "-L", which always print out the
514 * GNU grep has "-H", but this is portable.
516 if (!opt
->name_only
&& !opt
->unmatch_name_only
)
517 push_arg("/dev/null");
521 for (i
= 0; i
< active_nr
; i
++) {
522 struct cache_entry
*ce
= active_cache
[i
];
524 if (ce_stage(ce
) || !S_ISREG(ntohl(ce
->ce_mode
)))
526 if (!pathspec_matches(paths
, ce
->name
))
529 if (name
[0] == '-') {
530 int len
= ce_namelen(ce
);
531 name
= xmalloc(len
+ 3);
532 memcpy(name
, "./", 2);
533 memcpy(name
+ 2, ce
->name
, len
+ 1);
538 hit
+= exec_grep(argc
, argv
);
542 hit
+= exec_grep(argc
, argv
);
546 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
)
554 * Use the external "grep" command for the case where
555 * we grep through the checked-out files. It tends to
556 * be a lot more optimized
559 hit
= external_grep(opt
, paths
, cached
);
565 for (nr
= 0; nr
< active_nr
; nr
++) {
566 struct cache_entry
*ce
= active_cache
[nr
];
567 if (ce_stage(ce
) || !S_ISREG(ntohl(ce
->ce_mode
)))
569 if (!pathspec_matches(paths
, ce
->name
))
572 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
);
574 hit
|= grep_file(opt
, ce
->name
);
579 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
580 struct tree_desc
*tree
,
581 const char *tree_name
, const char *base
)
585 struct name_entry entry
;
587 char *path_buf
= xmalloc(PATH_MAX
+ strlen(tree_name
) + 100);
590 int offset
= sprintf(path_buf
, "%s:", tree_name
);
591 down
= path_buf
+ offset
;
598 len
= strlen(path_buf
);
600 while (tree_entry(tree
, &entry
)) {
601 strcpy(path_buf
+ len
, entry
.path
);
603 if (S_ISDIR(entry
.mode
))
604 /* Match "abc/" against pathspec to
605 * decide if we want to descend into "abc"
608 strcpy(path_buf
+ len
+ entry
.pathlen
, "/");
610 if (!pathspec_matches(paths
, down
))
612 else if (S_ISREG(entry
.mode
))
613 hit
|= grep_sha1(opt
, entry
.sha1
, path_buf
);
614 else if (S_ISDIR(entry
.mode
)) {
616 struct tree_desc sub
;
618 data
= read_sha1_file(entry
.sha1
, type
, &sub
.size
);
620 die("unable to read tree (%s)",
621 sha1_to_hex(entry
.sha1
));
623 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
630 static int grep_object(struct grep_opt
*opt
, const char **paths
,
631 struct object
*obj
, const char *name
)
633 if (obj
->type
== TYPE_BLOB
)
634 return grep_sha1(opt
, obj
->sha1
, name
);
635 if (obj
->type
== TYPE_COMMIT
|| obj
->type
== TYPE_TREE
) {
636 struct tree_desc tree
;
639 data
= read_object_with_reference(obj
->sha1
, tree_type
,
642 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
644 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
648 die("unable to grep from object of type %s", typename(obj
->type
));
651 static const char builtin_grep_usage
[] =
652 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
654 int cmd_grep(int argc
, const char **argv
, char **envp
)
658 int seen_dashdash
= 0;
660 struct object_list
*list
, **tail
, *object_list
= NULL
;
661 const char *prefix
= setup_git_directory();
662 const char **paths
= NULL
;
665 memset(&opt
, 0, sizeof(opt
));
666 opt
.pattern_tail
= &opt
.pattern_list
;
667 opt
.regflags
= REG_NEWLINE
;
670 * If there is no -- then the paths must exist in the working
671 * tree. If there is no explicit pattern specified with -e or
672 * -f, we take the first unrecognized non option to be the
673 * pattern, but then what follows it must be zero or more
674 * valid refs up to the -- (if exists), and then existing
675 * paths. If there is an explicit pattern, then the first
676 * unrecocnized non option is the beginning of the refs list
677 * that continues up to the -- (if exists), and then paths.
682 const char *arg
= argv
[1];
684 if (!strcmp("--cached", arg
)) {
688 if (!strcmp("-a", arg
) ||
689 !strcmp("--text", arg
)) {
690 opt
.binary
= GREP_BINARY_TEXT
;
693 if (!strcmp("-i", arg
) ||
694 !strcmp("--ignore-case", arg
)) {
695 opt
.regflags
|= REG_ICASE
;
698 if (!strcmp("-I", arg
)) {
699 opt
.binary
= GREP_BINARY_NOMATCH
;
702 if (!strcmp("-v", arg
) ||
703 !strcmp("--invert-match", arg
)) {
707 if (!strcmp("-E", arg
) ||
708 !strcmp("--extended-regexp", arg
)) {
709 opt
.regflags
|= REG_EXTENDED
;
712 if (!strcmp("-F", arg
) ||
713 !strcmp("--fixed-strings", arg
)) {
717 if (!strcmp("-G", arg
) ||
718 !strcmp("--basic-regexp", arg
)) {
719 opt
.regflags
&= ~REG_EXTENDED
;
722 if (!strcmp("-n", arg
)) {
726 if (!strcmp("-H", arg
)) {
727 /* We always show the pathname, so this
732 if (!strcmp("-l", arg
) ||
733 !strcmp("--files-with-matches", arg
)) {
737 if (!strcmp("-L", arg
) ||
738 !strcmp("--files-without-match", arg
)) {
739 opt
.unmatch_name_only
= 1;
742 if (!strcmp("-c", arg
) ||
743 !strcmp("--count", arg
)) {
747 if (!strcmp("-w", arg
) ||
748 !strcmp("--word-regexp", arg
)) {
752 if (!strncmp("-A", arg
, 2) ||
753 !strncmp("-B", arg
, 2) ||
754 !strncmp("-C", arg
, 2) ||
755 (arg
[0] == '-' && '1' <= arg
[1] && arg
[1] <= '9')) {
759 case 'A': case 'B': case 'C':
762 usage(builtin_grep_usage
);
773 if (sscanf(scan
, "%u", &num
) != 1)
774 usage(builtin_grep_usage
);
777 opt
.post_context
= num
;
781 opt
.post_context
= num
;
783 opt
.pre_context
= num
;
788 if (!strcmp("-f", arg
)) {
793 usage(builtin_grep_usage
);
794 patterns
= fopen(argv
[1], "r");
796 die("'%s': %s", argv
[1], strerror(errno
));
797 while (fgets(buf
, sizeof(buf
), patterns
)) {
798 int len
= strlen(buf
);
799 if (buf
[len
-1] == '\n')
801 /* ignore empty line like grep does */
804 add_pattern(&opt
, strdup(buf
), argv
[1], ++lno
);
811 if (!strcmp("-e", arg
)) {
813 add_pattern(&opt
, argv
[1], "-e option", 0);
818 usage(builtin_grep_usage
);
820 if (!strcmp("--", arg
))
823 usage(builtin_grep_usage
);
825 /* First unrecognized non-option token */
826 if (!opt
.pattern_list
) {
827 add_pattern(&opt
, arg
, "command line", 0);
831 /* We are looking at the first path or rev;
832 * it is found at argv[1] after leaving the
840 if (!opt
.pattern_list
)
841 die("no pattern given.");
842 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
843 die("cannot mix --fixed-strings and regexp");
845 compile_patterns(&opt
);
847 /* Check revs and then paths */
848 for (i
= 1; i
< argc
; i
++) {
849 const char *arg
= argv
[i
];
850 unsigned char sha1
[20];
852 if (!get_sha1(arg
, sha1
)) {
853 struct object
*object
= parse_object(sha1
);
854 struct object_list
*elem
;
856 die("bad object %s", arg
);
857 elem
= object_list_insert(object
, tail
);
862 if (!strcmp(arg
, "--")) {
869 /* The rest are paths */
870 if (!seen_dashdash
) {
872 for (j
= i
; j
< argc
; j
++)
873 verify_filename(prefix
, argv
[j
]);
877 paths
= get_pathspec(prefix
, argv
+ i
);
879 paths
= xcalloc(2, sizeof(const char *));
885 return !grep_cache(&opt
, paths
, cached
);
888 die("both --cached and trees are given.");
890 for (list
= object_list
; list
; list
= list
->next
) {
891 struct object
*real_obj
;
892 real_obj
= deref_tag(list
->item
, NULL
, 0);
893 if (grep_object(&opt
, paths
, real_obj
, list
->name
))