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 builtin_grep
;
25 static int grep_config(const char *var
, const char *value
, void *cb
)
27 struct grep_opt
*opt
= cb
;
29 if (!strcmp(var
, "grep.color") || !strcmp(var
, "color.grep")) {
30 opt
->color
= git_config_colorbool(var
, value
, -1);
33 if (!strcmp(var
, "grep.color.external") ||
34 !strcmp(var
, "color.grep.external")) {
35 return git_config_string(&(opt
->color_external
), var
, value
);
37 if (!strcmp(var
, "grep.color.match") ||
38 !strcmp(var
, "color.grep.match")) {
40 return config_error_nonbool(var
);
41 color_parse(value
, var
, opt
->color_match
);
44 return git_color_default_config(var
, value
, cb
);
48 * git grep pathspecs are somewhat different from diff-tree pathspecs;
49 * pathname wildcards are allowed.
51 static int pathspec_matches(const char **paths
, const char *name
)
54 if (!paths
|| !*paths
)
56 namelen
= strlen(name
);
57 for (i
= 0; paths
[i
]; i
++) {
58 const char *match
= paths
[i
];
59 int matchlen
= strlen(match
);
60 const char *cp
, *meta
;
63 ((matchlen
<= namelen
) &&
64 !strncmp(name
, match
, matchlen
) &&
65 (match
[matchlen
-1] == '/' ||
66 name
[matchlen
] == '\0' || name
[matchlen
] == '/')))
68 if (!fnmatch(match
, name
, 0))
70 if (name
[namelen
-1] != '/')
73 /* We are being asked if the directory ("name") is worth
76 * Find the longest leading directory name that does
77 * not have metacharacter in the pathspec; the name
78 * we are looking at must overlap with that directory.
80 for (cp
= match
, meta
= NULL
; cp
- match
< matchlen
; cp
++) {
82 if (ch
== '*' || ch
== '[' || ch
== '?') {
88 meta
= cp
; /* fully literal */
90 if (namelen
<= meta
- match
) {
91 /* Looking at "Documentation/" and
92 * the pattern says "Documentation/howto/", or
93 * "Documentation/diff*.txt". The name we
94 * have should match prefix.
96 if (!memcmp(match
, name
, namelen
))
101 if (meta
- match
< namelen
) {
102 /* Looking at "Documentation/howto/" and
103 * the pattern says "Documentation/h*";
104 * match up to "Do.../h"; this avoids descending
105 * into "Documentation/technical/".
107 if (!memcmp(match
, name
, meta
- match
))
115 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
, const char *name
, int tree_name_len
)
119 enum object_type type
;
120 char *to_free
= NULL
;
123 data
= read_sha1_file(sha1
, &type
, &size
);
125 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
128 if (opt
->relative
&& opt
->prefix_length
) {
129 static char name_buf
[PATH_MAX
];
131 int name_len
= strlen(name
) - opt
->prefix_length
+ 1;
134 name
+= opt
->prefix_length
;
136 if (ARRAY_SIZE(name_buf
) <= name_len
)
137 cp
= to_free
= xmalloc(name_len
);
140 memcpy(cp
, name
, tree_name_len
);
141 strcpy(cp
+ tree_name_len
,
142 name
+ tree_name_len
+ opt
->prefix_length
);
146 hit
= grep_buffer(opt
, name
, data
, size
);
152 static int grep_file(struct grep_opt
*opt
, const char *filename
)
159 if (lstat(filename
, &st
) < 0) {
162 error("'%s': %s", filename
, strerror(errno
));
166 return 0; /* empty file -- no grep hit */
167 if (!S_ISREG(st
.st_mode
))
169 sz
= xsize_t(st
.st_size
);
170 i
= open(filename
, O_RDONLY
);
173 data
= xmalloc(sz
+ 1);
174 if (st
.st_size
!= read_in_full(i
, data
, sz
)) {
175 error("'%s': short read %s", filename
, strerror(errno
));
181 if (opt
->relative
&& opt
->prefix_length
)
182 filename
+= opt
->prefix_length
;
183 i
= grep_buffer(opt
, filename
, data
, sz
);
188 #if !NO_EXTERNAL_GREP
189 static int exec_grep(int argc
, const char **argv
)
199 execvp("grep", (char **) argv
);
202 while (waitpid(pid
, &status
, 0) < 0) {
207 if (WIFEXITED(status
)) {
208 if (!WEXITSTATUS(status
))
217 #define push_arg(a) do { \
218 if (nr < MAXARGS) argv[nr++] = (a); \
219 else die("maximum number of args exceeded"); \
223 * If you send a singleton filename to grep, it does not give
224 * the name of the file. GNU grep has "-H" but we would want
225 * that behaviour in a portable way.
227 * So we keep two pathnames in argv buffer unsent to grep in
228 * the main loop if we need to do more than one grep.
230 static int flush_grep(struct grep_opt
*opt
,
231 int argc
, int arg0
, const char **argv
, int *kept
)
234 int count
= argc
- arg0
;
235 const char *kept_0
= NULL
;
239 * Because we keep at least 2 paths in the call from
240 * the main loop (i.e. kept != NULL), and MAXARGS is
241 * far greater than 2, this usually is a call to
242 * conclude the grep. However, the user could attempt
243 * to overflow the argv buffer by giving too many
244 * options to leave very small number of real
245 * arguments even for the call in the main loop.
248 die("insanely many options to grep");
251 * If we have two or more paths, we do not have to do
252 * anything special, but we need to push /dev/null to
253 * get "-H" behaviour of GNU grep portably but when we
254 * are not doing "-l" nor "-L" nor "-c".
258 !opt
->unmatch_name_only
&&
260 argv
[argc
++] = "/dev/null";
267 * Called because we found many paths and haven't finished
268 * iterating over the cache yet. We keep two paths
269 * for the concluding call. argv[argc-2] and argv[argc-1]
270 * has the last two paths, so save the first one away,
271 * replace it with NULL while sending the list to grep,
272 * and recover them after we are done.
275 kept_0
= argv
[argc
-2];
280 status
= exec_grep(argc
, argv
);
284 * Then recover them. Now the last arg is beyond the
285 * terminating NULL which is at argc, and the second
286 * from the last is what we saved away in kept_0
288 argv
[arg0
++] = kept_0
;
289 argv
[arg0
] = argv
[argc
+1];
294 static void grep_add_color(struct strbuf
*sb
, const char *escape_seq
)
296 size_t orig_len
= sb
->len
;
298 while (*escape_seq
) {
299 if (*escape_seq
== 'm')
300 strbuf_addch(sb
, ';');
301 else if (*escape_seq
!= '\033' && *escape_seq
!= '[')
302 strbuf_addch(sb
, *escape_seq
);
305 if (sb
->len
> orig_len
&& sb
->buf
[sb
->len
- 1] == ';')
306 strbuf_setlen(sb
, sb
->len
- 1);
309 static int external_grep(struct grep_opt
*opt
, const char **paths
, int cached
)
311 int i
, nr
, argc
, hit
, len
, status
;
312 const char *argv
[MAXARGS
+1];
313 char randarg
[ARGBUF
];
314 char *argptr
= randarg
;
317 if (opt
->extended
|| (opt
->relative
&& opt
->prefix_length
))
327 if (opt
->regflags
& REG_EXTENDED
)
329 if (opt
->regflags
& REG_ICASE
)
331 if (opt
->binary
== GREP_BINARY_NOMATCH
)
333 if (opt
->word_regexp
)
337 if (opt
->unmatch_name_only
)
339 if (opt
->null_following_name
)
340 /* in GNU grep git's "-z" translates to "-Z" */
344 if (opt
->post_context
|| opt
->pre_context
) {
345 if (opt
->post_context
!= opt
->pre_context
) {
346 if (opt
->pre_context
) {
348 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
349 "%u", opt
->pre_context
) + 1;
350 if (sizeof(randarg
) <= len
)
351 die("maximum length of args exceeded");
355 if (opt
->post_context
) {
357 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
358 "%u", opt
->post_context
) + 1;
359 if (sizeof(randarg
) <= len
)
360 die("maximum length of args exceeded");
367 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
368 "%u", opt
->post_context
) + 1;
369 if (sizeof(randarg
) <= len
)
370 die("maximum length of args exceeded");
375 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
377 push_arg(p
->pattern
);
380 struct strbuf sb
= STRBUF_INIT
;
382 grep_add_color(&sb
, opt
->color_match
);
383 setenv("GREP_COLOR", sb
.buf
, 1);
386 strbuf_addstr(&sb
, "mt=");
387 grep_add_color(&sb
, opt
->color_match
);
388 strbuf_addstr(&sb
, ":sl=:cx=:fn=:ln=:bn=:se=");
389 setenv("GREP_COLORS", sb
.buf
, 1);
393 if (opt
->color_external
&& strlen(opt
->color_external
) > 0)
394 push_arg(opt
->color_external
);
399 for (i
= 0; i
< active_nr
; i
++) {
400 struct cache_entry
*ce
= active_cache
[i
];
403 if (!S_ISREG(ce
->ce_mode
))
405 if (!pathspec_matches(paths
, ce
->name
))
408 if (name
[0] == '-') {
409 int len
= ce_namelen(ce
);
410 name
= xmalloc(len
+ 3);
411 memcpy(name
, "./", 2);
412 memcpy(name
+ 2, ce
->name
, len
+ 1);
415 if (MAXARGS
<= argc
) {
416 status
= flush_grep(opt
, argc
, nr
, argv
, &kept
);
424 } while (i
< active_nr
&&
425 !strcmp(ce
->name
, active_cache
[i
]->name
));
426 i
--; /* compensate for loop control */
430 status
= flush_grep(opt
, argc
, nr
, argv
, NULL
);
438 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
)
444 #if !NO_EXTERNAL_GREP
446 * Use the external "grep" command for the case where
447 * we grep through the checked-out files. It tends to
448 * be a lot more optimized
450 if (!cached
&& !builtin_grep
) {
451 hit
= external_grep(opt
, paths
, cached
);
457 for (nr
= 0; nr
< active_nr
; nr
++) {
458 struct cache_entry
*ce
= active_cache
[nr
];
459 if (!S_ISREG(ce
->ce_mode
))
461 if (!pathspec_matches(paths
, ce
->name
))
464 * If CE_VALID is on, we assume worktree file and its cache entry
465 * are identical, even if worktree file has been modified, so use
466 * cache version instead
468 if (cached
|| (ce
->ce_flags
& CE_VALID
)) {
471 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
, 0);
474 hit
|= grep_file(opt
, ce
->name
);
478 } while (nr
< active_nr
&&
479 !strcmp(ce
->name
, active_cache
[nr
]->name
));
480 nr
--; /* compensate for loop control */
483 free_grep_patterns(opt
);
487 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
488 struct tree_desc
*tree
,
489 const char *tree_name
, const char *base
)
493 struct name_entry entry
;
495 int tn_len
= strlen(tree_name
);
496 struct strbuf pathbuf
;
498 strbuf_init(&pathbuf
, PATH_MAX
+ tn_len
);
501 strbuf_add(&pathbuf
, tree_name
, tn_len
);
502 strbuf_addch(&pathbuf
, ':');
503 tn_len
= pathbuf
.len
;
505 strbuf_addstr(&pathbuf
, base
);
508 while (tree_entry(tree
, &entry
)) {
509 int te_len
= tree_entry_len(entry
.path
, entry
.sha1
);
511 strbuf_add(&pathbuf
, entry
.path
, te_len
);
513 if (S_ISDIR(entry
.mode
))
514 /* Match "abc/" against pathspec to
515 * decide if we want to descend into "abc"
518 strbuf_addch(&pathbuf
, '/');
520 down
= pathbuf
.buf
+ tn_len
;
521 if (!pathspec_matches(paths
, down
))
523 else if (S_ISREG(entry
.mode
))
524 hit
|= grep_sha1(opt
, entry
.sha1
, pathbuf
.buf
, tn_len
);
525 else if (S_ISDIR(entry
.mode
)) {
526 enum object_type type
;
527 struct tree_desc sub
;
531 data
= read_sha1_file(entry
.sha1
, &type
, &size
);
533 die("unable to read tree (%s)",
534 sha1_to_hex(entry
.sha1
));
535 init_tree_desc(&sub
, data
, size
);
536 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
540 strbuf_release(&pathbuf
);
544 static int grep_object(struct grep_opt
*opt
, const char **paths
,
545 struct object
*obj
, const char *name
)
547 if (obj
->type
== OBJ_BLOB
)
548 return grep_sha1(opt
, obj
->sha1
, name
, 0);
549 if (obj
->type
== OBJ_COMMIT
|| obj
->type
== OBJ_TREE
) {
550 struct tree_desc tree
;
554 data
= read_object_with_reference(obj
->sha1
, tree_type
,
557 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
558 init_tree_desc(&tree
, data
, size
);
559 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
563 die("unable to grep from object of type %s", typename(obj
->type
));
566 static const char builtin_grep_usage
[] =
567 "git grep <option>* [-e] <pattern> <rev>* [[--] <path>...]";
569 static const char emsg_invalid_context_len
[] =
570 "%s: invalid context length argument";
571 static const char emsg_missing_context_len
[] =
572 "missing context length argument";
573 static const char emsg_missing_argument
[] =
574 "option requires an argument -%s";
576 int cmd_grep(int argc
, const char **argv
, const char *prefix
)
580 int seen_dashdash
= 0;
582 struct object_array list
= { 0, 0, NULL
};
583 const char **paths
= NULL
;
586 memset(&opt
, 0, sizeof(opt
));
587 opt
.prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
590 opt
.pattern_tail
= &opt
.pattern_list
;
591 opt
.regflags
= REG_NEWLINE
;
593 strcpy(opt
.color_match
, GIT_COLOR_RED GIT_COLOR_BOLD
);
595 git_config(grep_config
, &opt
);
597 opt
.color
= git_use_color_default
;
600 * If there is no -- then the paths must exist in the working
601 * tree. If there is no explicit pattern specified with -e or
602 * -f, we take the first unrecognized non option to be the
603 * pattern, but then what follows it must be zero or more
604 * valid refs up to the -- (if exists), and then existing
605 * paths. If there is an explicit pattern, then the first
606 * unrecognized non option is the beginning of the refs list
607 * that continues up to the -- (if exists), and then paths.
611 const char *arg
= argv
[1];
613 if (!strcmp("--cached", arg
)) {
617 if (!strcmp("--no-ext-grep", arg
)) {
621 if (!strcmp("-a", arg
) ||
622 !strcmp("--text", arg
)) {
623 opt
.binary
= GREP_BINARY_TEXT
;
626 if (!strcmp("-i", arg
) ||
627 !strcmp("--ignore-case", arg
)) {
628 opt
.regflags
|= REG_ICASE
;
631 if (!strcmp("-I", arg
)) {
632 opt
.binary
= GREP_BINARY_NOMATCH
;
635 if (!strcmp("-v", arg
) ||
636 !strcmp("--invert-match", arg
)) {
640 if (!strcmp("-E", arg
) ||
641 !strcmp("--extended-regexp", arg
)) {
642 opt
.regflags
|= REG_EXTENDED
;
645 if (!strcmp("-F", arg
) ||
646 !strcmp("--fixed-strings", arg
)) {
650 if (!strcmp("-G", arg
) ||
651 !strcmp("--basic-regexp", arg
)) {
652 opt
.regflags
&= ~REG_EXTENDED
;
655 if (!strcmp("-n", arg
)) {
659 if (!strcmp("-h", arg
)) {
663 if (!strcmp("-H", arg
)) {
667 if (!strcmp("-l", arg
) ||
668 !strcmp("--name-only", arg
) ||
669 !strcmp("--files-with-matches", arg
)) {
673 if (!strcmp("-L", arg
) ||
674 !strcmp("--files-without-match", arg
)) {
675 opt
.unmatch_name_only
= 1;
678 if (!strcmp("-z", arg
) ||
679 !strcmp("--null", arg
)) {
680 opt
.null_following_name
= 1;
683 if (!strcmp("-c", arg
) ||
684 !strcmp("--count", arg
)) {
688 if (!strcmp("-w", arg
) ||
689 !strcmp("--word-regexp", arg
)) {
693 if (!prefixcmp(arg
, "-A") ||
694 !prefixcmp(arg
, "-B") ||
695 !prefixcmp(arg
, "-C") ||
696 (arg
[0] == '-' && '1' <= arg
[1] && arg
[1] <= '9')) {
700 case 'A': case 'B': case 'C':
703 die(emsg_missing_context_len
);
714 if (strtoul_ui(scan
, 10, &num
))
715 die(emsg_invalid_context_len
, scan
);
718 opt
.post_context
= num
;
722 opt
.post_context
= num
;
724 opt
.pre_context
= num
;
729 if (!strcmp("-f", arg
)) {
734 die(emsg_missing_argument
, arg
);
735 patterns
= fopen(argv
[1], "r");
737 die("'%s': %s", argv
[1], strerror(errno
));
738 while (fgets(buf
, sizeof(buf
), patterns
)) {
739 int len
= strlen(buf
);
740 if (len
&& buf
[len
-1] == '\n')
742 /* ignore empty line like grep does */
745 append_grep_pattern(&opt
, xstrdup(buf
),
754 if (!strcmp("--not", arg
)) {
755 append_grep_pattern(&opt
, arg
, "command line", 0,
759 if (!strcmp("--and", arg
)) {
760 append_grep_pattern(&opt
, arg
, "command line", 0,
764 if (!strcmp("--or", arg
))
765 continue; /* no-op */
766 if (!strcmp("(", arg
)) {
767 append_grep_pattern(&opt
, arg
, "command line", 0,
771 if (!strcmp(")", arg
)) {
772 append_grep_pattern(&opt
, arg
, "command line", 0,
776 if (!strcmp("--all-match", arg
)) {
780 if (!strcmp("-e", arg
)) {
782 append_grep_pattern(&opt
, argv
[1],
789 die(emsg_missing_argument
, arg
);
791 if (!strcmp("--full-name", arg
)) {
795 if (!strcmp("--color", arg
)) {
799 if (!strcmp("--no-color", arg
)) {
803 if (!strcmp("--", arg
)) {
804 /* later processing wants to have this at argv[1] */
810 usage(builtin_grep_usage
);
812 /* First unrecognized non-option token */
813 if (!opt
.pattern_list
) {
814 append_grep_pattern(&opt
, arg
, "command line", 0,
819 /* We are looking at the first path or rev;
820 * it is found at argv[1] after leaving the
828 if (opt
.color
&& !opt
.color_external
)
830 if (!opt
.pattern_list
)
831 die("no pattern given.");
832 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
833 die("cannot mix --fixed-strings and regexp");
834 compile_grep_patterns(&opt
);
836 /* Check revs and then paths */
837 for (i
= 1; i
< argc
; i
++) {
838 const char *arg
= argv
[i
];
839 unsigned char sha1
[20];
841 if (!get_sha1(arg
, sha1
)) {
842 struct object
*object
= parse_object(sha1
);
844 die("bad object %s", arg
);
845 add_object_array(object
, arg
, &list
);
848 if (!strcmp(arg
, "--")) {
855 /* The rest are paths */
856 if (!seen_dashdash
) {
858 for (j
= i
; j
< argc
; j
++)
859 verify_filename(prefix
, argv
[j
]);
863 paths
= get_pathspec(prefix
, argv
+ i
);
864 if (opt
.prefix_length
&& opt
.relative
) {
865 /* Make sure we do not get outside of paths */
866 for (i
= 0; paths
[i
]; i
++)
867 if (strncmp(prefix
, paths
[i
], opt
.prefix_length
))
868 die("git grep: cannot generate relative filenames containing '..'");
872 paths
= xcalloc(2, sizeof(const char *));
880 return !grep_cache(&opt
, paths
, cached
);
884 die("both --cached and trees are given.");
886 for (i
= 0; i
< list
.nr
; i
++) {
887 struct object
*real_obj
;
888 real_obj
= deref_tag(list
.objects
[i
].item
, NULL
, 0);
889 if (grep_object(&opt
, paths
, real_obj
, list
.objects
[i
].name
))
892 free_grep_patterns(&opt
);