grep: stop looking at random places for .gitattributes
[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 "string-list.h"
15 #include "run-command.h"
16 #include "userdiff.h"
17 #include "grep.h"
18 #include "quote.h"
19 #include "dir.h"
20
21 static char const * const grep_usage[] = {
22         "git grep [options] [-e] <pattern> [<rev>...] [[--] <path>...]",
23         NULL
24 };
25
26 static int use_threads = 1;
27
28 #ifndef NO_PTHREADS
29 #define THREADS 8
30 static pthread_t threads[THREADS];
31
32 /* We use one producer thread and THREADS consumer
33  * threads. The producer adds struct work_items to 'todo' and the
34  * consumers pick work items from the same array.
35  */
36 struct work_item {
37         struct grep_source source;
38         char done;
39         struct strbuf out;
40 };
41
42 /* In the range [todo_done, todo_start) in 'todo' we have work_items
43  * that have been or are processed by a consumer thread. We haven't
44  * written the result for these to stdout yet.
45  *
46  * The work_items in [todo_start, todo_end) are waiting to be picked
47  * up by a consumer thread.
48  *
49  * The ranges are modulo TODO_SIZE.
50  */
51 #define TODO_SIZE 128
52 static struct work_item todo[TODO_SIZE];
53 static int todo_start;
54 static int todo_end;
55 static int todo_done;
56
57 /* Has all work items been added? */
58 static int all_work_added;
59
60 /* This lock protects all the variables above. */
61 static pthread_mutex_t grep_mutex;
62
63 static inline void grep_lock(void)
64 {
65         if (use_threads)
66                 pthread_mutex_lock(&grep_mutex);
67 }
68
69 static inline void grep_unlock(void)
70 {
71         if (use_threads)
72                 pthread_mutex_unlock(&grep_mutex);
73 }
74
75 /* Signalled when a new work_item is added to todo. */
76 static pthread_cond_t cond_add;
77
78 /* Signalled when the result from one work_item is written to
79  * stdout.
80  */
81 static pthread_cond_t cond_write;
82
83 /* Signalled when we are finished with everything. */
84 static pthread_cond_t cond_result;
85
86 static int skip_first_line;
87
88 static void add_work(struct grep_opt *opt, enum grep_source_type type,
89                      const char *name, const char *path, const void *id)
90 {
91         grep_lock();
92
93         while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
94                 pthread_cond_wait(&cond_write, &grep_mutex);
95         }
96
97         grep_source_init(&todo[todo_end].source, type, name, path, id);
98         if (opt->binary != GREP_BINARY_TEXT)
99                 grep_source_load_driver(&todo[todo_end].source);
100         todo[todo_end].done = 0;
101         strbuf_reset(&todo[todo_end].out);
102         todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
103
104         pthread_cond_signal(&cond_add);
105         grep_unlock();
106 }
107
108 static struct work_item *get_work(void)
109 {
110         struct work_item *ret;
111
112         grep_lock();
113         while (todo_start == todo_end && !all_work_added) {
114                 pthread_cond_wait(&cond_add, &grep_mutex);
115         }
116
117         if (todo_start == todo_end && all_work_added) {
118                 ret = NULL;
119         } else {
120                 ret = &todo[todo_start];
121                 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
122         }
123         grep_unlock();
124         return ret;
125 }
126
127 static void work_done(struct work_item *w)
128 {
129         int old_done;
130
131         grep_lock();
132         w->done = 1;
133         old_done = todo_done;
134         for(; todo[todo_done].done && todo_done != todo_start;
135             todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
136                 w = &todo[todo_done];
137                 if (w->out.len) {
138                         const char *p = w->out.buf;
139                         size_t len = w->out.len;
140
141                         /* Skip the leading hunk mark of the first file. */
142                         if (skip_first_line) {
143                                 while (len) {
144                                         len--;
145                                         if (*p++ == '\n')
146                                                 break;
147                                 }
148                                 skip_first_line = 0;
149                         }
150
151                         write_or_die(1, p, len);
152                 }
153                 grep_source_clear(&w->source);
154         }
155
156         if (old_done != todo_done)
157                 pthread_cond_signal(&cond_write);
158
159         if (all_work_added && todo_done == todo_end)
160                 pthread_cond_signal(&cond_result);
161
162         grep_unlock();
163 }
164
165 static void *run(void *arg)
166 {
167         int hit = 0;
168         struct grep_opt *opt = arg;
169
170         while (1) {
171                 struct work_item *w = get_work();
172                 if (!w)
173                         break;
174
175                 opt->output_priv = w;
176                 hit |= grep_source(opt, &w->source);
177                 grep_source_clear_data(&w->source);
178                 work_done(w);
179         }
180         free_grep_patterns(arg);
181         free(arg);
182
183         return (void*) (intptr_t) hit;
184 }
185
186 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
187 {
188         struct work_item *w = opt->output_priv;
189         strbuf_add(&w->out, buf, size);
190 }
191
192 static void start_threads(struct grep_opt *opt)
193 {
194         int i;
195
196         pthread_mutex_init(&grep_mutex, NULL);
197         pthread_mutex_init(&grep_read_mutex, NULL);
198         pthread_mutex_init(&grep_attr_mutex, NULL);
199         pthread_cond_init(&cond_add, NULL);
200         pthread_cond_init(&cond_write, NULL);
201         pthread_cond_init(&cond_result, NULL);
202         grep_use_locks = 1;
203
204         for (i = 0; i < ARRAY_SIZE(todo); i++) {
205                 strbuf_init(&todo[i].out, 0);
206         }
207
208         for (i = 0; i < ARRAY_SIZE(threads); i++) {
209                 int err;
210                 struct grep_opt *o = grep_opt_dup(opt);
211                 o->output = strbuf_out;
212                 o->debug = 0;
213                 compile_grep_patterns(o);
214                 err = pthread_create(&threads[i], NULL, run, o);
215
216                 if (err)
217                         die(_("grep: failed to create thread: %s"),
218                             strerror(err));
219         }
220 }
221
222 static int wait_all(void)
223 {
224         int hit = 0;
225         int i;
226
227         grep_lock();
228         all_work_added = 1;
229
230         /* Wait until all work is done. */
231         while (todo_done != todo_end)
232                 pthread_cond_wait(&cond_result, &grep_mutex);
233
234         /* Wake up all the consumer threads so they can see that there
235          * is no more work to do.
236          */
237         pthread_cond_broadcast(&cond_add);
238         grep_unlock();
239
240         for (i = 0; i < ARRAY_SIZE(threads); i++) {
241                 void *h;
242                 pthread_join(threads[i], &h);
243                 hit |= (int) (intptr_t) h;
244         }
245
246         pthread_mutex_destroy(&grep_mutex);
247         pthread_mutex_destroy(&grep_read_mutex);
248         pthread_mutex_destroy(&grep_attr_mutex);
249         pthread_cond_destroy(&cond_add);
250         pthread_cond_destroy(&cond_write);
251         pthread_cond_destroy(&cond_result);
252         grep_use_locks = 0;
253
254         return hit;
255 }
256 #else /* !NO_PTHREADS */
257
258 static int wait_all(void)
259 {
260         return 0;
261 }
262 #endif
263
264 static int grep_config(const char *var, const char *value, void *cb)
265 {
266         struct grep_opt *opt = cb;
267         char *color = NULL;
268
269         if (userdiff_config(var, value) < 0)
270                 return -1;
271
272         if (!strcmp(var, "grep.extendedregexp")) {
273                 if (git_config_bool(var, value))
274                         opt->regflags |= REG_EXTENDED;
275                 else
276                         opt->regflags &= ~REG_EXTENDED;
277                 return 0;
278         }
279
280         if (!strcmp(var, "grep.linenumber")) {
281                 opt->linenum = git_config_bool(var, value);
282                 return 0;
283         }
284
285         if (!strcmp(var, "color.grep"))
286                 opt->color = git_config_colorbool(var, value);
287         else if (!strcmp(var, "color.grep.context"))
288                 color = opt->color_context;
289         else if (!strcmp(var, "color.grep.filename"))
290                 color = opt->color_filename;
291         else if (!strcmp(var, "color.grep.function"))
292                 color = opt->color_function;
293         else if (!strcmp(var, "color.grep.linenumber"))
294                 color = opt->color_lineno;
295         else if (!strcmp(var, "color.grep.match"))
296                 color = opt->color_match;
297         else if (!strcmp(var, "color.grep.selected"))
298                 color = opt->color_selected;
299         else if (!strcmp(var, "color.grep.separator"))
300                 color = opt->color_sep;
301         else
302                 return git_color_default_config(var, value, cb);
303         if (color) {
304                 if (!value)
305                         return config_error_nonbool(var);
306                 color_parse(value, var, color);
307         }
308         return 0;
309 }
310
311 static void *lock_and_read_sha1_file(const unsigned char *sha1, enum object_type *type, unsigned long *size)
312 {
313         void *data;
314
315         grep_read_lock();
316         data = read_sha1_file(sha1, type, size);
317         grep_read_unlock();
318         return data;
319 }
320
321 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1,
322                      const char *filename, int tree_name_len,
323                      const char *path)
324 {
325         struct strbuf pathbuf = STRBUF_INIT;
326
327         if (opt->relative && opt->prefix_length) {
328                 quote_path_relative(filename + tree_name_len, -1, &pathbuf,
329                                     opt->prefix);
330                 strbuf_insert(&pathbuf, 0, filename, tree_name_len);
331         } else {
332                 strbuf_addstr(&pathbuf, filename);
333         }
334
335 #ifndef NO_PTHREADS
336         if (use_threads) {
337                 add_work(opt, GREP_SOURCE_SHA1, pathbuf.buf, path, sha1);
338                 strbuf_release(&pathbuf);
339                 return 0;
340         } else
341 #endif
342         {
343                 struct grep_source gs;
344                 int hit;
345
346                 grep_source_init(&gs, GREP_SOURCE_SHA1, pathbuf.buf, path, sha1);
347                 strbuf_release(&pathbuf);
348                 hit = grep_source(opt, &gs);
349
350                 grep_source_clear(&gs);
351                 return hit;
352         }
353 }
354
355 static int grep_file(struct grep_opt *opt, const char *filename)
356 {
357         struct strbuf buf = STRBUF_INIT;
358
359         if (opt->relative && opt->prefix_length)
360                 quote_path_relative(filename, -1, &buf, opt->prefix);
361         else
362                 strbuf_addstr(&buf, filename);
363
364 #ifndef NO_PTHREADS
365         if (use_threads) {
366                 add_work(opt, GREP_SOURCE_FILE, buf.buf, filename, filename);
367                 strbuf_release(&buf);
368                 return 0;
369         } else
370 #endif
371         {
372                 struct grep_source gs;
373                 int hit;
374
375                 grep_source_init(&gs, GREP_SOURCE_FILE, buf.buf, filename, filename);
376                 strbuf_release(&buf);
377                 hit = grep_source(opt, &gs);
378
379                 grep_source_clear(&gs);
380                 return hit;
381         }
382 }
383
384 static void append_path(struct grep_opt *opt, const void *data, size_t len)
385 {
386         struct string_list *path_list = opt->output_priv;
387
388         if (len == 1 && *(const char *)data == '\0')
389                 return;
390         string_list_append(path_list, xstrndup(data, len));
391 }
392
393 static void run_pager(struct grep_opt *opt, const char *prefix)
394 {
395         struct string_list *path_list = opt->output_priv;
396         const char **argv = xmalloc(sizeof(const char *) * (path_list->nr + 1));
397         int i, status;
398
399         for (i = 0; i < path_list->nr; i++)
400                 argv[i] = path_list->items[i].string;
401         argv[path_list->nr] = NULL;
402
403         if (prefix && chdir(prefix))
404                 die(_("Failed to chdir: %s"), prefix);
405         status = run_command_v_opt(argv, RUN_USING_SHELL);
406         if (status)
407                 exit(status);
408         free(argv);
409 }
410
411 static int grep_cache(struct grep_opt *opt, const struct pathspec *pathspec, int cached)
412 {
413         int hit = 0;
414         int nr;
415         read_cache();
416
417         for (nr = 0; nr < active_nr; nr++) {
418                 struct cache_entry *ce = active_cache[nr];
419                 if (!S_ISREG(ce->ce_mode))
420                         continue;
421                 if (!match_pathspec_depth(pathspec, ce->name, ce_namelen(ce), 0, NULL))
422                         continue;
423                 /*
424                  * If CE_VALID is on, we assume worktree file and its cache entry
425                  * are identical, even if worktree file has been modified, so use
426                  * cache version instead
427                  */
428                 if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
429                         if (ce_stage(ce))
430                                 continue;
431                         hit |= grep_sha1(opt, ce->sha1, ce->name, 0, ce->name);
432                 }
433                 else
434                         hit |= grep_file(opt, ce->name);
435                 if (ce_stage(ce)) {
436                         do {
437                                 nr++;
438                         } while (nr < active_nr &&
439                                  !strcmp(ce->name, active_cache[nr]->name));
440                         nr--; /* compensate for loop control */
441                 }
442                 if (hit && opt->status_only)
443                         break;
444         }
445         return hit;
446 }
447
448 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
449                      struct tree_desc *tree, struct strbuf *base, int tn_len,
450                      int check_attr)
451 {
452         int hit = 0;
453         enum interesting match = entry_not_interesting;
454         struct name_entry entry;
455         int old_baselen = base->len;
456
457         while (tree_entry(tree, &entry)) {
458                 int te_len = tree_entry_len(&entry);
459
460                 if (match != all_entries_interesting) {
461                         match = tree_entry_interesting(&entry, base, tn_len, pathspec);
462                         if (match == all_entries_not_interesting)
463                                 break;
464                         if (match == entry_not_interesting)
465                                 continue;
466                 }
467
468                 strbuf_add(base, entry.path, te_len);
469
470                 if (S_ISREG(entry.mode)) {
471                         hit |= grep_sha1(opt, entry.sha1, base->buf, tn_len,
472                                          check_attr ? base->buf + tn_len : NULL);
473                 }
474                 else if (S_ISDIR(entry.mode)) {
475                         enum object_type type;
476                         struct tree_desc sub;
477                         void *data;
478                         unsigned long size;
479
480                         data = lock_and_read_sha1_file(entry.sha1, &type, &size);
481                         if (!data)
482                                 die(_("unable to read tree (%s)"),
483                                     sha1_to_hex(entry.sha1));
484
485                         strbuf_addch(base, '/');
486                         init_tree_desc(&sub, data, size);
487                         hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
488                                          check_attr);
489                         free(data);
490                 }
491                 strbuf_setlen(base, old_baselen);
492
493                 if (hit && opt->status_only)
494                         break;
495         }
496         return hit;
497 }
498
499 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
500                        struct object *obj, const char *name)
501 {
502         if (obj->type == OBJ_BLOB)
503                 return grep_sha1(opt, obj->sha1, name, 0, NULL);
504         if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
505                 struct tree_desc tree;
506                 void *data;
507                 unsigned long size;
508                 struct strbuf base;
509                 int hit, len;
510
511                 grep_read_lock();
512                 data = read_object_with_reference(obj->sha1, tree_type,
513                                                   &size, NULL);
514                 grep_read_unlock();
515
516                 if (!data)
517                         die(_("unable to read tree (%s)"), sha1_to_hex(obj->sha1));
518
519                 len = name ? strlen(name) : 0;
520                 strbuf_init(&base, PATH_MAX + len + 1);
521                 if (len) {
522                         strbuf_add(&base, name, len);
523                         strbuf_addch(&base, ':');
524                 }
525                 init_tree_desc(&tree, data, size);
526                 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
527                                 obj->type == OBJ_COMMIT);
528                 strbuf_release(&base);
529                 free(data);
530                 return hit;
531         }
532         die(_("unable to grep from object of type %s"), typename(obj->type));
533 }
534
535 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
536                         const struct object_array *list)
537 {
538         unsigned int i;
539         int hit = 0;
540         const unsigned int nr = list->nr;
541
542         for (i = 0; i < nr; i++) {
543                 struct object *real_obj;
544                 real_obj = deref_tag(list->objects[i].item, NULL, 0);
545                 if (grep_object(opt, pathspec, real_obj, list->objects[i].name)) {
546                         hit = 1;
547                         if (opt->status_only)
548                                 break;
549                 }
550         }
551         return hit;
552 }
553
554 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
555                           int exc_std)
556 {
557         struct dir_struct dir;
558         int i, hit = 0;
559
560         memset(&dir, 0, sizeof(dir));
561         if (exc_std)
562                 setup_standard_excludes(&dir);
563
564         fill_directory(&dir, pathspec->raw);
565         for (i = 0; i < dir.nr; i++) {
566                 const char *name = dir.entries[i]->name;
567                 int namelen = strlen(name);
568                 if (!match_pathspec_depth(pathspec, name, namelen, 0, NULL))
569                         continue;
570                 hit |= grep_file(opt, dir.entries[i]->name);
571                 if (hit && opt->status_only)
572                         break;
573         }
574         return hit;
575 }
576
577 static int context_callback(const struct option *opt, const char *arg,
578                             int unset)
579 {
580         struct grep_opt *grep_opt = opt->value;
581         int value;
582         const char *endp;
583
584         if (unset) {
585                 grep_opt->pre_context = grep_opt->post_context = 0;
586                 return 0;
587         }
588         value = strtol(arg, (char **)&endp, 10);
589         if (*endp) {
590                 return error(_("switch `%c' expects a numerical value"),
591                              opt->short_name);
592         }
593         grep_opt->pre_context = grep_opt->post_context = value;
594         return 0;
595 }
596
597 static int file_callback(const struct option *opt, const char *arg, int unset)
598 {
599         struct grep_opt *grep_opt = opt->value;
600         int from_stdin = !strcmp(arg, "-");
601         FILE *patterns;
602         int lno = 0;
603         struct strbuf sb = STRBUF_INIT;
604
605         patterns = from_stdin ? stdin : fopen(arg, "r");
606         if (!patterns)
607                 die_errno(_("cannot open '%s'"), arg);
608         while (strbuf_getline(&sb, patterns, '\n') == 0) {
609                 /* ignore empty line like grep does */
610                 if (sb.len == 0)
611                         continue;
612
613                 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
614                                 GREP_PATTERN);
615         }
616         if (!from_stdin)
617                 fclose(patterns);
618         strbuf_release(&sb);
619         return 0;
620 }
621
622 static int not_callback(const struct option *opt, const char *arg, int unset)
623 {
624         struct grep_opt *grep_opt = opt->value;
625         append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
626         return 0;
627 }
628
629 static int and_callback(const struct option *opt, const char *arg, int unset)
630 {
631         struct grep_opt *grep_opt = opt->value;
632         append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
633         return 0;
634 }
635
636 static int open_callback(const struct option *opt, const char *arg, int unset)
637 {
638         struct grep_opt *grep_opt = opt->value;
639         append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
640         return 0;
641 }
642
643 static int close_callback(const struct option *opt, const char *arg, int unset)
644 {
645         struct grep_opt *grep_opt = opt->value;
646         append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
647         return 0;
648 }
649
650 static int pattern_callback(const struct option *opt, const char *arg,
651                             int unset)
652 {
653         struct grep_opt *grep_opt = opt->value;
654         append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
655         return 0;
656 }
657
658 static int help_callback(const struct option *opt, const char *arg, int unset)
659 {
660         return -1;
661 }
662
663 int cmd_grep(int argc, const char **argv, const char *prefix)
664 {
665         int hit = 0;
666         int cached = 0, untracked = 0, opt_exclude = -1;
667         int seen_dashdash = 0;
668         int external_grep_allowed__ignored;
669         const char *show_in_pager = NULL, *default_pager = "dummy";
670         struct grep_opt opt;
671         struct object_array list = OBJECT_ARRAY_INIT;
672         const char **paths = NULL;
673         struct pathspec pathspec;
674         struct string_list path_list = STRING_LIST_INIT_NODUP;
675         int i;
676         int dummy;
677         int use_index = 1;
678         enum {
679                 pattern_type_unspecified = 0,
680                 pattern_type_bre,
681                 pattern_type_ere,
682                 pattern_type_fixed,
683                 pattern_type_pcre,
684         };
685         int pattern_type = pattern_type_unspecified;
686
687         struct option options[] = {
688                 OPT_BOOLEAN(0, "cached", &cached,
689                         "search in index instead of in the work tree"),
690                 OPT_NEGBIT(0, "no-index", &use_index,
691                          "finds in contents not managed by git", 1),
692                 OPT_BOOLEAN(0, "untracked", &untracked,
693                         "search in both tracked and untracked files"),
694                 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
695                             "search also in ignored files", 1),
696                 OPT_GROUP(""),
697                 OPT_BOOLEAN('v', "invert-match", &opt.invert,
698                         "show non-matching lines"),
699                 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
700                         "case insensitive matching"),
701                 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
702                         "match patterns only at word boundaries"),
703                 OPT_SET_INT('a', "text", &opt.binary,
704                         "process binary files as text", GREP_BINARY_TEXT),
705                 OPT_SET_INT('I', NULL, &opt.binary,
706                         "don't match patterns in binary files",
707                         GREP_BINARY_NOMATCH),
708                 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
709                         "descend at most <depth> levels", PARSE_OPT_NONEG,
710                         NULL, 1 },
711                 OPT_GROUP(""),
712                 OPT_SET_INT('E', "extended-regexp", &pattern_type,
713                             "use extended POSIX regular expressions",
714                             pattern_type_ere),
715                 OPT_SET_INT('G', "basic-regexp", &pattern_type,
716                             "use basic POSIX regular expressions (default)",
717                             pattern_type_bre),
718                 OPT_SET_INT('F', "fixed-strings", &pattern_type,
719                             "interpret patterns as fixed strings",
720                             pattern_type_fixed),
721                 OPT_SET_INT('P', "perl-regexp", &pattern_type,
722                             "use Perl-compatible regular expressions",
723                             pattern_type_pcre),
724                 OPT_GROUP(""),
725                 OPT_BOOLEAN('n', "line-number", &opt.linenum, "show line numbers"),
726                 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
727                 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
728                 OPT_NEGBIT(0, "full-name", &opt.relative,
729                         "show filenames relative to top directory", 1),
730                 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
731                         "show only filenames instead of matching lines"),
732                 OPT_BOOLEAN(0, "name-only", &opt.name_only,
733                         "synonym for --files-with-matches"),
734                 OPT_BOOLEAN('L', "files-without-match",
735                         &opt.unmatch_name_only,
736                         "show only the names of files without match"),
737                 OPT_BOOLEAN('z', "null", &opt.null_following_name,
738                         "print NUL after filenames"),
739                 OPT_BOOLEAN('c', "count", &opt.count,
740                         "show the number of matches instead of matching lines"),
741                 OPT__COLOR(&opt.color, "highlight matches"),
742                 OPT_BOOLEAN(0, "break", &opt.file_break,
743                         "print empty line between matches from different files"),
744                 OPT_BOOLEAN(0, "heading", &opt.heading,
745                         "show filename only once above matches from same file"),
746                 OPT_GROUP(""),
747                 OPT_CALLBACK('C', "context", &opt, "n",
748                         "show <n> context lines before and after matches",
749                         context_callback),
750                 OPT_INTEGER('B', "before-context", &opt.pre_context,
751                         "show <n> context lines before matches"),
752                 OPT_INTEGER('A', "after-context", &opt.post_context,
753                         "show <n> context lines after matches"),
754                 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
755                         context_callback),
756                 OPT_BOOLEAN('p', "show-function", &opt.funcname,
757                         "show a line with the function name before matches"),
758                 OPT_BOOLEAN('W', "function-context", &opt.funcbody,
759                         "show the surrounding function"),
760                 OPT_GROUP(""),
761                 OPT_CALLBACK('f', NULL, &opt, "file",
762                         "read patterns from file", file_callback),
763                 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
764                         "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
765                 { OPTION_CALLBACK, 0, "and", &opt, NULL,
766                   "combine patterns specified with -e",
767                   PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
768                 OPT_BOOLEAN(0, "or", &dummy, ""),
769                 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
770                   PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
771                 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
772                   PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
773                   open_callback },
774                 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
775                   PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
776                   close_callback },
777                 OPT__QUIET(&opt.status_only,
778                            "indicate hit with exit status without output"),
779                 OPT_BOOLEAN(0, "all-match", &opt.all_match,
780                         "show only matches from files that match all patterns"),
781                 { OPTION_SET_INT, 0, "debug", &opt.debug, NULL,
782                   "show parse tree for grep expression",
783                   PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 1 },
784                 OPT_GROUP(""),
785                 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
786                         "pager", "show matching files in the pager",
787                         PARSE_OPT_OPTARG, NULL, (intptr_t)default_pager },
788                 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
789                             "allow calling of grep(1) (ignored by this build)"),
790                 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
791                   PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
792                 OPT_END()
793         };
794
795         /*
796          * 'git grep -h', unlike 'git grep -h <pattern>', is a request
797          * to show usage information and exit.
798          */
799         if (argc == 2 && !strcmp(argv[1], "-h"))
800                 usage_with_options(grep_usage, options);
801
802         memset(&opt, 0, sizeof(opt));
803         opt.prefix = prefix;
804         opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
805         opt.relative = 1;
806         opt.pathname = 1;
807         opt.pattern_tail = &opt.pattern_list;
808         opt.header_tail = &opt.header_list;
809         opt.regflags = REG_NEWLINE;
810         opt.max_depth = -1;
811
812         strcpy(opt.color_context, "");
813         strcpy(opt.color_filename, "");
814         strcpy(opt.color_function, "");
815         strcpy(opt.color_lineno, "");
816         strcpy(opt.color_match, GIT_COLOR_BOLD_RED);
817         strcpy(opt.color_selected, "");
818         strcpy(opt.color_sep, GIT_COLOR_CYAN);
819         opt.color = -1;
820         git_config(grep_config, &opt);
821
822         /*
823          * If there is no -- then the paths must exist in the working
824          * tree.  If there is no explicit pattern specified with -e or
825          * -f, we take the first unrecognized non option to be the
826          * pattern, but then what follows it must be zero or more
827          * valid refs up to the -- (if exists), and then existing
828          * paths.  If there is an explicit pattern, then the first
829          * unrecognized non option is the beginning of the refs list
830          * that continues up to the -- (if exists), and then paths.
831          */
832         argc = parse_options(argc, argv, prefix, options, grep_usage,
833                              PARSE_OPT_KEEP_DASHDASH |
834                              PARSE_OPT_STOP_AT_NON_OPTION |
835                              PARSE_OPT_NO_INTERNAL_HELP);
836         switch (pattern_type) {
837         case pattern_type_fixed:
838                 opt.fixed = 1;
839                 opt.pcre = 0;
840                 break;
841         case pattern_type_bre:
842                 opt.fixed = 0;
843                 opt.pcre = 0;
844                 opt.regflags &= ~REG_EXTENDED;
845                 break;
846         case pattern_type_ere:
847                 opt.fixed = 0;
848                 opt.pcre = 0;
849                 opt.regflags |= REG_EXTENDED;
850                 break;
851         case pattern_type_pcre:
852                 opt.fixed = 0;
853                 opt.pcre = 1;
854                 break;
855         default:
856                 break; /* nothing */
857         }
858
859         if (use_index && !startup_info->have_repository)
860                 /* die the same way as if we did it at the beginning */
861                 setup_git_directory();
862
863         /*
864          * skip a -- separator; we know it cannot be
865          * separating revisions from pathnames if
866          * we haven't even had any patterns yet
867          */
868         if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
869                 argv++;
870                 argc--;
871         }
872
873         /* First unrecognized non-option token */
874         if (argc > 0 && !opt.pattern_list) {
875                 append_grep_pattern(&opt, argv[0], "command line", 0,
876                                     GREP_PATTERN);
877                 argv++;
878                 argc--;
879         }
880
881         if (show_in_pager == default_pager)
882                 show_in_pager = git_pager(1);
883         if (show_in_pager) {
884                 opt.color = 0;
885                 opt.name_only = 1;
886                 opt.null_following_name = 1;
887                 opt.output_priv = &path_list;
888                 opt.output = append_path;
889                 string_list_append(&path_list, show_in_pager);
890                 use_threads = 0;
891         }
892
893         if (!opt.pattern_list)
894                 die(_("no pattern given."));
895         if (!opt.fixed && opt.ignore_case)
896                 opt.regflags |= REG_ICASE;
897
898         compile_grep_patterns(&opt);
899
900         /* Check revs and then paths */
901         for (i = 0; i < argc; i++) {
902                 const char *arg = argv[i];
903                 unsigned char sha1[20];
904                 /* Is it a rev? */
905                 if (!get_sha1(arg, sha1)) {
906                         struct object *object = parse_object(sha1);
907                         if (!object)
908                                 die(_("bad object %s"), arg);
909                         add_object_array(object, arg, &list);
910                         continue;
911                 }
912                 if (!strcmp(arg, "--")) {
913                         i++;
914                         seen_dashdash = 1;
915                 }
916                 break;
917         }
918
919 #ifndef NO_PTHREADS
920         if (list.nr || cached || online_cpus() == 1)
921                 use_threads = 0;
922 #else
923         use_threads = 0;
924 #endif
925
926 #ifndef NO_PTHREADS
927         if (use_threads) {
928                 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
929                     && (opt.pre_context || opt.post_context ||
930                         opt.file_break || opt.funcbody))
931                         skip_first_line = 1;
932                 start_threads(&opt);
933         }
934 #endif
935
936         /* The rest are paths */
937         if (!seen_dashdash) {
938                 int j;
939                 for (j = i; j < argc; j++)
940                         verify_filename(prefix, argv[j], j == i);
941         }
942
943         paths = get_pathspec(prefix, argv + i);
944         init_pathspec(&pathspec, paths);
945         pathspec.max_depth = opt.max_depth;
946         pathspec.recursive = 1;
947
948         if (show_in_pager && (cached || list.nr))
949                 die(_("--open-files-in-pager only works on the worktree"));
950
951         if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
952                 const char *pager = path_list.items[0].string;
953                 int len = strlen(pager);
954
955                 if (len > 4 && is_dir_sep(pager[len - 5]))
956                         pager += len - 4;
957
958                 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
959                         struct strbuf buf = STRBUF_INIT;
960                         strbuf_addf(&buf, "+/%s%s",
961                                         strcmp("less", pager) ? "" : "*",
962                                         opt.pattern_list->pattern);
963                         string_list_append(&path_list, buf.buf);
964                         strbuf_detach(&buf, NULL);
965                 }
966         }
967
968         if (!show_in_pager)
969                 setup_pager();
970
971         if (!use_index && (untracked || cached))
972                 die(_("--cached or --untracked cannot be used with --no-index."));
973
974         if (!use_index || untracked) {
975                 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
976                 if (list.nr)
977                         die(_("--no-index or --untracked cannot be used with revs."));
978                 hit = grep_directory(&opt, &pathspec, use_exclude);
979         } else if (0 <= opt_exclude) {
980                 die(_("--[no-]exclude-standard cannot be used for tracked contents."));
981         } else if (!list.nr) {
982                 if (!cached)
983                         setup_work_tree();
984
985                 hit = grep_cache(&opt, &pathspec, cached);
986         } else {
987                 if (cached)
988                         die(_("both --cached and trees are given."));
989                 hit = grep_objects(&opt, &pathspec, &list);
990         }
991
992         if (use_threads)
993                 hit |= wait_all();
994         if (hit && show_in_pager)
995                 run_pager(&opt, prefix);
996         free_grep_patterns(&opt);
997         return !hit;
998 }