4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
15 #ifndef NO_EXTERNAL_GREP
17 #define NO_EXTERNAL_GREP 0
19 #define NO_EXTERNAL_GREP 1
23 static int grep_config(const char *var
, const char *value
, void *cb
)
25 struct grep_opt
*opt
= cb
;
27 if (!strcmp(var
, "color.grep")) {
28 opt
->color
= git_config_colorbool(var
, value
, -1);
31 if (!strcmp(var
, "color.grep.external"))
32 return git_config_string(&(opt
->color_external
), var
, value
);
33 if (!strcmp(var
, "color.grep.match")) {
35 return config_error_nonbool(var
);
36 color_parse(value
, var
, opt
->color_match
);
39 return git_color_default_config(var
, value
, cb
);
43 * git grep pathspecs are somewhat different from diff-tree pathspecs;
44 * pathname wildcards are allowed.
46 static int pathspec_matches(const char **paths
, const char *name
)
49 if (!paths
|| !*paths
)
51 namelen
= strlen(name
);
52 for (i
= 0; paths
[i
]; i
++) {
53 const char *match
= paths
[i
];
54 int matchlen
= strlen(match
);
55 const char *cp
, *meta
;
58 ((matchlen
<= namelen
) &&
59 !strncmp(name
, match
, matchlen
) &&
60 (match
[matchlen
-1] == '/' ||
61 name
[matchlen
] == '\0' || name
[matchlen
] == '/')))
63 if (!fnmatch(match
, name
, 0))
65 if (name
[namelen
-1] != '/')
68 /* We are being asked if the directory ("name") is worth
71 * Find the longest leading directory name that does
72 * not have metacharacter in the pathspec; the name
73 * we are looking at must overlap with that directory.
75 for (cp
= match
, meta
= NULL
; cp
- match
< matchlen
; cp
++) {
77 if (ch
== '*' || ch
== '[' || ch
== '?') {
83 meta
= cp
; /* fully literal */
85 if (namelen
<= meta
- match
) {
86 /* Looking at "Documentation/" and
87 * the pattern says "Documentation/howto/", or
88 * "Documentation/diff*.txt". The name we
89 * have should match prefix.
91 if (!memcmp(match
, name
, namelen
))
96 if (meta
- match
< namelen
) {
97 /* Looking at "Documentation/howto/" and
98 * the pattern says "Documentation/h*";
99 * match up to "Do.../h"; this avoids descending
100 * into "Documentation/technical/".
102 if (!memcmp(match
, name
, meta
- match
))
110 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
, const char *name
, int tree_name_len
)
114 enum object_type type
;
115 char *to_free
= NULL
;
118 data
= read_sha1_file(sha1
, &type
, &size
);
120 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
123 if (opt
->relative
&& opt
->prefix_length
) {
124 static char name_buf
[PATH_MAX
];
126 int name_len
= strlen(name
) - opt
->prefix_length
+ 1;
129 name
+= opt
->prefix_length
;
131 if (ARRAY_SIZE(name_buf
) <= name_len
)
132 cp
= to_free
= xmalloc(name_len
);
135 memcpy(cp
, name
, tree_name_len
);
136 strcpy(cp
+ tree_name_len
,
137 name
+ tree_name_len
+ opt
->prefix_length
);
141 hit
= grep_buffer(opt
, name
, data
, size
);
147 static int grep_file(struct grep_opt
*opt
, const char *filename
)
154 if (lstat(filename
, &st
) < 0) {
157 error("'%s': %s", filename
, strerror(errno
));
161 return 0; /* empty file -- no grep hit */
162 if (!S_ISREG(st
.st_mode
))
164 sz
= xsize_t(st
.st_size
);
165 i
= open(filename
, O_RDONLY
);
168 data
= xmalloc(sz
+ 1);
169 if (st
.st_size
!= read_in_full(i
, data
, sz
)) {
170 error("'%s': short read %s", filename
, strerror(errno
));
176 if (opt
->relative
&& opt
->prefix_length
)
177 filename
+= opt
->prefix_length
;
178 i
= grep_buffer(opt
, filename
, data
, sz
);
183 #if !NO_EXTERNAL_GREP
184 static int exec_grep(int argc
, const char **argv
)
194 execvp("grep", (char **) argv
);
197 while (waitpid(pid
, &status
, 0) < 0) {
202 if (WIFEXITED(status
)) {
203 if (!WEXITSTATUS(status
))
212 #define push_arg(a) do { \
213 if (nr < MAXARGS) argv[nr++] = (a); \
214 else die("maximum number of args exceeded"); \
218 * If you send a singleton filename to grep, it does not give
219 * the name of the file. GNU grep has "-H" but we would want
220 * that behaviour in a portable way.
222 * So we keep two pathnames in argv buffer unsent to grep in
223 * the main loop if we need to do more than one grep.
225 static int flush_grep(struct grep_opt
*opt
,
226 int argc
, int arg0
, const char **argv
, int *kept
)
229 int count
= argc
- arg0
;
230 const char *kept_0
= NULL
;
234 * Because we keep at least 2 paths in the call from
235 * the main loop (i.e. kept != NULL), and MAXARGS is
236 * far greater than 2, this usually is a call to
237 * conclude the grep. However, the user could attempt
238 * to overflow the argv buffer by giving too many
239 * options to leave very small number of real
240 * arguments even for the call in the main loop.
243 die("insanely many options to grep");
246 * If we have two or more paths, we do not have to do
247 * anything special, but we need to push /dev/null to
248 * get "-H" behaviour of GNU grep portably but when we
249 * are not doing "-l" nor "-L" nor "-c".
253 !opt
->unmatch_name_only
&&
255 argv
[argc
++] = "/dev/null";
262 * Called because we found many paths and haven't finished
263 * iterating over the cache yet. We keep two paths
264 * for the concluding call. argv[argc-2] and argv[argc-1]
265 * has the last two paths, so save the first one away,
266 * replace it with NULL while sending the list to grep,
267 * and recover them after we are done.
270 kept_0
= argv
[argc
-2];
275 status
= exec_grep(argc
, argv
);
279 * Then recover them. Now the last arg is beyond the
280 * terminating NULL which is at argc, and the second
281 * from the last is what we saved away in kept_0
283 argv
[arg0
++] = kept_0
;
284 argv
[arg0
] = argv
[argc
+1];
289 static void grep_add_color(struct strbuf
*sb
, const char *escape_seq
)
291 size_t orig_len
= sb
->len
;
293 while (*escape_seq
) {
294 if (*escape_seq
== 'm')
295 strbuf_addch(sb
, ';');
296 else if (*escape_seq
!= '\033' && *escape_seq
!= '[')
297 strbuf_addch(sb
, *escape_seq
);
300 if (sb
->len
> orig_len
&& sb
->buf
[sb
->len
- 1] == ';')
301 strbuf_setlen(sb
, sb
->len
- 1);
304 static int external_grep(struct grep_opt
*opt
, const char **paths
, int cached
)
306 int i
, nr
, argc
, hit
, len
, status
;
307 const char *argv
[MAXARGS
+1];
308 char randarg
[ARGBUF
];
309 char *argptr
= randarg
;
312 if (opt
->extended
|| (opt
->relative
&& opt
->prefix_length
))
322 if (opt
->regflags
& REG_EXTENDED
)
324 if (opt
->regflags
& REG_ICASE
)
326 if (opt
->binary
== GREP_BINARY_NOMATCH
)
328 if (opt
->word_regexp
)
332 if (opt
->unmatch_name_only
)
334 if (opt
->null_following_name
)
335 /* in GNU grep git's "-z" translates to "-Z" */
339 if (opt
->post_context
|| opt
->pre_context
) {
340 if (opt
->post_context
!= opt
->pre_context
) {
341 if (opt
->pre_context
) {
343 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
344 "%u", opt
->pre_context
) + 1;
345 if (sizeof(randarg
) <= len
)
346 die("maximum length of args exceeded");
350 if (opt
->post_context
) {
352 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
353 "%u", opt
->post_context
) + 1;
354 if (sizeof(randarg
) <= len
)
355 die("maximum length of args exceeded");
362 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
363 "%u", opt
->post_context
) + 1;
364 if (sizeof(randarg
) <= len
)
365 die("maximum length of args exceeded");
370 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
372 push_arg(p
->pattern
);
375 struct strbuf sb
= STRBUF_INIT
;
377 grep_add_color(&sb
, opt
->color_match
);
378 setenv("GREP_COLOR", sb
.buf
, 1);
381 strbuf_addstr(&sb
, "mt=");
382 grep_add_color(&sb
, opt
->color_match
);
383 strbuf_addstr(&sb
, ":sl=:cx=:fn=:ln=:bn=:se=");
384 setenv("GREP_COLORS", sb
.buf
, 1);
388 if (opt
->color_external
&& strlen(opt
->color_external
) > 0)
389 push_arg(opt
->color_external
);
394 for (i
= 0; i
< active_nr
; i
++) {
395 struct cache_entry
*ce
= active_cache
[i
];
398 if (!S_ISREG(ce
->ce_mode
))
400 if (!pathspec_matches(paths
, ce
->name
))
403 if (name
[0] == '-') {
404 int len
= ce_namelen(ce
);
405 name
= xmalloc(len
+ 3);
406 memcpy(name
, "./", 2);
407 memcpy(name
+ 2, ce
->name
, len
+ 1);
410 if (MAXARGS
<= argc
) {
411 status
= flush_grep(opt
, argc
, nr
, argv
, &kept
);
419 } while (i
< active_nr
&&
420 !strcmp(ce
->name
, active_cache
[i
]->name
));
421 i
--; /* compensate for loop control */
425 status
= flush_grep(opt
, argc
, nr
, argv
, NULL
);
433 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
,
434 int external_grep_allowed
)
440 #if !NO_EXTERNAL_GREP
442 * Use the external "grep" command for the case where
443 * we grep through the checked-out files. It tends to
444 * be a lot more optimized
446 if (!cached
&& external_grep_allowed
) {
447 hit
= external_grep(opt
, paths
, cached
);
453 for (nr
= 0; nr
< active_nr
; nr
++) {
454 struct cache_entry
*ce
= active_cache
[nr
];
455 if (!S_ISREG(ce
->ce_mode
))
457 if (!pathspec_matches(paths
, ce
->name
))
460 * If CE_VALID is on, we assume worktree file and its cache entry
461 * are identical, even if worktree file has been modified, so use
462 * cache version instead
464 if (cached
|| (ce
->ce_flags
& CE_VALID
)) {
467 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
, 0);
470 hit
|= grep_file(opt
, ce
->name
);
474 } while (nr
< active_nr
&&
475 !strcmp(ce
->name
, active_cache
[nr
]->name
));
476 nr
--; /* compensate for loop control */
479 free_grep_patterns(opt
);
483 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
484 struct tree_desc
*tree
,
485 const char *tree_name
, const char *base
)
489 struct name_entry entry
;
491 int tn_len
= strlen(tree_name
);
492 struct strbuf pathbuf
;
494 strbuf_init(&pathbuf
, PATH_MAX
+ tn_len
);
497 strbuf_add(&pathbuf
, tree_name
, tn_len
);
498 strbuf_addch(&pathbuf
, ':');
499 tn_len
= pathbuf
.len
;
501 strbuf_addstr(&pathbuf
, base
);
504 while (tree_entry(tree
, &entry
)) {
505 int te_len
= tree_entry_len(entry
.path
, entry
.sha1
);
507 strbuf_add(&pathbuf
, entry
.path
, te_len
);
509 if (S_ISDIR(entry
.mode
))
510 /* Match "abc/" against pathspec to
511 * decide if we want to descend into "abc"
514 strbuf_addch(&pathbuf
, '/');
516 down
= pathbuf
.buf
+ tn_len
;
517 if (!pathspec_matches(paths
, down
))
519 else if (S_ISREG(entry
.mode
))
520 hit
|= grep_sha1(opt
, entry
.sha1
, pathbuf
.buf
, tn_len
);
521 else if (S_ISDIR(entry
.mode
)) {
522 enum object_type type
;
523 struct tree_desc sub
;
527 data
= read_sha1_file(entry
.sha1
, &type
, &size
);
529 die("unable to read tree (%s)",
530 sha1_to_hex(entry
.sha1
));
531 init_tree_desc(&sub
, data
, size
);
532 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
536 strbuf_release(&pathbuf
);
540 static int grep_object(struct grep_opt
*opt
, const char **paths
,
541 struct object
*obj
, const char *name
)
543 if (obj
->type
== OBJ_BLOB
)
544 return grep_sha1(opt
, obj
->sha1
, name
, 0);
545 if (obj
->type
== OBJ_COMMIT
|| obj
->type
== OBJ_TREE
) {
546 struct tree_desc tree
;
550 data
= read_object_with_reference(obj
->sha1
, tree_type
,
553 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
554 init_tree_desc(&tree
, data
, size
);
555 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
559 die("unable to grep from object of type %s", typename(obj
->type
));
562 static const char builtin_grep_usage
[] =
563 "git grep <option>* [-e] <pattern> <rev>* [[--] <path>...]";
565 static const char emsg_invalid_context_len
[] =
566 "%s: invalid context length argument";
567 static const char emsg_missing_context_len
[] =
568 "missing context length argument";
569 static const char emsg_missing_argument
[] =
570 "option requires an argument -%s";
572 int cmd_grep(int argc
, const char **argv
, const char *prefix
)
576 int external_grep_allowed
= 1;
577 int seen_dashdash
= 0;
579 struct object_array list
= { 0, 0, NULL
};
580 const char **paths
= NULL
;
583 memset(&opt
, 0, sizeof(opt
));
584 opt
.prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
587 opt
.pattern_tail
= &opt
.pattern_list
;
588 opt
.regflags
= REG_NEWLINE
;
590 strcpy(opt
.color_match
, GIT_COLOR_RED GIT_COLOR_BOLD
);
592 git_config(grep_config
, &opt
);
594 opt
.color
= git_use_color_default
;
597 * If there is no -- then the paths must exist in the working
598 * tree. If there is no explicit pattern specified with -e or
599 * -f, we take the first unrecognized non option to be the
600 * pattern, but then what follows it must be zero or more
601 * valid refs up to the -- (if exists), and then existing
602 * paths. If there is an explicit pattern, then the first
603 * unrecognized non option is the beginning of the refs list
604 * that continues up to the -- (if exists), and then paths.
608 const char *arg
= argv
[1];
610 if (!strcmp("--cached", arg
)) {
614 if (!strcmp("--no-ext-grep", arg
)) {
615 external_grep_allowed
= 0;
618 if (!strcmp("-a", arg
) ||
619 !strcmp("--text", arg
)) {
620 opt
.binary
= GREP_BINARY_TEXT
;
623 if (!strcmp("-i", arg
) ||
624 !strcmp("--ignore-case", arg
)) {
625 opt
.regflags
|= REG_ICASE
;
628 if (!strcmp("-I", arg
)) {
629 opt
.binary
= GREP_BINARY_NOMATCH
;
632 if (!strcmp("-v", arg
) ||
633 !strcmp("--invert-match", arg
)) {
637 if (!strcmp("-E", arg
) ||
638 !strcmp("--extended-regexp", arg
)) {
639 opt
.regflags
|= REG_EXTENDED
;
642 if (!strcmp("-F", arg
) ||
643 !strcmp("--fixed-strings", arg
)) {
647 if (!strcmp("-G", arg
) ||
648 !strcmp("--basic-regexp", arg
)) {
649 opt
.regflags
&= ~REG_EXTENDED
;
652 if (!strcmp("-n", arg
)) {
656 if (!strcmp("-h", arg
)) {
660 if (!strcmp("-H", arg
)) {
664 if (!strcmp("-l", arg
) ||
665 !strcmp("--name-only", arg
) ||
666 !strcmp("--files-with-matches", arg
)) {
670 if (!strcmp("-L", arg
) ||
671 !strcmp("--files-without-match", arg
)) {
672 opt
.unmatch_name_only
= 1;
675 if (!strcmp("-z", arg
) ||
676 !strcmp("--null", arg
)) {
677 opt
.null_following_name
= 1;
680 if (!strcmp("-c", arg
) ||
681 !strcmp("--count", arg
)) {
685 if (!strcmp("-w", arg
) ||
686 !strcmp("--word-regexp", arg
)) {
690 if (!prefixcmp(arg
, "-A") ||
691 !prefixcmp(arg
, "-B") ||
692 !prefixcmp(arg
, "-C") ||
693 (arg
[0] == '-' && '1' <= arg
[1] && arg
[1] <= '9')) {
697 case 'A': case 'B': case 'C':
700 die(emsg_missing_context_len
);
711 if (strtoul_ui(scan
, 10, &num
))
712 die(emsg_invalid_context_len
, scan
);
715 opt
.post_context
= num
;
719 opt
.post_context
= num
;
721 opt
.pre_context
= num
;
726 if (!strcmp("-f", arg
)) {
731 die(emsg_missing_argument
, arg
);
732 patterns
= fopen(argv
[1], "r");
734 die("'%s': %s", argv
[1], strerror(errno
));
735 while (fgets(buf
, sizeof(buf
), patterns
)) {
736 int len
= strlen(buf
);
737 if (len
&& buf
[len
-1] == '\n')
739 /* ignore empty line like grep does */
742 append_grep_pattern(&opt
, xstrdup(buf
),
751 if (!strcmp("--not", arg
)) {
752 append_grep_pattern(&opt
, arg
, "command line", 0,
756 if (!strcmp("--and", arg
)) {
757 append_grep_pattern(&opt
, arg
, "command line", 0,
761 if (!strcmp("--or", arg
))
762 continue; /* no-op */
763 if (!strcmp("(", arg
)) {
764 append_grep_pattern(&opt
, arg
, "command line", 0,
768 if (!strcmp(")", arg
)) {
769 append_grep_pattern(&opt
, arg
, "command line", 0,
773 if (!strcmp("--all-match", arg
)) {
777 if (!strcmp("-e", arg
)) {
779 append_grep_pattern(&opt
, argv
[1],
786 die(emsg_missing_argument
, arg
);
788 if (!strcmp("--full-name", arg
)) {
792 if (!strcmp("--color", arg
)) {
796 if (!strcmp("--no-color", arg
)) {
800 if (!strcmp("--", arg
)) {
801 /* later processing wants to have this at argv[1] */
807 usage(builtin_grep_usage
);
809 /* First unrecognized non-option token */
810 if (!opt
.pattern_list
) {
811 append_grep_pattern(&opt
, arg
, "command line", 0,
816 /* We are looking at the first path or rev;
817 * it is found at argv[1] after leaving the
825 if (opt
.color
&& !opt
.color_external
)
826 external_grep_allowed
= 0;
827 if (!opt
.pattern_list
)
828 die("no pattern given.");
829 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
830 die("cannot mix --fixed-strings and regexp");
831 compile_grep_patterns(&opt
);
833 /* Check revs and then paths */
834 for (i
= 1; i
< argc
; i
++) {
835 const char *arg
= argv
[i
];
836 unsigned char sha1
[20];
838 if (!get_sha1(arg
, sha1
)) {
839 struct object
*object
= parse_object(sha1
);
841 die("bad object %s", arg
);
842 add_object_array(object
, arg
, &list
);
845 if (!strcmp(arg
, "--")) {
852 /* The rest are paths */
853 if (!seen_dashdash
) {
855 for (j
= i
; j
< argc
; j
++)
856 verify_filename(prefix
, argv
[j
]);
860 paths
= get_pathspec(prefix
, argv
+ i
);
861 if (opt
.prefix_length
&& opt
.relative
) {
862 /* Make sure we do not get outside of paths */
863 for (i
= 0; paths
[i
]; i
++)
864 if (strncmp(prefix
, paths
[i
], opt
.prefix_length
))
865 die("git grep: cannot generate relative filenames containing '..'");
869 paths
= xcalloc(2, sizeof(const char *));
877 return !grep_cache(&opt
, paths
, cached
, external_grep_allowed
);
881 die("both --cached and trees are given.");
883 for (i
= 0; i
< list
.nr
; i
++) {
884 struct object
*real_obj
;
885 real_obj
= deref_tag(list
.objects
[i
].item
, NULL
, 0);
886 if (grep_object(&opt
, paths
, real_obj
, list
.objects
[i
].name
))
889 free_grep_patterns(&opt
);