4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
13 #include "parse-options.h"
16 #ifndef NO_EXTERNAL_GREP
18 #define NO_EXTERNAL_GREP 0
20 #define NO_EXTERNAL_GREP 1
24 static char const * const grep_usage[] = {
25 "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
29 static int grep_config(const char *var, const char *value, void *cb)
31 struct grep_opt *opt = cb;
33 if (!strcmp(var, "color.grep")) {
34 opt->color = git_config_colorbool(var, value, -1);
37 if (!strcmp(var, "color.grep.external"))
38 return git_config_string(&(opt->color_external), var, value);
39 if (!strcmp(var, "color.grep.match")) {
41 return config_error_nonbool(var);
42 color_parse(value, var, opt->color_match);
45 return git_color_default_config(var, value, cb);
49 * git grep pathspecs are somewhat different from diff-tree pathspecs;
50 * pathname wildcards are allowed.
52 static int pathspec_matches(const char **paths, const char *name)
55 if (!paths || !*paths)
57 namelen = strlen(name);
58 for (i = 0; paths[i]; i++) {
59 const char *match = paths[i];
60 int matchlen = strlen(match);
61 const char *cp, *meta;
64 ((matchlen <= namelen) &&
65 !strncmp(name, match, matchlen) &&
66 (match[matchlen-1] == '/' ||
67 name[matchlen] == '\0' || name[matchlen] == '/')))
69 if (!fnmatch(match, name, 0))
71 if (name[namelen-1] != '/')
74 /* We are being asked if the directory ("name") is worth
77 * Find the longest leading directory name that does
78 * not have metacharacter in the pathspec; the name
79 * we are looking at must overlap with that directory.
81 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
83 if (ch == '*' || ch == '[' || ch == '?') {
89 meta = cp; /* fully literal */
91 if (namelen <= meta - match) {
92 /* Looking at "Documentation/" and
93 * the pattern says "Documentation/howto/", or
94 * "Documentation/diff*.txt". The name we
95 * have should match prefix.
97 if (!memcmp(match, name, namelen))
102 if (meta - match < namelen) {
103 /* Looking at "Documentation/howto/" and
104 * the pattern says "Documentation/h*";
105 * match up to "Do.../h"; this avoids descending
106 * into "Documentation/technical/".
108 if (!memcmp(match, name, meta - match))
116 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
120 enum object_type type;
121 char *to_free = NULL;
124 data = read_sha1_file(sha1, &type, &size);
126 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
129 if (opt->relative && opt->prefix_length) {
130 static char name_buf[PATH_MAX];
132 int name_len = strlen(name) - opt->prefix_length + 1;
135 name += opt->prefix_length;
137 if (ARRAY_SIZE(name_buf) <= name_len)
138 cp = to_free = xmalloc(name_len);
141 memcpy(cp, name, tree_name_len);
142 strcpy(cp + tree_name_len,
143 name + tree_name_len + opt->prefix_length);
147 hit = grep_buffer(opt, name, data, size);
153 static int grep_file(struct grep_opt *opt, const char *filename)
160 if (lstat(filename, &st) < 0) {
163 error("'%s': %s", filename, strerror(errno));
167 return 0; /* empty file -- no grep hit */
168 if (!S_ISREG(st.st_mode))
170 sz = xsize_t(st.st_size);
171 i = open(filename, O_RDONLY);
174 data = xmalloc(sz + 1);
175 if (st.st_size != read_in_full(i, data, sz)) {
176 error("'%s': short read %s", filename, strerror(errno));
182 if (opt->relative && opt->prefix_length)
183 filename += opt->prefix_length;
184 i = grep_buffer(opt, filename, data, sz);
189 #if !NO_EXTERNAL_GREP
190 static int exec_grep(int argc, const char **argv)
200 execvp("grep", (char **) argv);
203 while (waitpid(pid, &status, 0) < 0) {
208 if (WIFEXITED(status)) {
209 if (!WEXITSTATUS(status))
218 #define push_arg(a) do { \
219 if (nr < MAXARGS) argv[nr++] = (a); \
220 else die("maximum number of args exceeded"); \
224 * If you send a singleton filename to grep, it does not give
225 * the name of the file. GNU grep has "-H" but we would want
226 * that behaviour in a portable way.
228 * So we keep two pathnames in argv buffer unsent to grep in
229 * the main loop if we need to do more than one grep.
231 static int flush_grep(struct grep_opt *opt,
232 int argc, int arg0, const char **argv, int *kept)
235 int count = argc - arg0;
236 const char *kept_0 = NULL;
240 * Because we keep at least 2 paths in the call from
241 * the main loop (i.e. kept != NULL), and MAXARGS is
242 * far greater than 2, this usually is a call to
243 * conclude the grep. However, the user could attempt
244 * to overflow the argv buffer by giving too many
245 * options to leave very small number of real
246 * arguments even for the call in the main loop.
249 die("insanely many options to grep");
252 * If we have two or more paths, we do not have to do
253 * anything special, but we need to push /dev/null to
254 * get "-H" behaviour of GNU grep portably but when we
255 * are not doing "-l" nor "-L" nor "-c".
259 !opt->unmatch_name_only &&
261 argv[argc++] = "/dev/null";
268 * Called because we found many paths and haven't finished
269 * iterating over the cache yet. We keep two paths
270 * for the concluding call. argv[argc-2] and argv[argc-1]
271 * has the last two paths, so save the first one away,
272 * replace it with NULL while sending the list to grep,
273 * and recover them after we are done.
276 kept_0 = argv[argc-2];
281 status = exec_grep(argc, argv);
285 * Then recover them. Now the last arg is beyond the
286 * terminating NULL which is at argc, and the second
287 * from the last is what we saved away in kept_0
289 argv[arg0++] = kept_0;
290 argv[arg0] = argv[argc+1];
295 static void grep_add_color(struct strbuf *sb, const char *escape_seq)
297 size_t orig_len = sb->len;
299 while (*escape_seq) {
300 if (*escape_seq == 'm')
301 strbuf_addch(sb, ';');
302 else if (*escape_seq != '\033' && *escape_seq != '[')
303 strbuf_addch(sb, *escape_seq);
306 if (sb->len > orig_len && sb->buf[sb->len - 1] == ';')
307 strbuf_setlen(sb, sb->len - 1);
310 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
312 int i, nr, argc, hit, len, status;
313 const char *argv[MAXARGS+1];
314 char randarg[ARGBUF];
315 char *argptr = randarg;
318 if (opt->extended || (opt->relative && opt->prefix_length))
328 if (opt->regflags & REG_EXTENDED)
330 if (opt->regflags & REG_ICASE)
332 if (opt->binary == GREP_BINARY_NOMATCH)
334 if (opt->word_regexp)
338 if (opt->unmatch_name_only)
340 if (opt->null_following_name)
341 /* in GNU grep git's "-z" translates to "-Z" */
345 if (opt->post_context || opt->pre_context) {
346 if (opt->post_context != opt->pre_context) {
347 if (opt->pre_context) {
349 len += snprintf(argptr, sizeof(randarg)-len,
350 "%u", opt->pre_context) + 1;
351 if (sizeof(randarg) <= len)
352 die("maximum length of args exceeded");
356 if (opt->post_context) {
358 len += snprintf(argptr, sizeof(randarg)-len,
359 "%u", opt->post_context) + 1;
360 if (sizeof(randarg) <= len)
361 die("maximum length of args exceeded");
368 len += snprintf(argptr, sizeof(randarg)-len,
369 "%u", opt->post_context) + 1;
370 if (sizeof(randarg) <= len)
371 die("maximum length of args exceeded");
376 for (p = opt->pattern_list; p; p = p->next) {
378 push_arg(p->pattern);
381 struct strbuf sb = STRBUF_INIT;
383 grep_add_color(&sb, opt->color_match);
384 setenv("GREP_COLOR", sb.buf, 1);
387 strbuf_addstr(&sb, "mt=");
388 grep_add_color(&sb, opt->color_match);
389 strbuf_addstr(&sb, ":sl=:cx=:fn=:ln=:bn=:se=");
390 setenv("GREP_COLORS", sb.buf, 1);
394 if (opt->color_external && strlen(opt->color_external) > 0)
395 push_arg(opt->color_external);
400 for (i = 0; i < active_nr; i++) {
401 struct cache_entry *ce = active_cache[i];
404 if (!S_ISREG(ce->ce_mode))
406 if (!pathspec_matches(paths, ce->name))
409 if (name[0] == '-') {
410 int len = ce_namelen(ce);
411 name = xmalloc(len + 3);
412 memcpy(name, "./", 2);
413 memcpy(name + 2, ce->name, len + 1);
416 if (MAXARGS <= argc) {
417 status = flush_grep(opt, argc, nr, argv, &kept);
425 } while (i < active_nr &&
426 !strcmp(ce->name, active_cache[i]->name));
427 i--; /* compensate for loop control */
431 status = flush_grep(opt, argc, nr, argv, NULL);
439 static int grep_cache(struct grep_opt *opt, const char **paths, int cached,
440 int external_grep_allowed)
446 #if !NO_EXTERNAL_GREP
448 * Use the external "grep" command for the case where
449 * we grep through the checked-out files. It tends to
450 * be a lot more optimized
452 if (!cached && external_grep_allowed) {
453 hit = external_grep(opt, paths, cached);
459 for (nr = 0; nr < active_nr; nr++) {
460 struct cache_entry *ce = active_cache[nr];
461 if (!S_ISREG(ce->ce_mode))
463 if (!pathspec_matches(paths, ce->name))
466 * If CE_VALID is on, we assume worktree file and its cache entry
467 * are identical, even if worktree file has been modified, so use
468 * cache version instead
470 if (cached || (ce->ce_flags & CE_VALID)) {
473 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
476 hit |= grep_file(opt, ce->name);
480 } while (nr < active_nr &&
481 !strcmp(ce->name, active_cache[nr]->name));
482 nr--; /* compensate for loop control */
485 free_grep_patterns(opt);
489 static int grep_tree(struct grep_opt *opt, const char **paths,
490 struct tree_desc *tree,
491 const char *tree_name, const char *base)
495 struct name_entry entry;
497 int tn_len = strlen(tree_name);
498 struct strbuf pathbuf;
500 strbuf_init(&pathbuf, PATH_MAX + tn_len);
503 strbuf_add(&pathbuf, tree_name, tn_len);
504 strbuf_addch(&pathbuf, ':');
505 tn_len = pathbuf.len;
507 strbuf_addstr(&pathbuf, base);
510 while (tree_entry(tree, &entry)) {
511 int te_len = tree_entry_len(entry.path, entry.sha1);
513 strbuf_add(&pathbuf, entry.path, te_len);
515 if (S_ISDIR(entry.mode))
516 /* Match "abc/" against pathspec to
517 * decide if we want to descend into "abc"
520 strbuf_addch(&pathbuf, '/');
522 down = pathbuf.buf + tn_len;
523 if (!pathspec_matches(paths, down))
525 else if (S_ISREG(entry.mode))
526 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
527 else if (S_ISDIR(entry.mode)) {
528 enum object_type type;
529 struct tree_desc sub;
533 data = read_sha1_file(entry.sha1, &type, &size);
535 die("unable to read tree (%s)",
536 sha1_to_hex(entry.sha1));
537 init_tree_desc(&sub, data, size);
538 hit |= grep_tree(opt, paths, &sub, tree_name, down);
542 strbuf_release(&pathbuf);
546 static int grep_object(struct grep_opt *opt, const char **paths,
547 struct object *obj, const char *name)
549 if (obj->type == OBJ_BLOB)
550 return grep_sha1(opt, obj->sha1, name, 0);
551 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
552 struct tree_desc tree;
556 data = read_object_with_reference(obj->sha1, tree_type,
559 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
560 init_tree_desc(&tree, data, size);
561 hit = grep_tree(opt, paths, &tree, name, "");
565 die("unable to grep from object of type %s", typename(obj->type));
568 static int context_callback(const struct option *opt, const char *arg,
571 struct grep_opt *grep_opt = opt->value;
576 grep_opt->pre_context = grep_opt->post_context = 0;
579 value = strtol(arg, (char **)&endp, 10);
581 return error("switch `%c' expects a numerical value",
584 grep_opt->pre_context = grep_opt->post_context = value;
588 static int file_callback(const struct option *opt, const char *arg, int unset)
590 struct grep_opt *grep_opt = opt->value;
595 patterns = fopen(arg, "r");
597 die("'%s': %s", arg, strerror(errno));
598 while (strbuf_getline(&sb, patterns, '\n') == 0) {
599 /* ignore empty line like grep does */
602 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
603 ++lno, GREP_PATTERN);
610 static int not_callback(const struct option *opt, const char *arg, int unset)
612 struct grep_opt *grep_opt = opt->value;
613 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
617 static int and_callback(const struct option *opt, const char *arg, int unset)
619 struct grep_opt *grep_opt = opt->value;
620 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
624 static int open_callback(const struct option *opt, const char *arg, int unset)
626 struct grep_opt *grep_opt = opt->value;
627 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
631 static int close_callback(const struct option *opt, const char *arg, int unset)
633 struct grep_opt *grep_opt = opt->value;
634 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
638 static int pattern_callback(const struct option *opt, const char *arg,
641 struct grep_opt *grep_opt = opt->value;
642 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
646 static int help_callback(const struct option *opt, const char *arg, int unset)
651 int cmd_grep(int argc, const char **argv, const char *prefix)
655 int external_grep_allowed = 1;
656 int seen_dashdash = 0;
658 struct object_array list = { 0, 0, NULL };
659 const char **paths = NULL;
662 struct option options[] = {
663 OPT_BOOLEAN(0, "cached", &cached,
664 "search in index instead of in the work tree"),
666 OPT_BOOLEAN('v', "invert-match", &opt.invert,
667 "show non-matching lines"),
668 OPT_BIT('i', "ignore-case", &opt.regflags,
669 "case insensitive matching", REG_ICASE),
670 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
671 "match patterns only at word boundaries"),
672 OPT_SET_INT('a', "text", &opt.binary,
673 "process binary files as text", GREP_BINARY_TEXT),
674 OPT_SET_INT('I', NULL, &opt.binary,
675 "don't match patterns in binary files",
676 GREP_BINARY_NOMATCH),
678 OPT_BIT('E', "extended-regexp", &opt.regflags,
679 "use extended POSIX regular expressions", REG_EXTENDED),
680 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
681 "use basic POSIX regular expressions (default)",
683 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
684 "interpret patterns as fixed strings"),
686 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
687 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
688 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
689 OPT_NEGBIT(0, "full-name", &opt.relative,
690 "show filenames relative to top directory", 1),
691 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
692 "show only filenames instead of matching lines"),
693 OPT_BOOLEAN(0, "name-only", &opt.name_only,
694 "synonym for --files-with-matches"),
695 OPT_BOOLEAN('L', "files-without-match",
696 &opt.unmatch_name_only,
697 "show only the names of files without match"),
698 OPT_BOOLEAN('z', "null", &opt.null_following_name,
699 "print NUL after filenames"),
700 OPT_BOOLEAN('c', "count", &opt.count,
701 "show the number of matches instead of matching lines"),
702 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
704 OPT_CALLBACK('C', NULL, &opt, "n",
705 "show <n> context lines before and after matches",
707 OPT_INTEGER('B', NULL, &opt.pre_context,
708 "show <n> context lines before matches"),
709 OPT_INTEGER('A', NULL, &opt.post_context,
710 "show <n> context lines after matches"),
711 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
714 OPT_CALLBACK('f', NULL, &opt, "file",
715 "read patterns from file", file_callback),
716 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
717 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
718 { OPTION_CALLBACK, 0, "and", &opt, NULL,
719 "combine patterns specified with -e",
720 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
721 OPT_BOOLEAN(0, "or", &dummy, ""),
722 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
723 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
724 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
725 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
727 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
728 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
730 OPT_BOOLEAN(0, "all-match", &opt.all_match,
731 "show only matches from files that match all patterns"),
734 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
735 "allow calling of grep(1) (ignored by this build)"),
737 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
738 "allow calling of grep(1) (default)"),
740 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
741 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
745 memset(&opt, 0, sizeof(opt));
746 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
749 opt.pattern_tail = &opt.pattern_list;
750 opt.regflags = REG_NEWLINE;
752 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
754 git_config(grep_config, &opt);
756 opt.color = git_use_color_default;
759 * If there is no -- then the paths must exist in the working
760 * tree. If there is no explicit pattern specified with -e or
761 * -f, we take the first unrecognized non option to be the
762 * pattern, but then what follows it must be zero or more
763 * valid refs up to the -- (if exists), and then existing
764 * paths. If there is an explicit pattern, then the first
765 * unrecognized non option is the beginning of the refs list
766 * that continues up to the -- (if exists), and then paths.
768 argc = parse_options(argc, argv, prefix, options, grep_usage,
769 PARSE_OPT_KEEP_DASHDASH |
770 PARSE_OPT_STOP_AT_NON_OPTION |
771 PARSE_OPT_NO_INTERNAL_HELP);
773 /* First unrecognized non-option token */
774 if (argc > 0 && !opt.pattern_list) {
775 append_grep_pattern(&opt, argv[0], "command line", 0,
781 if (opt.color && !opt.color_external)
782 external_grep_allowed = 0;
783 if (!opt.pattern_list)
784 die("no pattern given.");
785 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
786 die("cannot mix --fixed-strings and regexp");
787 compile_grep_patterns(&opt);
789 /* Check revs and then paths */
790 for (i = 0; i < argc; i++) {
791 const char *arg = argv[i];
792 unsigned char sha1[20];
794 if (!get_sha1(arg, sha1)) {
795 struct object *object = parse_object(sha1);
797 die("bad object %s", arg);
798 add_object_array(object, arg, &list);
801 if (!strcmp(arg, "--")) {
808 /* The rest are paths */
809 if (!seen_dashdash) {
811 for (j = i; j < argc; j++)
812 verify_filename(prefix, argv[j]);
816 paths = get_pathspec(prefix, argv + i);
817 if (opt.prefix_length && opt.relative) {
818 /* Make sure we do not get outside of paths */
819 for (i = 0; paths[i]; i++)
820 if (strncmp(prefix, paths[i], opt.prefix_length))
821 die("git grep: cannot generate relative filenames containing '..'");
825 paths = xcalloc(2, sizeof(const char *));
833 return !grep_cache(&opt, paths, cached, external_grep_allowed);
837 die("both --cached and trees are given.");
839 for (i = 0; i < list.nr; i++) {
840 struct object *real_obj;
841 real_obj = deref_tag(list.objects[i].item, NULL, 0);
842 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
845 free_grep_patterns(&opt);