Merge branch 'mv/commit-tree'
[debian-git.git] / builtin-grep.c
blob3a51662a35878ae6b5965c90abb747b5b27c5493
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 struct strbuf pathbuf;
432 strbuf_init(&pathbuf, PATH_MAX + tn_len);
434 if (tn_len) {
435 strbuf_add(&pathbuf, tree_name, tn_len);
436 strbuf_addch(&pathbuf, ':');
437 tn_len = pathbuf.len;
439 strbuf_addstr(&pathbuf, base);
440 len = pathbuf.len;
442 while (tree_entry(tree, &entry)) {
443 int te_len = tree_entry_len(entry.path, entry.sha1);
444 pathbuf.len = len;
445 strbuf_add(&pathbuf, entry.path, te_len);
447 if (S_ISDIR(entry.mode))
448 /* Match "abc/" against pathspec to
449 * decide if we want to descend into "abc"
450 * directory.
452 strbuf_addch(&pathbuf, '/');
454 down = pathbuf.buf + tn_len;
455 if (!pathspec_matches(paths, down))
457 else if (S_ISREG(entry.mode))
458 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
459 else if (S_ISDIR(entry.mode)) {
460 enum object_type type;
461 struct tree_desc sub;
462 void *data;
463 unsigned long size;
465 data = read_sha1_file(entry.sha1, &type, &size);
466 if (!data)
467 die("unable to read tree (%s)",
468 sha1_to_hex(entry.sha1));
469 init_tree_desc(&sub, data, size);
470 hit |= grep_tree(opt, paths, &sub, tree_name, down);
471 free(data);
474 strbuf_release(&pathbuf);
475 return hit;
478 static int grep_object(struct grep_opt *opt, const char **paths,
479 struct object *obj, const char *name)
481 if (obj->type == OBJ_BLOB)
482 return grep_sha1(opt, obj->sha1, name, 0);
483 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
484 struct tree_desc tree;
485 void *data;
486 unsigned long size;
487 int hit;
488 data = read_object_with_reference(obj->sha1, tree_type,
489 &size, NULL);
490 if (!data)
491 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
492 init_tree_desc(&tree, data, size);
493 hit = grep_tree(opt, paths, &tree, name, "");
494 free(data);
495 return hit;
497 die("unable to grep from object of type %s", typename(obj->type));
500 static const char builtin_grep_usage[] =
501 "git grep <option>* [-e] <pattern> <rev>* [[--] <path>...]";
503 static const char emsg_invalid_context_len[] =
504 "%s: invalid context length argument";
505 static const char emsg_missing_context_len[] =
506 "missing context length argument";
507 static const char emsg_missing_argument[] =
508 "option requires an argument -%s";
510 int cmd_grep(int argc, const char **argv, const char *prefix)
512 int hit = 0;
513 int cached = 0;
514 int seen_dashdash = 0;
515 struct grep_opt opt;
516 struct object_array list = { 0, 0, NULL };
517 const char **paths = NULL;
518 int i;
520 memset(&opt, 0, sizeof(opt));
521 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
522 opt.relative = 1;
523 opt.pathname = 1;
524 opt.pattern_tail = &opt.pattern_list;
525 opt.regflags = REG_NEWLINE;
528 * If there is no -- then the paths must exist in the working
529 * tree. If there is no explicit pattern specified with -e or
530 * -f, we take the first unrecognized non option to be the
531 * pattern, but then what follows it must be zero or more
532 * valid refs up to the -- (if exists), and then existing
533 * paths. If there is an explicit pattern, then the first
534 * unrecognized non option is the beginning of the refs list
535 * that continues up to the -- (if exists), and then paths.
538 while (1 < argc) {
539 const char *arg = argv[1];
540 argc--; argv++;
541 if (!strcmp("--cached", arg)) {
542 cached = 1;
543 continue;
545 if (!strcmp("-a", arg) ||
546 !strcmp("--text", arg)) {
547 opt.binary = GREP_BINARY_TEXT;
548 continue;
550 if (!strcmp("-i", arg) ||
551 !strcmp("--ignore-case", arg)) {
552 opt.regflags |= REG_ICASE;
553 continue;
555 if (!strcmp("-I", arg)) {
556 opt.binary = GREP_BINARY_NOMATCH;
557 continue;
559 if (!strcmp("-v", arg) ||
560 !strcmp("--invert-match", arg)) {
561 opt.invert = 1;
562 continue;
564 if (!strcmp("-E", arg) ||
565 !strcmp("--extended-regexp", arg)) {
566 opt.regflags |= REG_EXTENDED;
567 continue;
569 if (!strcmp("-F", arg) ||
570 !strcmp("--fixed-strings", arg)) {
571 opt.fixed = 1;
572 continue;
574 if (!strcmp("-G", arg) ||
575 !strcmp("--basic-regexp", arg)) {
576 opt.regflags &= ~REG_EXTENDED;
577 continue;
579 if (!strcmp("-n", arg)) {
580 opt.linenum = 1;
581 continue;
583 if (!strcmp("-h", arg)) {
584 opt.pathname = 0;
585 continue;
587 if (!strcmp("-H", arg)) {
588 opt.pathname = 1;
589 continue;
591 if (!strcmp("-l", arg) ||
592 !strcmp("--name-only", arg) ||
593 !strcmp("--files-with-matches", arg)) {
594 opt.name_only = 1;
595 continue;
597 if (!strcmp("-L", arg) ||
598 !strcmp("--files-without-match", arg)) {
599 opt.unmatch_name_only = 1;
600 continue;
602 if (!strcmp("-c", arg) ||
603 !strcmp("--count", arg)) {
604 opt.count = 1;
605 continue;
607 if (!strcmp("-w", arg) ||
608 !strcmp("--word-regexp", arg)) {
609 opt.word_regexp = 1;
610 continue;
612 if (!prefixcmp(arg, "-A") ||
613 !prefixcmp(arg, "-B") ||
614 !prefixcmp(arg, "-C") ||
615 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
616 unsigned num;
617 const char *scan;
618 switch (arg[1]) {
619 case 'A': case 'B': case 'C':
620 if (!arg[2]) {
621 if (argc <= 1)
622 die(emsg_missing_context_len);
623 scan = *++argv;
624 argc--;
626 else
627 scan = arg + 2;
628 break;
629 default:
630 scan = arg + 1;
631 break;
633 if (strtoul_ui(scan, 10, &num))
634 die(emsg_invalid_context_len, scan);
635 switch (arg[1]) {
636 case 'A':
637 opt.post_context = num;
638 break;
639 default:
640 case 'C':
641 opt.post_context = num;
642 case 'B':
643 opt.pre_context = num;
644 break;
646 continue;
648 if (!strcmp("-f", arg)) {
649 FILE *patterns;
650 int lno = 0;
651 char buf[1024];
652 if (argc <= 1)
653 die(emsg_missing_argument, arg);
654 patterns = fopen(argv[1], "r");
655 if (!patterns)
656 die("'%s': %s", argv[1], strerror(errno));
657 while (fgets(buf, sizeof(buf), patterns)) {
658 int len = strlen(buf);
659 if (len && buf[len-1] == '\n')
660 buf[len-1] = 0;
661 /* ignore empty line like grep does */
662 if (!buf[0])
663 continue;
664 append_grep_pattern(&opt, xstrdup(buf),
665 argv[1], ++lno,
666 GREP_PATTERN);
668 fclose(patterns);
669 argv++;
670 argc--;
671 continue;
673 if (!strcmp("--not", arg)) {
674 append_grep_pattern(&opt, arg, "command line", 0,
675 GREP_NOT);
676 continue;
678 if (!strcmp("--and", arg)) {
679 append_grep_pattern(&opt, arg, "command line", 0,
680 GREP_AND);
681 continue;
683 if (!strcmp("--or", arg))
684 continue; /* no-op */
685 if (!strcmp("(", arg)) {
686 append_grep_pattern(&opt, arg, "command line", 0,
687 GREP_OPEN_PAREN);
688 continue;
690 if (!strcmp(")", arg)) {
691 append_grep_pattern(&opt, arg, "command line", 0,
692 GREP_CLOSE_PAREN);
693 continue;
695 if (!strcmp("--all-match", arg)) {
696 opt.all_match = 1;
697 continue;
699 if (!strcmp("-e", arg)) {
700 if (1 < argc) {
701 append_grep_pattern(&opt, argv[1],
702 "-e option", 0,
703 GREP_PATTERN);
704 argv++;
705 argc--;
706 continue;
708 die(emsg_missing_argument, arg);
710 if (!strcmp("--full-name", arg)) {
711 opt.relative = 0;
712 continue;
714 if (!strcmp("--", arg)) {
715 /* later processing wants to have this at argv[1] */
716 argv--;
717 argc++;
718 break;
720 if (*arg == '-')
721 usage(builtin_grep_usage);
723 /* First unrecognized non-option token */
724 if (!opt.pattern_list) {
725 append_grep_pattern(&opt, arg, "command line", 0,
726 GREP_PATTERN);
727 break;
729 else {
730 /* We are looking at the first path or rev;
731 * it is found at argv[1] after leaving the
732 * loop.
734 argc++; argv--;
735 break;
739 if (!opt.pattern_list)
740 die("no pattern given.");
741 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
742 die("cannot mix --fixed-strings and regexp");
743 compile_grep_patterns(&opt);
745 /* Check revs and then paths */
746 for (i = 1; i < argc; i++) {
747 const char *arg = argv[i];
748 unsigned char sha1[20];
749 /* Is it a rev? */
750 if (!get_sha1(arg, sha1)) {
751 struct object *object = parse_object(sha1);
752 if (!object)
753 die("bad object %s", arg);
754 add_object_array(object, arg, &list);
755 continue;
757 if (!strcmp(arg, "--")) {
758 i++;
759 seen_dashdash = 1;
761 break;
764 /* The rest are paths */
765 if (!seen_dashdash) {
766 int j;
767 for (j = i; j < argc; j++)
768 verify_filename(prefix, argv[j]);
771 if (i < argc) {
772 paths = get_pathspec(prefix, argv + i);
773 if (opt.prefix_length && opt.relative) {
774 /* Make sure we do not get outside of paths */
775 for (i = 0; paths[i]; i++)
776 if (strncmp(prefix, paths[i], opt.prefix_length))
777 die("git grep: cannot generate relative filenames containing '..'");
780 else if (prefix) {
781 paths = xcalloc(2, sizeof(const char *));
782 paths[0] = prefix;
783 paths[1] = NULL;
786 if (!list.nr) {
787 if (!cached)
788 setup_work_tree();
789 return !grep_cache(&opt, paths, cached);
792 if (cached)
793 die("both --cached and trees are given.");
795 for (i = 0; i < list.nr; i++) {
796 struct object *real_obj;
797 real_obj = deref_tag(list.objects[i].item, NULL, 0);
798 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
799 hit = 1;
801 free_grep_patterns(&opt);
802 return !hit;