Merge merge-recursive
[git/dscho.git] / builtin-grep.c
blob6c9a8e5090c2dd6963bb088a6e3f806ad05ccc95
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"
17 #include "dir.h"
18 #include "string-list.h"
20 #ifndef NO_PTHREADS
21 #include "thread-utils.h"
22 #include <pthread.h>
23 #endif
25 static char const * const grep_usage[] = {
26 "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
27 NULL
30 static int use_threads = 1;
32 #ifndef NO_PTHREADS
33 #define THREADS 8
34 static pthread_t threads[THREADS];
36 static void *load_sha1(const unsigned char *sha1, unsigned long *size,
37 const char *name);
38 static void *load_file(const char *filename, size_t *sz);
40 enum work_type {WORK_SHA1, WORK_FILE};
42 /* We use one producer thread and THREADS consumer
43 * threads. The producer adds struct work_items to 'todo' and the
44 * consumers pick work items from the same array.
46 struct work_item
48 enum work_type type;
49 char *name;
51 /* if type == WORK_SHA1, then 'identifier' is a SHA1,
52 * otherwise type == WORK_FILE, and 'identifier' is a NUL
53 * terminated filename.
55 void *identifier;
56 char done;
57 struct strbuf out;
60 /* In the range [todo_done, todo_start) in 'todo' we have work_items
61 * that have been or are processed by a consumer thread. We haven't
62 * written the result for these to stdout yet.
64 * The work_items in [todo_start, todo_end) are waiting to be picked
65 * up by a consumer thread.
67 * The ranges are modulo TODO_SIZE.
69 #define TODO_SIZE 128
70 static struct work_item todo[TODO_SIZE];
71 static int todo_start;
72 static int todo_end;
73 static int todo_done;
75 /* Has all work items been added? */
76 static int all_work_added;
78 /* This lock protects all the variables above. */
79 static pthread_mutex_t grep_mutex;
81 /* Used to serialize calls to read_sha1_file. */
82 static pthread_mutex_t read_sha1_mutex;
84 #define grep_lock() pthread_mutex_lock(&grep_mutex)
85 #define grep_unlock() pthread_mutex_unlock(&grep_mutex)
86 #define read_sha1_lock() pthread_mutex_lock(&read_sha1_mutex)
87 #define read_sha1_unlock() pthread_mutex_unlock(&read_sha1_mutex)
89 /* Signalled when a new work_item is added to todo. */
90 static pthread_cond_t cond_add;
92 /* Signalled when the result from one work_item is written to
93 * stdout.
95 static pthread_cond_t cond_write;
97 /* Signalled when we are finished with everything. */
98 static pthread_cond_t cond_result;
100 static void add_work(enum work_type type, char *name, void *id)
102 grep_lock();
104 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
105 pthread_cond_wait(&cond_write, &grep_mutex);
108 todo[todo_end].type = type;
109 todo[todo_end].name = name;
110 todo[todo_end].identifier = id;
111 todo[todo_end].done = 0;
112 strbuf_reset(&todo[todo_end].out);
113 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
115 pthread_cond_signal(&cond_add);
116 grep_unlock();
119 static struct work_item *get_work(void)
121 struct work_item *ret;
123 grep_lock();
124 while (todo_start == todo_end && !all_work_added) {
125 pthread_cond_wait(&cond_add, &grep_mutex);
128 if (todo_start == todo_end && all_work_added) {
129 ret = NULL;
130 } else {
131 ret = &todo[todo_start];
132 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
134 grep_unlock();
135 return ret;
138 static void grep_sha1_async(struct grep_opt *opt, char *name,
139 const unsigned char *sha1)
141 unsigned char *s;
142 s = xmalloc(20);
143 memcpy(s, sha1, 20);
144 add_work(WORK_SHA1, name, s);
147 static void grep_file_async(struct grep_opt *opt, char *name,
148 const char *filename)
150 add_work(WORK_FILE, name, xstrdup(filename));
153 static void work_done(struct work_item *w)
155 int old_done;
157 grep_lock();
158 w->done = 1;
159 old_done = todo_done;
160 for(; todo[todo_done].done && todo_done != todo_start;
161 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
162 w = &todo[todo_done];
163 write_or_die(1, w->out.buf, w->out.len);
164 free(w->name);
165 free(w->identifier);
168 if (old_done != todo_done)
169 pthread_cond_signal(&cond_write);
171 if (all_work_added && todo_done == todo_end)
172 pthread_cond_signal(&cond_result);
174 grep_unlock();
177 static void *run(void *arg)
179 int hit = 0;
180 struct grep_opt *opt = arg;
182 while (1) {
183 struct work_item *w = get_work();
184 if (!w)
185 break;
187 opt->output_priv = w;
188 if (w->type == WORK_SHA1) {
189 unsigned long sz;
190 void* data = load_sha1(w->identifier, &sz, w->name);
192 if (data) {
193 hit |= grep_buffer(opt, w->name, data, sz);
194 free(data);
196 } else if (w->type == WORK_FILE) {
197 size_t sz;
198 void* data = load_file(w->identifier, &sz);
199 if (data) {
200 hit |= grep_buffer(opt, w->name, data, sz);
201 free(data);
203 } else {
204 assert(0);
207 work_done(w);
209 free_grep_patterns(arg);
210 free(arg);
212 return (void*) (intptr_t) hit;
215 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
217 struct work_item *w = opt->output_priv;
218 strbuf_add(&w->out, buf, size);
221 static void start_threads(struct grep_opt *opt)
223 int i;
225 pthread_mutex_init(&grep_mutex, NULL);
226 pthread_mutex_init(&read_sha1_mutex, NULL);
227 pthread_cond_init(&cond_add, NULL);
228 pthread_cond_init(&cond_write, NULL);
229 pthread_cond_init(&cond_result, NULL);
231 for (i = 0; i < ARRAY_SIZE(todo); i++) {
232 strbuf_init(&todo[i].out, 0);
235 for (i = 0; i < ARRAY_SIZE(threads); i++) {
236 int err;
237 struct grep_opt *o = grep_opt_dup(opt);
238 o->output = strbuf_out;
239 compile_grep_patterns(o);
240 err = pthread_create(&threads[i], NULL, run, o);
242 if (err)
243 die("grep: failed to create thread: %s",
244 strerror(err));
248 static int wait_all(void)
250 int hit = 0;
251 int i;
253 grep_lock();
254 all_work_added = 1;
256 /* Wait until all work is done. */
257 while (todo_done != todo_end)
258 pthread_cond_wait(&cond_result, &grep_mutex);
260 /* Wake up all the consumer threads so they can see that there
261 * is no more work to do.
263 pthread_cond_broadcast(&cond_add);
264 grep_unlock();
266 for (i = 0; i < ARRAY_SIZE(threads); i++) {
267 void *h;
268 pthread_join(threads[i], &h);
269 hit |= (int) (intptr_t) h;
272 pthread_mutex_destroy(&grep_mutex);
273 pthread_mutex_destroy(&read_sha1_mutex);
274 pthread_cond_destroy(&cond_add);
275 pthread_cond_destroy(&cond_write);
276 pthread_cond_destroy(&cond_result);
278 return hit;
280 #else /* !NO_PTHREADS */
281 #define read_sha1_lock()
282 #define read_sha1_unlock()
284 static int wait_all(void)
286 return 0;
288 #endif
290 static int grep_config(const char *var, const char *value, void *cb)
292 struct grep_opt *opt = cb;
294 switch (userdiff_config(var, value)) {
295 case 0: break;
296 case -1: return -1;
297 default: return 0;
300 if (!strcmp(var, "color.grep")) {
301 opt->color = git_config_colorbool(var, value, -1);
302 return 0;
304 if (!strcmp(var, "color.grep.match")) {
305 if (!value)
306 return config_error_nonbool(var);
307 color_parse(value, var, opt->color_match);
308 return 0;
310 return git_color_default_config(var, value, cb);
314 * Return non-zero if max_depth is negative or path has no more then max_depth
315 * slashes.
317 static int accept_subdir(const char *path, int max_depth)
319 if (max_depth < 0)
320 return 1;
322 while ((path = strchr(path, '/')) != NULL) {
323 max_depth--;
324 if (max_depth < 0)
325 return 0;
326 path++;
328 return 1;
332 * Return non-zero if name is a subdirectory of match and is not too deep.
334 static int is_subdir(const char *name, int namelen,
335 const char *match, int matchlen, int max_depth)
337 if (matchlen > namelen || strncmp(name, match, matchlen))
338 return 0;
340 if (name[matchlen] == '\0') /* exact match */
341 return 1;
343 if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
344 return accept_subdir(name + matchlen + 1, max_depth);
346 return 0;
350 * git grep pathspecs are somewhat different from diff-tree pathspecs;
351 * pathname wildcards are allowed.
353 static int pathspec_matches(const char **paths, const char *name, int max_depth)
355 int namelen, i;
356 if (!paths || !*paths)
357 return accept_subdir(name, max_depth);
358 namelen = strlen(name);
359 for (i = 0; paths[i]; i++) {
360 const char *match = paths[i];
361 int matchlen = strlen(match);
362 const char *cp, *meta;
364 if (is_subdir(name, namelen, match, matchlen, max_depth))
365 return 1;
366 if (!fnmatch(match, name, 0))
367 return 1;
368 if (name[namelen-1] != '/')
369 continue;
371 /* We are being asked if the directory ("name") is worth
372 * descending into.
374 * Find the longest leading directory name that does
375 * not have metacharacter in the pathspec; the name
376 * we are looking at must overlap with that directory.
378 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
379 char ch = *cp;
380 if (ch == '*' || ch == '[' || ch == '?') {
381 meta = cp;
382 break;
385 if (!meta)
386 meta = cp; /* fully literal */
388 if (namelen <= meta - match) {
389 /* Looking at "Documentation/" and
390 * the pattern says "Documentation/howto/", or
391 * "Documentation/diff*.txt". The name we
392 * have should match prefix.
394 if (!memcmp(match, name, namelen))
395 return 1;
396 continue;
399 if (meta - match < namelen) {
400 /* Looking at "Documentation/howto/" and
401 * the pattern says "Documentation/h*";
402 * match up to "Do.../h"; this avoids descending
403 * into "Documentation/technical/".
405 if (!memcmp(match, name, meta - match))
406 return 1;
407 continue;
410 return 0;
413 static void *load_sha1(const unsigned char *sha1, unsigned long *size,
414 const char *name)
416 enum object_type type;
417 char *data;
419 read_sha1_lock();
420 data = read_sha1_file(sha1, &type, size);
421 read_sha1_unlock();
423 if (!data)
424 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
426 return data;
429 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1,
430 const char *filename, int tree_name_len)
432 struct strbuf pathbuf = STRBUF_INIT;
433 char *name;
435 if (opt->relative && opt->prefix_length) {
436 quote_path_relative(filename + tree_name_len, -1, &pathbuf,
437 opt->prefix);
438 strbuf_insert(&pathbuf, 0, filename, tree_name_len);
439 } else {
440 strbuf_addstr(&pathbuf, filename);
443 name = strbuf_detach(&pathbuf, NULL);
445 #ifndef NO_PTHREADS
446 if (use_threads) {
447 grep_sha1_async(opt, name, sha1);
448 return 0;
449 } else
450 #endif
452 int hit;
453 unsigned long sz;
454 void *data = load_sha1(sha1, &sz, name);
455 if (!data)
456 hit = 0;
457 else
458 hit = grep_buffer(opt, name, data, sz);
460 free(data);
461 free(name);
462 return hit;
466 static void *load_file(const char *filename, size_t *sz)
468 struct stat st;
469 char *data;
470 int i;
472 if (lstat(filename, &st) < 0) {
473 err_ret:
474 if (errno != ENOENT)
475 error("'%s': %s", filename, strerror(errno));
476 return 0;
478 if (!S_ISREG(st.st_mode))
479 return 0;
480 *sz = xsize_t(st.st_size);
481 i = open(filename, O_RDONLY);
482 if (i < 0)
483 goto err_ret;
484 data = xmalloc(*sz + 1);
485 if (st.st_size != read_in_full(i, data, *sz)) {
486 error("'%s': short read %s", filename, strerror(errno));
487 close(i);
488 free(data);
489 return 0;
491 close(i);
492 data[*sz] = 0;
493 return data;
496 static int grep_file(struct grep_opt *opt, const char *filename)
498 struct strbuf buf = STRBUF_INIT;
499 char *name;
501 if (opt->relative && opt->prefix_length)
502 quote_path_relative(filename, -1, &buf, opt->prefix);
503 else
504 strbuf_addstr(&buf, filename);
505 name = strbuf_detach(&buf, NULL);
507 #ifndef NO_PTHREADS
508 if (use_threads) {
509 grep_file_async(opt, name, filename);
510 return 0;
511 } else
512 #endif
514 int hit;
515 size_t sz;
516 void *data = load_file(filename, &sz);
517 if (!data)
518 hit = 0;
519 else
520 hit = grep_buffer(opt, name, data, sz);
522 free(data);
523 free(name);
524 return hit;
528 static void append_path(struct grep_opt *opt, const void *data, size_t len)
530 struct string_list *path_list = opt->output_priv;
532 if (len == 1 && *(char *)data == '\0')
533 return;
534 string_list_append(xstrndup(data, len), path_list);
537 static void run_pager(struct grep_opt *opt, const char *prefix)
539 struct string_list *path_list = opt->output_priv;
540 char **argv = xmalloc(sizeof(const char *) * (path_list->nr + 1));
541 int i;
543 for (i = 0; i < path_list->nr; i++)
544 argv[i] = path_list->items[i].string;
545 argv[path_list->nr] = NULL;
547 if (prefix)
548 chdir(prefix);
549 execvp(argv[0], argv);
550 error("Could not run pager %s: %s", argv[0], strerror(errno));
553 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
555 int hit = 0;
556 int nr;
557 read_cache();
559 for (nr = 0; nr < active_nr; nr++) {
560 struct cache_entry *ce = active_cache[nr];
561 if (!S_ISREG(ce->ce_mode))
562 continue;
563 if (!pathspec_matches(paths, ce->name, opt->max_depth))
564 continue;
566 * If CE_VALID is on, we assume worktree file and its cache entry
567 * are identical, even if worktree file has been modified, so use
568 * cache version instead
570 if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
571 if (ce_stage(ce))
572 continue;
573 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
575 else
576 hit |= grep_file(opt, ce->name);
577 if (ce_stage(ce)) {
578 do {
579 nr++;
580 } while (nr < active_nr &&
581 !strcmp(ce->name, active_cache[nr]->name));
582 nr--; /* compensate for loop control */
584 if (hit && opt->status_only)
585 break;
587 return hit;
590 static int grep_tree(struct grep_opt *opt, const char **paths,
591 struct tree_desc *tree,
592 const char *tree_name, const char *base)
594 int len;
595 int hit = 0;
596 struct name_entry entry;
597 char *down;
598 int tn_len = strlen(tree_name);
599 struct strbuf pathbuf;
601 strbuf_init(&pathbuf, PATH_MAX + tn_len);
603 if (tn_len) {
604 strbuf_add(&pathbuf, tree_name, tn_len);
605 strbuf_addch(&pathbuf, ':');
606 tn_len = pathbuf.len;
608 strbuf_addstr(&pathbuf, base);
609 len = pathbuf.len;
611 while (tree_entry(tree, &entry)) {
612 int te_len = tree_entry_len(entry.path, entry.sha1);
613 pathbuf.len = len;
614 strbuf_add(&pathbuf, entry.path, te_len);
616 if (S_ISDIR(entry.mode))
617 /* Match "abc/" against pathspec to
618 * decide if we want to descend into "abc"
619 * directory.
621 strbuf_addch(&pathbuf, '/');
623 down = pathbuf.buf + tn_len;
624 if (!pathspec_matches(paths, down, opt->max_depth))
626 else if (S_ISREG(entry.mode))
627 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
628 else if (S_ISDIR(entry.mode)) {
629 enum object_type type;
630 struct tree_desc sub;
631 void *data;
632 unsigned long size;
634 read_sha1_lock();
635 data = read_sha1_file(entry.sha1, &type, &size);
636 read_sha1_unlock();
638 if (!data)
639 die("unable to read tree (%s)",
640 sha1_to_hex(entry.sha1));
641 init_tree_desc(&sub, data, size);
642 hit |= grep_tree(opt, paths, &sub, tree_name, down);
643 free(data);
645 if (hit && opt->status_only)
646 break;
648 strbuf_release(&pathbuf);
649 return hit;
652 static int grep_object(struct grep_opt *opt, const char **paths,
653 struct object *obj, const char *name)
655 if (obj->type == OBJ_BLOB)
656 return grep_sha1(opt, obj->sha1, name, 0);
657 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
658 struct tree_desc tree;
659 void *data;
660 unsigned long size;
661 int hit;
662 data = read_object_with_reference(obj->sha1, tree_type,
663 &size, NULL);
664 if (!data)
665 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
666 init_tree_desc(&tree, data, size);
667 hit = grep_tree(opt, paths, &tree, name, "");
668 free(data);
669 return hit;
671 die("unable to grep from object of type %s", typename(obj->type));
674 static int grep_directory(struct grep_opt *opt, const char **paths)
676 struct dir_struct dir;
677 int i, hit = 0;
679 memset(&dir, 0, sizeof(dir));
680 setup_standard_excludes(&dir);
682 fill_directory(&dir, paths);
683 for (i = 0; i < dir.nr; i++) {
684 hit |= grep_file(opt, dir.entries[i]->name);
685 if (hit && opt->status_only)
686 break;
688 return hit;
691 static int context_callback(const struct option *opt, const char *arg,
692 int unset)
694 struct grep_opt *grep_opt = opt->value;
695 int value;
696 const char *endp;
698 if (unset) {
699 grep_opt->pre_context = grep_opt->post_context = 0;
700 return 0;
702 value = strtol(arg, (char **)&endp, 10);
703 if (*endp) {
704 return error("switch `%c' expects a numerical value",
705 opt->short_name);
707 grep_opt->pre_context = grep_opt->post_context = value;
708 return 0;
711 static int file_callback(const struct option *opt, const char *arg, int unset)
713 struct grep_opt *grep_opt = opt->value;
714 FILE *patterns;
715 int lno = 0;
716 struct strbuf sb = STRBUF_INIT;
718 patterns = fopen(arg, "r");
719 if (!patterns)
720 die_errno("cannot open '%s'", arg);
721 while (strbuf_getline(&sb, patterns, '\n') == 0) {
722 /* ignore empty line like grep does */
723 if (sb.len == 0)
724 continue;
725 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
726 ++lno, GREP_PATTERN);
728 fclose(patterns);
729 strbuf_release(&sb);
730 return 0;
733 static int not_callback(const struct option *opt, const char *arg, int unset)
735 struct grep_opt *grep_opt = opt->value;
736 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
737 return 0;
740 static int and_callback(const struct option *opt, const char *arg, int unset)
742 struct grep_opt *grep_opt = opt->value;
743 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
744 return 0;
747 static int open_callback(const struct option *opt, const char *arg, int unset)
749 struct grep_opt *grep_opt = opt->value;
750 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
751 return 0;
754 static int close_callback(const struct option *opt, const char *arg, int unset)
756 struct grep_opt *grep_opt = opt->value;
757 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
758 return 0;
761 static int pattern_callback(const struct option *opt, const char *arg,
762 int unset)
764 struct grep_opt *grep_opt = opt->value;
765 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
766 return 0;
769 static int help_callback(const struct option *opt, const char *arg, int unset)
771 return -1;
774 int cmd_grep(int argc, const char **argv, const char *prefix)
776 int hit = 0;
777 int cached = 0;
778 int seen_dashdash = 0;
779 int external_grep_allowed__ignored;
780 const char *show_in_pager = NULL, *default_pager = "dummy";
781 struct grep_opt opt;
782 struct object_array list = { 0, 0, NULL };
783 const char **paths = NULL;
784 struct string_list path_list = { NULL, 0, 0, 0 };
785 int i;
786 int dummy;
787 int nongit = 0, use_index = 1;
788 struct option options[] = {
789 OPT_BOOLEAN(0, "cached", &cached,
790 "search in index instead of in the work tree"),
791 OPT_BOOLEAN(0, "index", &use_index,
792 "--no-index finds in contents not managed by git"),
793 OPT_GROUP(""),
794 OPT_BOOLEAN('v', "invert-match", &opt.invert,
795 "show non-matching lines"),
796 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
797 "case insensitive matching"),
798 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
799 "match patterns only at word boundaries"),
800 OPT_SET_INT('a', "text", &opt.binary,
801 "process binary files as text", GREP_BINARY_TEXT),
802 OPT_SET_INT('I', NULL, &opt.binary,
803 "don't match patterns in binary files",
804 GREP_BINARY_NOMATCH),
805 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
806 "descend at most <depth> levels", PARSE_OPT_NONEG,
807 NULL, 1 },
808 OPT_GROUP(""),
809 OPT_BIT('E', "extended-regexp", &opt.regflags,
810 "use extended POSIX regular expressions", REG_EXTENDED),
811 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
812 "use basic POSIX regular expressions (default)",
813 REG_EXTENDED),
814 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
815 "interpret patterns as fixed strings"),
816 OPT_GROUP(""),
817 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
818 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
819 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
820 OPT_NEGBIT(0, "full-name", &opt.relative,
821 "show filenames relative to top directory", 1),
822 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
823 "show only filenames instead of matching lines"),
824 OPT_BOOLEAN(0, "name-only", &opt.name_only,
825 "synonym for --files-with-matches"),
826 OPT_BOOLEAN('L', "files-without-match",
827 &opt.unmatch_name_only,
828 "show only the names of files without match"),
829 OPT_BOOLEAN('z', "null", &opt.null_following_name,
830 "print NUL after filenames"),
831 OPT_BOOLEAN('c', "count", &opt.count,
832 "show the number of matches instead of matching lines"),
833 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
834 OPT_GROUP(""),
835 OPT_CALLBACK('C', NULL, &opt, "n",
836 "show <n> context lines before and after matches",
837 context_callback),
838 OPT_INTEGER('B', NULL, &opt.pre_context,
839 "show <n> context lines before matches"),
840 OPT_INTEGER('A', NULL, &opt.post_context,
841 "show <n> context lines after matches"),
842 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
843 context_callback),
844 OPT_BOOLEAN('p', "show-function", &opt.funcname,
845 "show a line with the function name before matches"),
846 OPT_GROUP(""),
847 OPT_CALLBACK('f', NULL, &opt, "file",
848 "read patterns from file", file_callback),
849 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
850 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
851 { OPTION_CALLBACK, 0, "and", &opt, NULL,
852 "combine patterns specified with -e",
853 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
854 OPT_BOOLEAN(0, "or", &dummy, ""),
855 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
856 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
857 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
858 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
859 open_callback },
860 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
861 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
862 close_callback },
863 OPT_BOOLEAN('q', "quiet", &opt.status_only,
864 "indicate hit with exit status without output"),
865 OPT_BOOLEAN(0, "all-match", &opt.all_match,
866 "show only matches from files that match all patterns"),
867 OPT_GROUP(""),
868 { OPTION_STRING, 'P', "open-files-in-pager", &show_in_pager,
869 "pager", "show matching files in the pager",
870 PARSE_OPT_OPTARG, NULL, (intptr_t)default_pager },
871 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
872 "allow calling of grep(1) (ignored by this build)"),
873 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
874 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
875 OPT_END()
878 prefix = setup_git_directory_gently(&nongit);
881 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
882 * to show usage information and exit.
884 if (argc == 2 && !strcmp(argv[1], "-h"))
885 usage_with_options(grep_usage, options);
887 memset(&opt, 0, sizeof(opt));
888 opt.prefix = prefix;
889 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
890 opt.relative = 1;
891 opt.pathname = 1;
892 opt.pattern_tail = &opt.pattern_list;
893 opt.regflags = REG_NEWLINE;
894 opt.max_depth = -1;
896 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
897 opt.color = -1;
898 git_config(grep_config, &opt);
899 if (opt.color == -1)
900 opt.color = git_use_color_default;
903 * If there is no -- then the paths must exist in the working
904 * tree. If there is no explicit pattern specified with -e or
905 * -f, we take the first unrecognized non option to be the
906 * pattern, but then what follows it must be zero or more
907 * valid refs up to the -- (if exists), and then existing
908 * paths. If there is an explicit pattern, then the first
909 * unrecognized non option is the beginning of the refs list
910 * that continues up to the -- (if exists), and then paths.
912 argc = parse_options(argc, argv, prefix, options, grep_usage,
913 PARSE_OPT_KEEP_DASHDASH |
914 PARSE_OPT_STOP_AT_NON_OPTION |
915 PARSE_OPT_NO_INTERNAL_HELP);
917 if (use_index && nongit)
918 /* die the same way as if we did it at the beginning */
919 setup_git_directory();
921 /* First unrecognized non-option token */
922 if (argc > 0 && !opt.pattern_list) {
923 append_grep_pattern(&opt, argv[0], "command line", 0,
924 GREP_PATTERN);
925 argv++;
926 argc--;
929 if (show_in_pager) {
930 if (show_in_pager == default_pager) {
931 show_in_pager = getenv("GIT_PAGER");
932 if (!show_in_pager)
933 show_in_pager = getenv("PAGER");
934 if (!show_in_pager)
935 show_in_pager = "less";
937 opt.name_only = 1;
938 opt.null_following_name = 1;
939 opt.output_priv = &path_list;
940 opt.output = append_path;
941 string_list_append(show_in_pager, &path_list);
942 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;
949 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
950 die("cannot mix --fixed-strings and regexp");
952 #ifndef NO_PTHREADS
953 if (online_cpus() == 1 || !grep_threads_ok(&opt))
954 use_threads = 0;
956 if (use_threads)
957 start_threads(&opt);
958 #else
959 use_threads = 0;
960 #endif
962 compile_grep_patterns(&opt);
964 /* Check revs and then paths */
965 for (i = 0; i < argc; i++) {
966 const char *arg = argv[i];
967 unsigned char sha1[20];
968 /* Is it a rev? */
969 if (!get_sha1(arg, sha1)) {
970 struct object *object = parse_object(sha1);
971 if (!object)
972 die("bad object %s", arg);
973 add_object_array(object, arg, &list);
974 continue;
976 if (!strcmp(arg, "--")) {
977 i++;
978 seen_dashdash = 1;
980 break;
983 /* The rest are paths */
984 if (!seen_dashdash) {
985 int j;
986 for (j = i; j < argc; j++)
987 verify_filename(prefix, argv[j]);
990 if (i < argc)
991 paths = get_pathspec(prefix, argv + i);
992 else if (prefix) {
993 paths = xcalloc(2, sizeof(const char *));
994 paths[0] = prefix;
995 paths[1] = NULL;
998 if (show_in_pager && cached)
999 die ("--open-files-in-pager and --cached are incompatible");
1001 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1002 const char *pager = path_list.items[0].string;
1003 int len = strlen(pager);
1005 if (len > 4 && is_dir_sep(pager[len - 5]))
1006 pager += len - 4;
1008 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1009 struct strbuf buf = STRBUF_INIT;
1010 strbuf_addf(&buf, "+/%s%s",
1011 strcmp("less", pager) ? "" : "*",
1012 opt.pattern_list->pattern);
1013 string_list_append(buf.buf, &path_list);
1014 strbuf_detach(&buf, NULL);
1018 if (!show_in_pager)
1019 setup_pager();
1021 if (!use_index) {
1022 if (cached)
1023 die("--cached cannot be used with --no-index.");
1024 if (list.nr)
1025 die("--no-index cannot be used with revs.");
1026 hit = grep_directory(&opt, paths);
1028 else if (!list.nr) {
1029 if (!cached)
1030 setup_work_tree();
1032 hit = grep_cache(&opt, paths, cached);
1034 else if (cached)
1035 die("both --cached and trees are given.");
1036 else
1037 for (i = 0; i < list.nr; i++) {
1038 struct object *real_obj;
1039 real_obj = deref_tag(list.objects[i].item, NULL, 0);
1040 if (grep_object(&opt, paths, real_obj,
1041 list.objects[i].name)) {
1042 hit = 1;
1043 if (opt.status_only)
1044 break;
1048 if (use_threads)
1049 hit |= wait_all();
1051 if (hit && show_in_pager)
1052 run_pager(&opt, prefix);
1054 free_grep_patterns(&opt);
1055 return !hit;