4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
13 #include "parse-options.h"
19 static char const * const grep_usage
[] = {
20 "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
24 static int grep_config(const char *var
, const char *value
, void *cb
)
26 struct grep_opt
*opt
= cb
;
28 switch (userdiff_config(var
, value
)) {
34 if (!strcmp(var
, "color.grep")) {
35 opt
->color
= git_config_colorbool(var
, value
, -1);
38 if (!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 * Return non-zero if max_depth is negative or path has no more then max_depth
51 static int accept_subdir(const char *path
, int max_depth
)
56 while ((path
= strchr(path
, '/')) != NULL
) {
66 * Return non-zero if name is a subdirectory of match and is not too deep.
68 static int is_subdir(const char *name
, int namelen
,
69 const char *match
, int matchlen
, int max_depth
)
71 if (matchlen
> namelen
|| strncmp(name
, match
, matchlen
))
74 if (name
[matchlen
] == '\0') /* exact match */
77 if (!matchlen
|| match
[matchlen
-1] == '/' || name
[matchlen
] == '/')
78 return accept_subdir(name
+ matchlen
+ 1, max_depth
);
84 * git grep pathspecs are somewhat different from diff-tree pathspecs;
85 * pathname wildcards are allowed.
87 static int pathspec_matches(const char **paths
, const char *name
, int max_depth
)
90 if (!paths
|| !*paths
)
91 return accept_subdir(name
, max_depth
);
92 namelen
= strlen(name
);
93 for (i
= 0; paths
[i
]; i
++) {
94 const char *match
= paths
[i
];
95 int matchlen
= strlen(match
);
96 const char *cp
, *meta
;
98 if (is_subdir(name
, namelen
, match
, matchlen
, max_depth
))
100 if (!fnmatch(match
, name
, 0))
102 if (name
[namelen
-1] != '/')
105 /* We are being asked if the directory ("name") is worth
108 * Find the longest leading directory name that does
109 * not have metacharacter in the pathspec; the name
110 * we are looking at must overlap with that directory.
112 for (cp
= match
, meta
= NULL
; cp
- match
< matchlen
; cp
++) {
114 if (ch
== '*' || ch
== '[' || ch
== '?') {
120 meta
= cp
; /* fully literal */
122 if (namelen
<= meta
- match
) {
123 /* Looking at "Documentation/" and
124 * the pattern says "Documentation/howto/", or
125 * "Documentation/diff*.txt". The name we
126 * have should match prefix.
128 if (!memcmp(match
, name
, namelen
))
133 if (meta
- match
< namelen
) {
134 /* Looking at "Documentation/howto/" and
135 * the pattern says "Documentation/h*";
136 * match up to "Do.../h"; this avoids descending
137 * into "Documentation/technical/".
139 if (!memcmp(match
, name
, meta
- match
))
147 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
, const char *name
, int tree_name_len
)
151 enum object_type type
;
153 struct strbuf pathbuf
= STRBUF_INIT
;
155 data
= read_sha1_file(sha1
, &type
, &size
);
157 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
160 if (opt
->relative
&& opt
->prefix_length
) {
161 quote_path_relative(name
+ tree_name_len
, -1, &pathbuf
, opt
->prefix
);
162 strbuf_insert(&pathbuf
, 0, name
, tree_name_len
);
165 hit
= grep_buffer(opt
, name
, data
, size
);
166 strbuf_release(&pathbuf
);
171 static int grep_file(struct grep_opt
*opt
, const char *filename
)
177 struct strbuf buf
= STRBUF_INIT
;
179 if (lstat(filename
, &st
) < 0) {
182 error("'%s': %s", filename
, strerror(errno
));
185 if (!S_ISREG(st
.st_mode
))
187 sz
= xsize_t(st
.st_size
);
188 i
= open(filename
, O_RDONLY
);
191 data
= xmalloc(sz
+ 1);
192 if (st
.st_size
!= read_in_full(i
, data
, sz
)) {
193 error("'%s': short read %s", filename
, strerror(errno
));
200 if (opt
->relative
&& opt
->prefix_length
)
201 filename
= quote_path_relative(filename
, -1, &buf
, opt
->prefix
);
202 i
= grep_buffer(opt
, filename
, data
, sz
);
203 strbuf_release(&buf
);
208 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
)
214 for (nr
= 0; nr
< active_nr
; nr
++) {
215 struct cache_entry
*ce
= active_cache
[nr
];
216 if (!S_ISREG(ce
->ce_mode
))
218 if (!pathspec_matches(paths
, ce
->name
, opt
->max_depth
))
221 * If CE_VALID is on, we assume worktree file and its cache entry
222 * are identical, even if worktree file has been modified, so use
223 * cache version instead
225 if (cached
|| (ce
->ce_flags
& CE_VALID
) || ce_skip_worktree(ce
)) {
228 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
, 0);
231 hit
|= grep_file(opt
, ce
->name
);
235 } while (nr
< active_nr
&&
236 !strcmp(ce
->name
, active_cache
[nr
]->name
));
237 nr
--; /* compensate for loop control */
240 free_grep_patterns(opt
);
244 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
245 struct tree_desc
*tree
,
246 const char *tree_name
, const char *base
)
250 struct name_entry entry
;
252 int tn_len
= strlen(tree_name
);
253 struct strbuf pathbuf
;
255 strbuf_init(&pathbuf
, PATH_MAX
+ tn_len
);
258 strbuf_add(&pathbuf
, tree_name
, tn_len
);
259 strbuf_addch(&pathbuf
, ':');
260 tn_len
= pathbuf
.len
;
262 strbuf_addstr(&pathbuf
, base
);
265 while (tree_entry(tree
, &entry
)) {
266 int te_len
= tree_entry_len(entry
.path
, entry
.sha1
);
268 strbuf_add(&pathbuf
, entry
.path
, te_len
);
270 if (S_ISDIR(entry
.mode
))
271 /* Match "abc/" against pathspec to
272 * decide if we want to descend into "abc"
275 strbuf_addch(&pathbuf
, '/');
277 down
= pathbuf
.buf
+ tn_len
;
278 if (!pathspec_matches(paths
, down
, opt
->max_depth
))
280 else if (S_ISREG(entry
.mode
))
281 hit
|= grep_sha1(opt
, entry
.sha1
, pathbuf
.buf
, tn_len
);
282 else if (S_ISDIR(entry
.mode
)) {
283 enum object_type type
;
284 struct tree_desc sub
;
288 data
= read_sha1_file(entry
.sha1
, &type
, &size
);
290 die("unable to read tree (%s)",
291 sha1_to_hex(entry
.sha1
));
292 init_tree_desc(&sub
, data
, size
);
293 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
297 strbuf_release(&pathbuf
);
301 static int grep_object(struct grep_opt
*opt
, const char **paths
,
302 struct object
*obj
, const char *name
)
304 if (obj
->type
== OBJ_BLOB
)
305 return grep_sha1(opt
, obj
->sha1
, name
, 0);
306 if (obj
->type
== OBJ_COMMIT
|| obj
->type
== OBJ_TREE
) {
307 struct tree_desc tree
;
311 data
= read_object_with_reference(obj
->sha1
, tree_type
,
314 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
315 init_tree_desc(&tree
, data
, size
);
316 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
320 die("unable to grep from object of type %s", typename(obj
->type
));
323 static int grep_directory(struct grep_opt
*opt
, const char **paths
)
325 struct dir_struct dir
;
328 memset(&dir
, 0, sizeof(dir
));
329 setup_standard_excludes(&dir
);
331 fill_directory(&dir
, paths
);
332 for (i
= 0; i
< dir
.nr
; i
++)
333 hit
|= grep_file(opt
, dir
.entries
[i
]->name
);
334 free_grep_patterns(opt
);
338 static int context_callback(const struct option
*opt
, const char *arg
,
341 struct grep_opt
*grep_opt
= opt
->value
;
346 grep_opt
->pre_context
= grep_opt
->post_context
= 0;
349 value
= strtol(arg
, (char **)&endp
, 10);
351 return error("switch `%c' expects a numerical value",
354 grep_opt
->pre_context
= grep_opt
->post_context
= value
;
358 static int file_callback(const struct option
*opt
, const char *arg
, int unset
)
360 struct grep_opt
*grep_opt
= opt
->value
;
363 struct strbuf sb
= STRBUF_INIT
;
365 patterns
= fopen(arg
, "r");
367 die_errno("cannot open '%s'", arg
);
368 while (strbuf_getline(&sb
, patterns
, '\n') == 0) {
369 /* ignore empty line like grep does */
372 append_grep_pattern(grep_opt
, strbuf_detach(&sb
, NULL
), arg
,
373 ++lno
, GREP_PATTERN
);
380 static int not_callback(const struct option
*opt
, const char *arg
, int unset
)
382 struct grep_opt
*grep_opt
= opt
->value
;
383 append_grep_pattern(grep_opt
, "--not", "command line", 0, GREP_NOT
);
387 static int and_callback(const struct option
*opt
, const char *arg
, int unset
)
389 struct grep_opt
*grep_opt
= opt
->value
;
390 append_grep_pattern(grep_opt
, "--and", "command line", 0, GREP_AND
);
394 static int open_callback(const struct option
*opt
, const char *arg
, int unset
)
396 struct grep_opt
*grep_opt
= opt
->value
;
397 append_grep_pattern(grep_opt
, "(", "command line", 0, GREP_OPEN_PAREN
);
401 static int close_callback(const struct option
*opt
, const char *arg
, int unset
)
403 struct grep_opt
*grep_opt
= opt
->value
;
404 append_grep_pattern(grep_opt
, ")", "command line", 0, GREP_CLOSE_PAREN
);
408 static int pattern_callback(const struct option
*opt
, const char *arg
,
411 struct grep_opt
*grep_opt
= opt
->value
;
412 append_grep_pattern(grep_opt
, arg
, "-e option", 0, GREP_PATTERN
);
416 static int help_callback(const struct option
*opt
, const char *arg
, int unset
)
421 int cmd_grep(int argc
, const char **argv
, const char *prefix
)
425 int seen_dashdash
= 0;
426 int external_grep_allowed__ignored
;
428 struct object_array list
= { 0, 0, NULL
};
429 const char **paths
= NULL
;
432 int nongit
= 0, use_index
= 1;
433 struct option options
[] = {
434 OPT_BOOLEAN(0, "cached", &cached
,
435 "search in index instead of in the work tree"),
436 OPT_BOOLEAN(0, "index", &use_index
,
437 "--no-index finds in contents not managed by git"),
439 OPT_BOOLEAN('v', "invert-match", &opt
.invert
,
440 "show non-matching lines"),
441 OPT_BOOLEAN('i', "ignore-case", &opt
.ignore_case
,
442 "case insensitive matching"),
443 OPT_BOOLEAN('w', "word-regexp", &opt
.word_regexp
,
444 "match patterns only at word boundaries"),
445 OPT_SET_INT('a', "text", &opt
.binary
,
446 "process binary files as text", GREP_BINARY_TEXT
),
447 OPT_SET_INT('I', NULL
, &opt
.binary
,
448 "don't match patterns in binary files",
449 GREP_BINARY_NOMATCH
),
450 { OPTION_INTEGER
, 0, "max-depth", &opt
.max_depth
, "depth",
451 "descend at most <depth> levels", PARSE_OPT_NONEG
,
454 OPT_BIT('E', "extended-regexp", &opt
.regflags
,
455 "use extended POSIX regular expressions", REG_EXTENDED
),
456 OPT_NEGBIT('G', "basic-regexp", &opt
.regflags
,
457 "use basic POSIX regular expressions (default)",
459 OPT_BOOLEAN('F', "fixed-strings", &opt
.fixed
,
460 "interpret patterns as fixed strings"),
462 OPT_BOOLEAN('n', NULL
, &opt
.linenum
, "show line numbers"),
463 OPT_NEGBIT('h', NULL
, &opt
.pathname
, "don't show filenames", 1),
464 OPT_BIT('H', NULL
, &opt
.pathname
, "show filenames", 1),
465 OPT_NEGBIT(0, "full-name", &opt
.relative
,
466 "show filenames relative to top directory", 1),
467 OPT_BOOLEAN('l', "files-with-matches", &opt
.name_only
,
468 "show only filenames instead of matching lines"),
469 OPT_BOOLEAN(0, "name-only", &opt
.name_only
,
470 "synonym for --files-with-matches"),
471 OPT_BOOLEAN('L', "files-without-match",
472 &opt
.unmatch_name_only
,
473 "show only the names of files without match"),
474 OPT_BOOLEAN('z', "null", &opt
.null_following_name
,
475 "print NUL after filenames"),
476 OPT_BOOLEAN('c', "count", &opt
.count
,
477 "show the number of matches instead of matching lines"),
478 OPT_SET_INT(0, "color", &opt
.color
, "highlight matches", 1),
480 OPT_CALLBACK('C', NULL
, &opt
, "n",
481 "show <n> context lines before and after matches",
483 OPT_INTEGER('B', NULL
, &opt
.pre_context
,
484 "show <n> context lines before matches"),
485 OPT_INTEGER('A', NULL
, &opt
.post_context
,
486 "show <n> context lines after matches"),
487 OPT_NUMBER_CALLBACK(&opt
, "shortcut for -C NUM",
489 OPT_BOOLEAN('p', "show-function", &opt
.funcname
,
490 "show a line with the function name before matches"),
492 OPT_CALLBACK('f', NULL
, &opt
, "file",
493 "read patterns from file", file_callback
),
494 { OPTION_CALLBACK
, 'e', NULL
, &opt
, "pattern",
495 "match <pattern>", PARSE_OPT_NONEG
, pattern_callback
},
496 { OPTION_CALLBACK
, 0, "and", &opt
, NULL
,
497 "combine patterns specified with -e",
498 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, and_callback
},
499 OPT_BOOLEAN(0, "or", &dummy
, ""),
500 { OPTION_CALLBACK
, 0, "not", &opt
, NULL
, "",
501 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, not_callback
},
502 { OPTION_CALLBACK
, '(', NULL
, &opt
, NULL
, "",
503 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
| PARSE_OPT_NODASH
,
505 { OPTION_CALLBACK
, ')', NULL
, &opt
, NULL
, "",
506 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
| PARSE_OPT_NODASH
,
508 OPT_BOOLEAN(0, "all-match", &opt
.all_match
,
509 "show only matches from files that match all patterns"),
511 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored
,
512 "allow calling of grep(1) (ignored by this build)"),
513 { OPTION_CALLBACK
, 0, "help-all", &options
, NULL
, "show usage",
514 PARSE_OPT_HIDDEN
| PARSE_OPT_NOARG
, help_callback
},
518 prefix
= setup_git_directory_gently(&nongit
);
521 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
522 * to show usage information and exit.
524 if (argc
== 2 && !strcmp(argv
[1], "-h"))
525 usage_with_options(grep_usage
, options
);
527 memset(&opt
, 0, sizeof(opt
));
529 opt
.prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
532 opt
.pattern_tail
= &opt
.pattern_list
;
533 opt
.regflags
= REG_NEWLINE
;
536 strcpy(opt
.color_match
, GIT_COLOR_RED GIT_COLOR_BOLD
);
538 git_config(grep_config
, &opt
);
540 opt
.color
= git_use_color_default
;
543 * If there is no -- then the paths must exist in the working
544 * tree. If there is no explicit pattern specified with -e or
545 * -f, we take the first unrecognized non option to be the
546 * pattern, but then what follows it must be zero or more
547 * valid refs up to the -- (if exists), and then existing
548 * paths. If there is an explicit pattern, then the first
549 * unrecognized non option is the beginning of the refs list
550 * that continues up to the -- (if exists), and then paths.
552 argc
= parse_options(argc
, argv
, prefix
, options
, grep_usage
,
553 PARSE_OPT_KEEP_DASHDASH
|
554 PARSE_OPT_STOP_AT_NON_OPTION
|
555 PARSE_OPT_NO_INTERNAL_HELP
);
557 if (use_index
&& nongit
)
558 /* die the same way as if we did it at the beginning */
559 setup_git_directory();
561 /* First unrecognized non-option token */
562 if (argc
> 0 && !opt
.pattern_list
) {
563 append_grep_pattern(&opt
, argv
[0], "command line", 0,
569 if (!opt
.pattern_list
)
570 die("no pattern given.");
571 if (!opt
.fixed
&& opt
.ignore_case
)
572 opt
.regflags
|= REG_ICASE
;
573 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
574 die("cannot mix --fixed-strings and regexp");
575 compile_grep_patterns(&opt
);
577 /* Check revs and then paths */
578 for (i
= 0; i
< argc
; i
++) {
579 const char *arg
= argv
[i
];
580 unsigned char sha1
[20];
582 if (!get_sha1(arg
, sha1
)) {
583 struct object
*object
= parse_object(sha1
);
585 die("bad object %s", arg
);
586 add_object_array(object
, arg
, &list
);
589 if (!strcmp(arg
, "--")) {
596 /* The rest are paths */
597 if (!seen_dashdash
) {
599 for (j
= i
; j
< argc
; j
++)
600 verify_filename(prefix
, argv
[j
]);
604 paths
= get_pathspec(prefix
, argv
+ i
);
606 paths
= xcalloc(2, sizeof(const char *));
613 die("--cached cannot be used with --no-index.");
615 die("--no-index cannot be used with revs.");
616 return !grep_directory(&opt
, paths
);
622 return !grep_cache(&opt
, paths
, cached
);
626 die("both --cached and trees are given.");
628 for (i
= 0; i
< list
.nr
; i
++) {
629 struct object
*real_obj
;
630 real_obj
= deref_tag(list
.objects
[i
].item
, NULL
, 0);
631 if (grep_object(&opt
, paths
, real_obj
, list
.objects
[i
].name
))
634 free_grep_patterns(&opt
);