4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
13 #include "parse-options.h"
20 #include "thread-utils.h"
24 static char const * const grep_usage[] = {
25 "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
29 static int use_threads = 1;
33 static pthread_t threads[THREADS];
35 static void *load_sha1(const unsigned char *sha1, unsigned long *size,
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.
50 /* if type == WORK_SHA1, then 'identifier' is a SHA1,
51 * otherwise type == WORK_FILE, and 'identifier' is a NUL
52 * terminated filename.
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.
69 static struct work_item todo[TODO_SIZE];
70 static int todo_start;
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
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)
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);
118 static struct work_item *get_work(void)
120 struct work_item *ret;
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) {
130 ret = &todo[todo_start];
131 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
137 static void grep_sha1_async(struct grep_opt *opt, char *name,
138 const unsigned char *sha1)
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)
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);
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);
176 static void *run(void *arg)
179 struct grep_opt *opt = arg;
182 struct work_item *w = get_work();
186 opt->output_priv = w;
187 if (w->type == WORK_SHA1) {
189 void* data = load_sha1(w->identifier, &sz, w->name);
192 hit |= grep_buffer(opt, w->name, data, sz);
195 } else if (w->type == WORK_FILE) {
197 void* data = load_file(w->identifier, &sz);
199 hit |= grep_buffer(opt, w->name, data, sz);
209 return (void*) (intptr_t) hit;
212 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
214 struct work_item *w = opt->output_priv;
215 strbuf_add(&w->out, buf, size);
218 static void start_threads(struct grep_opt *opt)
222 pthread_mutex_init(&grep_mutex, NULL);
223 pthread_mutex_init(&read_sha1_mutex, NULL);
224 pthread_cond_init(&cond_add, NULL);
225 pthread_cond_init(&cond_write, NULL);
226 pthread_cond_init(&cond_result, NULL);
228 for (i = 0; i < ARRAY_SIZE(todo); i++) {
229 strbuf_init(&todo[i].out, 0);
232 for (i = 0; i < ARRAY_SIZE(threads); i++) {
234 struct grep_opt *o = grep_opt_dup(opt);
235 o->output = strbuf_out;
236 compile_grep_patterns(o);
237 err = pthread_create(&threads[i], NULL, run, o);
240 die("grep: failed to create thread: %s",
245 static int wait_all(void)
253 /* Wait until all work is done. */
254 while (todo_done != todo_end)
255 pthread_cond_wait(&cond_result, &grep_mutex);
257 /* Wake up all the consumer threads so they can see that there
258 * is no more work to do.
260 pthread_cond_broadcast(&cond_add);
263 for (i = 0; i < ARRAY_SIZE(threads); i++) {
265 pthread_join(threads[i], &h);
266 hit |= (int) (intptr_t) h;
269 pthread_mutex_destroy(&grep_mutex);
270 pthread_mutex_destroy(&read_sha1_mutex);
271 pthread_cond_destroy(&cond_add);
272 pthread_cond_destroy(&cond_write);
273 pthread_cond_destroy(&cond_result);
277 #else /* !NO_PTHREADS */
278 #define read_sha1_lock()
279 #define read_sha1_unlock()
281 static int wait_all(void)
287 static int grep_config(const char *var, const char *value, void *cb)
289 struct grep_opt *opt = cb;
291 switch (userdiff_config(var, value)) {
297 if (!strcmp(var, "color.grep")) {
298 opt->color = git_config_colorbool(var, value, -1);
301 if (!strcmp(var, "color.grep.match")) {
303 return config_error_nonbool(var);
304 color_parse(value, var, opt->color_match);
307 return git_color_default_config(var, value, cb);
311 * Return non-zero if max_depth is negative or path has no more then max_depth
314 static int accept_subdir(const char *path, int max_depth)
319 while ((path = strchr(path, '/')) != NULL) {
329 * Return non-zero if name is a subdirectory of match and is not too deep.
331 static int is_subdir(const char *name, int namelen,
332 const char *match, int matchlen, int max_depth)
334 if (matchlen > namelen || strncmp(name, match, matchlen))
337 if (name[matchlen] == '\0') /* exact match */
340 if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
341 return accept_subdir(name + matchlen + 1, max_depth);
347 * git grep pathspecs are somewhat different from diff-tree pathspecs;
348 * pathname wildcards are allowed.
350 static int pathspec_matches(const char **paths, const char *name, int max_depth)
353 if (!paths || !*paths)
354 return accept_subdir(name, max_depth);
355 namelen = strlen(name);
356 for (i = 0; paths[i]; i++) {
357 const char *match = paths[i];
358 int matchlen = strlen(match);
359 const char *cp, *meta;
361 if (is_subdir(name, namelen, match, matchlen, max_depth))
363 if (!fnmatch(match, name, 0))
365 if (name[namelen-1] != '/')
368 /* We are being asked if the directory ("name") is worth
371 * Find the longest leading directory name that does
372 * not have metacharacter in the pathspec; the name
373 * we are looking at must overlap with that directory.
375 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
377 if (ch == '*' || ch == '[' || ch == '?') {
383 meta = cp; /* fully literal */
385 if (namelen <= meta - match) {
386 /* Looking at "Documentation/" and
387 * the pattern says "Documentation/howto/", or
388 * "Documentation/diff*.txt". The name we
389 * have should match prefix.
391 if (!memcmp(match, name, namelen))
396 if (meta - match < namelen) {
397 /* Looking at "Documentation/howto/" and
398 * the pattern says "Documentation/h*";
399 * match up to "Do.../h"; this avoids descending
400 * into "Documentation/technical/".
402 if (!memcmp(match, name, meta - match))
410 static void *load_sha1(const unsigned char *sha1, unsigned long *size,
413 enum object_type type;
417 data = read_sha1_file(sha1, &type, size);
421 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
426 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1,
427 const char *filename, int tree_name_len)
429 struct strbuf pathbuf = STRBUF_INIT;
432 if (opt->relative && opt->prefix_length) {
433 quote_path_relative(filename + tree_name_len, -1, &pathbuf,
435 strbuf_insert(&pathbuf, 0, filename, tree_name_len);
437 strbuf_addstr(&pathbuf, filename);
440 name = strbuf_detach(&pathbuf, NULL);
444 grep_sha1_async(opt, name, sha1);
451 void *data = load_sha1(sha1, &sz, name);
455 hit = grep_buffer(opt, name, data, sz);
463 static void *load_file(const char *filename, size_t *sz)
469 if (lstat(filename, &st) < 0) {
472 error("'%s': %s", filename, strerror(errno));
475 if (!S_ISREG(st.st_mode))
477 *sz = xsize_t(st.st_size);
478 i = open(filename, O_RDONLY);
481 data = xmalloc(*sz + 1);
482 if (st.st_size != read_in_full(i, data, *sz)) {
483 error("'%s': short read %s", filename, strerror(errno));
493 static int grep_file(struct grep_opt *opt, const char *filename)
495 struct strbuf buf = STRBUF_INIT;
498 if (opt->relative && opt->prefix_length)
499 quote_path_relative(filename, -1, &buf, opt->prefix);
501 strbuf_addstr(&buf, filename);
502 name = strbuf_detach(&buf, NULL);
506 grep_file_async(opt, name, filename);
513 void *data = load_file(filename, &sz);
517 hit = grep_buffer(opt, name, data, sz);
525 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
531 for (nr = 0; nr < active_nr; nr++) {
532 struct cache_entry *ce = active_cache[nr];
533 if (!S_ISREG(ce->ce_mode))
535 if (!pathspec_matches(paths, ce->name, opt->max_depth))
538 * If CE_VALID is on, we assume worktree file and its cache entry
539 * are identical, even if worktree file has been modified, so use
540 * cache version instead
542 if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
545 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
548 hit |= grep_file(opt, ce->name);
552 } while (nr < active_nr &&
553 !strcmp(ce->name, active_cache[nr]->name));
554 nr--; /* compensate for loop control */
556 if (hit && opt->status_only)
559 free_grep_patterns(opt);
563 static int grep_tree(struct grep_opt *opt, const char **paths,
564 struct tree_desc *tree,
565 const char *tree_name, const char *base)
569 struct name_entry entry;
571 int tn_len = strlen(tree_name);
572 struct strbuf pathbuf;
574 strbuf_init(&pathbuf, PATH_MAX + tn_len);
577 strbuf_add(&pathbuf, tree_name, tn_len);
578 strbuf_addch(&pathbuf, ':');
579 tn_len = pathbuf.len;
581 strbuf_addstr(&pathbuf, base);
584 while (tree_entry(tree, &entry)) {
585 int te_len = tree_entry_len(entry.path, entry.sha1);
587 strbuf_add(&pathbuf, entry.path, te_len);
589 if (S_ISDIR(entry.mode))
590 /* Match "abc/" against pathspec to
591 * decide if we want to descend into "abc"
594 strbuf_addch(&pathbuf, '/');
596 down = pathbuf.buf + tn_len;
597 if (!pathspec_matches(paths, down, opt->max_depth))
599 else if (S_ISREG(entry.mode))
600 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
601 else if (S_ISDIR(entry.mode)) {
602 enum object_type type;
603 struct tree_desc sub;
608 data = read_sha1_file(entry.sha1, &type, &size);
612 die("unable to read tree (%s)",
613 sha1_to_hex(entry.sha1));
614 init_tree_desc(&sub, data, size);
615 hit |= grep_tree(opt, paths, &sub, tree_name, down);
618 if (hit && opt->status_only)
621 strbuf_release(&pathbuf);
625 static int grep_object(struct grep_opt *opt, const char **paths,
626 struct object *obj, const char *name)
628 if (obj->type == OBJ_BLOB)
629 return grep_sha1(opt, obj->sha1, name, 0);
630 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
631 struct tree_desc tree;
635 data = read_object_with_reference(obj->sha1, tree_type,
638 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
639 init_tree_desc(&tree, data, size);
640 hit = grep_tree(opt, paths, &tree, name, "");
644 die("unable to grep from object of type %s", typename(obj->type));
647 static int grep_directory(struct grep_opt *opt, const char **paths)
649 struct dir_struct dir;
652 memset(&dir, 0, sizeof(dir));
653 setup_standard_excludes(&dir);
655 fill_directory(&dir, paths);
656 for (i = 0; i < dir.nr; i++) {
657 hit |= grep_file(opt, dir.entries[i]->name);
658 if (hit && opt->status_only)
661 free_grep_patterns(opt);
665 static int context_callback(const struct option *opt, const char *arg,
668 struct grep_opt *grep_opt = opt->value;
673 grep_opt->pre_context = grep_opt->post_context = 0;
676 value = strtol(arg, (char **)&endp, 10);
678 return error("switch `%c' expects a numerical value",
681 grep_opt->pre_context = grep_opt->post_context = value;
685 static int file_callback(const struct option *opt, const char *arg, int unset)
687 struct grep_opt *grep_opt = opt->value;
690 struct strbuf sb = STRBUF_INIT;
692 patterns = fopen(arg, "r");
694 die_errno("cannot open '%s'", arg);
695 while (strbuf_getline(&sb, patterns, '\n') == 0) {
696 /* ignore empty line like grep does */
699 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
700 ++lno, GREP_PATTERN);
707 static int not_callback(const struct option *opt, const char *arg, int unset)
709 struct grep_opt *grep_opt = opt->value;
710 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
714 static int and_callback(const struct option *opt, const char *arg, int unset)
716 struct grep_opt *grep_opt = opt->value;
717 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
721 static int open_callback(const struct option *opt, const char *arg, int unset)
723 struct grep_opt *grep_opt = opt->value;
724 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
728 static int close_callback(const struct option *opt, const char *arg, int unset)
730 struct grep_opt *grep_opt = opt->value;
731 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
735 static int pattern_callback(const struct option *opt, const char *arg,
738 struct grep_opt *grep_opt = opt->value;
739 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
743 static int help_callback(const struct option *opt, const char *arg, int unset)
748 int cmd_grep(int argc, const char **argv, const char *prefix)
752 int seen_dashdash = 0;
753 int external_grep_allowed__ignored;
755 struct object_array list = { 0, 0, NULL };
756 const char **paths = NULL;
759 int nongit = 0, use_index = 1;
760 struct option options[] = {
761 OPT_BOOLEAN(0, "cached", &cached,
762 "search in index instead of in the work tree"),
763 OPT_BOOLEAN(0, "index", &use_index,
764 "--no-index finds in contents not managed by git"),
766 OPT_BOOLEAN('v', "invert-match", &opt.invert,
767 "show non-matching lines"),
768 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
769 "case insensitive matching"),
770 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
771 "match patterns only at word boundaries"),
772 OPT_SET_INT('a', "text", &opt.binary,
773 "process binary files as text", GREP_BINARY_TEXT),
774 OPT_SET_INT('I', NULL, &opt.binary,
775 "don't match patterns in binary files",
776 GREP_BINARY_NOMATCH),
777 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
778 "descend at most <depth> levels", PARSE_OPT_NONEG,
781 OPT_BIT('E', "extended-regexp", &opt.regflags,
782 "use extended POSIX regular expressions", REG_EXTENDED),
783 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
784 "use basic POSIX regular expressions (default)",
786 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
787 "interpret patterns as fixed strings"),
789 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
790 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
791 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
792 OPT_NEGBIT(0, "full-name", &opt.relative,
793 "show filenames relative to top directory", 1),
794 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
795 "show only filenames instead of matching lines"),
796 OPT_BOOLEAN(0, "name-only", &opt.name_only,
797 "synonym for --files-with-matches"),
798 OPT_BOOLEAN('L', "files-without-match",
799 &opt.unmatch_name_only,
800 "show only the names of files without match"),
801 OPT_BOOLEAN('z', "null", &opt.null_following_name,
802 "print NUL after filenames"),
803 OPT_BOOLEAN('c', "count", &opt.count,
804 "show the number of matches instead of matching lines"),
805 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
807 OPT_CALLBACK('C', NULL, &opt, "n",
808 "show <n> context lines before and after matches",
810 OPT_INTEGER('B', NULL, &opt.pre_context,
811 "show <n> context lines before matches"),
812 OPT_INTEGER('A', NULL, &opt.post_context,
813 "show <n> context lines after matches"),
814 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
816 OPT_BOOLEAN('p', "show-function", &opt.funcname,
817 "show a line with the function name before matches"),
819 OPT_CALLBACK('f', NULL, &opt, "file",
820 "read patterns from file", file_callback),
821 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
822 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
823 { OPTION_CALLBACK, 0, "and", &opt, NULL,
824 "combine patterns specified with -e",
825 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
826 OPT_BOOLEAN(0, "or", &dummy, ""),
827 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
828 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
829 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
830 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
832 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
833 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
835 OPT_BOOLEAN('q', "quiet", &opt.status_only,
836 "indicate hit with exit status without output"),
837 OPT_BOOLEAN(0, "all-match", &opt.all_match,
838 "show only matches from files that match all patterns"),
840 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
841 "allow calling of grep(1) (ignored by this build)"),
842 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
843 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
847 prefix = setup_git_directory_gently(&nongit);
850 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
851 * to show usage information and exit.
853 if (argc == 2 && !strcmp(argv[1], "-h"))
854 usage_with_options(grep_usage, options);
856 memset(&opt, 0, sizeof(opt));
858 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
861 opt.pattern_tail = &opt.pattern_list;
862 opt.regflags = REG_NEWLINE;
865 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
867 git_config(grep_config, &opt);
869 opt.color = git_use_color_default;
872 * If there is no -- then the paths must exist in the working
873 * tree. If there is no explicit pattern specified with -e or
874 * -f, we take the first unrecognized non option to be the
875 * pattern, but then what follows it must be zero or more
876 * valid refs up to the -- (if exists), and then existing
877 * paths. If there is an explicit pattern, then the first
878 * unrecognized non option is the beginning of the refs list
879 * that continues up to the -- (if exists), and then paths.
881 argc = parse_options(argc, argv, prefix, options, grep_usage,
882 PARSE_OPT_KEEP_DASHDASH |
883 PARSE_OPT_STOP_AT_NON_OPTION |
884 PARSE_OPT_NO_INTERNAL_HELP);
886 if (use_index && nongit)
887 /* die the same way as if we did it at the beginning */
888 setup_git_directory();
890 /* First unrecognized non-option token */
891 if (argc > 0 && !opt.pattern_list) {
892 append_grep_pattern(&opt, argv[0], "command line", 0,
898 if (!opt.pattern_list)
899 die("no pattern given.");
900 if (!opt.fixed && opt.ignore_case)
901 opt.regflags |= REG_ICASE;
902 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
903 die("cannot mix --fixed-strings and regexp");
906 if (online_cpus() == 1 || !grep_threads_ok(&opt))
915 compile_grep_patterns(&opt);
917 /* Check revs and then paths */
918 for (i = 0; i < argc; i++) {
919 const char *arg = argv[i];
920 unsigned char sha1[20];
922 if (!get_sha1(arg, sha1)) {
923 struct object *object = parse_object(sha1);
925 die("bad object %s", arg);
926 add_object_array(object, arg, &list);
929 if (!strcmp(arg, "--")) {
936 /* The rest are paths */
937 if (!seen_dashdash) {
939 for (j = i; j < argc; j++)
940 verify_filename(prefix, argv[j]);
944 paths = get_pathspec(prefix, argv + i);
946 paths = xcalloc(2, sizeof(const char *));
954 die("--cached cannot be used with --no-index.");
956 die("--no-index cannot be used with revs.");
957 hit = grep_directory(&opt, paths);
968 hit = grep_cache(&opt, paths, cached);
975 die("both --cached and trees are given.");
977 for (i = 0; i < list.nr; i++) {
978 struct object *real_obj;
979 real_obj = deref_tag(list.objects[i].item, NULL, 0);
980 if (grep_object(&opt, paths, real_obj, list.objects[i].name)) {
989 free_grep_patterns(&opt);