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
;
33 ((matchlen
<= namelen
) &&
34 !strncmp(name
, match
, matchlen
) &&
35 (match
[matchlen
-1] == '/' ||
36 name
[matchlen
] == '\0' || name
[matchlen
] == '/')))
38 if (!fnmatch(match
, name
, 0))
40 if (name
[namelen
-1] != '/')
43 /* We are being asked if the directory ("name") is worth
46 * Find the longest leading directory name that does
47 * not have metacharacter in the pathspec; the name
48 * we are looking at must overlap with that directory.
50 for (cp
= match
, meta
= NULL
; cp
- match
< matchlen
; cp
++) {
52 if (ch
== '*' || ch
== '[' || ch
== '?') {
58 meta
= cp
; /* fully literal */
60 if (namelen
<= meta
- match
) {
61 /* Looking at "Documentation/" and
62 * the pattern says "Documentation/howto/", or
63 * "Documentation/diff*.txt". The name we
64 * have should match prefix.
66 if (!memcmp(match
, name
, namelen
))
71 if (meta
- match
< namelen
) {
72 /* Looking at "Documentation/howto/" and
73 * the pattern says "Documentation/h*";
74 * match up to "Do.../h"; this avoids descending
75 * into "Documentation/technical/".
77 if (!memcmp(match
, name
, meta
- match
))
86 struct grep_pat
*next
;
94 struct grep_pat
*pattern_list
;
95 struct grep_pat
**pattern_tail
;
100 unsigned unmatch_name_only
:1;
102 unsigned word_regexp
:1;
104 #define GREP_BINARY_DEFAULT 0
105 #define GREP_BINARY_NOMATCH 1
106 #define GREP_BINARY_TEXT 2
109 unsigned pre_context
;
110 unsigned post_context
;
113 static void add_pattern(struct grep_opt
*opt
, const char *pat
,
114 const char *origin
, int no
)
116 struct grep_pat
*p
= xcalloc(1, sizeof(*p
));
120 *opt
->pattern_tail
= p
;
121 opt
->pattern_tail
= &p
->next
;
125 static void compile_patterns(struct grep_opt
*opt
)
128 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
129 int err
= regcomp(&p
->regexp
, p
->pattern
, opt
->regflags
);
134 sprintf(where
, "In '%s' at %d, ",
137 sprintf(where
, "%s, ", p
->origin
);
140 regerror(err
, &p
->regexp
, errbuf
, 1024);
142 die("%s'%s': %s", where
, p
->pattern
, errbuf
);
147 static char *end_of_line(char *cp
, unsigned long *left
)
149 unsigned long l
= *left
;
150 while (l
&& *cp
!= '\n') {
158 static int word_char(char ch
)
160 return isalnum(ch
) || ch
== '_';
163 static void show_line(struct grep_opt
*opt
, const char *bol
, const char *eol
,
164 const char *name
, unsigned lno
, char sign
)
166 printf("%s%c", name
, sign
);
168 printf("%d%c", lno
, sign
);
169 printf("%.*s\n", (int)(eol
-bol
), bol
);
173 * NEEDSWORK: share code with diff.c
175 #define FIRST_FEW_BYTES 8000
176 static int buffer_is_binary(const char *ptr
, unsigned long size
)
178 if (FIRST_FEW_BYTES
< size
)
179 size
= FIRST_FEW_BYTES
;
180 if (memchr(ptr
, 0, size
))
185 static int fixmatch(const char *pattern
, char *line
, regmatch_t
*match
)
187 char *hit
= strstr(line
, pattern
);
189 match
->rm_so
= match
->rm_eo
= -1;
193 match
->rm_so
= hit
- line
;
194 match
->rm_eo
= match
->rm_so
+ strlen(pattern
);
199 static int grep_buffer(struct grep_opt
*opt
, const char *name
,
200 char *buf
, unsigned long size
)
203 unsigned long left
= size
;
205 struct pre_context_line
{
208 } *prev
= NULL
, *pcl
;
209 unsigned last_hit
= 0;
210 unsigned last_shown
= 0;
211 int binary_match_only
= 0;
212 const char *hunk_mark
= "";
215 if (buffer_is_binary(buf
, size
)) {
216 switch (opt
->binary
) {
217 case GREP_BINARY_DEFAULT
:
218 binary_match_only
= 1;
220 case GREP_BINARY_NOMATCH
:
221 return 0; /* Assume unmatch */
228 if (opt
->pre_context
)
229 prev
= xcalloc(opt
->pre_context
, sizeof(*prev
));
230 if (opt
->pre_context
|| opt
->post_context
)
234 regmatch_t pmatch
[10];
239 eol
= end_of_line(bol
, &left
);
243 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
245 regex_t
*exp
= &p
->regexp
;
246 hit
= !regexec(exp
, bol
, ARRAY_SIZE(pmatch
),
250 hit
= !fixmatch(p
->pattern
, bol
, pmatch
);
253 if (hit
&& opt
->word_regexp
) {
254 /* Match beginning must be either
255 * beginning of the line, or at word
256 * boundary (i.e. the last char must
257 * not be alnum or underscore).
259 if ((pmatch
[0].rm_so
< 0) ||
260 (eol
- bol
) <= pmatch
[0].rm_so
||
261 (pmatch
[0].rm_eo
< 0) ||
262 (eol
- bol
) < pmatch
[0].rm_eo
)
263 die("regexp returned nonsense");
264 if (pmatch
[0].rm_so
!= 0 &&
265 word_char(bol
[pmatch
[0].rm_so
-1]))
267 if (pmatch
[0].rm_eo
!= (eol
-bol
) &&
268 word_char(bol
[pmatch
[0].rm_eo
]))
274 /* "grep -v -e foo -e bla" should list lines
275 * that do not have either, so inversion should
280 if (opt
->unmatch_name_only
) {
287 if (binary_match_only
) {
288 printf("Binary file %s matches\n", name
);
291 if (opt
->name_only
) {
292 printf("%s\n", name
);
295 /* Hit at this line. If we haven't shown the
296 * pre-context lines, we would need to show them.
297 * When asked to do "count", this still show
298 * the context which is nonsense, but the user
299 * deserves to get that ;-).
301 if (opt
->pre_context
) {
303 if (opt
->pre_context
< lno
)
304 from
= lno
- opt
->pre_context
;
307 if (from
<= last_shown
)
308 from
= last_shown
+ 1;
309 if (last_shown
&& from
!= last_shown
+ 1)
312 pcl
= &prev
[lno
-from
-1];
313 show_line(opt
, pcl
->bol
, pcl
->eol
,
319 if (last_shown
&& lno
!= last_shown
+ 1)
322 show_line(opt
, bol
, eol
, name
, lno
, ':');
323 last_shown
= last_hit
= lno
;
326 lno
<= last_hit
+ opt
->post_context
) {
327 /* If the last hit is within the post context,
328 * we need to show this line.
330 if (last_shown
&& lno
!= last_shown
+ 1)
332 show_line(opt
, bol
, eol
, name
, lno
, '-');
335 if (opt
->pre_context
) {
336 memmove(prev
+1, prev
,
337 (opt
->pre_context
-1) * sizeof(*prev
));
351 if (opt
->unmatch_name_only
) {
352 /* We did not see any hit, so we want to show this */
353 printf("%s\n", name
);
358 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
359 * which feels mostly useless but sometimes useful. Maybe
360 * make it another option? For now suppress them.
362 if (opt
->count
&& count
)
363 printf("%s:%u\n", name
, count
);
367 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
, const char *name
)
373 data
= read_sha1_file(sha1
, type
, &size
);
375 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
378 hit
= grep_buffer(opt
, name
, data
, size
);
383 static int grep_file(struct grep_opt
*opt
, const char *filename
)
388 if (lstat(filename
, &st
) < 0) {
391 error("'%s': %s", filename
, strerror(errno
));
395 return 0; /* empty file -- no grep hit */
396 if (!S_ISREG(st
.st_mode
))
398 i
= open(filename
, O_RDONLY
);
401 data
= xmalloc(st
.st_size
+ 1);
402 if (st
.st_size
!= xread(i
, data
, st
.st_size
)) {
403 error("'%s': short read %s", filename
, strerror(errno
));
409 i
= grep_buffer(opt
, filename
, data
, st
.st_size
);
414 static int exec_grep(int argc
, const char **argv
)
424 execvp("grep", (char **) argv
);
427 while (waitpid(pid
, &status
, 0) < 0) {
432 if (WIFEXITED(status
)) {
433 if (!WEXITSTATUS(status
))
442 #define push_arg(a) do { \
443 if (nr < MAXARGS) argv[nr++] = (a); \
444 else die("maximum number of args exceeded"); \
447 static int external_grep(struct grep_opt
*opt
, const char **paths
, int cached
)
449 int i
, nr
, argc
, hit
, len
, status
;
450 const char *argv
[MAXARGS
+1];
451 char randarg
[ARGBUF
];
452 char *argptr
= randarg
;
461 if (opt
->regflags
& REG_EXTENDED
)
463 if (opt
->regflags
& REG_ICASE
)
465 if (opt
->word_regexp
)
469 if (opt
->unmatch_name_only
)
473 if (opt
->post_context
|| opt
->pre_context
) {
474 if (opt
->post_context
!= opt
->pre_context
) {
475 if (opt
->pre_context
) {
477 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
478 "%u", opt
->pre_context
);
479 if (sizeof(randarg
) <= len
)
480 die("maximum length of args exceeded");
484 if (opt
->post_context
) {
486 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
487 "%u", opt
->post_context
);
488 if (sizeof(randarg
) <= len
)
489 die("maximum length of args exceeded");
496 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
497 "%u", opt
->post_context
);
498 if (sizeof(randarg
) <= len
)
499 die("maximum length of args exceeded");
504 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
506 push_arg(p
->pattern
);
510 * To make sure we get the header printed out when we want it,
511 * add /dev/null to the paths to grep. This is unnecessary
512 * (and wrong) with "-l" or "-L", which always print out the
515 * GNU grep has "-H", but this is portable.
517 if (!opt
->name_only
&& !opt
->unmatch_name_only
)
518 push_arg("/dev/null");
522 for (i
= 0; i
< active_nr
; i
++) {
523 struct cache_entry
*ce
= active_cache
[i
];
525 if (ce_stage(ce
) || !S_ISREG(ntohl(ce
->ce_mode
)))
527 if (!pathspec_matches(paths
, ce
->name
))
530 if (name
[0] == '-') {
531 int len
= ce_namelen(ce
);
532 name
= xmalloc(len
+ 3);
533 memcpy(name
, "./", 2);
534 memcpy(name
+ 2, ce
->name
, len
+ 1);
539 status
= exec_grep(argc
, argv
);
545 status
= exec_grep(argc
, argv
);
552 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
)
560 * Use the external "grep" command for the case where
561 * we grep through the checked-out files. It tends to
562 * be a lot more optimized
565 hit
= external_grep(opt
, paths
, cached
);
571 for (nr
= 0; nr
< active_nr
; nr
++) {
572 struct cache_entry
*ce
= active_cache
[nr
];
573 if (ce_stage(ce
) || !S_ISREG(ntohl(ce
->ce_mode
)))
575 if (!pathspec_matches(paths
, ce
->name
))
578 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
);
580 hit
|= grep_file(opt
, ce
->name
);
585 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
586 struct tree_desc
*tree
,
587 const char *tree_name
, const char *base
)
591 struct name_entry entry
;
593 char *path_buf
= xmalloc(PATH_MAX
+ strlen(tree_name
) + 100);
596 int offset
= sprintf(path_buf
, "%s:", tree_name
);
597 down
= path_buf
+ offset
;
604 len
= strlen(path_buf
);
606 while (tree_entry(tree
, &entry
)) {
607 strcpy(path_buf
+ len
, entry
.path
);
609 if (S_ISDIR(entry
.mode
))
610 /* Match "abc/" against pathspec to
611 * decide if we want to descend into "abc"
614 strcpy(path_buf
+ len
+ entry
.pathlen
, "/");
616 if (!pathspec_matches(paths
, down
))
618 else if (S_ISREG(entry
.mode
))
619 hit
|= grep_sha1(opt
, entry
.sha1
, path_buf
);
620 else if (S_ISDIR(entry
.mode
)) {
622 struct tree_desc sub
;
624 data
= read_sha1_file(entry
.sha1
, type
, &sub
.size
);
626 die("unable to read tree (%s)",
627 sha1_to_hex(entry
.sha1
));
629 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
636 static int grep_object(struct grep_opt
*opt
, const char **paths
,
637 struct object
*obj
, const char *name
)
639 if (obj
->type
== TYPE_BLOB
)
640 return grep_sha1(opt
, obj
->sha1
, name
);
641 if (obj
->type
== TYPE_COMMIT
|| obj
->type
== TYPE_TREE
) {
642 struct tree_desc tree
;
645 data
= read_object_with_reference(obj
->sha1
, tree_type
,
648 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
650 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
654 die("unable to grep from object of type %s", typename(obj
->type
));
657 static const char builtin_grep_usage
[] =
658 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
660 static const char emsg_invalid_context_len
[] =
661 "%s: invalid context length argument";
662 static const char emsg_missing_context_len
[] =
663 "missing context length argument";
664 static const char emsg_missing_argument
[] =
665 "option requires an argument -%s";
667 int cmd_grep(int argc
, const char **argv
, char **envp
)
671 int seen_dashdash
= 0;
673 struct object_array list
= { 0, 0, NULL
};
674 const char *prefix
= setup_git_directory();
675 const char **paths
= NULL
;
678 memset(&opt
, 0, sizeof(opt
));
679 opt
.pattern_tail
= &opt
.pattern_list
;
680 opt
.regflags
= REG_NEWLINE
;
683 * If there is no -- then the paths must exist in the working
684 * tree. If there is no explicit pattern specified with -e or
685 * -f, we take the first unrecognized non option to be the
686 * pattern, but then what follows it must be zero or more
687 * valid refs up to the -- (if exists), and then existing
688 * paths. If there is an explicit pattern, then the first
689 * unrecocnized non option is the beginning of the refs list
690 * that continues up to the -- (if exists), and then paths.
694 const char *arg
= argv
[1];
696 if (!strcmp("--cached", arg
)) {
700 if (!strcmp("-a", arg
) ||
701 !strcmp("--text", arg
)) {
702 opt
.binary
= GREP_BINARY_TEXT
;
705 if (!strcmp("-i", arg
) ||
706 !strcmp("--ignore-case", arg
)) {
707 opt
.regflags
|= REG_ICASE
;
710 if (!strcmp("-I", arg
)) {
711 opt
.binary
= GREP_BINARY_NOMATCH
;
714 if (!strcmp("-v", arg
) ||
715 !strcmp("--invert-match", arg
)) {
719 if (!strcmp("-E", arg
) ||
720 !strcmp("--extended-regexp", arg
)) {
721 opt
.regflags
|= REG_EXTENDED
;
724 if (!strcmp("-F", arg
) ||
725 !strcmp("--fixed-strings", arg
)) {
729 if (!strcmp("-G", arg
) ||
730 !strcmp("--basic-regexp", arg
)) {
731 opt
.regflags
&= ~REG_EXTENDED
;
734 if (!strcmp("-n", arg
)) {
738 if (!strcmp("-H", arg
)) {
739 /* We always show the pathname, so this
744 if (!strcmp("-l", arg
) ||
745 !strcmp("--files-with-matches", arg
)) {
749 if (!strcmp("-L", arg
) ||
750 !strcmp("--files-without-match", arg
)) {
751 opt
.unmatch_name_only
= 1;
754 if (!strcmp("-c", arg
) ||
755 !strcmp("--count", arg
)) {
759 if (!strcmp("-w", arg
) ||
760 !strcmp("--word-regexp", arg
)) {
764 if (!strncmp("-A", arg
, 2) ||
765 !strncmp("-B", arg
, 2) ||
766 !strncmp("-C", arg
, 2) ||
767 (arg
[0] == '-' && '1' <= arg
[1] && arg
[1] <= '9')) {
771 case 'A': case 'B': case 'C':
774 die(emsg_missing_context_len
);
785 if (sscanf(scan
, "%u", &num
) != 1)
786 die(emsg_invalid_context_len
, scan
);
789 opt
.post_context
= num
;
793 opt
.post_context
= num
;
795 opt
.pre_context
= num
;
800 if (!strcmp("-f", arg
)) {
805 die(emsg_missing_argument
, arg
);
806 patterns
= fopen(argv
[1], "r");
808 die("'%s': %s", argv
[1], strerror(errno
));
809 while (fgets(buf
, sizeof(buf
), patterns
)) {
810 int len
= strlen(buf
);
811 if (buf
[len
-1] == '\n')
813 /* ignore empty line like grep does */
816 add_pattern(&opt
, strdup(buf
), argv
[1], ++lno
);
823 if (!strcmp("-e", arg
)) {
825 add_pattern(&opt
, argv
[1], "-e option", 0);
830 die(emsg_missing_argument
, arg
);
832 if (!strcmp("--", arg
)) {
833 /* later processing wants to have this at argv[1] */
839 usage(builtin_grep_usage
);
841 /* First unrecognized non-option token */
842 if (!opt
.pattern_list
) {
843 add_pattern(&opt
, arg
, "command line", 0);
847 /* We are looking at the first path or rev;
848 * it is found at argv[1] after leaving the
856 if (!opt
.pattern_list
)
857 die("no pattern given.");
858 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
859 die("cannot mix --fixed-strings and regexp");
861 compile_patterns(&opt
);
863 /* Check revs and then paths */
864 for (i
= 1; i
< argc
; i
++) {
865 const char *arg
= argv
[i
];
866 unsigned char sha1
[20];
868 if (!get_sha1(arg
, sha1
)) {
869 struct object
*object
= parse_object(sha1
);
871 die("bad object %s", arg
);
872 add_object_array(object
, arg
, &list
);
875 if (!strcmp(arg
, "--")) {
882 /* The rest are paths */
883 if (!seen_dashdash
) {
885 for (j
= i
; j
< argc
; j
++)
886 verify_filename(prefix
, argv
[j
]);
890 paths
= get_pathspec(prefix
, argv
+ i
);
892 paths
= xcalloc(2, sizeof(const char *));
898 return !grep_cache(&opt
, paths
, cached
);
901 die("both --cached and trees are given.");
903 for (i
= 0; i
< list
.nr
; i
++) {
904 struct object
*real_obj
;
905 real_obj
= deref_tag(list
.objects
[i
].item
, NULL
, 0);
906 if (grep_object(&opt
, paths
, real_obj
, list
.objects
[i
].name
))