Merge branch 'maint'
[git/jrn.git] / builtin-grep.c
blob3f12ba382690699d96580c3ddb1a61c79520e694
1 /*
2 * Builtin "git grep"
4 * Copyright (c) 2006 Junio C Hamano
5 */
6 #include "cache.h"
7 #include "blob.h"
8 #include "tree.h"
9 #include "commit.h"
10 #include "tag.h"
11 #include "tree-walk.h"
12 #include "builtin.h"
13 #include "grep.h"
15 #ifndef NO_EXTERNAL_GREP
16 #ifdef __unix__
17 #define NO_EXTERNAL_GREP 0
18 #else
19 #define NO_EXTERNAL_GREP 1
20 #endif
21 #endif
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)
31 int namelen, i;
32 if (!paths || !*paths)
33 return 1;
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;
40 if (!matchlen ||
41 ((matchlen <= namelen) &&
42 !strncmp(name, match, matchlen) &&
43 (match[matchlen-1] == '/' ||
44 name[matchlen] == '\0' || name[matchlen] == '/')))
45 return 1;
46 if (!fnmatch(match, name, 0))
47 return 1;
48 if (name[namelen-1] != '/')
49 continue;
51 /* We are being asked if the directory ("name") is worth
52 * descending into.
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++) {
59 char ch = *cp;
60 if (ch == '*' || ch == '[' || ch == '?') {
61 meta = cp;
62 break;
65 if (!meta)
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))
75 return 1;
76 continue;
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))
86 return 1;
87 continue;
90 return 0;
93 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
95 unsigned long size;
96 char *data;
97 enum object_type type;
98 char *to_free = NULL;
99 int hit;
101 data = read_sha1_file(sha1, &type, &size);
102 if (!data) {
103 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
104 return 0;
106 if (opt->relative && opt->prefix_length) {
107 static char name_buf[PATH_MAX];
108 char *cp;
109 int name_len = strlen(name) - opt->prefix_length + 1;
111 if (!tree_name_len)
112 name += opt->prefix_length;
113 else {
114 if (ARRAY_SIZE(name_buf) <= name_len)
115 cp = to_free = xmalloc(name_len);
116 else
117 cp = name_buf;
118 memcpy(cp, name, tree_name_len);
119 strcpy(cp + tree_name_len,
120 name + tree_name_len + opt->prefix_length);
121 name = cp;
124 hit = grep_buffer(opt, name, data, size);
125 free(data);
126 free(to_free);
127 return hit;
130 static int grep_file(struct grep_opt *opt, const char *filename)
132 struct stat st;
133 int i;
134 char *data;
135 size_t sz;
137 if (lstat(filename, &st) < 0) {
138 err_ret:
139 if (errno != ENOENT)
140 error("'%s': %s", filename, strerror(errno));
141 return 0;
143 if (!st.st_size)
144 return 0; /* empty file -- no grep hit */
145 if (!S_ISREG(st.st_mode))
146 return 0;
147 sz = xsize_t(st.st_size);
148 i = open(filename, O_RDONLY);
149 if (i < 0)
150 goto err_ret;
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));
154 close(i);
155 free(data);
156 return 0;
158 close(i);
159 if (opt->relative && opt->prefix_length)
160 filename += opt->prefix_length;
161 i = grep_buffer(opt, filename, data, sz);
162 free(data);
163 return i;
166 #if !NO_EXTERNAL_GREP
167 static int exec_grep(int argc, const char **argv)
169 pid_t pid;
170 int status;
172 argv[argc] = NULL;
173 pid = fork();
174 if (pid < 0)
175 return pid;
176 if (!pid) {
177 execvp("grep", (char **) argv);
178 exit(255);
180 while (waitpid(pid, &status, 0) < 0) {
181 if (errno == EINTR)
182 continue;
183 return -1;
185 if (WIFEXITED(status)) {
186 if (!WEXITSTATUS(status))
187 return 1;
188 return 0;
190 return -1;
193 #define MAXARGS 1000
194 #define ARGBUF 4096
195 #define push_arg(a) do { \
196 if (nr < MAXARGS) argv[nr++] = (a); \
197 else die("maximum number of args exceeded"); \
198 } while (0)
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)
211 int status;
212 int count = argc - arg0;
213 const char *kept_0 = NULL;
215 if (count <= 2) {
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.
225 if (kept)
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".
234 if (count == 1 &&
235 !opt->name_only &&
236 !opt->unmatch_name_only &&
237 !opt->count) {
238 argv[argc++] = "/dev/null";
239 argv[argc] = NULL;
243 else if (kept) {
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.
252 *kept = 2;
253 kept_0 = argv[argc-2];
254 argv[argc-2] = NULL;
255 argc -= 2;
258 status = exec_grep(argc, argv);
260 if (kept_0) {
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];
269 return status;
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;
278 struct grep_pat *p;
280 if (opt->extended || (opt->relative && opt->prefix_length))
281 return -1;
282 len = nr = 0;
283 push_arg("grep");
284 if (opt->fixed)
285 push_arg("-F");
286 if (opt->linenum)
287 push_arg("-n");
288 if (!opt->pathname)
289 push_arg("-h");
290 if (opt->regflags & REG_EXTENDED)
291 push_arg("-E");
292 if (opt->regflags & REG_ICASE)
293 push_arg("-i");
294 if (opt->binary == GREP_BINARY_NOMATCH)
295 push_arg("-I");
296 if (opt->word_regexp)
297 push_arg("-w");
298 if (opt->name_only)
299 push_arg("-l");
300 if (opt->unmatch_name_only)
301 push_arg("-L");
302 if (opt->null_following_name)
303 /* in GNU grep git's "-z" translates to "-Z" */
304 push_arg("-Z");
305 if (opt->count)
306 push_arg("-c");
307 if (opt->post_context || opt->pre_context) {
308 if (opt->post_context != opt->pre_context) {
309 if (opt->pre_context) {
310 push_arg("-B");
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");
315 push_arg(argptr);
316 argptr += len;
318 if (opt->post_context) {
319 push_arg("-A");
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");
324 push_arg(argptr);
325 argptr += len;
328 else {
329 push_arg("-C");
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");
334 push_arg(argptr);
335 argptr += len;
338 for (p = opt->pattern_list; p; p = p->next) {
339 push_arg("-e");
340 push_arg(p->pattern);
343 hit = 0;
344 argc = nr;
345 for (i = 0; i < active_nr; i++) {
346 struct cache_entry *ce = active_cache[i];
347 char *name;
348 int kept;
349 if (!S_ISREG(ce->ce_mode))
350 continue;
351 if (!pathspec_matches(paths, ce->name))
352 continue;
353 name = 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);
360 argv[argc++] = name;
361 if (MAXARGS <= argc) {
362 status = flush_grep(opt, argc, nr, argv, &kept);
363 if (0 < status)
364 hit = 1;
365 argc = nr + kept;
367 if (ce_stage(ce)) {
368 do {
369 i++;
370 } while (i < active_nr &&
371 !strcmp(ce->name, active_cache[i]->name));
372 i--; /* compensate for loop control */
375 if (argc > nr) {
376 status = flush_grep(opt, argc, nr, argv, NULL);
377 if (0 < status)
378 hit = 1;
380 return hit;
382 #endif
384 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
386 int hit = 0;
387 int nr;
388 read_cache();
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);
398 if (hit >= 0)
399 return hit;
401 #endif
403 for (nr = 0; nr < active_nr; nr++) {
404 struct cache_entry *ce = active_cache[nr];
405 if (!S_ISREG(ce->ce_mode))
406 continue;
407 if (!pathspec_matches(paths, ce->name))
408 continue;
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)) {
415 if (ce_stage(ce))
416 continue;
417 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
419 else
420 hit |= grep_file(opt, ce->name);
421 if (ce_stage(ce)) {
422 do {
423 nr++;
424 } while (nr < active_nr &&
425 !strcmp(ce->name, active_cache[nr]->name));
426 nr--; /* compensate for loop control */
429 free_grep_patterns(opt);
430 return hit;
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)
437 int len;
438 int hit = 0;
439 struct name_entry entry;
440 char *down;
441 int tn_len = strlen(tree_name);
442 struct strbuf pathbuf;
444 strbuf_init(&pathbuf, PATH_MAX + tn_len);
446 if (tn_len) {
447 strbuf_add(&pathbuf, tree_name, tn_len);
448 strbuf_addch(&pathbuf, ':');
449 tn_len = pathbuf.len;
451 strbuf_addstr(&pathbuf, base);
452 len = pathbuf.len;
454 while (tree_entry(tree, &entry)) {
455 int te_len = tree_entry_len(entry.path, entry.sha1);
456 pathbuf.len = len;
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"
462 * directory.
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;
474 void *data;
475 unsigned long size;
477 data = read_sha1_file(entry.sha1, &type, &size);
478 if (!data)
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);
483 free(data);
486 strbuf_release(&pathbuf);
487 return hit;
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;
497 void *data;
498 unsigned long size;
499 int hit;
500 data = read_object_with_reference(obj->sha1, tree_type,
501 &size, NULL);
502 if (!data)
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, "");
506 free(data);
507 return hit;
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)
524 int hit = 0;
525 int cached = 0;
526 int seen_dashdash = 0;
527 struct grep_opt opt;
528 struct object_array list = { 0, 0, NULL };
529 const char **paths = NULL;
530 int i;
532 memset(&opt, 0, sizeof(opt));
533 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
534 opt.relative = 1;
535 opt.pathname = 1;
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.
550 while (1 < argc) {
551 const char *arg = argv[1];
552 argc--; argv++;
553 if (!strcmp("--cached", arg)) {
554 cached = 1;
555 continue;
557 if (!strcmp("--no-ext-grep", arg)) {
558 builtin_grep = 1;
559 continue;
561 if (!strcmp("-a", arg) ||
562 !strcmp("--text", arg)) {
563 opt.binary = GREP_BINARY_TEXT;
564 continue;
566 if (!strcmp("-i", arg) ||
567 !strcmp("--ignore-case", arg)) {
568 opt.regflags |= REG_ICASE;
569 continue;
571 if (!strcmp("-I", arg)) {
572 opt.binary = GREP_BINARY_NOMATCH;
573 continue;
575 if (!strcmp("-v", arg) ||
576 !strcmp("--invert-match", arg)) {
577 opt.invert = 1;
578 continue;
580 if (!strcmp("-E", arg) ||
581 !strcmp("--extended-regexp", arg)) {
582 opt.regflags |= REG_EXTENDED;
583 continue;
585 if (!strcmp("-F", arg) ||
586 !strcmp("--fixed-strings", arg)) {
587 opt.fixed = 1;
588 continue;
590 if (!strcmp("-G", arg) ||
591 !strcmp("--basic-regexp", arg)) {
592 opt.regflags &= ~REG_EXTENDED;
593 continue;
595 if (!strcmp("-n", arg)) {
596 opt.linenum = 1;
597 continue;
599 if (!strcmp("-h", arg)) {
600 opt.pathname = 0;
601 continue;
603 if (!strcmp("-H", arg)) {
604 opt.pathname = 1;
605 continue;
607 if (!strcmp("-l", arg) ||
608 !strcmp("--name-only", arg) ||
609 !strcmp("--files-with-matches", arg)) {
610 opt.name_only = 1;
611 continue;
613 if (!strcmp("-L", arg) ||
614 !strcmp("--files-without-match", arg)) {
615 opt.unmatch_name_only = 1;
616 continue;
618 if (!strcmp("-z", arg) ||
619 !strcmp("--null", arg)) {
620 opt.null_following_name = 1;
621 continue;
623 if (!strcmp("-c", arg) ||
624 !strcmp("--count", arg)) {
625 opt.count = 1;
626 continue;
628 if (!strcmp("-w", arg) ||
629 !strcmp("--word-regexp", arg)) {
630 opt.word_regexp = 1;
631 continue;
633 if (!prefixcmp(arg, "-A") ||
634 !prefixcmp(arg, "-B") ||
635 !prefixcmp(arg, "-C") ||
636 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
637 unsigned num;
638 const char *scan;
639 switch (arg[1]) {
640 case 'A': case 'B': case 'C':
641 if (!arg[2]) {
642 if (argc <= 1)
643 die(emsg_missing_context_len);
644 scan = *++argv;
645 argc--;
647 else
648 scan = arg + 2;
649 break;
650 default:
651 scan = arg + 1;
652 break;
654 if (strtoul_ui(scan, 10, &num))
655 die(emsg_invalid_context_len, scan);
656 switch (arg[1]) {
657 case 'A':
658 opt.post_context = num;
659 break;
660 default:
661 case 'C':
662 opt.post_context = num;
663 case 'B':
664 opt.pre_context = num;
665 break;
667 continue;
669 if (!strcmp("-f", arg)) {
670 FILE *patterns;
671 int lno = 0;
672 char buf[1024];
673 if (argc <= 1)
674 die(emsg_missing_argument, arg);
675 patterns = fopen(argv[1], "r");
676 if (!patterns)
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')
681 buf[len-1] = 0;
682 /* ignore empty line like grep does */
683 if (!buf[0])
684 continue;
685 append_grep_pattern(&opt, xstrdup(buf),
686 argv[1], ++lno,
687 GREP_PATTERN);
689 fclose(patterns);
690 argv++;
691 argc--;
692 continue;
694 if (!strcmp("--not", arg)) {
695 append_grep_pattern(&opt, arg, "command line", 0,
696 GREP_NOT);
697 continue;
699 if (!strcmp("--and", arg)) {
700 append_grep_pattern(&opt, arg, "command line", 0,
701 GREP_AND);
702 continue;
704 if (!strcmp("--or", arg))
705 continue; /* no-op */
706 if (!strcmp("(", arg)) {
707 append_grep_pattern(&opt, arg, "command line", 0,
708 GREP_OPEN_PAREN);
709 continue;
711 if (!strcmp(")", arg)) {
712 append_grep_pattern(&opt, arg, "command line", 0,
713 GREP_CLOSE_PAREN);
714 continue;
716 if (!strcmp("--all-match", arg)) {
717 opt.all_match = 1;
718 continue;
720 if (!strcmp("-e", arg)) {
721 if (1 < argc) {
722 append_grep_pattern(&opt, argv[1],
723 "-e option", 0,
724 GREP_PATTERN);
725 argv++;
726 argc--;
727 continue;
729 die(emsg_missing_argument, arg);
731 if (!strcmp("--full-name", arg)) {
732 opt.relative = 0;
733 continue;
735 if (!strcmp("--", arg)) {
736 /* later processing wants to have this at argv[1] */
737 argv--;
738 argc++;
739 break;
741 if (*arg == '-')
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,
747 GREP_PATTERN);
748 break;
750 else {
751 /* We are looking at the first path or rev;
752 * it is found at argv[1] after leaving the
753 * loop.
755 argc++; argv--;
756 break;
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];
770 /* Is it a rev? */
771 if (!get_sha1(arg, sha1)) {
772 struct object *object = parse_object(sha1);
773 if (!object)
774 die("bad object %s", arg);
775 add_object_array(object, arg, &list);
776 continue;
778 if (!strcmp(arg, "--")) {
779 i++;
780 seen_dashdash = 1;
782 break;
785 /* The rest are paths */
786 if (!seen_dashdash) {
787 int j;
788 for (j = i; j < argc; j++)
789 verify_filename(prefix, argv[j]);
792 if (i < argc) {
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 '..'");
801 else if (prefix) {
802 paths = xcalloc(2, sizeof(const char *));
803 paths[0] = prefix;
804 paths[1] = NULL;
807 if (!list.nr) {
808 if (!cached)
809 setup_work_tree();
810 return !grep_cache(&opt, paths, cached);
813 if (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))
820 hit = 1;
822 free_grep_patterns(&opt);
823 return !hit;