4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
14 #include "run-command.h"
16 #ifndef NO_EXTERNAL_GREP
18 #define NO_EXTERNAL_GREP 0
20 #define NO_EXTERNAL_GREP 1
25 * git grep pathspecs are somewhat different from diff-tree pathspecs;
26 * pathname wildcards are allowed.
28 static int pathspec_matches(const char **paths
, const char *name
)
31 if (!paths
|| !*paths
)
33 namelen
= strlen(name
);
34 for (i
= 0; paths
[i
]; i
++) {
35 const char *match
= paths
[i
];
36 int matchlen
= strlen(match
);
37 const char *cp
, *meta
;
40 ((matchlen
<= namelen
) &&
41 !strncmp(name
, match
, matchlen
) &&
42 (match
[matchlen
-1] == '/' ||
43 name
[matchlen
] == '\0' || name
[matchlen
] == '/')))
45 if (!fnmatch(match
, name
, 0))
47 if (name
[namelen
-1] != '/')
50 /* We are being asked if the directory ("name") is worth
53 * Find the longest leading directory name that does
54 * not have metacharacter in the pathspec; the name
55 * we are looking at must overlap with that directory.
57 for (cp
= match
, meta
= NULL
; cp
- match
< matchlen
; cp
++) {
59 if (ch
== '*' || ch
== '[' || ch
== '?') {
65 meta
= cp
; /* fully literal */
67 if (namelen
<= meta
- match
) {
68 /* Looking at "Documentation/" and
69 * the pattern says "Documentation/howto/", or
70 * "Documentation/diff*.txt". The name we
71 * have should match prefix.
73 if (!memcmp(match
, name
, namelen
))
78 if (meta
- match
< namelen
) {
79 /* Looking at "Documentation/howto/" and
80 * the pattern says "Documentation/h*";
81 * match up to "Do.../h"; this avoids descending
82 * into "Documentation/technical/".
84 if (!memcmp(match
, name
, meta
- match
))
92 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
, const char *name
, int tree_name_len
)
96 enum object_type type
;
100 data
= read_sha1_file(sha1
, &type
, &size
);
102 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
105 if (opt
->relative
&& opt
->prefix_length
) {
106 static char name_buf
[PATH_MAX
];
108 int name_len
= strlen(name
) - opt
->prefix_length
+ 1;
111 name
+= opt
->prefix_length
;
113 if (ARRAY_SIZE(name_buf
) <= name_len
)
114 cp
= to_free
= xmalloc(name_len
);
117 memcpy(cp
, name
, tree_name_len
);
118 strcpy(cp
+ tree_name_len
,
119 name
+ tree_name_len
+ opt
->prefix_length
);
123 hit
= grep_buffer(opt
, name
, data
, size
);
129 static int grep_file(struct grep_opt
*opt
, const char *filename
)
136 if (lstat(filename
, &st
) < 0) {
139 error("'%s': %s", filename
, strerror(errno
));
143 return 0; /* empty file -- no grep hit */
144 if (!S_ISREG(st
.st_mode
))
146 sz
= xsize_t(st
.st_size
);
147 i
= open(filename
, O_RDONLY
);
150 data
= xmalloc(sz
+ 1);
151 if (st
.st_size
!= read_in_full(i
, data
, sz
)) {
152 error("'%s': short read %s", filename
, strerror(errno
));
158 if (opt
->relative
&& opt
->prefix_length
)
159 filename
+= opt
->prefix_length
;
160 i
= grep_buffer(opt
, filename
, data
, sz
);
165 #if !NO_EXTERNAL_GREP
168 #define push_arg(a) do { \
169 if (nr < MAXARGS) argv[nr++] = (a); \
170 else die("maximum number of args exceeded"); \
174 * If you send a singleton filename to grep, it does not give
175 * the name of the file. GNU grep has "-H" but we would want
176 * that behaviour in a portable way.
178 * So we keep two pathnames in argv buffer unsent to grep in
179 * the main loop if we need to do more than one grep.
181 static int flush_grep(struct grep_opt
*opt
,
182 int argc
, int arg0
, const char **argv
, int *kept
)
185 int count
= argc
- arg0
;
186 const char *kept_0
= NULL
;
190 * Because we keep at least 2 paths in the call from
191 * the main loop (i.e. kept != NULL), and MAXARGS is
192 * far greater than 2, this usually is a call to
193 * conclude the grep. However, the user could attempt
194 * to overflow the argv buffer by giving too many
195 * options to leave very small number of real
196 * arguments even for the call in the main loop.
199 die("insanely many options to grep");
202 * If we have two or more paths, we do not have to do
203 * anything special, but we need to push /dev/null to
204 * get "-H" behaviour of GNU grep portably but when we
205 * are not doing "-l" nor "-L" nor "-c".
209 !opt
->unmatch_name_only
&&
211 argv
[argc
++] = "/dev/null";
218 * Called because we found many paths and haven't finished
219 * iterating over the cache yet. We keep two paths
220 * for the concluding call. argv[argc-2] and argv[argc-1]
221 * has the last two paths, so save the first one away,
222 * replace it with NULL while sending the list to grep,
223 * and recover them after we are done.
226 kept_0
= argv
[argc
-2];
232 status
= run_command_v_opt(argv
, 0);
236 * Then recover them. Now the last arg is beyond the
237 * terminating NULL which is at argc, and the second
238 * from the last is what we saved away in kept_0
240 argv
[arg0
++] = kept_0
;
241 argv
[arg0
] = argv
[argc
+1];
243 return status
== 0 ? 1 : -1;
246 static int external_grep(struct grep_opt
*opt
, const char **paths
, int cached
)
248 int i
, nr
, argc
, hit
, len
, status
;
249 const char *argv
[MAXARGS
+1];
250 char randarg
[ARGBUF
];
251 char *argptr
= randarg
;
254 if (opt
->extended
|| (opt
->relative
&& opt
->prefix_length
))
264 if (opt
->regflags
& REG_EXTENDED
)
266 if (opt
->regflags
& REG_ICASE
)
268 if (opt
->word_regexp
)
272 if (opt
->unmatch_name_only
)
276 if (opt
->post_context
|| opt
->pre_context
) {
277 if (opt
->post_context
!= opt
->pre_context
) {
278 if (opt
->pre_context
) {
280 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
281 "%u", opt
->pre_context
) + 1;
282 if (sizeof(randarg
) <= len
)
283 die("maximum length of args exceeded");
287 if (opt
->post_context
) {
289 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
290 "%u", opt
->post_context
) + 1;
291 if (sizeof(randarg
) <= len
)
292 die("maximum length of args exceeded");
299 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
300 "%u", opt
->post_context
) + 1;
301 if (sizeof(randarg
) <= len
)
302 die("maximum length of args exceeded");
307 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
309 push_arg(p
->pattern
);
314 for (i
= 0; i
< active_nr
; i
++) {
315 struct cache_entry
*ce
= active_cache
[i
];
318 if (!S_ISREG(ce
->ce_mode
))
320 if (!pathspec_matches(paths
, ce
->name
))
323 if (name
[0] == '-') {
324 int len
= ce_namelen(ce
);
325 name
= xmalloc(len
+ 3);
326 memcpy(name
, "./", 2);
327 memcpy(name
+ 2, ce
->name
, len
+ 1);
330 if (MAXARGS
<= argc
) {
331 status
= flush_grep(opt
, argc
, nr
, argv
, &kept
);
339 } while (i
< active_nr
&&
340 !strcmp(ce
->name
, active_cache
[i
]->name
));
341 i
--; /* compensate for loop control */
345 status
= flush_grep(opt
, argc
, nr
, argv
, NULL
);
353 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
)
359 #if !NO_EXTERNAL_GREP
361 * Use the external "grep" command for the case where
362 * we grep through the checked-out files. It tends to
363 * be a lot more optimized
366 hit
= external_grep(opt
, paths
, cached
);
372 for (nr
= 0; nr
< active_nr
; nr
++) {
373 struct cache_entry
*ce
= active_cache
[nr
];
374 if (!S_ISREG(ce
->ce_mode
))
376 if (!pathspec_matches(paths
, ce
->name
))
381 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
, 0);
384 hit
|= grep_file(opt
, ce
->name
);
388 } while (nr
< active_nr
&&
389 !strcmp(ce
->name
, active_cache
[nr
]->name
));
390 nr
--; /* compensate for loop control */
393 free_grep_patterns(opt
);
397 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
398 struct tree_desc
*tree
,
399 const char *tree_name
, const char *base
)
403 struct name_entry entry
;
405 int tn_len
= strlen(tree_name
);
406 char *path_buf
= xmalloc(PATH_MAX
+ tn_len
+ 100);
409 tn_len
= sprintf(path_buf
, "%s:", tree_name
);
410 down
= path_buf
+ tn_len
;
417 len
= strlen(path_buf
);
419 while (tree_entry(tree
, &entry
)) {
420 strcpy(path_buf
+ len
, entry
.path
);
422 if (S_ISDIR(entry
.mode
))
423 /* Match "abc/" against pathspec to
424 * decide if we want to descend into "abc"
427 strcpy(path_buf
+ len
+ tree_entry_len(entry
.path
, entry
.sha1
), "/");
429 if (!pathspec_matches(paths
, down
))
431 else if (S_ISREG(entry
.mode
))
432 hit
|= grep_sha1(opt
, entry
.sha1
, path_buf
, tn_len
);
433 else if (S_ISDIR(entry
.mode
)) {
434 enum object_type type
;
435 struct tree_desc sub
;
439 data
= read_sha1_file(entry
.sha1
, &type
, &size
);
441 die("unable to read tree (%s)",
442 sha1_to_hex(entry
.sha1
));
443 init_tree_desc(&sub
, data
, size
);
444 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
451 static int grep_object(struct grep_opt
*opt
, const char **paths
,
452 struct object
*obj
, const char *name
)
454 if (obj
->type
== OBJ_BLOB
)
455 return grep_sha1(opt
, obj
->sha1
, name
, 0);
456 if (obj
->type
== OBJ_COMMIT
|| obj
->type
== OBJ_TREE
) {
457 struct tree_desc tree
;
461 data
= read_object_with_reference(obj
->sha1
, tree_type
,
464 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
465 init_tree_desc(&tree
, data
, size
);
466 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
470 die("unable to grep from object of type %s", typename(obj
->type
));
473 static const char builtin_grep_usage
[] =
474 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
476 static const char emsg_invalid_context_len
[] =
477 "%s: invalid context length argument";
478 static const char emsg_missing_context_len
[] =
479 "missing context length argument";
480 static const char emsg_missing_argument
[] =
481 "option requires an argument -%s";
483 int cmd_grep(int argc
, const char **argv
, const char *prefix
)
487 int seen_dashdash
= 0;
489 struct object_array list
= { 0, 0, NULL
};
490 const char **paths
= NULL
;
493 memset(&opt
, 0, sizeof(opt
));
494 opt
.prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
497 opt
.pattern_tail
= &opt
.pattern_list
;
498 opt
.regflags
= REG_NEWLINE
;
501 * If there is no -- then the paths must exist in the working
502 * tree. If there is no explicit pattern specified with -e or
503 * -f, we take the first unrecognized non option to be the
504 * pattern, but then what follows it must be zero or more
505 * valid refs up to the -- (if exists), and then existing
506 * paths. If there is an explicit pattern, then the first
507 * unrecognized non option is the beginning of the refs list
508 * that continues up to the -- (if exists), and then paths.
512 const char *arg
= argv
[1];
514 if (!strcmp("--cached", arg
)) {
518 if (!strcmp("-a", arg
) ||
519 !strcmp("--text", arg
)) {
520 opt
.binary
= GREP_BINARY_TEXT
;
523 if (!strcmp("-i", arg
) ||
524 !strcmp("--ignore-case", arg
)) {
525 opt
.regflags
|= REG_ICASE
;
528 if (!strcmp("-I", arg
)) {
529 opt
.binary
= GREP_BINARY_NOMATCH
;
532 if (!strcmp("-v", arg
) ||
533 !strcmp("--invert-match", arg
)) {
537 if (!strcmp("-E", arg
) ||
538 !strcmp("--extended-regexp", arg
)) {
539 opt
.regflags
|= REG_EXTENDED
;
542 if (!strcmp("-F", arg
) ||
543 !strcmp("--fixed-strings", arg
)) {
547 if (!strcmp("-G", arg
) ||
548 !strcmp("--basic-regexp", arg
)) {
549 opt
.regflags
&= ~REG_EXTENDED
;
552 if (!strcmp("-n", arg
)) {
556 if (!strcmp("-h", arg
)) {
560 if (!strcmp("-H", arg
)) {
564 if (!strcmp("-l", arg
) ||
565 !strcmp("--name-only", arg
) ||
566 !strcmp("--files-with-matches", arg
)) {
570 if (!strcmp("-L", arg
) ||
571 !strcmp("--files-without-match", arg
)) {
572 opt
.unmatch_name_only
= 1;
575 if (!strcmp("-c", arg
) ||
576 !strcmp("--count", arg
)) {
580 if (!strcmp("-w", arg
) ||
581 !strcmp("--word-regexp", arg
)) {
585 if (!prefixcmp(arg
, "-A") ||
586 !prefixcmp(arg
, "-B") ||
587 !prefixcmp(arg
, "-C") ||
588 (arg
[0] == '-' && '1' <= arg
[1] && arg
[1] <= '9')) {
592 case 'A': case 'B': case 'C':
595 die(emsg_missing_context_len
);
606 if (strtoul_ui(scan
, 10, &num
))
607 die(emsg_invalid_context_len
, scan
);
610 opt
.post_context
= num
;
614 opt
.post_context
= num
;
616 opt
.pre_context
= num
;
621 if (!strcmp("-f", arg
)) {
626 die(emsg_missing_argument
, arg
);
627 patterns
= fopen(argv
[1], "r");
629 die("'%s': %s", argv
[1], strerror(errno
));
630 while (fgets(buf
, sizeof(buf
), patterns
)) {
631 int len
= strlen(buf
);
632 if (len
&& buf
[len
-1] == '\n')
634 /* ignore empty line like grep does */
637 append_grep_pattern(&opt
, xstrdup(buf
),
646 if (!strcmp("--not", arg
)) {
647 append_grep_pattern(&opt
, arg
, "command line", 0,
651 if (!strcmp("--and", arg
)) {
652 append_grep_pattern(&opt
, arg
, "command line", 0,
656 if (!strcmp("--or", arg
))
657 continue; /* no-op */
658 if (!strcmp("(", arg
)) {
659 append_grep_pattern(&opt
, arg
, "command line", 0,
663 if (!strcmp(")", arg
)) {
664 append_grep_pattern(&opt
, arg
, "command line", 0,
668 if (!strcmp("--all-match", arg
)) {
672 if (!strcmp("-e", arg
)) {
674 append_grep_pattern(&opt
, argv
[1],
681 die(emsg_missing_argument
, arg
);
683 if (!strcmp("--full-name", arg
)) {
687 if (!strcmp("--", arg
)) {
688 /* later processing wants to have this at argv[1] */
694 usage(builtin_grep_usage
);
696 /* First unrecognized non-option token */
697 if (!opt
.pattern_list
) {
698 append_grep_pattern(&opt
, arg
, "command line", 0,
703 /* We are looking at the first path or rev;
704 * it is found at argv[1] after leaving the
712 if (!opt
.pattern_list
)
713 die("no pattern given.");
714 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
715 die("cannot mix --fixed-strings and regexp");
716 compile_grep_patterns(&opt
);
718 /* Check revs and then paths */
719 for (i
= 1; i
< argc
; i
++) {
720 const char *arg
= argv
[i
];
721 unsigned char sha1
[20];
723 if (!get_sha1(arg
, sha1
)) {
724 struct object
*object
= parse_object(sha1
);
726 die("bad object %s", arg
);
727 add_object_array(object
, arg
, &list
);
730 if (!strcmp(arg
, "--")) {
737 /* The rest are paths */
738 if (!seen_dashdash
) {
740 for (j
= i
; j
< argc
; j
++)
741 verify_filename(prefix
, argv
[j
]);
745 paths
= get_pathspec(prefix
, argv
+ i
);
746 if (opt
.prefix_length
&& opt
.relative
) {
747 /* Make sure we do not get outside of paths */
748 for (i
= 0; paths
[i
]; i
++)
749 if (strncmp(prefix
, paths
[i
], opt
.prefix_length
))
750 die("git-grep: cannot generate relative filenames containing '..'");
754 paths
= xcalloc(2, sizeof(const char *));
760 return !grep_cache(&opt
, paths
, cached
);
763 die("both --cached and trees are given.");
765 for (i
= 0; i
< list
.nr
; i
++) {
766 struct object
*real_obj
;
767 real_obj
= deref_tag(list
.objects
[i
].item
, NULL
, 0);
768 if (grep_object(&opt
, paths
, real_obj
, list
.objects
[i
].name
))
771 free_grep_patterns(&opt
);