git grep -O -i: if the pager is 'less', pass the '-i' option
[git/mingw/4msysgit.git] / builtin / grep.c
blob3af417e76c60550ab48bb19e8e21f7e8af175656
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 "string-list.h"
15 #include "run-command.h"
16 #include "userdiff.h"
17 #include "grep.h"
18 #include "quote.h"
19 #include "dir.h"
20 #include "attr.h"
22 static char const * const grep_usage[] = {
23 "git grep [options] [-e] <pattern> [<rev>...] [[--] <path>...]",
24 NULL
27 static int use_threads = 1;
29 #ifndef NO_PTHREADS
30 #define THREADS 8
31 static pthread_t threads[THREADS];
33 /* We use one producer thread and THREADS consumer
34 * threads. The producer adds struct work_items to 'todo' and the
35 * consumers pick work items from the same array.
37 struct work_item {
38 struct grep_source source;
39 char done;
40 struct strbuf out;
43 /* In the range [todo_done, todo_start) in 'todo' we have work_items
44 * that have been or are processed by a consumer thread. We haven't
45 * written the result for these to stdout yet.
47 * The work_items in [todo_start, todo_end) are waiting to be picked
48 * up by a consumer thread.
50 * The ranges are modulo TODO_SIZE.
52 #define TODO_SIZE 128
53 static struct work_item todo[TODO_SIZE];
54 static int todo_start;
55 static int todo_end;
56 static int todo_done;
58 /* Has all work items been added? */
59 static int all_work_added;
61 /* This lock protects all the variables above. */
62 static pthread_mutex_t grep_mutex;
64 static inline void grep_lock(void)
66 if (use_threads)
67 pthread_mutex_lock(&grep_mutex);
70 static inline void grep_unlock(void)
72 if (use_threads)
73 pthread_mutex_unlock(&grep_mutex);
76 /* Signalled when a new work_item is added to todo. */
77 static pthread_cond_t cond_add;
79 /* Signalled when the result from one work_item is written to
80 * stdout.
82 static pthread_cond_t cond_write;
84 /* Signalled when we are finished with everything. */
85 static pthread_cond_t cond_result;
87 static int skip_first_line;
89 static void add_work(struct grep_opt *opt, enum grep_source_type type,
90 const char *name, const void *id)
92 grep_lock();
94 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
95 pthread_cond_wait(&cond_write, &grep_mutex);
98 grep_source_init(&todo[todo_end].source, type, name, id);
99 if (opt->binary != GREP_BINARY_TEXT)
100 grep_source_load_driver(&todo[todo_end].source);
101 todo[todo_end].done = 0;
102 strbuf_reset(&todo[todo_end].out);
103 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
105 pthread_cond_signal(&cond_add);
106 grep_unlock();
109 static struct work_item *get_work(void)
111 struct work_item *ret;
113 grep_lock();
114 while (todo_start == todo_end && !all_work_added) {
115 pthread_cond_wait(&cond_add, &grep_mutex);
118 if (todo_start == todo_end && all_work_added) {
119 ret = NULL;
120 } else {
121 ret = &todo[todo_start];
122 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
124 grep_unlock();
125 return ret;
128 static void work_done(struct work_item *w)
130 int old_done;
132 grep_lock();
133 w->done = 1;
134 old_done = todo_done;
135 for(; todo[todo_done].done && todo_done != todo_start;
136 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
137 w = &todo[todo_done];
138 if (w->out.len) {
139 const char *p = w->out.buf;
140 size_t len = w->out.len;
142 /* Skip the leading hunk mark of the first file. */
143 if (skip_first_line) {
144 while (len) {
145 len--;
146 if (*p++ == '\n')
147 break;
149 skip_first_line = 0;
152 write_or_die(1, p, len);
154 grep_source_clear(&w->source);
157 if (old_done != todo_done)
158 pthread_cond_signal(&cond_write);
160 if (all_work_added && todo_done == todo_end)
161 pthread_cond_signal(&cond_result);
163 grep_unlock();
166 static int skip_binary(struct grep_opt *opt, const char *filename)
168 if ((opt->binary & GREP_BINARY_NOMATCH)) {
169 static struct git_attr *attr_text;
170 struct git_attr_check check;
172 if (!attr_text)
173 attr_text = git_attr("text");
174 memset(&check, 0, sizeof(check));
175 check.attr = attr_text;
176 return !git_check_attr(filename, 1, &check) &&
177 ATTR_FALSE(check.value);
179 return 0;
182 static void *run(void *arg)
184 int hit = 0;
185 struct grep_opt *opt = arg;
187 while (1) {
188 struct work_item *w = get_work();
189 if (!w)
190 break;
192 if (skip_binary(opt, (const char *)w->source.identifier))
193 continue;
195 opt->output_priv = w;
196 hit |= grep_source(opt, &w->source);
197 grep_source_clear_data(&w->source);
198 work_done(w);
200 free_grep_patterns(arg);
201 free(arg);
203 return (void*) (intptr_t) hit;
206 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
208 struct work_item *w = opt->output_priv;
209 strbuf_add(&w->out, buf, size);
212 static void start_threads(struct grep_opt *opt)
214 int i;
216 pthread_mutex_init(&grep_mutex, NULL);
217 pthread_mutex_init(&grep_read_mutex, NULL);
218 pthread_mutex_init(&grep_attr_mutex, NULL);
219 pthread_cond_init(&cond_add, NULL);
220 pthread_cond_init(&cond_write, NULL);
221 pthread_cond_init(&cond_result, NULL);
222 grep_use_locks = 1;
224 for (i = 0; i < ARRAY_SIZE(todo); i++) {
225 strbuf_init(&todo[i].out, 0);
228 for (i = 0; i < ARRAY_SIZE(threads); i++) {
229 int err;
230 struct grep_opt *o = grep_opt_dup(opt);
231 o->output = strbuf_out;
232 compile_grep_patterns(o);
233 err = pthread_create(&threads[i], NULL, run, o);
235 if (err)
236 die(_("grep: failed to create thread: %s"),
237 strerror(err));
241 static int wait_all(void)
243 int hit = 0;
244 int i;
246 grep_lock();
247 all_work_added = 1;
249 /* Wait until all work is done. */
250 while (todo_done != todo_end)
251 pthread_cond_wait(&cond_result, &grep_mutex);
253 /* Wake up all the consumer threads so they can see that there
254 * is no more work to do.
256 pthread_cond_broadcast(&cond_add);
257 grep_unlock();
259 for (i = 0; i < ARRAY_SIZE(threads); i++) {
260 void *h;
261 pthread_join(threads[i], &h);
262 hit |= (int) (intptr_t) h;
265 pthread_mutex_destroy(&grep_mutex);
266 pthread_mutex_destroy(&grep_read_mutex);
267 pthread_mutex_destroy(&grep_attr_mutex);
268 pthread_cond_destroy(&cond_add);
269 pthread_cond_destroy(&cond_write);
270 pthread_cond_destroy(&cond_result);
271 grep_use_locks = 0;
273 return hit;
275 #else /* !NO_PTHREADS */
277 static int wait_all(void)
279 return 0;
281 #endif
283 static int grep_config(const char *var, const char *value, void *cb)
285 struct grep_opt *opt = cb;
286 char *color = NULL;
288 if (userdiff_config(var, value) < 0)
289 return -1;
291 if (!strcmp(var, "grep.extendedregexp")) {
292 if (git_config_bool(var, value))
293 opt->regflags |= REG_EXTENDED;
294 else
295 opt->regflags &= ~REG_EXTENDED;
296 return 0;
299 if (!strcmp(var, "grep.linenumber")) {
300 opt->linenum = git_config_bool(var, value);
301 return 0;
304 if (!strcmp(var, "color.grep"))
305 opt->color = git_config_colorbool(var, value);
306 else if (!strcmp(var, "color.grep.context"))
307 color = opt->color_context;
308 else if (!strcmp(var, "color.grep.filename"))
309 color = opt->color_filename;
310 else if (!strcmp(var, "color.grep.function"))
311 color = opt->color_function;
312 else if (!strcmp(var, "color.grep.linenumber"))
313 color = opt->color_lineno;
314 else if (!strcmp(var, "color.grep.match"))
315 color = opt->color_match;
316 else if (!strcmp(var, "color.grep.selected"))
317 color = opt->color_selected;
318 else if (!strcmp(var, "color.grep.separator"))
319 color = opt->color_sep;
320 else
321 return git_color_default_config(var, value, cb);
322 if (color) {
323 if (!value)
324 return config_error_nonbool(var);
325 color_parse(value, var, color);
327 return 0;
330 static void *lock_and_read_sha1_file(const unsigned char *sha1, enum object_type *type, unsigned long *size)
332 void *data;
334 grep_read_lock();
335 data = read_sha1_file(sha1, type, size);
336 grep_read_unlock();
337 return data;
340 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1,
341 const char *filename, int tree_name_len)
343 struct strbuf pathbuf = STRBUF_INIT;
345 if (opt->relative && opt->prefix_length) {
346 quote_path_relative(filename + tree_name_len, -1, &pathbuf,
347 opt->prefix);
348 strbuf_insert(&pathbuf, 0, filename, tree_name_len);
349 } else {
350 strbuf_addstr(&pathbuf, filename);
353 #ifndef NO_PTHREADS
354 if (use_threads) {
355 add_work(opt, GREP_SOURCE_SHA1, pathbuf.buf, sha1);
356 strbuf_release(&pathbuf);
357 return 0;
358 } else
359 #endif
361 struct grep_source gs;
362 int hit;
364 grep_source_init(&gs, GREP_SOURCE_SHA1, pathbuf.buf, sha1);
365 strbuf_release(&pathbuf);
366 hit = grep_source(opt, &gs);
368 grep_source_clear(&gs);
369 return hit;
373 static int grep_file(struct grep_opt *opt, const char *filename)
375 struct strbuf buf = STRBUF_INIT;
377 if (opt->relative && opt->prefix_length)
378 quote_path_relative(filename, -1, &buf, opt->prefix);
379 else
380 strbuf_addstr(&buf, filename);
382 #ifndef NO_PTHREADS
383 if (use_threads) {
384 add_work(opt, GREP_SOURCE_FILE, buf.buf, filename);
385 strbuf_release(&buf);
386 return 0;
387 } else
388 #endif
390 struct grep_source gs;
391 int hit;
393 grep_source_init(&gs, GREP_SOURCE_FILE, buf.buf, filename);
394 strbuf_release(&buf);
395 hit = grep_source(opt, &gs);
397 grep_source_clear(&gs);
398 return hit;
402 static void append_path(struct grep_opt *opt, const void *data, size_t len)
404 struct string_list *path_list = opt->output_priv;
406 if (len == 1 && *(const char *)data == '\0')
407 return;
408 string_list_append(path_list, xstrndup(data, len));
411 static void run_pager(struct grep_opt *opt, const char *prefix)
413 struct string_list *path_list = opt->output_priv;
414 const char **argv = xmalloc(sizeof(const char *) * (path_list->nr + 1));
415 int i, status;
417 for (i = 0; i < path_list->nr; i++)
418 argv[i] = path_list->items[i].string;
419 argv[path_list->nr] = NULL;
421 if (prefix && chdir(prefix))
422 die(_("Failed to chdir: %s"), prefix);
423 status = run_command_v_opt(argv, RUN_USING_SHELL);
424 if (status)
425 exit(status);
426 free(argv);
429 static int grep_cache(struct grep_opt *opt, const struct pathspec *pathspec, int cached)
431 int hit = 0;
432 int nr;
433 read_cache();
435 for (nr = 0; nr < active_nr; nr++) {
436 struct cache_entry *ce = active_cache[nr];
437 if (!S_ISREG(ce->ce_mode))
438 continue;
439 if (!match_pathspec_depth(pathspec, ce->name, ce_namelen(ce), 0, NULL))
440 continue;
441 if (skip_binary(opt, ce->name))
442 continue;
445 * If CE_VALID is on, we assume worktree file and its cache entry
446 * are identical, even if worktree file has been modified, so use
447 * cache version instead
449 if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
450 if (ce_stage(ce))
451 continue;
452 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
454 else
455 hit |= grep_file(opt, ce->name);
456 if (ce_stage(ce)) {
457 do {
458 nr++;
459 } while (nr < active_nr &&
460 !strcmp(ce->name, active_cache[nr]->name));
461 nr--; /* compensate for loop control */
463 if (hit && opt->status_only)
464 break;
466 return hit;
469 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
470 struct tree_desc *tree, struct strbuf *base, int tn_len)
472 int hit = 0;
473 enum interesting match = entry_not_interesting;
474 struct name_entry entry;
475 int old_baselen = base->len;
477 while (tree_entry(tree, &entry)) {
478 int te_len = tree_entry_len(&entry);
480 if (match != all_entries_interesting) {
481 match = tree_entry_interesting(&entry, base, tn_len, pathspec);
482 if (match == all_entries_not_interesting)
483 break;
484 if (match == entry_not_interesting)
485 continue;
488 strbuf_add(base, entry.path, te_len);
490 if (S_ISREG(entry.mode)) {
491 hit |= grep_sha1(opt, entry.sha1, base->buf, tn_len);
493 else if (S_ISDIR(entry.mode)) {
494 enum object_type type;
495 struct tree_desc sub;
496 void *data;
497 unsigned long size;
499 data = lock_and_read_sha1_file(entry.sha1, &type, &size);
500 if (!data)
501 die(_("unable to read tree (%s)"),
502 sha1_to_hex(entry.sha1));
504 strbuf_addch(base, '/');
505 init_tree_desc(&sub, data, size);
506 hit |= grep_tree(opt, pathspec, &sub, base, tn_len);
507 free(data);
509 strbuf_setlen(base, old_baselen);
511 if (hit && opt->status_only)
512 break;
514 return hit;
517 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
518 struct object *obj, const char *name)
520 if (obj->type == OBJ_BLOB)
521 return grep_sha1(opt, obj->sha1, name, 0);
522 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
523 struct tree_desc tree;
524 void *data;
525 unsigned long size;
526 struct strbuf base;
527 int hit, len;
529 grep_read_lock();
530 data = read_object_with_reference(obj->sha1, tree_type,
531 &size, NULL);
532 grep_read_unlock();
534 if (!data)
535 die(_("unable to read tree (%s)"), sha1_to_hex(obj->sha1));
537 len = name ? strlen(name) : 0;
538 strbuf_init(&base, PATH_MAX + len + 1);
539 if (len) {
540 strbuf_add(&base, name, len);
541 strbuf_addch(&base, ':');
543 init_tree_desc(&tree, data, size);
544 hit = grep_tree(opt, pathspec, &tree, &base, base.len);
545 strbuf_release(&base);
546 free(data);
547 return hit;
549 die(_("unable to grep from object of type %s"), typename(obj->type));
552 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
553 const struct object_array *list)
555 unsigned int i;
556 int hit = 0;
557 const unsigned int nr = list->nr;
559 for (i = 0; i < nr; i++) {
560 struct object *real_obj;
561 real_obj = deref_tag(list->objects[i].item, NULL, 0);
562 if (grep_object(opt, pathspec, real_obj, list->objects[i].name)) {
563 hit = 1;
564 if (opt->status_only)
565 break;
568 return hit;
571 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
572 int exc_std)
574 struct dir_struct dir;
575 int i, hit = 0;
577 memset(&dir, 0, sizeof(dir));
578 if (exc_std)
579 setup_standard_excludes(&dir);
581 fill_directory(&dir, pathspec->raw);
582 for (i = 0; i < dir.nr; i++) {
583 const char *name = dir.entries[i]->name;
584 int namelen = strlen(name);
585 if (!match_pathspec_depth(pathspec, name, namelen, 0, NULL))
586 continue;
587 hit |= grep_file(opt, dir.entries[i]->name);
588 if (hit && opt->status_only)
589 break;
591 return hit;
594 static int context_callback(const struct option *opt, const char *arg,
595 int unset)
597 struct grep_opt *grep_opt = opt->value;
598 int value;
599 const char *endp;
601 if (unset) {
602 grep_opt->pre_context = grep_opt->post_context = 0;
603 return 0;
605 value = strtol(arg, (char **)&endp, 10);
606 if (*endp) {
607 return error(_("switch `%c' expects a numerical value"),
608 opt->short_name);
610 grep_opt->pre_context = grep_opt->post_context = value;
611 return 0;
614 static int file_callback(const struct option *opt, const char *arg, int unset)
616 struct grep_opt *grep_opt = opt->value;
617 int from_stdin = !strcmp(arg, "-");
618 FILE *patterns;
619 int lno = 0;
620 struct strbuf sb = STRBUF_INIT;
622 patterns = from_stdin ? stdin : fopen(arg, "r");
623 if (!patterns)
624 die_errno(_("cannot open '%s'"), arg);
625 while (strbuf_getline(&sb, patterns, '\n') == 0) {
626 char *s;
627 size_t len;
629 /* ignore empty line like grep does */
630 if (sb.len == 0)
631 continue;
633 s = strbuf_detach(&sb, &len);
634 append_grep_pat(grep_opt, s, len, arg, ++lno, GREP_PATTERN);
636 if (!from_stdin)
637 fclose(patterns);
638 strbuf_release(&sb);
639 return 0;
642 static int not_callback(const struct option *opt, const char *arg, int unset)
644 struct grep_opt *grep_opt = opt->value;
645 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
646 return 0;
649 static int and_callback(const struct option *opt, const char *arg, int unset)
651 struct grep_opt *grep_opt = opt->value;
652 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
653 return 0;
656 static int open_callback(const struct option *opt, const char *arg, int unset)
658 struct grep_opt *grep_opt = opt->value;
659 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
660 return 0;
663 static int close_callback(const struct option *opt, const char *arg, int unset)
665 struct grep_opt *grep_opt = opt->value;
666 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
667 return 0;
670 static int pattern_callback(const struct option *opt, const char *arg,
671 int unset)
673 struct grep_opt *grep_opt = opt->value;
674 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
675 return 0;
678 static int help_callback(const struct option *opt, const char *arg, int unset)
680 return -1;
683 int cmd_grep(int argc, const char **argv, const char *prefix)
685 int hit = 0;
686 int cached = 0, untracked = 0, opt_exclude = -1;
687 int seen_dashdash = 0;
688 int external_grep_allowed__ignored;
689 const char *show_in_pager = NULL, *default_pager = "dummy";
690 struct grep_opt opt;
691 struct object_array list = OBJECT_ARRAY_INIT;
692 const char **paths = NULL;
693 struct pathspec pathspec;
694 struct string_list path_list = STRING_LIST_INIT_NODUP;
695 int i;
696 int dummy;
697 int use_index = 1;
698 enum {
699 pattern_type_unspecified = 0,
700 pattern_type_bre,
701 pattern_type_ere,
702 pattern_type_fixed,
703 pattern_type_pcre,
705 int pattern_type = pattern_type_unspecified;
707 struct option options[] = {
708 OPT_BOOLEAN(0, "cached", &cached,
709 "search in index instead of in the work tree"),
710 OPT_NEGBIT(0, "no-index", &use_index,
711 "finds in contents not managed by git", 1),
712 OPT_BOOLEAN(0, "untracked", &untracked,
713 "search in both tracked and untracked files"),
714 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
715 "search also in ignored files", 1),
716 OPT_GROUP(""),
717 OPT_BOOLEAN('v', "invert-match", &opt.invert,
718 "show non-matching lines"),
719 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
720 "case insensitive matching"),
721 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
722 "match patterns only at word boundaries"),
723 OPT_SET_INT('a', "text", &opt.binary,
724 "process binary files as text", GREP_BINARY_TEXT),
725 OPT_SET_INT('I', NULL, &opt.binary,
726 "don't match patterns in binary files",
727 GREP_BINARY_NOMATCH),
728 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
729 "descend at most <depth> levels", PARSE_OPT_NONEG,
730 NULL, 1 },
731 OPT_GROUP(""),
732 OPT_SET_INT('E', "extended-regexp", &pattern_type,
733 "use extended POSIX regular expressions",
734 pattern_type_ere),
735 OPT_SET_INT('G', "basic-regexp", &pattern_type,
736 "use basic POSIX regular expressions (default)",
737 pattern_type_bre),
738 OPT_SET_INT('F', "fixed-strings", &pattern_type,
739 "interpret patterns as fixed strings",
740 pattern_type_fixed),
741 OPT_SET_INT('P', "perl-regexp", &pattern_type,
742 "use Perl-compatible regular expressions",
743 pattern_type_pcre),
744 OPT_GROUP(""),
745 OPT_BOOLEAN('n', "line-number", &opt.linenum, "show line numbers"),
746 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
747 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
748 OPT_NEGBIT(0, "full-name", &opt.relative,
749 "show filenames relative to top directory", 1),
750 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
751 "show only filenames instead of matching lines"),
752 OPT_BOOLEAN(0, "name-only", &opt.name_only,
753 "synonym for --files-with-matches"),
754 OPT_BOOLEAN('L', "files-without-match",
755 &opt.unmatch_name_only,
756 "show only the names of files without match"),
757 OPT_BOOLEAN('z', "null", &opt.null_following_name,
758 "print NUL after filenames"),
759 OPT_BOOLEAN('c', "count", &opt.count,
760 "show the number of matches instead of matching lines"),
761 OPT__COLOR(&opt.color, "highlight matches"),
762 OPT_BOOLEAN(0, "break", &opt.file_break,
763 "print empty line between matches from different files"),
764 OPT_BOOLEAN(0, "heading", &opt.heading,
765 "show filename only once above matches from same file"),
766 OPT_GROUP(""),
767 OPT_CALLBACK('C', "context", &opt, "n",
768 "show <n> context lines before and after matches",
769 context_callback),
770 OPT_INTEGER('B', "before-context", &opt.pre_context,
771 "show <n> context lines before matches"),
772 OPT_INTEGER('A', "after-context", &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_BOOLEAN('W', "function-context", &opt.funcbody,
779 "show the surrounding function"),
780 OPT_GROUP(""),
781 OPT_CALLBACK('f', NULL, &opt, "file",
782 "read patterns from file", file_callback),
783 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
784 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
785 { OPTION_CALLBACK, 0, "and", &opt, NULL,
786 "combine patterns specified with -e",
787 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
788 OPT_BOOLEAN(0, "or", &dummy, ""),
789 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
790 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
791 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
792 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
793 open_callback },
794 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
795 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
796 close_callback },
797 OPT__QUIET(&opt.status_only,
798 "indicate hit with exit status without output"),
799 OPT_BOOLEAN(0, "all-match", &opt.all_match,
800 "show only matches from files that match all patterns"),
801 OPT_GROUP(""),
802 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
803 "pager", "show matching files in the pager",
804 PARSE_OPT_OPTARG, NULL, (intptr_t)default_pager },
805 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
806 "allow calling of grep(1) (ignored by this build)"),
807 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
808 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
809 OPT_END()
813 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
814 * to show usage information and exit.
816 if (argc == 2 && !strcmp(argv[1], "-h"))
817 usage_with_options(grep_usage, options);
819 memset(&opt, 0, sizeof(opt));
820 opt.prefix = prefix;
821 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
822 opt.relative = 1;
823 opt.pathname = 1;
824 opt.pattern_tail = &opt.pattern_list;
825 opt.header_tail = &opt.header_list;
826 opt.regflags = REG_NEWLINE;
827 opt.max_depth = -1;
829 strcpy(opt.color_context, "");
830 strcpy(opt.color_filename, "");
831 strcpy(opt.color_function, "");
832 strcpy(opt.color_lineno, "");
833 strcpy(opt.color_match, GIT_COLOR_BOLD_RED);
834 strcpy(opt.color_selected, "");
835 strcpy(opt.color_sep, GIT_COLOR_CYAN);
836 opt.color = -1;
837 git_config(grep_config, &opt);
840 * If there is no -- then the paths must exist in the working
841 * tree. If there is no explicit pattern specified with -e or
842 * -f, we take the first unrecognized non option to be the
843 * pattern, but then what follows it must be zero or more
844 * valid refs up to the -- (if exists), and then existing
845 * paths. If there is an explicit pattern, then the first
846 * unrecognized non option is the beginning of the refs list
847 * that continues up to the -- (if exists), and then paths.
849 argc = parse_options(argc, argv, prefix, options, grep_usage,
850 PARSE_OPT_KEEP_DASHDASH |
851 PARSE_OPT_STOP_AT_NON_OPTION |
852 PARSE_OPT_NO_INTERNAL_HELP);
853 switch (pattern_type) {
854 case pattern_type_fixed:
855 opt.fixed = 1;
856 opt.pcre = 0;
857 break;
858 case pattern_type_bre:
859 opt.fixed = 0;
860 opt.pcre = 0;
861 opt.regflags &= ~REG_EXTENDED;
862 break;
863 case pattern_type_ere:
864 opt.fixed = 0;
865 opt.pcre = 0;
866 opt.regflags |= REG_EXTENDED;
867 break;
868 case pattern_type_pcre:
869 opt.fixed = 0;
870 opt.pcre = 1;
871 break;
872 default:
873 break; /* nothing */
876 if (use_index && !startup_info->have_repository)
877 /* die the same way as if we did it at the beginning */
878 setup_git_directory();
881 * skip a -- separator; we know it cannot be
882 * separating revisions from pathnames if
883 * we haven't even had any patterns yet
885 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
886 argv++;
887 argc--;
890 /* First unrecognized non-option token */
891 if (argc > 0 && !opt.pattern_list) {
892 append_grep_pattern(&opt, argv[0], "command line", 0,
893 GREP_PATTERN);
894 argv++;
895 argc--;
898 if (show_in_pager == default_pager)
899 show_in_pager = git_pager(1);
900 if (show_in_pager) {
901 opt.color = 0;
902 opt.name_only = 1;
903 opt.null_following_name = 1;
904 opt.output_priv = &path_list;
905 opt.output = append_path;
906 string_list_append(&path_list, show_in_pager);
907 use_threads = 0;
909 if ((opt.binary & GREP_BINARY_NOMATCH))
910 use_threads = 0;
912 if (!opt.pattern_list)
913 die(_("no pattern given."));
914 if (!opt.fixed && opt.ignore_case)
915 opt.regflags |= REG_ICASE;
917 compile_grep_patterns(&opt);
919 /* Check revs and then paths */
920 for (i = 0; i < argc; i++) {
921 const char *arg = argv[i];
922 unsigned char sha1[20];
923 /* Is it a rev? */
924 if (!get_sha1(arg, sha1)) {
925 struct object *object = parse_object(sha1);
926 if (!object)
927 die(_("bad object %s"), arg);
928 add_object_array(object, arg, &list);
929 continue;
931 if (!strcmp(arg, "--")) {
932 i++;
933 seen_dashdash = 1;
935 break;
938 #ifndef NO_PTHREADS
939 if (list.nr || cached || online_cpus() == 1)
940 use_threads = 0;
941 #else
942 use_threads = 0;
943 #endif
945 #ifndef NO_PTHREADS
946 if (use_threads) {
947 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
948 && (opt.pre_context || opt.post_context ||
949 opt.file_break || opt.funcbody))
950 skip_first_line = 1;
951 start_threads(&opt);
953 #endif
955 /* The rest are paths */
956 if (!seen_dashdash) {
957 int j;
958 for (j = i; j < argc; j++)
959 verify_filename(prefix, argv[j]);
962 paths = get_pathspec(prefix, argv + i);
963 init_pathspec(&pathspec, paths);
964 pathspec.max_depth = opt.max_depth;
965 pathspec.recursive = 1;
967 if (show_in_pager && (cached || list.nr))
968 die(_("--open-files-in-pager only works on the worktree"));
970 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
971 const char *pager = path_list.items[0].string;
972 int len = strlen(pager);
974 if (len > 4 && is_dir_sep(pager[len - 5]))
975 pager += len - 4;
977 if (opt.ignore_case && !strcmp("less", pager))
978 string_list_append(&path_list, "-i");
980 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
981 struct strbuf buf = STRBUF_INIT;
982 strbuf_addf(&buf, "+/%s%s",
983 strcmp("less", pager) ? "" : "*",
984 opt.pattern_list->pattern);
985 string_list_append(&path_list, buf.buf);
986 strbuf_detach(&buf, NULL);
990 if (!show_in_pager)
991 setup_pager();
993 if (!use_index && (untracked || cached))
994 die(_("--cached or --untracked cannot be used with --no-index."));
996 if (!use_index || untracked) {
997 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
998 if (list.nr)
999 die(_("--no-index or --untracked cannot be used with revs."));
1000 hit = grep_directory(&opt, &pathspec, use_exclude);
1001 } else if (0 <= opt_exclude) {
1002 die(_("--[no-]exclude-standard cannot be used for tracked contents."));
1003 } else if (!list.nr) {
1004 if (!cached)
1005 setup_work_tree();
1007 hit = grep_cache(&opt, &pathspec, cached);
1008 } else {
1009 if (cached)
1010 die(_("both --cached and trees are given."));
1011 hit = grep_objects(&opt, &pathspec, &list);
1014 if (use_threads)
1015 hit |= wait_all();
1016 if (hit && show_in_pager)
1017 run_pager(&opt, prefix);
1018 free_grep_patterns(&opt);
1019 return !hit;