t4200: use cut instead of sed
[git/peff.git] / builtin-grep.c
blob44d9bac8bf7ecfd62d3782171b20693d7d1498e4
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"
14 #include "run-command.h"
16 #ifndef NO_EXTERNAL_GREP
17 #ifdef __unix__
18 #define NO_EXTERNAL_GREP 0
19 #else
20 #define NO_EXTERNAL_GREP 1
21 #endif
22 #endif
25 * git grep pathspecs are somewhat different from diff-tree pathspecs;
26 * pathname wildcards are allowed.
28 static int pathspec_matches(const char **paths, const char *name)
30 int namelen, i;
31 if (!paths || !*paths)
32 return 1;
33 namelen = strlen(name);
34 for (i = 0; paths[i]; i++) {
35 const char *match = paths[i];
36 int matchlen = strlen(match);
37 const char *cp, *meta;
39 if (!matchlen ||
40 ((matchlen <= namelen) &&
41 !strncmp(name, match, matchlen) &&
42 (match[matchlen-1] == '/' ||
43 name[matchlen] == '\0' || name[matchlen] == '/')))
44 return 1;
45 if (!fnmatch(match, name, 0))
46 return 1;
47 if (name[namelen-1] != '/')
48 continue;
50 /* We are being asked if the directory ("name") is worth
51 * descending into.
53 * Find the longest leading directory name that does
54 * not have metacharacter in the pathspec; the name
55 * we are looking at must overlap with that directory.
57 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
58 char ch = *cp;
59 if (ch == '*' || ch == '[' || ch == '?') {
60 meta = cp;
61 break;
64 if (!meta)
65 meta = cp; /* fully literal */
67 if (namelen <= meta - match) {
68 /* Looking at "Documentation/" and
69 * the pattern says "Documentation/howto/", or
70 * "Documentation/diff*.txt". The name we
71 * have should match prefix.
73 if (!memcmp(match, name, namelen))
74 return 1;
75 continue;
78 if (meta - match < namelen) {
79 /* Looking at "Documentation/howto/" and
80 * the pattern says "Documentation/h*";
81 * match up to "Do.../h"; this avoids descending
82 * into "Documentation/technical/".
84 if (!memcmp(match, name, meta - match))
85 return 1;
86 continue;
89 return 0;
92 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
94 unsigned long size;
95 char *data;
96 enum object_type type;
97 char *to_free = NULL;
98 int hit;
100 data = read_sha1_file(sha1, &type, &size);
101 if (!data) {
102 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
103 return 0;
105 if (opt->relative && opt->prefix_length) {
106 static char name_buf[PATH_MAX];
107 char *cp;
108 int name_len = strlen(name) - opt->prefix_length + 1;
110 if (!tree_name_len)
111 name += opt->prefix_length;
112 else {
113 if (ARRAY_SIZE(name_buf) <= name_len)
114 cp = to_free = xmalloc(name_len);
115 else
116 cp = name_buf;
117 memcpy(cp, name, tree_name_len);
118 strcpy(cp + tree_name_len,
119 name + tree_name_len + opt->prefix_length);
120 name = cp;
123 hit = grep_buffer(opt, name, data, size);
124 free(data);
125 free(to_free);
126 return hit;
129 static int grep_file(struct grep_opt *opt, const char *filename)
131 struct stat st;
132 int i;
133 char *data;
134 size_t sz;
136 if (lstat(filename, &st) < 0) {
137 err_ret:
138 if (errno != ENOENT)
139 error("'%s': %s", filename, strerror(errno));
140 return 0;
142 if (!st.st_size)
143 return 0; /* empty file -- no grep hit */
144 if (!S_ISREG(st.st_mode))
145 return 0;
146 sz = xsize_t(st.st_size);
147 i = open(filename, O_RDONLY);
148 if (i < 0)
149 goto err_ret;
150 data = xmalloc(sz + 1);
151 if (st.st_size != read_in_full(i, data, sz)) {
152 error("'%s': short read %s", filename, strerror(errno));
153 close(i);
154 free(data);
155 return 0;
157 close(i);
158 if (opt->relative && opt->prefix_length)
159 filename += opt->prefix_length;
160 i = grep_buffer(opt, filename, data, sz);
161 free(data);
162 return i;
165 #if !NO_EXTERNAL_GREP
166 #define MAXARGS 1000
167 #define ARGBUF 4096
168 #define push_arg(a) do { \
169 if (nr < MAXARGS) argv[nr++] = (a); \
170 else die("maximum number of args exceeded"); \
171 } while (0)
174 * If you send a singleton filename to grep, it does not give
175 * the name of the file. GNU grep has "-H" but we would want
176 * that behaviour in a portable way.
178 * So we keep two pathnames in argv buffer unsent to grep in
179 * the main loop if we need to do more than one grep.
181 static int flush_grep(struct grep_opt *opt,
182 int argc, int arg0, const char **argv, int *kept)
184 int status;
185 int count = argc - arg0;
186 const char *kept_0 = NULL;
188 if (count <= 2) {
190 * Because we keep at least 2 paths in the call from
191 * the main loop (i.e. kept != NULL), and MAXARGS is
192 * far greater than 2, this usually is a call to
193 * conclude the grep. However, the user could attempt
194 * to overflow the argv buffer by giving too many
195 * options to leave very small number of real
196 * arguments even for the call in the main loop.
198 if (kept)
199 die("insanely many options to grep");
202 * If we have two or more paths, we do not have to do
203 * anything special, but we need to push /dev/null to
204 * get "-H" behaviour of GNU grep portably but when we
205 * are not doing "-l" nor "-L" nor "-c".
207 if (count == 1 &&
208 !opt->name_only &&
209 !opt->unmatch_name_only &&
210 !opt->count) {
211 argv[argc++] = "/dev/null";
212 argv[argc] = NULL;
216 else if (kept) {
218 * Called because we found many paths and haven't finished
219 * iterating over the cache yet. We keep two paths
220 * for the concluding call. argv[argc-2] and argv[argc-1]
221 * has the last two paths, so save the first one away,
222 * replace it with NULL while sending the list to grep,
223 * and recover them after we are done.
225 *kept = 2;
226 kept_0 = argv[argc-2];
227 argv[argc-2] = NULL;
228 argc -= 2;
231 argv[argc] = NULL;
232 status = run_command_v_opt(argv, 0);
234 if (kept_0) {
236 * Then recover them. Now the last arg is beyond the
237 * terminating NULL which is at argc, and the second
238 * from the last is what we saved away in kept_0
240 argv[arg0++] = kept_0;
241 argv[arg0] = argv[argc+1];
243 return status == 0 ? 1 : -1;
246 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
248 int i, nr, argc, hit, len, status;
249 const char *argv[MAXARGS+1];
250 char randarg[ARGBUF];
251 char *argptr = randarg;
252 struct grep_pat *p;
254 if (opt->extended || (opt->relative && opt->prefix_length))
255 return -1;
256 len = nr = 0;
257 push_arg("grep");
258 if (opt->fixed)
259 push_arg("-F");
260 if (opt->linenum)
261 push_arg("-n");
262 if (!opt->pathname)
263 push_arg("-h");
264 if (opt->regflags & REG_EXTENDED)
265 push_arg("-E");
266 if (opt->regflags & REG_ICASE)
267 push_arg("-i");
268 if (opt->word_regexp)
269 push_arg("-w");
270 if (opt->name_only)
271 push_arg("-l");
272 if (opt->unmatch_name_only)
273 push_arg("-L");
274 if (opt->count)
275 push_arg("-c");
276 if (opt->post_context || opt->pre_context) {
277 if (opt->post_context != opt->pre_context) {
278 if (opt->pre_context) {
279 push_arg("-B");
280 len += snprintf(argptr, sizeof(randarg)-len,
281 "%u", opt->pre_context) + 1;
282 if (sizeof(randarg) <= len)
283 die("maximum length of args exceeded");
284 push_arg(argptr);
285 argptr += len;
287 if (opt->post_context) {
288 push_arg("-A");
289 len += snprintf(argptr, sizeof(randarg)-len,
290 "%u", opt->post_context) + 1;
291 if (sizeof(randarg) <= len)
292 die("maximum length of args exceeded");
293 push_arg(argptr);
294 argptr += len;
297 else {
298 push_arg("-C");
299 len += snprintf(argptr, sizeof(randarg)-len,
300 "%u", opt->post_context) + 1;
301 if (sizeof(randarg) <= len)
302 die("maximum length of args exceeded");
303 push_arg(argptr);
304 argptr += len;
307 for (p = opt->pattern_list; p; p = p->next) {
308 push_arg("-e");
309 push_arg(p->pattern);
312 hit = 0;
313 argc = nr;
314 for (i = 0; i < active_nr; i++) {
315 struct cache_entry *ce = active_cache[i];
316 char *name;
317 int kept;
318 if (!S_ISREG(ce->ce_mode))
319 continue;
320 if (!pathspec_matches(paths, ce->name))
321 continue;
322 name = ce->name;
323 if (name[0] == '-') {
324 int len = ce_namelen(ce);
325 name = xmalloc(len + 3);
326 memcpy(name, "./", 2);
327 memcpy(name + 2, ce->name, len + 1);
329 argv[argc++] = name;
330 if (MAXARGS <= argc) {
331 status = flush_grep(opt, argc, nr, argv, &kept);
332 if (0 < status)
333 hit = 1;
334 argc = nr + kept;
336 if (ce_stage(ce)) {
337 do {
338 i++;
339 } while (i < active_nr &&
340 !strcmp(ce->name, active_cache[i]->name));
341 i--; /* compensate for loop control */
344 if (argc > nr) {
345 status = flush_grep(opt, argc, nr, argv, NULL);
346 if (0 < status)
347 hit = 1;
349 return hit;
351 #endif
353 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
355 int hit = 0;
356 int nr;
357 read_cache();
359 #if !NO_EXTERNAL_GREP
361 * Use the external "grep" command for the case where
362 * we grep through the checked-out files. It tends to
363 * be a lot more optimized
365 if (!cached) {
366 hit = external_grep(opt, paths, cached);
367 if (hit >= 0)
368 return hit;
370 #endif
372 for (nr = 0; nr < active_nr; nr++) {
373 struct cache_entry *ce = active_cache[nr];
374 if (!S_ISREG(ce->ce_mode))
375 continue;
376 if (!pathspec_matches(paths, ce->name))
377 continue;
378 if (cached) {
379 if (ce_stage(ce))
380 continue;
381 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
383 else
384 hit |= grep_file(opt, ce->name);
385 if (ce_stage(ce)) {
386 do {
387 nr++;
388 } while (nr < active_nr &&
389 !strcmp(ce->name, active_cache[nr]->name));
390 nr--; /* compensate for loop control */
393 free_grep_patterns(opt);
394 return hit;
397 static int grep_tree(struct grep_opt *opt, const char **paths,
398 struct tree_desc *tree,
399 const char *tree_name, const char *base)
401 int len;
402 int hit = 0;
403 struct name_entry entry;
404 char *down;
405 int tn_len = strlen(tree_name);
406 char *path_buf = xmalloc(PATH_MAX + tn_len + 100);
408 if (tn_len) {
409 tn_len = sprintf(path_buf, "%s:", tree_name);
410 down = path_buf + tn_len;
411 strcat(down, base);
413 else {
414 down = path_buf;
415 strcpy(down, base);
417 len = strlen(path_buf);
419 while (tree_entry(tree, &entry)) {
420 strcpy(path_buf + len, entry.path);
422 if (S_ISDIR(entry.mode))
423 /* Match "abc/" against pathspec to
424 * decide if we want to descend into "abc"
425 * directory.
427 strcpy(path_buf + len + tree_entry_len(entry.path, entry.sha1), "/");
429 if (!pathspec_matches(paths, down))
431 else if (S_ISREG(entry.mode))
432 hit |= grep_sha1(opt, entry.sha1, path_buf, tn_len);
433 else if (S_ISDIR(entry.mode)) {
434 enum object_type type;
435 struct tree_desc sub;
436 void *data;
437 unsigned long size;
439 data = read_sha1_file(entry.sha1, &type, &size);
440 if (!data)
441 die("unable to read tree (%s)",
442 sha1_to_hex(entry.sha1));
443 init_tree_desc(&sub, data, size);
444 hit |= grep_tree(opt, paths, &sub, tree_name, down);
445 free(data);
448 return hit;
451 static int grep_object(struct grep_opt *opt, const char **paths,
452 struct object *obj, const char *name)
454 if (obj->type == OBJ_BLOB)
455 return grep_sha1(opt, obj->sha1, name, 0);
456 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
457 struct tree_desc tree;
458 void *data;
459 unsigned long size;
460 int hit;
461 data = read_object_with_reference(obj->sha1, tree_type,
462 &size, NULL);
463 if (!data)
464 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
465 init_tree_desc(&tree, data, size);
466 hit = grep_tree(opt, paths, &tree, name, "");
467 free(data);
468 return hit;
470 die("unable to grep from object of type %s", typename(obj->type));
473 static const char builtin_grep_usage[] =
474 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
476 static const char emsg_invalid_context_len[] =
477 "%s: invalid context length argument";
478 static const char emsg_missing_context_len[] =
479 "missing context length argument";
480 static const char emsg_missing_argument[] =
481 "option requires an argument -%s";
483 int cmd_grep(int argc, const char **argv, const char *prefix)
485 int hit = 0;
486 int cached = 0;
487 int seen_dashdash = 0;
488 struct grep_opt opt;
489 struct object_array list = { 0, 0, NULL };
490 const char **paths = NULL;
491 int i;
493 memset(&opt, 0, sizeof(opt));
494 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
495 opt.relative = 1;
496 opt.pathname = 1;
497 opt.pattern_tail = &opt.pattern_list;
498 opt.regflags = REG_NEWLINE;
501 * If there is no -- then the paths must exist in the working
502 * tree. If there is no explicit pattern specified with -e or
503 * -f, we take the first unrecognized non option to be the
504 * pattern, but then what follows it must be zero or more
505 * valid refs up to the -- (if exists), and then existing
506 * paths. If there is an explicit pattern, then the first
507 * unrecognized non option is the beginning of the refs list
508 * that continues up to the -- (if exists), and then paths.
511 while (1 < argc) {
512 const char *arg = argv[1];
513 argc--; argv++;
514 if (!strcmp("--cached", arg)) {
515 cached = 1;
516 continue;
518 if (!strcmp("-a", arg) ||
519 !strcmp("--text", arg)) {
520 opt.binary = GREP_BINARY_TEXT;
521 continue;
523 if (!strcmp("-i", arg) ||
524 !strcmp("--ignore-case", arg)) {
525 opt.regflags |= REG_ICASE;
526 continue;
528 if (!strcmp("-I", arg)) {
529 opt.binary = GREP_BINARY_NOMATCH;
530 continue;
532 if (!strcmp("-v", arg) ||
533 !strcmp("--invert-match", arg)) {
534 opt.invert = 1;
535 continue;
537 if (!strcmp("-E", arg) ||
538 !strcmp("--extended-regexp", arg)) {
539 opt.regflags |= REG_EXTENDED;
540 continue;
542 if (!strcmp("-F", arg) ||
543 !strcmp("--fixed-strings", arg)) {
544 opt.fixed = 1;
545 continue;
547 if (!strcmp("-G", arg) ||
548 !strcmp("--basic-regexp", arg)) {
549 opt.regflags &= ~REG_EXTENDED;
550 continue;
552 if (!strcmp("-n", arg)) {
553 opt.linenum = 1;
554 continue;
556 if (!strcmp("-h", arg)) {
557 opt.pathname = 0;
558 continue;
560 if (!strcmp("-H", arg)) {
561 opt.pathname = 1;
562 continue;
564 if (!strcmp("-l", arg) ||
565 !strcmp("--name-only", arg) ||
566 !strcmp("--files-with-matches", arg)) {
567 opt.name_only = 1;
568 continue;
570 if (!strcmp("-L", arg) ||
571 !strcmp("--files-without-match", arg)) {
572 opt.unmatch_name_only = 1;
573 continue;
575 if (!strcmp("-c", arg) ||
576 !strcmp("--count", arg)) {
577 opt.count = 1;
578 continue;
580 if (!strcmp("-w", arg) ||
581 !strcmp("--word-regexp", arg)) {
582 opt.word_regexp = 1;
583 continue;
585 if (!prefixcmp(arg, "-A") ||
586 !prefixcmp(arg, "-B") ||
587 !prefixcmp(arg, "-C") ||
588 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
589 unsigned num;
590 const char *scan;
591 switch (arg[1]) {
592 case 'A': case 'B': case 'C':
593 if (!arg[2]) {
594 if (argc <= 1)
595 die(emsg_missing_context_len);
596 scan = *++argv;
597 argc--;
599 else
600 scan = arg + 2;
601 break;
602 default:
603 scan = arg + 1;
604 break;
606 if (strtoul_ui(scan, 10, &num))
607 die(emsg_invalid_context_len, scan);
608 switch (arg[1]) {
609 case 'A':
610 opt.post_context = num;
611 break;
612 default:
613 case 'C':
614 opt.post_context = num;
615 case 'B':
616 opt.pre_context = num;
617 break;
619 continue;
621 if (!strcmp("-f", arg)) {
622 FILE *patterns;
623 int lno = 0;
624 char buf[1024];
625 if (argc <= 1)
626 die(emsg_missing_argument, arg);
627 patterns = fopen(argv[1], "r");
628 if (!patterns)
629 die("'%s': %s", argv[1], strerror(errno));
630 while (fgets(buf, sizeof(buf), patterns)) {
631 int len = strlen(buf);
632 if (len && buf[len-1] == '\n')
633 buf[len-1] = 0;
634 /* ignore empty line like grep does */
635 if (!buf[0])
636 continue;
637 append_grep_pattern(&opt, xstrdup(buf),
638 argv[1], ++lno,
639 GREP_PATTERN);
641 fclose(patterns);
642 argv++;
643 argc--;
644 continue;
646 if (!strcmp("--not", arg)) {
647 append_grep_pattern(&opt, arg, "command line", 0,
648 GREP_NOT);
649 continue;
651 if (!strcmp("--and", arg)) {
652 append_grep_pattern(&opt, arg, "command line", 0,
653 GREP_AND);
654 continue;
656 if (!strcmp("--or", arg))
657 continue; /* no-op */
658 if (!strcmp("(", arg)) {
659 append_grep_pattern(&opt, arg, "command line", 0,
660 GREP_OPEN_PAREN);
661 continue;
663 if (!strcmp(")", arg)) {
664 append_grep_pattern(&opt, arg, "command line", 0,
665 GREP_CLOSE_PAREN);
666 continue;
668 if (!strcmp("--all-match", arg)) {
669 opt.all_match = 1;
670 continue;
672 if (!strcmp("-e", arg)) {
673 if (1 < argc) {
674 append_grep_pattern(&opt, argv[1],
675 "-e option", 0,
676 GREP_PATTERN);
677 argv++;
678 argc--;
679 continue;
681 die(emsg_missing_argument, arg);
683 if (!strcmp("--full-name", arg)) {
684 opt.relative = 0;
685 continue;
687 if (!strcmp("--", arg)) {
688 /* later processing wants to have this at argv[1] */
689 argv--;
690 argc++;
691 break;
693 if (*arg == '-')
694 usage(builtin_grep_usage);
696 /* First unrecognized non-option token */
697 if (!opt.pattern_list) {
698 append_grep_pattern(&opt, arg, "command line", 0,
699 GREP_PATTERN);
700 break;
702 else {
703 /* We are looking at the first path or rev;
704 * it is found at argv[1] after leaving the
705 * loop.
707 argc++; argv--;
708 break;
712 if (!opt.pattern_list)
713 die("no pattern given.");
714 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
715 die("cannot mix --fixed-strings and regexp");
716 compile_grep_patterns(&opt);
718 /* Check revs and then paths */
719 for (i = 1; i < argc; i++) {
720 const char *arg = argv[i];
721 unsigned char sha1[20];
722 /* Is it a rev? */
723 if (!get_sha1(arg, sha1)) {
724 struct object *object = parse_object(sha1);
725 if (!object)
726 die("bad object %s", arg);
727 add_object_array(object, arg, &list);
728 continue;
730 if (!strcmp(arg, "--")) {
731 i++;
732 seen_dashdash = 1;
734 break;
737 /* The rest are paths */
738 if (!seen_dashdash) {
739 int j;
740 for (j = i; j < argc; j++)
741 verify_filename(prefix, argv[j]);
744 if (i < argc) {
745 paths = get_pathspec(prefix, argv + i);
746 if (opt.prefix_length && opt.relative) {
747 /* Make sure we do not get outside of paths */
748 for (i = 0; paths[i]; i++)
749 if (strncmp(prefix, paths[i], opt.prefix_length))
750 die("git-grep: cannot generate relative filenames containing '..'");
753 else if (prefix) {
754 paths = xcalloc(2, sizeof(const char *));
755 paths[0] = prefix;
756 paths[1] = NULL;
759 if (!list.nr)
760 return !grep_cache(&opt, paths, cached);
762 if (cached)
763 die("both --cached and trees are given.");
765 for (i = 0; i < list.nr; i++) {
766 struct object *real_obj;
767 real_obj = deref_tag(list.objects[i].item, NULL, 0);
768 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
769 hit = 1;
771 free_grep_patterns(&opt);
772 return !hit;