4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
16 * git grep pathspecs are somewhat different from diff-tree pathspecs;
17 * pathname wildcards are allowed.
19 static int pathspec_matches(const char **paths
, const char *name
)
22 if (!paths
|| !*paths
)
24 namelen
= strlen(name
);
25 for (i
= 0; paths
[i
]; i
++) {
26 const char *match
= paths
[i
];
27 int matchlen
= strlen(match
);
28 const char *cp
, *meta
;
31 ((matchlen
<= namelen
) &&
32 !strncmp(name
, match
, matchlen
) &&
33 (match
[matchlen
-1] == '/' ||
34 name
[matchlen
] == '\0' || name
[matchlen
] == '/')))
36 if (!fnmatch(match
, name
, 0))
38 if (name
[namelen
-1] != '/')
41 /* We are being asked if the directory ("name") is worth
44 * Find the longest leading directory name that does
45 * not have metacharacter in the pathspec; the name
46 * we are looking at must overlap with that directory.
48 for (cp
= match
, meta
= NULL
; cp
- match
< matchlen
; cp
++) {
50 if (ch
== '*' || ch
== '[' || ch
== '?') {
56 meta
= cp
; /* fully literal */
58 if (namelen
<= meta
- match
) {
59 /* Looking at "Documentation/" and
60 * the pattern says "Documentation/howto/", or
61 * "Documentation/diff*.txt". The name we
62 * have should match prefix.
64 if (!memcmp(match
, name
, namelen
))
69 if (meta
- match
< namelen
) {
70 /* Looking at "Documentation/howto/" and
71 * the pattern says "Documentation/h*";
72 * match up to "Do.../h"; this avoids descending
73 * into "Documentation/technical/".
75 if (!memcmp(match
, name
, meta
- match
))
83 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
, const char *name
, int tree_name_len
)
91 data
= read_sha1_file(sha1
, type
, &size
);
93 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
96 if (opt
->relative
&& opt
->prefix_length
) {
97 static char name_buf
[PATH_MAX
];
99 int name_len
= strlen(name
) - opt
->prefix_length
+ 1;
102 name
+= opt
->prefix_length
;
104 if (ARRAY_SIZE(name_buf
) <= name_len
)
105 cp
= to_free
= xmalloc(name_len
);
108 memcpy(cp
, name
, tree_name_len
);
109 strcpy(cp
+ tree_name_len
,
110 name
+ tree_name_len
+ opt
->prefix_length
);
114 hit
= grep_buffer(opt
, name
, data
, size
);
120 static int grep_file(struct grep_opt
*opt
, const char *filename
)
125 if (lstat(filename
, &st
) < 0) {
128 error("'%s': %s", filename
, strerror(errno
));
132 return 0; /* empty file -- no grep hit */
133 if (!S_ISREG(st
.st_mode
))
135 i
= open(filename
, O_RDONLY
);
138 data
= xmalloc(st
.st_size
+ 1);
139 if (st
.st_size
!= read_in_full(i
, data
, st
.st_size
)) {
140 error("'%s': short read %s", filename
, strerror(errno
));
146 if (opt
->relative
&& opt
->prefix_length
)
147 filename
+= opt
->prefix_length
;
148 i
= grep_buffer(opt
, filename
, data
, st
.st_size
);
153 static int exec_grep(int argc
, const char **argv
)
163 execvp("grep", (char **) argv
);
166 while (waitpid(pid
, &status
, 0) < 0) {
171 if (WIFEXITED(status
)) {
172 if (!WEXITSTATUS(status
))
181 #define push_arg(a) do { \
182 if (nr < MAXARGS) argv[nr++] = (a); \
183 else die("maximum number of args exceeded"); \
186 static int external_grep(struct grep_opt
*opt
, const char **paths
, int cached
)
188 int i
, nr
, argc
, hit
, len
, status
;
189 const char *argv
[MAXARGS
+1];
190 char randarg
[ARGBUF
];
191 char *argptr
= randarg
;
194 if (opt
->extended
|| (opt
->relative
&& opt
->prefix_length
))
204 if (opt
->regflags
& REG_EXTENDED
)
206 if (opt
->regflags
& REG_ICASE
)
208 if (opt
->word_regexp
)
212 if (opt
->unmatch_name_only
)
216 if (opt
->post_context
|| opt
->pre_context
) {
217 if (opt
->post_context
!= opt
->pre_context
) {
218 if (opt
->pre_context
) {
220 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
221 "%u", opt
->pre_context
);
222 if (sizeof(randarg
) <= len
)
223 die("maximum length of args exceeded");
227 if (opt
->post_context
) {
229 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
230 "%u", opt
->post_context
);
231 if (sizeof(randarg
) <= len
)
232 die("maximum length of args exceeded");
239 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
240 "%u", opt
->post_context
);
241 if (sizeof(randarg
) <= len
)
242 die("maximum length of args exceeded");
247 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
249 push_arg(p
->pattern
);
253 * To make sure we get the header printed out when we want it,
254 * add /dev/null to the paths to grep. This is unnecessary
255 * (and wrong) with "-l" or "-L", which always print out the
258 * GNU grep has "-H", but this is portable.
260 if (!opt
->name_only
&& !opt
->unmatch_name_only
)
261 push_arg("/dev/null");
265 for (i
= 0; i
< active_nr
; i
++) {
266 struct cache_entry
*ce
= active_cache
[i
];
268 if (!S_ISREG(ntohl(ce
->ce_mode
)))
270 if (!pathspec_matches(paths
, ce
->name
))
273 if (name
[0] == '-') {
274 int len
= ce_namelen(ce
);
275 name
= xmalloc(len
+ 3);
276 memcpy(name
, "./", 2);
277 memcpy(name
+ 2, ce
->name
, len
+ 1);
280 if (argc
< MAXARGS
&& !ce_stage(ce
))
282 status
= exec_grep(argc
, argv
);
289 } while (i
< active_nr
&&
290 !strcmp(ce
->name
, active_cache
[i
]->name
));
291 i
--; /* compensate for loop control */
295 status
= exec_grep(argc
, argv
);
302 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
)
310 * Use the external "grep" command for the case where
311 * we grep through the checked-out files. It tends to
312 * be a lot more optimized
315 hit
= external_grep(opt
, paths
, cached
);
321 for (nr
= 0; nr
< active_nr
; nr
++) {
322 struct cache_entry
*ce
= active_cache
[nr
];
323 if (!S_ISREG(ntohl(ce
->ce_mode
)))
325 if (!pathspec_matches(paths
, ce
->name
))
330 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
, 0);
333 hit
|= grep_file(opt
, ce
->name
);
337 } while (nr
< active_nr
&&
338 !strcmp(ce
->name
, active_cache
[nr
]->name
));
339 nr
--; /* compensate for loop control */
342 free_grep_patterns(opt
);
346 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
347 struct tree_desc
*tree
,
348 const char *tree_name
, const char *base
)
352 struct name_entry entry
;
354 int tn_len
= strlen(tree_name
);
355 char *path_buf
= xmalloc(PATH_MAX
+ tn_len
+ 100);
358 tn_len
= sprintf(path_buf
, "%s:", tree_name
);
359 down
= path_buf
+ tn_len
;
366 len
= strlen(path_buf
);
368 while (tree_entry(tree
, &entry
)) {
369 strcpy(path_buf
+ len
, entry
.path
);
371 if (S_ISDIR(entry
.mode
))
372 /* Match "abc/" against pathspec to
373 * decide if we want to descend into "abc"
376 strcpy(path_buf
+ len
+ entry
.pathlen
, "/");
378 if (!pathspec_matches(paths
, down
))
380 else if (S_ISREG(entry
.mode
))
381 hit
|= grep_sha1(opt
, entry
.sha1
, path_buf
, tn_len
);
382 else if (S_ISDIR(entry
.mode
)) {
384 struct tree_desc sub
;
386 data
= read_sha1_file(entry
.sha1
, type
, &sub
.size
);
388 die("unable to read tree (%s)",
389 sha1_to_hex(entry
.sha1
));
391 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
398 static int grep_object(struct grep_opt
*opt
, const char **paths
,
399 struct object
*obj
, const char *name
)
401 if (obj
->type
== OBJ_BLOB
)
402 return grep_sha1(opt
, obj
->sha1
, name
, 0);
403 if (obj
->type
== OBJ_COMMIT
|| obj
->type
== OBJ_TREE
) {
404 struct tree_desc tree
;
407 data
= read_object_with_reference(obj
->sha1
, tree_type
,
410 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
412 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
416 die("unable to grep from object of type %s", typename(obj
->type
));
419 static const char builtin_grep_usage
[] =
420 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
422 static const char emsg_invalid_context_len
[] =
423 "%s: invalid context length argument";
424 static const char emsg_missing_context_len
[] =
425 "missing context length argument";
426 static const char emsg_missing_argument
[] =
427 "option requires an argument -%s";
429 int cmd_grep(int argc
, const char **argv
, const char *prefix
)
433 int seen_dashdash
= 0;
435 struct object_array list
= { 0, 0, NULL
};
436 const char **paths
= NULL
;
439 memset(&opt
, 0, sizeof(opt
));
440 opt
.prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
443 opt
.pattern_tail
= &opt
.pattern_list
;
444 opt
.regflags
= REG_NEWLINE
;
447 * If there is no -- then the paths must exist in the working
448 * tree. If there is no explicit pattern specified with -e or
449 * -f, we take the first unrecognized non option to be the
450 * pattern, but then what follows it must be zero or more
451 * valid refs up to the -- (if exists), and then existing
452 * paths. If there is an explicit pattern, then the first
453 * unrecognized non option is the beginning of the refs list
454 * that continues up to the -- (if exists), and then paths.
458 const char *arg
= argv
[1];
460 if (!strcmp("--cached", arg
)) {
464 if (!strcmp("-a", arg
) ||
465 !strcmp("--text", arg
)) {
466 opt
.binary
= GREP_BINARY_TEXT
;
469 if (!strcmp("-i", arg
) ||
470 !strcmp("--ignore-case", arg
)) {
471 opt
.regflags
|= REG_ICASE
;
474 if (!strcmp("-I", arg
)) {
475 opt
.binary
= GREP_BINARY_NOMATCH
;
478 if (!strcmp("-v", arg
) ||
479 !strcmp("--invert-match", arg
)) {
483 if (!strcmp("-E", arg
) ||
484 !strcmp("--extended-regexp", arg
)) {
485 opt
.regflags
|= REG_EXTENDED
;
488 if (!strcmp("-F", arg
) ||
489 !strcmp("--fixed-strings", arg
)) {
493 if (!strcmp("-G", arg
) ||
494 !strcmp("--basic-regexp", arg
)) {
495 opt
.regflags
&= ~REG_EXTENDED
;
498 if (!strcmp("-n", arg
)) {
502 if (!strcmp("-h", arg
)) {
506 if (!strcmp("-H", arg
)) {
510 if (!strcmp("-l", arg
) ||
511 !strcmp("--files-with-matches", arg
)) {
515 if (!strcmp("-L", arg
) ||
516 !strcmp("--files-without-match", arg
)) {
517 opt
.unmatch_name_only
= 1;
520 if (!strcmp("-c", arg
) ||
521 !strcmp("--count", arg
)) {
525 if (!strcmp("-w", arg
) ||
526 !strcmp("--word-regexp", arg
)) {
530 if (!prefixcmp(arg
, "-A") ||
531 !prefixcmp(arg
, "-B") ||
532 !prefixcmp(arg
, "-C") ||
533 (arg
[0] == '-' && '1' <= arg
[1] && arg
[1] <= '9')) {
537 case 'A': case 'B': case 'C':
540 die(emsg_missing_context_len
);
551 if (sscanf(scan
, "%u", &num
) != 1)
552 die(emsg_invalid_context_len
, scan
);
555 opt
.post_context
= num
;
559 opt
.post_context
= num
;
561 opt
.pre_context
= num
;
566 if (!strcmp("-f", arg
)) {
571 die(emsg_missing_argument
, arg
);
572 patterns
= fopen(argv
[1], "r");
574 die("'%s': %s", argv
[1], strerror(errno
));
575 while (fgets(buf
, sizeof(buf
), patterns
)) {
576 int len
= strlen(buf
);
577 if (buf
[len
-1] == '\n')
579 /* ignore empty line like grep does */
582 append_grep_pattern(&opt
, xstrdup(buf
),
591 if (!strcmp("--not", arg
)) {
592 append_grep_pattern(&opt
, arg
, "command line", 0,
596 if (!strcmp("--and", arg
)) {
597 append_grep_pattern(&opt
, arg
, "command line", 0,
601 if (!strcmp("--or", arg
))
602 continue; /* no-op */
603 if (!strcmp("(", arg
)) {
604 append_grep_pattern(&opt
, arg
, "command line", 0,
608 if (!strcmp(")", arg
)) {
609 append_grep_pattern(&opt
, arg
, "command line", 0,
613 if (!strcmp("--all-match", arg
)) {
617 if (!strcmp("-e", arg
)) {
619 append_grep_pattern(&opt
, argv
[1],
626 die(emsg_missing_argument
, arg
);
628 if (!strcmp("--full-name", arg
)) {
632 if (!strcmp("--", arg
)) {
633 /* later processing wants to have this at argv[1] */
639 usage(builtin_grep_usage
);
641 /* First unrecognized non-option token */
642 if (!opt
.pattern_list
) {
643 append_grep_pattern(&opt
, arg
, "command line", 0,
648 /* We are looking at the first path or rev;
649 * it is found at argv[1] after leaving the
657 if (!opt
.pattern_list
)
658 die("no pattern given.");
659 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
660 die("cannot mix --fixed-strings and regexp");
661 compile_grep_patterns(&opt
);
663 /* Check revs and then paths */
664 for (i
= 1; i
< argc
; i
++) {
665 const char *arg
= argv
[i
];
666 unsigned char sha1
[20];
668 if (!get_sha1(arg
, sha1
)) {
669 struct object
*object
= parse_object(sha1
);
671 die("bad object %s", arg
);
672 add_object_array(object
, arg
, &list
);
675 if (!strcmp(arg
, "--")) {
682 /* The rest are paths */
683 if (!seen_dashdash
) {
685 for (j
= i
; j
< argc
; j
++)
686 verify_filename(prefix
, argv
[j
]);
690 paths
= get_pathspec(prefix
, argv
+ i
);
691 if (opt
.prefix_length
&& opt
.relative
) {
692 /* Make sure we do not get outside of paths */
693 for (i
= 0; paths
[i
]; i
++)
694 if (strncmp(prefix
, paths
[i
], opt
.prefix_length
))
695 die("git-grep: cannot generate relative filenames containing '..'");
699 paths
= xcalloc(2, sizeof(const char *));
705 return !grep_cache(&opt
, paths
, cached
);
708 die("both --cached and trees are given.");
710 for (i
= 0; i
< list
.nr
; i
++) {
711 struct object
*real_obj
;
712 real_obj
= deref_tag(list
.objects
[i
].item
, NULL
, 0);
713 if (grep_object(&opt
, paths
, real_obj
, list
.objects
[i
].name
))
716 free_grep_patterns(&opt
);