remote-testgit: factor out RemoteHelper class
[git/dscho.git] / builtin / grep.c
blobea3323acbf8b2a3ad2d452a0261d5dd24fba73d9
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 N_("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 o->debug = 0;
233 compile_grep_patterns(o);
234 err = pthread_create(&threads[i], NULL, run, o);
236 if (err)
237 die(_("grep: failed to create thread: %s"),
238 strerror(err));
242 static int wait_all(void)
244 int hit = 0;
245 int i;
247 grep_lock();
248 all_work_added = 1;
250 /* Wait until all work is done. */
251 while (todo_done != todo_end)
252 pthread_cond_wait(&cond_result, &grep_mutex);
254 /* Wake up all the consumer threads so they can see that there
255 * is no more work to do.
257 pthread_cond_broadcast(&cond_add);
258 grep_unlock();
260 for (i = 0; i < ARRAY_SIZE(threads); i++) {
261 void *h;
262 pthread_join(threads[i], &h);
263 hit |= (int) (intptr_t) h;
266 pthread_mutex_destroy(&grep_mutex);
267 pthread_mutex_destroy(&grep_read_mutex);
268 pthread_mutex_destroy(&grep_attr_mutex);
269 pthread_cond_destroy(&cond_add);
270 pthread_cond_destroy(&cond_write);
271 pthread_cond_destroy(&cond_result);
272 grep_use_locks = 0;
274 return hit;
276 #else /* !NO_PTHREADS */
278 static int wait_all(void)
280 return 0;
282 #endif
284 static int parse_pattern_type_arg(const char *opt, const char *arg)
286 if (!strcmp(arg, "default"))
287 return GREP_PATTERN_TYPE_UNSPECIFIED;
288 else if (!strcmp(arg, "basic"))
289 return GREP_PATTERN_TYPE_BRE;
290 else if (!strcmp(arg, "extended"))
291 return GREP_PATTERN_TYPE_ERE;
292 else if (!strcmp(arg, "fixed"))
293 return GREP_PATTERN_TYPE_FIXED;
294 else if (!strcmp(arg, "perl"))
295 return GREP_PATTERN_TYPE_PCRE;
296 die("bad %s argument: %s", opt, arg);
299 static void grep_pattern_type_options(const int pattern_type, struct grep_opt *opt)
301 switch (pattern_type) {
302 case GREP_PATTERN_TYPE_UNSPECIFIED:
303 /* fall through */
305 case GREP_PATTERN_TYPE_BRE:
306 opt->fixed = 0;
307 opt->pcre = 0;
308 opt->regflags &= ~REG_EXTENDED;
309 break;
311 case GREP_PATTERN_TYPE_ERE:
312 opt->fixed = 0;
313 opt->pcre = 0;
314 opt->regflags |= REG_EXTENDED;
315 break;
317 case GREP_PATTERN_TYPE_FIXED:
318 opt->fixed = 1;
319 opt->pcre = 0;
320 opt->regflags &= ~REG_EXTENDED;
321 break;
323 case GREP_PATTERN_TYPE_PCRE:
324 opt->fixed = 0;
325 opt->pcre = 1;
326 opt->regflags &= ~REG_EXTENDED;
327 break;
331 static int grep_config(const char *var, const char *value, void *cb)
333 struct grep_opt *opt = cb;
334 char *color = NULL;
336 if (userdiff_config(var, value) < 0)
337 return -1;
339 if (!strcmp(var, "grep.extendedregexp")) {
340 if (git_config_bool(var, value))
341 opt->extended_regexp_option = 1;
342 else
343 opt->extended_regexp_option = 0;
344 return 0;
347 if (!strcmp(var, "grep.patterntype")) {
348 opt->pattern_type_option = parse_pattern_type_arg(var, value);
349 return 0;
352 if (!strcmp(var, "grep.linenumber")) {
353 opt->linenum = git_config_bool(var, value);
354 return 0;
357 if (!strcmp(var, "color.grep"))
358 opt->color = git_config_colorbool(var, value);
359 else if (!strcmp(var, "color.grep.context"))
360 color = opt->color_context;
361 else if (!strcmp(var, "color.grep.filename"))
362 color = opt->color_filename;
363 else if (!strcmp(var, "color.grep.function"))
364 color = opt->color_function;
365 else if (!strcmp(var, "color.grep.linenumber"))
366 color = opt->color_lineno;
367 else if (!strcmp(var, "color.grep.match"))
368 color = opt->color_match;
369 else if (!strcmp(var, "color.grep.selected"))
370 color = opt->color_selected;
371 else if (!strcmp(var, "color.grep.separator"))
372 color = opt->color_sep;
373 else
374 return git_color_default_config(var, value, cb);
375 if (color) {
376 if (!value)
377 return config_error_nonbool(var);
378 color_parse(value, var, color);
380 return 0;
383 static void *lock_and_read_sha1_file(const unsigned char *sha1, enum object_type *type, unsigned long *size)
385 void *data;
387 grep_read_lock();
388 data = read_sha1_file(sha1, type, size);
389 grep_read_unlock();
390 return data;
393 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1,
394 const char *filename, int tree_name_len)
396 struct strbuf pathbuf = STRBUF_INIT;
398 if (opt->relative && opt->prefix_length) {
399 quote_path_relative(filename + tree_name_len, -1, &pathbuf,
400 opt->prefix);
401 strbuf_insert(&pathbuf, 0, filename, tree_name_len);
402 } else {
403 strbuf_addstr(&pathbuf, filename);
406 #ifndef NO_PTHREADS
407 if (use_threads) {
408 add_work(opt, GREP_SOURCE_SHA1, pathbuf.buf, sha1);
409 strbuf_release(&pathbuf);
410 return 0;
411 } else
412 #endif
414 struct grep_source gs;
415 int hit;
417 grep_source_init(&gs, GREP_SOURCE_SHA1, pathbuf.buf, sha1);
418 strbuf_release(&pathbuf);
419 hit = grep_source(opt, &gs);
421 grep_source_clear(&gs);
422 return hit;
426 static int grep_file(struct grep_opt *opt, const char *filename)
428 struct strbuf buf = STRBUF_INIT;
430 if (opt->relative && opt->prefix_length)
431 quote_path_relative(filename, -1, &buf, opt->prefix);
432 else
433 strbuf_addstr(&buf, filename);
435 #ifndef NO_PTHREADS
436 if (use_threads) {
437 add_work(opt, GREP_SOURCE_FILE, buf.buf, filename);
438 strbuf_release(&buf);
439 return 0;
440 } else
441 #endif
443 struct grep_source gs;
444 int hit;
446 grep_source_init(&gs, GREP_SOURCE_FILE, buf.buf, filename);
447 strbuf_release(&buf);
448 hit = grep_source(opt, &gs);
450 grep_source_clear(&gs);
451 return hit;
455 static void append_path(struct grep_opt *opt, const void *data, size_t len)
457 struct string_list *path_list = opt->output_priv;
459 if (len == 1 && *(const char *)data == '\0')
460 return;
461 string_list_append(path_list, xstrndup(data, len));
464 static void run_pager(struct grep_opt *opt, const char *prefix)
466 struct string_list *path_list = opt->output_priv;
467 const char **argv = xmalloc(sizeof(const char *) * (path_list->nr + 1));
468 int i, status;
470 for (i = 0; i < path_list->nr; i++)
471 argv[i] = path_list->items[i].string;
472 argv[path_list->nr] = NULL;
474 if (prefix && chdir(prefix))
475 die(_("Failed to chdir: %s"), prefix);
476 status = run_command_v_opt(argv, RUN_USING_SHELL);
477 if (status)
478 exit(status);
479 free(argv);
482 static int grep_cache(struct grep_opt *opt, const struct pathspec *pathspec, int cached)
484 int hit = 0;
485 int nr;
486 read_cache();
488 for (nr = 0; nr < active_nr; nr++) {
489 struct cache_entry *ce = active_cache[nr];
490 if (!S_ISREG(ce->ce_mode))
491 continue;
492 if (!match_pathspec_depth(pathspec, ce->name, ce_namelen(ce), 0, NULL))
493 continue;
494 if (skip_binary(opt, ce->name))
495 continue;
498 * If CE_VALID is on, we assume worktree file and its cache entry
499 * are identical, even if worktree file has been modified, so use
500 * cache version instead
502 if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
503 if (ce_stage(ce))
504 continue;
505 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
507 else
508 hit |= grep_file(opt, ce->name);
509 if (ce_stage(ce)) {
510 do {
511 nr++;
512 } while (nr < active_nr &&
513 !strcmp(ce->name, active_cache[nr]->name));
514 nr--; /* compensate for loop control */
516 if (hit && opt->status_only)
517 break;
519 return hit;
522 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
523 struct tree_desc *tree, struct strbuf *base, int tn_len)
525 int hit = 0;
526 enum interesting match = entry_not_interesting;
527 struct name_entry entry;
528 int old_baselen = base->len;
530 while (tree_entry(tree, &entry)) {
531 int te_len = tree_entry_len(&entry);
533 if (match != all_entries_interesting) {
534 match = tree_entry_interesting(&entry, base, tn_len, pathspec);
535 if (match == all_entries_not_interesting)
536 break;
537 if (match == entry_not_interesting)
538 continue;
541 strbuf_add(base, entry.path, te_len);
543 if (S_ISREG(entry.mode)) {
544 hit |= grep_sha1(opt, entry.sha1, base->buf, tn_len);
546 else if (S_ISDIR(entry.mode)) {
547 enum object_type type;
548 struct tree_desc sub;
549 void *data;
550 unsigned long size;
552 data = lock_and_read_sha1_file(entry.sha1, &type, &size);
553 if (!data)
554 die(_("unable to read tree (%s)"),
555 sha1_to_hex(entry.sha1));
557 strbuf_addch(base, '/');
558 init_tree_desc(&sub, data, size);
559 hit |= grep_tree(opt, pathspec, &sub, base, tn_len);
560 free(data);
562 strbuf_setlen(base, old_baselen);
564 if (hit && opt->status_only)
565 break;
567 return hit;
570 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
571 struct object *obj, const char *name)
573 if (obj->type == OBJ_BLOB)
574 return grep_sha1(opt, obj->sha1, name, 0);
575 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
576 struct tree_desc tree;
577 void *data;
578 unsigned long size;
579 struct strbuf base;
580 int hit, len;
582 grep_read_lock();
583 data = read_object_with_reference(obj->sha1, tree_type,
584 &size, NULL);
585 grep_read_unlock();
587 if (!data)
588 die(_("unable to read tree (%s)"), sha1_to_hex(obj->sha1));
590 len = name ? strlen(name) : 0;
591 strbuf_init(&base, PATH_MAX + len + 1);
592 if (len) {
593 strbuf_add(&base, name, len);
594 strbuf_addch(&base, ':');
596 init_tree_desc(&tree, data, size);
597 hit = grep_tree(opt, pathspec, &tree, &base, base.len);
598 strbuf_release(&base);
599 free(data);
600 return hit;
602 die(_("unable to grep from object of type %s"), typename(obj->type));
605 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
606 const struct object_array *list)
608 unsigned int i;
609 int hit = 0;
610 const unsigned int nr = list->nr;
612 for (i = 0; i < nr; i++) {
613 struct object *real_obj;
614 real_obj = deref_tag(list->objects[i].item, NULL, 0);
615 if (grep_object(opt, pathspec, real_obj, list->objects[i].name)) {
616 hit = 1;
617 if (opt->status_only)
618 break;
621 return hit;
624 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
625 int exc_std)
627 struct dir_struct dir;
628 int i, hit = 0;
630 memset(&dir, 0, sizeof(dir));
631 if (exc_std)
632 setup_standard_excludes(&dir);
634 fill_directory(&dir, pathspec->raw);
635 for (i = 0; i < dir.nr; i++) {
636 const char *name = dir.entries[i]->name;
637 int namelen = strlen(name);
638 if (!match_pathspec_depth(pathspec, name, namelen, 0, NULL))
639 continue;
640 hit |= grep_file(opt, dir.entries[i]->name);
641 if (hit && opt->status_only)
642 break;
644 return hit;
647 static int context_callback(const struct option *opt, const char *arg,
648 int unset)
650 struct grep_opt *grep_opt = opt->value;
651 int value;
652 const char *endp;
654 if (unset) {
655 grep_opt->pre_context = grep_opt->post_context = 0;
656 return 0;
658 value = strtol(arg, (char **)&endp, 10);
659 if (*endp) {
660 return error(_("switch `%c' expects a numerical value"),
661 opt->short_name);
663 grep_opt->pre_context = grep_opt->post_context = value;
664 return 0;
667 static int file_callback(const struct option *opt, const char *arg, int unset)
669 struct grep_opt *grep_opt = opt->value;
670 int from_stdin = !strcmp(arg, "-");
671 FILE *patterns;
672 int lno = 0;
673 struct strbuf sb = STRBUF_INIT;
675 patterns = from_stdin ? stdin : fopen(arg, "r");
676 if (!patterns)
677 die_errno(_("cannot open '%s'"), arg);
678 while (strbuf_getline(&sb, patterns, '\n') == 0) {
679 /* ignore empty line like grep does */
680 if (sb.len == 0)
681 continue;
683 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
684 GREP_PATTERN);
686 if (!from_stdin)
687 fclose(patterns);
688 strbuf_release(&sb);
689 return 0;
692 static int not_callback(const struct option *opt, const char *arg, int unset)
694 struct grep_opt *grep_opt = opt->value;
695 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
696 return 0;
699 static int and_callback(const struct option *opt, const char *arg, int unset)
701 struct grep_opt *grep_opt = opt->value;
702 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
703 return 0;
706 static int open_callback(const struct option *opt, const char *arg, int unset)
708 struct grep_opt *grep_opt = opt->value;
709 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
710 return 0;
713 static int close_callback(const struct option *opt, const char *arg, int unset)
715 struct grep_opt *grep_opt = opt->value;
716 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
717 return 0;
720 static int pattern_callback(const struct option *opt, const char *arg,
721 int unset)
723 struct grep_opt *grep_opt = opt->value;
724 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
725 return 0;
728 static int help_callback(const struct option *opt, const char *arg, int unset)
730 return -1;
733 int cmd_grep(int argc, const char **argv, const char *prefix)
735 int hit = 0;
736 int cached = 0, untracked = 0, opt_exclude = -1;
737 int seen_dashdash = 0;
738 int external_grep_allowed__ignored;
739 const char *show_in_pager = NULL, *default_pager = "dummy";
740 struct grep_opt opt;
741 struct object_array list = OBJECT_ARRAY_INIT;
742 const char **paths = NULL;
743 struct pathspec pathspec;
744 struct string_list path_list = STRING_LIST_INIT_NODUP;
745 int i;
746 int dummy;
747 int use_index = 1;
748 int pattern_type_arg = GREP_PATTERN_TYPE_UNSPECIFIED;
750 struct option options[] = {
751 OPT_BOOLEAN(0, "cached", &cached,
752 N_("search in index instead of in the work tree")),
753 OPT_NEGBIT(0, "no-index", &use_index,
754 N_("find in contents not managed by git"), 1),
755 OPT_BOOLEAN(0, "untracked", &untracked,
756 N_("search in both tracked and untracked files")),
757 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
758 N_("search also in ignored files"), 1),
759 OPT_GROUP(""),
760 OPT_BOOLEAN('v', "invert-match", &opt.invert,
761 N_("show non-matching lines")),
762 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
763 N_("case insensitive matching")),
764 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
765 N_("match patterns only at word boundaries")),
766 OPT_SET_INT('a', "text", &opt.binary,
767 N_("process binary files as text"), GREP_BINARY_TEXT),
768 OPT_SET_INT('I', NULL, &opt.binary,
769 N_("don't match patterns in binary files"),
770 GREP_BINARY_NOMATCH),
771 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
772 N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
773 NULL, 1 },
774 OPT_GROUP(""),
775 OPT_SET_INT('E', "extended-regexp", &pattern_type_arg,
776 N_("use extended POSIX regular expressions"),
777 GREP_PATTERN_TYPE_ERE),
778 OPT_SET_INT('G', "basic-regexp", &pattern_type_arg,
779 N_("use basic POSIX regular expressions (default)"),
780 GREP_PATTERN_TYPE_BRE),
781 OPT_SET_INT('F', "fixed-strings", &pattern_type_arg,
782 N_("interpret patterns as fixed strings"),
783 GREP_PATTERN_TYPE_FIXED),
784 OPT_SET_INT('P', "perl-regexp", &pattern_type_arg,
785 N_("use Perl-compatible regular expressions"),
786 GREP_PATTERN_TYPE_PCRE),
787 OPT_GROUP(""),
788 OPT_BOOLEAN('n', "line-number", &opt.linenum, N_("show line numbers")),
789 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
790 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
791 OPT_NEGBIT(0, "full-name", &opt.relative,
792 N_("show filenames relative to top directory"), 1),
793 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
794 N_("show only filenames instead of matching lines")),
795 OPT_BOOLEAN(0, "name-only", &opt.name_only,
796 N_("synonym for --files-with-matches")),
797 OPT_BOOLEAN('L', "files-without-match",
798 &opt.unmatch_name_only,
799 N_("show only the names of files without match")),
800 OPT_BOOLEAN('z', "null", &opt.null_following_name,
801 N_("print NUL after filenames")),
802 OPT_BOOLEAN('c', "count", &opt.count,
803 N_("show the number of matches instead of matching lines")),
804 OPT__COLOR(&opt.color, N_("highlight matches")),
805 OPT_BOOLEAN(0, "break", &opt.file_break,
806 N_("print empty line between matches from different files")),
807 OPT_BOOLEAN(0, "heading", &opt.heading,
808 N_("show filename only once above matches from same file")),
809 OPT_GROUP(""),
810 OPT_CALLBACK('C', "context", &opt, N_("n"),
811 N_("show <n> context lines before and after matches"),
812 context_callback),
813 OPT_INTEGER('B', "before-context", &opt.pre_context,
814 N_("show <n> context lines before matches")),
815 OPT_INTEGER('A', "after-context", &opt.post_context,
816 N_("show <n> context lines after matches")),
817 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
818 context_callback),
819 OPT_BOOLEAN('p', "show-function", &opt.funcname,
820 N_("show a line with the function name before matches")),
821 OPT_BOOLEAN('W', "function-context", &opt.funcbody,
822 N_("show the surrounding function")),
823 OPT_GROUP(""),
824 OPT_CALLBACK('f', NULL, &opt, N_("file"),
825 N_("read patterns from file"), file_callback),
826 { OPTION_CALLBACK, 'e', NULL, &opt, N_("pattern"),
827 N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback },
828 { OPTION_CALLBACK, 0, "and", &opt, NULL,
829 N_("combine patterns specified with -e"),
830 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
831 OPT_BOOLEAN(0, "or", &dummy, ""),
832 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
833 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
834 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
835 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
836 open_callback },
837 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
838 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
839 close_callback },
840 OPT__QUIET(&opt.status_only,
841 N_("indicate hit with exit status without output")),
842 OPT_BOOLEAN(0, "all-match", &opt.all_match,
843 N_("show only matches from files that match all patterns")),
844 { OPTION_SET_INT, 0, "debug", &opt.debug, NULL,
845 N_("show parse tree for grep expression"),
846 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 1 },
847 OPT_GROUP(""),
848 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
849 N_("pager"), N_("show matching files in the pager"),
850 PARSE_OPT_OPTARG, NULL, (intptr_t)default_pager },
851 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
852 N_("allow calling of grep(1) (ignored by this build)")),
853 { OPTION_CALLBACK, 0, "help-all", &options, NULL, N_("show usage"),
854 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
855 OPT_END()
859 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
860 * to show usage information and exit.
862 if (argc == 2 && !strcmp(argv[1], "-h"))
863 usage_with_options(grep_usage, options);
865 memset(&opt, 0, sizeof(opt));
866 opt.prefix = prefix;
867 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
868 opt.relative = 1;
869 opt.pathname = 1;
870 opt.pattern_tail = &opt.pattern_list;
871 opt.header_tail = &opt.header_list;
872 opt.regflags = REG_NEWLINE;
873 opt.max_depth = -1;
874 opt.pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
875 opt.extended_regexp_option = 0;
877 strcpy(opt.color_context, "");
878 strcpy(opt.color_filename, "");
879 strcpy(opt.color_function, "");
880 strcpy(opt.color_lineno, "");
881 strcpy(opt.color_match, GIT_COLOR_BOLD_RED);
882 strcpy(opt.color_selected, "");
883 strcpy(opt.color_sep, GIT_COLOR_CYAN);
884 opt.color = -1;
885 git_config(grep_config, &opt);
888 * If there is no -- then the paths must exist in the working
889 * tree. If there is no explicit pattern specified with -e or
890 * -f, we take the first unrecognized non option to be the
891 * pattern, but then what follows it must be zero or more
892 * valid refs up to the -- (if exists), and then existing
893 * paths. If there is an explicit pattern, then the first
894 * unrecognized non option is the beginning of the refs list
895 * that continues up to the -- (if exists), and then paths.
897 argc = parse_options(argc, argv, prefix, options, grep_usage,
898 PARSE_OPT_KEEP_DASHDASH |
899 PARSE_OPT_STOP_AT_NON_OPTION |
900 PARSE_OPT_NO_INTERNAL_HELP);
902 if (pattern_type_arg != GREP_PATTERN_TYPE_UNSPECIFIED)
903 grep_pattern_type_options(pattern_type_arg, &opt);
904 else if (opt.pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
905 grep_pattern_type_options(opt.pattern_type_option, &opt);
906 else if (opt.extended_regexp_option)
907 grep_pattern_type_options(GREP_PATTERN_TYPE_ERE, &opt);
909 if (use_index && !startup_info->have_repository)
910 /* die the same way as if we did it at the beginning */
911 setup_git_directory();
914 * skip a -- separator; we know it cannot be
915 * separating revisions from pathnames if
916 * we haven't even had any patterns yet
918 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
919 argv++;
920 argc--;
923 /* First unrecognized non-option token */
924 if (argc > 0 && !opt.pattern_list) {
925 append_grep_pattern(&opt, argv[0], "command line", 0,
926 GREP_PATTERN);
927 argv++;
928 argc--;
931 if (show_in_pager == default_pager)
932 show_in_pager = git_pager(1);
933 if (show_in_pager) {
934 opt.color = 0;
935 opt.name_only = 1;
936 opt.null_following_name = 1;
937 opt.output_priv = &path_list;
938 opt.output = append_path;
939 string_list_append(&path_list, show_in_pager);
940 use_threads = 0;
942 if ((opt.binary & GREP_BINARY_NOMATCH))
943 use_threads = 0;
945 if (!opt.pattern_list)
946 die(_("no pattern given."));
947 if (!opt.fixed && opt.ignore_case)
948 opt.regflags |= REG_ICASE;
950 compile_grep_patterns(&opt);
952 /* Check revs and then paths */
953 for (i = 0; i < argc; i++) {
954 const char *arg = argv[i];
955 unsigned char sha1[20];
956 /* Is it a rev? */
957 if (!get_sha1(arg, sha1)) {
958 struct object *object = parse_object(sha1);
959 if (!object)
960 die(_("bad object %s"), arg);
961 add_object_array(object, arg, &list);
962 continue;
964 if (!strcmp(arg, "--")) {
965 i++;
966 seen_dashdash = 1;
968 break;
971 #ifndef NO_PTHREADS
972 if (list.nr || cached || online_cpus() == 1)
973 use_threads = 0;
974 #else
975 use_threads = 0;
976 #endif
978 #ifndef NO_PTHREADS
979 if (use_threads) {
980 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
981 && (opt.pre_context || opt.post_context ||
982 opt.file_break || opt.funcbody))
983 skip_first_line = 1;
984 start_threads(&opt);
986 #endif
988 /* The rest are paths */
989 if (!seen_dashdash) {
990 int j;
991 for (j = i; j < argc; j++)
992 verify_filename(prefix, argv[j], j == i);
995 paths = get_pathspec(prefix, argv + i);
996 init_pathspec(&pathspec, paths);
997 pathspec.max_depth = opt.max_depth;
998 pathspec.recursive = 1;
1000 if (show_in_pager && (cached || list.nr))
1001 die(_("--open-files-in-pager only works on the worktree"));
1003 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1004 const char *pager = path_list.items[0].string;
1005 int len = strlen(pager);
1007 if (len > 4 && is_dir_sep(pager[len - 5]))
1008 pager += len - 4;
1010 if (opt.ignore_case && !strcmp("less", pager))
1011 string_list_append(&path_list, "-i");
1013 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1014 struct strbuf buf = STRBUF_INIT;
1015 strbuf_addf(&buf, "+/%s%s",
1016 strcmp("less", pager) ? "" : "*",
1017 opt.pattern_list->pattern);
1018 string_list_append(&path_list, buf.buf);
1019 strbuf_detach(&buf, NULL);
1023 if (!show_in_pager)
1024 setup_pager();
1026 if (!use_index && (untracked || cached))
1027 die(_("--cached or --untracked cannot be used with --no-index."));
1029 if (!use_index || untracked) {
1030 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
1031 if (list.nr)
1032 die(_("--no-index or --untracked cannot be used with revs."));
1033 hit = grep_directory(&opt, &pathspec, use_exclude);
1034 } else if (0 <= opt_exclude) {
1035 die(_("--[no-]exclude-standard cannot be used for tracked contents."));
1036 } else if (!list.nr) {
1037 if (!cached)
1038 setup_work_tree();
1040 hit = grep_cache(&opt, &pathspec, cached);
1041 } else {
1042 if (cached)
1043 die(_("both --cached and trees are given."));
1044 hit = grep_objects(&opt, &pathspec, &list);
1047 if (use_threads)
1048 hit |= wait_all();
1049 if (hit && show_in_pager)
1050 run_pager(&opt, prefix);
1051 free_grep_patterns(&opt);
1052 return !hit;