cvsimport: standarize open() calls to external git tools
[git/mingw.git] / builtin-grep.c
blobcea973ba6bafff69b72db0923e5b583dc0a3f8bc
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 (!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;
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;
217 #if !NO_EXTERNAL_GREP
218 static int exec_grep(int argc, const char **argv)
220 pid_t pid;
221 int status;
223 argv[argc] = NULL;
224 trace_argv_printf(argv, "trace: grep:");
225 pid = fork();
226 if (pid < 0)
227 return pid;
228 if (!pid) {
229 execvp("grep", (char **) argv);
230 exit(255);
232 while (waitpid(pid, &status, 0) < 0) {
233 if (errno == EINTR)
234 continue;
235 return -1;
237 if (WIFEXITED(status)) {
238 if (!WEXITSTATUS(status))
239 return 1;
240 return 0;
242 return -1;
245 #define MAXARGS 1000
246 #define ARGBUF 4096
247 #define push_arg(a) do { \
248 if (nr < MAXARGS) argv[nr++] = (a); \
249 else die("maximum number of args exceeded"); \
250 } while (0)
253 * If you send a singleton filename to grep, it does not give
254 * the name of the file. GNU grep has "-H" but we would want
255 * that behaviour in a portable way.
257 * So we keep two pathnames in argv buffer unsent to grep in
258 * the main loop if we need to do more than one grep.
260 static int flush_grep(struct grep_opt *opt,
261 int argc, int arg0, const char **argv, int *kept)
263 int status;
264 int count = argc - arg0;
265 const char *kept_0 = NULL;
267 if (count <= 2) {
269 * Because we keep at least 2 paths in the call from
270 * the main loop (i.e. kept != NULL), and MAXARGS is
271 * far greater than 2, this usually is a call to
272 * conclude the grep. However, the user could attempt
273 * to overflow the argv buffer by giving too many
274 * options to leave very small number of real
275 * arguments even for the call in the main loop.
277 if (kept)
278 die("insanely many options to grep");
281 * If we have two or more paths, we do not have to do
282 * anything special, but we need to push /dev/null to
283 * get "-H" behaviour of GNU grep portably but when we
284 * are not doing "-l" nor "-L" nor "-c".
286 if (count == 1 &&
287 !opt->name_only &&
288 !opt->unmatch_name_only &&
289 !opt->count) {
290 argv[argc++] = "/dev/null";
291 argv[argc] = NULL;
295 else if (kept) {
297 * Called because we found many paths and haven't finished
298 * iterating over the cache yet. We keep two paths
299 * for the concluding call. argv[argc-2] and argv[argc-1]
300 * has the last two paths, so save the first one away,
301 * replace it with NULL while sending the list to grep,
302 * and recover them after we are done.
304 *kept = 2;
305 kept_0 = argv[argc-2];
306 argv[argc-2] = NULL;
307 argc -= 2;
310 if (opt->pre_context || opt->post_context) {
312 * grep handles hunk marks between files, but we need to
313 * do that ourselves between multiple calls.
315 if (opt->show_hunk_mark)
316 write_or_die(1, "--\n", 3);
317 else
318 opt->show_hunk_mark = 1;
321 status = exec_grep(argc, argv);
323 if (kept_0) {
325 * Then recover them. Now the last arg is beyond the
326 * terminating NULL which is at argc, and the second
327 * from the last is what we saved away in kept_0
329 argv[arg0++] = kept_0;
330 argv[arg0] = argv[argc+1];
332 return status;
335 static void grep_add_color(struct strbuf *sb, const char *escape_seq)
337 size_t orig_len = sb->len;
339 while (*escape_seq) {
340 if (*escape_seq == 'm')
341 strbuf_addch(sb, ';');
342 else if (*escape_seq != '\033' && *escape_seq != '[')
343 strbuf_addch(sb, *escape_seq);
344 escape_seq++;
346 if (sb->len > orig_len && sb->buf[sb->len - 1] == ';')
347 strbuf_setlen(sb, sb->len - 1);
350 static int has_skip_worktree_entry(struct grep_opt *opt, const char **paths)
352 int nr;
353 for (nr = 0; nr < active_nr; nr++) {
354 struct cache_entry *ce = active_cache[nr];
355 if (!S_ISREG(ce->ce_mode))
356 continue;
357 if (!pathspec_matches(paths, ce->name, opt->max_depth))
358 continue;
359 if (ce_skip_worktree(ce))
360 return 1;
362 return 0;
365 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
367 int i, nr, argc, hit, len, status;
368 const char *argv[MAXARGS+1];
369 char randarg[ARGBUF];
370 char *argptr = randarg;
371 struct grep_pat *p;
373 if (opt->extended || (opt->relative && opt->prefix_length)
374 || has_skip_worktree_entry(opt, paths))
375 return -1;
376 len = nr = 0;
377 push_arg("grep");
378 if (opt->fixed)
379 push_arg("-F");
380 if (opt->linenum)
381 push_arg("-n");
382 if (!opt->pathname)
383 push_arg("-h");
384 if (opt->regflags & REG_EXTENDED)
385 push_arg("-E");
386 if (opt->ignore_case)
387 push_arg("-i");
388 if (opt->binary == GREP_BINARY_NOMATCH)
389 push_arg("-I");
390 if (opt->word_regexp)
391 push_arg("-w");
392 if (opt->name_only)
393 push_arg("-l");
394 if (opt->unmatch_name_only)
395 push_arg("-L");
396 if (opt->null_following_name)
397 /* in GNU grep git's "-z" translates to "-Z" */
398 push_arg("-Z");
399 if (opt->count)
400 push_arg("-c");
401 if (opt->post_context || opt->pre_context) {
402 if (opt->post_context != opt->pre_context) {
403 if (opt->pre_context) {
404 push_arg("-B");
405 len += snprintf(argptr, sizeof(randarg)-len,
406 "%u", opt->pre_context) + 1;
407 if (sizeof(randarg) <= len)
408 die("maximum length of args exceeded");
409 push_arg(argptr);
410 argptr += len;
412 if (opt->post_context) {
413 push_arg("-A");
414 len += snprintf(argptr, sizeof(randarg)-len,
415 "%u", opt->post_context) + 1;
416 if (sizeof(randarg) <= len)
417 die("maximum length of args exceeded");
418 push_arg(argptr);
419 argptr += len;
422 else {
423 push_arg("-C");
424 len += snprintf(argptr, sizeof(randarg)-len,
425 "%u", opt->post_context) + 1;
426 if (sizeof(randarg) <= len)
427 die("maximum length of args exceeded");
428 push_arg(argptr);
429 argptr += len;
432 for (p = opt->pattern_list; p; p = p->next) {
433 push_arg("-e");
434 push_arg(p->pattern);
436 if (opt->color) {
437 struct strbuf sb = STRBUF_INIT;
439 grep_add_color(&sb, opt->color_match);
440 setenv("GREP_COLOR", sb.buf, 1);
442 strbuf_reset(&sb);
443 strbuf_addstr(&sb, "mt=");
444 grep_add_color(&sb, opt->color_match);
445 strbuf_addstr(&sb, ":sl=:cx=:fn=:ln=:bn=:se=");
446 setenv("GREP_COLORS", sb.buf, 1);
448 strbuf_release(&sb);
450 if (opt->color_external && strlen(opt->color_external) > 0)
451 push_arg(opt->color_external);
452 } else {
453 unsetenv("GREP_COLOR");
454 unsetenv("GREP_COLORS");
456 unsetenv("GREP_OPTIONS");
458 hit = 0;
459 argc = nr;
460 for (i = 0; i < active_nr; i++) {
461 struct cache_entry *ce = active_cache[i];
462 char *name;
463 int kept;
464 if (!S_ISREG(ce->ce_mode))
465 continue;
466 if (!pathspec_matches(paths, ce->name, opt->max_depth))
467 continue;
468 name = ce->name;
469 if (name[0] == '-') {
470 int len = ce_namelen(ce);
471 name = xmalloc(len + 3);
472 memcpy(name, "./", 2);
473 memcpy(name + 2, ce->name, len + 1);
475 argv[argc++] = name;
476 if (MAXARGS <= argc) {
477 status = flush_grep(opt, argc, nr, argv, &kept);
478 if (0 < status)
479 hit = 1;
480 argc = nr + kept;
482 if (ce_stage(ce)) {
483 do {
484 i++;
485 } while (i < active_nr &&
486 !strcmp(ce->name, active_cache[i]->name));
487 i--; /* compensate for loop control */
490 if (argc > nr) {
491 status = flush_grep(opt, argc, nr, argv, NULL);
492 if (0 < status)
493 hit = 1;
495 return hit;
497 #endif
499 static int grep_cache(struct grep_opt *opt, const char **paths, int cached,
500 int external_grep_allowed)
502 int hit = 0;
503 int nr;
504 read_cache();
506 #if !NO_EXTERNAL_GREP
508 * Use the external "grep" command for the case where
509 * we grep through the checked-out files. It tends to
510 * be a lot more optimized
512 if (!cached && external_grep_allowed) {
513 hit = external_grep(opt, paths, cached);
514 if (hit >= 0)
515 return hit;
516 hit = 0;
518 #endif
520 for (nr = 0; nr < active_nr; nr++) {
521 struct cache_entry *ce = active_cache[nr];
522 if (!S_ISREG(ce->ce_mode))
523 continue;
524 if (!pathspec_matches(paths, ce->name, opt->max_depth))
525 continue;
527 * If CE_VALID is on, we assume worktree file and its cache entry
528 * are identical, even if worktree file has been modified, so use
529 * cache version instead
531 if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
532 if (ce_stage(ce))
533 continue;
534 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
536 else
537 hit |= grep_file(opt, ce->name);
538 if (ce_stage(ce)) {
539 do {
540 nr++;
541 } while (nr < active_nr &&
542 !strcmp(ce->name, active_cache[nr]->name));
543 nr--; /* compensate for loop control */
546 free_grep_patterns(opt);
547 return hit;
550 static int grep_tree(struct grep_opt *opt, const char **paths,
551 struct tree_desc *tree,
552 const char *tree_name, const char *base)
554 int len;
555 int hit = 0;
556 struct name_entry entry;
557 char *down;
558 int tn_len = strlen(tree_name);
559 struct strbuf pathbuf;
561 strbuf_init(&pathbuf, PATH_MAX + tn_len);
563 if (tn_len) {
564 strbuf_add(&pathbuf, tree_name, tn_len);
565 strbuf_addch(&pathbuf, ':');
566 tn_len = pathbuf.len;
568 strbuf_addstr(&pathbuf, base);
569 len = pathbuf.len;
571 while (tree_entry(tree, &entry)) {
572 int te_len = tree_entry_len(entry.path, entry.sha1);
573 pathbuf.len = len;
574 strbuf_add(&pathbuf, entry.path, te_len);
576 if (S_ISDIR(entry.mode))
577 /* Match "abc/" against pathspec to
578 * decide if we want to descend into "abc"
579 * directory.
581 strbuf_addch(&pathbuf, '/');
583 down = pathbuf.buf + tn_len;
584 if (!pathspec_matches(paths, down, opt->max_depth))
586 else if (S_ISREG(entry.mode))
587 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
588 else if (S_ISDIR(entry.mode)) {
589 enum object_type type;
590 struct tree_desc sub;
591 void *data;
592 unsigned long size;
594 data = read_sha1_file(entry.sha1, &type, &size);
595 if (!data)
596 die("unable to read tree (%s)",
597 sha1_to_hex(entry.sha1));
598 init_tree_desc(&sub, data, size);
599 hit |= grep_tree(opt, paths, &sub, tree_name, down);
600 free(data);
603 strbuf_release(&pathbuf);
604 return hit;
607 static int grep_object(struct grep_opt *opt, const char **paths,
608 struct object *obj, const char *name)
610 if (obj->type == OBJ_BLOB)
611 return grep_sha1(opt, obj->sha1, name, 0);
612 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
613 struct tree_desc tree;
614 void *data;
615 unsigned long size;
616 int hit;
617 data = read_object_with_reference(obj->sha1, tree_type,
618 &size, NULL);
619 if (!data)
620 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
621 init_tree_desc(&tree, data, size);
622 hit = grep_tree(opt, paths, &tree, name, "");
623 free(data);
624 return hit;
626 die("unable to grep from object of type %s", typename(obj->type));
629 static int context_callback(const struct option *opt, const char *arg,
630 int unset)
632 struct grep_opt *grep_opt = opt->value;
633 int value;
634 const char *endp;
636 if (unset) {
637 grep_opt->pre_context = grep_opt->post_context = 0;
638 return 0;
640 value = strtol(arg, (char **)&endp, 10);
641 if (*endp) {
642 return error("switch `%c' expects a numerical value",
643 opt->short_name);
645 grep_opt->pre_context = grep_opt->post_context = value;
646 return 0;
649 static int file_callback(const struct option *opt, const char *arg, int unset)
651 struct grep_opt *grep_opt = opt->value;
652 FILE *patterns;
653 int lno = 0;
654 struct strbuf sb = STRBUF_INIT;
656 patterns = fopen(arg, "r");
657 if (!patterns)
658 die_errno("cannot open '%s'", arg);
659 while (strbuf_getline(&sb, patterns, '\n') == 0) {
660 /* ignore empty line like grep does */
661 if (sb.len == 0)
662 continue;
663 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
664 ++lno, GREP_PATTERN);
666 fclose(patterns);
667 strbuf_release(&sb);
668 return 0;
671 static int not_callback(const struct option *opt, const char *arg, int unset)
673 struct grep_opt *grep_opt = opt->value;
674 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
675 return 0;
678 static int and_callback(const struct option *opt, const char *arg, int unset)
680 struct grep_opt *grep_opt = opt->value;
681 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
682 return 0;
685 static int open_callback(const struct option *opt, const char *arg, int unset)
687 struct grep_opt *grep_opt = opt->value;
688 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
689 return 0;
692 static int close_callback(const struct option *opt, const char *arg, int unset)
694 struct grep_opt *grep_opt = opt->value;
695 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
696 return 0;
699 static int pattern_callback(const struct option *opt, const char *arg,
700 int unset)
702 struct grep_opt *grep_opt = opt->value;
703 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
704 return 0;
707 static int help_callback(const struct option *opt, const char *arg, int unset)
709 return -1;
712 int cmd_grep(int argc, const char **argv, const char *prefix)
714 int hit = 0;
715 int cached = 0;
716 int external_grep_allowed = 1;
717 int seen_dashdash = 0;
718 struct grep_opt opt;
719 struct object_array list = { 0, 0, NULL };
720 const char **paths = NULL;
721 int i;
722 int dummy;
723 struct option options[] = {
724 OPT_BOOLEAN(0, "cached", &cached,
725 "search in index instead of in the work tree"),
726 OPT_GROUP(""),
727 OPT_BOOLEAN('v', "invert-match", &opt.invert,
728 "show non-matching lines"),
729 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
730 "case insensitive matching"),
731 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
732 "match patterns only at word boundaries"),
733 OPT_SET_INT('a', "text", &opt.binary,
734 "process binary files as text", GREP_BINARY_TEXT),
735 OPT_SET_INT('I', NULL, &opt.binary,
736 "don't match patterns in binary files",
737 GREP_BINARY_NOMATCH),
738 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
739 "descend at most <depth> levels", PARSE_OPT_NONEG,
740 NULL, 1 },
741 OPT_GROUP(""),
742 OPT_BIT('E', "extended-regexp", &opt.regflags,
743 "use extended POSIX regular expressions", REG_EXTENDED),
744 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
745 "use basic POSIX regular expressions (default)",
746 REG_EXTENDED),
747 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
748 "interpret patterns as fixed strings"),
749 OPT_GROUP(""),
750 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
751 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
752 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
753 OPT_NEGBIT(0, "full-name", &opt.relative,
754 "show filenames relative to top directory", 1),
755 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
756 "show only filenames instead of matching lines"),
757 OPT_BOOLEAN(0, "name-only", &opt.name_only,
758 "synonym for --files-with-matches"),
759 OPT_BOOLEAN('L', "files-without-match",
760 &opt.unmatch_name_only,
761 "show only the names of files without match"),
762 OPT_BOOLEAN('z', "null", &opt.null_following_name,
763 "print NUL after filenames"),
764 OPT_BOOLEAN('c', "count", &opt.count,
765 "show the number of matches instead of matching lines"),
766 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
767 OPT_GROUP(""),
768 OPT_CALLBACK('C', NULL, &opt, "n",
769 "show <n> context lines before and after matches",
770 context_callback),
771 OPT_INTEGER('B', NULL, &opt.pre_context,
772 "show <n> context lines before matches"),
773 OPT_INTEGER('A', NULL, &opt.post_context,
774 "show <n> context lines after matches"),
775 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
776 context_callback),
777 OPT_BOOLEAN('p', "show-function", &opt.funcname,
778 "show a line with the function name before matches"),
779 OPT_GROUP(""),
780 OPT_CALLBACK('f', NULL, &opt, "file",
781 "read patterns from file", file_callback),
782 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
783 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
784 { OPTION_CALLBACK, 0, "and", &opt, NULL,
785 "combine patterns specified with -e",
786 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
787 OPT_BOOLEAN(0, "or", &dummy, ""),
788 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
789 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
790 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
791 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
792 open_callback },
793 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
794 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
795 close_callback },
796 OPT_BOOLEAN(0, "all-match", &opt.all_match,
797 "show only matches from files that match all patterns"),
798 OPT_GROUP(""),
799 #if NO_EXTERNAL_GREP
800 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
801 "allow calling of grep(1) (ignored by this build)"),
802 #else
803 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
804 "allow calling of grep(1) (default)"),
805 #endif
806 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
807 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
808 OPT_END()
812 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
813 * to show usage information and exit.
815 if (argc == 2 && !strcmp(argv[1], "-h"))
816 usage_with_options(grep_usage, options);
818 memset(&opt, 0, sizeof(opt));
819 opt.prefix = prefix;
820 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
821 opt.relative = 1;
822 opt.pathname = 1;
823 opt.pattern_tail = &opt.pattern_list;
824 opt.regflags = REG_NEWLINE;
825 opt.max_depth = -1;
827 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
828 opt.color = -1;
829 git_config(grep_config, &opt);
830 if (opt.color == -1)
831 opt.color = git_use_color_default;
834 * If there is no -- then the paths must exist in the working
835 * tree. If there is no explicit pattern specified with -e or
836 * -f, we take the first unrecognized non option to be the
837 * pattern, but then what follows it must be zero or more
838 * valid refs up to the -- (if exists), and then existing
839 * paths. If there is an explicit pattern, then the first
840 * unrecognized non option is the beginning of the refs list
841 * that continues up to the -- (if exists), and then paths.
843 argc = parse_options(argc, argv, prefix, options, grep_usage,
844 PARSE_OPT_KEEP_DASHDASH |
845 PARSE_OPT_STOP_AT_NON_OPTION |
846 PARSE_OPT_NO_INTERNAL_HELP);
848 /* First unrecognized non-option token */
849 if (argc > 0 && !opt.pattern_list) {
850 append_grep_pattern(&opt, argv[0], "command line", 0,
851 GREP_PATTERN);
852 argv++;
853 argc--;
856 if ((opt.color && !opt.color_external) || opt.funcname)
857 external_grep_allowed = 0;
858 if (!opt.pattern_list)
859 die("no pattern given.");
860 if (!opt.fixed && opt.ignore_case)
861 opt.regflags |= REG_ICASE;
862 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
863 die("cannot mix --fixed-strings and regexp");
864 compile_grep_patterns(&opt);
866 /* Check revs and then paths */
867 for (i = 0; i < argc; i++) {
868 const char *arg = argv[i];
869 unsigned char sha1[20];
870 /* Is it a rev? */
871 if (!get_sha1(arg, sha1)) {
872 struct object *object = parse_object(sha1);
873 if (!object)
874 die("bad object %s", arg);
875 add_object_array(object, arg, &list);
876 continue;
878 if (!strcmp(arg, "--")) {
879 i++;
880 seen_dashdash = 1;
882 break;
885 /* The rest are paths */
886 if (!seen_dashdash) {
887 int j;
888 for (j = i; j < argc; j++)
889 verify_filename(prefix, argv[j]);
892 if (i < argc)
893 paths = get_pathspec(prefix, argv + i);
894 else if (prefix) {
895 paths = xcalloc(2, sizeof(const char *));
896 paths[0] = prefix;
897 paths[1] = NULL;
900 if (!list.nr) {
901 if (!cached)
902 setup_work_tree();
903 return !grep_cache(&opt, paths, cached, external_grep_allowed);
906 if (cached)
907 die("both --cached and trees are given.");
909 for (i = 0; i < list.nr; i++) {
910 struct object *real_obj;
911 real_obj = deref_tag(list.objects[i].item, NULL, 0);
912 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
913 hit = 1;
915 free_grep_patterns(&opt);
916 return !hit;