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