Merge branch 'maint'
[git/debian.git] / builtin-grep.c
blobef299108f529fa5fa931d765828f04535c3a6351
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
24 * git grep pathspecs are somewhat different from diff-tree pathspecs;
25 * pathname wildcards are allowed.
27 static int pathspec_matches(const char **paths, const char *name)
29 int namelen, i;
30 if (!paths || !*paths)
31 return 1;
32 namelen = strlen(name);
33 for (i = 0; paths[i]; i++) {
34 const char *match = paths[i];
35 int matchlen = strlen(match);
36 const char *cp, *meta;
38 if (!matchlen ||
39 ((matchlen <= namelen) &&
40 !strncmp(name, match, matchlen) &&
41 (match[matchlen-1] == '/' ||
42 name[matchlen] == '\0' || name[matchlen] == '/')))
43 return 1;
44 if (!fnmatch(match, name, 0))
45 return 1;
46 if (name[namelen-1] != '/')
47 continue;
49 /* We are being asked if the directory ("name") is worth
50 * descending into.
52 * Find the longest leading directory name that does
53 * not have metacharacter in the pathspec; the name
54 * we are looking at must overlap with that directory.
56 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
57 char ch = *cp;
58 if (ch == '*' || ch == '[' || ch == '?') {
59 meta = cp;
60 break;
63 if (!meta)
64 meta = cp; /* fully literal */
66 if (namelen <= meta - match) {
67 /* Looking at "Documentation/" and
68 * the pattern says "Documentation/howto/", or
69 * "Documentation/diff*.txt". The name we
70 * have should match prefix.
72 if (!memcmp(match, name, namelen))
73 return 1;
74 continue;
77 if (meta - match < namelen) {
78 /* Looking at "Documentation/howto/" and
79 * the pattern says "Documentation/h*";
80 * match up to "Do.../h"; this avoids descending
81 * into "Documentation/technical/".
83 if (!memcmp(match, name, meta - match))
84 return 1;
85 continue;
88 return 0;
91 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
93 unsigned long size;
94 char *data;
95 enum object_type type;
96 char *to_free = NULL;
97 int hit;
99 data = read_sha1_file(sha1, &type, &size);
100 if (!data) {
101 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
102 return 0;
104 if (opt->relative && opt->prefix_length) {
105 static char name_buf[PATH_MAX];
106 char *cp;
107 int name_len = strlen(name) - opt->prefix_length + 1;
109 if (!tree_name_len)
110 name += opt->prefix_length;
111 else {
112 if (ARRAY_SIZE(name_buf) <= name_len)
113 cp = to_free = xmalloc(name_len);
114 else
115 cp = name_buf;
116 memcpy(cp, name, tree_name_len);
117 strcpy(cp + tree_name_len,
118 name + tree_name_len + opt->prefix_length);
119 name = cp;
122 hit = grep_buffer(opt, name, data, size);
123 free(data);
124 free(to_free);
125 return hit;
128 static int grep_file(struct grep_opt *opt, const char *filename)
130 struct stat st;
131 int i;
132 char *data;
133 size_t sz;
135 if (lstat(filename, &st) < 0) {
136 err_ret:
137 if (errno != ENOENT)
138 error("'%s': %s", filename, strerror(errno));
139 return 0;
141 if (!st.st_size)
142 return 0; /* empty file -- no grep hit */
143 if (!S_ISREG(st.st_mode))
144 return 0;
145 sz = xsize_t(st.st_size);
146 i = open(filename, O_RDONLY);
147 if (i < 0)
148 goto err_ret;
149 data = xmalloc(sz + 1);
150 if (st.st_size != read_in_full(i, data, sz)) {
151 error("'%s': short read %s", filename, strerror(errno));
152 close(i);
153 free(data);
154 return 0;
156 close(i);
157 if (opt->relative && opt->prefix_length)
158 filename += opt->prefix_length;
159 i = grep_buffer(opt, filename, data, sz);
160 free(data);
161 return i;
164 #if !NO_EXTERNAL_GREP
165 static int exec_grep(int argc, const char **argv)
167 pid_t pid;
168 int status;
170 argv[argc] = NULL;
171 pid = fork();
172 if (pid < 0)
173 return pid;
174 if (!pid) {
175 execvp("grep", (char **) argv);
176 exit(255);
178 while (waitpid(pid, &status, 0) < 0) {
179 if (errno == EINTR)
180 continue;
181 return -1;
183 if (WIFEXITED(status)) {
184 if (!WEXITSTATUS(status))
185 return 1;
186 return 0;
188 return -1;
191 #define MAXARGS 1000
192 #define ARGBUF 4096
193 #define push_arg(a) do { \
194 if (nr < MAXARGS) argv[nr++] = (a); \
195 else die("maximum number of args exceeded"); \
196 } while (0)
199 * If you send a singleton filename to grep, it does not give
200 * the name of the file. GNU grep has "-H" but we would want
201 * that behaviour in a portable way.
203 * So we keep two pathnames in argv buffer unsent to grep in
204 * the main loop if we need to do more than one grep.
206 static int flush_grep(struct grep_opt *opt,
207 int argc, int arg0, const char **argv, int *kept)
209 int status;
210 int count = argc - arg0;
211 const char *kept_0 = NULL;
213 if (count <= 2) {
215 * Because we keep at least 2 paths in the call from
216 * the main loop (i.e. kept != NULL), and MAXARGS is
217 * far greater than 2, this usually is a call to
218 * conclude the grep. However, the user could attempt
219 * to overflow the argv buffer by giving too many
220 * options to leave very small number of real
221 * arguments even for the call in the main loop.
223 if (kept)
224 die("insanely many options to grep");
227 * If we have two or more paths, we do not have to do
228 * anything special, but we need to push /dev/null to
229 * get "-H" behaviour of GNU grep portably but when we
230 * are not doing "-l" nor "-L" nor "-c".
232 if (count == 1 &&
233 !opt->name_only &&
234 !opt->unmatch_name_only &&
235 !opt->count) {
236 argv[argc++] = "/dev/null";
237 argv[argc] = NULL;
241 else if (kept) {
243 * Called because we found many paths and haven't finished
244 * iterating over the cache yet. We keep two paths
245 * for the concluding call. argv[argc-2] and argv[argc-1]
246 * has the last two paths, so save the first one away,
247 * replace it with NULL while sending the list to grep,
248 * and recover them after we are done.
250 *kept = 2;
251 kept_0 = argv[argc-2];
252 argv[argc-2] = NULL;
253 argc -= 2;
256 status = exec_grep(argc, argv);
258 if (kept_0) {
260 * Then recover them. Now the last arg is beyond the
261 * terminating NULL which is at argc, and the second
262 * from the last is what we saved away in kept_0
264 argv[arg0++] = kept_0;
265 argv[arg0] = argv[argc+1];
267 return status;
270 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
272 int i, nr, argc, hit, len, status;
273 const char *argv[MAXARGS+1];
274 char randarg[ARGBUF];
275 char *argptr = randarg;
276 struct grep_pat *p;
278 if (opt->extended || (opt->relative && opt->prefix_length))
279 return -1;
280 len = nr = 0;
281 push_arg("grep");
282 if (opt->fixed)
283 push_arg("-F");
284 if (opt->linenum)
285 push_arg("-n");
286 if (!opt->pathname)
287 push_arg("-h");
288 if (opt->regflags & REG_EXTENDED)
289 push_arg("-E");
290 if (opt->regflags & REG_ICASE)
291 push_arg("-i");
292 if (opt->word_regexp)
293 push_arg("-w");
294 if (opt->name_only)
295 push_arg("-l");
296 if (opt->unmatch_name_only)
297 push_arg("-L");
298 if (opt->count)
299 push_arg("-c");
300 if (opt->post_context || opt->pre_context) {
301 if (opt->post_context != opt->pre_context) {
302 if (opt->pre_context) {
303 push_arg("-B");
304 len += snprintf(argptr, sizeof(randarg)-len,
305 "%u", opt->pre_context) + 1;
306 if (sizeof(randarg) <= len)
307 die("maximum length of args exceeded");
308 push_arg(argptr);
309 argptr += len;
311 if (opt->post_context) {
312 push_arg("-A");
313 len += snprintf(argptr, sizeof(randarg)-len,
314 "%u", opt->post_context) + 1;
315 if (sizeof(randarg) <= len)
316 die("maximum length of args exceeded");
317 push_arg(argptr);
318 argptr += len;
321 else {
322 push_arg("-C");
323 len += snprintf(argptr, sizeof(randarg)-len,
324 "%u", opt->post_context) + 1;
325 if (sizeof(randarg) <= len)
326 die("maximum length of args exceeded");
327 push_arg(argptr);
328 argptr += len;
331 for (p = opt->pattern_list; p; p = p->next) {
332 push_arg("-e");
333 push_arg(p->pattern);
336 hit = 0;
337 argc = nr;
338 for (i = 0; i < active_nr; i++) {
339 struct cache_entry *ce = active_cache[i];
340 char *name;
341 int kept;
342 if (!S_ISREG(ce->ce_mode))
343 continue;
344 if (!pathspec_matches(paths, ce->name))
345 continue;
346 name = ce->name;
347 if (name[0] == '-') {
348 int len = ce_namelen(ce);
349 name = xmalloc(len + 3);
350 memcpy(name, "./", 2);
351 memcpy(name + 2, ce->name, len + 1);
353 argv[argc++] = name;
354 if (MAXARGS <= argc) {
355 status = flush_grep(opt, argc, nr, argv, &kept);
356 if (0 < status)
357 hit = 1;
358 argc = nr + kept;
360 if (ce_stage(ce)) {
361 do {
362 i++;
363 } while (i < active_nr &&
364 !strcmp(ce->name, active_cache[i]->name));
365 i--; /* compensate for loop control */
368 if (argc > nr) {
369 status = flush_grep(opt, argc, nr, argv, NULL);
370 if (0 < status)
371 hit = 1;
373 return hit;
375 #endif
377 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
379 int hit = 0;
380 int nr;
381 read_cache();
383 #if !NO_EXTERNAL_GREP
385 * Use the external "grep" command for the case where
386 * we grep through the checked-out files. It tends to
387 * be a lot more optimized
389 if (!cached) {
390 hit = external_grep(opt, paths, cached);
391 if (hit >= 0)
392 return hit;
394 #endif
396 for (nr = 0; nr < active_nr; nr++) {
397 struct cache_entry *ce = active_cache[nr];
398 if (!S_ISREG(ce->ce_mode))
399 continue;
400 if (!pathspec_matches(paths, ce->name))
401 continue;
402 if (cached) {
403 if (ce_stage(ce))
404 continue;
405 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
407 else
408 hit |= grep_file(opt, ce->name);
409 if (ce_stage(ce)) {
410 do {
411 nr++;
412 } while (nr < active_nr &&
413 !strcmp(ce->name, active_cache[nr]->name));
414 nr--; /* compensate for loop control */
417 free_grep_patterns(opt);
418 return hit;
421 static int grep_tree(struct grep_opt *opt, const char **paths,
422 struct tree_desc *tree,
423 const char *tree_name, const char *base)
425 int len;
426 int hit = 0;
427 struct name_entry entry;
428 char *down;
429 int tn_len = strlen(tree_name);
430 char *path_buf = xmalloc(PATH_MAX + tn_len + 100);
432 if (tn_len) {
433 tn_len = sprintf(path_buf, "%s:", tree_name);
434 down = path_buf + tn_len;
435 strcat(down, base);
437 else {
438 down = path_buf;
439 strcpy(down, base);
441 len = strlen(path_buf);
443 while (tree_entry(tree, &entry)) {
444 strcpy(path_buf + len, entry.path);
446 if (S_ISDIR(entry.mode))
447 /* Match "abc/" against pathspec to
448 * decide if we want to descend into "abc"
449 * directory.
451 strcpy(path_buf + len + tree_entry_len(entry.path, entry.sha1), "/");
453 if (!pathspec_matches(paths, down))
455 else if (S_ISREG(entry.mode))
456 hit |= grep_sha1(opt, entry.sha1, path_buf, tn_len);
457 else if (S_ISDIR(entry.mode)) {
458 enum object_type type;
459 struct tree_desc sub;
460 void *data;
461 unsigned long size;
463 data = read_sha1_file(entry.sha1, &type, &size);
464 if (!data)
465 die("unable to read tree (%s)",
466 sha1_to_hex(entry.sha1));
467 init_tree_desc(&sub, data, size);
468 hit |= grep_tree(opt, paths, &sub, tree_name, down);
469 free(data);
472 return hit;
475 static int grep_object(struct grep_opt *opt, const char **paths,
476 struct object *obj, const char *name)
478 if (obj->type == OBJ_BLOB)
479 return grep_sha1(opt, obj->sha1, name, 0);
480 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
481 struct tree_desc tree;
482 void *data;
483 unsigned long size;
484 int hit;
485 data = read_object_with_reference(obj->sha1, tree_type,
486 &size, NULL);
487 if (!data)
488 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
489 init_tree_desc(&tree, data, size);
490 hit = grep_tree(opt, paths, &tree, name, "");
491 free(data);
492 return hit;
494 die("unable to grep from object of type %s", typename(obj->type));
497 static const char builtin_grep_usage[] =
498 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
500 static const char emsg_invalid_context_len[] =
501 "%s: invalid context length argument";
502 static const char emsg_missing_context_len[] =
503 "missing context length argument";
504 static const char emsg_missing_argument[] =
505 "option requires an argument -%s";
507 int cmd_grep(int argc, const char **argv, const char *prefix)
509 int hit = 0;
510 int cached = 0;
511 int seen_dashdash = 0;
512 struct grep_opt opt;
513 struct object_array list = { 0, 0, NULL };
514 const char **paths = NULL;
515 int i;
517 memset(&opt, 0, sizeof(opt));
518 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
519 opt.relative = 1;
520 opt.pathname = 1;
521 opt.pattern_tail = &opt.pattern_list;
522 opt.regflags = REG_NEWLINE;
525 * If there is no -- then the paths must exist in the working
526 * tree. If there is no explicit pattern specified with -e or
527 * -f, we take the first unrecognized non option to be the
528 * pattern, but then what follows it must be zero or more
529 * valid refs up to the -- (if exists), and then existing
530 * paths. If there is an explicit pattern, then the first
531 * unrecognized non option is the beginning of the refs list
532 * that continues up to the -- (if exists), and then paths.
535 while (1 < argc) {
536 const char *arg = argv[1];
537 argc--; argv++;
538 if (!strcmp("--cached", arg)) {
539 cached = 1;
540 continue;
542 if (!strcmp("-a", arg) ||
543 !strcmp("--text", arg)) {
544 opt.binary = GREP_BINARY_TEXT;
545 continue;
547 if (!strcmp("-i", arg) ||
548 !strcmp("--ignore-case", arg)) {
549 opt.regflags |= REG_ICASE;
550 continue;
552 if (!strcmp("-I", arg)) {
553 opt.binary = GREP_BINARY_NOMATCH;
554 continue;
556 if (!strcmp("-v", arg) ||
557 !strcmp("--invert-match", arg)) {
558 opt.invert = 1;
559 continue;
561 if (!strcmp("-E", arg) ||
562 !strcmp("--extended-regexp", arg)) {
563 opt.regflags |= REG_EXTENDED;
564 continue;
566 if (!strcmp("-F", arg) ||
567 !strcmp("--fixed-strings", arg)) {
568 opt.fixed = 1;
569 continue;
571 if (!strcmp("-G", arg) ||
572 !strcmp("--basic-regexp", arg)) {
573 opt.regflags &= ~REG_EXTENDED;
574 continue;
576 if (!strcmp("-n", arg)) {
577 opt.linenum = 1;
578 continue;
580 if (!strcmp("-h", arg)) {
581 opt.pathname = 0;
582 continue;
584 if (!strcmp("-H", arg)) {
585 opt.pathname = 1;
586 continue;
588 if (!strcmp("-l", arg) ||
589 !strcmp("--name-only", arg) ||
590 !strcmp("--files-with-matches", arg)) {
591 opt.name_only = 1;
592 continue;
594 if (!strcmp("-L", arg) ||
595 !strcmp("--files-without-match", arg)) {
596 opt.unmatch_name_only = 1;
597 continue;
599 if (!strcmp("-c", arg) ||
600 !strcmp("--count", arg)) {
601 opt.count = 1;
602 continue;
604 if (!strcmp("-w", arg) ||
605 !strcmp("--word-regexp", arg)) {
606 opt.word_regexp = 1;
607 continue;
609 if (!prefixcmp(arg, "-A") ||
610 !prefixcmp(arg, "-B") ||
611 !prefixcmp(arg, "-C") ||
612 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
613 unsigned num;
614 const char *scan;
615 switch (arg[1]) {
616 case 'A': case 'B': case 'C':
617 if (!arg[2]) {
618 if (argc <= 1)
619 die(emsg_missing_context_len);
620 scan = *++argv;
621 argc--;
623 else
624 scan = arg + 2;
625 break;
626 default:
627 scan = arg + 1;
628 break;
630 if (strtoul_ui(scan, 10, &num))
631 die(emsg_invalid_context_len, scan);
632 switch (arg[1]) {
633 case 'A':
634 opt.post_context = num;
635 break;
636 default:
637 case 'C':
638 opt.post_context = num;
639 case 'B':
640 opt.pre_context = num;
641 break;
643 continue;
645 if (!strcmp("-f", arg)) {
646 FILE *patterns;
647 int lno = 0;
648 char buf[1024];
649 if (argc <= 1)
650 die(emsg_missing_argument, arg);
651 patterns = fopen(argv[1], "r");
652 if (!patterns)
653 die("'%s': %s", argv[1], strerror(errno));
654 while (fgets(buf, sizeof(buf), patterns)) {
655 int len = strlen(buf);
656 if (len && buf[len-1] == '\n')
657 buf[len-1] = 0;
658 /* ignore empty line like grep does */
659 if (!buf[0])
660 continue;
661 append_grep_pattern(&opt, xstrdup(buf),
662 argv[1], ++lno,
663 GREP_PATTERN);
665 fclose(patterns);
666 argv++;
667 argc--;
668 continue;
670 if (!strcmp("--not", arg)) {
671 append_grep_pattern(&opt, arg, "command line", 0,
672 GREP_NOT);
673 continue;
675 if (!strcmp("--and", arg)) {
676 append_grep_pattern(&opt, arg, "command line", 0,
677 GREP_AND);
678 continue;
680 if (!strcmp("--or", arg))
681 continue; /* no-op */
682 if (!strcmp("(", arg)) {
683 append_grep_pattern(&opt, arg, "command line", 0,
684 GREP_OPEN_PAREN);
685 continue;
687 if (!strcmp(")", arg)) {
688 append_grep_pattern(&opt, arg, "command line", 0,
689 GREP_CLOSE_PAREN);
690 continue;
692 if (!strcmp("--all-match", arg)) {
693 opt.all_match = 1;
694 continue;
696 if (!strcmp("-e", arg)) {
697 if (1 < argc) {
698 append_grep_pattern(&opt, argv[1],
699 "-e option", 0,
700 GREP_PATTERN);
701 argv++;
702 argc--;
703 continue;
705 die(emsg_missing_argument, arg);
707 if (!strcmp("--full-name", arg)) {
708 opt.relative = 0;
709 continue;
711 if (!strcmp("--", arg)) {
712 /* later processing wants to have this at argv[1] */
713 argv--;
714 argc++;
715 break;
717 if (*arg == '-')
718 usage(builtin_grep_usage);
720 /* First unrecognized non-option token */
721 if (!opt.pattern_list) {
722 append_grep_pattern(&opt, arg, "command line", 0,
723 GREP_PATTERN);
724 break;
726 else {
727 /* We are looking at the first path or rev;
728 * it is found at argv[1] after leaving the
729 * loop.
731 argc++; argv--;
732 break;
736 if (!opt.pattern_list)
737 die("no pattern given.");
738 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
739 die("cannot mix --fixed-strings and regexp");
740 compile_grep_patterns(&opt);
742 /* Check revs and then paths */
743 for (i = 1; i < argc; i++) {
744 const char *arg = argv[i];
745 unsigned char sha1[20];
746 /* Is it a rev? */
747 if (!get_sha1(arg, sha1)) {
748 struct object *object = parse_object(sha1);
749 if (!object)
750 die("bad object %s", arg);
751 add_object_array(object, arg, &list);
752 continue;
754 if (!strcmp(arg, "--")) {
755 i++;
756 seen_dashdash = 1;
758 break;
761 /* The rest are paths */
762 if (!seen_dashdash) {
763 int j;
764 for (j = i; j < argc; j++)
765 verify_filename(prefix, argv[j]);
768 if (i < argc) {
769 paths = get_pathspec(prefix, argv + i);
770 if (opt.prefix_length && opt.relative) {
771 /* Make sure we do not get outside of paths */
772 for (i = 0; paths[i]; i++)
773 if (strncmp(prefix, paths[i], opt.prefix_length))
774 die("git-grep: cannot generate relative filenames containing '..'");
777 else if (prefix) {
778 paths = xcalloc(2, sizeof(const char *));
779 paths[0] = prefix;
780 paths[1] = NULL;
783 if (!list.nr)
784 return !grep_cache(&opt, paths, cached);
786 if (cached)
787 die("both --cached and trees are given.");
789 for (i = 0; i < list.nr; i++) {
790 struct object *real_obj;
791 real_obj = deref_tag(list.objects[i].item, NULL, 0);
792 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
793 hit = 1;
795 free_grep_patterns(&opt);
796 return !hit;