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
)
87 enum object_type type
;
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
)
127 if (lstat(filename
, &st
) < 0) {
130 error("'%s': %s", filename
, strerror(errno
));
134 return 0; /* empty file -- no grep hit */
135 if (!S_ISREG(st
.st_mode
))
137 sz
= xsize_t(st
.st_size
);
138 i
= open(filename
, O_RDONLY
);
141 data
= xmalloc(sz
+ 1);
142 if (st
.st_size
!= read_in_full(i
, data
, sz
)) {
143 error("'%s': short read %s", filename
, strerror(errno
));
149 if (opt
->relative
&& opt
->prefix_length
)
150 filename
+= opt
->prefix_length
;
151 i
= grep_buffer(opt
, filename
, data
, sz
);
157 static int exec_grep(int argc
, const char **argv
)
167 execvp("grep", (char **) argv
);
170 while (waitpid(pid
, &status
, 0) < 0) {
175 if (WIFEXITED(status
)) {
176 if (!WEXITSTATUS(status
))
185 #define push_arg(a) do { \
186 if (nr < MAXARGS) argv[nr++] = (a); \
187 else die("maximum number of args exceeded"); \
190 static int external_grep(struct grep_opt
*opt
, const char **paths
, int cached
)
192 int i
, nr
, argc
, hit
, len
, status
;
193 const char *argv
[MAXARGS
+1];
194 char randarg
[ARGBUF
];
195 char *argptr
= randarg
;
198 if (opt
->extended
|| (opt
->relative
&& opt
->prefix_length
))
208 if (opt
->regflags
& REG_EXTENDED
)
210 if (opt
->regflags
& REG_ICASE
)
212 if (opt
->word_regexp
)
216 if (opt
->unmatch_name_only
)
220 if (opt
->post_context
|| opt
->pre_context
) {
221 if (opt
->post_context
!= opt
->pre_context
) {
222 if (opt
->pre_context
) {
224 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
225 "%u", opt
->pre_context
);
226 if (sizeof(randarg
) <= len
)
227 die("maximum length of args exceeded");
231 if (opt
->post_context
) {
233 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
234 "%u", opt
->post_context
);
235 if (sizeof(randarg
) <= len
)
236 die("maximum length of args exceeded");
243 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
244 "%u", opt
->post_context
);
245 if (sizeof(randarg
) <= len
)
246 die("maximum length of args exceeded");
251 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
253 push_arg(p
->pattern
);
257 * To make sure we get the header printed out when we want it,
258 * add /dev/null to the paths to grep. This is unnecessary
259 * (and wrong) with "-l" or "-L", which always print out the
262 * GNU grep has "-H", but this is portable.
264 if (!opt
->name_only
&& !opt
->unmatch_name_only
)
265 push_arg("/dev/null");
269 for (i
= 0; i
< active_nr
; i
++) {
270 struct cache_entry
*ce
= active_cache
[i
];
272 if (!S_ISREG(ntohl(ce
->ce_mode
)))
274 if (!pathspec_matches(paths
, ce
->name
))
277 if (name
[0] == '-') {
278 int len
= ce_namelen(ce
);
279 name
= xmalloc(len
+ 3);
280 memcpy(name
, "./", 2);
281 memcpy(name
+ 2, ce
->name
, len
+ 1);
284 if (argc
< MAXARGS
&& !ce_stage(ce
))
286 status
= exec_grep(argc
, argv
);
293 } while (i
< active_nr
&&
294 !strcmp(ce
->name
, active_cache
[i
]->name
));
295 i
--; /* compensate for loop control */
299 status
= exec_grep(argc
, argv
);
307 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
)
315 * Use the external "grep" command for the case where
316 * we grep through the checked-out files. It tends to
317 * be a lot more optimized
320 hit
= external_grep(opt
, paths
, cached
);
326 for (nr
= 0; nr
< active_nr
; nr
++) {
327 struct cache_entry
*ce
= active_cache
[nr
];
328 if (!S_ISREG(ntohl(ce
->ce_mode
)))
330 if (!pathspec_matches(paths
, ce
->name
))
335 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
, 0);
338 hit
|= grep_file(opt
, ce
->name
);
342 } while (nr
< active_nr
&&
343 !strcmp(ce
->name
, active_cache
[nr
]->name
));
344 nr
--; /* compensate for loop control */
347 free_grep_patterns(opt
);
351 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
352 struct tree_desc
*tree
,
353 const char *tree_name
, const char *base
)
357 struct name_entry entry
;
359 int tn_len
= strlen(tree_name
);
360 char *path_buf
= xmalloc(PATH_MAX
+ tn_len
+ 100);
363 tn_len
= sprintf(path_buf
, "%s:", tree_name
);
364 down
= path_buf
+ tn_len
;
371 len
= strlen(path_buf
);
373 while (tree_entry(tree
, &entry
)) {
374 strcpy(path_buf
+ len
, entry
.path
);
376 if (S_ISDIR(entry
.mode
))
377 /* Match "abc/" against pathspec to
378 * decide if we want to descend into "abc"
381 strcpy(path_buf
+ len
+ entry
.pathlen
, "/");
383 if (!pathspec_matches(paths
, down
))
385 else if (S_ISREG(entry
.mode
))
386 hit
|= grep_sha1(opt
, entry
.sha1
, path_buf
, tn_len
);
387 else if (S_ISDIR(entry
.mode
)) {
388 enum object_type type
;
389 struct tree_desc sub
;
391 data
= read_sha1_file(entry
.sha1
, &type
, &sub
.size
);
393 die("unable to read tree (%s)",
394 sha1_to_hex(entry
.sha1
));
396 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
403 static int grep_object(struct grep_opt
*opt
, const char **paths
,
404 struct object
*obj
, const char *name
)
406 if (obj
->type
== OBJ_BLOB
)
407 return grep_sha1(opt
, obj
->sha1
, name
, 0);
408 if (obj
->type
== OBJ_COMMIT
|| obj
->type
== OBJ_TREE
) {
409 struct tree_desc tree
;
412 data
= read_object_with_reference(obj
->sha1
, tree_type
,
415 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
417 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
421 die("unable to grep from object of type %s", typename(obj
->type
));
424 static const char builtin_grep_usage
[] =
425 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
427 static const char emsg_invalid_context_len
[] =
428 "%s: invalid context length argument";
429 static const char emsg_missing_context_len
[] =
430 "missing context length argument";
431 static const char emsg_missing_argument
[] =
432 "option requires an argument -%s";
434 static int strtoul_ui(char const *s
, unsigned int *result
)
440 ul
= strtoul(s
, &p
, 10);
441 if (errno
|| *p
|| p
== s
|| (unsigned int) ul
!= ul
)
447 int cmd_grep(int argc
, const char **argv
, const char *prefix
)
451 int seen_dashdash
= 0;
453 struct object_array list
= { 0, 0, NULL
};
454 const char **paths
= NULL
;
457 memset(&opt
, 0, sizeof(opt
));
458 opt
.prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
461 opt
.pattern_tail
= &opt
.pattern_list
;
462 opt
.regflags
= REG_NEWLINE
;
465 * If there is no -- then the paths must exist in the working
466 * tree. If there is no explicit pattern specified with -e or
467 * -f, we take the first unrecognized non option to be the
468 * pattern, but then what follows it must be zero or more
469 * valid refs up to the -- (if exists), and then existing
470 * paths. If there is an explicit pattern, then the first
471 * unrecognized non option is the beginning of the refs list
472 * that continues up to the -- (if exists), and then paths.
476 const char *arg
= argv
[1];
478 if (!strcmp("--cached", arg
)) {
482 if (!strcmp("-a", arg
) ||
483 !strcmp("--text", arg
)) {
484 opt
.binary
= GREP_BINARY_TEXT
;
487 if (!strcmp("-i", arg
) ||
488 !strcmp("--ignore-case", arg
)) {
489 opt
.regflags
|= REG_ICASE
;
492 if (!strcmp("-I", arg
)) {
493 opt
.binary
= GREP_BINARY_NOMATCH
;
496 if (!strcmp("-v", arg
) ||
497 !strcmp("--invert-match", arg
)) {
501 if (!strcmp("-E", arg
) ||
502 !strcmp("--extended-regexp", arg
)) {
503 opt
.regflags
|= REG_EXTENDED
;
506 if (!strcmp("-F", arg
) ||
507 !strcmp("--fixed-strings", arg
)) {
511 if (!strcmp("-G", arg
) ||
512 !strcmp("--basic-regexp", arg
)) {
513 opt
.regflags
&= ~REG_EXTENDED
;
516 if (!strcmp("-n", arg
)) {
520 if (!strcmp("-h", arg
)) {
524 if (!strcmp("-H", arg
)) {
528 if (!strcmp("-l", arg
) ||
529 !strcmp("--files-with-matches", arg
)) {
533 if (!strcmp("-L", arg
) ||
534 !strcmp("--files-without-match", arg
)) {
535 opt
.unmatch_name_only
= 1;
538 if (!strcmp("-c", arg
) ||
539 !strcmp("--count", arg
)) {
543 if (!strcmp("-w", arg
) ||
544 !strcmp("--word-regexp", arg
)) {
548 if (!prefixcmp(arg
, "-A") ||
549 !prefixcmp(arg
, "-B") ||
550 !prefixcmp(arg
, "-C") ||
551 (arg
[0] == '-' && '1' <= arg
[1] && arg
[1] <= '9')) {
555 case 'A': case 'B': case 'C':
558 die(emsg_missing_context_len
);
569 if (strtoul_ui(scan
, &num
))
570 die(emsg_invalid_context_len
, scan
);
573 opt
.post_context
= num
;
577 opt
.post_context
= num
;
579 opt
.pre_context
= num
;
584 if (!strcmp("-f", arg
)) {
589 die(emsg_missing_argument
, arg
);
590 patterns
= fopen(argv
[1], "r");
592 die("'%s': %s", argv
[1], strerror(errno
));
593 while (fgets(buf
, sizeof(buf
), patterns
)) {
594 int len
= strlen(buf
);
595 if (buf
[len
-1] == '\n')
597 /* ignore empty line like grep does */
600 append_grep_pattern(&opt
, xstrdup(buf
),
609 if (!strcmp("--not", arg
)) {
610 append_grep_pattern(&opt
, arg
, "command line", 0,
614 if (!strcmp("--and", arg
)) {
615 append_grep_pattern(&opt
, arg
, "command line", 0,
619 if (!strcmp("--or", arg
))
620 continue; /* no-op */
621 if (!strcmp("(", arg
)) {
622 append_grep_pattern(&opt
, arg
, "command line", 0,
626 if (!strcmp(")", arg
)) {
627 append_grep_pattern(&opt
, arg
, "command line", 0,
631 if (!strcmp("--all-match", arg
)) {
635 if (!strcmp("-e", arg
)) {
637 append_grep_pattern(&opt
, argv
[1],
644 die(emsg_missing_argument
, arg
);
646 if (!strcmp("--full-name", arg
)) {
650 if (!strcmp("--", arg
)) {
651 /* later processing wants to have this at argv[1] */
657 usage(builtin_grep_usage
);
659 /* First unrecognized non-option token */
660 if (!opt
.pattern_list
) {
661 append_grep_pattern(&opt
, arg
, "command line", 0,
666 /* We are looking at the first path or rev;
667 * it is found at argv[1] after leaving the
675 if (!opt
.pattern_list
)
676 die("no pattern given.");
677 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
678 die("cannot mix --fixed-strings and regexp");
679 compile_grep_patterns(&opt
);
681 /* Check revs and then paths */
682 for (i
= 1; i
< argc
; i
++) {
683 const char *arg
= argv
[i
];
684 unsigned char sha1
[20];
686 if (!get_sha1(arg
, sha1
)) {
687 struct object
*object
= parse_object(sha1
);
689 die("bad object %s", arg
);
690 add_object_array(object
, arg
, &list
);
693 if (!strcmp(arg
, "--")) {
700 /* The rest are paths */
701 if (!seen_dashdash
) {
703 for (j
= i
; j
< argc
; j
++)
704 verify_filename(prefix
, argv
[j
]);
708 paths
= get_pathspec(prefix
, argv
+ i
);
709 if (opt
.prefix_length
&& opt
.relative
) {
710 /* Make sure we do not get outside of paths */
711 for (i
= 0; paths
[i
]; i
++)
712 if (strncmp(prefix
, paths
[i
], opt
.prefix_length
))
713 die("git-grep: cannot generate relative filenames containing '..'");
717 paths
= xcalloc(2, sizeof(const char *));
723 return !grep_cache(&opt
, paths
, cached
);
726 die("both --cached and trees are given.");
728 for (i
= 0; i
< list
.nr
; i
++) {
729 struct object
*real_obj
;
730 real_obj
= deref_tag(list
.objects
[i
].item
, NULL
, 0);
731 if (grep_object(&opt
, paths
, real_obj
, list
.objects
[i
].name
))
734 free_grep_patterns(&opt
);