Merge branch 'jk/maint-1.6.5-reset-hard' into maint-1.6.5
[git/git-svn.git] / builtin-grep.c
blob63dc31c45c309c7a2a67977e5631cb5334b32ecf
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 "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
31 static int grep_config(const char *var, const char *value, void *cb)
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;
41 if (!strcmp(var, "color.grep")) {
42 opt->color = git_config_colorbool(var, value, -1);
43 return 0;
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;
53 return git_color_default_config(var, value, cb);
57 * Return non-zero if max_depth is negative or path has no more then max_depth
58 * slashes.
60 static int accept_subdir(const char *path, int max_depth)
62 if (max_depth < 0)
63 return 1;
65 while ((path = strchr(path, '/')) != NULL) {
66 max_depth--;
67 if (max_depth < 0)
68 return 0;
69 path++;
71 return 1;
75 * Return non-zero if name is a subdirectory of match and is not too deep.
77 static int is_subdir(const char *name, int namelen,
78 const char *match, int matchlen, int max_depth)
80 if (matchlen > namelen || strncmp(name, match, matchlen))
81 return 0;
83 if (name[matchlen] == '\0') /* exact match */
84 return 1;
86 if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
87 return accept_subdir(name + matchlen + 1, max_depth);
89 return 0;
93 * git grep pathspecs are somewhat different from diff-tree pathspecs;
94 * pathname wildcards are allowed.
96 static int pathspec_matches(const char **paths, const char *name, int max_depth)
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;
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;
114 /* We are being asked if the directory ("name") is worth
115 * descending into.
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.
121 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
122 char ch = *cp;
123 if (ch == '*' || ch == '[' || ch == '?') {
124 meta = cp;
125 break;
128 if (!meta)
129 meta = cp; /* fully literal */
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.
137 if (!memcmp(match, name, namelen))
138 return 1;
139 continue;
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/".
148 if (!memcmp(match, name, meta - match))
149 return 1;
150 continue;
153 return 0;
156 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
158 unsigned long size;
159 char *data;
160 enum object_type type;
161 int hit;
162 struct strbuf pathbuf = STRBUF_INIT;
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;
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;
174 hit = grep_buffer(opt, name, data, size);
175 strbuf_release(&pathbuf);
176 free(data);
177 return hit;
180 static int grep_file(struct grep_opt *opt, const char *filename)
182 struct stat st;
183 int i;
184 char *data;
185 size_t sz;
186 struct strbuf buf = STRBUF_INIT;
188 if (lstat(filename, &st) < 0) {
189 err_ret:
190 if (errno != ENOENT)
191 error("'%s': %s", filename, strerror(errno));
192 return 0;
194 if (!st.st_size)
195 return 0; /* empty file -- no grep hit */
196 if (!S_ISREG(st.st_mode))
197 return 0;
198 sz = xsize_t(st.st_size);
199 i = open(filename, O_RDONLY);
200 if (i < 0)
201 goto err_ret;
202 data = xmalloc(sz + 1);
203 if (st.st_size != read_in_full(i, data, sz)) {
204 error("'%s': short read %s", filename, strerror(errno));
205 close(i);
206 free(data);
207 return 0;
209 close(i);
210 data[sz] = 0;
211 if (opt->relative && opt->prefix_length)
212 filename = quote_path_relative(filename, -1, &buf, opt->prefix);
213 i = grep_buffer(opt, filename, data, sz);
214 strbuf_release(&buf);
215 free(data);
216 return i;
219 #if !NO_EXTERNAL_GREP
220 static int exec_grep(int argc, const char **argv)
222 pid_t pid;
223 int status;
225 argv[argc] = NULL;
226 pid = fork();
227 if (pid < 0)
228 return pid;
229 if (!pid) {
230 execvp("grep", (char **) argv);
231 exit(255);
233 while (waitpid(pid, &status, 0) < 0) {
234 if (errno == EINTR)
235 continue;
236 return -1;
238 if (WIFEXITED(status)) {
239 if (!WEXITSTATUS(status))
240 return 1;
241 return 0;
243 return -1;
246 #define MAXARGS 1000
247 #define ARGBUF 4096
248 #define push_arg(a) do { \
249 if (nr < MAXARGS) argv[nr++] = (a); \
250 else die("maximum number of args exceeded"); \
251 } while (0)
254 * If you send a singleton filename to grep, it does not give
255 * the name of the file. GNU grep has "-H" but we would want
256 * that behaviour in a portable way.
258 * So we keep two pathnames in argv buffer unsent to grep in
259 * the main loop if we need to do more than one grep.
261 static int flush_grep(struct grep_opt *opt,
262 int argc, int arg0, const char **argv, int *kept)
264 int status;
265 int count = argc - arg0;
266 const char *kept_0 = NULL;
268 if (count <= 2) {
270 * Because we keep at least 2 paths in the call from
271 * the main loop (i.e. kept != NULL), and MAXARGS is
272 * far greater than 2, this usually is a call to
273 * conclude the grep. However, the user could attempt
274 * to overflow the argv buffer by giving too many
275 * options to leave very small number of real
276 * arguments even for the call in the main loop.
278 if (kept)
279 die("insanely many options to grep");
282 * If we have two or more paths, we do not have to do
283 * anything special, but we need to push /dev/null to
284 * get "-H" behaviour of GNU grep portably but when we
285 * are not doing "-l" nor "-L" nor "-c".
287 if (count == 1 &&
288 !opt->name_only &&
289 !opt->unmatch_name_only &&
290 !opt->count) {
291 argv[argc++] = "/dev/null";
292 argv[argc] = NULL;
296 else if (kept) {
298 * Called because we found many paths and haven't finished
299 * iterating over the cache yet. We keep two paths
300 * for the concluding call. argv[argc-2] and argv[argc-1]
301 * has the last two paths, so save the first one away,
302 * replace it with NULL while sending the list to grep,
303 * and recover them after we are done.
305 *kept = 2;
306 kept_0 = argv[argc-2];
307 argv[argc-2] = NULL;
308 argc -= 2;
311 if (opt->pre_context || opt->post_context) {
313 * grep handles hunk marks between files, but we need to
314 * do that ourselves between multiple calls.
316 if (opt->show_hunk_mark)
317 write_or_die(1, "--\n", 3);
318 else
319 opt->show_hunk_mark = 1;
322 status = exec_grep(argc, argv);
324 if (kept_0) {
326 * Then recover them. Now the last arg is beyond the
327 * terminating NULL which is at argc, and the second
328 * from the last is what we saved away in kept_0
330 argv[arg0++] = kept_0;
331 argv[arg0] = argv[argc+1];
333 return status;
336 static void grep_add_color(struct strbuf *sb, const char *escape_seq)
338 size_t orig_len = sb->len;
340 while (*escape_seq) {
341 if (*escape_seq == 'm')
342 strbuf_addch(sb, ';');
343 else if (*escape_seq != '\033' && *escape_seq != '[')
344 strbuf_addch(sb, *escape_seq);
345 escape_seq++;
347 if (sb->len > orig_len && sb->buf[sb->len - 1] == ';')
348 strbuf_setlen(sb, sb->len - 1);
351 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
353 int i, nr, argc, hit, len, status;
354 const char *argv[MAXARGS+1];
355 char randarg[ARGBUF];
356 char *argptr = randarg;
357 struct grep_pat *p;
359 if (opt->extended || (opt->relative && opt->prefix_length))
360 return -1;
361 len = nr = 0;
362 push_arg("grep");
363 if (opt->fixed)
364 push_arg("-F");
365 if (opt->linenum)
366 push_arg("-n");
367 if (!opt->pathname)
368 push_arg("-h");
369 if (opt->regflags & REG_EXTENDED)
370 push_arg("-E");
371 if (opt->ignore_case)
372 push_arg("-i");
373 if (opt->binary == GREP_BINARY_NOMATCH)
374 push_arg("-I");
375 if (opt->word_regexp)
376 push_arg("-w");
377 if (opt->name_only)
378 push_arg("-l");
379 if (opt->unmatch_name_only)
380 push_arg("-L");
381 if (opt->null_following_name)
382 /* in GNU grep git's "-z" translates to "-Z" */
383 push_arg("-Z");
384 if (opt->count)
385 push_arg("-c");
386 if (opt->post_context || opt->pre_context) {
387 if (opt->post_context != opt->pre_context) {
388 if (opt->pre_context) {
389 push_arg("-B");
390 len += snprintf(argptr, sizeof(randarg)-len,
391 "%u", opt->pre_context) + 1;
392 if (sizeof(randarg) <= len)
393 die("maximum length of args exceeded");
394 push_arg(argptr);
395 argptr += len;
397 if (opt->post_context) {
398 push_arg("-A");
399 len += snprintf(argptr, sizeof(randarg)-len,
400 "%u", opt->post_context) + 1;
401 if (sizeof(randarg) <= len)
402 die("maximum length of args exceeded");
403 push_arg(argptr);
404 argptr += len;
407 else {
408 push_arg("-C");
409 len += snprintf(argptr, sizeof(randarg)-len,
410 "%u", opt->post_context) + 1;
411 if (sizeof(randarg) <= len)
412 die("maximum length of args exceeded");
413 push_arg(argptr);
414 argptr += len;
417 for (p = opt->pattern_list; p; p = p->next) {
418 push_arg("-e");
419 push_arg(p->pattern);
421 if (opt->color) {
422 struct strbuf sb = STRBUF_INIT;
424 grep_add_color(&sb, opt->color_match);
425 setenv("GREP_COLOR", sb.buf, 1);
427 strbuf_reset(&sb);
428 strbuf_addstr(&sb, "mt=");
429 grep_add_color(&sb, opt->color_match);
430 strbuf_addstr(&sb, ":sl=:cx=:fn=:ln=:bn=:se=");
431 setenv("GREP_COLORS", sb.buf, 1);
433 strbuf_release(&sb);
435 if (opt->color_external && strlen(opt->color_external) > 0)
436 push_arg(opt->color_external);
439 hit = 0;
440 argc = nr;
441 for (i = 0; i < active_nr; i++) {
442 struct cache_entry *ce = active_cache[i];
443 char *name;
444 int kept;
445 if (!S_ISREG(ce->ce_mode))
446 continue;
447 if (!pathspec_matches(paths, ce->name, opt->max_depth))
448 continue;
449 name = ce->name;
450 if (name[0] == '-') {
451 int len = ce_namelen(ce);
452 name = xmalloc(len + 3);
453 memcpy(name, "./", 2);
454 memcpy(name + 2, ce->name, len + 1);
456 argv[argc++] = name;
457 if (MAXARGS <= argc) {
458 status = flush_grep(opt, argc, nr, argv, &kept);
459 if (0 < status)
460 hit = 1;
461 argc = nr + kept;
463 if (ce_stage(ce)) {
464 do {
465 i++;
466 } while (i < active_nr &&
467 !strcmp(ce->name, active_cache[i]->name));
468 i--; /* compensate for loop control */
471 if (argc > nr) {
472 status = flush_grep(opt, argc, nr, argv, NULL);
473 if (0 < status)
474 hit = 1;
476 return hit;
478 #endif
480 static int grep_cache(struct grep_opt *opt, const char **paths, int cached,
481 int external_grep_allowed)
483 int hit = 0;
484 int nr;
485 read_cache();
487 #if !NO_EXTERNAL_GREP
489 * Use the external "grep" command for the case where
490 * we grep through the checked-out files. It tends to
491 * be a lot more optimized
493 if (!cached && external_grep_allowed) {
494 hit = external_grep(opt, paths, cached);
495 if (hit >= 0)
496 return hit;
497 hit = 0;
499 #endif
501 for (nr = 0; nr < active_nr; nr++) {
502 struct cache_entry *ce = active_cache[nr];
503 if (!S_ISREG(ce->ce_mode))
504 continue;
505 if (!pathspec_matches(paths, ce->name, opt->max_depth))
506 continue;
508 * If CE_VALID is on, we assume worktree file and its cache entry
509 * are identical, even if worktree file has been modified, so use
510 * cache version instead
512 if (cached || (ce->ce_flags & CE_VALID)) {
513 if (ce_stage(ce))
514 continue;
515 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
517 else
518 hit |= grep_file(opt, ce->name);
519 if (ce_stage(ce)) {
520 do {
521 nr++;
522 } while (nr < active_nr &&
523 !strcmp(ce->name, active_cache[nr]->name));
524 nr--; /* compensate for loop control */
527 free_grep_patterns(opt);
528 return hit;
531 static int grep_tree(struct grep_opt *opt, const char **paths,
532 struct tree_desc *tree,
533 const char *tree_name, const char *base)
535 int len;
536 int hit = 0;
537 struct name_entry entry;
538 char *down;
539 int tn_len = strlen(tree_name);
540 struct strbuf pathbuf;
542 strbuf_init(&pathbuf, PATH_MAX + tn_len);
544 if (tn_len) {
545 strbuf_add(&pathbuf, tree_name, tn_len);
546 strbuf_addch(&pathbuf, ':');
547 tn_len = pathbuf.len;
549 strbuf_addstr(&pathbuf, base);
550 len = pathbuf.len;
552 while (tree_entry(tree, &entry)) {
553 int te_len = tree_entry_len(entry.path, entry.sha1);
554 pathbuf.len = len;
555 strbuf_add(&pathbuf, entry.path, te_len);
557 if (S_ISDIR(entry.mode))
558 /* Match "abc/" against pathspec to
559 * decide if we want to descend into "abc"
560 * directory.
562 strbuf_addch(&pathbuf, '/');
564 down = pathbuf.buf + tn_len;
565 if (!pathspec_matches(paths, down, opt->max_depth))
567 else if (S_ISREG(entry.mode))
568 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
569 else if (S_ISDIR(entry.mode)) {
570 enum object_type type;
571 struct tree_desc sub;
572 void *data;
573 unsigned long size;
575 data = read_sha1_file(entry.sha1, &type, &size);
576 if (!data)
577 die("unable to read tree (%s)",
578 sha1_to_hex(entry.sha1));
579 init_tree_desc(&sub, data, size);
580 hit |= grep_tree(opt, paths, &sub, tree_name, down);
581 free(data);
584 strbuf_release(&pathbuf);
585 return hit;
588 static int grep_object(struct grep_opt *opt, const char **paths,
589 struct object *obj, const char *name)
591 if (obj->type == OBJ_BLOB)
592 return grep_sha1(opt, obj->sha1, name, 0);
593 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
594 struct tree_desc tree;
595 void *data;
596 unsigned long size;
597 int hit;
598 data = read_object_with_reference(obj->sha1, tree_type,
599 &size, NULL);
600 if (!data)
601 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
602 init_tree_desc(&tree, data, size);
603 hit = grep_tree(opt, paths, &tree, name, "");
604 free(data);
605 return hit;
607 die("unable to grep from object of type %s", typename(obj->type));
610 static int context_callback(const struct option *opt, const char *arg,
611 int unset)
613 struct grep_opt *grep_opt = opt->value;
614 int value;
615 const char *endp;
617 if (unset) {
618 grep_opt->pre_context = grep_opt->post_context = 0;
619 return 0;
621 value = strtol(arg, (char **)&endp, 10);
622 if (*endp) {
623 return error("switch `%c' expects a numerical value",
624 opt->short_name);
626 grep_opt->pre_context = grep_opt->post_context = value;
627 return 0;
630 static int file_callback(const struct option *opt, const char *arg, int unset)
632 struct grep_opt *grep_opt = opt->value;
633 FILE *patterns;
634 int lno = 0;
635 struct strbuf sb = STRBUF_INIT;
637 patterns = fopen(arg, "r");
638 if (!patterns)
639 die_errno("cannot open '%s'", arg);
640 while (strbuf_getline(&sb, patterns, '\n') == 0) {
641 /* ignore empty line like grep does */
642 if (sb.len == 0)
643 continue;
644 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
645 ++lno, GREP_PATTERN);
647 fclose(patterns);
648 strbuf_release(&sb);
649 return 0;
652 static int not_callback(const struct option *opt, const char *arg, int unset)
654 struct grep_opt *grep_opt = opt->value;
655 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
656 return 0;
659 static int and_callback(const struct option *opt, const char *arg, int unset)
661 struct grep_opt *grep_opt = opt->value;
662 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
663 return 0;
666 static int open_callback(const struct option *opt, const char *arg, int unset)
668 struct grep_opt *grep_opt = opt->value;
669 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
670 return 0;
673 static int close_callback(const struct option *opt, const char *arg, int unset)
675 struct grep_opt *grep_opt = opt->value;
676 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
677 return 0;
680 static int pattern_callback(const struct option *opt, const char *arg,
681 int unset)
683 struct grep_opt *grep_opt = opt->value;
684 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
685 return 0;
688 static int help_callback(const struct option *opt, const char *arg, int unset)
690 return -1;
693 int cmd_grep(int argc, const char **argv, const char *prefix)
695 int hit = 0;
696 int cached = 0;
697 int external_grep_allowed = 1;
698 int seen_dashdash = 0;
699 struct grep_opt opt;
700 struct object_array list = { 0, 0, NULL };
701 const char **paths = NULL;
702 int i;
703 int dummy;
704 struct option options[] = {
705 OPT_BOOLEAN(0, "cached", &cached,
706 "search in index instead of in the work tree"),
707 OPT_GROUP(""),
708 OPT_BOOLEAN('v', "invert-match", &opt.invert,
709 "show non-matching lines"),
710 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
711 "case insensitive matching"),
712 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
713 "match patterns only at word boundaries"),
714 OPT_SET_INT('a', "text", &opt.binary,
715 "process binary files as text", GREP_BINARY_TEXT),
716 OPT_SET_INT('I', NULL, &opt.binary,
717 "don't match patterns in binary files",
718 GREP_BINARY_NOMATCH),
719 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
720 "descend at most <depth> levels", PARSE_OPT_NONEG,
721 NULL, 1 },
722 OPT_GROUP(""),
723 OPT_BIT('E', "extended-regexp", &opt.regflags,
724 "use extended POSIX regular expressions", REG_EXTENDED),
725 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
726 "use basic POSIX regular expressions (default)",
727 REG_EXTENDED),
728 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
729 "interpret patterns as fixed strings"),
730 OPT_GROUP(""),
731 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
732 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
733 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
734 OPT_NEGBIT(0, "full-name", &opt.relative,
735 "show filenames relative to top directory", 1),
736 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
737 "show only filenames instead of matching lines"),
738 OPT_BOOLEAN(0, "name-only", &opt.name_only,
739 "synonym for --files-with-matches"),
740 OPT_BOOLEAN('L', "files-without-match",
741 &opt.unmatch_name_only,
742 "show only the names of files without match"),
743 OPT_BOOLEAN('z', "null", &opt.null_following_name,
744 "print NUL after filenames"),
745 OPT_BOOLEAN('c', "count", &opt.count,
746 "show the number of matches instead of matching lines"),
747 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
748 OPT_GROUP(""),
749 OPT_CALLBACK('C', NULL, &opt, "n",
750 "show <n> context lines before and after matches",
751 context_callback),
752 OPT_INTEGER('B', NULL, &opt.pre_context,
753 "show <n> context lines before matches"),
754 OPT_INTEGER('A', NULL, &opt.post_context,
755 "show <n> context lines after matches"),
756 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
757 context_callback),
758 OPT_BOOLEAN('p', "show-function", &opt.funcname,
759 "show a line with the function name before matches"),
760 OPT_GROUP(""),
761 OPT_CALLBACK('f', NULL, &opt, "file",
762 "read patterns from file", file_callback),
763 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
764 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
765 { OPTION_CALLBACK, 0, "and", &opt, NULL,
766 "combine patterns specified with -e",
767 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
768 OPT_BOOLEAN(0, "or", &dummy, ""),
769 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
770 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
771 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
772 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
773 open_callback },
774 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
775 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
776 close_callback },
777 OPT_BOOLEAN(0, "all-match", &opt.all_match,
778 "show only matches from files that match all patterns"),
779 OPT_GROUP(""),
780 #if NO_EXTERNAL_GREP
781 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
782 "allow calling of grep(1) (ignored by this build)"),
783 #else
784 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
785 "allow calling of grep(1) (default)"),
786 #endif
787 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
788 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
789 OPT_END()
792 memset(&opt, 0, sizeof(opt));
793 opt.prefix = prefix;
794 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
795 opt.relative = 1;
796 opt.pathname = 1;
797 opt.pattern_tail = &opt.pattern_list;
798 opt.regflags = REG_NEWLINE;
799 opt.max_depth = -1;
801 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
802 opt.color = -1;
803 git_config(grep_config, &opt);
804 if (opt.color == -1)
805 opt.color = git_use_color_default;
808 * If there is no -- then the paths must exist in the working
809 * tree. If there is no explicit pattern specified with -e or
810 * -f, we take the first unrecognized non option to be the
811 * pattern, but then what follows it must be zero or more
812 * valid refs up to the -- (if exists), and then existing
813 * paths. If there is an explicit pattern, then the first
814 * unrecognized non option is the beginning of the refs list
815 * that continues up to the -- (if exists), and then paths.
817 argc = parse_options(argc, argv, prefix, options, grep_usage,
818 PARSE_OPT_KEEP_DASHDASH |
819 PARSE_OPT_STOP_AT_NON_OPTION |
820 PARSE_OPT_NO_INTERNAL_HELP);
822 /* First unrecognized non-option token */
823 if (argc > 0 && !opt.pattern_list) {
824 append_grep_pattern(&opt, argv[0], "command line", 0,
825 GREP_PATTERN);
826 argv++;
827 argc--;
830 if ((opt.color && !opt.color_external) || opt.funcname)
831 external_grep_allowed = 0;
832 if (!opt.pattern_list)
833 die("no pattern given.");
834 if (!opt.fixed && opt.ignore_case)
835 opt.regflags |= REG_ICASE;
836 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
837 die("cannot mix --fixed-strings and regexp");
838 compile_grep_patterns(&opt);
840 /* Check revs and then paths */
841 for (i = 0; i < argc; i++) {
842 const char *arg = argv[i];
843 unsigned char sha1[20];
844 /* Is it a rev? */
845 if (!get_sha1(arg, sha1)) {
846 struct object *object = parse_object(sha1);
847 if (!object)
848 die("bad object %s", arg);
849 add_object_array(object, arg, &list);
850 continue;
852 if (!strcmp(arg, "--")) {
853 i++;
854 seen_dashdash = 1;
856 break;
859 /* The rest are paths */
860 if (!seen_dashdash) {
861 int j;
862 for (j = i; j < argc; j++)
863 verify_filename(prefix, argv[j]);
866 if (i < argc)
867 paths = get_pathspec(prefix, argv + i);
868 else if (prefix) {
869 paths = xcalloc(2, sizeof(const char *));
870 paths[0] = prefix;
871 paths[1] = NULL;
874 if (!list.nr) {
875 if (!cached)
876 setup_work_tree();
877 return !grep_cache(&opt, paths, cached, external_grep_allowed);
880 if (cached)
881 die("both --cached and trees are given.");
883 for (i = 0; i < list.nr; i++) {
884 struct object *real_obj;
885 real_obj = deref_tag(list.objects[i].item, NULL, 0);
886 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
887 hit = 1;
889 free_grep_patterns(&opt);
890 return !hit;