4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
13 #include "parse-options.h"
17 #ifndef NO_EXTERNAL_GREP
19 #define NO_EXTERNAL_GREP 0
21 #define NO_EXTERNAL_GREP 1
25 static char const * const grep_usage[] = {
26 "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
30 static int grep_config(const char *var, const char *value, void *cb)
32 struct grep_opt *opt = cb;
34 switch (userdiff_config(var, value)) {
40 if (!strcmp(var, "color.grep")) {
41 opt->color = git_config_colorbool(var, value, -1);
44 if (!strcmp(var, "color.grep.external"))
45 return git_config_string(&(opt->color_external), var, value);
46 if (!strcmp(var, "color.grep.match")) {
48 return config_error_nonbool(var);
49 color_parse(value, var, opt->color_match);
52 return git_color_default_config(var, value, cb);
56 * Return non-zero if max_depth is negative or path has no more then max_depth
59 static int accept_subdir(const char *path, int max_depth)
64 while ((path = strchr(path, '/')) != NULL) {
74 * Return non-zero if name is a subdirectory of match and is not too deep.
76 static int is_subdir(const char *name, int namelen,
77 const char *match, int matchlen, int max_depth)
79 if (matchlen > namelen || strncmp(name, match, matchlen))
82 if (name[matchlen] == '\0') /* exact match */
85 if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
86 return accept_subdir(name + matchlen + 1, max_depth);
92 * git grep pathspecs are somewhat different from diff-tree pathspecs;
93 * pathname wildcards are allowed.
95 static int pathspec_matches(const char **paths, const char *name, int max_depth)
98 if (!paths || !*paths)
99 return accept_subdir(name, max_depth);
100 namelen = strlen(name);
101 for (i = 0; paths[i]; i++) {
102 const char *match = paths[i];
103 int matchlen = strlen(match);
104 const char *cp, *meta;
106 if (is_subdir(name, namelen, match, matchlen, max_depth))
108 if (!fnmatch(match, name, 0))
110 if (name[namelen-1] != '/')
113 /* We are being asked if the directory ("name") is worth
116 * Find the longest leading directory name that does
117 * not have metacharacter in the pathspec; the name
118 * we are looking at must overlap with that directory.
120 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
122 if (ch == '*' || ch == '[' || ch == '?') {
128 meta = cp; /* fully literal */
130 if (namelen <= meta - match) {
131 /* Looking at "Documentation/" and
132 * the pattern says "Documentation/howto/", or
133 * "Documentation/diff*.txt". The name we
134 * have should match prefix.
136 if (!memcmp(match, name, namelen))
141 if (meta - match < namelen) {
142 /* Looking at "Documentation/howto/" and
143 * the pattern says "Documentation/h*";
144 * match up to "Do.../h"; this avoids descending
145 * into "Documentation/technical/".
147 if (!memcmp(match, name, meta - match))
155 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
159 enum object_type type;
160 char *to_free = NULL;
163 data = read_sha1_file(sha1, &type, &size);
165 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
168 if (opt->relative && opt->prefix_length) {
169 static char name_buf[PATH_MAX];
171 int name_len = strlen(name) - opt->prefix_length + 1;
174 name += opt->prefix_length;
176 if (ARRAY_SIZE(name_buf) <= name_len)
177 cp = to_free = xmalloc(name_len);
180 memcpy(cp, name, tree_name_len);
181 strcpy(cp + tree_name_len,
182 name + tree_name_len + opt->prefix_length);
186 hit = grep_buffer(opt, name, data, size);
192 static int grep_file(struct grep_opt *opt, const char *filename)
199 if (lstat(filename, &st) < 0) {
202 error("'%s': %s", filename, strerror(errno));
206 return 0; /* empty file -- no grep hit */
207 if (!S_ISREG(st.st_mode))
209 sz = xsize_t(st.st_size);
210 i = open(filename, O_RDONLY);
213 data = xmalloc(sz + 1);
214 if (st.st_size != read_in_full(i, data, sz)) {
215 error("'%s': short read %s", filename, strerror(errno));
221 if (opt->relative && opt->prefix_length)
222 filename += opt->prefix_length;
223 i = grep_buffer(opt, filename, data, sz);
228 #if !NO_EXTERNAL_GREP
229 static int exec_grep(int argc, const char **argv)
239 execvp("grep", (char **) argv);
242 while (waitpid(pid, &status, 0) < 0) {
247 if (WIFEXITED(status)) {
248 if (!WEXITSTATUS(status))
257 #define push_arg(a) do { \
258 if (nr < MAXARGS) argv[nr++] = (a); \
259 else die("maximum number of args exceeded"); \
263 * If you send a singleton filename to grep, it does not give
264 * the name of the file. GNU grep has "-H" but we would want
265 * that behaviour in a portable way.
267 * So we keep two pathnames in argv buffer unsent to grep in
268 * the main loop if we need to do more than one grep.
270 static int flush_grep(struct grep_opt *opt,
271 int argc, int arg0, const char **argv, int *kept)
274 int count = argc - arg0;
275 const char *kept_0 = NULL;
279 * Because we keep at least 2 paths in the call from
280 * the main loop (i.e. kept != NULL), and MAXARGS is
281 * far greater than 2, this usually is a call to
282 * conclude the grep. However, the user could attempt
283 * to overflow the argv buffer by giving too many
284 * options to leave very small number of real
285 * arguments even for the call in the main loop.
288 die("insanely many options to grep");
291 * If we have two or more paths, we do not have to do
292 * anything special, but we need to push /dev/null to
293 * get "-H" behaviour of GNU grep portably but when we
294 * are not doing "-l" nor "-L" nor "-c".
298 !opt->unmatch_name_only &&
300 argv[argc++] = "/dev/null";
307 * Called because we found many paths and haven't finished
308 * iterating over the cache yet. We keep two paths
309 * for the concluding call. argv[argc-2] and argv[argc-1]
310 * has the last two paths, so save the first one away,
311 * replace it with NULL while sending the list to grep,
312 * and recover them after we are done.
315 kept_0 = argv[argc-2];
320 if (opt->pre_context || opt->post_context) {
322 * grep handles hunk marks between files, but we need to
323 * do that ourselves between multiple calls.
325 if (opt->show_hunk_mark)
326 write_or_die(1, "--\n", 3);
328 opt->show_hunk_mark = 1;
331 status = exec_grep(argc, argv);
335 * Then recover them. Now the last arg is beyond the
336 * terminating NULL which is at argc, and the second
337 * from the last is what we saved away in kept_0
339 argv[arg0++] = kept_0;
340 argv[arg0] = argv[argc+1];
345 static void grep_add_color(struct strbuf *sb, const char *escape_seq)
347 size_t orig_len = sb->len;
349 while (*escape_seq) {
350 if (*escape_seq == 'm')
351 strbuf_addch(sb, ';');
352 else if (*escape_seq != '\033' && *escape_seq != '[')
353 strbuf_addch(sb, *escape_seq);
356 if (sb->len > orig_len && sb->buf[sb->len - 1] == ';')
357 strbuf_setlen(sb, sb->len - 1);
360 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
362 int i, nr, argc, hit, len, status;
363 const char *argv[MAXARGS+1];
364 char randarg[ARGBUF];
365 char *argptr = randarg;
368 if (opt->extended || (opt->relative && opt->prefix_length))
378 if (opt->regflags & REG_EXTENDED)
380 if (opt->regflags & REG_ICASE)
382 if (opt->binary == GREP_BINARY_NOMATCH)
384 if (opt->word_regexp)
388 if (opt->unmatch_name_only)
390 if (opt->null_following_name)
391 /* in GNU grep git's "-z" translates to "-Z" */
395 if (opt->post_context || opt->pre_context) {
396 if (opt->post_context != opt->pre_context) {
397 if (opt->pre_context) {
399 len += snprintf(argptr, sizeof(randarg)-len,
400 "%u", opt->pre_context) + 1;
401 if (sizeof(randarg) <= len)
402 die("maximum length of args exceeded");
406 if (opt->post_context) {
408 len += snprintf(argptr, sizeof(randarg)-len,
409 "%u", opt->post_context) + 1;
410 if (sizeof(randarg) <= len)
411 die("maximum length of args exceeded");
418 len += snprintf(argptr, sizeof(randarg)-len,
419 "%u", opt->post_context) + 1;
420 if (sizeof(randarg) <= len)
421 die("maximum length of args exceeded");
426 for (p = opt->pattern_list; p; p = p->next) {
428 push_arg(p->pattern);
431 struct strbuf sb = STRBUF_INIT;
433 grep_add_color(&sb, opt->color_match);
434 setenv("GREP_COLOR", sb.buf, 1);
437 strbuf_addstr(&sb, "mt=");
438 grep_add_color(&sb, opt->color_match);
439 strbuf_addstr(&sb, ":sl=:cx=:fn=:ln=:bn=:se=");
440 setenv("GREP_COLORS", sb.buf, 1);
444 if (opt->color_external && strlen(opt->color_external) > 0)
445 push_arg(opt->color_external);
450 for (i = 0; i < active_nr; i++) {
451 struct cache_entry *ce = active_cache[i];
454 if (!S_ISREG(ce->ce_mode))
456 if (!pathspec_matches(paths, ce->name, opt->max_depth))
459 if (name[0] == '-') {
460 int len = ce_namelen(ce);
461 name = xmalloc(len + 3);
462 memcpy(name, "./", 2);
463 memcpy(name + 2, ce->name, len + 1);
466 if (MAXARGS <= argc) {
467 status = flush_grep(opt, argc, nr, argv, &kept);
475 } while (i < active_nr &&
476 !strcmp(ce->name, active_cache[i]->name));
477 i--; /* compensate for loop control */
481 status = flush_grep(opt, argc, nr, argv, NULL);
489 static int grep_cache(struct grep_opt *opt, const char **paths, int cached,
490 int external_grep_allowed)
496 #if !NO_EXTERNAL_GREP
498 * Use the external "grep" command for the case where
499 * we grep through the checked-out files. It tends to
500 * be a lot more optimized
502 if (!cached && external_grep_allowed) {
503 hit = external_grep(opt, paths, cached);
509 for (nr = 0; nr < active_nr; nr++) {
510 struct cache_entry *ce = active_cache[nr];
511 if (!S_ISREG(ce->ce_mode))
513 if (!pathspec_matches(paths, ce->name, opt->max_depth))
516 * If CE_VALID is on, we assume worktree file and its cache entry
517 * are identical, even if worktree file has been modified, so use
518 * cache version instead
520 if (cached || (ce->ce_flags & CE_VALID)) {
523 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
526 hit |= grep_file(opt, ce->name);
530 } while (nr < active_nr &&
531 !strcmp(ce->name, active_cache[nr]->name));
532 nr--; /* compensate for loop control */
535 free_grep_patterns(opt);
539 static int grep_tree(struct grep_opt *opt, const char **paths,
540 struct tree_desc *tree,
541 const char *tree_name, const char *base)
545 struct name_entry entry;
547 int tn_len = strlen(tree_name);
548 struct strbuf pathbuf;
550 strbuf_init(&pathbuf, PATH_MAX + tn_len);
553 strbuf_add(&pathbuf, tree_name, tn_len);
554 strbuf_addch(&pathbuf, ':');
555 tn_len = pathbuf.len;
557 strbuf_addstr(&pathbuf, base);
560 while (tree_entry(tree, &entry)) {
561 int te_len = tree_entry_len(entry.path, entry.sha1);
563 strbuf_add(&pathbuf, entry.path, te_len);
565 if (S_ISDIR(entry.mode))
566 /* Match "abc/" against pathspec to
567 * decide if we want to descend into "abc"
570 strbuf_addch(&pathbuf, '/');
572 down = pathbuf.buf + tn_len;
573 if (!pathspec_matches(paths, down, opt->max_depth))
575 else if (S_ISREG(entry.mode))
576 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
577 else if (S_ISDIR(entry.mode)) {
578 enum object_type type;
579 struct tree_desc sub;
583 data = read_sha1_file(entry.sha1, &type, &size);
585 die("unable to read tree (%s)",
586 sha1_to_hex(entry.sha1));
587 init_tree_desc(&sub, data, size);
588 hit |= grep_tree(opt, paths, &sub, tree_name, down);
592 strbuf_release(&pathbuf);
596 static int grep_object(struct grep_opt *opt, const char **paths,
597 struct object *obj, const char *name)
599 if (obj->type == OBJ_BLOB)
600 return grep_sha1(opt, obj->sha1, name, 0);
601 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
602 struct tree_desc tree;
606 data = read_object_with_reference(obj->sha1, tree_type,
609 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
610 init_tree_desc(&tree, data, size);
611 hit = grep_tree(opt, paths, &tree, name, "");
615 die("unable to grep from object of type %s", typename(obj->type));
618 static int context_callback(const struct option *opt, const char *arg,
621 struct grep_opt *grep_opt = opt->value;
626 grep_opt->pre_context = grep_opt->post_context = 0;
629 value = strtol(arg, (char **)&endp, 10);
631 return error("switch `%c' expects a numerical value",
634 grep_opt->pre_context = grep_opt->post_context = value;
638 static int file_callback(const struct option *opt, const char *arg, int unset)
640 struct grep_opt *grep_opt = opt->value;
645 patterns = fopen(arg, "r");
647 die_errno("cannot open '%s'", arg);
648 while (strbuf_getline(&sb, patterns, '\n') == 0) {
649 /* ignore empty line like grep does */
652 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
653 ++lno, GREP_PATTERN);
660 static int not_callback(const struct option *opt, const char *arg, int unset)
662 struct grep_opt *grep_opt = opt->value;
663 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
667 static int and_callback(const struct option *opt, const char *arg, int unset)
669 struct grep_opt *grep_opt = opt->value;
670 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
674 static int open_callback(const struct option *opt, const char *arg, int unset)
676 struct grep_opt *grep_opt = opt->value;
677 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
681 static int close_callback(const struct option *opt, const char *arg, int unset)
683 struct grep_opt *grep_opt = opt->value;
684 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
688 static int pattern_callback(const struct option *opt, const char *arg,
691 struct grep_opt *grep_opt = opt->value;
692 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
696 static int help_callback(const struct option *opt, const char *arg, int unset)
701 int cmd_grep(int argc, const char **argv, const char *prefix)
705 int external_grep_allowed = 1;
706 int seen_dashdash = 0;
708 struct object_array list = { 0, 0, NULL };
709 const char **paths = NULL;
712 struct option options[] = {
713 OPT_BOOLEAN(0, "cached", &cached,
714 "search in index instead of in the work tree"),
716 OPT_BOOLEAN('v', "invert-match", &opt.invert,
717 "show non-matching lines"),
718 OPT_BIT('i', "ignore-case", &opt.regflags,
719 "case insensitive matching", REG_ICASE),
720 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
721 "match patterns only at word boundaries"),
722 OPT_SET_INT('a', "text", &opt.binary,
723 "process binary files as text", GREP_BINARY_TEXT),
724 OPT_SET_INT('I', NULL, &opt.binary,
725 "don't match patterns in binary files",
726 GREP_BINARY_NOMATCH),
727 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
728 "descend at most <depth> levels", PARSE_OPT_NONEG,
731 OPT_BIT('E', "extended-regexp", &opt.regflags,
732 "use extended POSIX regular expressions", REG_EXTENDED),
733 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
734 "use basic POSIX regular expressions (default)",
736 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
737 "interpret patterns as fixed strings"),
739 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
740 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
741 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
742 OPT_NEGBIT(0, "full-name", &opt.relative,
743 "show filenames relative to top directory", 1),
744 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
745 "show only filenames instead of matching lines"),
746 OPT_BOOLEAN(0, "name-only", &opt.name_only,
747 "synonym for --files-with-matches"),
748 OPT_BOOLEAN('L', "files-without-match",
749 &opt.unmatch_name_only,
750 "show only the names of files without match"),
751 OPT_BOOLEAN('z', "null", &opt.null_following_name,
752 "print NUL after filenames"),
753 OPT_BOOLEAN('c', "count", &opt.count,
754 "show the number of matches instead of matching lines"),
755 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
757 OPT_CALLBACK('C', NULL, &opt, "n",
758 "show <n> context lines before and after matches",
760 OPT_INTEGER('B', NULL, &opt.pre_context,
761 "show <n> context lines before matches"),
762 OPT_INTEGER('A', NULL, &opt.post_context,
763 "show <n> context lines after matches"),
764 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
766 OPT_BOOLEAN('p', "show-function", &opt.funcname,
767 "show a line with the function name before matches"),
769 OPT_CALLBACK('f', NULL, &opt, "file",
770 "read patterns from file", file_callback),
771 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
772 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
773 { OPTION_CALLBACK, 0, "and", &opt, NULL,
774 "combine patterns specified with -e",
775 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
776 OPT_BOOLEAN(0, "or", &dummy, ""),
777 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
778 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
779 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
780 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
782 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
783 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
785 OPT_BOOLEAN(0, "all-match", &opt.all_match,
786 "show only matches from files that match all patterns"),
789 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
790 "allow calling of grep(1) (ignored by this build)"),
792 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
793 "allow calling of grep(1) (default)"),
795 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
796 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
800 memset(&opt, 0, sizeof(opt));
801 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
804 opt.pattern_tail = &opt.pattern_list;
805 opt.regflags = REG_NEWLINE;
808 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
810 git_config(grep_config, &opt);
812 opt.color = git_use_color_default;
815 * If there is no -- then the paths must exist in the working
816 * tree. If there is no explicit pattern specified with -e or
817 * -f, we take the first unrecognized non option to be the
818 * pattern, but then what follows it must be zero or more
819 * valid refs up to the -- (if exists), and then existing
820 * paths. If there is an explicit pattern, then the first
821 * unrecognized non option is the beginning of the refs list
822 * that continues up to the -- (if exists), and then paths.
824 argc = parse_options(argc, argv, prefix, options, grep_usage,
825 PARSE_OPT_KEEP_DASHDASH |
826 PARSE_OPT_STOP_AT_NON_OPTION |
827 PARSE_OPT_NO_INTERNAL_HELP);
829 /* First unrecognized non-option token */
830 if (argc > 0 && !opt.pattern_list) {
831 append_grep_pattern(&opt, argv[0], "command line", 0,
837 if ((opt.color && !opt.color_external) || opt.funcname)
838 external_grep_allowed = 0;
839 if (!opt.pattern_list)
840 die("no pattern given.");
841 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
842 die("cannot mix --fixed-strings and regexp");
843 compile_grep_patterns(&opt);
845 /* Check revs and then paths */
846 for (i = 0; i < argc; i++) {
847 const char *arg = argv[i];
848 unsigned char sha1[20];
850 if (!get_sha1(arg, sha1)) {
851 struct object *object = parse_object(sha1);
853 die("bad object %s", arg);
854 add_object_array(object, arg, &list);
857 if (!strcmp(arg, "--")) {
864 /* The rest are paths */
865 if (!seen_dashdash) {
867 for (j = i; j < argc; j++)
868 verify_filename(prefix, argv[j]);
872 paths = get_pathspec(prefix, argv + i);
873 if (opt.prefix_length && opt.relative) {
874 /* Make sure we do not get outside of paths */
875 for (i = 0; paths[i]; i++)
876 if (strncmp(prefix, paths[i], opt.prefix_length))
877 die("git grep: cannot generate relative filenames containing '..'");
881 paths = xcalloc(2, sizeof(const char *));
889 return !grep_cache(&opt, paths, cached, external_grep_allowed);
893 die("both --cached and trees are given.");
895 for (i = 0; i < list.nr; i++) {
896 struct object *real_obj;
897 real_obj = deref_tag(list.objects[i].item, NULL, 0);
898 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
901 free_grep_patterns(&opt);