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
))
410 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
, 0);
413 hit
|= grep_file(opt
, ce
->name
);
417 } while (nr
< active_nr
&&
418 !strcmp(ce
->name
, active_cache
[nr
]->name
));
419 nr
--; /* compensate for loop control */
422 free_grep_patterns(opt
);
426 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
427 struct tree_desc
*tree
,
428 const char *tree_name
, const char *base
)
432 struct name_entry entry
;
434 int tn_len
= strlen(tree_name
);
435 struct strbuf pathbuf
;
437 strbuf_init(&pathbuf
, PATH_MAX
+ tn_len
);
440 strbuf_add(&pathbuf
, tree_name
, tn_len
);
441 strbuf_addch(&pathbuf
, ':');
442 tn_len
= pathbuf
.len
;
444 strbuf_addstr(&pathbuf
, base
);
447 while (tree_entry(tree
, &entry
)) {
448 int te_len
= tree_entry_len(entry
.path
, entry
.sha1
);
450 strbuf_add(&pathbuf
, entry
.path
, te_len
);
452 if (S_ISDIR(entry
.mode
))
453 /* Match "abc/" against pathspec to
454 * decide if we want to descend into "abc"
457 strbuf_addch(&pathbuf
, '/');
459 down
= pathbuf
.buf
+ tn_len
;
460 if (!pathspec_matches(paths
, down
))
462 else if (S_ISREG(entry
.mode
))
463 hit
|= grep_sha1(opt
, entry
.sha1
, pathbuf
.buf
, tn_len
);
464 else if (S_ISDIR(entry
.mode
)) {
465 enum object_type type
;
466 struct tree_desc sub
;
470 data
= read_sha1_file(entry
.sha1
, &type
, &size
);
472 die("unable to read tree (%s)",
473 sha1_to_hex(entry
.sha1
));
474 init_tree_desc(&sub
, data
, size
);
475 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
479 strbuf_release(&pathbuf
);
483 static int grep_object(struct grep_opt
*opt
, const char **paths
,
484 struct object
*obj
, const char *name
)
486 if (obj
->type
== OBJ_BLOB
)
487 return grep_sha1(opt
, obj
->sha1
, name
, 0);
488 if (obj
->type
== OBJ_COMMIT
|| obj
->type
== OBJ_TREE
) {
489 struct tree_desc tree
;
493 data
= read_object_with_reference(obj
->sha1
, tree_type
,
496 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
497 init_tree_desc(&tree
, data
, size
);
498 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
502 die("unable to grep from object of type %s", typename(obj
->type
));
505 static const char builtin_grep_usage
[] =
506 "git grep <option>* [-e] <pattern> <rev>* [[--] <path>...]";
508 static const char emsg_invalid_context_len
[] =
509 "%s: invalid context length argument";
510 static const char emsg_missing_context_len
[] =
511 "missing context length argument";
512 static const char emsg_missing_argument
[] =
513 "option requires an argument -%s";
515 int cmd_grep(int argc
, const char **argv
, const char *prefix
)
519 int seen_dashdash
= 0;
521 struct object_array list
= { 0, 0, NULL
};
522 const char **paths
= NULL
;
525 memset(&opt
, 0, sizeof(opt
));
526 opt
.prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
529 opt
.pattern_tail
= &opt
.pattern_list
;
530 opt
.regflags
= REG_NEWLINE
;
533 * If there is no -- then the paths must exist in the working
534 * tree. If there is no explicit pattern specified with -e or
535 * -f, we take the first unrecognized non option to be the
536 * pattern, but then what follows it must be zero or more
537 * valid refs up to the -- (if exists), and then existing
538 * paths. If there is an explicit pattern, then the first
539 * unrecognized non option is the beginning of the refs list
540 * that continues up to the -- (if exists), and then paths.
544 const char *arg
= argv
[1];
546 if (!strcmp("--cached", arg
)) {
550 if (!strcmp("--no-ext-grep", arg
)) {
554 if (!strcmp("-a", arg
) ||
555 !strcmp("--text", arg
)) {
556 opt
.binary
= GREP_BINARY_TEXT
;
559 if (!strcmp("-i", arg
) ||
560 !strcmp("--ignore-case", arg
)) {
561 opt
.regflags
|= REG_ICASE
;
564 if (!strcmp("-I", arg
)) {
565 opt
.binary
= GREP_BINARY_NOMATCH
;
568 if (!strcmp("-v", arg
) ||
569 !strcmp("--invert-match", arg
)) {
573 if (!strcmp("-E", arg
) ||
574 !strcmp("--extended-regexp", arg
)) {
575 opt
.regflags
|= REG_EXTENDED
;
578 if (!strcmp("-F", arg
) ||
579 !strcmp("--fixed-strings", arg
)) {
583 if (!strcmp("-G", arg
) ||
584 !strcmp("--basic-regexp", arg
)) {
585 opt
.regflags
&= ~REG_EXTENDED
;
588 if (!strcmp("-n", arg
)) {
592 if (!strcmp("-h", arg
)) {
596 if (!strcmp("-H", arg
)) {
600 if (!strcmp("-l", arg
) ||
601 !strcmp("--name-only", arg
) ||
602 !strcmp("--files-with-matches", arg
)) {
606 if (!strcmp("-L", arg
) ||
607 !strcmp("--files-without-match", arg
)) {
608 opt
.unmatch_name_only
= 1;
611 if (!strcmp("-z", arg
) ||
612 !strcmp("--null", arg
)) {
613 opt
.null_following_name
= 1;
616 if (!strcmp("-c", arg
) ||
617 !strcmp("--count", arg
)) {
621 if (!strcmp("-w", arg
) ||
622 !strcmp("--word-regexp", arg
)) {
626 if (!prefixcmp(arg
, "-A") ||
627 !prefixcmp(arg
, "-B") ||
628 !prefixcmp(arg
, "-C") ||
629 (arg
[0] == '-' && '1' <= arg
[1] && arg
[1] <= '9')) {
633 case 'A': case 'B': case 'C':
636 die(emsg_missing_context_len
);
647 if (strtoul_ui(scan
, 10, &num
))
648 die(emsg_invalid_context_len
, scan
);
651 opt
.post_context
= num
;
655 opt
.post_context
= num
;
657 opt
.pre_context
= num
;
662 if (!strcmp("-f", arg
)) {
667 die(emsg_missing_argument
, arg
);
668 patterns
= fopen(argv
[1], "r");
670 die("'%s': %s", argv
[1], strerror(errno
));
671 while (fgets(buf
, sizeof(buf
), patterns
)) {
672 int len
= strlen(buf
);
673 if (len
&& buf
[len
-1] == '\n')
675 /* ignore empty line like grep does */
678 append_grep_pattern(&opt
, xstrdup(buf
),
687 if (!strcmp("--not", arg
)) {
688 append_grep_pattern(&opt
, arg
, "command line", 0,
692 if (!strcmp("--and", arg
)) {
693 append_grep_pattern(&opt
, arg
, "command line", 0,
697 if (!strcmp("--or", arg
))
698 continue; /* no-op */
699 if (!strcmp("(", arg
)) {
700 append_grep_pattern(&opt
, arg
, "command line", 0,
704 if (!strcmp(")", arg
)) {
705 append_grep_pattern(&opt
, arg
, "command line", 0,
709 if (!strcmp("--all-match", arg
)) {
713 if (!strcmp("-e", arg
)) {
715 append_grep_pattern(&opt
, argv
[1],
722 die(emsg_missing_argument
, arg
);
724 if (!strcmp("--full-name", arg
)) {
728 if (!strcmp("--", arg
)) {
729 /* later processing wants to have this at argv[1] */
735 usage(builtin_grep_usage
);
737 /* First unrecognized non-option token */
738 if (!opt
.pattern_list
) {
739 append_grep_pattern(&opt
, arg
, "command line", 0,
744 /* We are looking at the first path or rev;
745 * it is found at argv[1] after leaving the
753 if (!opt
.pattern_list
)
754 die("no pattern given.");
755 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
756 die("cannot mix --fixed-strings and regexp");
757 compile_grep_patterns(&opt
);
759 /* Check revs and then paths */
760 for (i
= 1; i
< argc
; i
++) {
761 const char *arg
= argv
[i
];
762 unsigned char sha1
[20];
764 if (!get_sha1(arg
, sha1
)) {
765 struct object
*object
= parse_object(sha1
);
767 die("bad object %s", arg
);
768 add_object_array(object
, arg
, &list
);
771 if (!strcmp(arg
, "--")) {
778 /* The rest are paths */
779 if (!seen_dashdash
) {
781 for (j
= i
; j
< argc
; j
++)
782 verify_filename(prefix
, argv
[j
]);
786 paths
= get_pathspec(prefix
, argv
+ i
);
787 if (opt
.prefix_length
&& opt
.relative
) {
788 /* Make sure we do not get outside of paths */
789 for (i
= 0; paths
[i
]; i
++)
790 if (strncmp(prefix
, paths
[i
], opt
.prefix_length
))
791 die("git grep: cannot generate relative filenames containing '..'");
795 paths
= xcalloc(2, sizeof(const char *));
803 return !grep_cache(&opt
, paths
, cached
);
807 die("both --cached and trees are given.");
809 for (i
= 0; i
< list
.nr
; i
++) {
810 struct object
*real_obj
;
811 real_obj
= deref_tag(list
.objects
[i
].item
, NULL
, 0);
812 if (grep_object(&opt
, paths
, real_obj
, list
.objects
[i
].name
))
815 free_grep_patterns(&opt
);