4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
13 #include "parse-options.h"
17 #ifndef NO_EXTERNAL_GREP
19 #define NO_EXTERNAL_GREP 0
21 #define NO_EXTERNAL_GREP 1
25 static char const * const grep_usage
[] = {
26 "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
30 static int grep_config(const char *var
, const char *value
, void *cb
)
32 struct grep_opt
*opt
= cb
;
34 switch (userdiff_config(var
, value
)) {
40 if (!strcmp(var
, "color.grep")) {
41 opt
->color
= git_config_colorbool(var
, value
, -1);
44 if (!strcmp(var
, "color.grep.external"))
45 return git_config_string(&(opt
->color_external
), var
, value
);
46 if (!strcmp(var
, "color.grep.match")) {
48 return config_error_nonbool(var
);
49 color_parse(value
, var
, opt
->color_match
);
52 return git_color_default_config(var
, value
, cb
);
56 * git grep pathspecs are somewhat different from diff-tree pathspecs;
57 * pathname wildcards are allowed.
59 static int pathspec_matches(const char **paths
, const char *name
)
62 if (!paths
|| !*paths
)
64 namelen
= strlen(name
);
65 for (i
= 0; paths
[i
]; i
++) {
66 const char *match
= paths
[i
];
67 int matchlen
= strlen(match
);
68 const char *cp
, *meta
;
71 ((matchlen
<= namelen
) &&
72 !strncmp(name
, match
, matchlen
) &&
73 (match
[matchlen
-1] == '/' ||
74 name
[matchlen
] == '\0' || name
[matchlen
] == '/')))
76 if (!fnmatch(match
, name
, 0))
78 if (name
[namelen
-1] != '/')
81 /* We are being asked if the directory ("name") is worth
84 * Find the longest leading directory name that does
85 * not have metacharacter in the pathspec; the name
86 * we are looking at must overlap with that directory.
88 for (cp
= match
, meta
= NULL
; cp
- match
< matchlen
; cp
++) {
90 if (ch
== '*' || ch
== '[' || ch
== '?') {
96 meta
= cp
; /* fully literal */
98 if (namelen
<= meta
- match
) {
99 /* Looking at "Documentation/" and
100 * the pattern says "Documentation/howto/", or
101 * "Documentation/diff*.txt". The name we
102 * have should match prefix.
104 if (!memcmp(match
, name
, namelen
))
109 if (meta
- match
< namelen
) {
110 /* Looking at "Documentation/howto/" and
111 * the pattern says "Documentation/h*";
112 * match up to "Do.../h"; this avoids descending
113 * into "Documentation/technical/".
115 if (!memcmp(match
, name
, meta
- match
))
123 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
, const char *name
, int tree_name_len
)
127 enum object_type type
;
128 char *to_free
= NULL
;
131 data
= read_sha1_file(sha1
, &type
, &size
);
133 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
136 if (opt
->relative
&& opt
->prefix_length
) {
137 static char name_buf
[PATH_MAX
];
139 int name_len
= strlen(name
) - opt
->prefix_length
+ 1;
142 name
+= opt
->prefix_length
;
144 if (ARRAY_SIZE(name_buf
) <= name_len
)
145 cp
= to_free
= xmalloc(name_len
);
148 memcpy(cp
, name
, tree_name_len
);
149 strcpy(cp
+ tree_name_len
,
150 name
+ tree_name_len
+ opt
->prefix_length
);
154 hit
= grep_buffer(opt
, name
, data
, size
);
160 static int grep_file(struct grep_opt
*opt
, const char *filename
)
167 if (lstat(filename
, &st
) < 0) {
170 error("'%s': %s", filename
, strerror(errno
));
174 return 0; /* empty file -- no grep hit */
175 if (!S_ISREG(st
.st_mode
))
177 sz
= xsize_t(st
.st_size
);
178 i
= open(filename
, O_RDONLY
);
181 data
= xmalloc(sz
+ 1);
182 if (st
.st_size
!= read_in_full(i
, data
, sz
)) {
183 error("'%s': short read %s", filename
, strerror(errno
));
189 if (opt
->relative
&& opt
->prefix_length
)
190 filename
+= opt
->prefix_length
;
191 i
= grep_buffer(opt
, filename
, data
, sz
);
196 #if !NO_EXTERNAL_GREP
197 static int exec_grep(int argc
, const char **argv
)
207 execvp("grep", (char **) argv
);
210 while (waitpid(pid
, &status
, 0) < 0) {
215 if (WIFEXITED(status
)) {
216 if (!WEXITSTATUS(status
))
225 #define push_arg(a) do { \
226 if (nr < MAXARGS) argv[nr++] = (a); \
227 else die("maximum number of args exceeded"); \
231 * If you send a singleton filename to grep, it does not give
232 * the name of the file. GNU grep has "-H" but we would want
233 * that behaviour in a portable way.
235 * So we keep two pathnames in argv buffer unsent to grep in
236 * the main loop if we need to do more than one grep.
238 static int flush_grep(struct grep_opt
*opt
,
239 int argc
, int arg0
, const char **argv
, int *kept
)
242 int count
= argc
- arg0
;
243 const char *kept_0
= NULL
;
247 * Because we keep at least 2 paths in the call from
248 * the main loop (i.e. kept != NULL), and MAXARGS is
249 * far greater than 2, this usually is a call to
250 * conclude the grep. However, the user could attempt
251 * to overflow the argv buffer by giving too many
252 * options to leave very small number of real
253 * arguments even for the call in the main loop.
256 die("insanely many options to grep");
259 * If we have two or more paths, we do not have to do
260 * anything special, but we need to push /dev/null to
261 * get "-H" behaviour of GNU grep portably but when we
262 * are not doing "-l" nor "-L" nor "-c".
266 !opt
->unmatch_name_only
&&
268 argv
[argc
++] = "/dev/null";
275 * Called because we found many paths and haven't finished
276 * iterating over the cache yet. We keep two paths
277 * for the concluding call. argv[argc-2] and argv[argc-1]
278 * has the last two paths, so save the first one away,
279 * replace it with NULL while sending the list to grep,
280 * and recover them after we are done.
283 kept_0
= argv
[argc
-2];
288 if (opt
->pre_context
|| opt
->post_context
) {
290 * grep handles hunk marks between files, but we need to
291 * do that ourselves between multiple calls.
293 if (opt
->show_hunk_mark
)
294 write_or_die(1, "--\n", 3);
296 opt
->show_hunk_mark
= 1;
299 status
= exec_grep(argc
, argv
);
303 * Then recover them. Now the last arg is beyond the
304 * terminating NULL which is at argc, and the second
305 * from the last is what we saved away in kept_0
307 argv
[arg0
++] = kept_0
;
308 argv
[arg0
] = argv
[argc
+1];
313 static void grep_add_color(struct strbuf
*sb
, const char *escape_seq
)
315 size_t orig_len
= sb
->len
;
317 while (*escape_seq
) {
318 if (*escape_seq
== 'm')
319 strbuf_addch(sb
, ';');
320 else if (*escape_seq
!= '\033' && *escape_seq
!= '[')
321 strbuf_addch(sb
, *escape_seq
);
324 if (sb
->len
> orig_len
&& sb
->buf
[sb
->len
- 1] == ';')
325 strbuf_setlen(sb
, sb
->len
- 1);
328 static int external_grep(struct grep_opt
*opt
, const char **paths
, int cached
)
330 int i
, nr
, argc
, hit
, len
, status
;
331 const char *argv
[MAXARGS
+1];
332 char randarg
[ARGBUF
];
333 char *argptr
= randarg
;
336 if (opt
->extended
|| (opt
->relative
&& opt
->prefix_length
))
346 if (opt
->regflags
& REG_EXTENDED
)
348 if (opt
->regflags
& REG_ICASE
)
350 if (opt
->binary
== GREP_BINARY_NOMATCH
)
352 if (opt
->word_regexp
)
356 if (opt
->unmatch_name_only
)
358 if (opt
->null_following_name
)
359 /* in GNU grep git's "-z" translates to "-Z" */
363 if (opt
->post_context
|| opt
->pre_context
) {
364 if (opt
->post_context
!= opt
->pre_context
) {
365 if (opt
->pre_context
) {
367 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
368 "%u", opt
->pre_context
) + 1;
369 if (sizeof(randarg
) <= len
)
370 die("maximum length of args exceeded");
374 if (opt
->post_context
) {
376 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
377 "%u", opt
->post_context
) + 1;
378 if (sizeof(randarg
) <= len
)
379 die("maximum length of args exceeded");
386 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
387 "%u", opt
->post_context
) + 1;
388 if (sizeof(randarg
) <= len
)
389 die("maximum length of args exceeded");
394 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
396 push_arg(p
->pattern
);
399 struct strbuf sb
= STRBUF_INIT
;
401 grep_add_color(&sb
, opt
->color_match
);
402 setenv("GREP_COLOR", sb
.buf
, 1);
405 strbuf_addstr(&sb
, "mt=");
406 grep_add_color(&sb
, opt
->color_match
);
407 strbuf_addstr(&sb
, ":sl=:cx=:fn=:ln=:bn=:se=");
408 setenv("GREP_COLORS", sb
.buf
, 1);
412 if (opt
->color_external
&& strlen(opt
->color_external
) > 0)
413 push_arg(opt
->color_external
);
418 for (i
= 0; i
< active_nr
; i
++) {
419 struct cache_entry
*ce
= active_cache
[i
];
422 if (!S_ISREG(ce
->ce_mode
))
424 if (!pathspec_matches(paths
, ce
->name
))
427 if (name
[0] == '-') {
428 int len
= ce_namelen(ce
);
429 name
= xmalloc(len
+ 3);
430 memcpy(name
, "./", 2);
431 memcpy(name
+ 2, ce
->name
, len
+ 1);
434 if (MAXARGS
<= argc
) {
435 status
= flush_grep(opt
, argc
, nr
, argv
, &kept
);
443 } while (i
< active_nr
&&
444 !strcmp(ce
->name
, active_cache
[i
]->name
));
445 i
--; /* compensate for loop control */
449 status
= flush_grep(opt
, argc
, nr
, argv
, NULL
);
457 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
,
458 int external_grep_allowed
)
464 #if !NO_EXTERNAL_GREP
466 * Use the external "grep" command for the case where
467 * we grep through the checked-out files. It tends to
468 * be a lot more optimized
470 if (!cached
&& external_grep_allowed
) {
471 hit
= external_grep(opt
, paths
, cached
);
477 for (nr
= 0; nr
< active_nr
; nr
++) {
478 struct cache_entry
*ce
= active_cache
[nr
];
479 if (!S_ISREG(ce
->ce_mode
))
481 if (!pathspec_matches(paths
, ce
->name
))
484 * If CE_VALID is on, we assume worktree file and its cache entry
485 * are identical, even if worktree file has been modified, so use
486 * cache version instead
488 if (cached
|| (ce
->ce_flags
& CE_VALID
)) {
491 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
, 0);
494 hit
|= grep_file(opt
, ce
->name
);
498 } while (nr
< active_nr
&&
499 !strcmp(ce
->name
, active_cache
[nr
]->name
));
500 nr
--; /* compensate for loop control */
503 free_grep_patterns(opt
);
507 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
508 struct tree_desc
*tree
,
509 const char *tree_name
, const char *base
)
513 struct name_entry entry
;
515 int tn_len
= strlen(tree_name
);
516 struct strbuf pathbuf
;
518 strbuf_init(&pathbuf
, PATH_MAX
+ tn_len
);
521 strbuf_add(&pathbuf
, tree_name
, tn_len
);
522 strbuf_addch(&pathbuf
, ':');
523 tn_len
= pathbuf
.len
;
525 strbuf_addstr(&pathbuf
, base
);
528 while (tree_entry(tree
, &entry
)) {
529 int te_len
= tree_entry_len(entry
.path
, entry
.sha1
);
531 strbuf_add(&pathbuf
, entry
.path
, te_len
);
533 if (S_ISDIR(entry
.mode
))
534 /* Match "abc/" against pathspec to
535 * decide if we want to descend into "abc"
538 strbuf_addch(&pathbuf
, '/');
540 down
= pathbuf
.buf
+ tn_len
;
541 if (!pathspec_matches(paths
, down
))
543 else if (S_ISREG(entry
.mode
))
544 hit
|= grep_sha1(opt
, entry
.sha1
, pathbuf
.buf
, tn_len
);
545 else if (S_ISDIR(entry
.mode
)) {
546 enum object_type type
;
547 struct tree_desc sub
;
551 data
= read_sha1_file(entry
.sha1
, &type
, &size
);
553 die("unable to read tree (%s)",
554 sha1_to_hex(entry
.sha1
));
555 init_tree_desc(&sub
, data
, size
);
556 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
560 strbuf_release(&pathbuf
);
564 static int grep_object(struct grep_opt
*opt
, const char **paths
,
565 struct object
*obj
, const char *name
)
567 if (obj
->type
== OBJ_BLOB
)
568 return grep_sha1(opt
, obj
->sha1
, name
, 0);
569 if (obj
->type
== OBJ_COMMIT
|| obj
->type
== OBJ_TREE
) {
570 struct tree_desc tree
;
574 data
= read_object_with_reference(obj
->sha1
, tree_type
,
577 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
578 init_tree_desc(&tree
, data
, size
);
579 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
583 die("unable to grep from object of type %s", typename(obj
->type
));
586 static int context_callback(const struct option
*opt
, const char *arg
,
589 struct grep_opt
*grep_opt
= opt
->value
;
594 grep_opt
->pre_context
= grep_opt
->post_context
= 0;
597 value
= strtol(arg
, (char **)&endp
, 10);
599 return error("switch `%c' expects a numerical value",
602 grep_opt
->pre_context
= grep_opt
->post_context
= value
;
606 static int file_callback(const struct option
*opt
, const char *arg
, int unset
)
608 struct grep_opt
*grep_opt
= opt
->value
;
613 patterns
= fopen(arg
, "r");
615 die_errno("cannot open '%s'", arg
);
616 while (strbuf_getline(&sb
, patterns
, '\n') == 0) {
617 /* ignore empty line like grep does */
620 append_grep_pattern(grep_opt
, strbuf_detach(&sb
, NULL
), arg
,
621 ++lno
, GREP_PATTERN
);
628 static int not_callback(const struct option
*opt
, const char *arg
, int unset
)
630 struct grep_opt
*grep_opt
= opt
->value
;
631 append_grep_pattern(grep_opt
, "--not", "command line", 0, GREP_NOT
);
635 static int and_callback(const struct option
*opt
, const char *arg
, int unset
)
637 struct grep_opt
*grep_opt
= opt
->value
;
638 append_grep_pattern(grep_opt
, "--and", "command line", 0, GREP_AND
);
642 static int open_callback(const struct option
*opt
, const char *arg
, int unset
)
644 struct grep_opt
*grep_opt
= opt
->value
;
645 append_grep_pattern(grep_opt
, "(", "command line", 0, GREP_OPEN_PAREN
);
649 static int close_callback(const struct option
*opt
, const char *arg
, int unset
)
651 struct grep_opt
*grep_opt
= opt
->value
;
652 append_grep_pattern(grep_opt
, ")", "command line", 0, GREP_CLOSE_PAREN
);
656 static int pattern_callback(const struct option
*opt
, const char *arg
,
659 struct grep_opt
*grep_opt
= opt
->value
;
660 append_grep_pattern(grep_opt
, arg
, "-e option", 0, GREP_PATTERN
);
664 static int help_callback(const struct option
*opt
, const char *arg
, int unset
)
669 int cmd_grep(int argc
, const char **argv
, const char *prefix
)
673 int external_grep_allowed
= 1;
674 int seen_dashdash
= 0;
676 struct object_array list
= { 0, 0, NULL
};
677 const char **paths
= NULL
;
680 struct option options
[] = {
681 OPT_BOOLEAN(0, "cached", &cached
,
682 "search in index instead of in the work tree"),
684 OPT_BOOLEAN('v', "invert-match", &opt
.invert
,
685 "show non-matching lines"),
686 OPT_BIT('i', "ignore-case", &opt
.regflags
,
687 "case insensitive matching", REG_ICASE
),
688 OPT_BOOLEAN('w', "word-regexp", &opt
.word_regexp
,
689 "match patterns only at word boundaries"),
690 OPT_SET_INT('a', "text", &opt
.binary
,
691 "process binary files as text", GREP_BINARY_TEXT
),
692 OPT_SET_INT('I', NULL
, &opt
.binary
,
693 "don't match patterns in binary files",
694 GREP_BINARY_NOMATCH
),
696 OPT_BIT('E', "extended-regexp", &opt
.regflags
,
697 "use extended POSIX regular expressions", REG_EXTENDED
),
698 OPT_NEGBIT('G', "basic-regexp", &opt
.regflags
,
699 "use basic POSIX regular expressions (default)",
701 OPT_BOOLEAN('F', "fixed-strings", &opt
.fixed
,
702 "interpret patterns as fixed strings"),
704 OPT_BOOLEAN('n', NULL
, &opt
.linenum
, "show line numbers"),
705 OPT_NEGBIT('h', NULL
, &opt
.pathname
, "don't show filenames", 1),
706 OPT_BIT('H', NULL
, &opt
.pathname
, "show filenames", 1),
707 OPT_NEGBIT(0, "full-name", &opt
.relative
,
708 "show filenames relative to top directory", 1),
709 OPT_BOOLEAN('l', "files-with-matches", &opt
.name_only
,
710 "show only filenames instead of matching lines"),
711 OPT_BOOLEAN(0, "name-only", &opt
.name_only
,
712 "synonym for --files-with-matches"),
713 OPT_BOOLEAN('L', "files-without-match",
714 &opt
.unmatch_name_only
,
715 "show only the names of files without match"),
716 OPT_BOOLEAN('z', "null", &opt
.null_following_name
,
717 "print NUL after filenames"),
718 OPT_BOOLEAN('c', "count", &opt
.count
,
719 "show the number of matches instead of matching lines"),
720 OPT_SET_INT(0, "color", &opt
.color
, "highlight matches", 1),
722 OPT_CALLBACK('C', NULL
, &opt
, "n",
723 "show <n> context lines before and after matches",
725 OPT_INTEGER('B', NULL
, &opt
.pre_context
,
726 "show <n> context lines before matches"),
727 OPT_INTEGER('A', NULL
, &opt
.post_context
,
728 "show <n> context lines after matches"),
729 OPT_NUMBER_CALLBACK(&opt
, "shortcut for -C NUM",
731 OPT_BOOLEAN('p', "show-function", &opt
.funcname
,
732 "show a line with the function name before matches"),
734 OPT_CALLBACK('f', NULL
, &opt
, "file",
735 "read patterns from file", file_callback
),
736 { OPTION_CALLBACK
, 'e', NULL
, &opt
, "pattern",
737 "match <pattern>", PARSE_OPT_NONEG
, pattern_callback
},
738 { OPTION_CALLBACK
, 0, "and", &opt
, NULL
,
739 "combine patterns specified with -e",
740 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, and_callback
},
741 OPT_BOOLEAN(0, "or", &dummy
, ""),
742 { OPTION_CALLBACK
, 0, "not", &opt
, NULL
, "",
743 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, not_callback
},
744 { OPTION_CALLBACK
, '(', NULL
, &opt
, NULL
, "",
745 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
| PARSE_OPT_NODASH
,
747 { OPTION_CALLBACK
, ')', NULL
, &opt
, NULL
, "",
748 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
| PARSE_OPT_NODASH
,
750 OPT_BOOLEAN(0, "all-match", &opt
.all_match
,
751 "show only matches from files that match all patterns"),
754 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed
,
755 "allow calling of grep(1) (ignored by this build)"),
757 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed
,
758 "allow calling of grep(1) (default)"),
760 { OPTION_CALLBACK
, 0, "help-all", &options
, NULL
, "show usage",
761 PARSE_OPT_HIDDEN
| PARSE_OPT_NOARG
, help_callback
},
765 memset(&opt
, 0, sizeof(opt
));
766 opt
.prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
769 opt
.pattern_tail
= &opt
.pattern_list
;
770 opt
.regflags
= REG_NEWLINE
;
772 strcpy(opt
.color_match
, GIT_COLOR_RED GIT_COLOR_BOLD
);
774 git_config(grep_config
, &opt
);
776 opt
.color
= git_use_color_default
;
779 * If there is no -- then the paths must exist in the working
780 * tree. If there is no explicit pattern specified with -e or
781 * -f, we take the first unrecognized non option to be the
782 * pattern, but then what follows it must be zero or more
783 * valid refs up to the -- (if exists), and then existing
784 * paths. If there is an explicit pattern, then the first
785 * unrecognized non option is the beginning of the refs list
786 * that continues up to the -- (if exists), and then paths.
788 argc
= parse_options(argc
, argv
, prefix
, options
, grep_usage
,
789 PARSE_OPT_KEEP_DASHDASH
|
790 PARSE_OPT_STOP_AT_NON_OPTION
|
791 PARSE_OPT_NO_INTERNAL_HELP
);
793 /* First unrecognized non-option token */
794 if (argc
> 0 && !opt
.pattern_list
) {
795 append_grep_pattern(&opt
, argv
[0], "command line", 0,
801 if ((opt
.color
&& !opt
.color_external
) || opt
.funcname
)
802 external_grep_allowed
= 0;
803 if (!opt
.pattern_list
)
804 die("no pattern given.");
805 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
806 die("cannot mix --fixed-strings and regexp");
807 compile_grep_patterns(&opt
);
809 /* Check revs and then paths */
810 for (i
= 0; i
< argc
; i
++) {
811 const char *arg
= argv
[i
];
812 unsigned char sha1
[20];
814 if (!get_sha1(arg
, sha1
)) {
815 struct object
*object
= parse_object(sha1
);
817 die("bad object %s", arg
);
818 add_object_array(object
, arg
, &list
);
821 if (!strcmp(arg
, "--")) {
828 /* The rest are paths */
829 if (!seen_dashdash
) {
831 for (j
= i
; j
< argc
; j
++)
832 verify_filename(prefix
, argv
[j
]);
836 paths
= get_pathspec(prefix
, argv
+ i
);
837 if (opt
.prefix_length
&& opt
.relative
) {
838 /* Make sure we do not get outside of paths */
839 for (i
= 0; paths
[i
]; i
++)
840 if (strncmp(prefix
, paths
[i
], opt
.prefix_length
))
841 die("git grep: cannot generate relative filenames containing '..'");
845 paths
= xcalloc(2, sizeof(const char *));
853 return !grep_cache(&opt
, paths
, cached
, external_grep_allowed
);
857 die("both --cached and trees are given.");
859 for (i
= 0; i
< list
.nr
; i
++) {
860 struct object
*real_obj
;
861 real_obj
= deref_tag(list
.objects
[i
].item
, NULL
, 0);
862 if (grep_object(&opt
, paths
, real_obj
, list
.objects
[i
].name
))
865 free_grep_patterns(&opt
);