4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
13 #include "parse-options.h"
18 #ifndef NO_EXTERNAL_GREP
20 #define NO_EXTERNAL_GREP 0
22 #define NO_EXTERNAL_GREP 1
26 static char const * const grep_usage[] = {
27 "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
31 static int grep_config(const char *var, const char *value, void *cb)
33 struct grep_opt *opt = cb;
35 switch (userdiff_config(var, value)) {
41 if (!strcmp(var, "color.grep")) {
42 opt->color = git_config_colorbool(var, value, -1);
45 if (!strcmp(var, "color.grep.external"))
46 return git_config_string(&(opt->color_external), var, value);
47 if (!strcmp(var, "color.grep.match")) {
49 return config_error_nonbool(var);
50 color_parse(value, var, opt->color_match);
53 return git_color_default_config(var, value, cb);
57 * git grep pathspecs are somewhat different from diff-tree pathspecs;
58 * pathname wildcards are allowed.
60 static int pathspec_matches(const char **paths, const char *name)
63 if (!paths || !*paths)
65 namelen = strlen(name);
66 for (i = 0; paths[i]; i++) {
67 const char *match = paths[i];
68 int matchlen = strlen(match);
69 const char *cp, *meta;
72 ((matchlen <= namelen) &&
73 !strncmp(name, match, matchlen) &&
74 (match[matchlen-1] == '/' ||
75 name[matchlen] == '\0' || name[matchlen] == '/')))
77 if (!fnmatch(match, name, 0))
79 if (name[namelen-1] != '/')
82 /* We are being asked if the directory ("name") is worth
85 * Find the longest leading directory name that does
86 * not have metacharacter in the pathspec; the name
87 * we are looking at must overlap with that directory.
89 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
91 if (ch == '*' || ch == '[' || ch == '?') {
97 meta = cp; /* fully literal */
99 if (namelen <= meta - match) {
100 /* Looking at "Documentation/" and
101 * the pattern says "Documentation/howto/", or
102 * "Documentation/diff*.txt". The name we
103 * have should match prefix.
105 if (!memcmp(match, name, namelen))
110 if (meta - match < namelen) {
111 /* Looking at "Documentation/howto/" and
112 * the pattern says "Documentation/h*";
113 * match up to "Do.../h"; this avoids descending
114 * into "Documentation/technical/".
116 if (!memcmp(match, name, meta - match))
124 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
128 enum object_type type;
130 struct strbuf pathbuf = STRBUF_INIT;
132 data = read_sha1_file(sha1, &type, &size);
134 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
137 if (opt->relative && opt->prefix_length) {
138 quote_path_relative(name + tree_name_len, -1, &pathbuf, opt->prefix);
139 strbuf_insert(&pathbuf, 0, name, tree_name_len);
142 hit = grep_buffer(opt, name, data, size);
143 strbuf_release(&pathbuf);
148 static int grep_file(struct grep_opt *opt, const char *filename)
154 struct strbuf buf = STRBUF_INIT;
156 if (lstat(filename, &st) < 0) {
159 error("'%s': %s", filename, strerror(errno));
163 return 0; /* empty file -- no grep hit */
164 if (!S_ISREG(st.st_mode))
166 sz = xsize_t(st.st_size);
167 i = open(filename, O_RDONLY);
170 data = xmalloc(sz + 1);
171 if (st.st_size != read_in_full(i, data, sz)) {
172 error("'%s': short read %s", filename, strerror(errno));
178 if (opt->relative && opt->prefix_length)
179 filename = quote_path_relative(filename, -1, &buf, opt->prefix);
180 i = grep_buffer(opt, filename, data, sz);
181 strbuf_release(&buf);
186 #if !NO_EXTERNAL_GREP
187 static int exec_grep(int argc, const char **argv)
197 execvp("grep", (char **) argv);
200 while (waitpid(pid, &status, 0) < 0) {
205 if (WIFEXITED(status)) {
206 if (!WEXITSTATUS(status))
215 #define push_arg(a) do { \
216 if (nr < MAXARGS) argv[nr++] = (a); \
217 else die("maximum number of args exceeded"); \
221 * If you send a singleton filename to grep, it does not give
222 * the name of the file. GNU grep has "-H" but we would want
223 * that behaviour in a portable way.
225 * So we keep two pathnames in argv buffer unsent to grep in
226 * the main loop if we need to do more than one grep.
228 static int flush_grep(struct grep_opt *opt,
229 int argc, int arg0, const char **argv, int *kept)
232 int count = argc - arg0;
233 const char *kept_0 = NULL;
237 * Because we keep at least 2 paths in the call from
238 * the main loop (i.e. kept != NULL), and MAXARGS is
239 * far greater than 2, this usually is a call to
240 * conclude the grep. However, the user could attempt
241 * to overflow the argv buffer by giving too many
242 * options to leave very small number of real
243 * arguments even for the call in the main loop.
246 die("insanely many options to grep");
249 * If we have two or more paths, we do not have to do
250 * anything special, but we need to push /dev/null to
251 * get "-H" behaviour of GNU grep portably but when we
252 * are not doing "-l" nor "-L" nor "-c".
256 !opt->unmatch_name_only &&
258 argv[argc++] = "/dev/null";
265 * Called because we found many paths and haven't finished
266 * iterating over the cache yet. We keep two paths
267 * for the concluding call. argv[argc-2] and argv[argc-1]
268 * has the last two paths, so save the first one away,
269 * replace it with NULL while sending the list to grep,
270 * and recover them after we are done.
273 kept_0 = argv[argc-2];
278 if (opt->pre_context || opt->post_context) {
280 * grep handles hunk marks between files, but we need to
281 * do that ourselves between multiple calls.
283 if (opt->show_hunk_mark)
284 write_or_die(1, "--\n", 3);
286 opt->show_hunk_mark = 1;
289 status = exec_grep(argc, argv);
293 * Then recover them. Now the last arg is beyond the
294 * terminating NULL which is at argc, and the second
295 * from the last is what we saved away in kept_0
297 argv[arg0++] = kept_0;
298 argv[arg0] = argv[argc+1];
303 static void grep_add_color(struct strbuf *sb, const char *escape_seq)
305 size_t orig_len = sb->len;
307 while (*escape_seq) {
308 if (*escape_seq == 'm')
309 strbuf_addch(sb, ';');
310 else if (*escape_seq != '\033' && *escape_seq != '[')
311 strbuf_addch(sb, *escape_seq);
314 if (sb->len > orig_len && sb->buf[sb->len - 1] == ';')
315 strbuf_setlen(sb, sb->len - 1);
318 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
320 int i, nr, argc, hit, len, status;
321 const char *argv[MAXARGS+1];
322 char randarg[ARGBUF];
323 char *argptr = randarg;
326 if (opt->extended || (opt->relative && opt->prefix_length))
336 if (opt->regflags & REG_EXTENDED)
338 if (opt->regflags & REG_ICASE)
340 if (opt->binary == GREP_BINARY_NOMATCH)
342 if (opt->word_regexp)
346 if (opt->unmatch_name_only)
348 if (opt->null_following_name)
349 /* in GNU grep git's "-z" translates to "-Z" */
353 if (opt->post_context || opt->pre_context) {
354 if (opt->post_context != opt->pre_context) {
355 if (opt->pre_context) {
357 len += snprintf(argptr, sizeof(randarg)-len,
358 "%u", opt->pre_context) + 1;
359 if (sizeof(randarg) <= len)
360 die("maximum length of args exceeded");
364 if (opt->post_context) {
366 len += snprintf(argptr, sizeof(randarg)-len,
367 "%u", opt->post_context) + 1;
368 if (sizeof(randarg) <= len)
369 die("maximum length of args exceeded");
376 len += snprintf(argptr, sizeof(randarg)-len,
377 "%u", opt->post_context) + 1;
378 if (sizeof(randarg) <= len)
379 die("maximum length of args exceeded");
384 for (p = opt->pattern_list; p; p = p->next) {
386 push_arg(p->pattern);
389 struct strbuf sb = STRBUF_INIT;
391 grep_add_color(&sb, opt->color_match);
392 setenv("GREP_COLOR", sb.buf, 1);
395 strbuf_addstr(&sb, "mt=");
396 grep_add_color(&sb, opt->color_match);
397 strbuf_addstr(&sb, ":sl=:cx=:fn=:ln=:bn=:se=");
398 setenv("GREP_COLORS", sb.buf, 1);
402 if (opt->color_external && strlen(opt->color_external) > 0)
403 push_arg(opt->color_external);
408 for (i = 0; i < active_nr; i++) {
409 struct cache_entry *ce = active_cache[i];
412 if (!S_ISREG(ce->ce_mode))
414 if (!pathspec_matches(paths, ce->name))
417 if (name[0] == '-') {
418 int len = ce_namelen(ce);
419 name = xmalloc(len + 3);
420 memcpy(name, "./", 2);
421 memcpy(name + 2, ce->name, len + 1);
424 if (MAXARGS <= argc) {
425 status = flush_grep(opt, argc, nr, argv, &kept);
433 } while (i < active_nr &&
434 !strcmp(ce->name, active_cache[i]->name));
435 i--; /* compensate for loop control */
439 status = flush_grep(opt, argc, nr, argv, NULL);
447 static int grep_cache(struct grep_opt *opt, const char **paths, int cached,
448 int external_grep_allowed)
454 #if !NO_EXTERNAL_GREP
456 * Use the external "grep" command for the case where
457 * we grep through the checked-out files. It tends to
458 * be a lot more optimized
460 if (!cached && external_grep_allowed) {
461 hit = external_grep(opt, paths, cached);
468 for (nr = 0; nr < active_nr; nr++) {
469 struct cache_entry *ce = active_cache[nr];
470 if (!S_ISREG(ce->ce_mode))
472 if (!pathspec_matches(paths, ce->name))
475 * If CE_VALID is on, we assume worktree file and its cache entry
476 * are identical, even if worktree file has been modified, so use
477 * cache version instead
479 if (cached || (ce->ce_flags & CE_VALID)) {
482 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
485 hit |= grep_file(opt, ce->name);
489 } while (nr < active_nr &&
490 !strcmp(ce->name, active_cache[nr]->name));
491 nr--; /* compensate for loop control */
494 free_grep_patterns(opt);
498 static int grep_tree(struct grep_opt *opt, const char **paths,
499 struct tree_desc *tree,
500 const char *tree_name, const char *base)
504 struct name_entry entry;
506 int tn_len = strlen(tree_name);
507 struct strbuf pathbuf;
509 strbuf_init(&pathbuf, PATH_MAX + tn_len);
512 strbuf_add(&pathbuf, tree_name, tn_len);
513 strbuf_addch(&pathbuf, ':');
514 tn_len = pathbuf.len;
516 strbuf_addstr(&pathbuf, base);
519 while (tree_entry(tree, &entry)) {
520 int te_len = tree_entry_len(entry.path, entry.sha1);
522 strbuf_add(&pathbuf, entry.path, te_len);
524 if (S_ISDIR(entry.mode))
525 /* Match "abc/" against pathspec to
526 * decide if we want to descend into "abc"
529 strbuf_addch(&pathbuf, '/');
531 down = pathbuf.buf + tn_len;
532 if (!pathspec_matches(paths, down))
534 else if (S_ISREG(entry.mode))
535 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
536 else if (S_ISDIR(entry.mode)) {
537 enum object_type type;
538 struct tree_desc sub;
542 data = read_sha1_file(entry.sha1, &type, &size);
544 die("unable to read tree (%s)",
545 sha1_to_hex(entry.sha1));
546 init_tree_desc(&sub, data, size);
547 hit |= grep_tree(opt, paths, &sub, tree_name, down);
551 strbuf_release(&pathbuf);
555 static int grep_object(struct grep_opt *opt, const char **paths,
556 struct object *obj, const char *name)
558 if (obj->type == OBJ_BLOB)
559 return grep_sha1(opt, obj->sha1, name, 0);
560 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
561 struct tree_desc tree;
565 data = read_object_with_reference(obj->sha1, tree_type,
568 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
569 init_tree_desc(&tree, data, size);
570 hit = grep_tree(opt, paths, &tree, name, "");
574 die("unable to grep from object of type %s", typename(obj->type));
577 static int context_callback(const struct option *opt, const char *arg,
580 struct grep_opt *grep_opt = opt->value;
585 grep_opt->pre_context = grep_opt->post_context = 0;
588 value = strtol(arg, (char **)&endp, 10);
590 return error("switch `%c' expects a numerical value",
593 grep_opt->pre_context = grep_opt->post_context = value;
597 static int file_callback(const struct option *opt, const char *arg, int unset)
599 struct grep_opt *grep_opt = opt->value;
602 struct strbuf sb = STRBUF_INIT;
604 patterns = fopen(arg, "r");
606 die_errno("cannot open '%s'", arg);
607 while (strbuf_getline(&sb, patterns, '\n') == 0) {
608 /* ignore empty line like grep does */
611 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
612 ++lno, GREP_PATTERN);
619 static int not_callback(const struct option *opt, const char *arg, int unset)
621 struct grep_opt *grep_opt = opt->value;
622 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
626 static int and_callback(const struct option *opt, const char *arg, int unset)
628 struct grep_opt *grep_opt = opt->value;
629 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
633 static int open_callback(const struct option *opt, const char *arg, int unset)
635 struct grep_opt *grep_opt = opt->value;
636 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
640 static int close_callback(const struct option *opt, const char *arg, int unset)
642 struct grep_opt *grep_opt = opt->value;
643 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
647 static int pattern_callback(const struct option *opt, const char *arg,
650 struct grep_opt *grep_opt = opt->value;
651 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
655 static int help_callback(const struct option *opt, const char *arg, int unset)
660 int cmd_grep(int argc, const char **argv, const char *prefix)
664 int external_grep_allowed = 1;
665 int seen_dashdash = 0;
667 struct object_array list = { 0, 0, NULL };
668 const char **paths = NULL;
671 struct option options[] = {
672 OPT_BOOLEAN(0, "cached", &cached,
673 "search in index instead of in the work tree"),
675 OPT_BOOLEAN('v', "invert-match", &opt.invert,
676 "show non-matching lines"),
677 OPT_BIT('i', "ignore-case", &opt.regflags,
678 "case insensitive matching", REG_ICASE),
679 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
680 "match patterns only at word boundaries"),
681 OPT_SET_INT('a', "text", &opt.binary,
682 "process binary files as text", GREP_BINARY_TEXT),
683 OPT_SET_INT('I', NULL, &opt.binary,
684 "don't match patterns in binary files",
685 GREP_BINARY_NOMATCH),
687 OPT_BIT('E', "extended-regexp", &opt.regflags,
688 "use extended POSIX regular expressions", REG_EXTENDED),
689 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
690 "use basic POSIX regular expressions (default)",
692 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
693 "interpret patterns as fixed strings"),
695 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
696 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
697 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
698 OPT_NEGBIT(0, "full-name", &opt.relative,
699 "show filenames relative to top directory", 1),
700 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
701 "show only filenames instead of matching lines"),
702 OPT_BOOLEAN(0, "name-only", &opt.name_only,
703 "synonym for --files-with-matches"),
704 OPT_BOOLEAN('L', "files-without-match",
705 &opt.unmatch_name_only,
706 "show only the names of files without match"),
707 OPT_BOOLEAN('z', "null", &opt.null_following_name,
708 "print NUL after filenames"),
709 OPT_BOOLEAN('c', "count", &opt.count,
710 "show the number of matches instead of matching lines"),
711 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
713 OPT_CALLBACK('C', NULL, &opt, "n",
714 "show <n> context lines before and after matches",
716 OPT_INTEGER('B', NULL, &opt.pre_context,
717 "show <n> context lines before matches"),
718 OPT_INTEGER('A', NULL, &opt.post_context,
719 "show <n> context lines after matches"),
720 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
722 OPT_BOOLEAN('p', "show-function", &opt.funcname,
723 "show a line with the function name before matches"),
725 OPT_CALLBACK('f', NULL, &opt, "file",
726 "read patterns from file", file_callback),
727 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
728 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
729 { OPTION_CALLBACK, 0, "and", &opt, NULL,
730 "combine patterns specified with -e",
731 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
732 OPT_BOOLEAN(0, "or", &dummy, ""),
733 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
734 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
735 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
736 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
738 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
739 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
741 OPT_BOOLEAN(0, "all-match", &opt.all_match,
742 "show only matches from files that match all patterns"),
745 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
746 "allow calling of grep(1) (ignored by this build)"),
748 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
749 "allow calling of grep(1) (default)"),
751 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
752 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
756 memset(&opt, 0, sizeof(opt));
758 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
761 opt.pattern_tail = &opt.pattern_list;
762 opt.regflags = REG_NEWLINE;
764 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
766 git_config(grep_config, &opt);
768 opt.color = git_use_color_default;
771 * If there is no -- then the paths must exist in the working
772 * tree. If there is no explicit pattern specified with -e or
773 * -f, we take the first unrecognized non option to be the
774 * pattern, but then what follows it must be zero or more
775 * valid refs up to the -- (if exists), and then existing
776 * paths. If there is an explicit pattern, then the first
777 * unrecognized non option is the beginning of the refs list
778 * that continues up to the -- (if exists), and then paths.
780 argc = parse_options(argc, argv, prefix, options, grep_usage,
781 PARSE_OPT_KEEP_DASHDASH |
782 PARSE_OPT_STOP_AT_NON_OPTION |
783 PARSE_OPT_NO_INTERNAL_HELP);
785 /* First unrecognized non-option token */
786 if (argc > 0 && !opt.pattern_list) {
787 append_grep_pattern(&opt, argv[0], "command line", 0,
793 if ((opt.color && !opt.color_external) || opt.funcname)
794 external_grep_allowed = 0;
795 if (!opt.pattern_list)
796 die("no pattern given.");
797 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
798 die("cannot mix --fixed-strings and regexp");
799 compile_grep_patterns(&opt);
801 /* Check revs and then paths */
802 for (i = 0; i < argc; i++) {
803 const char *arg = argv[i];
804 unsigned char sha1[20];
806 if (!get_sha1(arg, sha1)) {
807 struct object *object = parse_object(sha1);
809 die("bad object %s", arg);
810 add_object_array(object, arg, &list);
813 if (!strcmp(arg, "--")) {
820 /* The rest are paths */
821 if (!seen_dashdash) {
823 for (j = i; j < argc; j++)
824 verify_filename(prefix, argv[j]);
828 paths = get_pathspec(prefix, argv + i);
830 paths = xcalloc(2, sizeof(const char *));
838 return !grep_cache(&opt, paths, cached, external_grep_allowed);
842 die("both --cached and trees are given.");
844 for (i = 0; i < list.nr; i++) {
845 struct object *real_obj;
846 real_obj = deref_tag(list.objects[i].item, NULL, 0);
847 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
850 free_grep_patterns(&opt);