4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
19 * git grep pathspecs are somewhat different from diff-tree pathspecs;
20 * pathname wildcards are allowed.
22 static int pathspec_matches(const char **paths
, const char *name
)
25 if (!paths
|| !*paths
)
27 namelen
= strlen(name
);
28 for (i
= 0; paths
[i
]; i
++) {
29 const char *match
= paths
[i
];
30 int matchlen
= strlen(match
);
31 const char *cp
, *meta
;
34 ((matchlen
<= namelen
) &&
35 !strncmp(name
, match
, matchlen
) &&
36 (match
[matchlen
-1] == '/' ||
37 name
[matchlen
] == '\0' || name
[matchlen
] == '/')))
39 if (!fnmatch(match
, name
, 0))
41 if (name
[namelen
-1] != '/')
44 /* We are being asked if the directory ("name") is worth
47 * Find the longest leading directory name that does
48 * not have metacharacter in the pathspec; the name
49 * we are looking at must overlap with that directory.
51 for (cp
= match
, meta
= NULL
; cp
- match
< matchlen
; cp
++) {
53 if (ch
== '*' || ch
== '[' || ch
== '?') {
59 meta
= cp
; /* fully literal */
61 if (namelen
<= meta
- match
) {
62 /* Looking at "Documentation/" and
63 * the pattern says "Documentation/howto/", or
64 * "Documentation/diff*.txt". The name we
65 * have should match prefix.
67 if (!memcmp(match
, name
, namelen
))
72 if (meta
- match
< namelen
) {
73 /* Looking at "Documentation/howto/" and
74 * the pattern says "Documentation/h*";
75 * match up to "Do.../h"; this avoids descending
76 * into "Documentation/technical/".
78 if (!memcmp(match
, name
, meta
- match
))
86 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
, const char *name
, int tree_name_len
)
94 data
= read_sha1_file(sha1
, type
, &size
);
96 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
99 if (opt
->relative
&& opt
->prefix_length
) {
100 static char name_buf
[PATH_MAX
];
102 int name_len
= strlen(name
) - opt
->prefix_length
+ 1;
105 name
+= opt
->prefix_length
;
107 if (ARRAY_SIZE(name_buf
) <= name_len
)
108 cp
= to_free
= xmalloc(name_len
);
111 memcpy(cp
, name
, tree_name_len
);
112 strcpy(cp
+ tree_name_len
,
113 name
+ tree_name_len
+ opt
->prefix_length
);
117 hit
= grep_buffer(opt
, name
, data
, size
);
123 static int grep_file(struct grep_opt
*opt
, const char *filename
)
128 if (lstat(filename
, &st
) < 0) {
131 error("'%s': %s", filename
, strerror(errno
));
135 return 0; /* empty file -- no grep hit */
136 if (!S_ISREG(st
.st_mode
))
138 i
= open(filename
, O_RDONLY
);
141 data
= xmalloc(st
.st_size
+ 1);
142 if (st
.st_size
!= xread(i
, data
, st
.st_size
)) {
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
, st
.st_size
);
156 static int exec_grep(int argc
, const char **argv
)
166 execvp("grep", (char **) argv
);
169 while (waitpid(pid
, &status
, 0) < 0) {
174 if (WIFEXITED(status
)) {
175 if (!WEXITSTATUS(status
))
184 #define push_arg(a) do { \
185 if (nr < MAXARGS) argv[nr++] = (a); \
186 else die("maximum number of args exceeded"); \
189 static int external_grep(struct grep_opt
*opt
, const char **paths
, int cached
)
191 int i
, nr
, argc
, hit
, len
, status
;
192 const char *argv
[MAXARGS
+1];
193 char randarg
[ARGBUF
];
194 char *argptr
= randarg
;
197 if (opt
->extended
|| (opt
->relative
&& opt
->prefix_length
))
207 if (opt
->regflags
& REG_EXTENDED
)
209 if (opt
->regflags
& REG_ICASE
)
211 if (opt
->word_regexp
)
215 if (opt
->unmatch_name_only
)
219 if (opt
->post_context
|| opt
->pre_context
) {
220 if (opt
->post_context
!= opt
->pre_context
) {
221 if (opt
->pre_context
) {
223 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
224 "%u", opt
->pre_context
);
225 if (sizeof(randarg
) <= len
)
226 die("maximum length of args exceeded");
230 if (opt
->post_context
) {
232 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
233 "%u", opt
->post_context
);
234 if (sizeof(randarg
) <= len
)
235 die("maximum length of args exceeded");
242 len
+= snprintf(argptr
, sizeof(randarg
)-len
,
243 "%u", opt
->post_context
);
244 if (sizeof(randarg
) <= len
)
245 die("maximum length of args exceeded");
250 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
252 push_arg(p
->pattern
);
256 * To make sure we get the header printed out when we want it,
257 * add /dev/null to the paths to grep. This is unnecessary
258 * (and wrong) with "-l" or "-L", which always print out the
261 * GNU grep has "-H", but this is portable.
263 if (!opt
->name_only
&& !opt
->unmatch_name_only
)
264 push_arg("/dev/null");
268 for (i
= 0; i
< active_nr
; i
++) {
269 struct cache_entry
*ce
= active_cache
[i
];
271 if (!S_ISREG(ntohl(ce
->ce_mode
)))
273 if (!pathspec_matches(paths
, ce
->name
))
276 if (name
[0] == '-') {
277 int len
= ce_namelen(ce
);
278 name
= xmalloc(len
+ 3);
279 memcpy(name
, "./", 2);
280 memcpy(name
+ 2, ce
->name
, len
+ 1);
283 if (argc
< MAXARGS
&& !ce_stage(ce
))
285 status
= exec_grep(argc
, argv
);
292 } while (i
< active_nr
&&
293 !strcmp(ce
->name
, active_cache
[i
]->name
));
294 i
--; /* compensate for loop control */
298 status
= exec_grep(argc
, argv
);
305 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
)
313 * Use the external "grep" command for the case where
314 * we grep through the checked-out files. It tends to
315 * be a lot more optimized
318 hit
= external_grep(opt
, paths
, cached
);
324 for (nr
= 0; nr
< active_nr
; nr
++) {
325 struct cache_entry
*ce
= active_cache
[nr
];
326 if (!S_ISREG(ntohl(ce
->ce_mode
)))
328 if (!pathspec_matches(paths
, ce
->name
))
333 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
, 0);
336 hit
|= grep_file(opt
, ce
->name
);
340 } while (nr
< active_nr
&&
341 !strcmp(ce
->name
, active_cache
[nr
]->name
));
342 nr
--; /* compensate for loop control */
345 free_grep_patterns(opt
);
349 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
350 struct tree_desc
*tree
,
351 const char *tree_name
, const char *base
)
355 struct name_entry entry
;
357 int tn_len
= strlen(tree_name
);
358 char *path_buf
= xmalloc(PATH_MAX
+ tn_len
+ 100);
361 tn_len
= sprintf(path_buf
, "%s:", tree_name
);
362 down
= path_buf
+ tn_len
;
369 len
= strlen(path_buf
);
371 while (tree_entry(tree
, &entry
)) {
372 strcpy(path_buf
+ len
, entry
.path
);
374 if (S_ISDIR(entry
.mode
))
375 /* Match "abc/" against pathspec to
376 * decide if we want to descend into "abc"
379 strcpy(path_buf
+ len
+ entry
.pathlen
, "/");
381 if (!pathspec_matches(paths
, down
))
383 else if (S_ISREG(entry
.mode
))
384 hit
|= grep_sha1(opt
, entry
.sha1
, path_buf
, tn_len
);
385 else if (S_ISDIR(entry
.mode
)) {
387 struct tree_desc sub
;
389 data
= read_sha1_file(entry
.sha1
, type
, &sub
.size
);
391 die("unable to read tree (%s)",
392 sha1_to_hex(entry
.sha1
));
394 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
401 static int grep_object(struct grep_opt
*opt
, const char **paths
,
402 struct object
*obj
, const char *name
)
404 if (obj
->type
== OBJ_BLOB
)
405 return grep_sha1(opt
, obj
->sha1
, name
, 0);
406 if (obj
->type
== OBJ_COMMIT
|| obj
->type
== OBJ_TREE
) {
407 struct tree_desc tree
;
410 data
= read_object_with_reference(obj
->sha1
, tree_type
,
413 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
415 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
419 die("unable to grep from object of type %s", typename(obj
->type
));
422 static const char builtin_grep_usage
[] =
423 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
425 static const char emsg_invalid_context_len
[] =
426 "%s: invalid context length argument";
427 static const char emsg_missing_context_len
[] =
428 "missing context length argument";
429 static const char emsg_missing_argument
[] =
430 "option requires an argument -%s";
432 int cmd_grep(int argc
, const char **argv
, const char *prefix
)
436 int seen_dashdash
= 0;
438 struct object_array list
= { 0, 0, NULL
};
439 const char **paths
= NULL
;
442 memset(&opt
, 0, sizeof(opt
));
443 opt
.prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
446 opt
.pattern_tail
= &opt
.pattern_list
;
447 opt
.regflags
= REG_NEWLINE
;
450 * If there is no -- then the paths must exist in the working
451 * tree. If there is no explicit pattern specified with -e or
452 * -f, we take the first unrecognized non option to be the
453 * pattern, but then what follows it must be zero or more
454 * valid refs up to the -- (if exists), and then existing
455 * paths. If there is an explicit pattern, then the first
456 * unrecognized non option is the beginning of the refs list
457 * that continues up to the -- (if exists), and then paths.
461 const char *arg
= argv
[1];
463 if (!strcmp("--cached", arg
)) {
467 if (!strcmp("-a", arg
) ||
468 !strcmp("--text", arg
)) {
469 opt
.binary
= GREP_BINARY_TEXT
;
472 if (!strcmp("-i", arg
) ||
473 !strcmp("--ignore-case", arg
)) {
474 opt
.regflags
|= REG_ICASE
;
477 if (!strcmp("-I", arg
)) {
478 opt
.binary
= GREP_BINARY_NOMATCH
;
481 if (!strcmp("-v", arg
) ||
482 !strcmp("--invert-match", arg
)) {
486 if (!strcmp("-E", arg
) ||
487 !strcmp("--extended-regexp", arg
)) {
488 opt
.regflags
|= REG_EXTENDED
;
491 if (!strcmp("-F", arg
) ||
492 !strcmp("--fixed-strings", arg
)) {
496 if (!strcmp("-G", arg
) ||
497 !strcmp("--basic-regexp", arg
)) {
498 opt
.regflags
&= ~REG_EXTENDED
;
501 if (!strcmp("-n", arg
)) {
505 if (!strcmp("-h", arg
)) {
509 if (!strcmp("-H", arg
)) {
513 if (!strcmp("-l", arg
) ||
514 !strcmp("--files-with-matches", arg
)) {
518 if (!strcmp("-L", arg
) ||
519 !strcmp("--files-without-match", arg
)) {
520 opt
.unmatch_name_only
= 1;
523 if (!strcmp("-c", arg
) ||
524 !strcmp("--count", arg
)) {
528 if (!strcmp("-w", arg
) ||
529 !strcmp("--word-regexp", arg
)) {
533 if (!strncmp("-A", arg
, 2) ||
534 !strncmp("-B", arg
, 2) ||
535 !strncmp("-C", arg
, 2) ||
536 (arg
[0] == '-' && '1' <= arg
[1] && arg
[1] <= '9')) {
540 case 'A': case 'B': case 'C':
543 die(emsg_missing_context_len
);
554 if (sscanf(scan
, "%u", &num
) != 1)
555 die(emsg_invalid_context_len
, scan
);
558 opt
.post_context
= num
;
562 opt
.post_context
= num
;
564 opt
.pre_context
= num
;
569 if (!strcmp("-f", arg
)) {
574 die(emsg_missing_argument
, arg
);
575 patterns
= fopen(argv
[1], "r");
577 die("'%s': %s", argv
[1], strerror(errno
));
578 while (fgets(buf
, sizeof(buf
), patterns
)) {
579 int len
= strlen(buf
);
580 if (buf
[len
-1] == '\n')
582 /* ignore empty line like grep does */
585 append_grep_pattern(&opt
, xstrdup(buf
),
594 if (!strcmp("--not", arg
)) {
595 append_grep_pattern(&opt
, arg
, "command line", 0,
599 if (!strcmp("--and", arg
)) {
600 append_grep_pattern(&opt
, arg
, "command line", 0,
604 if (!strcmp("--or", arg
))
605 continue; /* no-op */
606 if (!strcmp("(", arg
)) {
607 append_grep_pattern(&opt
, arg
, "command line", 0,
611 if (!strcmp(")", arg
)) {
612 append_grep_pattern(&opt
, arg
, "command line", 0,
616 if (!strcmp("--all-match", arg
)) {
620 if (!strcmp("-e", arg
)) {
622 append_grep_pattern(&opt
, argv
[1],
629 die(emsg_missing_argument
, arg
);
631 if (!strcmp("--full-name", arg
)) {
635 if (!strcmp("--", arg
)) {
636 /* later processing wants to have this at argv[1] */
642 usage(builtin_grep_usage
);
644 /* First unrecognized non-option token */
645 if (!opt
.pattern_list
) {
646 append_grep_pattern(&opt
, arg
, "command line", 0,
651 /* We are looking at the first path or rev;
652 * it is found at argv[1] after leaving the
660 if (!opt
.pattern_list
)
661 die("no pattern given.");
662 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
663 die("cannot mix --fixed-strings and regexp");
664 compile_grep_patterns(&opt
);
666 /* Check revs and then paths */
667 for (i
= 1; i
< argc
; i
++) {
668 const char *arg
= argv
[i
];
669 unsigned char sha1
[20];
671 if (!get_sha1(arg
, sha1
)) {
672 struct object
*object
= parse_object(sha1
);
674 die("bad object %s", arg
);
675 add_object_array(object
, arg
, &list
);
678 if (!strcmp(arg
, "--")) {
685 /* The rest are paths */
686 if (!seen_dashdash
) {
688 for (j
= i
; j
< argc
; j
++)
689 verify_filename(prefix
, argv
[j
]);
693 paths
= get_pathspec(prefix
, argv
+ i
);
694 if (opt
.prefix_length
&& opt
.relative
) {
695 /* Make sure we do not get outside of paths */
696 for (i
= 0; paths
[i
]; i
++)
697 if (strncmp(prefix
, paths
[i
], opt
.prefix_length
))
698 die("git-grep: cannot generate relative filenames containing '..'");
702 paths
= xcalloc(2, sizeof(const char *));
708 return !grep_cache(&opt
, paths
, cached
);
711 die("both --cached and trees are given.");
713 for (i
= 0; i
< list
.nr
; i
++) {
714 struct object
*real_obj
;
715 real_obj
= deref_tag(list
.objects
[i
].item
, NULL
, 0);
716 if (grep_object(&opt
, paths
, real_obj
, list
.objects
[i
].name
))
719 free_grep_patterns(&opt
);