Fix uninitialized variable in get_refs_via_rsync().
[git/dkf.git] / builtin-grep.c
blobaf6c6fe8a7ed677de84cdbd828e8daae0a6bb12d
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 if (opt->relative && opt->prefix_length)
209 filename = quote_path_relative(filename, -1, &buf, opt->prefix);
210 i = grep_buffer(opt, filename, data, sz);
211 strbuf_release(&buf);
212 free(data);
213 return i;
216 #if !NO_EXTERNAL_GREP
217 static int exec_grep(int argc, const char **argv)
219 pid_t pid;
220 int status;
222 argv[argc] = NULL;
223 pid = fork();
224 if (pid < 0)
225 return pid;
226 if (!pid) {
227 execvp("grep", (char **) argv);
228 exit(255);
230 while (waitpid(pid, &status, 0) < 0) {
231 if (errno == EINTR)
232 continue;
233 return -1;
235 if (WIFEXITED(status)) {
236 if (!WEXITSTATUS(status))
237 return 1;
238 return 0;
240 return -1;
243 #define MAXARGS 1000
244 #define ARGBUF 4096
245 #define push_arg(a) do { \
246 if (nr < MAXARGS) argv[nr++] = (a); \
247 else die("maximum number of args exceeded"); \
248 } while (0)
251 * If you send a singleton filename to grep, it does not give
252 * the name of the file. GNU grep has "-H" but we would want
253 * that behaviour in a portable way.
255 * So we keep two pathnames in argv buffer unsent to grep in
256 * the main loop if we need to do more than one grep.
258 static int flush_grep(struct grep_opt *opt,
259 int argc, int arg0, const char **argv, int *kept)
261 int status;
262 int count = argc - arg0;
263 const char *kept_0 = NULL;
265 if (count <= 2) {
267 * Because we keep at least 2 paths in the call from
268 * the main loop (i.e. kept != NULL), and MAXARGS is
269 * far greater than 2, this usually is a call to
270 * conclude the grep. However, the user could attempt
271 * to overflow the argv buffer by giving too many
272 * options to leave very small number of real
273 * arguments even for the call in the main loop.
275 if (kept)
276 die("insanely many options to grep");
279 * If we have two or more paths, we do not have to do
280 * anything special, but we need to push /dev/null to
281 * get "-H" behaviour of GNU grep portably but when we
282 * are not doing "-l" nor "-L" nor "-c".
284 if (count == 1 &&
285 !opt->name_only &&
286 !opt->unmatch_name_only &&
287 !opt->count) {
288 argv[argc++] = "/dev/null";
289 argv[argc] = NULL;
293 else if (kept) {
295 * Called because we found many paths and haven't finished
296 * iterating over the cache yet. We keep two paths
297 * for the concluding call. argv[argc-2] and argv[argc-1]
298 * has the last two paths, so save the first one away,
299 * replace it with NULL while sending the list to grep,
300 * and recover them after we are done.
302 *kept = 2;
303 kept_0 = argv[argc-2];
304 argv[argc-2] = NULL;
305 argc -= 2;
308 if (opt->pre_context || opt->post_context) {
310 * grep handles hunk marks between files, but we need to
311 * do that ourselves between multiple calls.
313 if (opt->show_hunk_mark)
314 write_or_die(1, "--\n", 3);
315 else
316 opt->show_hunk_mark = 1;
319 status = exec_grep(argc, argv);
321 if (kept_0) {
323 * Then recover them. Now the last arg is beyond the
324 * terminating NULL which is at argc, and the second
325 * from the last is what we saved away in kept_0
327 argv[arg0++] = kept_0;
328 argv[arg0] = argv[argc+1];
330 return status;
333 static void grep_add_color(struct strbuf *sb, const char *escape_seq)
335 size_t orig_len = sb->len;
337 while (*escape_seq) {
338 if (*escape_seq == 'm')
339 strbuf_addch(sb, ';');
340 else if (*escape_seq != '\033' && *escape_seq != '[')
341 strbuf_addch(sb, *escape_seq);
342 escape_seq++;
344 if (sb->len > orig_len && sb->buf[sb->len - 1] == ';')
345 strbuf_setlen(sb, sb->len - 1);
348 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
350 int i, nr, argc, hit, len, status;
351 const char *argv[MAXARGS+1];
352 char randarg[ARGBUF];
353 char *argptr = randarg;
354 struct grep_pat *p;
356 if (opt->extended || (opt->relative && opt->prefix_length))
357 return -1;
358 len = nr = 0;
359 push_arg("grep");
360 if (opt->fixed)
361 push_arg("-F");
362 if (opt->linenum)
363 push_arg("-n");
364 if (!opt->pathname)
365 push_arg("-h");
366 if (opt->regflags & REG_EXTENDED)
367 push_arg("-E");
368 if (opt->ignore_case)
369 push_arg("-i");
370 if (opt->binary == GREP_BINARY_NOMATCH)
371 push_arg("-I");
372 if (opt->word_regexp)
373 push_arg("-w");
374 if (opt->name_only)
375 push_arg("-l");
376 if (opt->unmatch_name_only)
377 push_arg("-L");
378 if (opt->null_following_name)
379 /* in GNU grep git's "-z" translates to "-Z" */
380 push_arg("-Z");
381 if (opt->count)
382 push_arg("-c");
383 if (opt->post_context || opt->pre_context) {
384 if (opt->post_context != opt->pre_context) {
385 if (opt->pre_context) {
386 push_arg("-B");
387 len += snprintf(argptr, sizeof(randarg)-len,
388 "%u", opt->pre_context) + 1;
389 if (sizeof(randarg) <= len)
390 die("maximum length of args exceeded");
391 push_arg(argptr);
392 argptr += len;
394 if (opt->post_context) {
395 push_arg("-A");
396 len += snprintf(argptr, sizeof(randarg)-len,
397 "%u", opt->post_context) + 1;
398 if (sizeof(randarg) <= len)
399 die("maximum length of args exceeded");
400 push_arg(argptr);
401 argptr += len;
404 else {
405 push_arg("-C");
406 len += snprintf(argptr, sizeof(randarg)-len,
407 "%u", opt->post_context) + 1;
408 if (sizeof(randarg) <= len)
409 die("maximum length of args exceeded");
410 push_arg(argptr);
411 argptr += len;
414 for (p = opt->pattern_list; p; p = p->next) {
415 push_arg("-e");
416 push_arg(p->pattern);
418 if (opt->color) {
419 struct strbuf sb = STRBUF_INIT;
421 grep_add_color(&sb, opt->color_match);
422 setenv("GREP_COLOR", sb.buf, 1);
424 strbuf_reset(&sb);
425 strbuf_addstr(&sb, "mt=");
426 grep_add_color(&sb, opt->color_match);
427 strbuf_addstr(&sb, ":sl=:cx=:fn=:ln=:bn=:se=");
428 setenv("GREP_COLORS", sb.buf, 1);
430 strbuf_release(&sb);
432 if (opt->color_external && strlen(opt->color_external) > 0)
433 push_arg(opt->color_external);
434 } else {
435 unsetenv("GREP_COLOR");
436 unsetenv("GREP_COLORS");
438 unsetenv("GREP_OPTIONS");
440 hit = 0;
441 argc = nr;
442 for (i = 0; i < active_nr; i++) {
443 struct cache_entry *ce = active_cache[i];
444 char *name;
445 int kept;
446 if (!S_ISREG(ce->ce_mode))
447 continue;
448 if (!pathspec_matches(paths, ce->name, opt->max_depth))
449 continue;
450 name = ce->name;
451 if (name[0] == '-') {
452 int len = ce_namelen(ce);
453 name = xmalloc(len + 3);
454 memcpy(name, "./", 2);
455 memcpy(name + 2, ce->name, len + 1);
457 argv[argc++] = name;
458 if (MAXARGS <= argc) {
459 status = flush_grep(opt, argc, nr, argv, &kept);
460 if (0 < status)
461 hit = 1;
462 argc = nr + kept;
464 if (ce_stage(ce)) {
465 do {
466 i++;
467 } while (i < active_nr &&
468 !strcmp(ce->name, active_cache[i]->name));
469 i--; /* compensate for loop control */
472 if (argc > nr) {
473 status = flush_grep(opt, argc, nr, argv, NULL);
474 if (0 < status)
475 hit = 1;
477 return hit;
479 #endif
481 static int grep_cache(struct grep_opt *opt, const char **paths, int cached,
482 int external_grep_allowed)
484 int hit = 0;
485 int nr;
486 read_cache();
488 #if !NO_EXTERNAL_GREP
490 * Use the external "grep" command for the case where
491 * we grep through the checked-out files. It tends to
492 * be a lot more optimized
494 if (!cached && external_grep_allowed) {
495 hit = external_grep(opt, paths, cached);
496 if (hit >= 0)
497 return hit;
498 hit = 0;
500 #endif
502 for (nr = 0; nr < active_nr; nr++) {
503 struct cache_entry *ce = active_cache[nr];
504 if (!S_ISREG(ce->ce_mode))
505 continue;
506 if (!pathspec_matches(paths, ce->name, opt->max_depth))
507 continue;
509 * If CE_VALID is on, we assume worktree file and its cache entry
510 * are identical, even if worktree file has been modified, so use
511 * cache version instead
513 if (cached || (ce->ce_flags & CE_VALID)) {
514 if (ce_stage(ce))
515 continue;
516 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
518 else
519 hit |= grep_file(opt, ce->name);
520 if (ce_stage(ce)) {
521 do {
522 nr++;
523 } while (nr < active_nr &&
524 !strcmp(ce->name, active_cache[nr]->name));
525 nr--; /* compensate for loop control */
528 free_grep_patterns(opt);
529 return hit;
532 static int grep_tree(struct grep_opt *opt, const char **paths,
533 struct tree_desc *tree,
534 const char *tree_name, const char *base)
536 int len;
537 int hit = 0;
538 struct name_entry entry;
539 char *down;
540 int tn_len = strlen(tree_name);
541 struct strbuf pathbuf;
543 strbuf_init(&pathbuf, PATH_MAX + tn_len);
545 if (tn_len) {
546 strbuf_add(&pathbuf, tree_name, tn_len);
547 strbuf_addch(&pathbuf, ':');
548 tn_len = pathbuf.len;
550 strbuf_addstr(&pathbuf, base);
551 len = pathbuf.len;
553 while (tree_entry(tree, &entry)) {
554 int te_len = tree_entry_len(entry.path, entry.sha1);
555 pathbuf.len = len;
556 strbuf_add(&pathbuf, entry.path, te_len);
558 if (S_ISDIR(entry.mode))
559 /* Match "abc/" against pathspec to
560 * decide if we want to descend into "abc"
561 * directory.
563 strbuf_addch(&pathbuf, '/');
565 down = pathbuf.buf + tn_len;
566 if (!pathspec_matches(paths, down, opt->max_depth))
568 else if (S_ISREG(entry.mode))
569 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
570 else if (S_ISDIR(entry.mode)) {
571 enum object_type type;
572 struct tree_desc sub;
573 void *data;
574 unsigned long size;
576 data = read_sha1_file(entry.sha1, &type, &size);
577 if (!data)
578 die("unable to read tree (%s)",
579 sha1_to_hex(entry.sha1));
580 init_tree_desc(&sub, data, size);
581 hit |= grep_tree(opt, paths, &sub, tree_name, down);
582 free(data);
585 strbuf_release(&pathbuf);
586 return hit;
589 static int grep_object(struct grep_opt *opt, const char **paths,
590 struct object *obj, const char *name)
592 if (obj->type == OBJ_BLOB)
593 return grep_sha1(opt, obj->sha1, name, 0);
594 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
595 struct tree_desc tree;
596 void *data;
597 unsigned long size;
598 int hit;
599 data = read_object_with_reference(obj->sha1, tree_type,
600 &size, NULL);
601 if (!data)
602 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
603 init_tree_desc(&tree, data, size);
604 hit = grep_tree(opt, paths, &tree, name, "");
605 free(data);
606 return hit;
608 die("unable to grep from object of type %s", typename(obj->type));
611 static int context_callback(const struct option *opt, const char *arg,
612 int unset)
614 struct grep_opt *grep_opt = opt->value;
615 int value;
616 const char *endp;
618 if (unset) {
619 grep_opt->pre_context = grep_opt->post_context = 0;
620 return 0;
622 value = strtol(arg, (char **)&endp, 10);
623 if (*endp) {
624 return error("switch `%c' expects a numerical value",
625 opt->short_name);
627 grep_opt->pre_context = grep_opt->post_context = value;
628 return 0;
631 static int file_callback(const struct option *opt, const char *arg, int unset)
633 struct grep_opt *grep_opt = opt->value;
634 FILE *patterns;
635 int lno = 0;
636 struct strbuf sb = STRBUF_INIT;
638 patterns = fopen(arg, "r");
639 if (!patterns)
640 die_errno("cannot open '%s'", arg);
641 while (strbuf_getline(&sb, patterns, '\n') == 0) {
642 /* ignore empty line like grep does */
643 if (sb.len == 0)
644 continue;
645 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
646 ++lno, GREP_PATTERN);
648 fclose(patterns);
649 strbuf_release(&sb);
650 return 0;
653 static int not_callback(const struct option *opt, const char *arg, int unset)
655 struct grep_opt *grep_opt = opt->value;
656 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
657 return 0;
660 static int and_callback(const struct option *opt, const char *arg, int unset)
662 struct grep_opt *grep_opt = opt->value;
663 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
664 return 0;
667 static int open_callback(const struct option *opt, const char *arg, int unset)
669 struct grep_opt *grep_opt = opt->value;
670 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
671 return 0;
674 static int close_callback(const struct option *opt, const char *arg, int unset)
676 struct grep_opt *grep_opt = opt->value;
677 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
678 return 0;
681 static int pattern_callback(const struct option *opt, const char *arg,
682 int unset)
684 struct grep_opt *grep_opt = opt->value;
685 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
686 return 0;
689 static int help_callback(const struct option *opt, const char *arg, int unset)
691 return -1;
694 int cmd_grep(int argc, const char **argv, const char *prefix)
696 int hit = 0;
697 int cached = 0;
698 int external_grep_allowed = 1;
699 int seen_dashdash = 0;
700 struct grep_opt opt;
701 struct object_array list = { 0, 0, NULL };
702 const char **paths = NULL;
703 int i;
704 int dummy;
705 struct option options[] = {
706 OPT_BOOLEAN(0, "cached", &cached,
707 "search in index instead of in the work tree"),
708 OPT_GROUP(""),
709 OPT_BOOLEAN('v', "invert-match", &opt.invert,
710 "show non-matching lines"),
711 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
712 "case insensitive matching"),
713 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
714 "match patterns only at word boundaries"),
715 OPT_SET_INT('a', "text", &opt.binary,
716 "process binary files as text", GREP_BINARY_TEXT),
717 OPT_SET_INT('I', NULL, &opt.binary,
718 "don't match patterns in binary files",
719 GREP_BINARY_NOMATCH),
720 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
721 "descend at most <depth> levels", PARSE_OPT_NONEG,
722 NULL, 1 },
723 OPT_GROUP(""),
724 OPT_BIT('E', "extended-regexp", &opt.regflags,
725 "use extended POSIX regular expressions", REG_EXTENDED),
726 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
727 "use basic POSIX regular expressions (default)",
728 REG_EXTENDED),
729 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
730 "interpret patterns as fixed strings"),
731 OPT_GROUP(""),
732 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
733 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
734 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
735 OPT_NEGBIT(0, "full-name", &opt.relative,
736 "show filenames relative to top directory", 1),
737 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
738 "show only filenames instead of matching lines"),
739 OPT_BOOLEAN(0, "name-only", &opt.name_only,
740 "synonym for --files-with-matches"),
741 OPT_BOOLEAN('L', "files-without-match",
742 &opt.unmatch_name_only,
743 "show only the names of files without match"),
744 OPT_BOOLEAN('z', "null", &opt.null_following_name,
745 "print NUL after filenames"),
746 OPT_BOOLEAN('c', "count", &opt.count,
747 "show the number of matches instead of matching lines"),
748 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
749 OPT_GROUP(""),
750 OPT_CALLBACK('C', NULL, &opt, "n",
751 "show <n> context lines before and after matches",
752 context_callback),
753 OPT_INTEGER('B', NULL, &opt.pre_context,
754 "show <n> context lines before matches"),
755 OPT_INTEGER('A', NULL, &opt.post_context,
756 "show <n> context lines after matches"),
757 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
758 context_callback),
759 OPT_BOOLEAN('p', "show-function", &opt.funcname,
760 "show a line with the function name before matches"),
761 OPT_GROUP(""),
762 OPT_CALLBACK('f', NULL, &opt, "file",
763 "read patterns from file", file_callback),
764 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
765 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
766 { OPTION_CALLBACK, 0, "and", &opt, NULL,
767 "combine patterns specified with -e",
768 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
769 OPT_BOOLEAN(0, "or", &dummy, ""),
770 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
771 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
772 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
773 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
774 open_callback },
775 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
776 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
777 close_callback },
778 OPT_BOOLEAN(0, "all-match", &opt.all_match,
779 "show only matches from files that match all patterns"),
780 OPT_GROUP(""),
781 #if NO_EXTERNAL_GREP
782 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
783 "allow calling of grep(1) (ignored by this build)"),
784 #else
785 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
786 "allow calling of grep(1) (default)"),
787 #endif
788 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
789 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
790 OPT_END()
794 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
795 * to show usage information and exit.
797 if (argc == 2 && !strcmp(argv[1], "-h"))
798 usage_with_options(grep_usage, options);
800 memset(&opt, 0, sizeof(opt));
801 opt.prefix = prefix;
802 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
803 opt.relative = 1;
804 opt.pathname = 1;
805 opt.pattern_tail = &opt.pattern_list;
806 opt.regflags = REG_NEWLINE;
807 opt.max_depth = -1;
809 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
810 opt.color = -1;
811 git_config(grep_config, &opt);
812 if (opt.color == -1)
813 opt.color = git_use_color_default;
816 * If there is no -- then the paths must exist in the working
817 * tree. If there is no explicit pattern specified with -e or
818 * -f, we take the first unrecognized non option to be the
819 * pattern, but then what follows it must be zero or more
820 * valid refs up to the -- (if exists), and then existing
821 * paths. If there is an explicit pattern, then the first
822 * unrecognized non option is the beginning of the refs list
823 * that continues up to the -- (if exists), and then paths.
825 argc = parse_options(argc, argv, prefix, options, grep_usage,
826 PARSE_OPT_KEEP_DASHDASH |
827 PARSE_OPT_STOP_AT_NON_OPTION |
828 PARSE_OPT_NO_INTERNAL_HELP);
830 /* First unrecognized non-option token */
831 if (argc > 0 && !opt.pattern_list) {
832 append_grep_pattern(&opt, argv[0], "command line", 0,
833 GREP_PATTERN);
834 argv++;
835 argc--;
838 if ((opt.color && !opt.color_external) || opt.funcname)
839 external_grep_allowed = 0;
840 if (!opt.pattern_list)
841 die("no pattern given.");
842 if (!opt.fixed && opt.ignore_case)
843 opt.regflags |= REG_ICASE;
844 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
845 die("cannot mix --fixed-strings and regexp");
846 compile_grep_patterns(&opt);
848 /* Check revs and then paths */
849 for (i = 0; i < argc; i++) {
850 const char *arg = argv[i];
851 unsigned char sha1[20];
852 /* Is it a rev? */
853 if (!get_sha1(arg, sha1)) {
854 struct object *object = parse_object(sha1);
855 if (!object)
856 die("bad object %s", arg);
857 add_object_array(object, arg, &list);
858 continue;
860 if (!strcmp(arg, "--")) {
861 i++;
862 seen_dashdash = 1;
864 break;
867 /* The rest are paths */
868 if (!seen_dashdash) {
869 int j;
870 for (j = i; j < argc; j++)
871 verify_filename(prefix, argv[j]);
874 if (i < argc)
875 paths = get_pathspec(prefix, argv + i);
876 else if (prefix) {
877 paths = xcalloc(2, sizeof(const char *));
878 paths[0] = prefix;
879 paths[1] = NULL;
882 if (!list.nr) {
883 if (!cached)
884 setup_work_tree();
885 return !grep_cache(&opt, paths, cached, external_grep_allowed);
888 if (cached)
889 die("both --cached and trees are given.");
891 for (i = 0; i < list.nr; i++) {
892 struct object *real_obj;
893 real_obj = deref_tag(list.objects[i].item, NULL, 0);
894 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
895 hit = 1;
897 free_grep_patterns(&opt);
898 return !hit;