git am: ignore dirty submodules
[git/mingw/4msysgit/kblees.git] / builtin / grep.c
blobf6657afed70b2b930765380b1d9520985a1e39fb
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 <pthread.h>
22 #include "thread-utils.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 int print_hunk_marks_between_files;
101 static int printed_something;
103 static void add_work(enum work_type type, char *name, void *id)
105 grep_lock();
107 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
108 pthread_cond_wait(&cond_write, &grep_mutex);
111 todo[todo_end].type = type;
112 todo[todo_end].name = name;
113 todo[todo_end].identifier = id;
114 todo[todo_end].done = 0;
115 strbuf_reset(&todo[todo_end].out);
116 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
118 pthread_cond_signal(&cond_add);
119 grep_unlock();
122 static struct work_item *get_work(void)
124 struct work_item *ret;
126 grep_lock();
127 while (todo_start == todo_end && !all_work_added) {
128 pthread_cond_wait(&cond_add, &grep_mutex);
131 if (todo_start == todo_end && all_work_added) {
132 ret = NULL;
133 } else {
134 ret = &todo[todo_start];
135 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
137 grep_unlock();
138 return ret;
141 static void grep_sha1_async(struct grep_opt *opt, char *name,
142 const unsigned char *sha1)
144 unsigned char *s;
145 s = xmalloc(20);
146 memcpy(s, sha1, 20);
147 add_work(WORK_SHA1, name, s);
150 static void grep_file_async(struct grep_opt *opt, char *name,
151 const char *filename)
153 add_work(WORK_FILE, name, xstrdup(filename));
156 static void work_done(struct work_item *w)
158 int old_done;
160 grep_lock();
161 w->done = 1;
162 old_done = todo_done;
163 for(; todo[todo_done].done && todo_done != todo_start;
164 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
165 w = &todo[todo_done];
166 if (w->out.len) {
167 if (print_hunk_marks_between_files && printed_something)
168 write_or_die(1, "--\n", 3);
169 write_or_die(1, w->out.buf, w->out.len);
170 printed_something = 1;
172 free(w->name);
173 free(w->identifier);
176 if (old_done != todo_done)
177 pthread_cond_signal(&cond_write);
179 if (all_work_added && todo_done == todo_end)
180 pthread_cond_signal(&cond_result);
182 grep_unlock();
185 static void *run(void *arg)
187 int hit = 0;
188 struct grep_opt *opt = arg;
190 while (1) {
191 struct work_item *w = get_work();
192 if (!w)
193 break;
195 opt->output_priv = w;
196 if (w->type == WORK_SHA1) {
197 unsigned long sz;
198 void* data = load_sha1(w->identifier, &sz, w->name);
200 if (data) {
201 hit |= grep_buffer(opt, w->name, data, sz);
202 free(data);
204 } else if (w->type == WORK_FILE) {
205 size_t sz;
206 void* data = load_file(w->identifier, &sz);
207 if (data) {
208 hit |= grep_buffer(opt, w->name, data, sz);
209 free(data);
211 } else {
212 assert(0);
215 work_done(w);
217 free_grep_patterns(arg);
218 free(arg);
220 return (void*) (intptr_t) hit;
223 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
225 struct work_item *w = opt->output_priv;
226 strbuf_add(&w->out, buf, size);
229 static void start_threads(struct grep_opt *opt)
231 int i;
233 pthread_mutex_init(&grep_mutex, NULL);
234 pthread_mutex_init(&read_sha1_mutex, NULL);
235 pthread_cond_init(&cond_add, NULL);
236 pthread_cond_init(&cond_write, NULL);
237 pthread_cond_init(&cond_result, NULL);
239 for (i = 0; i < ARRAY_SIZE(todo); i++) {
240 strbuf_init(&todo[i].out, 0);
243 for (i = 0; i < ARRAY_SIZE(threads); i++) {
244 int err;
245 struct grep_opt *o = grep_opt_dup(opt);
246 o->output = strbuf_out;
247 compile_grep_patterns(o);
248 err = pthread_create(&threads[i], NULL, run, o);
250 if (err)
251 die("grep: failed to create thread: %s",
252 strerror(err));
256 static int wait_all(void)
258 int hit = 0;
259 int i;
261 grep_lock();
262 all_work_added = 1;
264 /* Wait until all work is done. */
265 while (todo_done != todo_end)
266 pthread_cond_wait(&cond_result, &grep_mutex);
268 /* Wake up all the consumer threads so they can see that there
269 * is no more work to do.
271 pthread_cond_broadcast(&cond_add);
272 grep_unlock();
274 for (i = 0; i < ARRAY_SIZE(threads); i++) {
275 void *h;
276 pthread_join(threads[i], &h);
277 hit |= (int) (intptr_t) h;
280 pthread_mutex_destroy(&grep_mutex);
281 pthread_mutex_destroy(&read_sha1_mutex);
282 pthread_cond_destroy(&cond_add);
283 pthread_cond_destroy(&cond_write);
284 pthread_cond_destroy(&cond_result);
286 return hit;
288 #else /* !NO_PTHREADS */
289 #define read_sha1_lock()
290 #define read_sha1_unlock()
292 static int wait_all(void)
294 return 0;
296 #endif
298 static int grep_config(const char *var, const char *value, void *cb)
300 struct grep_opt *opt = cb;
301 char *color = NULL;
303 switch (userdiff_config(var, value)) {
304 case 0: break;
305 case -1: return -1;
306 default: return 0;
309 if (!strcmp(var, "color.grep"))
310 opt->color = git_config_colorbool(var, value, -1);
311 else if (!strcmp(var, "color.grep.context"))
312 color = opt->color_context;
313 else if (!strcmp(var, "color.grep.filename"))
314 color = opt->color_filename;
315 else if (!strcmp(var, "color.grep.function"))
316 color = opt->color_function;
317 else if (!strcmp(var, "color.grep.linenumber"))
318 color = opt->color_lineno;
319 else if (!strcmp(var, "color.grep.match"))
320 color = opt->color_match;
321 else if (!strcmp(var, "color.grep.selected"))
322 color = opt->color_selected;
323 else if (!strcmp(var, "color.grep.separator"))
324 color = opt->color_sep;
325 else
326 return git_color_default_config(var, value, cb);
327 if (color) {
328 if (!value)
329 return config_error_nonbool(var);
330 color_parse(value, var, color);
332 return 0;
336 * Return non-zero if max_depth is negative or path has no more then max_depth
337 * slashes.
339 static int accept_subdir(const char *path, int max_depth)
341 if (max_depth < 0)
342 return 1;
344 while ((path = strchr(path, '/')) != NULL) {
345 max_depth--;
346 if (max_depth < 0)
347 return 0;
348 path++;
350 return 1;
354 * Return non-zero if name is a subdirectory of match and is not too deep.
356 static int is_subdir(const char *name, int namelen,
357 const char *match, int matchlen, int max_depth)
359 if (matchlen > namelen || strncmp(name, match, matchlen))
360 return 0;
362 if (name[matchlen] == '\0') /* exact match */
363 return 1;
365 if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
366 return accept_subdir(name + matchlen + 1, max_depth);
368 return 0;
372 * git grep pathspecs are somewhat different from diff-tree pathspecs;
373 * pathname wildcards are allowed.
375 static int pathspec_matches(const char **paths, const char *name, int max_depth)
377 int namelen, i;
378 if (!paths || !*paths)
379 return accept_subdir(name, max_depth);
380 namelen = strlen(name);
381 for (i = 0; paths[i]; i++) {
382 const char *match = paths[i];
383 int matchlen = strlen(match);
384 const char *cp, *meta;
386 if (is_subdir(name, namelen, match, matchlen, max_depth))
387 return 1;
388 if (!fnmatch(match, name, 0))
389 return 1;
390 if (name[namelen-1] != '/')
391 continue;
393 /* We are being asked if the directory ("name") is worth
394 * descending into.
396 * Find the longest leading directory name that does
397 * not have metacharacter in the pathspec; the name
398 * we are looking at must overlap with that directory.
400 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
401 char ch = *cp;
402 if (ch == '*' || ch == '[' || ch == '?') {
403 meta = cp;
404 break;
407 if (!meta)
408 meta = cp; /* fully literal */
410 if (namelen <= meta - match) {
411 /* Looking at "Documentation/" and
412 * the pattern says "Documentation/howto/", or
413 * "Documentation/diff*.txt". The name we
414 * have should match prefix.
416 if (!memcmp(match, name, namelen))
417 return 1;
418 continue;
421 if (meta - match < namelen) {
422 /* Looking at "Documentation/howto/" and
423 * the pattern says "Documentation/h*";
424 * match up to "Do.../h"; this avoids descending
425 * into "Documentation/technical/".
427 if (!memcmp(match, name, meta - match))
428 return 1;
429 continue;
432 return 0;
435 static void *lock_and_read_sha1_file(const unsigned char *sha1, enum object_type *type, unsigned long *size)
437 void *data;
439 if (use_threads) {
440 read_sha1_lock();
441 data = read_sha1_file(sha1, type, size);
442 read_sha1_unlock();
443 } else {
444 data = read_sha1_file(sha1, type, size);
446 return data;
449 static void *load_sha1(const unsigned char *sha1, unsigned long *size,
450 const char *name)
452 enum object_type type;
453 void *data = lock_and_read_sha1_file(sha1, &type, size);
455 if (!data)
456 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
458 return data;
461 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1,
462 const char *filename, int tree_name_len)
464 struct strbuf pathbuf = STRBUF_INIT;
465 char *name;
467 if (opt->relative && opt->prefix_length) {
468 quote_path_relative(filename + tree_name_len, -1, &pathbuf,
469 opt->prefix);
470 strbuf_insert(&pathbuf, 0, filename, tree_name_len);
471 } else {
472 strbuf_addstr(&pathbuf, filename);
475 name = strbuf_detach(&pathbuf, NULL);
477 #ifndef NO_PTHREADS
478 if (use_threads) {
479 grep_sha1_async(opt, name, sha1);
480 return 0;
481 } else
482 #endif
484 int hit;
485 unsigned long sz;
486 void *data = load_sha1(sha1, &sz, name);
487 if (!data)
488 hit = 0;
489 else
490 hit = grep_buffer(opt, name, data, sz);
492 free(data);
493 free(name);
494 return hit;
498 static void *load_file(const char *filename, size_t *sz)
500 struct stat st;
501 char *data;
502 int i;
504 if (lstat(filename, &st) < 0) {
505 err_ret:
506 if (errno != ENOENT)
507 error("'%s': %s", filename, strerror(errno));
508 return 0;
510 if (!S_ISREG(st.st_mode))
511 return 0;
512 *sz = xsize_t(st.st_size);
513 i = open(filename, O_RDONLY);
514 if (i < 0)
515 goto err_ret;
516 data = xmalloc(*sz + 1);
517 if (st.st_size != read_in_full(i, data, *sz)) {
518 error("'%s': short read %s", filename, strerror(errno));
519 close(i);
520 free(data);
521 return 0;
523 close(i);
524 data[*sz] = 0;
525 return data;
528 static int grep_file(struct grep_opt *opt, const char *filename)
530 struct strbuf buf = STRBUF_INIT;
531 char *name;
533 if (opt->relative && opt->prefix_length)
534 quote_path_relative(filename, -1, &buf, opt->prefix);
535 else
536 strbuf_addstr(&buf, filename);
537 name = strbuf_detach(&buf, NULL);
539 #ifndef NO_PTHREADS
540 if (use_threads) {
541 grep_file_async(opt, name, filename);
542 return 0;
543 } else
544 #endif
546 int hit;
547 size_t sz;
548 void *data = load_file(filename, &sz);
549 if (!data)
550 hit = 0;
551 else
552 hit = grep_buffer(opt, name, data, sz);
554 free(data);
555 free(name);
556 return hit;
560 static void append_path(struct grep_opt *opt, const void *data, size_t len)
562 struct string_list *path_list = opt->output_priv;
564 if (len == 1 && *(char *)data == '\0')
565 return;
566 string_list_append(xstrndup(data, len), path_list);
569 static void run_pager(struct grep_opt *opt, const char *prefix)
571 struct string_list *path_list = opt->output_priv;
572 char **argv = xmalloc(sizeof(const char *) * (path_list->nr + 1));
573 int i;
575 for (i = 0; i < path_list->nr; i++)
576 argv[i] = path_list->items[i].string;
577 argv[path_list->nr] = NULL;
579 if (prefix)
580 chdir(prefix);
581 execvp(argv[0], argv);
582 error("Could not run pager %s: %s", argv[0], strerror(errno));
585 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
587 int hit = 0;
588 int nr;
589 read_cache();
591 for (nr = 0; nr < active_nr; nr++) {
592 struct cache_entry *ce = active_cache[nr];
593 if (!S_ISREG(ce->ce_mode))
594 continue;
595 if (!pathspec_matches(paths, ce->name, opt->max_depth))
596 continue;
598 * If CE_VALID is on, we assume worktree file and its cache entry
599 * are identical, even if worktree file has been modified, so use
600 * cache version instead
602 if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
603 if (ce_stage(ce))
604 continue;
605 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
607 else
608 hit |= grep_file(opt, ce->name);
609 if (ce_stage(ce)) {
610 do {
611 nr++;
612 } while (nr < active_nr &&
613 !strcmp(ce->name, active_cache[nr]->name));
614 nr--; /* compensate for loop control */
616 if (hit && opt->status_only)
617 break;
619 return hit;
622 static int grep_tree(struct grep_opt *opt, const char **paths,
623 struct tree_desc *tree,
624 const char *tree_name, const char *base)
626 int len;
627 int hit = 0;
628 struct name_entry entry;
629 char *down;
630 int tn_len = strlen(tree_name);
631 struct strbuf pathbuf;
633 strbuf_init(&pathbuf, PATH_MAX + tn_len);
635 if (tn_len) {
636 strbuf_add(&pathbuf, tree_name, tn_len);
637 strbuf_addch(&pathbuf, ':');
638 tn_len = pathbuf.len;
640 strbuf_addstr(&pathbuf, base);
641 len = pathbuf.len;
643 while (tree_entry(tree, &entry)) {
644 int te_len = tree_entry_len(entry.path, entry.sha1);
645 pathbuf.len = len;
646 strbuf_add(&pathbuf, entry.path, te_len);
648 if (S_ISDIR(entry.mode))
649 /* Match "abc/" against pathspec to
650 * decide if we want to descend into "abc"
651 * directory.
653 strbuf_addch(&pathbuf, '/');
655 down = pathbuf.buf + tn_len;
656 if (!pathspec_matches(paths, down, opt->max_depth))
658 else if (S_ISREG(entry.mode))
659 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
660 else if (S_ISDIR(entry.mode)) {
661 enum object_type type;
662 struct tree_desc sub;
663 void *data;
664 unsigned long size;
666 data = lock_and_read_sha1_file(entry.sha1, &type, &size);
667 if (!data)
668 die("unable to read tree (%s)",
669 sha1_to_hex(entry.sha1));
670 init_tree_desc(&sub, data, size);
671 hit |= grep_tree(opt, paths, &sub, tree_name, down);
672 free(data);
674 if (hit && opt->status_only)
675 break;
677 strbuf_release(&pathbuf);
678 return hit;
681 static int grep_object(struct grep_opt *opt, const char **paths,
682 struct object *obj, const char *name)
684 if (obj->type == OBJ_BLOB)
685 return grep_sha1(opt, obj->sha1, name, 0);
686 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
687 struct tree_desc tree;
688 void *data;
689 unsigned long size;
690 int hit;
691 data = read_object_with_reference(obj->sha1, tree_type,
692 &size, NULL);
693 if (!data)
694 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
695 init_tree_desc(&tree, data, size);
696 hit = grep_tree(opt, paths, &tree, name, "");
697 free(data);
698 return hit;
700 die("unable to grep from object of type %s", typename(obj->type));
703 static int grep_directory(struct grep_opt *opt, const char **paths)
705 struct dir_struct dir;
706 int i, hit = 0;
708 memset(&dir, 0, sizeof(dir));
709 setup_standard_excludes(&dir);
711 fill_directory(&dir, paths);
712 for (i = 0; i < dir.nr; i++) {
713 hit |= grep_file(opt, dir.entries[i]->name);
714 if (hit && opt->status_only)
715 break;
717 free_grep_patterns(opt);
718 return hit;
721 static int context_callback(const struct option *opt, const char *arg,
722 int unset)
724 struct grep_opt *grep_opt = opt->value;
725 int value;
726 const char *endp;
728 if (unset) {
729 grep_opt->pre_context = grep_opt->post_context = 0;
730 return 0;
732 value = strtol(arg, (char **)&endp, 10);
733 if (*endp) {
734 return error("switch `%c' expects a numerical value",
735 opt->short_name);
737 grep_opt->pre_context = grep_opt->post_context = value;
738 return 0;
741 static int file_callback(const struct option *opt, const char *arg, int unset)
743 struct grep_opt *grep_opt = opt->value;
744 FILE *patterns;
745 int lno = 0;
746 struct strbuf sb = STRBUF_INIT;
748 patterns = fopen(arg, "r");
749 if (!patterns)
750 die_errno("cannot open '%s'", arg);
751 while (strbuf_getline(&sb, patterns, '\n') == 0) {
752 char *s;
753 size_t len;
755 /* ignore empty line like grep does */
756 if (sb.len == 0)
757 continue;
759 s = strbuf_detach(&sb, &len);
760 append_grep_pat(grep_opt, s, len, arg, ++lno, GREP_PATTERN);
762 fclose(patterns);
763 strbuf_release(&sb);
764 return 0;
767 static int not_callback(const struct option *opt, const char *arg, int unset)
769 struct grep_opt *grep_opt = opt->value;
770 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
771 return 0;
774 static int and_callback(const struct option *opt, const char *arg, int unset)
776 struct grep_opt *grep_opt = opt->value;
777 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
778 return 0;
781 static int open_callback(const struct option *opt, const char *arg, int unset)
783 struct grep_opt *grep_opt = opt->value;
784 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
785 return 0;
788 static int close_callback(const struct option *opt, const char *arg, int unset)
790 struct grep_opt *grep_opt = opt->value;
791 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
792 return 0;
795 static int pattern_callback(const struct option *opt, const char *arg,
796 int unset)
798 struct grep_opt *grep_opt = opt->value;
799 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
800 return 0;
803 static int help_callback(const struct option *opt, const char *arg, int unset)
805 return -1;
808 int cmd_grep(int argc, const char **argv, const char *prefix)
810 int hit = 0;
811 int cached = 0;
812 int seen_dashdash = 0;
813 int external_grep_allowed__ignored;
814 const char *show_in_pager = NULL, *default_pager = "dummy";
815 struct grep_opt opt;
816 struct object_array list = { 0, 0, NULL };
817 const char **paths = NULL;
818 struct string_list path_list = { NULL, 0, 0, 0 };
819 int i;
820 int dummy;
821 int nongit = 0, use_index = 1;
822 struct option options[] = {
823 OPT_BOOLEAN(0, "cached", &cached,
824 "search in index instead of in the work tree"),
825 OPT_BOOLEAN(0, "index", &use_index,
826 "--no-index finds in contents not managed by git"),
827 OPT_GROUP(""),
828 OPT_BOOLEAN('v', "invert-match", &opt.invert,
829 "show non-matching lines"),
830 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
831 "case insensitive matching"),
832 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
833 "match patterns only at word boundaries"),
834 OPT_SET_INT('a', "text", &opt.binary,
835 "process binary files as text", GREP_BINARY_TEXT),
836 OPT_SET_INT('I', NULL, &opt.binary,
837 "don't match patterns in binary files",
838 GREP_BINARY_NOMATCH),
839 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
840 "descend at most <depth> levels", PARSE_OPT_NONEG,
841 NULL, 1 },
842 OPT_GROUP(""),
843 OPT_BIT('E', "extended-regexp", &opt.regflags,
844 "use extended POSIX regular expressions", REG_EXTENDED),
845 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
846 "use basic POSIX regular expressions (default)",
847 REG_EXTENDED),
848 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
849 "interpret patterns as fixed strings"),
850 OPT_GROUP(""),
851 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
852 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
853 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
854 OPT_NEGBIT(0, "full-name", &opt.relative,
855 "show filenames relative to top directory", 1),
856 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
857 "show only filenames instead of matching lines"),
858 OPT_BOOLEAN(0, "name-only", &opt.name_only,
859 "synonym for --files-with-matches"),
860 OPT_BOOLEAN('L', "files-without-match",
861 &opt.unmatch_name_only,
862 "show only the names of files without match"),
863 OPT_BOOLEAN('z', "null", &opt.null_following_name,
864 "print NUL after filenames"),
865 OPT_BOOLEAN('c', "count", &opt.count,
866 "show the number of matches instead of matching lines"),
867 OPT__COLOR(&opt.color, "highlight matches"),
868 OPT_GROUP(""),
869 OPT_CALLBACK('C', NULL, &opt, "n",
870 "show <n> context lines before and after matches",
871 context_callback),
872 OPT_INTEGER('B', NULL, &opt.pre_context,
873 "show <n> context lines before matches"),
874 OPT_INTEGER('A', NULL, &opt.post_context,
875 "show <n> context lines after matches"),
876 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
877 context_callback),
878 OPT_BOOLEAN('p', "show-function", &opt.funcname,
879 "show a line with the function name before matches"),
880 OPT_GROUP(""),
881 OPT_CALLBACK('f', NULL, &opt, "file",
882 "read patterns from file", file_callback),
883 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
884 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
885 { OPTION_CALLBACK, 0, "and", &opt, NULL,
886 "combine patterns specified with -e",
887 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
888 OPT_BOOLEAN(0, "or", &dummy, ""),
889 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
890 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
891 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
892 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
893 open_callback },
894 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
895 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
896 close_callback },
897 OPT_BOOLEAN('q', "quiet", &opt.status_only,
898 "indicate hit with exit status without output"),
899 OPT_BOOLEAN(0, "all-match", &opt.all_match,
900 "show only matches from files that match all patterns"),
901 OPT_GROUP(""),
902 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
903 "pager", "show matching files in the pager",
904 PARSE_OPT_OPTARG, NULL, (intptr_t)default_pager },
905 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
906 "allow calling of grep(1) (ignored by this build)"),
907 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
908 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
909 OPT_END()
912 prefix = setup_git_directory_gently(&nongit);
915 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
916 * to show usage information and exit.
918 if (argc == 2 && !strcmp(argv[1], "-h"))
919 usage_with_options(grep_usage, options);
921 memset(&opt, 0, sizeof(opt));
922 opt.prefix = prefix;
923 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
924 opt.relative = 1;
925 opt.pathname = 1;
926 opt.pattern_tail = &opt.pattern_list;
927 opt.header_tail = &opt.header_list;
928 opt.regflags = REG_NEWLINE;
929 opt.max_depth = -1;
931 strcpy(opt.color_context, "");
932 strcpy(opt.color_filename, "");
933 strcpy(opt.color_function, "");
934 strcpy(opt.color_lineno, "");
935 strcpy(opt.color_match, GIT_COLOR_BOLD_RED);
936 strcpy(opt.color_selected, "");
937 strcpy(opt.color_sep, GIT_COLOR_CYAN);
938 opt.color = -1;
939 git_config(grep_config, &opt);
940 if (opt.color == -1)
941 opt.color = git_use_color_default;
944 * If there is no -- then the paths must exist in the working
945 * tree. If there is no explicit pattern specified with -e or
946 * -f, we take the first unrecognized non option to be the
947 * pattern, but then what follows it must be zero or more
948 * valid refs up to the -- (if exists), and then existing
949 * paths. If there is an explicit pattern, then the first
950 * unrecognized non option is the beginning of the refs list
951 * that continues up to the -- (if exists), and then paths.
953 argc = parse_options(argc, argv, prefix, options, grep_usage,
954 PARSE_OPT_KEEP_DASHDASH |
955 PARSE_OPT_STOP_AT_NON_OPTION |
956 PARSE_OPT_NO_INTERNAL_HELP);
958 if (use_index && nongit)
959 /* die the same way as if we did it at the beginning */
960 setup_git_directory();
963 * skip a -- separator; we know it cannot be
964 * separating revisions from pathnames if
965 * we haven't even had any patterns yet
967 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
968 argv++;
969 argc--;
972 /* First unrecognized non-option token */
973 if (argc > 0 && !opt.pattern_list) {
974 append_grep_pattern(&opt, argv[0], "command line", 0,
975 GREP_PATTERN);
976 argv++;
977 argc--;
980 if (show_in_pager) {
981 if (show_in_pager == default_pager) {
982 show_in_pager = getenv("GIT_PAGER");
983 if (!show_in_pager)
984 show_in_pager = getenv("PAGER");
985 if (!show_in_pager)
986 show_in_pager = "less";
988 opt.name_only = 1;
989 opt.null_following_name = 1;
990 opt.output_priv = &path_list;
991 opt.output = append_path;
992 string_list_append(show_in_pager, &path_list);
993 use_threads = 0;
996 if (!opt.pattern_list)
997 die("no pattern given.");
998 if (!opt.fixed && opt.ignore_case)
999 opt.regflags |= REG_ICASE;
1000 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
1001 die("cannot mix --fixed-strings and regexp");
1003 #ifndef NO_PTHREADS
1004 if (online_cpus() == 1 || !grep_threads_ok(&opt))
1005 use_threads = 0;
1007 if (use_threads) {
1008 if (opt.pre_context || opt.post_context)
1009 print_hunk_marks_between_files = 1;
1010 start_threads(&opt);
1012 #else
1013 use_threads = 0;
1014 #endif
1016 compile_grep_patterns(&opt);
1018 /* Check revs and then paths */
1019 for (i = 0; i < argc; i++) {
1020 const char *arg = argv[i];
1021 unsigned char sha1[20];
1022 /* Is it a rev? */
1023 if (!get_sha1(arg, sha1)) {
1024 struct object *object = parse_object(sha1);
1025 if (!object)
1026 die("bad object %s", arg);
1027 add_object_array(object, arg, &list);
1028 continue;
1030 if (!strcmp(arg, "--")) {
1031 i++;
1032 seen_dashdash = 1;
1034 break;
1037 /* The rest are paths */
1038 if (!seen_dashdash) {
1039 int j;
1040 for (j = i; j < argc; j++)
1041 verify_filename(prefix, argv[j]);
1044 if (i < argc)
1045 paths = get_pathspec(prefix, argv + i);
1046 else if (prefix) {
1047 paths = xcalloc(2, sizeof(const char *));
1048 paths[0] = prefix;
1049 paths[1] = NULL;
1052 if (!use_index) {
1053 int hit;
1054 if (cached)
1055 die("--cached cannot be used with --no-index.");
1056 if (list.nr)
1057 die("--no-index cannot be used with revs.");
1058 hit = grep_directory(&opt, paths);
1059 if (use_threads)
1060 hit |= wait_all();
1061 return !hit;
1064 if (show_in_pager && (cached || list.nr))
1065 die ("--open-files-in-pager only works on the worktree");
1067 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1068 const char *pager = path_list.items[0].string;
1069 int len = strlen(pager);
1071 if (len > 4 && is_dir_sep(pager[len - 5]))
1072 pager += len - 4;
1074 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1075 struct strbuf buf = STRBUF_INIT;
1076 strbuf_addf(&buf, "+/%s%s",
1077 strcmp("less", pager) ? "" : "*",
1078 opt.pattern_list->pattern);
1079 string_list_append(buf.buf, &path_list);
1080 strbuf_detach(&buf, NULL);
1084 if (!show_in_pager)
1085 setup_pager();
1087 if (!list.nr) {
1088 if (!cached)
1089 setup_work_tree();
1091 hit = grep_cache(&opt, paths, cached);
1093 else if (cached)
1094 die("both --cached and trees are given.");
1095 else
1096 for (i = 0; i < list.nr; i++) {
1097 struct object *real_obj;
1098 real_obj = deref_tag(list.objects[i].item, NULL, 0);
1099 if (grep_object(&opt, paths, real_obj,
1100 list.objects[i].name)) {
1101 hit = 1;
1102 if (opt.status_only)
1103 break;
1107 if (use_threads)
1108 hit |= wait_all();
1110 if (hit && show_in_pager)
1111 run_pager(&opt, prefix);
1113 free_grep_patterns(&opt);
1114 return !hit;