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