t1510: setup case #10
[git/dkf.git] / builtin / grep.c
blob3d5f6ace97b806fd7dba9f8c5d62abcdbd903681
1 /*
2 * Builtin "git grep"
4 * Copyright (c) 2006 Junio C Hamano
5 */
6 #include "cache.h"
7 #include "blob.h"
8 #include "tree.h"
9 #include "commit.h"
10 #include "tag.h"
11 #include "tree-walk.h"
12 #include "builtin.h"
13 #include "parse-options.h"
14 #include "string-list.h"
15 #include "run-command.h"
16 #include "userdiff.h"
17 #include "grep.h"
18 #include "quote.h"
19 #include "dir.h"
21 #ifndef NO_PTHREADS
22 #include <pthread.h>
23 #include "thread-utils.h"
24 #endif
26 static char const * const grep_usage[] = {
27 "git grep [options] [-e] <pattern> [<rev>...] [[--] <path>...]",
28 NULL
31 static int use_threads = 1;
33 #ifndef NO_PTHREADS
34 #define THREADS 8
35 static pthread_t threads[THREADS];
37 static void *load_sha1(const unsigned char *sha1, unsigned long *size,
38 const char *name);
39 static void *load_file(const char *filename, size_t *sz);
41 enum work_type {WORK_SHA1, WORK_FILE};
43 /* We use one producer thread and THREADS consumer
44 * threads. The producer adds struct work_items to 'todo' and the
45 * consumers pick work items from the same array.
47 struct work_item
49 enum work_type type;
50 char *name;
52 /* if type == WORK_SHA1, then 'identifier' is a SHA1,
53 * otherwise type == WORK_FILE, and 'identifier' is a NUL
54 * terminated filename.
56 void *identifier;
57 char done;
58 struct strbuf out;
61 /* In the range [todo_done, todo_start) in 'todo' we have work_items
62 * that have been or are processed by a consumer thread. We haven't
63 * written the result for these to stdout yet.
65 * The work_items in [todo_start, todo_end) are waiting to be picked
66 * up by a consumer thread.
68 * The ranges are modulo TODO_SIZE.
70 #define TODO_SIZE 128
71 static struct work_item todo[TODO_SIZE];
72 static int todo_start;
73 static int todo_end;
74 static int todo_done;
76 /* Has all work items been added? */
77 static int all_work_added;
79 /* This lock protects all the variables above. */
80 static pthread_mutex_t grep_mutex;
82 /* Used to serialize calls to read_sha1_file. */
83 static pthread_mutex_t read_sha1_mutex;
85 #define grep_lock() pthread_mutex_lock(&grep_mutex)
86 #define grep_unlock() pthread_mutex_unlock(&grep_mutex)
87 #define read_sha1_lock() pthread_mutex_lock(&read_sha1_mutex)
88 #define read_sha1_unlock() pthread_mutex_unlock(&read_sha1_mutex)
90 /* Signalled when a new work_item is added to todo. */
91 static pthread_cond_t cond_add;
93 /* Signalled when the result from one work_item is written to
94 * stdout.
96 static pthread_cond_t cond_write;
98 /* Signalled when we are finished with everything. */
99 static pthread_cond_t cond_result;
101 static int print_hunk_marks_between_files;
102 static int printed_something;
104 static void add_work(enum work_type type, char *name, void *id)
106 grep_lock();
108 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
109 pthread_cond_wait(&cond_write, &grep_mutex);
112 todo[todo_end].type = type;
113 todo[todo_end].name = name;
114 todo[todo_end].identifier = id;
115 todo[todo_end].done = 0;
116 strbuf_reset(&todo[todo_end].out);
117 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
119 pthread_cond_signal(&cond_add);
120 grep_unlock();
123 static struct work_item *get_work(void)
125 struct work_item *ret;
127 grep_lock();
128 while (todo_start == todo_end && !all_work_added) {
129 pthread_cond_wait(&cond_add, &grep_mutex);
132 if (todo_start == todo_end && all_work_added) {
133 ret = NULL;
134 } else {
135 ret = &todo[todo_start];
136 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
138 grep_unlock();
139 return ret;
142 static void grep_sha1_async(struct grep_opt *opt, char *name,
143 const unsigned char *sha1)
145 unsigned char *s;
146 s = xmalloc(20);
147 memcpy(s, sha1, 20);
148 add_work(WORK_SHA1, name, s);
151 static void grep_file_async(struct grep_opt *opt, char *name,
152 const char *filename)
154 add_work(WORK_FILE, name, xstrdup(filename));
157 static void work_done(struct work_item *w)
159 int old_done;
161 grep_lock();
162 w->done = 1;
163 old_done = todo_done;
164 for(; todo[todo_done].done && todo_done != todo_start;
165 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
166 w = &todo[todo_done];
167 if (w->out.len) {
168 if (print_hunk_marks_between_files && printed_something)
169 write_or_die(1, "--\n", 3);
170 write_or_die(1, w->out.buf, w->out.len);
171 printed_something = 1;
173 free(w->name);
174 free(w->identifier);
177 if (old_done != todo_done)
178 pthread_cond_signal(&cond_write);
180 if (all_work_added && todo_done == todo_end)
181 pthread_cond_signal(&cond_result);
183 grep_unlock();
186 static void *run(void *arg)
188 int hit = 0;
189 struct grep_opt *opt = arg;
191 while (1) {
192 struct work_item *w = get_work();
193 if (!w)
194 break;
196 opt->output_priv = w;
197 if (w->type == WORK_SHA1) {
198 unsigned long sz;
199 void* data = load_sha1(w->identifier, &sz, w->name);
201 if (data) {
202 hit |= grep_buffer(opt, w->name, data, sz);
203 free(data);
205 } else if (w->type == WORK_FILE) {
206 size_t sz;
207 void* data = load_file(w->identifier, &sz);
208 if (data) {
209 hit |= grep_buffer(opt, w->name, data, sz);
210 free(data);
212 } else {
213 assert(0);
216 work_done(w);
218 free_grep_patterns(arg);
219 free(arg);
221 return (void*) (intptr_t) hit;
224 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
226 struct work_item *w = opt->output_priv;
227 strbuf_add(&w->out, buf, size);
230 static void start_threads(struct grep_opt *opt)
232 int i;
234 pthread_mutex_init(&grep_mutex, NULL);
235 pthread_mutex_init(&read_sha1_mutex, NULL);
236 pthread_cond_init(&cond_add, NULL);
237 pthread_cond_init(&cond_write, NULL);
238 pthread_cond_init(&cond_result, NULL);
240 for (i = 0; i < ARRAY_SIZE(todo); i++) {
241 strbuf_init(&todo[i].out, 0);
244 for (i = 0; i < ARRAY_SIZE(threads); i++) {
245 int err;
246 struct grep_opt *o = grep_opt_dup(opt);
247 o->output = strbuf_out;
248 compile_grep_patterns(o);
249 err = pthread_create(&threads[i], NULL, run, o);
251 if (err)
252 die("grep: failed to create thread: %s",
253 strerror(err));
257 static int wait_all(void)
259 int hit = 0;
260 int i;
262 grep_lock();
263 all_work_added = 1;
265 /* Wait until all work is done. */
266 while (todo_done != todo_end)
267 pthread_cond_wait(&cond_result, &grep_mutex);
269 /* Wake up all the consumer threads so they can see that there
270 * is no more work to do.
272 pthread_cond_broadcast(&cond_add);
273 grep_unlock();
275 for (i = 0; i < ARRAY_SIZE(threads); i++) {
276 void *h;
277 pthread_join(threads[i], &h);
278 hit |= (int) (intptr_t) h;
281 pthread_mutex_destroy(&grep_mutex);
282 pthread_mutex_destroy(&read_sha1_mutex);
283 pthread_cond_destroy(&cond_add);
284 pthread_cond_destroy(&cond_write);
285 pthread_cond_destroy(&cond_result);
287 return hit;
289 #else /* !NO_PTHREADS */
290 #define read_sha1_lock()
291 #define read_sha1_unlock()
293 static int wait_all(void)
295 return 0;
297 #endif
299 static int grep_config(const char *var, const char *value, void *cb)
301 struct grep_opt *opt = cb;
302 char *color = NULL;
304 switch (userdiff_config(var, value)) {
305 case 0: break;
306 case -1: return -1;
307 default: return 0;
310 if (!strcmp(var, "color.grep"))
311 opt->color = git_config_colorbool(var, value, -1);
312 else if (!strcmp(var, "color.grep.context"))
313 color = opt->color_context;
314 else if (!strcmp(var, "color.grep.filename"))
315 color = opt->color_filename;
316 else if (!strcmp(var, "color.grep.function"))
317 color = opt->color_function;
318 else if (!strcmp(var, "color.grep.linenumber"))
319 color = opt->color_lineno;
320 else if (!strcmp(var, "color.grep.match"))
321 color = opt->color_match;
322 else if (!strcmp(var, "color.grep.selected"))
323 color = opt->color_selected;
324 else if (!strcmp(var, "color.grep.separator"))
325 color = opt->color_sep;
326 else
327 return git_color_default_config(var, value, cb);
328 if (color) {
329 if (!value)
330 return config_error_nonbool(var);
331 color_parse(value, var, color);
333 return 0;
337 * Return non-zero if max_depth is negative or path has no more then max_depth
338 * slashes.
340 static int accept_subdir(const char *path, int max_depth)
342 if (max_depth < 0)
343 return 1;
345 while ((path = strchr(path, '/')) != NULL) {
346 max_depth--;
347 if (max_depth < 0)
348 return 0;
349 path++;
351 return 1;
355 * Return non-zero if name is a subdirectory of match and is not too deep.
357 static int is_subdir(const char *name, int namelen,
358 const char *match, int matchlen, int max_depth)
360 if (matchlen > namelen || strncmp(name, match, matchlen))
361 return 0;
363 if (name[matchlen] == '\0') /* exact match */
364 return 1;
366 if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
367 return accept_subdir(name + matchlen + 1, max_depth);
369 return 0;
373 * git grep pathspecs are somewhat different from diff-tree pathspecs;
374 * pathname wildcards are allowed.
376 static int pathspec_matches(const char **paths, const char *name, int max_depth)
378 int namelen, i;
379 if (!paths || !*paths)
380 return accept_subdir(name, max_depth);
381 namelen = strlen(name);
382 for (i = 0; paths[i]; i++) {
383 const char *match = paths[i];
384 int matchlen = strlen(match);
385 const char *cp, *meta;
387 if (is_subdir(name, namelen, match, matchlen, max_depth))
388 return 1;
389 if (!fnmatch(match, name, 0))
390 return 1;
391 if (name[namelen-1] != '/')
392 continue;
394 /* We are being asked if the directory ("name") is worth
395 * descending into.
397 * Find the longest leading directory name that does
398 * not have metacharacter in the pathspec; the name
399 * we are looking at must overlap with that directory.
401 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
402 char ch = *cp;
403 if (ch == '*' || ch == '[' || ch == '?') {
404 meta = cp;
405 break;
408 if (!meta)
409 meta = cp; /* fully literal */
411 if (namelen <= meta - match) {
412 /* Looking at "Documentation/" and
413 * the pattern says "Documentation/howto/", or
414 * "Documentation/diff*.txt". The name we
415 * have should match prefix.
417 if (!memcmp(match, name, namelen))
418 return 1;
419 continue;
422 if (meta - match < namelen) {
423 /* Looking at "Documentation/howto/" and
424 * the pattern says "Documentation/h*";
425 * match up to "Do.../h"; this avoids descending
426 * into "Documentation/technical/".
428 if (!memcmp(match, name, meta - match))
429 return 1;
430 continue;
433 return 0;
436 static void *lock_and_read_sha1_file(const unsigned char *sha1, enum object_type *type, unsigned long *size)
438 void *data;
440 if (use_threads) {
441 read_sha1_lock();
442 data = read_sha1_file(sha1, type, size);
443 read_sha1_unlock();
444 } else {
445 data = read_sha1_file(sha1, type, size);
447 return data;
450 static void *load_sha1(const unsigned char *sha1, unsigned long *size,
451 const char *name)
453 enum object_type type;
454 void *data = lock_and_read_sha1_file(sha1, &type, size);
456 if (!data)
457 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
459 return data;
462 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1,
463 const char *filename, int tree_name_len)
465 struct strbuf pathbuf = STRBUF_INIT;
466 char *name;
468 if (opt->relative && opt->prefix_length) {
469 quote_path_relative(filename + tree_name_len, -1, &pathbuf,
470 opt->prefix);
471 strbuf_insert(&pathbuf, 0, filename, tree_name_len);
472 } else {
473 strbuf_addstr(&pathbuf, filename);
476 name = strbuf_detach(&pathbuf, NULL);
478 #ifndef NO_PTHREADS
479 if (use_threads) {
480 grep_sha1_async(opt, name, sha1);
481 return 0;
482 } else
483 #endif
485 int hit;
486 unsigned long sz;
487 void *data = load_sha1(sha1, &sz, name);
488 if (!data)
489 hit = 0;
490 else
491 hit = grep_buffer(opt, name, data, sz);
493 free(data);
494 free(name);
495 return hit;
499 static void *load_file(const char *filename, size_t *sz)
501 struct stat st;
502 char *data;
503 int i;
505 if (lstat(filename, &st) < 0) {
506 err_ret:
507 if (errno != ENOENT)
508 error("'%s': %s", filename, strerror(errno));
509 return 0;
511 if (!S_ISREG(st.st_mode))
512 return 0;
513 *sz = xsize_t(st.st_size);
514 i = open(filename, O_RDONLY);
515 if (i < 0)
516 goto err_ret;
517 data = xmalloc(*sz + 1);
518 if (st.st_size != read_in_full(i, data, *sz)) {
519 error("'%s': short read %s", filename, strerror(errno));
520 close(i);
521 free(data);
522 return 0;
524 close(i);
525 data[*sz] = 0;
526 return data;
529 static int grep_file(struct grep_opt *opt, const char *filename)
531 struct strbuf buf = STRBUF_INIT;
532 char *name;
534 if (opt->relative && opt->prefix_length)
535 quote_path_relative(filename, -1, &buf, opt->prefix);
536 else
537 strbuf_addstr(&buf, filename);
538 name = strbuf_detach(&buf, NULL);
540 #ifndef NO_PTHREADS
541 if (use_threads) {
542 grep_file_async(opt, name, filename);
543 return 0;
544 } else
545 #endif
547 int hit;
548 size_t sz;
549 void *data = load_file(filename, &sz);
550 if (!data)
551 hit = 0;
552 else
553 hit = grep_buffer(opt, name, data, sz);
555 free(data);
556 free(name);
557 return hit;
561 static void append_path(struct grep_opt *opt, const void *data, size_t len)
563 struct string_list *path_list = opt->output_priv;
565 if (len == 1 && *(const char *)data == '\0')
566 return;
567 string_list_append(path_list, xstrndup(data, len));
570 static void run_pager(struct grep_opt *opt, const char *prefix)
572 struct string_list *path_list = opt->output_priv;
573 const char **argv = xmalloc(sizeof(const char *) * (path_list->nr + 1));
574 int i, status;
576 for (i = 0; i < path_list->nr; i++)
577 argv[i] = path_list->items[i].string;
578 argv[path_list->nr] = NULL;
580 if (prefix && chdir(prefix))
581 die("Failed to chdir: %s", prefix);
582 status = run_command_v_opt(argv, RUN_USING_SHELL);
583 if (status)
584 exit(status);
585 free(argv);
588 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
590 int hit = 0;
591 int nr;
592 read_cache();
594 for (nr = 0; nr < active_nr; nr++) {
595 struct cache_entry *ce = active_cache[nr];
596 if (!S_ISREG(ce->ce_mode))
597 continue;
598 if (!pathspec_matches(paths, ce->name, opt->max_depth))
599 continue;
601 * If CE_VALID is on, we assume worktree file and its cache entry
602 * are identical, even if worktree file has been modified, so use
603 * cache version instead
605 if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
606 if (ce_stage(ce))
607 continue;
608 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
610 else
611 hit |= grep_file(opt, ce->name);
612 if (ce_stage(ce)) {
613 do {
614 nr++;
615 } while (nr < active_nr &&
616 !strcmp(ce->name, active_cache[nr]->name));
617 nr--; /* compensate for loop control */
619 if (hit && opt->status_only)
620 break;
622 return hit;
625 static int grep_tree(struct grep_opt *opt, const char **paths,
626 struct tree_desc *tree,
627 const char *tree_name, const char *base)
629 int len;
630 int hit = 0;
631 struct name_entry entry;
632 char *down;
633 int tn_len = strlen(tree_name);
634 struct strbuf pathbuf;
636 strbuf_init(&pathbuf, PATH_MAX + tn_len);
638 if (tn_len) {
639 strbuf_add(&pathbuf, tree_name, tn_len);
640 strbuf_addch(&pathbuf, ':');
641 tn_len = pathbuf.len;
643 strbuf_addstr(&pathbuf, base);
644 len = pathbuf.len;
646 while (tree_entry(tree, &entry)) {
647 int te_len = tree_entry_len(entry.path, entry.sha1);
648 pathbuf.len = len;
649 strbuf_add(&pathbuf, entry.path, te_len);
651 if (S_ISDIR(entry.mode))
652 /* Match "abc/" against pathspec to
653 * decide if we want to descend into "abc"
654 * directory.
656 strbuf_addch(&pathbuf, '/');
658 down = pathbuf.buf + tn_len;
659 if (!pathspec_matches(paths, down, opt->max_depth))
661 else if (S_ISREG(entry.mode))
662 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
663 else if (S_ISDIR(entry.mode)) {
664 enum object_type type;
665 struct tree_desc sub;
666 void *data;
667 unsigned long size;
669 data = lock_and_read_sha1_file(entry.sha1, &type, &size);
670 if (!data)
671 die("unable to read tree (%s)",
672 sha1_to_hex(entry.sha1));
673 init_tree_desc(&sub, data, size);
674 hit |= grep_tree(opt, paths, &sub, tree_name, down);
675 free(data);
677 if (hit && opt->status_only)
678 break;
680 strbuf_release(&pathbuf);
681 return hit;
684 static int grep_object(struct grep_opt *opt, const char **paths,
685 struct object *obj, const char *name)
687 if (obj->type == OBJ_BLOB)
688 return grep_sha1(opt, obj->sha1, name, 0);
689 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
690 struct tree_desc tree;
691 void *data;
692 unsigned long size;
693 int hit;
694 data = read_object_with_reference(obj->sha1, tree_type,
695 &size, NULL);
696 if (!data)
697 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
698 init_tree_desc(&tree, data, size);
699 hit = grep_tree(opt, paths, &tree, name, "");
700 free(data);
701 return hit;
703 die("unable to grep from object of type %s", typename(obj->type));
706 static int grep_objects(struct grep_opt *opt, const char **paths,
707 const struct object_array *list)
709 unsigned int i;
710 int hit = 0;
711 const unsigned int nr = list->nr;
713 for (i = 0; i < nr; i++) {
714 struct object *real_obj;
715 real_obj = deref_tag(list->objects[i].item, NULL, 0);
716 if (grep_object(opt, paths, real_obj, list->objects[i].name)) {
717 hit = 1;
718 if (opt->status_only)
719 break;
722 return hit;
725 static int grep_directory(struct grep_opt *opt, const char **paths)
727 struct dir_struct dir;
728 int i, hit = 0;
730 memset(&dir, 0, sizeof(dir));
731 setup_standard_excludes(&dir);
733 fill_directory(&dir, paths);
734 for (i = 0; i < dir.nr; i++) {
735 hit |= grep_file(opt, dir.entries[i]->name);
736 if (hit && opt->status_only)
737 break;
739 return hit;
742 static int context_callback(const struct option *opt, const char *arg,
743 int unset)
745 struct grep_opt *grep_opt = opt->value;
746 int value;
747 const char *endp;
749 if (unset) {
750 grep_opt->pre_context = grep_opt->post_context = 0;
751 return 0;
753 value = strtol(arg, (char **)&endp, 10);
754 if (*endp) {
755 return error("switch `%c' expects a numerical value",
756 opt->short_name);
758 grep_opt->pre_context = grep_opt->post_context = value;
759 return 0;
762 static int file_callback(const struct option *opt, const char *arg, int unset)
764 struct grep_opt *grep_opt = opt->value;
765 FILE *patterns;
766 int lno = 0;
767 struct strbuf sb = STRBUF_INIT;
769 patterns = fopen(arg, "r");
770 if (!patterns)
771 die_errno("cannot open '%s'", arg);
772 while (strbuf_getline(&sb, patterns, '\n') == 0) {
773 char *s;
774 size_t len;
776 /* ignore empty line like grep does */
777 if (sb.len == 0)
778 continue;
780 s = strbuf_detach(&sb, &len);
781 append_grep_pat(grep_opt, s, len, arg, ++lno, GREP_PATTERN);
783 fclose(patterns);
784 strbuf_release(&sb);
785 return 0;
788 static int not_callback(const struct option *opt, const char *arg, int unset)
790 struct grep_opt *grep_opt = opt->value;
791 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
792 return 0;
795 static int and_callback(const struct option *opt, const char *arg, int unset)
797 struct grep_opt *grep_opt = opt->value;
798 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
799 return 0;
802 static int open_callback(const struct option *opt, const char *arg, int unset)
804 struct grep_opt *grep_opt = opt->value;
805 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
806 return 0;
809 static int close_callback(const struct option *opt, const char *arg, int unset)
811 struct grep_opt *grep_opt = opt->value;
812 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
813 return 0;
816 static int pattern_callback(const struct option *opt, const char *arg,
817 int unset)
819 struct grep_opt *grep_opt = opt->value;
820 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
821 return 0;
824 static int help_callback(const struct option *opt, const char *arg, int unset)
826 return -1;
829 int cmd_grep(int argc, const char **argv, const char *prefix)
831 int hit = 0;
832 int cached = 0;
833 int seen_dashdash = 0;
834 int external_grep_allowed__ignored;
835 const char *show_in_pager = NULL, *default_pager = "dummy";
836 struct grep_opt opt;
837 struct object_array list = OBJECT_ARRAY_INIT;
838 const char **paths = NULL;
839 struct string_list path_list = STRING_LIST_INIT_NODUP;
840 int i;
841 int dummy;
842 int use_index = 1;
843 struct option options[] = {
844 OPT_BOOLEAN(0, "cached", &cached,
845 "search in index instead of in the work tree"),
846 OPT_BOOLEAN(0, "index", &use_index,
847 "--no-index finds in contents not managed by git"),
848 OPT_GROUP(""),
849 OPT_BOOLEAN('v', "invert-match", &opt.invert,
850 "show non-matching lines"),
851 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
852 "case insensitive matching"),
853 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
854 "match patterns only at word boundaries"),
855 OPT_SET_INT('a', "text", &opt.binary,
856 "process binary files as text", GREP_BINARY_TEXT),
857 OPT_SET_INT('I', NULL, &opt.binary,
858 "don't match patterns in binary files",
859 GREP_BINARY_NOMATCH),
860 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
861 "descend at most <depth> levels", PARSE_OPT_NONEG,
862 NULL, 1 },
863 OPT_GROUP(""),
864 OPT_BIT('E', "extended-regexp", &opt.regflags,
865 "use extended POSIX regular expressions", REG_EXTENDED),
866 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
867 "use basic POSIX regular expressions (default)",
868 REG_EXTENDED),
869 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
870 "interpret patterns as fixed strings"),
871 OPT_GROUP(""),
872 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
873 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
874 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
875 OPT_NEGBIT(0, "full-name", &opt.relative,
876 "show filenames relative to top directory", 1),
877 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
878 "show only filenames instead of matching lines"),
879 OPT_BOOLEAN(0, "name-only", &opt.name_only,
880 "synonym for --files-with-matches"),
881 OPT_BOOLEAN('L', "files-without-match",
882 &opt.unmatch_name_only,
883 "show only the names of files without match"),
884 OPT_BOOLEAN('z', "null", &opt.null_following_name,
885 "print NUL after filenames"),
886 OPT_BOOLEAN('c', "count", &opt.count,
887 "show the number of matches instead of matching lines"),
888 OPT__COLOR(&opt.color, "highlight matches"),
889 OPT_GROUP(""),
890 OPT_CALLBACK('C', NULL, &opt, "n",
891 "show <n> context lines before and after matches",
892 context_callback),
893 OPT_INTEGER('B', NULL, &opt.pre_context,
894 "show <n> context lines before matches"),
895 OPT_INTEGER('A', NULL, &opt.post_context,
896 "show <n> context lines after matches"),
897 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
898 context_callback),
899 OPT_BOOLEAN('p', "show-function", &opt.funcname,
900 "show a line with the function name before matches"),
901 OPT_GROUP(""),
902 OPT_CALLBACK('f', NULL, &opt, "file",
903 "read patterns from file", file_callback),
904 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
905 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
906 { OPTION_CALLBACK, 0, "and", &opt, NULL,
907 "combine patterns specified with -e",
908 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
909 OPT_BOOLEAN(0, "or", &dummy, ""),
910 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
911 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
912 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
913 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
914 open_callback },
915 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
916 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
917 close_callback },
918 OPT_BOOLEAN('q', "quiet", &opt.status_only,
919 "indicate hit with exit status without output"),
920 OPT_BOOLEAN(0, "all-match", &opt.all_match,
921 "show only matches from files that match all patterns"),
922 OPT_GROUP(""),
923 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
924 "pager", "show matching files in the pager",
925 PARSE_OPT_OPTARG, NULL, (intptr_t)default_pager },
926 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
927 "allow calling of grep(1) (ignored by this build)"),
928 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
929 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
930 OPT_END()
934 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
935 * to show usage information and exit.
937 if (argc == 2 && !strcmp(argv[1], "-h"))
938 usage_with_options(grep_usage, options);
940 memset(&opt, 0, sizeof(opt));
941 opt.prefix = prefix;
942 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
943 opt.relative = 1;
944 opt.pathname = 1;
945 opt.pattern_tail = &opt.pattern_list;
946 opt.header_tail = &opt.header_list;
947 opt.regflags = REG_NEWLINE;
948 opt.max_depth = -1;
950 strcpy(opt.color_context, "");
951 strcpy(opt.color_filename, "");
952 strcpy(opt.color_function, "");
953 strcpy(opt.color_lineno, "");
954 strcpy(opt.color_match, GIT_COLOR_BOLD_RED);
955 strcpy(opt.color_selected, "");
956 strcpy(opt.color_sep, GIT_COLOR_CYAN);
957 opt.color = -1;
958 git_config(grep_config, &opt);
959 if (opt.color == -1)
960 opt.color = git_use_color_default;
963 * If there is no -- then the paths must exist in the working
964 * tree. If there is no explicit pattern specified with -e or
965 * -f, we take the first unrecognized non option to be the
966 * pattern, but then what follows it must be zero or more
967 * valid refs up to the -- (if exists), and then existing
968 * paths. If there is an explicit pattern, then the first
969 * unrecognized non option is the beginning of the refs list
970 * that continues up to the -- (if exists), and then paths.
972 argc = parse_options(argc, argv, prefix, options, grep_usage,
973 PARSE_OPT_KEEP_DASHDASH |
974 PARSE_OPT_STOP_AT_NON_OPTION |
975 PARSE_OPT_NO_INTERNAL_HELP);
977 if (use_index && !startup_info->have_repository)
978 /* die the same way as if we did it at the beginning */
979 setup_git_directory();
982 * skip a -- separator; we know it cannot be
983 * separating revisions from pathnames if
984 * we haven't even had any patterns yet
986 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
987 argv++;
988 argc--;
991 /* First unrecognized non-option token */
992 if (argc > 0 && !opt.pattern_list) {
993 append_grep_pattern(&opt, argv[0], "command line", 0,
994 GREP_PATTERN);
995 argv++;
996 argc--;
999 if (show_in_pager == default_pager)
1000 show_in_pager = git_pager(1);
1001 if (show_in_pager) {
1002 opt.color = 0;
1003 opt.name_only = 1;
1004 opt.null_following_name = 1;
1005 opt.output_priv = &path_list;
1006 opt.output = append_path;
1007 string_list_append(&path_list, show_in_pager);
1008 use_threads = 0;
1011 if (!opt.pattern_list)
1012 die("no pattern given.");
1013 if (!opt.fixed && opt.ignore_case)
1014 opt.regflags |= REG_ICASE;
1015 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
1016 die("cannot mix --fixed-strings and regexp");
1018 #ifndef NO_PTHREADS
1019 if (online_cpus() == 1 || !grep_threads_ok(&opt))
1020 use_threads = 0;
1022 if (use_threads) {
1023 if (opt.pre_context || opt.post_context)
1024 print_hunk_marks_between_files = 1;
1025 start_threads(&opt);
1027 #else
1028 use_threads = 0;
1029 #endif
1031 compile_grep_patterns(&opt);
1033 /* Check revs and then paths */
1034 for (i = 0; i < argc; i++) {
1035 const char *arg = argv[i];
1036 unsigned char sha1[20];
1037 /* Is it a rev? */
1038 if (!get_sha1(arg, sha1)) {
1039 struct object *object = parse_object(sha1);
1040 if (!object)
1041 die("bad object %s", arg);
1042 add_object_array(object, arg, &list);
1043 continue;
1045 if (!strcmp(arg, "--")) {
1046 i++;
1047 seen_dashdash = 1;
1049 break;
1052 /* The rest are paths */
1053 if (!seen_dashdash) {
1054 int j;
1055 for (j = i; j < argc; j++)
1056 verify_filename(prefix, argv[j]);
1059 if (i < argc)
1060 paths = get_pathspec(prefix, argv + i);
1061 else if (prefix) {
1062 paths = xcalloc(2, sizeof(const char *));
1063 paths[0] = prefix;
1064 paths[1] = NULL;
1067 if (show_in_pager && (cached || list.nr))
1068 die("--open-files-in-pager only works on the worktree");
1070 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1071 const char *pager = path_list.items[0].string;
1072 int len = strlen(pager);
1074 if (len > 4 && is_dir_sep(pager[len - 5]))
1075 pager += len - 4;
1077 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1078 struct strbuf buf = STRBUF_INIT;
1079 strbuf_addf(&buf, "+/%s%s",
1080 strcmp("less", pager) ? "" : "*",
1081 opt.pattern_list->pattern);
1082 string_list_append(&path_list, buf.buf);
1083 strbuf_detach(&buf, NULL);
1087 if (!show_in_pager)
1088 setup_pager();
1091 if (!use_index) {
1092 if (cached)
1093 die("--cached cannot be used with --no-index.");
1094 if (list.nr)
1095 die("--no-index cannot be used with revs.");
1096 hit = grep_directory(&opt, paths);
1097 } else if (!list.nr) {
1098 if (!cached)
1099 setup_work_tree();
1101 hit = grep_cache(&opt, paths, cached);
1102 } else {
1103 if (cached)
1104 die("both --cached and trees are given.");
1105 hit = grep_objects(&opt, paths, &list);
1108 if (use_threads)
1109 hit |= wait_all();
1110 if (hit && show_in_pager)
1111 run_pager(&opt, prefix);
1112 free_grep_patterns(&opt);
1113 return !hit;