Code

grep: enable threading for context line printing
[git.git] / builtin / grep.c
1 /*
2  * Builtin "git grep"
3  *
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
27 };
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.
44  */
45 struct work_item
46 {
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.
53          */
54         void *identifier;
55         char done;
56         struct strbuf out;
57 };
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.
62  *
63  * The work_items in [todo_start, todo_end) are waiting to be picked
64  * up by a consumer thread.
65  *
66  * The ranges are modulo TODO_SIZE.
67  */
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.
93  */
94 static pthread_cond_t cond_write;
96 /* Signalled when we are finished with everything. */
97 static pthread_cond_t cond_result;
99 static int print_hunk_marks_between_files;
100 static int printed_something;
102 static void add_work(enum work_type type, char *name, void *id)
104         grep_lock();
106         while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
107                 pthread_cond_wait(&cond_write, &grep_mutex);
108         }
110         todo[todo_end].type = type;
111         todo[todo_end].name = name;
112         todo[todo_end].identifier = id;
113         todo[todo_end].done = 0;
114         strbuf_reset(&todo[todo_end].out);
115         todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
117         pthread_cond_signal(&cond_add);
118         grep_unlock();
121 static struct work_item *get_work(void)
123         struct work_item *ret;
125         grep_lock();
126         while (todo_start == todo_end && !all_work_added) {
127                 pthread_cond_wait(&cond_add, &grep_mutex);
128         }
130         if (todo_start == todo_end && all_work_added) {
131                 ret = NULL;
132         } else {
133                 ret = &todo[todo_start];
134                 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
135         }
136         grep_unlock();
137         return ret;
140 static void grep_sha1_async(struct grep_opt *opt, char *name,
141                             const unsigned char *sha1)
143         unsigned char *s;
144         s = xmalloc(20);
145         memcpy(s, sha1, 20);
146         add_work(WORK_SHA1, name, s);
149 static void grep_file_async(struct grep_opt *opt, char *name,
150                             const char *filename)
152         add_work(WORK_FILE, name, xstrdup(filename));
155 static void work_done(struct work_item *w)
157         int old_done;
159         grep_lock();
160         w->done = 1;
161         old_done = todo_done;
162         for(; todo[todo_done].done && todo_done != todo_start;
163             todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
164                 w = &todo[todo_done];
165                 if (w->out.len) {
166                         if (print_hunk_marks_between_files && printed_something)
167                                 write_or_die(1, "--\n", 3);
168                         write_or_die(1, w->out.buf, w->out.len);
169                         printed_something = 1;
170                 }
171                 free(w->name);
172                 free(w->identifier);
173         }
175         if (old_done != todo_done)
176                 pthread_cond_signal(&cond_write);
178         if (all_work_added && todo_done == todo_end)
179                 pthread_cond_signal(&cond_result);
181         grep_unlock();
184 static void *run(void *arg)
186         int hit = 0;
187         struct grep_opt *opt = arg;
189         while (1) {
190                 struct work_item *w = get_work();
191                 if (!w)
192                         break;
194                 opt->output_priv = w;
195                 if (w->type == WORK_SHA1) {
196                         unsigned long sz;
197                         void* data = load_sha1(w->identifier, &sz, w->name);
199                         if (data) {
200                                 hit |= grep_buffer(opt, w->name, data, sz);
201                                 free(data);
202                         }
203                 } else if (w->type == WORK_FILE) {
204                         size_t sz;
205                         void* data = load_file(w->identifier, &sz);
206                         if (data) {
207                                 hit |= grep_buffer(opt, w->name, data, sz);
208                                 free(data);
209                         }
210                 } else {
211                         assert(0);
212                 }
214                 work_done(w);
215         }
216         free_grep_patterns(arg);
217         free(arg);
219         return (void*) (intptr_t) hit;
222 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
224         struct work_item *w = opt->output_priv;
225         strbuf_add(&w->out, buf, size);
228 static void start_threads(struct grep_opt *opt)
230         int i;
232         pthread_mutex_init(&grep_mutex, NULL);
233         pthread_mutex_init(&read_sha1_mutex, NULL);
234         pthread_cond_init(&cond_add, NULL);
235         pthread_cond_init(&cond_write, NULL);
236         pthread_cond_init(&cond_result, NULL);
238         for (i = 0; i < ARRAY_SIZE(todo); i++) {
239                 strbuf_init(&todo[i].out, 0);
240         }
242         for (i = 0; i < ARRAY_SIZE(threads); i++) {
243                 int err;
244                 struct grep_opt *o = grep_opt_dup(opt);
245                 o->output = strbuf_out;
246                 compile_grep_patterns(o);
247                 err = pthread_create(&threads[i], NULL, run, o);
249                 if (err)
250                         die("grep: failed to create thread: %s",
251                             strerror(err));
252         }
255 static int wait_all(void)
257         int hit = 0;
258         int i;
260         grep_lock();
261         all_work_added = 1;
263         /* Wait until all work is done. */
264         while (todo_done != todo_end)
265                 pthread_cond_wait(&cond_result, &grep_mutex);
267         /* Wake up all the consumer threads so they can see that there
268          * is no more work to do.
269          */
270         pthread_cond_broadcast(&cond_add);
271         grep_unlock();
273         for (i = 0; i < ARRAY_SIZE(threads); i++) {
274                 void *h;
275                 pthread_join(threads[i], &h);
276                 hit |= (int) (intptr_t) h;
277         }
279         pthread_mutex_destroy(&grep_mutex);
280         pthread_mutex_destroy(&read_sha1_mutex);
281         pthread_cond_destroy(&cond_add);
282         pthread_cond_destroy(&cond_write);
283         pthread_cond_destroy(&cond_result);
285         return hit;
287 #else /* !NO_PTHREADS */
288 #define read_sha1_lock()
289 #define read_sha1_unlock()
291 static int wait_all(void)
293         return 0;
295 #endif
297 static int grep_config(const char *var, const char *value, void *cb)
299         struct grep_opt *opt = cb;
301         switch (userdiff_config(var, value)) {
302         case 0: break;
303         case -1: return -1;
304         default: return 0;
305         }
307         if (!strcmp(var, "color.grep")) {
308                 opt->color = git_config_colorbool(var, value, -1);
309                 return 0;
310         }
311         if (!strcmp(var, "color.grep.match")) {
312                 if (!value)
313                         return config_error_nonbool(var);
314                 color_parse(value, var, opt->color_match);
315                 return 0;
316         }
317         return git_color_default_config(var, value, cb);
320 /*
321  * Return non-zero if max_depth is negative or path has no more then max_depth
322  * slashes.
323  */
324 static int accept_subdir(const char *path, int max_depth)
326         if (max_depth < 0)
327                 return 1;
329         while ((path = strchr(path, '/')) != NULL) {
330                 max_depth--;
331                 if (max_depth < 0)
332                         return 0;
333                 path++;
334         }
335         return 1;
338 /*
339  * Return non-zero if name is a subdirectory of match and is not too deep.
340  */
341 static int is_subdir(const char *name, int namelen,
342                 const char *match, int matchlen, int max_depth)
344         if (matchlen > namelen || strncmp(name, match, matchlen))
345                 return 0;
347         if (name[matchlen] == '\0') /* exact match */
348                 return 1;
350         if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
351                 return accept_subdir(name + matchlen + 1, max_depth);
353         return 0;
356 /*
357  * git grep pathspecs are somewhat different from diff-tree pathspecs;
358  * pathname wildcards are allowed.
359  */
360 static int pathspec_matches(const char **paths, const char *name, int max_depth)
362         int namelen, i;
363         if (!paths || !*paths)
364                 return accept_subdir(name, max_depth);
365         namelen = strlen(name);
366         for (i = 0; paths[i]; i++) {
367                 const char *match = paths[i];
368                 int matchlen = strlen(match);
369                 const char *cp, *meta;
371                 if (is_subdir(name, namelen, match, matchlen, max_depth))
372                         return 1;
373                 if (!fnmatch(match, name, 0))
374                         return 1;
375                 if (name[namelen-1] != '/')
376                         continue;
378                 /* We are being asked if the directory ("name") is worth
379                  * descending into.
380                  *
381                  * Find the longest leading directory name that does
382                  * not have metacharacter in the pathspec; the name
383                  * we are looking at must overlap with that directory.
384                  */
385                 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
386                         char ch = *cp;
387                         if (ch == '*' || ch == '[' || ch == '?') {
388                                 meta = cp;
389                                 break;
390                         }
391                 }
392                 if (!meta)
393                         meta = cp; /* fully literal */
395                 if (namelen <= meta - match) {
396                         /* Looking at "Documentation/" and
397                          * the pattern says "Documentation/howto/", or
398                          * "Documentation/diff*.txt".  The name we
399                          * have should match prefix.
400                          */
401                         if (!memcmp(match, name, namelen))
402                                 return 1;
403                         continue;
404                 }
406                 if (meta - match < namelen) {
407                         /* Looking at "Documentation/howto/" and
408                          * the pattern says "Documentation/h*";
409                          * match up to "Do.../h"; this avoids descending
410                          * into "Documentation/technical/".
411                          */
412                         if (!memcmp(match, name, meta - match))
413                                 return 1;
414                         continue;
415                 }
416         }
417         return 0;
420 static void *lock_and_read_sha1_file(const unsigned char *sha1, enum object_type *type, unsigned long *size)
422         void *data;
424         if (use_threads) {
425                 read_sha1_lock();
426                 data = read_sha1_file(sha1, type, size);
427                 read_sha1_unlock();
428         } else {
429                 data = read_sha1_file(sha1, type, size);
430         }
431         return data;
434 static void *load_sha1(const unsigned char *sha1, unsigned long *size,
435                        const char *name)
437         enum object_type type;
438         void *data = lock_and_read_sha1_file(sha1, &type, size);
440         if (!data)
441                 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
443         return data;
446 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1,
447                      const char *filename, int tree_name_len)
449         struct strbuf pathbuf = STRBUF_INIT;
450         char *name;
452         if (opt->relative && opt->prefix_length) {
453                 quote_path_relative(filename + tree_name_len, -1, &pathbuf,
454                                     opt->prefix);
455                 strbuf_insert(&pathbuf, 0, filename, tree_name_len);
456         } else {
457                 strbuf_addstr(&pathbuf, filename);
458         }
460         name = strbuf_detach(&pathbuf, NULL);
462 #ifndef NO_PTHREADS
463         if (use_threads) {
464                 grep_sha1_async(opt, name, sha1);
465                 return 0;
466         } else
467 #endif
468         {
469                 int hit;
470                 unsigned long sz;
471                 void *data = load_sha1(sha1, &sz, name);
472                 if (!data)
473                         hit = 0;
474                 else
475                         hit = grep_buffer(opt, name, data, sz);
477                 free(data);
478                 free(name);
479                 return hit;
480         }
483 static void *load_file(const char *filename, size_t *sz)
485         struct stat st;
486         char *data;
487         int i;
489         if (lstat(filename, &st) < 0) {
490         err_ret:
491                 if (errno != ENOENT)
492                         error("'%s': %s", filename, strerror(errno));
493                 return 0;
494         }
495         if (!S_ISREG(st.st_mode))
496                 return 0;
497         *sz = xsize_t(st.st_size);
498         i = open(filename, O_RDONLY);
499         if (i < 0)
500                 goto err_ret;
501         data = xmalloc(*sz + 1);
502         if (st.st_size != read_in_full(i, data, *sz)) {
503                 error("'%s': short read %s", filename, strerror(errno));
504                 close(i);
505                 free(data);
506                 return 0;
507         }
508         close(i);
509         data[*sz] = 0;
510         return data;
513 static int grep_file(struct grep_opt *opt, const char *filename)
515         struct strbuf buf = STRBUF_INIT;
516         char *name;
518         if (opt->relative && opt->prefix_length)
519                 quote_path_relative(filename, -1, &buf, opt->prefix);
520         else
521                 strbuf_addstr(&buf, filename);
522         name = strbuf_detach(&buf, NULL);
524 #ifndef NO_PTHREADS
525         if (use_threads) {
526                 grep_file_async(opt, name, filename);
527                 return 0;
528         } else
529 #endif
530         {
531                 int hit;
532                 size_t sz;
533                 void *data = load_file(filename, &sz);
534                 if (!data)
535                         hit = 0;
536                 else
537                         hit = grep_buffer(opt, name, data, sz);
539                 free(data);
540                 free(name);
541                 return hit;
542         }
545 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
547         int hit = 0;
548         int nr;
549         read_cache();
551         for (nr = 0; nr < active_nr; nr++) {
552                 struct cache_entry *ce = active_cache[nr];
553                 if (!S_ISREG(ce->ce_mode))
554                         continue;
555                 if (!pathspec_matches(paths, ce->name, opt->max_depth))
556                         continue;
557                 /*
558                  * If CE_VALID is on, we assume worktree file and its cache entry
559                  * are identical, even if worktree file has been modified, so use
560                  * cache version instead
561                  */
562                 if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
563                         if (ce_stage(ce))
564                                 continue;
565                         hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
566                 }
567                 else
568                         hit |= grep_file(opt, ce->name);
569                 if (ce_stage(ce)) {
570                         do {
571                                 nr++;
572                         } while (nr < active_nr &&
573                                  !strcmp(ce->name, active_cache[nr]->name));
574                         nr--; /* compensate for loop control */
575                 }
576                 if (hit && opt->status_only)
577                         break;
578         }
579         free_grep_patterns(opt);
580         return hit;
583 static int grep_tree(struct grep_opt *opt, const char **paths,
584                      struct tree_desc *tree,
585                      const char *tree_name, const char *base)
587         int len;
588         int hit = 0;
589         struct name_entry entry;
590         char *down;
591         int tn_len = strlen(tree_name);
592         struct strbuf pathbuf;
594         strbuf_init(&pathbuf, PATH_MAX + tn_len);
596         if (tn_len) {
597                 strbuf_add(&pathbuf, tree_name, tn_len);
598                 strbuf_addch(&pathbuf, ':');
599                 tn_len = pathbuf.len;
600         }
601         strbuf_addstr(&pathbuf, base);
602         len = pathbuf.len;
604         while (tree_entry(tree, &entry)) {
605                 int te_len = tree_entry_len(entry.path, entry.sha1);
606                 pathbuf.len = len;
607                 strbuf_add(&pathbuf, entry.path, te_len);
609                 if (S_ISDIR(entry.mode))
610                         /* Match "abc/" against pathspec to
611                          * decide if we want to descend into "abc"
612                          * directory.
613                          */
614                         strbuf_addch(&pathbuf, '/');
616                 down = pathbuf.buf + tn_len;
617                 if (!pathspec_matches(paths, down, opt->max_depth))
618                         ;
619                 else if (S_ISREG(entry.mode))
620                         hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
621                 else if (S_ISDIR(entry.mode)) {
622                         enum object_type type;
623                         struct tree_desc sub;
624                         void *data;
625                         unsigned long size;
627                         data = lock_and_read_sha1_file(entry.sha1, &type, &size);
628                         if (!data)
629                                 die("unable to read tree (%s)",
630                                     sha1_to_hex(entry.sha1));
631                         init_tree_desc(&sub, data, size);
632                         hit |= grep_tree(opt, paths, &sub, tree_name, down);
633                         free(data);
634                 }
635                 if (hit && opt->status_only)
636                         break;
637         }
638         strbuf_release(&pathbuf);
639         return hit;
642 static int grep_object(struct grep_opt *opt, const char **paths,
643                        struct object *obj, const char *name)
645         if (obj->type == OBJ_BLOB)
646                 return grep_sha1(opt, obj->sha1, name, 0);
647         if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
648                 struct tree_desc tree;
649                 void *data;
650                 unsigned long size;
651                 int hit;
652                 data = read_object_with_reference(obj->sha1, tree_type,
653                                                   &size, NULL);
654                 if (!data)
655                         die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
656                 init_tree_desc(&tree, data, size);
657                 hit = grep_tree(opt, paths, &tree, name, "");
658                 free(data);
659                 return hit;
660         }
661         die("unable to grep from object of type %s", typename(obj->type));
664 static int grep_directory(struct grep_opt *opt, const char **paths)
666         struct dir_struct dir;
667         int i, hit = 0;
669         memset(&dir, 0, sizeof(dir));
670         setup_standard_excludes(&dir);
672         fill_directory(&dir, paths);
673         for (i = 0; i < dir.nr; i++) {
674                 hit |= grep_file(opt, dir.entries[i]->name);
675                 if (hit && opt->status_only)
676                         break;
677         }
678         free_grep_patterns(opt);
679         return hit;
682 static int context_callback(const struct option *opt, const char *arg,
683                             int unset)
685         struct grep_opt *grep_opt = opt->value;
686         int value;
687         const char *endp;
689         if (unset) {
690                 grep_opt->pre_context = grep_opt->post_context = 0;
691                 return 0;
692         }
693         value = strtol(arg, (char **)&endp, 10);
694         if (*endp) {
695                 return error("switch `%c' expects a numerical value",
696                              opt->short_name);
697         }
698         grep_opt->pre_context = grep_opt->post_context = value;
699         return 0;
702 static int file_callback(const struct option *opt, const char *arg, int unset)
704         struct grep_opt *grep_opt = opt->value;
705         FILE *patterns;
706         int lno = 0;
707         struct strbuf sb = STRBUF_INIT;
709         patterns = fopen(arg, "r");
710         if (!patterns)
711                 die_errno("cannot open '%s'", arg);
712         while (strbuf_getline(&sb, patterns, '\n') == 0) {
713                 /* ignore empty line like grep does */
714                 if (sb.len == 0)
715                         continue;
716                 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
717                                     ++lno, GREP_PATTERN);
718         }
719         fclose(patterns);
720         strbuf_release(&sb);
721         return 0;
724 static int not_callback(const struct option *opt, const char *arg, int unset)
726         struct grep_opt *grep_opt = opt->value;
727         append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
728         return 0;
731 static int and_callback(const struct option *opt, const char *arg, int unset)
733         struct grep_opt *grep_opt = opt->value;
734         append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
735         return 0;
738 static int open_callback(const struct option *opt, const char *arg, int unset)
740         struct grep_opt *grep_opt = opt->value;
741         append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
742         return 0;
745 static int close_callback(const struct option *opt, const char *arg, int unset)
747         struct grep_opt *grep_opt = opt->value;
748         append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
749         return 0;
752 static int pattern_callback(const struct option *opt, const char *arg,
753                             int unset)
755         struct grep_opt *grep_opt = opt->value;
756         append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
757         return 0;
760 static int help_callback(const struct option *opt, const char *arg, int unset)
762         return -1;
765 int cmd_grep(int argc, const char **argv, const char *prefix)
767         int hit = 0;
768         int cached = 0;
769         int seen_dashdash = 0;
770         int external_grep_allowed__ignored;
771         struct grep_opt opt;
772         struct object_array list = { 0, 0, NULL };
773         const char **paths = NULL;
774         int i;
775         int dummy;
776         int nongit = 0, use_index = 1;
777         struct option options[] = {
778                 OPT_BOOLEAN(0, "cached", &cached,
779                         "search in index instead of in the work tree"),
780                 OPT_BOOLEAN(0, "index", &use_index,
781                         "--no-index finds in contents not managed by git"),
782                 OPT_GROUP(""),
783                 OPT_BOOLEAN('v', "invert-match", &opt.invert,
784                         "show non-matching lines"),
785                 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
786                         "case insensitive matching"),
787                 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
788                         "match patterns only at word boundaries"),
789                 OPT_SET_INT('a', "text", &opt.binary,
790                         "process binary files as text", GREP_BINARY_TEXT),
791                 OPT_SET_INT('I', NULL, &opt.binary,
792                         "don't match patterns in binary files",
793                         GREP_BINARY_NOMATCH),
794                 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
795                         "descend at most <depth> levels", PARSE_OPT_NONEG,
796                         NULL, 1 },
797                 OPT_GROUP(""),
798                 OPT_BIT('E', "extended-regexp", &opt.regflags,
799                         "use extended POSIX regular expressions", REG_EXTENDED),
800                 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
801                         "use basic POSIX regular expressions (default)",
802                         REG_EXTENDED),
803                 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
804                         "interpret patterns as fixed strings"),
805                 OPT_GROUP(""),
806                 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
807                 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
808                 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
809                 OPT_NEGBIT(0, "full-name", &opt.relative,
810                         "show filenames relative to top directory", 1),
811                 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
812                         "show only filenames instead of matching lines"),
813                 OPT_BOOLEAN(0, "name-only", &opt.name_only,
814                         "synonym for --files-with-matches"),
815                 OPT_BOOLEAN('L', "files-without-match",
816                         &opt.unmatch_name_only,
817                         "show only the names of files without match"),
818                 OPT_BOOLEAN('z', "null", &opt.null_following_name,
819                         "print NUL after filenames"),
820                 OPT_BOOLEAN('c', "count", &opt.count,
821                         "show the number of matches instead of matching lines"),
822                 OPT__COLOR(&opt.color, "highlight matches"),
823                 OPT_GROUP(""),
824                 OPT_CALLBACK('C', NULL, &opt, "n",
825                         "show <n> context lines before and after matches",
826                         context_callback),
827                 OPT_INTEGER('B', NULL, &opt.pre_context,
828                         "show <n> context lines before matches"),
829                 OPT_INTEGER('A', NULL, &opt.post_context,
830                         "show <n> context lines after matches"),
831                 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
832                         context_callback),
833                 OPT_BOOLEAN('p', "show-function", &opt.funcname,
834                         "show a line with the function name before matches"),
835                 OPT_GROUP(""),
836                 OPT_CALLBACK('f', NULL, &opt, "file",
837                         "read patterns from file", file_callback),
838                 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
839                         "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
840                 { OPTION_CALLBACK, 0, "and", &opt, NULL,
841                   "combine patterns specified with -e",
842                   PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
843                 OPT_BOOLEAN(0, "or", &dummy, ""),
844                 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
845                   PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
846                 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
847                   PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
848                   open_callback },
849                 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
850                   PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
851                   close_callback },
852                 OPT_BOOLEAN('q', "quiet", &opt.status_only,
853                             "indicate hit with exit status without output"),
854                 OPT_BOOLEAN(0, "all-match", &opt.all_match,
855                         "show only matches from files that match all patterns"),
856                 OPT_GROUP(""),
857                 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
858                             "allow calling of grep(1) (ignored by this build)"),
859                 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
860                   PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
861                 OPT_END()
862         };
864         prefix = setup_git_directory_gently(&nongit);
866         /*
867          * 'git grep -h', unlike 'git grep -h <pattern>', is a request
868          * to show usage information and exit.
869          */
870         if (argc == 2 && !strcmp(argv[1], "-h"))
871                 usage_with_options(grep_usage, options);
873         memset(&opt, 0, sizeof(opt));
874         opt.prefix = prefix;
875         opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
876         opt.relative = 1;
877         opt.pathname = 1;
878         opt.pattern_tail = &opt.pattern_list;
879         opt.header_tail = &opt.header_list;
880         opt.regflags = REG_NEWLINE;
881         opt.max_depth = -1;
883         strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
884         opt.color = -1;
885         git_config(grep_config, &opt);
886         if (opt.color == -1)
887                 opt.color = git_use_color_default;
889         /*
890          * If there is no -- then the paths must exist in the working
891          * tree.  If there is no explicit pattern specified with -e or
892          * -f, we take the first unrecognized non option to be the
893          * pattern, but then what follows it must be zero or more
894          * valid refs up to the -- (if exists), and then existing
895          * paths.  If there is an explicit pattern, then the first
896          * unrecognized non option is the beginning of the refs list
897          * that continues up to the -- (if exists), and then paths.
898          */
899         argc = parse_options(argc, argv, prefix, options, grep_usage,
900                              PARSE_OPT_KEEP_DASHDASH |
901                              PARSE_OPT_STOP_AT_NON_OPTION |
902                              PARSE_OPT_NO_INTERNAL_HELP);
904         if (use_index && nongit)
905                 /* die the same way as if we did it at the beginning */
906                 setup_git_directory();
908         /*
909          * skip a -- separator; we know it cannot be
910          * separating revisions from pathnames if
911          * we haven't even had any patterns yet
912          */
913         if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
914                 argv++;
915                 argc--;
916         }
918         /* First unrecognized non-option token */
919         if (argc > 0 && !opt.pattern_list) {
920                 append_grep_pattern(&opt, argv[0], "command line", 0,
921                                     GREP_PATTERN);
922                 argv++;
923                 argc--;
924         }
926         if (!opt.pattern_list)
927                 die("no pattern given.");
928         if (!opt.fixed && opt.ignore_case)
929                 opt.regflags |= REG_ICASE;
930         if ((opt.regflags != REG_NEWLINE) && opt.fixed)
931                 die("cannot mix --fixed-strings and regexp");
933 #ifndef NO_PTHREADS
934         if (online_cpus() == 1 || !grep_threads_ok(&opt))
935                 use_threads = 0;
937         if (use_threads) {
938                 if (opt.pre_context || opt.post_context)
939                         print_hunk_marks_between_files = 1;
940                 start_threads(&opt);
941         }
942 #else
943         use_threads = 0;
944 #endif
946         compile_grep_patterns(&opt);
948         /* Check revs and then paths */
949         for (i = 0; i < argc; i++) {
950                 const char *arg = argv[i];
951                 unsigned char sha1[20];
952                 /* Is it a rev? */
953                 if (!get_sha1(arg, sha1)) {
954                         struct object *object = parse_object(sha1);
955                         if (!object)
956                                 die("bad object %s", arg);
957                         add_object_array(object, arg, &list);
958                         continue;
959                 }
960                 if (!strcmp(arg, "--")) {
961                         i++;
962                         seen_dashdash = 1;
963                 }
964                 break;
965         }
967         /* The rest are paths */
968         if (!seen_dashdash) {
969                 int j;
970                 for (j = i; j < argc; j++)
971                         verify_filename(prefix, argv[j]);
972         }
974         if (i < argc)
975                 paths = get_pathspec(prefix, argv + i);
976         else if (prefix) {
977                 paths = xcalloc(2, sizeof(const char *));
978                 paths[0] = prefix;
979                 paths[1] = NULL;
980         }
982         if (!use_index) {
983                 int hit;
984                 if (cached)
985                         die("--cached cannot be used with --no-index.");
986                 if (list.nr)
987                         die("--no-index cannot be used with revs.");
988                 hit = grep_directory(&opt, paths);
989                 if (use_threads)
990                         hit |= wait_all();
991                 return !hit;
992         }
994         if (!list.nr) {
995                 int hit;
996                 if (!cached)
997                         setup_work_tree();
999                 hit = grep_cache(&opt, paths, cached);
1000                 if (use_threads)
1001                         hit |= wait_all();
1002                 return !hit;
1003         }
1005         if (cached)
1006                 die("both --cached and trees are given.");
1008         for (i = 0; i < list.nr; i++) {
1009                 struct object *real_obj;
1010                 real_obj = deref_tag(list.objects[i].item, NULL, 0);
1011                 if (grep_object(&opt, paths, real_obj, list.objects[i].name)) {
1012                         hit = 1;
1013                         if (opt.status_only)
1014                                 break;
1015                 }
1016         }
1018         if (use_threads)
1019                 hit |= wait_all();
1020         free_grep_patterns(&opt);
1021         return !hit;