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
24 * git grep pathspecs are somewhat different from diff-tree pathspecs;
25 * pathname wildcards are allowed.
27 static int pathspec_matches(const char **paths, const char *name)
30 if (!paths || !*paths)
32 namelen = strlen(name);
33 for (i = 0; paths[i]; i++) {
34 const char *match = paths[i];
35 int matchlen = strlen(match);
36 const char *cp, *meta;
39 ((matchlen <= namelen) &&
40 !strncmp(name, match, matchlen) &&
41 (match[matchlen-1] == '/' ||
42 name[matchlen] == '\0' || name[matchlen] == '/')))
44 if (!fnmatch(match, name, 0))
46 if (name[namelen-1] != '/')
49 /* We are being asked if the directory ("name") is worth
52 * Find the longest leading directory name that does
53 * not have metacharacter in the pathspec; the name
54 * we are looking at must overlap with that directory.
56 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
58 if (ch == '*' || ch == '[' || ch == '?') {
64 meta = cp; /* fully literal */
66 if (namelen <= meta - match) {
67 /* Looking at "Documentation/" and
68 * the pattern says "Documentation/howto/", or
69 * "Documentation/diff*.txt". The name we
70 * have should match prefix.
72 if (!memcmp(match, name, namelen))
77 if (meta - match < namelen) {
78 /* Looking at "Documentation/howto/" and
79 * the pattern says "Documentation/h*";
80 * match up to "Do.../h"; this avoids descending
81 * into "Documentation/technical/".
83 if (!memcmp(match, name, meta - match))
91 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
95 enum object_type type;
99 data = read_sha1_file(sha1, &type, &size);
101 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
104 if (opt->relative && opt->prefix_length) {
105 static char name_buf[PATH_MAX];
107 int name_len = strlen(name) - opt->prefix_length + 1;
110 name += opt->prefix_length;
112 if (ARRAY_SIZE(name_buf) <= name_len)
113 cp = to_free = xmalloc(name_len);
116 memcpy(cp, name, tree_name_len);
117 strcpy(cp + tree_name_len,
118 name + tree_name_len + opt->prefix_length);
122 hit = grep_buffer(opt, name, data, size);
128 static int grep_file(struct grep_opt *opt, const char *filename)
135 if (lstat(filename, &st) < 0) {
138 error("'%s': %s", filename, strerror(errno));
142 return 0; /* empty file -- no grep hit */
143 if (!S_ISREG(st.st_mode))
145 sz = xsize_t(st.st_size);
146 i = open(filename, O_RDONLY);
149 data = xmalloc(sz + 1);
150 if (st.st_size != read_in_full(i, data, sz)) {
151 error("'%s': short read %s", filename, strerror(errno));
157 if (opt->relative && opt->prefix_length)
158 filename += opt->prefix_length;
159 i = grep_buffer(opt, filename, data, sz);
164 #if !NO_EXTERNAL_GREP
165 static int exec_grep(int argc, const char **argv)
175 execvp("grep", (char **) argv);
178 while (waitpid(pid, &status, 0) < 0) {
183 if (WIFEXITED(status)) {
184 if (!WEXITSTATUS(status))
193 #define push_arg(a) do { \
194 if (nr < MAXARGS) argv[nr++] = (a); \
195 else die("maximum number of args exceeded"); \
199 * If you send a singleton filename to grep, it does not give
200 * the name of the file. GNU grep has "-H" but we would want
201 * that behaviour in a portable way.
203 * So we keep two pathnames in argv buffer unsent to grep in
204 * the main loop if we need to do more than one grep.
206 static int flush_grep(struct grep_opt *opt,
207 int argc, int arg0, const char **argv, int *kept)
210 int count = argc - arg0;
211 const char *kept_0 = NULL;
215 * Because we keep at least 2 paths in the call from
216 * the main loop (i.e. kept != NULL), and MAXARGS is
217 * far greater than 2, this usually is a call to
218 * conclude the grep. However, the user could attempt
219 * to overflow the argv buffer by giving too many
220 * options to leave very small number of real
221 * arguments even for the call in the main loop.
224 die("insanely many options to grep");
227 * If we have two or more paths, we do not have to do
228 * anything special, but we need to push /dev/null to
229 * get "-H" behaviour of GNU grep portably but when we
230 * are not doing "-l" nor "-L" nor "-c".
234 !opt->unmatch_name_only &&
236 argv[argc++] = "/dev/null";
243 * Called because we found many paths and haven't finished
244 * iterating over the cache yet. We keep two paths
245 * for the concluding call. argv[argc-2] and argv[argc-1]
246 * has the last two paths, so save the first one away,
247 * replace it with NULL while sending the list to grep,
248 * and recover them after we are done.
251 kept_0 = argv[argc-2];
256 status = exec_grep(argc, argv);
260 * Then recover them. Now the last arg is beyond the
261 * terminating NULL which is at argc, and the second
262 * from the last is what we saved away in kept_0
264 argv[arg0++] = kept_0;
265 argv[arg0] = argv[argc+1];
270 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
272 int i, nr, argc, hit, len, status;
273 const char *argv[MAXARGS+1];
274 char randarg[ARGBUF];
275 char *argptr = randarg;
278 if (opt->extended || (opt->relative && opt->prefix_length))
288 if (opt->regflags & REG_EXTENDED)
290 if (opt->regflags & REG_ICASE)
292 if (opt->word_regexp)
296 if (opt->unmatch_name_only)
300 if (opt->post_context || opt->pre_context) {
301 if (opt->post_context != opt->pre_context) {
302 if (opt->pre_context) {
304 len += snprintf(argptr, sizeof(randarg)-len,
305 "%u", opt->pre_context) + 1;
306 if (sizeof(randarg) <= len)
307 die("maximum length of args exceeded");
311 if (opt->post_context) {
313 len += snprintf(argptr, sizeof(randarg)-len,
314 "%u", opt->post_context) + 1;
315 if (sizeof(randarg) <= len)
316 die("maximum length of args exceeded");
323 len += snprintf(argptr, sizeof(randarg)-len,
324 "%u", opt->post_context) + 1;
325 if (sizeof(randarg) <= len)
326 die("maximum length of args exceeded");
331 for (p = opt->pattern_list; p; p = p->next) {
333 push_arg(p->pattern);
338 for (i = 0; i < active_nr; i++) {
339 struct cache_entry *ce = active_cache[i];
342 if (!S_ISREG(ce->ce_mode))
344 if (!pathspec_matches(paths, ce->name))
347 if (name[0] == '-') {
348 int len = ce_namelen(ce);
349 name = xmalloc(len + 3);
350 memcpy(name, "./", 2);
351 memcpy(name + 2, ce->name, len + 1);
354 if (MAXARGS <= argc) {
355 status = flush_grep(opt, argc, nr, argv, &kept);
363 } while (i < active_nr &&
364 !strcmp(ce->name, active_cache[i]->name));
365 i--; /* compensate for loop control */
369 status = flush_grep(opt, argc, nr, argv, NULL);
377 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
383 #if !NO_EXTERNAL_GREP
385 * Use the external "grep" command for the case where
386 * we grep through the checked-out files. It tends to
387 * be a lot more optimized
390 hit = external_grep(opt, paths, cached);
396 for (nr = 0; nr < active_nr; nr++) {
397 struct cache_entry *ce = active_cache[nr];
398 if (!S_ISREG(ce->ce_mode))
400 if (!pathspec_matches(paths, ce->name))
405 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
408 hit |= grep_file(opt, ce->name);
412 } while (nr < active_nr &&
413 !strcmp(ce->name, active_cache[nr]->name));
414 nr--; /* compensate for loop control */
417 free_grep_patterns(opt);
421 static int grep_tree(struct grep_opt *opt, const char **paths,
422 struct tree_desc *tree,
423 const char *tree_name, const char *base)
427 struct name_entry entry;
429 int tn_len = strlen(tree_name);
430 char *path_buf = xmalloc(PATH_MAX + tn_len + 100);
433 tn_len = sprintf(path_buf, "%s:", tree_name);
434 down = path_buf + tn_len;
441 len = strlen(path_buf);
443 while (tree_entry(tree, &entry)) {
444 strcpy(path_buf + len, entry.path);
446 if (S_ISDIR(entry.mode))
447 /* Match "abc/" against pathspec to
448 * decide if we want to descend into "abc"
451 strcpy(path_buf + len + tree_entry_len(entry.path, entry.sha1), "/");
453 if (!pathspec_matches(paths, down))
455 else if (S_ISREG(entry.mode))
456 hit |= grep_sha1(opt, entry.sha1, path_buf, tn_len);
457 else if (S_ISDIR(entry.mode)) {
458 enum object_type type;
459 struct tree_desc sub;
463 data = read_sha1_file(entry.sha1, &type, &size);
465 die("unable to read tree (%s)",
466 sha1_to_hex(entry.sha1));
467 init_tree_desc(&sub, data, size);
468 hit |= grep_tree(opt, paths, &sub, tree_name, down);
475 static int grep_object(struct grep_opt *opt, const char **paths,
476 struct object *obj, const char *name)
478 if (obj->type == OBJ_BLOB)
479 return grep_sha1(opt, obj->sha1, name, 0);
480 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
481 struct tree_desc tree;
485 data = read_object_with_reference(obj->sha1, tree_type,
488 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
489 init_tree_desc(&tree, data, size);
490 hit = grep_tree(opt, paths, &tree, name, "");
494 die("unable to grep from object of type %s", typename(obj->type));
497 static const char builtin_grep_usage[] =
498 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
500 static const char emsg_invalid_context_len[] =
501 "%s: invalid context length argument";
502 static const char emsg_missing_context_len[] =
503 "missing context length argument";
504 static const char emsg_missing_argument[] =
505 "option requires an argument -%s";
507 int cmd_grep(int argc, const char **argv, const char *prefix)
511 int seen_dashdash = 0;
513 struct object_array list = { 0, 0, NULL };
514 const char **paths = NULL;
517 memset(&opt, 0, sizeof(opt));
518 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
521 opt.pattern_tail = &opt.pattern_list;
522 opt.regflags = REG_NEWLINE;
525 * If there is no -- then the paths must exist in the working
526 * tree. If there is no explicit pattern specified with -e or
527 * -f, we take the first unrecognized non option to be the
528 * pattern, but then what follows it must be zero or more
529 * valid refs up to the -- (if exists), and then existing
530 * paths. If there is an explicit pattern, then the first
531 * unrecognized non option is the beginning of the refs list
532 * that continues up to the -- (if exists), and then paths.
536 const char *arg = argv[1];
538 if (!strcmp("--cached", arg)) {
542 if (!strcmp("-a", arg) ||
543 !strcmp("--text", arg)) {
544 opt.binary = GREP_BINARY_TEXT;
547 if (!strcmp("-i", arg) ||
548 !strcmp("--ignore-case", arg)) {
549 opt.regflags |= REG_ICASE;
552 if (!strcmp("-I", arg)) {
553 opt.binary = GREP_BINARY_NOMATCH;
556 if (!strcmp("-v", arg) ||
557 !strcmp("--invert-match", arg)) {
561 if (!strcmp("-E", arg) ||
562 !strcmp("--extended-regexp", arg)) {
563 opt.regflags |= REG_EXTENDED;
566 if (!strcmp("-F", arg) ||
567 !strcmp("--fixed-strings", arg)) {
571 if (!strcmp("-G", arg) ||
572 !strcmp("--basic-regexp", arg)) {
573 opt.regflags &= ~REG_EXTENDED;
576 if (!strcmp("-n", arg)) {
580 if (!strcmp("-h", arg)) {
584 if (!strcmp("-H", arg)) {
588 if (!strcmp("-l", arg) ||
589 !strcmp("--name-only", arg) ||
590 !strcmp("--files-with-matches", arg)) {
594 if (!strcmp("-L", arg) ||
595 !strcmp("--files-without-match", arg)) {
596 opt.unmatch_name_only = 1;
599 if (!strcmp("-c", arg) ||
600 !strcmp("--count", arg)) {
604 if (!strcmp("-w", arg) ||
605 !strcmp("--word-regexp", arg)) {
609 if (!prefixcmp(arg, "-A") ||
610 !prefixcmp(arg, "-B") ||
611 !prefixcmp(arg, "-C") ||
612 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
616 case 'A': case 'B': case 'C':
619 die(emsg_missing_context_len);
630 if (strtoul_ui(scan, 10, &num))
631 die(emsg_invalid_context_len, scan);
634 opt.post_context = num;
638 opt.post_context = num;
640 opt.pre_context = num;
645 if (!strcmp("-f", arg)) {
650 die(emsg_missing_argument, arg);
651 patterns = fopen(argv[1], "r");
653 die("'%s': %s", argv[1], strerror(errno));
654 while (fgets(buf, sizeof(buf), patterns)) {
655 int len = strlen(buf);
656 if (len && buf[len-1] == '\n')
658 /* ignore empty line like grep does */
661 append_grep_pattern(&opt, xstrdup(buf),
670 if (!strcmp("--not", arg)) {
671 append_grep_pattern(&opt, arg, "command line", 0,
675 if (!strcmp("--and", arg)) {
676 append_grep_pattern(&opt, arg, "command line", 0,
680 if (!strcmp("--or", arg))
681 continue; /* no-op */
682 if (!strcmp("(", arg)) {
683 append_grep_pattern(&opt, arg, "command line", 0,
687 if (!strcmp(")", arg)) {
688 append_grep_pattern(&opt, arg, "command line", 0,
692 if (!strcmp("--all-match", arg)) {
696 if (!strcmp("-e", arg)) {
698 append_grep_pattern(&opt, argv[1],
705 die(emsg_missing_argument, arg);
707 if (!strcmp("--full-name", arg)) {
711 if (!strcmp("--", arg)) {
712 /* later processing wants to have this at argv[1] */
718 usage(builtin_grep_usage);
720 /* First unrecognized non-option token */
721 if (!opt.pattern_list) {
722 append_grep_pattern(&opt, arg, "command line", 0,
727 /* We are looking at the first path or rev;
728 * it is found at argv[1] after leaving the
736 if (!opt.pattern_list)
737 die("no pattern given.");
738 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
739 die("cannot mix --fixed-strings and regexp");
740 compile_grep_patterns(&opt);
742 /* Check revs and then paths */
743 for (i = 1; i < argc; i++) {
744 const char *arg = argv[i];
745 unsigned char sha1[20];
747 if (!get_sha1(arg, sha1)) {
748 struct object *object = parse_object(sha1);
750 die("bad object %s", arg);
751 add_object_array(object, arg, &list);
754 if (!strcmp(arg, "--")) {
761 /* The rest are paths */
762 if (!seen_dashdash) {
764 for (j = i; j < argc; j++)
765 verify_filename(prefix, argv[j]);
769 paths = get_pathspec(prefix, argv + i);
770 if (opt.prefix_length && opt.relative) {
771 /* Make sure we do not get outside of paths */
772 for (i = 0; paths[i]; i++)
773 if (strncmp(prefix, paths[i], opt.prefix_length))
774 die("git-grep: cannot generate relative filenames containing '..'");
778 paths = xcalloc(2, sizeof(const char *));
784 return !grep_cache(&opt, paths, cached);
787 die("both --cached and trees are given.");
789 for (i = 0; i < list.nr; i++) {
790 struct object *real_obj;
791 real_obj = deref_tag(list.objects[i].item, NULL, 0);
792 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
795 free_grep_patterns(&opt);