4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
16 * git grep pathspecs are somewhat different from diff-tree pathspecs;
17 * pathname wildcards are allowed.
19 static int pathspec_matches(const char **paths, const char *name)
22 if (!paths || !*paths)
24 namelen = strlen(name);
25 for (i = 0; paths[i]; i++) {
26 const char *match = paths[i];
27 int matchlen = strlen(match);
28 const char *cp, *meta;
31 ((matchlen <= namelen) &&
32 !strncmp(name, match, matchlen) &&
33 (match[matchlen-1] == '/' ||
34 name[matchlen] == '\0' || name[matchlen] == '/')))
36 if (!fnmatch(match, name, 0))
38 if (name[namelen-1] != '/')
41 /* We are being asked if the directory ("name") is worth
44 * Find the longest leading directory name that does
45 * not have metacharacter in the pathspec; the name
46 * we are looking at must overlap with that directory.
48 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
50 if (ch == '*' || ch == '[' || ch == '?') {
56 meta = cp; /* fully literal */
58 if (namelen <= meta - match) {
59 /* Looking at "Documentation/" and
60 * the pattern says "Documentation/howto/", or
61 * "Documentation/diff*.txt". The name we
62 * have should match prefix.
64 if (!memcmp(match, name, namelen))
69 if (meta - match < namelen) {
70 /* Looking at "Documentation/howto/" and
71 * the pattern says "Documentation/h*";
72 * match up to "Do.../h"; this avoids descending
73 * into "Documentation/technical/".
75 if (!memcmp(match, name, meta - match))
83 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
87 enum object_type type;
91 data = read_sha1_file(sha1, &type, &size);
93 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
96 if (opt->relative && opt->prefix_length) {
97 static char name_buf[PATH_MAX];
99 int name_len = strlen(name) - opt->prefix_length + 1;
102 name += opt->prefix_length;
104 if (ARRAY_SIZE(name_buf) <= name_len)
105 cp = to_free = xmalloc(name_len);
108 memcpy(cp, name, tree_name_len);
109 strcpy(cp + tree_name_len,
110 name + tree_name_len + opt->prefix_length);
114 hit = grep_buffer(opt, name, data, size);
120 static int grep_file(struct grep_opt *opt, const char *filename)
127 if (lstat(filename, &st) < 0) {
130 error("'%s': %s", filename, strerror(errno));
134 return 0; /* empty file -- no grep hit */
135 if (!S_ISREG(st.st_mode))
137 sz = xsize_t(st.st_size);
138 i = open(filename, O_RDONLY);
141 data = xmalloc(sz + 1);
142 if (st.st_size != read_in_full(i, data, sz)) {
143 error("'%s': short read %s", filename, strerror(errno));
149 if (opt->relative && opt->prefix_length)
150 filename += opt->prefix_length;
151 i = grep_buffer(opt, filename, data, sz);
157 static int exec_grep(int argc, const char **argv)
167 execvp("grep", (char **) argv);
170 while (waitpid(pid, &status, 0) < 0) {
175 if (WIFEXITED(status)) {
176 if (!WEXITSTATUS(status))
185 #define push_arg(a) do { \
186 if (nr < MAXARGS) argv[nr++] = (a); \
187 else die("maximum number of args exceeded"); \
191 * If you send a singleton filename to grep, it does not give
192 * the name of the file. GNU grep has "-H" but we would want
193 * that behaviour in a portable way.
195 * So we keep two pathnames in argv buffer unsent to grep in
196 * the main loop if we need to do more than one grep.
198 static int flush_grep(struct grep_opt *opt,
199 int argc, int arg0, const char **argv, int *kept)
202 int count = argc - arg0;
203 const char *kept_0 = NULL;
207 * Because we keep at least 2 paths in the call from
208 * the main loop (i.e. kept != NULL), and MAXARGS is
209 * far greater than 2, this usually is a call to
210 * conclude the grep. However, the user could attempt
211 * to overflow the argv buffer by giving too many
212 * options to leave very small number of real
213 * arguments even for the call in the main loop.
216 die("insanely many options to grep");
219 * If we have two or more paths, we do not have to do
220 * anything special, but we need to push /dev/null to
221 * get "-H" behaviour of GNU grep portably but when we
222 * are not doing "-l" nor "-L" nor "-c".
226 !opt->unmatch_name_only &&
228 argv[argc++] = "/dev/null";
235 * Called because we found many paths and haven't finished
236 * iterating over the cache yet. We keep two paths
237 * for the concluding call. argv[argc-2] and argv[argc-1]
238 * has the last two paths, so save the first one away,
239 * replace it with NULL while sending the list to grep,
240 * and recover them after we are done.
243 kept_0 = argv[argc-2];
248 status = exec_grep(argc, argv);
252 * Then recover them. Now the last arg is beyond the
253 * terminating NULL which is at argc, and the second
254 * from the last is what we saved away in kept_0
256 argv[arg0++] = kept_0;
257 argv[arg0] = argv[argc+1];
262 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
264 int i, nr, argc, hit, len, status;
265 const char *argv[MAXARGS+1];
266 char randarg[ARGBUF];
267 char *argptr = randarg;
270 if (opt->extended || (opt->relative && opt->prefix_length))
280 if (opt->regflags & REG_EXTENDED)
282 if (opt->regflags & REG_ICASE)
284 if (opt->word_regexp)
288 if (opt->unmatch_name_only)
292 if (opt->post_context || opt->pre_context) {
293 if (opt->post_context != opt->pre_context) {
294 if (opt->pre_context) {
296 len += snprintf(argptr, sizeof(randarg)-len,
297 "%u", opt->pre_context) + 1;
298 if (sizeof(randarg) <= len)
299 die("maximum length of args exceeded");
303 if (opt->post_context) {
305 len += snprintf(argptr, sizeof(randarg)-len,
306 "%u", opt->post_context) + 1;
307 if (sizeof(randarg) <= len)
308 die("maximum length of args exceeded");
315 len += snprintf(argptr, sizeof(randarg)-len,
316 "%u", opt->post_context) + 1;
317 if (sizeof(randarg) <= len)
318 die("maximum length of args exceeded");
323 for (p = opt->pattern_list; p; p = p->next) {
325 push_arg(p->pattern);
330 for (i = 0; i < active_nr; i++) {
331 struct cache_entry *ce = active_cache[i];
334 if (!S_ISREG(ce->ce_mode))
336 if (!pathspec_matches(paths, ce->name))
339 if (name[0] == '-') {
340 int len = ce_namelen(ce);
341 name = xmalloc(len + 3);
342 memcpy(name, "./", 2);
343 memcpy(name + 2, ce->name, len + 1);
346 if (MAXARGS <= argc) {
347 status = flush_grep(opt, argc, nr, argv, &kept);
355 } while (i < active_nr &&
356 !strcmp(ce->name, active_cache[i]->name));
357 i--; /* compensate for loop control */
361 status = flush_grep(opt, argc, nr, argv, NULL);
369 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
377 * Use the external "grep" command for the case where
378 * we grep through the checked-out files. It tends to
379 * be a lot more optimized
382 hit = external_grep(opt, paths, cached);
388 for (nr = 0; nr < active_nr; nr++) {
389 struct cache_entry *ce = active_cache[nr];
390 if (!S_ISREG(ce->ce_mode))
392 if (!pathspec_matches(paths, ce->name))
397 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
400 hit |= grep_file(opt, ce->name);
404 } while (nr < active_nr &&
405 !strcmp(ce->name, active_cache[nr]->name));
406 nr--; /* compensate for loop control */
409 free_grep_patterns(opt);
413 static int grep_tree(struct grep_opt *opt, const char **paths,
414 struct tree_desc *tree,
415 const char *tree_name, const char *base)
419 struct name_entry entry;
421 int tn_len = strlen(tree_name);
422 char *path_buf = xmalloc(PATH_MAX + tn_len + 100);
425 tn_len = sprintf(path_buf, "%s:", tree_name);
426 down = path_buf + tn_len;
433 len = strlen(path_buf);
435 while (tree_entry(tree, &entry)) {
436 strcpy(path_buf + len, entry.path);
438 if (S_ISDIR(entry.mode))
439 /* Match "abc/" against pathspec to
440 * decide if we want to descend into "abc"
443 strcpy(path_buf + len + tree_entry_len(entry.path, entry.sha1), "/");
445 if (!pathspec_matches(paths, down))
447 else if (S_ISREG(entry.mode))
448 hit |= grep_sha1(opt, entry.sha1, path_buf, tn_len);
449 else if (S_ISDIR(entry.mode)) {
450 enum object_type type;
451 struct tree_desc sub;
455 data = read_sha1_file(entry.sha1, &type, &size);
457 die("unable to read tree (%s)",
458 sha1_to_hex(entry.sha1));
459 init_tree_desc(&sub, data, size);
460 hit |= grep_tree(opt, paths, &sub, tree_name, down);
467 static int grep_object(struct grep_opt *opt, const char **paths,
468 struct object *obj, const char *name)
470 if (obj->type == OBJ_BLOB)
471 return grep_sha1(opt, obj->sha1, name, 0);
472 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
473 struct tree_desc tree;
477 data = read_object_with_reference(obj->sha1, tree_type,
480 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
481 init_tree_desc(&tree, data, size);
482 hit = grep_tree(opt, paths, &tree, name, "");
486 die("unable to grep from object of type %s", typename(obj->type));
489 static const char builtin_grep_usage[] =
490 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
492 static const char emsg_invalid_context_len[] =
493 "%s: invalid context length argument";
494 static const char emsg_missing_context_len[] =
495 "missing context length argument";
496 static const char emsg_missing_argument[] =
497 "option requires an argument -%s";
499 int cmd_grep(int argc, const char **argv, const char *prefix)
503 int seen_dashdash = 0;
505 struct object_array list = { 0, 0, NULL };
506 const char **paths = NULL;
509 memset(&opt, 0, sizeof(opt));
510 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
513 opt.pattern_tail = &opt.pattern_list;
514 opt.regflags = REG_NEWLINE;
517 * If there is no -- then the paths must exist in the working
518 * tree. If there is no explicit pattern specified with -e or
519 * -f, we take the first unrecognized non option to be the
520 * pattern, but then what follows it must be zero or more
521 * valid refs up to the -- (if exists), and then existing
522 * paths. If there is an explicit pattern, then the first
523 * unrecognized non option is the beginning of the refs list
524 * that continues up to the -- (if exists), and then paths.
528 const char *arg = argv[1];
530 if (!strcmp("--cached", arg)) {
534 if (!strcmp("-a", arg) ||
535 !strcmp("--text", arg)) {
536 opt.binary = GREP_BINARY_TEXT;
539 if (!strcmp("-i", arg) ||
540 !strcmp("--ignore-case", arg)) {
541 opt.regflags |= REG_ICASE;
544 if (!strcmp("-I", arg)) {
545 opt.binary = GREP_BINARY_NOMATCH;
548 if (!strcmp("-v", arg) ||
549 !strcmp("--invert-match", arg)) {
553 if (!strcmp("-E", arg) ||
554 !strcmp("--extended-regexp", arg)) {
555 opt.regflags |= REG_EXTENDED;
558 if (!strcmp("-F", arg) ||
559 !strcmp("--fixed-strings", arg)) {
563 if (!strcmp("-G", arg) ||
564 !strcmp("--basic-regexp", arg)) {
565 opt.regflags &= ~REG_EXTENDED;
568 if (!strcmp("-n", arg)) {
572 if (!strcmp("-h", arg)) {
576 if (!strcmp("-H", arg)) {
580 if (!strcmp("-l", arg) ||
581 !strcmp("--name-only", arg) ||
582 !strcmp("--files-with-matches", arg)) {
586 if (!strcmp("-L", arg) ||
587 !strcmp("--files-without-match", arg)) {
588 opt.unmatch_name_only = 1;
591 if (!strcmp("-c", arg) ||
592 !strcmp("--count", arg)) {
596 if (!strcmp("-w", arg) ||
597 !strcmp("--word-regexp", arg)) {
601 if (!prefixcmp(arg, "-A") ||
602 !prefixcmp(arg, "-B") ||
603 !prefixcmp(arg, "-C") ||
604 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
608 case 'A': case 'B': case 'C':
611 die(emsg_missing_context_len);
622 if (strtoul_ui(scan, 10, &num))
623 die(emsg_invalid_context_len, scan);
626 opt.post_context = num;
630 opt.post_context = num;
632 opt.pre_context = num;
637 if (!strcmp("-f", arg)) {
642 die(emsg_missing_argument, arg);
643 patterns = fopen(argv[1], "r");
645 die("'%s': %s", argv[1], strerror(errno));
646 while (fgets(buf, sizeof(buf), patterns)) {
647 int len = strlen(buf);
648 if (len && buf[len-1] == '\n')
650 /* ignore empty line like grep does */
653 append_grep_pattern(&opt, xstrdup(buf),
662 if (!strcmp("--not", arg)) {
663 append_grep_pattern(&opt, arg, "command line", 0,
667 if (!strcmp("--and", arg)) {
668 append_grep_pattern(&opt, arg, "command line", 0,
672 if (!strcmp("--or", arg))
673 continue; /* no-op */
674 if (!strcmp("(", arg)) {
675 append_grep_pattern(&opt, arg, "command line", 0,
679 if (!strcmp(")", arg)) {
680 append_grep_pattern(&opt, arg, "command line", 0,
684 if (!strcmp("--all-match", arg)) {
688 if (!strcmp("-e", arg)) {
690 append_grep_pattern(&opt, argv[1],
697 die(emsg_missing_argument, arg);
699 if (!strcmp("--full-name", arg)) {
703 if (!strcmp("--", arg)) {
704 /* later processing wants to have this at argv[1] */
710 usage(builtin_grep_usage);
712 /* First unrecognized non-option token */
713 if (!opt.pattern_list) {
714 append_grep_pattern(&opt, arg, "command line", 0,
719 /* We are looking at the first path or rev;
720 * it is found at argv[1] after leaving the
728 if (!opt.pattern_list)
729 die("no pattern given.");
730 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
731 die("cannot mix --fixed-strings and regexp");
732 compile_grep_patterns(&opt);
734 /* Check revs and then paths */
735 for (i = 1; i < argc; i++) {
736 const char *arg = argv[i];
737 unsigned char sha1[20];
739 if (!get_sha1(arg, sha1)) {
740 struct object *object = parse_object(sha1);
742 die("bad object %s", arg);
743 add_object_array(object, arg, &list);
746 if (!strcmp(arg, "--")) {
753 /* The rest are paths */
754 if (!seen_dashdash) {
756 for (j = i; j < argc; j++)
757 verify_filename(prefix, argv[j]);
761 paths = get_pathspec(prefix, argv + i);
762 if (opt.prefix_length && opt.relative) {
763 /* Make sure we do not get outside of paths */
764 for (i = 0; paths[i]; i++)
765 if (strncmp(prefix, paths[i], opt.prefix_length))
766 die("git-grep: cannot generate relative filenames containing '..'");
770 paths = xcalloc(2, sizeof(const char *));
776 return !grep_cache(&opt, paths, cached);
779 die("both --cached and trees are given.");
781 for (i = 0; i < list.nr; i++) {
782 struct object *real_obj;
783 real_obj = deref_tag(list.objects[i].item, NULL, 0);
784 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
787 free_grep_patterns(&opt);