1/*
2 * Builtin "git grep"
3 *
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 "parse-options.h"
14#include "userdiff.h"
15#include "grep.h"
16#include "quote.h"
17
18#ifndef NO_EXTERNAL_GREP
19#ifdef __unix__
20#define NO_EXTERNAL_GREP 0
21#else
22#define NO_EXTERNAL_GREP 1
23#endif
24#endif
25
26static char const * const grep_usage[] = {
27 "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
28 NULL
29};
30
31static int grep_config(const char *var, const char *value, void *cb)
32{
33 struct grep_opt *opt = cb;
34
35 switch (userdiff_config(var, value)) {
36 case 0: break;
37 case -1: return -1;
38 default: return 0;
39 }
40
41 if (!strcmp(var, "color.grep")) {
42 opt->color = git_config_colorbool(var, value, -1);
43 return 0;
44 }
45 if (!strcmp(var, "color.grep.external"))
46 return git_config_string(&(opt->color_external), var, value);
47 if (!strcmp(var, "color.grep.match")) {
48 if (!value)
49 return config_error_nonbool(var);
50 color_parse(value, var, opt->color_match);
51 return 0;
52 }
53 return git_color_default_config(var, value, cb);
54}
55
56/*
57 * Return non-zero if max_depth is negative or path has no more then max_depth
58 * slashes.
59 */
60static int accept_subdir(const char *path, int max_depth)
61{
62 if (max_depth < 0)
63 return 1;
64
65 while ((path = strchr(path, '/')) != NULL) {
66 max_depth--;
67 if (max_depth < 0)
68 return 0;
69 path++;
70 }
71 return 1;
72}
73
74/*
75 * Return non-zero if name is a subdirectory of match and is not too deep.
76 */
77static int is_subdir(const char *name, int namelen,
78 const char *match, int matchlen, int max_depth)
79{
80 if (matchlen > namelen || strncmp(name, match, matchlen))
81 return 0;
82
83 if (name[matchlen] == '\0') /* exact match */
84 return 1;
85
86 if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
87 return accept_subdir(name + matchlen + 1, max_depth);
88
89 return 0;
90}
91
92/*
93 * git grep pathspecs are somewhat different from diff-tree pathspecs;
94 * pathname wildcards are allowed.
95 */
96static int pathspec_matches(const char **paths, const char *name, int max_depth)
97{
98 int namelen, i;
99 if (!paths || !*paths)
100 return accept_subdir(name, max_depth);
101 namelen = strlen(name);
102 for (i = 0; paths[i]; i++) {
103 const char *match = paths[i];
104 int matchlen = strlen(match);
105 const char *cp, *meta;
106
107 if (is_subdir(name, namelen, match, matchlen, max_depth))
108 return 1;
109 if (!fnmatch(match, name, 0))
110 return 1;
111 if (name[namelen-1] != '/')
112 continue;
113
114 /* We are being asked if the directory ("name") is worth
115 * descending into.
116 *
117 * Find the longest leading directory name that does
118 * not have metacharacter in the pathspec; the name
119 * we are looking at must overlap with that directory.
120 */
121 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
122 char ch = *cp;
123 if (ch == '*' || ch == '[' || ch == '?') {
124 meta = cp;
125 break;
126 }
127 }
128 if (!meta)
129 meta = cp; /* fully literal */
130
131 if (namelen <= meta - match) {
132 /* Looking at "Documentation/" and
133 * the pattern says "Documentation/howto/", or
134 * "Documentation/diff*.txt". The name we
135 * have should match prefix.
136 */
137 if (!memcmp(match, name, namelen))
138 return 1;
139 continue;
140 }
141
142 if (meta - match < namelen) {
143 /* Looking at "Documentation/howto/" and
144 * the pattern says "Documentation/h*";
145 * match up to "Do.../h"; this avoids descending
146 * into "Documentation/technical/".
147 */
148 if (!memcmp(match, name, meta - match))
149 return 1;
150 continue;
151 }
152 }
153 return 0;
154}
155
156static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
157{
158 unsigned long size;
159 char *data;
160 enum object_type type;
161 int hit;
162 struct strbuf pathbuf = STRBUF_INIT;
163
164 data = read_sha1_file(sha1, &type, &size);
165 if (!data) {
166 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
167 return 0;
168 }
169 if (opt->relative && opt->prefix_length) {
170 quote_path_relative(name + tree_name_len, -1, &pathbuf, opt->prefix);
171 strbuf_insert(&pathbuf, 0, name, tree_name_len);
172 name = pathbuf.buf;
173 }
174 hit = grep_buffer(opt, name, data, size);
175 strbuf_release(&pathbuf);
176 free(data);
177 return hit;
178}
179
180static int grep_file(struct grep_opt *opt, const char *filename)
181{
182 struct stat st;
183 int i;
184 char *data;
185 size_t sz;
186 struct strbuf buf = STRBUF_INIT;
187
188 if (lstat(filename, &st) < 0) {
189 err_ret:
190 if (errno != ENOENT)
191 error("'%s': %s", filename, strerror(errno));
192 return 0;
193 }
194 if (!S_ISREG(st.st_mode))
195 return 0;
196 sz = xsize_t(st.st_size);
197 i = open(filename, O_RDONLY);
198 if (i < 0)
199 goto err_ret;
200 data = xmalloc(sz + 1);
201 if (st.st_size != read_in_full(i, data, sz)) {
202 error("'%s': short read %s", filename, strerror(errno));
203 close(i);
204 free(data);
205 return 0;
206 }
207 close(i);
208 data[sz] = 0;
209 if (opt->relative && opt->prefix_length)
210 filename = quote_path_relative(filename, -1, &buf, opt->prefix);
211 i = grep_buffer(opt, filename, data, sz);
212 strbuf_release(&buf);
213 free(data);
214 return i;
215}
216
217#if !NO_EXTERNAL_GREP
218static int exec_grep(int argc, const char **argv)
219{
220 pid_t pid;
221 int status;
222
223 argv[argc] = NULL;
224 pid = fork();
225 if (pid < 0)
226 return pid;
227 if (!pid) {
228 execvp("grep", (char **) argv);
229 exit(255);
230 }
231 while (waitpid(pid, &status, 0) < 0) {
232 if (errno == EINTR)
233 continue;
234 return -1;
235 }
236 if (WIFEXITED(status)) {
237 if (!WEXITSTATUS(status))
238 return 1;
239 return 0;
240 }
241 return -1;
242}
243
244#define MAXARGS 1000
245#define ARGBUF 4096
246#define push_arg(a) do { \
247 if (nr < MAXARGS) argv[nr++] = (a); \
248 else die("maximum number of args exceeded"); \
249 } while (0)
250
251/*
252 * If you send a singleton filename to grep, it does not give
253 * the name of the file. GNU grep has "-H" but we would want
254 * that behaviour in a portable way.
255 *
256 * So we keep two pathnames in argv buffer unsent to grep in
257 * the main loop if we need to do more than one grep.
258 */
259static int flush_grep(struct grep_opt *opt,
260 int argc, int arg0, const char **argv, int *kept)
261{
262 int status;
263 int count = argc - arg0;
264 const char *kept_0 = NULL;
265
266 if (count <= 2) {
267 /*
268 * Because we keep at least 2 paths in the call from
269 * the main loop (i.e. kept != NULL), and MAXARGS is
270 * far greater than 2, this usually is a call to
271 * conclude the grep. However, the user could attempt
272 * to overflow the argv buffer by giving too many
273 * options to leave very small number of real
274 * arguments even for the call in the main loop.
275 */
276 if (kept)
277 die("insanely many options to grep");
278
279 /*
280 * If we have two or more paths, we do not have to do
281 * anything special, but we need to push /dev/null to
282 * get "-H" behaviour of GNU grep portably but when we
283 * are not doing "-l" nor "-L" nor "-c".
284 */
285 if (count == 1 &&
286 !opt->name_only &&
287 !opt->unmatch_name_only &&
288 !opt->count) {
289 argv[argc++] = "/dev/null";
290 argv[argc] = NULL;
291 }
292 }
293
294 else if (kept) {
295 /*
296 * Called because we found many paths and haven't finished
297 * iterating over the cache yet. We keep two paths
298 * for the concluding call. argv[argc-2] and argv[argc-1]
299 * has the last two paths, so save the first one away,
300 * replace it with NULL while sending the list to grep,
301 * and recover them after we are done.
302 */
303 *kept = 2;
304 kept_0 = argv[argc-2];
305 argv[argc-2] = NULL;
306 argc -= 2;
307 }
308
309 if (opt->pre_context || opt->post_context) {
310 /*
311 * grep handles hunk marks between files, but we need to
312 * do that ourselves between multiple calls.
313 */
314 if (opt->show_hunk_mark)
315 write_or_die(1, "--\n", 3);
316 else
317 opt->show_hunk_mark = 1;
318 }
319
320 status = exec_grep(argc, argv);
321
322 if (kept_0) {
323 /*
324 * Then recover them. Now the last arg is beyond the
325 * terminating NULL which is at argc, and the second
326 * from the last is what we saved away in kept_0
327 */
328 argv[arg0++] = kept_0;
329 argv[arg0] = argv[argc+1];
330 }
331 return status;
332}
333
334static void grep_add_color(struct strbuf *sb, const char *escape_seq)
335{
336 size_t orig_len = sb->len;
337
338 while (*escape_seq) {
339 if (*escape_seq == 'm')
340 strbuf_addch(sb, ';');
341 else if (*escape_seq != '\033' && *escape_seq != '[')
342 strbuf_addch(sb, *escape_seq);
343 escape_seq++;
344 }
345 if (sb->len > orig_len && sb->buf[sb->len - 1] == ';')
346 strbuf_setlen(sb, sb->len - 1);
347}
348
349static int external_grep(struct grep_opt *opt, const char **paths, int cached)
350{
351 int i, nr, argc, hit, len, status;
352 const char *argv[MAXARGS+1];
353 char randarg[ARGBUF];
354 char *argptr = randarg;
355 struct grep_pat *p;
356
357 if (opt->extended || (opt->relative && opt->prefix_length))
358 return -1;
359 len = nr = 0;
360 push_arg("grep");
361 if (opt->fixed)
362 push_arg("-F");
363 if (opt->linenum)
364 push_arg("-n");
365 if (!opt->pathname)
366 push_arg("-h");
367 if (opt->regflags & REG_EXTENDED)
368 push_arg("-E");
369 if (opt->ignore_case)
370 push_arg("-i");
371 if (opt->binary == GREP_BINARY_NOMATCH)
372 push_arg("-I");
373 if (opt->word_regexp)
374 push_arg("-w");
375 if (opt->name_only)
376 push_arg("-l");
377 if (opt->unmatch_name_only)
378 push_arg("-L");
379 if (opt->null_following_name)
380 /* in GNU grep git's "-z" translates to "-Z" */
381 push_arg("-Z");
382 if (opt->count)
383 push_arg("-c");
384 if (opt->post_context || opt->pre_context) {
385 if (opt->post_context != opt->pre_context) {
386 if (opt->pre_context) {
387 push_arg("-B");
388 len += snprintf(argptr, sizeof(randarg)-len,
389 "%u", opt->pre_context) + 1;
390 if (sizeof(randarg) <= len)
391 die("maximum length of args exceeded");
392 push_arg(argptr);
393 argptr += len;
394 }
395 if (opt->post_context) {
396 push_arg("-A");
397 len += snprintf(argptr, sizeof(randarg)-len,
398 "%u", opt->post_context) + 1;
399 if (sizeof(randarg) <= len)
400 die("maximum length of args exceeded");
401 push_arg(argptr);
402 argptr += len;
403 }
404 }
405 else {
406 push_arg("-C");
407 len += snprintf(argptr, sizeof(randarg)-len,
408 "%u", opt->post_context) + 1;
409 if (sizeof(randarg) <= len)
410 die("maximum length of args exceeded");
411 push_arg(argptr);
412 argptr += len;
413 }
414 }
415 for (p = opt->pattern_list; p; p = p->next) {
416 push_arg("-e");
417 push_arg(p->pattern);
418 }
419 if (opt->color) {
420 struct strbuf sb = STRBUF_INIT;
421
422 grep_add_color(&sb, opt->color_match);
423 setenv("GREP_COLOR", sb.buf, 1);
424
425 strbuf_reset(&sb);
426 strbuf_addstr(&sb, "mt=");
427 grep_add_color(&sb, opt->color_match);
428 strbuf_addstr(&sb, ":sl=:cx=:fn=:ln=:bn=:se=");
429 setenv("GREP_COLORS", sb.buf, 1);
430
431 strbuf_release(&sb);
432
433 if (opt->color_external && strlen(opt->color_external) > 0)
434 push_arg(opt->color_external);
435 } else {
436 unsetenv("GREP_COLOR");
437 unsetenv("GREP_COLORS");
438 }
439 unsetenv("GREP_OPTIONS");
440
441 hit = 0;
442 argc = nr;
443 for (i = 0; i < active_nr; i++) {
444 struct cache_entry *ce = active_cache[i];
445 char *name;
446 int kept;
447 if (!S_ISREG(ce->ce_mode))
448 continue;
449 if (!pathspec_matches(paths, ce->name, opt->max_depth))
450 continue;
451 name = ce->name;
452 if (name[0] == '-') {
453 int len = ce_namelen(ce);
454 name = xmalloc(len + 3);
455 memcpy(name, "./", 2);
456 memcpy(name + 2, ce->name, len + 1);
457 }
458 argv[argc++] = name;
459 if (MAXARGS <= argc) {
460 status = flush_grep(opt, argc, nr, argv, &kept);
461 if (0 < status)
462 hit = 1;
463 argc = nr + kept;
464 }
465 if (ce_stage(ce)) {
466 do {
467 i++;
468 } while (i < active_nr &&
469 !strcmp(ce->name, active_cache[i]->name));
470 i--; /* compensate for loop control */
471 }
472 }
473 if (argc > nr) {
474 status = flush_grep(opt, argc, nr, argv, NULL);
475 if (0 < status)
476 hit = 1;
477 }
478 return hit;
479}
480#endif
481
482static int grep_cache(struct grep_opt *opt, const char **paths, int cached,
483 int external_grep_allowed)
484{
485 int hit = 0;
486 int nr;
487 read_cache();
488
489#if !NO_EXTERNAL_GREP
490 /*
491 * Use the external "grep" command for the case where
492 * we grep through the checked-out files. It tends to
493 * be a lot more optimized
494 */
495 if (!cached && external_grep_allowed) {
496 hit = external_grep(opt, paths, cached);
497 if (hit >= 0)
498 return hit;
499 hit = 0;
500 }
501#endif
502
503 for (nr = 0; nr < active_nr; nr++) {
504 struct cache_entry *ce = active_cache[nr];
505 if (!S_ISREG(ce->ce_mode))
506 continue;
507 if (!pathspec_matches(paths, ce->name, opt->max_depth))
508 continue;
509 /*
510 * If CE_VALID is on, we assume worktree file and its cache entry
511 * are identical, even if worktree file has been modified, so use
512 * cache version instead
513 */
514 if (cached || (ce->ce_flags & CE_VALID)) {
515 if (ce_stage(ce))
516 continue;
517 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
518 }
519 else
520 hit |= grep_file(opt, ce->name);
521 if (ce_stage(ce)) {
522 do {
523 nr++;
524 } while (nr < active_nr &&
525 !strcmp(ce->name, active_cache[nr]->name));
526 nr--; /* compensate for loop control */
527 }
528 }
529 free_grep_patterns(opt);
530 return hit;
531}
532
533static int grep_tree(struct grep_opt *opt, const char **paths,
534 struct tree_desc *tree,
535 const char *tree_name, const char *base)
536{
537 int len;
538 int hit = 0;
539 struct name_entry entry;
540 char *down;
541 int tn_len = strlen(tree_name);
542 struct strbuf pathbuf;
543
544 strbuf_init(&pathbuf, PATH_MAX + tn_len);
545
546 if (tn_len) {
547 strbuf_add(&pathbuf, tree_name, tn_len);
548 strbuf_addch(&pathbuf, ':');
549 tn_len = pathbuf.len;
550 }
551 strbuf_addstr(&pathbuf, base);
552 len = pathbuf.len;
553
554 while (tree_entry(tree, &entry)) {
555 int te_len = tree_entry_len(entry.path, entry.sha1);
556 pathbuf.len = len;
557 strbuf_add(&pathbuf, entry.path, te_len);
558
559 if (S_ISDIR(entry.mode))
560 /* Match "abc/" against pathspec to
561 * decide if we want to descend into "abc"
562 * directory.
563 */
564 strbuf_addch(&pathbuf, '/');
565
566 down = pathbuf.buf + tn_len;
567 if (!pathspec_matches(paths, down, opt->max_depth))
568 ;
569 else if (S_ISREG(entry.mode))
570 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
571 else if (S_ISDIR(entry.mode)) {
572 enum object_type type;
573 struct tree_desc sub;
574 void *data;
575 unsigned long size;
576
577 data = read_sha1_file(entry.sha1, &type, &size);
578 if (!data)
579 die("unable to read tree (%s)",
580 sha1_to_hex(entry.sha1));
581 init_tree_desc(&sub, data, size);
582 hit |= grep_tree(opt, paths, &sub, tree_name, down);
583 free(data);
584 }
585 }
586 strbuf_release(&pathbuf);
587 return hit;
588}
589
590static int grep_object(struct grep_opt *opt, const char **paths,
591 struct object *obj, const char *name)
592{
593 if (obj->type == OBJ_BLOB)
594 return grep_sha1(opt, obj->sha1, name, 0);
595 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
596 struct tree_desc tree;
597 void *data;
598 unsigned long size;
599 int hit;
600 data = read_object_with_reference(obj->sha1, tree_type,
601 &size, NULL);
602 if (!data)
603 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
604 init_tree_desc(&tree, data, size);
605 hit = grep_tree(opt, paths, &tree, name, "");
606 free(data);
607 return hit;
608 }
609 die("unable to grep from object of type %s", typename(obj->type));
610}
611
612static int context_callback(const struct option *opt, const char *arg,
613 int unset)
614{
615 struct grep_opt *grep_opt = opt->value;
616 int value;
617 const char *endp;
618
619 if (unset) {
620 grep_opt->pre_context = grep_opt->post_context = 0;
621 return 0;
622 }
623 value = strtol(arg, (char **)&endp, 10);
624 if (*endp) {
625 return error("switch `%c' expects a numerical value",
626 opt->short_name);
627 }
628 grep_opt->pre_context = grep_opt->post_context = value;
629 return 0;
630}
631
632static int file_callback(const struct option *opt, const char *arg, int unset)
633{
634 struct grep_opt *grep_opt = opt->value;
635 FILE *patterns;
636 int lno = 0;
637 struct strbuf sb = STRBUF_INIT;
638
639 patterns = fopen(arg, "r");
640 if (!patterns)
641 die_errno("cannot open '%s'", arg);
642 while (strbuf_getline(&sb, patterns, '\n') == 0) {
643 /* ignore empty line like grep does */
644 if (sb.len == 0)
645 continue;
646 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
647 ++lno, GREP_PATTERN);
648 }
649 fclose(patterns);
650 strbuf_release(&sb);
651 return 0;
652}
653
654static int not_callback(const struct option *opt, const char *arg, int unset)
655{
656 struct grep_opt *grep_opt = opt->value;
657 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
658 return 0;
659}
660
661static int and_callback(const struct option *opt, const char *arg, int unset)
662{
663 struct grep_opt *grep_opt = opt->value;
664 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
665 return 0;
666}
667
668static int open_callback(const struct option *opt, const char *arg, int unset)
669{
670 struct grep_opt *grep_opt = opt->value;
671 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
672 return 0;
673}
674
675static int close_callback(const struct option *opt, const char *arg, int unset)
676{
677 struct grep_opt *grep_opt = opt->value;
678 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
679 return 0;
680}
681
682static int pattern_callback(const struct option *opt, const char *arg,
683 int unset)
684{
685 struct grep_opt *grep_opt = opt->value;
686 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
687 return 0;
688}
689
690static int help_callback(const struct option *opt, const char *arg, int unset)
691{
692 return -1;
693}
694
695int cmd_grep(int argc, const char **argv, const char *prefix)
696{
697 int hit = 0;
698 int cached = 0;
699 int external_grep_allowed = 1;
700 int seen_dashdash = 0;
701 struct grep_opt opt;
702 struct object_array list = { 0, 0, NULL };
703 const char **paths = NULL;
704 int i;
705 int dummy;
706 struct option options[] = {
707 OPT_BOOLEAN(0, "cached", &cached,
708 "search in index instead of in the work tree"),
709 OPT_GROUP(""),
710 OPT_BOOLEAN('v', "invert-match", &opt.invert,
711 "show non-matching lines"),
712 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
713 "case insensitive matching"),
714 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
715 "match patterns only at word boundaries"),
716 OPT_SET_INT('a', "text", &opt.binary,
717 "process binary files as text", GREP_BINARY_TEXT),
718 OPT_SET_INT('I', NULL, &opt.binary,
719 "don't match patterns in binary files",
720 GREP_BINARY_NOMATCH),
721 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
722 "descend at most <depth> levels", PARSE_OPT_NONEG,
723 NULL, 1 },
724 OPT_GROUP(""),
725 OPT_BIT('E', "extended-regexp", &opt.regflags,
726 "use extended POSIX regular expressions", REG_EXTENDED),
727 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
728 "use basic POSIX regular expressions (default)",
729 REG_EXTENDED),
730 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
731 "interpret patterns as fixed strings"),
732 OPT_GROUP(""),
733 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
734 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
735 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
736 OPT_NEGBIT(0, "full-name", &opt.relative,
737 "show filenames relative to top directory", 1),
738 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
739 "show only filenames instead of matching lines"),
740 OPT_BOOLEAN(0, "name-only", &opt.name_only,
741 "synonym for --files-with-matches"),
742 OPT_BOOLEAN('L', "files-without-match",
743 &opt.unmatch_name_only,
744 "show only the names of files without match"),
745 OPT_BOOLEAN('z', "null", &opt.null_following_name,
746 "print NUL after filenames"),
747 OPT_BOOLEAN('c', "count", &opt.count,
748 "show the number of matches instead of matching lines"),
749 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
750 OPT_GROUP(""),
751 OPT_CALLBACK('C', NULL, &opt, "n",
752 "show <n> context lines before and after matches",
753 context_callback),
754 OPT_INTEGER('B', NULL, &opt.pre_context,
755 "show <n> context lines before matches"),
756 OPT_INTEGER('A', NULL, &opt.post_context,
757 "show <n> context lines after matches"),
758 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
759 context_callback),
760 OPT_BOOLEAN('p', "show-function", &opt.funcname,
761 "show a line with the function name before matches"),
762 OPT_GROUP(""),
763 OPT_CALLBACK('f', NULL, &opt, "file",
764 "read patterns from file", file_callback),
765 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
766 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
767 { OPTION_CALLBACK, 0, "and", &opt, NULL,
768 "combine patterns specified with -e",
769 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
770 OPT_BOOLEAN(0, "or", &dummy, ""),
771 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
772 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
773 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
774 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
775 open_callback },
776 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
777 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
778 close_callback },
779 OPT_BOOLEAN(0, "all-match", &opt.all_match,
780 "show only matches from files that match all patterns"),
781 OPT_GROUP(""),
782#if NO_EXTERNAL_GREP
783 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
784 "allow calling of grep(1) (ignored by this build)"),
785#else
786 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
787 "allow calling of grep(1) (default)"),
788#endif
789 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
790 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
791 OPT_END()
792 };
793
794 /*
795 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
796 * to show usage information and exit.
797 */
798 if (argc == 2 && !strcmp(argv[1], "-h"))
799 usage_with_options(grep_usage, options);
800
801 memset(&opt, 0, sizeof(opt));
802 opt.prefix = prefix;
803 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
804 opt.relative = 1;
805 opt.pathname = 1;
806 opt.pattern_tail = &opt.pattern_list;
807 opt.regflags = REG_NEWLINE;
808 opt.max_depth = -1;
809
810 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
811 opt.color = -1;
812 git_config(grep_config, &opt);
813 if (opt.color == -1)
814 opt.color = git_use_color_default;
815
816 /*
817 * If there is no -- then the paths must exist in the working
818 * tree. If there is no explicit pattern specified with -e or
819 * -f, we take the first unrecognized non option to be the
820 * pattern, but then what follows it must be zero or more
821 * valid refs up to the -- (if exists), and then existing
822 * paths. If there is an explicit pattern, then the first
823 * unrecognized non option is the beginning of the refs list
824 * that continues up to the -- (if exists), and then paths.
825 */
826 argc = parse_options(argc, argv, prefix, options, grep_usage,
827 PARSE_OPT_KEEP_DASHDASH |
828 PARSE_OPT_STOP_AT_NON_OPTION |
829 PARSE_OPT_NO_INTERNAL_HELP);
830
831 /* First unrecognized non-option token */
832 if (argc > 0 && !opt.pattern_list) {
833 append_grep_pattern(&opt, argv[0], "command line", 0,
834 GREP_PATTERN);
835 argv++;
836 argc--;
837 }
838
839 if ((opt.color && !opt.color_external) || opt.funcname)
840 external_grep_allowed = 0;
841 if (!opt.pattern_list)
842 die("no pattern given.");
843 if (!opt.fixed && opt.ignore_case)
844 opt.regflags |= REG_ICASE;
845 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
846 die("cannot mix --fixed-strings and regexp");
847 compile_grep_patterns(&opt);
848
849 /* Check revs and then paths */
850 for (i = 0; i < argc; i++) {
851 const char *arg = argv[i];
852 unsigned char sha1[20];
853 /* Is it a rev? */
854 if (!get_sha1(arg, sha1)) {
855 struct object *object = parse_object(sha1);
856 if (!object)
857 die("bad object %s", arg);
858 add_object_array(object, arg, &list);
859 continue;
860 }
861 if (!strcmp(arg, "--")) {
862 i++;
863 seen_dashdash = 1;
864 }
865 break;
866 }
867
868 /* The rest are paths */
869 if (!seen_dashdash) {
870 int j;
871 for (j = i; j < argc; j++)
872 verify_filename(prefix, argv[j]);
873 }
874
875 if (i < argc)
876 paths = get_pathspec(prefix, argv + i);
877 else if (prefix) {
878 paths = xcalloc(2, sizeof(const char *));
879 paths[0] = prefix;
880 paths[1] = NULL;
881 }
882
883 if (!list.nr) {
884 if (!cached)
885 setup_work_tree();
886 return !grep_cache(&opt, paths, cached, external_grep_allowed);
887 }
888
889 if (cached)
890 die("both --cached and trees are given.");
891
892 for (i = 0; i < list.nr; i++) {
893 struct object *real_obj;
894 real_obj = deref_tag(list.objects[i].item, NULL, 0);
895 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
896 hit = 1;
897 }
898 free_grep_patterns(&opt);
899 return !hit;
900}