Make CFLAGS more strict
[git/dscho.git] / builtin-grep.c
blob0ef849cb84650705ffc840aed8a3fcedbeb48f9a
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"
19 #ifndef NO_PTHREADS
20 #include "thread-utils.h"
21 #include <pthread.h>
22 #endif
24 static char const * const grep_usage[] = {
25 "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
26 NULL
29 static int use_threads = 1;
31 #ifndef NO_PTHREADS
32 #define THREADS 8
33 static pthread_t threads[THREADS];
35 static void *load_sha1(const unsigned char *sha1, unsigned long *size,
36 const char *name);
37 static void *load_file(const char *filename, size_t *sz);
39 enum work_type {WORK_SHA1, WORK_FILE};
41 /* We use one producer thread and THREADS consumer
42 * threads. The producer adds struct work_items to 'todo' and the
43 * consumers pick work items from the same array.
45 struct work_item
47 enum work_type type;
48 char *name;
50 /* if type == WORK_SHA1, then 'identifier' is a SHA1,
51 * otherwise type == WORK_FILE, and 'identifier' is a NUL
52 * terminated filename.
54 void *identifier;
55 char done;
56 struct strbuf out;
59 /* In the range [todo_done, todo_start) in 'todo' we have work_items
60 * that have been or are processed by a consumer thread. We haven't
61 * written the result for these to stdout yet.
63 * The work_items in [todo_start, todo_end) are waiting to be picked
64 * up by a consumer thread.
66 * The ranges are modulo TODO_SIZE.
68 #define TODO_SIZE 128
69 static struct work_item todo[TODO_SIZE];
70 static int todo_start;
71 static int todo_end;
72 static int todo_done;
74 /* Has all work items been added? */
75 static int all_work_added;
77 /* This lock protects all the variables above. */
78 static pthread_mutex_t grep_mutex;
80 /* Used to serialize calls to read_sha1_file. */
81 static pthread_mutex_t read_sha1_mutex;
83 #define grep_lock() pthread_mutex_lock(&grep_mutex)
84 #define grep_unlock() pthread_mutex_unlock(&grep_mutex)
85 #define read_sha1_lock() pthread_mutex_lock(&read_sha1_mutex)
86 #define read_sha1_unlock() pthread_mutex_unlock(&read_sha1_mutex)
88 /* Signalled when a new work_item is added to todo. */
89 static pthread_cond_t cond_add;
91 /* Signalled when the result from one work_item is written to
92 * stdout.
94 static pthread_cond_t cond_write;
96 /* Signalled when we are finished with everything. */
97 static pthread_cond_t cond_result;
99 static void add_work(enum work_type type, char *name, void *id)
101 grep_lock();
103 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
104 pthread_cond_wait(&cond_write, &grep_mutex);
107 todo[todo_end].type = type;
108 todo[todo_end].name = name;
109 todo[todo_end].identifier = id;
110 todo[todo_end].done = 0;
111 strbuf_reset(&todo[todo_end].out);
112 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
114 pthread_cond_signal(&cond_add);
115 grep_unlock();
118 static struct work_item *get_work(void)
120 struct work_item *ret;
122 grep_lock();
123 while (todo_start == todo_end && !all_work_added) {
124 pthread_cond_wait(&cond_add, &grep_mutex);
127 if (todo_start == todo_end && all_work_added) {
128 ret = NULL;
129 } else {
130 ret = &todo[todo_start];
131 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
133 grep_unlock();
134 return ret;
137 static void grep_sha1_async(struct grep_opt *opt, char *name,
138 const unsigned char *sha1)
140 unsigned char *s;
141 s = xmalloc(20);
142 memcpy(s, sha1, 20);
143 add_work(WORK_SHA1, name, s);
146 static void grep_file_async(struct grep_opt *opt, char *name,
147 const char *filename)
149 add_work(WORK_FILE, name, xstrdup(filename));
152 static void work_done(struct work_item *w)
154 int old_done;
156 grep_lock();
157 w->done = 1;
158 old_done = todo_done;
159 for(; todo[todo_done].done && todo_done != todo_start;
160 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
161 w = &todo[todo_done];
162 write_or_die(1, w->out.buf, w->out.len);
163 free(w->name);
164 free(w->identifier);
167 if (old_done != todo_done)
168 pthread_cond_signal(&cond_write);
170 if (all_work_added && todo_done == todo_end)
171 pthread_cond_signal(&cond_result);
173 grep_unlock();
176 static void *run(void *arg)
178 int hit = 0;
179 struct grep_opt *opt = arg;
181 while (1) {
182 struct work_item *w = get_work();
183 if (!w)
184 break;
186 opt->output_priv = w;
187 if (w->type == WORK_SHA1) {
188 unsigned long sz;
189 void* data = load_sha1(w->identifier, &sz, w->name);
191 if (data) {
192 hit |= grep_buffer(opt, w->name, data, sz);
193 free(data);
195 } else if (w->type == WORK_FILE) {
196 size_t sz;
197 void* data = load_file(w->identifier, &sz);
198 if (data) {
199 hit |= grep_buffer(opt, w->name, data, sz);
200 free(data);
202 } else {
203 assert(0);
206 work_done(w);
208 free_grep_patterns(arg);
209 free(arg);
211 return (void*) (intptr_t) hit;
214 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
216 struct work_item *w = opt->output_priv;
217 strbuf_add(&w->out, buf, size);
220 static void start_threads(struct grep_opt *opt)
222 int i;
224 pthread_mutex_init(&grep_mutex, NULL);
225 pthread_mutex_init(&read_sha1_mutex, NULL);
226 pthread_cond_init(&cond_add, NULL);
227 pthread_cond_init(&cond_write, NULL);
228 pthread_cond_init(&cond_result, NULL);
230 for (i = 0; i < ARRAY_SIZE(todo); i++) {
231 strbuf_init(&todo[i].out, 0);
234 for (i = 0; i < ARRAY_SIZE(threads); i++) {
235 int err;
236 struct grep_opt *o = grep_opt_dup(opt);
237 o->output = strbuf_out;
238 compile_grep_patterns(o);
239 err = pthread_create(&threads[i], NULL, run, o);
241 if (err)
242 die("grep: failed to create thread: %s",
243 strerror(err));
247 static int wait_all(void)
249 int hit = 0;
250 int i;
252 grep_lock();
253 all_work_added = 1;
255 /* Wait until all work is done. */
256 while (todo_done != todo_end)
257 pthread_cond_wait(&cond_result, &grep_mutex);
259 /* Wake up all the consumer threads so they can see that there
260 * is no more work to do.
262 pthread_cond_broadcast(&cond_add);
263 grep_unlock();
265 for (i = 0; i < ARRAY_SIZE(threads); i++) {
266 void *h;
267 pthread_join(threads[i], &h);
268 hit |= (int) (intptr_t) h;
271 pthread_mutex_destroy(&grep_mutex);
272 pthread_mutex_destroy(&read_sha1_mutex);
273 pthread_cond_destroy(&cond_add);
274 pthread_cond_destroy(&cond_write);
275 pthread_cond_destroy(&cond_result);
277 return hit;
279 #else /* !NO_PTHREADS */
280 #define read_sha1_lock()
281 #define read_sha1_unlock()
283 static int wait_all(void)
285 return 0;
287 #endif
289 static int grep_config(const char *var, const char *value, void *cb)
291 struct grep_opt *opt = cb;
293 switch (userdiff_config(var, value)) {
294 case 0: break;
295 case -1: return -1;
296 default: return 0;
299 if (!strcmp(var, "color.grep")) {
300 opt->color = git_config_colorbool(var, value, -1);
301 return 0;
303 if (!strcmp(var, "color.grep.match")) {
304 if (!value)
305 return config_error_nonbool(var);
306 color_parse(value, var, opt->color_match);
307 return 0;
309 return git_color_default_config(var, value, cb);
313 * Return non-zero if max_depth is negative or path has no more then max_depth
314 * slashes.
316 static int accept_subdir(const char *path, int max_depth)
318 if (max_depth < 0)
319 return 1;
321 while ((path = strchr(path, '/')) != NULL) {
322 max_depth--;
323 if (max_depth < 0)
324 return 0;
325 path++;
327 return 1;
331 * Return non-zero if name is a subdirectory of match and is not too deep.
333 static int is_subdir(const char *name, int namelen,
334 const char *match, int matchlen, int max_depth)
336 if (matchlen > namelen || strncmp(name, match, matchlen))
337 return 0;
339 if (name[matchlen] == '\0') /* exact match */
340 return 1;
342 if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
343 return accept_subdir(name + matchlen + 1, max_depth);
345 return 0;
349 * git grep pathspecs are somewhat different from diff-tree pathspecs;
350 * pathname wildcards are allowed.
352 static int pathspec_matches(const char **paths, const char *name, int max_depth)
354 int namelen, i;
355 if (!paths || !*paths)
356 return accept_subdir(name, max_depth);
357 namelen = strlen(name);
358 for (i = 0; paths[i]; i++) {
359 const char *match = paths[i];
360 int matchlen = strlen(match);
361 const char *cp, *meta;
363 if (is_subdir(name, namelen, match, matchlen, max_depth))
364 return 1;
365 if (!fnmatch(match, name, 0))
366 return 1;
367 if (name[namelen-1] != '/')
368 continue;
370 /* We are being asked if the directory ("name") is worth
371 * descending into.
373 * Find the longest leading directory name that does
374 * not have metacharacter in the pathspec; the name
375 * we are looking at must overlap with that directory.
377 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
378 char ch = *cp;
379 if (ch == '*' || ch == '[' || ch == '?') {
380 meta = cp;
381 break;
384 if (!meta)
385 meta = cp; /* fully literal */
387 if (namelen <= meta - match) {
388 /* Looking at "Documentation/" and
389 * the pattern says "Documentation/howto/", or
390 * "Documentation/diff*.txt". The name we
391 * have should match prefix.
393 if (!memcmp(match, name, namelen))
394 return 1;
395 continue;
398 if (meta - match < namelen) {
399 /* Looking at "Documentation/howto/" and
400 * the pattern says "Documentation/h*";
401 * match up to "Do.../h"; this avoids descending
402 * into "Documentation/technical/".
404 if (!memcmp(match, name, meta - match))
405 return 1;
406 continue;
409 return 0;
412 static void *load_sha1(const unsigned char *sha1, unsigned long *size,
413 const char *name)
415 enum object_type type;
416 char *data;
418 read_sha1_lock();
419 data = read_sha1_file(sha1, &type, size);
420 read_sha1_unlock();
422 if (!data)
423 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
425 return data;
428 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1,
429 const char *filename, int tree_name_len)
431 struct strbuf pathbuf = STRBUF_INIT;
432 char *name;
434 if (opt->relative && opt->prefix_length) {
435 quote_path_relative(filename + tree_name_len, -1, &pathbuf,
436 opt->prefix);
437 strbuf_insert(&pathbuf, 0, filename, tree_name_len);
438 } else {
439 strbuf_addstr(&pathbuf, filename);
442 name = strbuf_detach(&pathbuf, NULL);
444 #ifndef NO_PTHREADS
445 if (use_threads) {
446 grep_sha1_async(opt, name, sha1);
447 return 0;
448 } else
449 #endif
451 int hit;
452 unsigned long sz;
453 void *data = load_sha1(sha1, &sz, name);
454 if (!data)
455 hit = 0;
456 else
457 hit = grep_buffer(opt, name, data, sz);
459 free(data);
460 free(name);
461 return hit;
465 static void *load_file(const char *filename, size_t *sz)
467 struct stat st;
468 char *data;
469 int i;
471 if (lstat(filename, &st) < 0) {
472 err_ret:
473 if (errno != ENOENT)
474 error("'%s': %s", filename, strerror(errno));
475 return 0;
477 if (!S_ISREG(st.st_mode))
478 return 0;
479 *sz = xsize_t(st.st_size);
480 i = open(filename, O_RDONLY);
481 if (i < 0)
482 goto err_ret;
483 data = xmalloc(*sz + 1);
484 if (st.st_size != read_in_full(i, data, *sz)) {
485 error("'%s': short read %s", filename, strerror(errno));
486 close(i);
487 free(data);
488 return 0;
490 close(i);
491 data[*sz] = 0;
492 return data;
495 static int grep_file(struct grep_opt *opt, const char *filename)
497 struct strbuf buf = STRBUF_INIT;
498 char *name;
500 if (opt->relative && opt->prefix_length)
501 quote_path_relative(filename, -1, &buf, opt->prefix);
502 else
503 strbuf_addstr(&buf, filename);
504 name = strbuf_detach(&buf, NULL);
506 #ifndef NO_PTHREADS
507 if (use_threads) {
508 grep_file_async(opt, name, filename);
509 return 0;
510 } else
511 #endif
513 int hit;
514 size_t sz;
515 void *data = load_file(filename, &sz);
516 if (!data)
517 hit = 0;
518 else
519 hit = grep_buffer(opt, name, data, sz);
521 free(data);
522 free(name);
523 return hit;
527 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
529 int hit = 0;
530 int nr;
531 read_cache();
533 for (nr = 0; nr < active_nr; nr++) {
534 struct cache_entry *ce = active_cache[nr];
535 if (!S_ISREG(ce->ce_mode))
536 continue;
537 if (!pathspec_matches(paths, ce->name, opt->max_depth))
538 continue;
540 * If CE_VALID is on, we assume worktree file and its cache entry
541 * are identical, even if worktree file has been modified, so use
542 * cache version instead
544 if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
545 if (ce_stage(ce))
546 continue;
547 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
549 else
550 hit |= grep_file(opt, ce->name);
551 if (ce_stage(ce)) {
552 do {
553 nr++;
554 } while (nr < active_nr &&
555 !strcmp(ce->name, active_cache[nr]->name));
556 nr--; /* compensate for loop control */
558 if (hit && opt->status_only)
559 break;
561 free_grep_patterns(opt);
562 return hit;
565 static int grep_tree(struct grep_opt *opt, const char **paths,
566 struct tree_desc *tree,
567 const char *tree_name, const char *base)
569 int len;
570 int hit = 0;
571 struct name_entry entry;
572 char *down;
573 int tn_len = strlen(tree_name);
574 struct strbuf pathbuf;
576 strbuf_init(&pathbuf, PATH_MAX + tn_len);
578 if (tn_len) {
579 strbuf_add(&pathbuf, tree_name, tn_len);
580 strbuf_addch(&pathbuf, ':');
581 tn_len = pathbuf.len;
583 strbuf_addstr(&pathbuf, base);
584 len = pathbuf.len;
586 while (tree_entry(tree, &entry)) {
587 int te_len = tree_entry_len(entry.path, entry.sha1);
588 pathbuf.len = len;
589 strbuf_add(&pathbuf, entry.path, te_len);
591 if (S_ISDIR(entry.mode))
592 /* Match "abc/" against pathspec to
593 * decide if we want to descend into "abc"
594 * directory.
596 strbuf_addch(&pathbuf, '/');
598 down = pathbuf.buf + tn_len;
599 if (!pathspec_matches(paths, down, opt->max_depth))
601 else if (S_ISREG(entry.mode))
602 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
603 else if (S_ISDIR(entry.mode)) {
604 enum object_type type;
605 struct tree_desc sub;
606 void *data;
607 unsigned long size;
609 read_sha1_lock();
610 data = read_sha1_file(entry.sha1, &type, &size);
611 read_sha1_unlock();
613 if (!data)
614 die("unable to read tree (%s)",
615 sha1_to_hex(entry.sha1));
616 init_tree_desc(&sub, data, size);
617 hit |= grep_tree(opt, paths, &sub, tree_name, down);
618 free(data);
620 if (hit && opt->status_only)
621 break;
623 strbuf_release(&pathbuf);
624 return hit;
627 static int grep_object(struct grep_opt *opt, const char **paths,
628 struct object *obj, const char *name)
630 if (obj->type == OBJ_BLOB)
631 return grep_sha1(opt, obj->sha1, name, 0);
632 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
633 struct tree_desc tree;
634 void *data;
635 unsigned long size;
636 int hit;
637 data = read_object_with_reference(obj->sha1, tree_type,
638 &size, NULL);
639 if (!data)
640 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
641 init_tree_desc(&tree, data, size);
642 hit = grep_tree(opt, paths, &tree, name, "");
643 free(data);
644 return hit;
646 die("unable to grep from object of type %s", typename(obj->type));
649 static int grep_directory(struct grep_opt *opt, const char **paths)
651 struct dir_struct dir;
652 int i, hit = 0;
654 memset(&dir, 0, sizeof(dir));
655 setup_standard_excludes(&dir);
657 fill_directory(&dir, paths);
658 for (i = 0; i < dir.nr; i++) {
659 hit |= grep_file(opt, dir.entries[i]->name);
660 if (hit && opt->status_only)
661 break;
663 free_grep_patterns(opt);
664 return hit;
667 static int context_callback(const struct option *opt, const char *arg,
668 int unset)
670 struct grep_opt *grep_opt = opt->value;
671 int value;
672 const char *endp;
674 if (unset) {
675 grep_opt->pre_context = grep_opt->post_context = 0;
676 return 0;
678 value = strtol(arg, (char **)&endp, 10);
679 if (*endp) {
680 return error("switch `%c' expects a numerical value",
681 opt->short_name);
683 grep_opt->pre_context = grep_opt->post_context = value;
684 return 0;
687 static int file_callback(const struct option *opt, const char *arg, int unset)
689 struct grep_opt *grep_opt = opt->value;
690 FILE *patterns;
691 int lno = 0;
692 struct strbuf sb = STRBUF_INIT;
694 patterns = fopen(arg, "r");
695 if (!patterns)
696 die_errno("cannot open '%s'", arg);
697 while (strbuf_getline(&sb, patterns, '\n') == 0) {
698 /* ignore empty line like grep does */
699 if (sb.len == 0)
700 continue;
701 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
702 ++lno, GREP_PATTERN);
704 fclose(patterns);
705 strbuf_release(&sb);
706 return 0;
709 static int not_callback(const struct option *opt, const char *arg, int unset)
711 struct grep_opt *grep_opt = opt->value;
712 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
713 return 0;
716 static int and_callback(const struct option *opt, const char *arg, int unset)
718 struct grep_opt *grep_opt = opt->value;
719 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
720 return 0;
723 static int open_callback(const struct option *opt, const char *arg, int unset)
725 struct grep_opt *grep_opt = opt->value;
726 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
727 return 0;
730 static int close_callback(const struct option *opt, const char *arg, int unset)
732 struct grep_opt *grep_opt = opt->value;
733 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
734 return 0;
737 static int pattern_callback(const struct option *opt, const char *arg,
738 int unset)
740 struct grep_opt *grep_opt = opt->value;
741 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
742 return 0;
745 static int help_callback(const struct option *opt, const char *arg, int unset)
747 return -1;
750 int cmd_grep(int argc, const char **argv, const char *prefix)
752 int hit = 0;
753 int cached = 0;
754 int seen_dashdash = 0;
755 int external_grep_allowed__ignored;
756 struct grep_opt opt;
757 struct object_array list = { 0, 0, NULL };
758 const char **paths = NULL;
759 int i;
760 int dummy;
761 int nongit = 0, use_index = 1;
762 struct option options[] = {
763 OPT_BOOLEAN(0, "cached", &cached,
764 "search in index instead of in the work tree"),
765 OPT_BOOLEAN(0, "index", &use_index,
766 "--no-index finds in contents not managed by git"),
767 OPT_GROUP(""),
768 OPT_BOOLEAN('v', "invert-match", &opt.invert,
769 "show non-matching lines"),
770 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
771 "case insensitive matching"),
772 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
773 "match patterns only at word boundaries"),
774 OPT_SET_INT('a', "text", &opt.binary,
775 "process binary files as text", GREP_BINARY_TEXT),
776 OPT_SET_INT('I', NULL, &opt.binary,
777 "don't match patterns in binary files",
778 GREP_BINARY_NOMATCH),
779 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
780 "descend at most <depth> levels", PARSE_OPT_NONEG,
781 NULL, 1 },
782 OPT_GROUP(""),
783 OPT_BIT('E', "extended-regexp", &opt.regflags,
784 "use extended POSIX regular expressions", REG_EXTENDED),
785 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
786 "use basic POSIX regular expressions (default)",
787 REG_EXTENDED),
788 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
789 "interpret patterns as fixed strings"),
790 OPT_GROUP(""),
791 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
792 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
793 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
794 OPT_NEGBIT(0, "full-name", &opt.relative,
795 "show filenames relative to top directory", 1),
796 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
797 "show only filenames instead of matching lines"),
798 OPT_BOOLEAN(0, "name-only", &opt.name_only,
799 "synonym for --files-with-matches"),
800 OPT_BOOLEAN('L', "files-without-match",
801 &opt.unmatch_name_only,
802 "show only the names of files without match"),
803 OPT_BOOLEAN('z', "null", &opt.null_following_name,
804 "print NUL after filenames"),
805 OPT_BOOLEAN('c', "count", &opt.count,
806 "show the number of matches instead of matching lines"),
807 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
808 OPT_GROUP(""),
809 OPT_CALLBACK('C', NULL, &opt, "n",
810 "show <n> context lines before and after matches",
811 context_callback),
812 OPT_INTEGER('B', NULL, &opt.pre_context,
813 "show <n> context lines before matches"),
814 OPT_INTEGER('A', NULL, &opt.post_context,
815 "show <n> context lines after matches"),
816 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
817 context_callback),
818 OPT_BOOLEAN('p', "show-function", &opt.funcname,
819 "show a line with the function name before matches"),
820 OPT_GROUP(""),
821 OPT_CALLBACK('f', NULL, &opt, "file",
822 "read patterns from file", file_callback),
823 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
824 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
825 { OPTION_CALLBACK, 0, "and", &opt, NULL,
826 "combine patterns specified with -e",
827 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
828 OPT_BOOLEAN(0, "or", &dummy, ""),
829 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
830 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
831 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
832 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
833 open_callback },
834 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
835 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
836 close_callback },
837 OPT_BOOLEAN('q', "quiet", &opt.status_only,
838 "indicate hit with exit status without output"),
839 OPT_BOOLEAN(0, "all-match", &opt.all_match,
840 "show only matches from files that match all patterns"),
841 OPT_GROUP(""),
842 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
843 "allow calling of grep(1) (ignored by this build)"),
844 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
845 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
846 OPT_END()
849 prefix = setup_git_directory_gently(&nongit);
852 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
853 * to show usage information and exit.
855 if (argc == 2 && !strcmp(argv[1], "-h"))
856 usage_with_options(grep_usage, options);
858 memset(&opt, 0, sizeof(opt));
859 opt.prefix = prefix;
860 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
861 opt.relative = 1;
862 opt.pathname = 1;
863 opt.pattern_tail = &opt.pattern_list;
864 opt.regflags = REG_NEWLINE;
865 opt.max_depth = -1;
867 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
868 opt.color = -1;
869 git_config(grep_config, &opt);
870 if (opt.color == -1)
871 opt.color = git_use_color_default;
874 * If there is no -- then the paths must exist in the working
875 * tree. If there is no explicit pattern specified with -e or
876 * -f, we take the first unrecognized non option to be the
877 * pattern, but then what follows it must be zero or more
878 * valid refs up to the -- (if exists), and then existing
879 * paths. If there is an explicit pattern, then the first
880 * unrecognized non option is the beginning of the refs list
881 * that continues up to the -- (if exists), and then paths.
883 argc = parse_options(argc, argv, prefix, options, grep_usage,
884 PARSE_OPT_KEEP_DASHDASH |
885 PARSE_OPT_STOP_AT_NON_OPTION |
886 PARSE_OPT_NO_INTERNAL_HELP);
888 if (use_index && nongit)
889 /* die the same way as if we did it at the beginning */
890 setup_git_directory();
892 /* First unrecognized non-option token */
893 if (argc > 0 && !opt.pattern_list) {
894 append_grep_pattern(&opt, argv[0], "command line", 0,
895 GREP_PATTERN);
896 argv++;
897 argc--;
900 if (!opt.pattern_list)
901 die("no pattern given.");
902 if (!opt.fixed && opt.ignore_case)
903 opt.regflags |= REG_ICASE;
904 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
905 die("cannot mix --fixed-strings and regexp");
907 #ifndef NO_PTHREADS
908 if (online_cpus() == 1 || !grep_threads_ok(&opt))
909 use_threads = 0;
911 if (use_threads)
912 start_threads(&opt);
913 #else
914 use_threads = 0;
915 #endif
917 compile_grep_patterns(&opt);
919 /* Check revs and then paths */
920 for (i = 0; i < argc; i++) {
921 const char *arg = argv[i];
922 unsigned char sha1[20];
923 /* Is it a rev? */
924 if (!get_sha1(arg, sha1)) {
925 struct object *object = parse_object(sha1);
926 if (!object)
927 die("bad object %s", arg);
928 add_object_array(object, arg, &list);
929 continue;
931 if (!strcmp(arg, "--")) {
932 i++;
933 seen_dashdash = 1;
935 break;
938 /* The rest are paths */
939 if (!seen_dashdash) {
940 int j;
941 for (j = i; j < argc; j++)
942 verify_filename(prefix, argv[j]);
945 if (i < argc)
946 paths = get_pathspec(prefix, argv + i);
947 else if (prefix) {
948 paths = xcalloc(2, sizeof(const char *));
949 paths[0] = prefix;
950 paths[1] = NULL;
953 if (!use_index) {
954 int hit;
955 if (cached)
956 die("--cached cannot be used with --no-index.");
957 if (list.nr)
958 die("--no-index cannot be used with revs.");
959 hit = grep_directory(&opt, paths);
960 if (use_threads)
961 hit |= wait_all();
962 return !hit;
965 if (!list.nr) {
966 int hit;
967 if (!cached)
968 setup_work_tree();
970 hit = grep_cache(&opt, paths, cached);
971 if (use_threads)
972 hit |= wait_all();
973 return !hit;
976 if (cached)
977 die("both --cached and trees are given.");
979 for (i = 0; i < list.nr; i++) {
980 struct object *real_obj;
981 real_obj = deref_tag(list.objects[i].item, NULL, 0);
982 if (grep_object(&opt, paths, real_obj, list.objects[i].name)) {
983 hit = 1;
984 if (opt.status_only)
985 break;
989 if (use_threads)
990 hit |= wait_all();
991 free_grep_patterns(&opt);
992 return !hit;