gitweb: Syntax highlighting support
[git/dscho.git] / builtin-grep.c
blob26bf1165288532a3afc76b1bf3ffbefd2efc2115
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 void perform_substitutions(struct grep_opt *opt,
554 const char *substitute, const char *prefix, int cached)
556 int i;
558 die ("TODO!!!");
559 for (i = 0; i < opt->collect_file_names->nr; i++) {
560 if (cached)
561 die ("TODO!");
562 die ("TODO!!!");
566 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
568 int hit = 0;
569 int nr;
570 read_cache();
572 for (nr = 0; nr < active_nr; nr++) {
573 struct cache_entry *ce = active_cache[nr];
574 if (!S_ISREG(ce->ce_mode))
575 continue;
576 if (!pathspec_matches(paths, ce->name, opt->max_depth))
577 continue;
579 * If CE_VALID is on, we assume worktree file and its cache entry
580 * are identical, even if worktree file has been modified, so use
581 * cache version instead
583 if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
584 if (ce_stage(ce))
585 continue;
586 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
588 else
589 hit |= grep_file(opt, ce->name);
590 if (ce_stage(ce)) {
591 do {
592 nr++;
593 } while (nr < active_nr &&
594 !strcmp(ce->name, active_cache[nr]->name));
595 nr--; /* compensate for loop control */
597 if (hit && opt->status_only)
598 break;
600 return hit;
603 static int grep_tree(struct grep_opt *opt, const char **paths,
604 struct tree_desc *tree,
605 const char *tree_name, const char *base)
607 int len;
608 int hit = 0;
609 struct name_entry entry;
610 char *down;
611 int tn_len = strlen(tree_name);
612 struct strbuf pathbuf;
614 strbuf_init(&pathbuf, PATH_MAX + tn_len);
616 if (tn_len) {
617 strbuf_add(&pathbuf, tree_name, tn_len);
618 strbuf_addch(&pathbuf, ':');
619 tn_len = pathbuf.len;
621 strbuf_addstr(&pathbuf, base);
622 len = pathbuf.len;
624 while (tree_entry(tree, &entry)) {
625 int te_len = tree_entry_len(entry.path, entry.sha1);
626 pathbuf.len = len;
627 strbuf_add(&pathbuf, entry.path, te_len);
629 if (S_ISDIR(entry.mode))
630 /* Match "abc/" against pathspec to
631 * decide if we want to descend into "abc"
632 * directory.
634 strbuf_addch(&pathbuf, '/');
636 down = pathbuf.buf + tn_len;
637 if (!pathspec_matches(paths, down, opt->max_depth))
639 else if (S_ISREG(entry.mode))
640 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
641 else if (S_ISDIR(entry.mode)) {
642 enum object_type type;
643 struct tree_desc sub;
644 void *data;
645 unsigned long size;
647 read_sha1_lock();
648 data = read_sha1_file(entry.sha1, &type, &size);
649 read_sha1_unlock();
651 if (!data)
652 die("unable to read tree (%s)",
653 sha1_to_hex(entry.sha1));
654 init_tree_desc(&sub, data, size);
655 hit |= grep_tree(opt, paths, &sub, tree_name, down);
656 free(data);
658 if (hit && opt->status_only)
659 break;
661 strbuf_release(&pathbuf);
662 return hit;
665 static int grep_object(struct grep_opt *opt, const char **paths,
666 struct object *obj, const char *name)
668 if (obj->type == OBJ_BLOB)
669 return grep_sha1(opt, obj->sha1, name, 0);
670 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
671 struct tree_desc tree;
672 void *data;
673 unsigned long size;
674 int hit;
675 data = read_object_with_reference(obj->sha1, tree_type,
676 &size, NULL);
677 if (!data)
678 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
679 init_tree_desc(&tree, data, size);
680 hit = grep_tree(opt, paths, &tree, name, "");
681 free(data);
682 return hit;
684 die("unable to grep from object of type %s", typename(obj->type));
687 static int grep_directory(struct grep_opt *opt, const char **paths)
689 struct dir_struct dir;
690 int i, hit = 0;
692 memset(&dir, 0, sizeof(dir));
693 setup_standard_excludes(&dir);
695 fill_directory(&dir, paths);
696 for (i = 0; i < dir.nr; i++) {
697 hit |= grep_file(opt, dir.entries[i]->name);
698 if (hit && opt->status_only)
699 break;
701 return hit;
704 static int context_callback(const struct option *opt, const char *arg,
705 int unset)
707 struct grep_opt *grep_opt = opt->value;
708 int value;
709 const char *endp;
711 if (unset) {
712 grep_opt->pre_context = grep_opt->post_context = 0;
713 return 0;
715 value = strtol(arg, (char **)&endp, 10);
716 if (*endp) {
717 return error("switch `%c' expects a numerical value",
718 opt->short_name);
720 grep_opt->pre_context = grep_opt->post_context = value;
721 return 0;
724 static int file_callback(const struct option *opt, const char *arg, int unset)
726 struct grep_opt *grep_opt = opt->value;
727 FILE *patterns;
728 int lno = 0;
729 struct strbuf sb = STRBUF_INIT;
731 patterns = fopen(arg, "r");
732 if (!patterns)
733 die_errno("cannot open '%s'", arg);
734 while (strbuf_getline(&sb, patterns, '\n') == 0) {
735 /* ignore empty line like grep does */
736 if (sb.len == 0)
737 continue;
738 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
739 ++lno, GREP_PATTERN);
741 fclose(patterns);
742 strbuf_release(&sb);
743 return 0;
746 static int not_callback(const struct option *opt, const char *arg, int unset)
748 struct grep_opt *grep_opt = opt->value;
749 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
750 return 0;
753 static int and_callback(const struct option *opt, const char *arg, int unset)
755 struct grep_opt *grep_opt = opt->value;
756 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
757 return 0;
760 static int open_callback(const struct option *opt, const char *arg, int unset)
762 struct grep_opt *grep_opt = opt->value;
763 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
764 return 0;
767 static int close_callback(const struct option *opt, const char *arg, int unset)
769 struct grep_opt *grep_opt = opt->value;
770 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
771 return 0;
774 static int pattern_callback(const struct option *opt, const char *arg,
775 int unset)
777 struct grep_opt *grep_opt = opt->value;
778 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
779 return 0;
782 static int help_callback(const struct option *opt, const char *arg, int unset)
784 return -1;
787 int cmd_grep(int argc, const char **argv, const char *prefix)
789 int hit = 0;
790 int cached = 0;
791 int seen_dashdash = 0;
792 int external_grep_allowed__ignored;
793 const char *show_in_pager = NULL, *default_pager = "dummy";
794 const char *substitute = NULL;
795 struct grep_opt opt;
796 struct object_array list = { 0, 0, NULL };
797 const char **paths = NULL;
798 struct string_list path_list = { NULL, 0, 0, 0 };
799 int i;
800 int dummy;
801 int nongit = 0, use_index = 1;
802 struct option options[] = {
803 OPT_BOOLEAN(0, "cached", &cached,
804 "search in index instead of in the work tree"),
805 OPT_BOOLEAN(0, "index", &use_index,
806 "--no-index finds in contents not managed by git"),
807 OPT_GROUP(""),
808 OPT_BOOLEAN('v', "invert-match", &opt.invert,
809 "show non-matching lines"),
810 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
811 "case insensitive matching"),
812 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
813 "match patterns only at word boundaries"),
814 OPT_SET_INT('a', "text", &opt.binary,
815 "process binary files as text", GREP_BINARY_TEXT),
816 OPT_SET_INT('I', NULL, &opt.binary,
817 "don't match patterns in binary files",
818 GREP_BINARY_NOMATCH),
819 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
820 "descend at most <depth> levels", PARSE_OPT_NONEG,
821 NULL, 1 },
822 OPT_GROUP(""),
823 OPT_BIT('E', "extended-regexp", &opt.regflags,
824 "use extended POSIX regular expressions", REG_EXTENDED),
825 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
826 "use basic POSIX regular expressions (default)",
827 REG_EXTENDED),
828 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
829 "interpret patterns as fixed strings"),
830 OPT_GROUP(""),
831 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
832 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
833 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
834 OPT_NEGBIT(0, "full-name", &opt.relative,
835 "show filenames relative to top directory", 1),
836 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
837 "show only filenames instead of matching lines"),
838 OPT_BOOLEAN(0, "name-only", &opt.name_only,
839 "synonym for --files-with-matches"),
840 OPT_BOOLEAN('L', "files-without-match",
841 &opt.unmatch_name_only,
842 "show only the names of files without match"),
843 OPT_BOOLEAN('z', "null", &opt.null_following_name,
844 "print NUL after filenames"),
845 OPT_BOOLEAN('c', "count", &opt.count,
846 "show the number of matches instead of matching lines"),
847 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
848 OPT_GROUP(""),
849 OPT_CALLBACK('C', NULL, &opt, "n",
850 "show <n> context lines before and after matches",
851 context_callback),
852 OPT_INTEGER('B', NULL, &opt.pre_context,
853 "show <n> context lines before matches"),
854 OPT_INTEGER('A', NULL, &opt.post_context,
855 "show <n> context lines after matches"),
856 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
857 context_callback),
858 OPT_BOOLEAN('p', "show-function", &opt.funcname,
859 "show a line with the function name before matches"),
860 OPT_GROUP(""),
861 OPT_CALLBACK('f', NULL, &opt, "file",
862 "read patterns from file", file_callback),
863 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
864 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
865 { OPTION_CALLBACK, 0, "and", &opt, NULL,
866 "combine patterns specified with -e",
867 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
868 OPT_BOOLEAN(0, "or", &dummy, ""),
869 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
870 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
871 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
872 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
873 open_callback },
874 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
875 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
876 close_callback },
877 OPT_BOOLEAN('q', "quiet", &opt.status_only,
878 "indicate hit with exit status without output"),
879 OPT_BOOLEAN(0, "all-match", &opt.all_match,
880 "show only matches from files that match all patterns"),
881 OPT_GROUP(""),
882 { OPTION_STRING, 'P', "open-files-in-pager", &show_in_pager,
883 "pager", "show matching files in the pager",
884 PARSE_OPT_OPTARG, NULL, (intptr_t)default_pager },
885 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
886 "allow calling of grep(1) (ignored by this build)"),
887 OPT_STRING(0, "--substitute", &substitute,
888 "substitute (single) regular expression", NULL),
889 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
890 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
891 OPT_END()
894 prefix = setup_git_directory_gently(&nongit);
897 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
898 * to show usage information and exit.
900 if (argc == 2 && !strcmp(argv[1], "-h"))
901 usage_with_options(grep_usage, options);
903 memset(&opt, 0, sizeof(opt));
904 opt.prefix = prefix;
905 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
906 opt.relative = 1;
907 opt.pathname = 1;
908 opt.pattern_tail = &opt.pattern_list;
909 opt.regflags = REG_NEWLINE;
910 opt.max_depth = -1;
912 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
913 opt.color = -1;
914 git_config(grep_config, &opt);
915 if (opt.color == -1)
916 opt.color = git_use_color_default;
919 * If there is no -- then the paths must exist in the working
920 * tree. If there is no explicit pattern specified with -e or
921 * -f, we take the first unrecognized non option to be the
922 * pattern, but then what follows it must be zero or more
923 * valid refs up to the -- (if exists), and then existing
924 * paths. If there is an explicit pattern, then the first
925 * unrecognized non option is the beginning of the refs list
926 * that continues up to the -- (if exists), and then paths.
928 argc = parse_options(argc, argv, prefix, options, grep_usage,
929 PARSE_OPT_KEEP_DASHDASH |
930 PARSE_OPT_STOP_AT_NON_OPTION |
931 PARSE_OPT_NO_INTERNAL_HELP);
933 if (use_index && nongit)
934 /* die the same way as if we did it at the beginning */
935 setup_git_directory();
937 /* First unrecognized non-option token */
938 if (argc > 0 && !opt.pattern_list) {
939 append_grep_pattern(&opt, argv[0], "command line", 0,
940 GREP_PATTERN);
941 argv++;
942 argc--;
945 if (show_in_pager) {
946 if (show_in_pager == default_pager) {
947 show_in_pager = getenv("GIT_PAGER");
948 if (!show_in_pager)
949 show_in_pager = getenv("PAGER");
950 if (!show_in_pager)
951 show_in_pager = "less";
953 opt.name_only = 1;
954 opt.null_following_name = 1;
955 opt.output_priv = &path_list;
956 opt.output = append_path;
957 string_list_append(show_in_pager, &path_list);
958 use_threads = 0;
961 if (!opt.pattern_list)
962 die("no pattern given.");
963 if (!opt.fixed && opt.ignore_case)
964 opt.regflags |= REG_ICASE;
965 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
966 die("cannot mix --fixed-strings and regexp");
968 #ifndef NO_PTHREADS
969 if (online_cpus() == 1 || !grep_threads_ok(&opt))
970 use_threads = 0;
972 if (use_threads)
973 start_threads(&opt);
974 #else
975 use_threads = 0;
976 #endif
978 compile_grep_patterns(&opt);
980 /* Check revs and then paths */
981 for (i = 0; i < argc; i++) {
982 const char *arg = argv[i];
983 unsigned char sha1[20];
984 /* Is it a rev? */
985 if (!get_sha1(arg, sha1)) {
986 struct object *object = parse_object(sha1);
987 if (!object)
988 die("bad object %s", arg);
989 add_object_array(object, arg, &list);
990 continue;
992 if (!strcmp(arg, "--")) {
993 i++;
994 seen_dashdash = 1;
996 break;
999 /* The rest are paths */
1000 if (!seen_dashdash) {
1001 int j;
1002 for (j = i; j < argc; j++)
1003 verify_filename(prefix, argv[j]);
1006 if (i < argc)
1007 paths = get_pathspec(prefix, argv + i);
1008 else if (prefix) {
1009 paths = xcalloc(2, sizeof(const char *));
1010 paths[0] = prefix;
1011 paths[1] = NULL;
1014 warning ("TODO: audit incompatible options");
1015 if (substitute && list.nr)
1016 die ("--substitute is incompatible with rev parameters");
1018 if (substitute && (!opt.pattern_list || opt.pattern_list->next))
1019 die ("--substitute needs exactly one pattern");
1021 if (show_in_pager && cached)
1022 die ("--open-files-in-pager and --cached are incompatible");
1024 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1025 const char *pager = path_list.items[0].string;
1026 int len = strlen(pager);
1028 if (len > 4 && is_dir_sep(pager[len - 5]))
1029 pager += len - 4;
1031 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1032 struct strbuf buf = STRBUF_INIT;
1033 strbuf_addf(&buf, "+/%s%s",
1034 strcmp("less", pager) ? "" : "*",
1035 opt.pattern_list->pattern);
1036 string_list_append(buf.buf, &path_list);
1037 strbuf_detach(&buf, NULL);
1041 if (!show_in_pager)
1042 setup_pager();
1044 if (!use_index) {
1045 if (cached)
1046 die("--cached cannot be used with --no-index.");
1047 if (list.nr)
1048 die("--no-index cannot be used with revs.");
1049 hit = grep_directory(&opt, paths);
1051 else if (!list.nr) {
1052 if (!cached)
1053 setup_work_tree();
1055 hit = grep_cache(&opt, paths, cached);
1057 else if (cached)
1058 die("both --cached and trees are given.");
1059 else
1060 for (i = 0; i < list.nr; i++) {
1061 struct object *real_obj;
1062 real_obj = deref_tag(list.objects[i].item, NULL, 0);
1063 if (grep_object(&opt, paths, real_obj,
1064 list.objects[i].name)) {
1065 hit = 1;
1066 if (opt.status_only)
1067 break;
1071 if (use_threads)
1072 hit |= wait_all();
1074 if (hit && show_in_pager)
1075 run_pager(&opt, prefix);
1077 if (hit && substitute)
1078 perform_substitutions(&opt, substitute, prefix, cached);
1080 free_grep_patterns(&opt);
1081 return !hit;