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
;
26 * git grep pathspecs are somewhat different from diff-tree pathspecs;
27 * pathname wildcards are allowed.
29 static int pathspec_matches(const char **paths
, const char *name
)
32 if (!paths
|| !*paths
)
34 namelen
= strlen(name
);
35 for (i
= 0; paths
[i
]; i
++) {
36 const char *match
= paths
[i
];
37 int matchlen
= strlen(match
);
38 const char *cp
, *meta
;
41 ((matchlen
<= namelen
) &&
42 !strncmp(name
, match
, matchlen
) &&
43 (match
[matchlen
-1] == '/' ||
44 name
[matchlen
] == '\0' || name
[matchlen
] == '/')))
46 if (!fnmatch(match
, name
, 0))
48 if (name
[namelen
-1] != '/')
51 /* We are being asked if the directory ("name") is worth
54 * Find the longest leading directory name that does
55 * not have metacharacter in the pathspec; the name
56 * we are looking at must overlap with that directory.
58 for (cp
= match
, meta
= NULL
; cp
- match
< matchlen
; cp
++) {
60 if (ch
== '*' || ch
== '[' || ch
== '?') {
66 meta
= cp
; /* fully literal */
68 if (namelen
<= meta
- match
) {
69 /* Looking at "Documentation/" and
70 * the pattern says "Documentation/howto/", or
71 * "Documentation/diff*.txt". The name we
72 * have should match prefix.
74 if (!memcmp(match
, name
, namelen
))
79 if (meta
- match
< namelen
) {
80 /* Looking at "Documentation/howto/" and
81 * the pattern says "Documentation/h*";
82 * match up to "Do.../h"; this avoids descending
83 * into "Documentation/technical/".
85 if (!memcmp(match
, name
, meta
- match
))
93 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
, const char *name
, int tree_name_len
)
97 enum object_type type
;
101 data
= read_sha1_file(sha1
, &type
, &size
);
103 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
106 if (opt
->relative
&& opt
->prefix_length
) {
107 static char name_buf
[PATH_MAX
];
109 int name_len
= strlen(name
) - opt
->prefix_length
+ 1;
112 name
+= opt
->prefix_length
;
114 if (ARRAY_SIZE(name_buf
) <= name_len
)
115 cp
= to_free
= xmalloc(name_len
);
118 memcpy(cp
, name
, tree_name_len
);
119 strcpy(cp
+ tree_name_len
,
120 name
+ tree_name_len
+ opt
->prefix_length
);
124 hit
= grep_buffer(opt
, name
, data
, size
);
130 static int grep_file(struct grep_opt
*opt
, const char *filename
)
137 if (lstat(filename
, &st
) < 0) {
140 error("'%s': %s", filename
, strerror(errno
));
144 return 0; /* empty file -- no grep hit */
145 if (!S_ISREG(st
.st_mode
))
147 sz
= xsize_t(st
.st_size
);
148 i
= open(filename
, O_RDONLY
);
151 data
= xmalloc(sz
+ 1);
152 if (st
.st_size
!= read_in_full(i
, data
, sz
)) {
153 error("'%s': short read %s", filename
, strerror(errno
));
159 if (opt
->relative
&& opt
->prefix_length
)
160 filename
+= opt
->prefix_length
;
161 i
= grep_buffer(opt
, filename
, data
, sz
);
166 #if !NO_EXTERNAL_GREP
167 static int exec_grep(int argc
, const char **argv
)
177 execvp("grep", (char **) argv
);
180 while (waitpid(pid
, &status
, 0) < 0) {
185 if (WIFEXITED(status
)) {
186 if (!WEXITSTATUS(status
))
195 #define push_arg(a) do { \
196 if (nr < MAXARGS) argv[nr++] = (a); \
197 else die("maximum number of args exceeded"); \
201 * If you send a singleton filename to grep, it does not give
202 * the name of the file. GNU grep has "-H" but we would want
203 * that behaviour in a portable way.
205 * So we keep two pathnames in argv buffer unsent to grep in
206 * the main loop if we need to do more than one grep.
208 static int flush_grep(struct grep_opt
*opt
,
209 int argc
, int arg0
, const char **argv
, int *kept
)
212 int count
= argc
- arg0
;
213 const char *kept_0
= NULL
;
217 * Because we keep at least 2 paths in the call from
218 * the main loop (i.e. kept != NULL), and MAXARGS is
219 * far greater than 2, this usually is a call to
220 * conclude the grep. However, the user could attempt
221 * to overflow the argv buffer by giving too many
222 * options to leave very small number of real
223 * arguments even for the call in the main loop.
226 die("insanely many options to grep");
229 * If we have two or more paths, we do not have to do
230 * anything special, but we need to push /dev/null to
231 * get "-H" behaviour of GNU grep portably but when we
232 * are not doing "-l" nor "-L" nor "-c".
236 !opt
->unmatch_name_only
&&
238 argv
[argc
++] = "/dev/null";
245 * Called because we found many paths and haven't finished
246 * iterating over the cache yet. We keep two paths
247 * for the concluding call. argv[argc-2] and argv[argc-1]
248 * has the last two paths, so save the first one away,
249 * replace it with NULL while sending the list to grep,
250 * and recover them after we are done.
253 kept_0
= argv
[argc
-2];
258 status
= exec_grep(argc
, argv
);
262 * Then recover them. Now the last arg is beyond the
263 * terminating NULL which is at argc, and the second
264 * from the last is what we saved away in kept_0
266 argv
[arg0
++] = kept_0
;
267 argv
[arg0
] = argv
[argc
+1];
272 static int external_grep(struct grep_opt
*opt
, const char **paths
, int cached
)
274 int i
, nr
, argc
, hit
, len
, status
;
275 const char *argv
[MAXARGS
+1];
276 char randarg
[ARGBUF
];
277 char *argptr
= randarg
;
280 if (opt
->extended
|| (opt
->relative
&& opt
->prefix_length
))
290 if (opt
->regflags
& REG_EXTENDED
)
292 if (opt
->regflags
& REG_ICASE
)
294 if (opt
->word_regexp
)
298 if (opt
->unmatch_name_only
)
300 if (opt
->null_following_name
)
301 /* in GNU grep git's "-z" translates to "-Z" */
305 if (opt
->post_context
|| opt
->pre_context
) {
306 if (opt
->post_context
!= opt
->pre_context
) {
307 if (opt
->pre_context
) {
309 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
310 "%u", opt
->pre_context
) + 1;
311 if (sizeof(randarg
) <= len
)
312 die("maximum length of args exceeded");
316 if (opt
->post_context
) {
318 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
319 "%u", opt
->post_context
) + 1;
320 if (sizeof(randarg
) <= len
)
321 die("maximum length of args exceeded");
328 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
329 "%u", opt
->post_context
) + 1;
330 if (sizeof(randarg
) <= len
)
331 die("maximum length of args exceeded");
336 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
338 push_arg(p
->pattern
);
343 for (i
= 0; i
< active_nr
; i
++) {
344 struct cache_entry
*ce
= active_cache
[i
];
347 if (!S_ISREG(ce
->ce_mode
))
349 if (!pathspec_matches(paths
, ce
->name
))
352 if (name
[0] == '-') {
353 int len
= ce_namelen(ce
);
354 name
= xmalloc(len
+ 3);
355 memcpy(name
, "./", 2);
356 memcpy(name
+ 2, ce
->name
, len
+ 1);
359 if (MAXARGS
<= argc
) {
360 status
= flush_grep(opt
, argc
, nr
, argv
, &kept
);
368 } while (i
< active_nr
&&
369 !strcmp(ce
->name
, active_cache
[i
]->name
));
370 i
--; /* compensate for loop control */
374 status
= flush_grep(opt
, argc
, nr
, argv
, NULL
);
382 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
)
388 #if !NO_EXTERNAL_GREP
390 * Use the external "grep" command for the case where
391 * we grep through the checked-out files. It tends to
392 * be a lot more optimized
394 if (!cached
&& !builtin_grep
) {
395 hit
= external_grep(opt
, paths
, cached
);
401 for (nr
= 0; nr
< active_nr
; nr
++) {
402 struct cache_entry
*ce
= active_cache
[nr
];
403 if (!S_ISREG(ce
->ce_mode
))
405 if (!pathspec_matches(paths
, ce
->name
))
408 * If CE_VALID is on, we assume worktree file and its cache entry
409 * are identical, even if worktree file has been modified, so use
410 * cache version instead
412 if (cached
|| (ce
->ce_flags
& CE_VALID
)) {
415 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
, 0);
418 hit
|= grep_file(opt
, ce
->name
);
422 } while (nr
< active_nr
&&
423 !strcmp(ce
->name
, active_cache
[nr
]->name
));
424 nr
--; /* compensate for loop control */
427 free_grep_patterns(opt
);
431 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
432 struct tree_desc
*tree
,
433 const char *tree_name
, const char *base
)
437 struct name_entry entry
;
439 int tn_len
= strlen(tree_name
);
440 struct strbuf pathbuf
;
442 strbuf_init(&pathbuf
, PATH_MAX
+ tn_len
);
445 strbuf_add(&pathbuf
, tree_name
, tn_len
);
446 strbuf_addch(&pathbuf
, ':');
447 tn_len
= pathbuf
.len
;
449 strbuf_addstr(&pathbuf
, base
);
452 while (tree_entry(tree
, &entry
)) {
453 int te_len
= tree_entry_len(entry
.path
, entry
.sha1
);
455 strbuf_add(&pathbuf
, entry
.path
, te_len
);
457 if (S_ISDIR(entry
.mode
))
458 /* Match "abc/" against pathspec to
459 * decide if we want to descend into "abc"
462 strbuf_addch(&pathbuf
, '/');
464 down
= pathbuf
.buf
+ tn_len
;
465 if (!pathspec_matches(paths
, down
))
467 else if (S_ISREG(entry
.mode
))
468 hit
|= grep_sha1(opt
, entry
.sha1
, pathbuf
.buf
, tn_len
);
469 else if (S_ISDIR(entry
.mode
)) {
470 enum object_type type
;
471 struct tree_desc sub
;
475 data
= read_sha1_file(entry
.sha1
, &type
, &size
);
477 die("unable to read tree (%s)",
478 sha1_to_hex(entry
.sha1
));
479 init_tree_desc(&sub
, data
, size
);
480 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
484 strbuf_release(&pathbuf
);
488 static int grep_object(struct grep_opt
*opt
, const char **paths
,
489 struct object
*obj
, const char *name
)
491 if (obj
->type
== OBJ_BLOB
)
492 return grep_sha1(opt
, obj
->sha1
, name
, 0);
493 if (obj
->type
== OBJ_COMMIT
|| obj
->type
== OBJ_TREE
) {
494 struct tree_desc tree
;
498 data
= read_object_with_reference(obj
->sha1
, tree_type
,
501 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
502 init_tree_desc(&tree
, data
, size
);
503 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
507 die("unable to grep from object of type %s", typename(obj
->type
));
510 static const char builtin_grep_usage
[] =
511 "git grep <option>* [-e] <pattern> <rev>* [[--] <path>...]";
513 static const char emsg_invalid_context_len
[] =
514 "%s: invalid context length argument";
515 static const char emsg_missing_context_len
[] =
516 "missing context length argument";
517 static const char emsg_missing_argument
[] =
518 "option requires an argument -%s";
520 int cmd_grep(int argc
, const char **argv
, const char *prefix
)
524 int seen_dashdash
= 0;
526 struct object_array list
= { 0, 0, NULL
};
527 const char **paths
= NULL
;
530 memset(&opt
, 0, sizeof(opt
));
531 opt
.prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
534 opt
.pattern_tail
= &opt
.pattern_list
;
535 opt
.regflags
= REG_NEWLINE
;
538 * If there is no -- then the paths must exist in the working
539 * tree. If there is no explicit pattern specified with -e or
540 * -f, we take the first unrecognized non option to be the
541 * pattern, but then what follows it must be zero or more
542 * valid refs up to the -- (if exists), and then existing
543 * paths. If there is an explicit pattern, then the first
544 * unrecognized non option is the beginning of the refs list
545 * that continues up to the -- (if exists), and then paths.
549 const char *arg
= argv
[1];
551 if (!strcmp("--cached", arg
)) {
555 if (!strcmp("--no-ext-grep", arg
)) {
559 if (!strcmp("-a", arg
) ||
560 !strcmp("--text", arg
)) {
561 opt
.binary
= GREP_BINARY_TEXT
;
564 if (!strcmp("-i", arg
) ||
565 !strcmp("--ignore-case", arg
)) {
566 opt
.regflags
|= REG_ICASE
;
569 if (!strcmp("-I", arg
)) {
570 opt
.binary
= GREP_BINARY_NOMATCH
;
573 if (!strcmp("-v", arg
) ||
574 !strcmp("--invert-match", arg
)) {
578 if (!strcmp("-E", arg
) ||
579 !strcmp("--extended-regexp", arg
)) {
580 opt
.regflags
|= REG_EXTENDED
;
583 if (!strcmp("-F", arg
) ||
584 !strcmp("--fixed-strings", arg
)) {
588 if (!strcmp("-G", arg
) ||
589 !strcmp("--basic-regexp", arg
)) {
590 opt
.regflags
&= ~REG_EXTENDED
;
593 if (!strcmp("-n", arg
)) {
597 if (!strcmp("-h", arg
)) {
601 if (!strcmp("-H", arg
)) {
605 if (!strcmp("-l", arg
) ||
606 !strcmp("--name-only", arg
) ||
607 !strcmp("--files-with-matches", arg
)) {
611 if (!strcmp("-L", arg
) ||
612 !strcmp("--files-without-match", arg
)) {
613 opt
.unmatch_name_only
= 1;
616 if (!strcmp("-z", arg
) ||
617 !strcmp("--null", arg
)) {
618 opt
.null_following_name
= 1;
621 if (!strcmp("-c", arg
) ||
622 !strcmp("--count", arg
)) {
626 if (!strcmp("-w", arg
) ||
627 !strcmp("--word-regexp", arg
)) {
631 if (!prefixcmp(arg
, "-A") ||
632 !prefixcmp(arg
, "-B") ||
633 !prefixcmp(arg
, "-C") ||
634 (arg
[0] == '-' && '1' <= arg
[1] && arg
[1] <= '9')) {
638 case 'A': case 'B': case 'C':
641 die(emsg_missing_context_len
);
652 if (strtoul_ui(scan
, 10, &num
))
653 die(emsg_invalid_context_len
, scan
);
656 opt
.post_context
= num
;
660 opt
.post_context
= num
;
662 opt
.pre_context
= num
;
667 if (!strcmp("-f", arg
)) {
672 die(emsg_missing_argument
, arg
);
673 patterns
= fopen(argv
[1], "r");
675 die("'%s': %s", argv
[1], strerror(errno
));
676 while (fgets(buf
, sizeof(buf
), patterns
)) {
677 int len
= strlen(buf
);
678 if (len
&& buf
[len
-1] == '\n')
680 /* ignore empty line like grep does */
683 append_grep_pattern(&opt
, xstrdup(buf
),
692 if (!strcmp("--not", arg
)) {
693 append_grep_pattern(&opt
, arg
, "command line", 0,
697 if (!strcmp("--and", arg
)) {
698 append_grep_pattern(&opt
, arg
, "command line", 0,
702 if (!strcmp("--or", arg
))
703 continue; /* no-op */
704 if (!strcmp("(", arg
)) {
705 append_grep_pattern(&opt
, arg
, "command line", 0,
709 if (!strcmp(")", arg
)) {
710 append_grep_pattern(&opt
, arg
, "command line", 0,
714 if (!strcmp("--all-match", arg
)) {
718 if (!strcmp("-e", arg
)) {
720 append_grep_pattern(&opt
, argv
[1],
727 die(emsg_missing_argument
, arg
);
729 if (!strcmp("--full-name", arg
)) {
733 if (!strcmp("--", arg
)) {
734 /* later processing wants to have this at argv[1] */
740 usage(builtin_grep_usage
);
742 /* First unrecognized non-option token */
743 if (!opt
.pattern_list
) {
744 append_grep_pattern(&opt
, arg
, "command line", 0,
749 /* We are looking at the first path or rev;
750 * it is found at argv[1] after leaving the
758 if (!opt
.pattern_list
)
759 die("no pattern given.");
760 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
761 die("cannot mix --fixed-strings and regexp");
762 compile_grep_patterns(&opt
);
764 /* Check revs and then paths */
765 for (i
= 1; i
< argc
; i
++) {
766 const char *arg
= argv
[i
];
767 unsigned char sha1
[20];
769 if (!get_sha1(arg
, sha1
)) {
770 struct object
*object
= parse_object(sha1
);
772 die("bad object %s", arg
);
773 add_object_array(object
, arg
, &list
);
776 if (!strcmp(arg
, "--")) {
783 /* The rest are paths */
784 if (!seen_dashdash
) {
786 for (j
= i
; j
< argc
; j
++)
787 verify_filename(prefix
, argv
[j
]);
791 paths
= get_pathspec(prefix
, argv
+ i
);
792 if (opt
.prefix_length
&& opt
.relative
) {
793 /* Make sure we do not get outside of paths */
794 for (i
= 0; paths
[i
]; i
++)
795 if (strncmp(prefix
, paths
[i
], opt
.prefix_length
))
796 die("git grep: cannot generate relative filenames containing '..'");
800 paths
= xcalloc(2, sizeof(const char *));
808 return !grep_cache(&opt
, paths
, cached
);
812 die("both --cached and trees are given.");
814 for (i
= 0; i
< list
.nr
; i
++) {
815 struct object
*real_obj
;
816 real_obj
= deref_tag(list
.objects
[i
].item
, NULL
, 0);
817 if (grep_object(&opt
, paths
, real_obj
, list
.objects
[i
].name
))
820 free_grep_patterns(&opt
);