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
23 static int builtin_grep;
26 * git grep pathspecs are somewhat different from diff-tree pathspecs;
27 * pathname wildcards are allowed.
29 static int pathspec_matches(const char **paths, const char *name)
32 if (!paths || !*paths)
34 namelen = strlen(name);
35 for (i = 0; paths[i]; i++) {
36 const char *match = paths[i];
37 int matchlen = strlen(match);
38 const char *cp, *meta;
41 ((matchlen <= namelen) &&
42 !strncmp(name, match, matchlen) &&
43 (match[matchlen-1] == '/' ||
44 name[matchlen] == '\0' || name[matchlen] == '/')))
46 if (!fnmatch(match, name, 0))
48 if (name[namelen-1] != '/')
51 /* We are being asked if the directory ("name") is worth
54 * Find the longest leading directory name that does
55 * not have metacharacter in the pathspec; the name
56 * we are looking at must overlap with that directory.
58 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
60 if (ch == '*' || ch == '[' || ch == '?') {
66 meta = cp; /* fully literal */
68 if (namelen <= meta - match) {
69 /* Looking at "Documentation/" and
70 * the pattern says "Documentation/howto/", or
71 * "Documentation/diff*.txt". The name we
72 * have should match prefix.
74 if (!memcmp(match, name, namelen))
79 if (meta - match < namelen) {
80 /* Looking at "Documentation/howto/" and
81 * the pattern says "Documentation/h*";
82 * match up to "Do.../h"; this avoids descending
83 * into "Documentation/technical/".
85 if (!memcmp(match, name, meta - match))
93 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
97 enum object_type type;
101 data = read_sha1_file(sha1, &type, &size);
103 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
106 if (opt->relative && opt->prefix_length) {
107 static char name_buf[PATH_MAX];
109 int name_len = strlen(name) - opt->prefix_length + 1;
112 name += opt->prefix_length;
114 if (ARRAY_SIZE(name_buf) <= name_len)
115 cp = to_free = xmalloc(name_len);
118 memcpy(cp, name, tree_name_len);
119 strcpy(cp + tree_name_len,
120 name + tree_name_len + opt->prefix_length);
124 hit = grep_buffer(opt, name, data, size);
130 static int grep_file(struct grep_opt *opt, const char *filename)
137 if (lstat(filename, &st) < 0) {
140 error("'%s': %s", filename, strerror(errno));
144 return 0; /* empty file -- no grep hit */
145 if (!S_ISREG(st.st_mode))
147 sz = xsize_t(st.st_size);
148 i = open(filename, O_RDONLY);
151 data = xmalloc(sz + 1);
152 if (st.st_size != read_in_full(i, data, sz)) {
153 error("'%s': short read %s", filename, strerror(errno));
159 if (opt->relative && opt->prefix_length)
160 filename += opt->prefix_length;
161 i = grep_buffer(opt, filename, data, sz);
166 #if !NO_EXTERNAL_GREP
167 static int exec_grep(int argc, const char **argv)
177 execvp("grep", (char **) argv);
180 while (waitpid(pid, &status, 0) < 0) {
185 if (WIFEXITED(status)) {
186 if (!WEXITSTATUS(status))
195 #define push_arg(a) do { \
196 if (nr < MAXARGS) argv[nr++] = (a); \
197 else die("maximum number of args exceeded"); \
201 * If you send a singleton filename to grep, it does not give
202 * the name of the file. GNU grep has "-H" but we would want
203 * that behaviour in a portable way.
205 * So we keep two pathnames in argv buffer unsent to grep in
206 * the main loop if we need to do more than one grep.
208 static int flush_grep(struct grep_opt *opt,
209 int argc, int arg0, const char **argv, int *kept)
212 int count = argc - arg0;
213 const char *kept_0 = NULL;
217 * Because we keep at least 2 paths in the call from
218 * the main loop (i.e. kept != NULL), and MAXARGS is
219 * far greater than 2, this usually is a call to
220 * conclude the grep. However, the user could attempt
221 * to overflow the argv buffer by giving too many
222 * options to leave very small number of real
223 * arguments even for the call in the main loop.
226 die("insanely many options to grep");
229 * If we have two or more paths, we do not have to do
230 * anything special, but we need to push /dev/null to
231 * get "-H" behaviour of GNU grep portably but when we
232 * are not doing "-l" nor "-L" nor "-c".
236 !opt->unmatch_name_only &&
238 argv[argc++] = "/dev/null";
245 * Called because we found many paths and haven't finished
246 * iterating over the cache yet. We keep two paths
247 * for the concluding call. argv[argc-2] and argv[argc-1]
248 * has the last two paths, so save the first one away,
249 * replace it with NULL while sending the list to grep,
250 * and recover them after we are done.
253 kept_0 = argv[argc-2];
258 status = exec_grep(argc, argv);
262 * Then recover them. Now the last arg is beyond the
263 * terminating NULL which is at argc, and the second
264 * from the last is what we saved away in kept_0
266 argv[arg0++] = kept_0;
267 argv[arg0] = argv[argc+1];
272 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
274 int i, nr, argc, hit, len, status;
275 const char *argv[MAXARGS+1];
276 char randarg[ARGBUF];
277 char *argptr = randarg;
280 if (opt->extended || (opt->relative && opt->prefix_length))
290 if (opt->regflags & REG_EXTENDED)
292 if (opt->regflags & REG_ICASE)
294 if (opt->binary == GREP_BINARY_NOMATCH)
296 if (opt->word_regexp)
300 if (opt->unmatch_name_only)
302 if (opt->null_following_name)
303 /* in GNU grep git's "-z" translates to "-Z" */
307 if (opt->post_context || opt->pre_context) {
308 if (opt->post_context != opt->pre_context) {
309 if (opt->pre_context) {
311 len += snprintf(argptr, sizeof(randarg)-len,
312 "%u", opt->pre_context) + 1;
313 if (sizeof(randarg) <= len)
314 die("maximum length of args exceeded");
318 if (opt->post_context) {
320 len += snprintf(argptr, sizeof(randarg)-len,
321 "%u", opt->post_context) + 1;
322 if (sizeof(randarg) <= len)
323 die("maximum length of args exceeded");
330 len += snprintf(argptr, sizeof(randarg)-len,
331 "%u", opt->post_context) + 1;
332 if (sizeof(randarg) <= len)
333 die("maximum length of args exceeded");
338 for (p = opt->pattern_list; p; p = p->next) {
340 push_arg(p->pattern);
345 for (i = 0; i < active_nr; i++) {
346 struct cache_entry *ce = active_cache[i];
349 if (!S_ISREG(ce->ce_mode))
351 if (!pathspec_matches(paths, ce->name))
354 if (name[0] == '-') {
355 int len = ce_namelen(ce);
356 name = xmalloc(len + 3);
357 memcpy(name, "./", 2);
358 memcpy(name + 2, ce->name, len + 1);
361 if (MAXARGS <= argc) {
362 status = flush_grep(opt, argc, nr, argv, &kept);
370 } while (i < active_nr &&
371 !strcmp(ce->name, active_cache[i]->name));
372 i--; /* compensate for loop control */
376 status = flush_grep(opt, argc, nr, argv, NULL);
384 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
390 #if !NO_EXTERNAL_GREP
392 * Use the external "grep" command for the case where
393 * we grep through the checked-out files. It tends to
394 * be a lot more optimized
396 if (!cached && !builtin_grep) {
397 hit = external_grep(opt, paths, cached);
403 for (nr = 0; nr < active_nr; nr++) {
404 struct cache_entry *ce = active_cache[nr];
405 if (!S_ISREG(ce->ce_mode))
407 if (!pathspec_matches(paths, ce->name))
410 * If CE_VALID is on, we assume worktree file and its cache entry
411 * are identical, even if worktree file has been modified, so use
412 * cache version instead
414 if (cached || (ce->ce_flags & CE_VALID)) {
417 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
420 hit |= grep_file(opt, ce->name);
424 } while (nr < active_nr &&
425 !strcmp(ce->name, active_cache[nr]->name));
426 nr--; /* compensate for loop control */
429 free_grep_patterns(opt);
433 static int grep_tree(struct grep_opt *opt, const char **paths,
434 struct tree_desc *tree,
435 const char *tree_name, const char *base)
439 struct name_entry entry;
441 int tn_len = strlen(tree_name);
442 struct strbuf pathbuf;
444 strbuf_init(&pathbuf, PATH_MAX + tn_len);
447 strbuf_add(&pathbuf, tree_name, tn_len);
448 strbuf_addch(&pathbuf, ':');
449 tn_len = pathbuf.len;
451 strbuf_addstr(&pathbuf, base);
454 while (tree_entry(tree, &entry)) {
455 int te_len = tree_entry_len(entry.path, entry.sha1);
457 strbuf_add(&pathbuf, entry.path, te_len);
459 if (S_ISDIR(entry.mode))
460 /* Match "abc/" against pathspec to
461 * decide if we want to descend into "abc"
464 strbuf_addch(&pathbuf, '/');
466 down = pathbuf.buf + tn_len;
467 if (!pathspec_matches(paths, down))
469 else if (S_ISREG(entry.mode))
470 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
471 else if (S_ISDIR(entry.mode)) {
472 enum object_type type;
473 struct tree_desc sub;
477 data = read_sha1_file(entry.sha1, &type, &size);
479 die("unable to read tree (%s)",
480 sha1_to_hex(entry.sha1));
481 init_tree_desc(&sub, data, size);
482 hit |= grep_tree(opt, paths, &sub, tree_name, down);
486 strbuf_release(&pathbuf);
490 static int grep_object(struct grep_opt *opt, const char **paths,
491 struct object *obj, const char *name)
493 if (obj->type == OBJ_BLOB)
494 return grep_sha1(opt, obj->sha1, name, 0);
495 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
496 struct tree_desc tree;
500 data = read_object_with_reference(obj->sha1, tree_type,
503 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
504 init_tree_desc(&tree, data, size);
505 hit = grep_tree(opt, paths, &tree, name, "");
509 die("unable to grep from object of type %s", typename(obj->type));
512 static const char builtin_grep_usage[] =
513 "git grep <option>* [-e] <pattern> <rev>* [[--] <path>...]";
515 static const char emsg_invalid_context_len[] =
516 "%s: invalid context length argument";
517 static const char emsg_missing_context_len[] =
518 "missing context length argument";
519 static const char emsg_missing_argument[] =
520 "option requires an argument -%s";
522 int cmd_grep(int argc, const char **argv, const char *prefix)
526 int seen_dashdash = 0;
528 struct object_array list = { 0, 0, NULL };
529 const char **paths = NULL;
532 memset(&opt, 0, sizeof(opt));
533 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
536 opt.pattern_tail = &opt.pattern_list;
537 opt.regflags = REG_NEWLINE;
540 * If there is no -- then the paths must exist in the working
541 * tree. If there is no explicit pattern specified with -e or
542 * -f, we take the first unrecognized non option to be the
543 * pattern, but then what follows it must be zero or more
544 * valid refs up to the -- (if exists), and then existing
545 * paths. If there is an explicit pattern, then the first
546 * unrecognized non option is the beginning of the refs list
547 * that continues up to the -- (if exists), and then paths.
551 const char *arg = argv[1];
553 if (!strcmp("--cached", arg)) {
557 if (!strcmp("--no-ext-grep", arg)) {
561 if (!strcmp("-a", arg) ||
562 !strcmp("--text", arg)) {
563 opt.binary = GREP_BINARY_TEXT;
566 if (!strcmp("-i", arg) ||
567 !strcmp("--ignore-case", arg)) {
568 opt.regflags |= REG_ICASE;
571 if (!strcmp("-I", arg)) {
572 opt.binary = GREP_BINARY_NOMATCH;
575 if (!strcmp("-v", arg) ||
576 !strcmp("--invert-match", arg)) {
580 if (!strcmp("-E", arg) ||
581 !strcmp("--extended-regexp", arg)) {
582 opt.regflags |= REG_EXTENDED;
585 if (!strcmp("-F", arg) ||
586 !strcmp("--fixed-strings", arg)) {
590 if (!strcmp("-G", arg) ||
591 !strcmp("--basic-regexp", arg)) {
592 opt.regflags &= ~REG_EXTENDED;
595 if (!strcmp("-n", arg)) {
599 if (!strcmp("-h", arg)) {
603 if (!strcmp("-H", arg)) {
607 if (!strcmp("-l", arg) ||
608 !strcmp("--name-only", arg) ||
609 !strcmp("--files-with-matches", arg)) {
613 if (!strcmp("-L", arg) ||
614 !strcmp("--files-without-match", arg)) {
615 opt.unmatch_name_only = 1;
618 if (!strcmp("-z", arg) ||
619 !strcmp("--null", arg)) {
620 opt.null_following_name = 1;
623 if (!strcmp("-c", arg) ||
624 !strcmp("--count", arg)) {
628 if (!strcmp("-w", arg) ||
629 !strcmp("--word-regexp", arg)) {
633 if (!prefixcmp(arg, "-A") ||
634 !prefixcmp(arg, "-B") ||
635 !prefixcmp(arg, "-C") ||
636 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
640 case 'A': case 'B': case 'C':
643 die(emsg_missing_context_len);
654 if (strtoul_ui(scan, 10, &num))
655 die(emsg_invalid_context_len, scan);
658 opt.post_context = num;
662 opt.post_context = num;
664 opt.pre_context = num;
669 if (!strcmp("-f", arg)) {
674 die(emsg_missing_argument, arg);
675 patterns = fopen(argv[1], "r");
677 die("'%s': %s", argv[1], strerror(errno));
678 while (fgets(buf, sizeof(buf), patterns)) {
679 int len = strlen(buf);
680 if (len && buf[len-1] == '\n')
682 /* ignore empty line like grep does */
685 append_grep_pattern(&opt, xstrdup(buf),
694 if (!strcmp("--not", arg)) {
695 append_grep_pattern(&opt, arg, "command line", 0,
699 if (!strcmp("--and", arg)) {
700 append_grep_pattern(&opt, arg, "command line", 0,
704 if (!strcmp("--or", arg))
705 continue; /* no-op */
706 if (!strcmp("(", arg)) {
707 append_grep_pattern(&opt, arg, "command line", 0,
711 if (!strcmp(")", arg)) {
712 append_grep_pattern(&opt, arg, "command line", 0,
716 if (!strcmp("--all-match", arg)) {
720 if (!strcmp("-e", arg)) {
722 append_grep_pattern(&opt, argv[1],
729 die(emsg_missing_argument, arg);
731 if (!strcmp("--full-name", arg)) {
735 if (!strcmp("--", arg)) {
736 /* later processing wants to have this at argv[1] */
742 usage(builtin_grep_usage);
744 /* First unrecognized non-option token */
745 if (!opt.pattern_list) {
746 append_grep_pattern(&opt, arg, "command line", 0,
751 /* We are looking at the first path or rev;
752 * it is found at argv[1] after leaving the
760 if (!opt.pattern_list)
761 die("no pattern given.");
762 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
763 die("cannot mix --fixed-strings and regexp");
764 compile_grep_patterns(&opt);
766 /* Check revs and then paths */
767 for (i = 1; i < argc; i++) {
768 const char *arg = argv[i];
769 unsigned char sha1[20];
771 if (!get_sha1(arg, sha1)) {
772 struct object *object = parse_object(sha1);
774 die("bad object %s", arg);
775 add_object_array(object, arg, &list);
778 if (!strcmp(arg, "--")) {
785 /* The rest are paths */
786 if (!seen_dashdash) {
788 for (j = i; j < argc; j++)
789 verify_filename(prefix, argv[j]);
793 paths = get_pathspec(prefix, argv + i);
794 if (opt.prefix_length && opt.relative) {
795 /* Make sure we do not get outside of paths */
796 for (i = 0; paths[i]; i++)
797 if (strncmp(prefix, paths[i], opt.prefix_length))
798 die("git grep: cannot generate relative filenames containing '..'");
802 paths = xcalloc(2, sizeof(const char *));
810 return !grep_cache(&opt, paths, cached);
814 die("both --cached and trees are given.");
816 for (i = 0; i < list.nr; i++) {
817 struct object *real_obj;
818 real_obj = deref_tag(list.objects[i].item, NULL, 0);
819 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
822 free_grep_patterns(&opt);