Merge branch 'sg/doc-pretty-formats'
[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 #include "pathspec.h"
21 #include "submodule.h"
22 #include "submodule-config.h"
23
24 static char const * const grep_usage[] = {
25         N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
26         NULL
27 };
28
29 static const char *super_prefix;
30 static int recurse_submodules;
31 static struct argv_array submodule_options = ARGV_ARRAY_INIT;
32 static const char *parent_basename;
33
34 static int grep_submodule_launch(struct grep_opt *opt,
35                                  const struct grep_source *gs);
36
37 #define GREP_NUM_THREADS_DEFAULT 8
38 static int num_threads;
39
40 #ifndef NO_PTHREADS
41 static pthread_t *threads;
42
43 /* We use one producer thread and THREADS consumer
44  * threads. The producer adds struct work_items to 'todo' and the
45  * consumers pick work items from the same array.
46  */
47 struct work_item {
48         struct grep_source source;
49         char done;
50         struct strbuf out;
51 };
52
53 /* In the range [todo_done, todo_start) in 'todo' we have work_items
54  * that have been or are processed by a consumer thread. We haven't
55  * written the result for these to stdout yet.
56  *
57  * The work_items in [todo_start, todo_end) are waiting to be picked
58  * up by a consumer thread.
59  *
60  * The ranges are modulo TODO_SIZE.
61  */
62 #define TODO_SIZE 128
63 static struct work_item todo[TODO_SIZE];
64 static int todo_start;
65 static int todo_end;
66 static int todo_done;
67
68 /* Has all work items been added? */
69 static int all_work_added;
70
71 /* This lock protects all the variables above. */
72 static pthread_mutex_t grep_mutex;
73
74 static inline void grep_lock(void)
75 {
76         assert(num_threads);
77         pthread_mutex_lock(&grep_mutex);
78 }
79
80 static inline void grep_unlock(void)
81 {
82         assert(num_threads);
83         pthread_mutex_unlock(&grep_mutex);
84 }
85
86 /* Signalled when a new work_item is added to todo. */
87 static pthread_cond_t cond_add;
88
89 /* Signalled when the result from one work_item is written to
90  * stdout.
91  */
92 static pthread_cond_t cond_write;
93
94 /* Signalled when we are finished with everything. */
95 static pthread_cond_t cond_result;
96
97 static int skip_first_line;
98
99 static void add_work(struct grep_opt *opt, enum grep_source_type type,
100                      const char *name, const char *path, const void *id)
101 {
102         grep_lock();
103
104         while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
105                 pthread_cond_wait(&cond_write, &grep_mutex);
106         }
107
108         grep_source_init(&todo[todo_end].source, type, name, path, id);
109         if (opt->binary != GREP_BINARY_TEXT)
110                 grep_source_load_driver(&todo[todo_end].source);
111         todo[todo_end].done = 0;
112         strbuf_reset(&todo[todo_end].out);
113         todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
114
115         pthread_cond_signal(&cond_add);
116         grep_unlock();
117 }
118
119 static struct work_item *get_work(void)
120 {
121         struct work_item *ret;
122
123         grep_lock();
124         while (todo_start == todo_end && !all_work_added) {
125                 pthread_cond_wait(&cond_add, &grep_mutex);
126         }
127
128         if (todo_start == todo_end && all_work_added) {
129                 ret = NULL;
130         } else {
131                 ret = &todo[todo_start];
132                 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
133         }
134         grep_unlock();
135         return ret;
136 }
137
138 static void work_done(struct work_item *w)
139 {
140         int old_done;
141
142         grep_lock();
143         w->done = 1;
144         old_done = todo_done;
145         for(; todo[todo_done].done && todo_done != todo_start;
146             todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
147                 w = &todo[todo_done];
148                 if (w->out.len) {
149                         const char *p = w->out.buf;
150                         size_t len = w->out.len;
151
152                         /* Skip the leading hunk mark of the first file. */
153                         if (skip_first_line) {
154                                 while (len) {
155                                         len--;
156                                         if (*p++ == '\n')
157                                                 break;
158                                 }
159                                 skip_first_line = 0;
160                         }
161
162                         write_or_die(1, p, len);
163                 }
164                 grep_source_clear(&w->source);
165         }
166
167         if (old_done != todo_done)
168                 pthread_cond_signal(&cond_write);
169
170         if (all_work_added && todo_done == todo_end)
171                 pthread_cond_signal(&cond_result);
172
173         grep_unlock();
174 }
175
176 static void *run(void *arg)
177 {
178         int hit = 0;
179         struct grep_opt *opt = arg;
180
181         while (1) {
182                 struct work_item *w = get_work();
183                 if (!w)
184                         break;
185
186                 opt->output_priv = w;
187                 if (w->source.type == GREP_SOURCE_SUBMODULE)
188                         hit |= grep_submodule_launch(opt, &w->source);
189                 else
190                         hit |= grep_source(opt, &w->source);
191                 grep_source_clear_data(&w->source);
192                 work_done(w);
193         }
194         free_grep_patterns(arg);
195         free(arg);
196
197         return (void*) (intptr_t) hit;
198 }
199
200 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
201 {
202         struct work_item *w = opt->output_priv;
203         strbuf_add(&w->out, buf, size);
204 }
205
206 static void start_threads(struct grep_opt *opt)
207 {
208         int i;
209
210         pthread_mutex_init(&grep_mutex, NULL);
211         pthread_mutex_init(&grep_read_mutex, NULL);
212         pthread_mutex_init(&grep_attr_mutex, NULL);
213         pthread_cond_init(&cond_add, NULL);
214         pthread_cond_init(&cond_write, NULL);
215         pthread_cond_init(&cond_result, NULL);
216         grep_use_locks = 1;
217
218         for (i = 0; i < ARRAY_SIZE(todo); i++) {
219                 strbuf_init(&todo[i].out, 0);
220         }
221
222         threads = xcalloc(num_threads, sizeof(*threads));
223         for (i = 0; i < num_threads; i++) {
224                 int err;
225                 struct grep_opt *o = grep_opt_dup(opt);
226                 o->output = strbuf_out;
227                 if (i)
228                         o->debug = 0;
229                 compile_grep_patterns(o);
230                 err = pthread_create(&threads[i], NULL, run, o);
231
232                 if (err)
233                         die(_("grep: failed to create thread: %s"),
234                             strerror(err));
235         }
236 }
237
238 static int wait_all(void)
239 {
240         int hit = 0;
241         int i;
242
243         grep_lock();
244         all_work_added = 1;
245
246         /* Wait until all work is done. */
247         while (todo_done != todo_end)
248                 pthread_cond_wait(&cond_result, &grep_mutex);
249
250         /* Wake up all the consumer threads so they can see that there
251          * is no more work to do.
252          */
253         pthread_cond_broadcast(&cond_add);
254         grep_unlock();
255
256         for (i = 0; i < num_threads; i++) {
257                 void *h;
258                 pthread_join(threads[i], &h);
259                 hit |= (int) (intptr_t) h;
260         }
261
262         free(threads);
263
264         pthread_mutex_destroy(&grep_mutex);
265         pthread_mutex_destroy(&grep_read_mutex);
266         pthread_mutex_destroy(&grep_attr_mutex);
267         pthread_cond_destroy(&cond_add);
268         pthread_cond_destroy(&cond_write);
269         pthread_cond_destroy(&cond_result);
270         grep_use_locks = 0;
271
272         return hit;
273 }
274 #else /* !NO_PTHREADS */
275
276 static int wait_all(void)
277 {
278         return 0;
279 }
280 #endif
281
282 static int grep_cmd_config(const char *var, const char *value, void *cb)
283 {
284         int st = grep_config(var, value, cb);
285         if (git_color_default_config(var, value, cb) < 0)
286                 st = -1;
287
288         if (!strcmp(var, "grep.threads")) {
289                 num_threads = git_config_int(var, value);
290                 if (num_threads < 0)
291                         die(_("invalid number of threads specified (%d) for %s"),
292                             num_threads, var);
293 #ifdef NO_PTHREADS
294                 else if (num_threads && num_threads != 1) {
295                         /*
296                          * TRANSLATORS: %s is the configuration
297                          * variable for tweaking threads, currently
298                          * grep.threads
299                          */
300                         warning(_("no threads support, ignoring %s"), var);
301                         num_threads = 0;
302                 }
303 #endif
304         }
305
306         if (!strcmp(var, "submodule.recurse"))
307                 recurse_submodules = git_config_bool(var, value);
308
309         return st;
310 }
311
312 static void *lock_and_read_oid_file(const struct object_id *oid, enum object_type *type, unsigned long *size)
313 {
314         void *data;
315
316         grep_read_lock();
317         data = read_sha1_file(oid->hash, type, size);
318         grep_read_unlock();
319         return data;
320 }
321
322 static int grep_oid(struct grep_opt *opt, const struct object_id *oid,
323                      const char *filename, int tree_name_len,
324                      const char *path)
325 {
326         struct strbuf pathbuf = STRBUF_INIT;
327
328         if (super_prefix) {
329                 strbuf_add(&pathbuf, filename, tree_name_len);
330                 strbuf_addstr(&pathbuf, super_prefix);
331                 strbuf_addstr(&pathbuf, filename + tree_name_len);
332         } else {
333                 strbuf_addstr(&pathbuf, filename);
334         }
335
336         if (opt->relative && opt->prefix_length) {
337                 char *name = strbuf_detach(&pathbuf, NULL);
338                 quote_path_relative(name + tree_name_len, opt->prefix, &pathbuf);
339                 strbuf_insert(&pathbuf, 0, name, tree_name_len);
340                 free(name);
341         }
342
343 #ifndef NO_PTHREADS
344         if (num_threads) {
345                 add_work(opt, GREP_SOURCE_OID, pathbuf.buf, path, oid);
346                 strbuf_release(&pathbuf);
347                 return 0;
348         } else
349 #endif
350         {
351                 struct grep_source gs;
352                 int hit;
353
354                 grep_source_init(&gs, GREP_SOURCE_OID, pathbuf.buf, path, oid);
355                 strbuf_release(&pathbuf);
356                 hit = grep_source(opt, &gs);
357
358                 grep_source_clear(&gs);
359                 return hit;
360         }
361 }
362
363 static int grep_file(struct grep_opt *opt, const char *filename)
364 {
365         struct strbuf buf = STRBUF_INIT;
366
367         if (super_prefix)
368                 strbuf_addstr(&buf, super_prefix);
369         strbuf_addstr(&buf, filename);
370
371         if (opt->relative && opt->prefix_length) {
372                 char *name = strbuf_detach(&buf, NULL);
373                 quote_path_relative(name, opt->prefix, &buf);
374                 free(name);
375         }
376
377 #ifndef NO_PTHREADS
378         if (num_threads) {
379                 add_work(opt, GREP_SOURCE_FILE, buf.buf, filename, filename);
380                 strbuf_release(&buf);
381                 return 0;
382         } else
383 #endif
384         {
385                 struct grep_source gs;
386                 int hit;
387
388                 grep_source_init(&gs, GREP_SOURCE_FILE, buf.buf, filename, filename);
389                 strbuf_release(&buf);
390                 hit = grep_source(opt, &gs);
391
392                 grep_source_clear(&gs);
393                 return hit;
394         }
395 }
396
397 static void append_path(struct grep_opt *opt, const void *data, size_t len)
398 {
399         struct string_list *path_list = opt->output_priv;
400
401         if (len == 1 && *(const char *)data == '\0')
402                 return;
403         string_list_append(path_list, xstrndup(data, len));
404 }
405
406 static void run_pager(struct grep_opt *opt, const char *prefix)
407 {
408         struct string_list *path_list = opt->output_priv;
409         struct child_process child = CHILD_PROCESS_INIT;
410         int i, status;
411
412         for (i = 0; i < path_list->nr; i++)
413                 argv_array_push(&child.args, path_list->items[i].string);
414         child.dir = prefix;
415         child.use_shell = 1;
416
417         status = run_command(&child);
418         if (status)
419                 exit(status);
420 }
421
422 static void compile_submodule_options(const struct grep_opt *opt,
423                                       const char **argv,
424                                       int cached, int untracked,
425                                       int opt_exclude, int use_index,
426                                       int pattern_type_arg)
427 {
428         struct grep_pat *pattern;
429
430         if (recurse_submodules)
431                 argv_array_push(&submodule_options, "--recurse-submodules");
432
433         if (cached)
434                 argv_array_push(&submodule_options, "--cached");
435         if (!use_index)
436                 argv_array_push(&submodule_options, "--no-index");
437         if (untracked)
438                 argv_array_push(&submodule_options, "--untracked");
439         if (opt_exclude > 0)
440                 argv_array_push(&submodule_options, "--exclude-standard");
441
442         if (opt->invert)
443                 argv_array_push(&submodule_options, "-v");
444         if (opt->ignore_case)
445                 argv_array_push(&submodule_options, "-i");
446         if (opt->word_regexp)
447                 argv_array_push(&submodule_options, "-w");
448         switch (opt->binary) {
449         case GREP_BINARY_NOMATCH:
450                 argv_array_push(&submodule_options, "-I");
451                 break;
452         case GREP_BINARY_TEXT:
453                 argv_array_push(&submodule_options, "-a");
454                 break;
455         default:
456                 break;
457         }
458         if (opt->allow_textconv)
459                 argv_array_push(&submodule_options, "--textconv");
460         if (opt->max_depth != -1)
461                 argv_array_pushf(&submodule_options, "--max-depth=%d",
462                                  opt->max_depth);
463         if (opt->linenum)
464                 argv_array_push(&submodule_options, "-n");
465         if (!opt->pathname)
466                 argv_array_push(&submodule_options, "-h");
467         if (!opt->relative)
468                 argv_array_push(&submodule_options, "--full-name");
469         if (opt->name_only)
470                 argv_array_push(&submodule_options, "-l");
471         if (opt->unmatch_name_only)
472                 argv_array_push(&submodule_options, "-L");
473         if (opt->null_following_name)
474                 argv_array_push(&submodule_options, "-z");
475         if (opt->count)
476                 argv_array_push(&submodule_options, "-c");
477         if (opt->file_break)
478                 argv_array_push(&submodule_options, "--break");
479         if (opt->heading)
480                 argv_array_push(&submodule_options, "--heading");
481         if (opt->pre_context)
482                 argv_array_pushf(&submodule_options, "--before-context=%d",
483                                  opt->pre_context);
484         if (opt->post_context)
485                 argv_array_pushf(&submodule_options, "--after-context=%d",
486                                  opt->post_context);
487         if (opt->funcname)
488                 argv_array_push(&submodule_options, "-p");
489         if (opt->funcbody)
490                 argv_array_push(&submodule_options, "-W");
491         if (opt->all_match)
492                 argv_array_push(&submodule_options, "--all-match");
493         if (opt->debug)
494                 argv_array_push(&submodule_options, "--debug");
495         if (opt->status_only)
496                 argv_array_push(&submodule_options, "-q");
497
498         switch (pattern_type_arg) {
499         case GREP_PATTERN_TYPE_BRE:
500                 argv_array_push(&submodule_options, "-G");
501                 break;
502         case GREP_PATTERN_TYPE_ERE:
503                 argv_array_push(&submodule_options, "-E");
504                 break;
505         case GREP_PATTERN_TYPE_FIXED:
506                 argv_array_push(&submodule_options, "-F");
507                 break;
508         case GREP_PATTERN_TYPE_PCRE:
509                 argv_array_push(&submodule_options, "-P");
510                 break;
511         case GREP_PATTERN_TYPE_UNSPECIFIED:
512                 break;
513         default:
514                 die("BUG: Added a new grep pattern type without updating switch statement");
515         }
516
517         for (pattern = opt->pattern_list; pattern != NULL;
518              pattern = pattern->next) {
519                 switch (pattern->token) {
520                 case GREP_PATTERN:
521                         argv_array_pushf(&submodule_options, "-e%s",
522                                          pattern->pattern);
523                         break;
524                 case GREP_AND:
525                 case GREP_OPEN_PAREN:
526                 case GREP_CLOSE_PAREN:
527                 case GREP_NOT:
528                 case GREP_OR:
529                         argv_array_push(&submodule_options, pattern->pattern);
530                         break;
531                 /* BODY and HEAD are not used by git-grep */
532                 case GREP_PATTERN_BODY:
533                 case GREP_PATTERN_HEAD:
534                         break;
535                 }
536         }
537
538         /*
539          * Limit number of threads for child process to use.
540          * This is to prevent potential fork-bomb behavior of git-grep as each
541          * submodule process has its own thread pool.
542          */
543         argv_array_pushf(&submodule_options, "--threads=%d",
544                          (num_threads + 1) / 2);
545
546         /* Add Pathspecs */
547         argv_array_push(&submodule_options, "--");
548         for (; *argv; argv++)
549                 argv_array_push(&submodule_options, *argv);
550 }
551
552 /*
553  * Launch child process to grep contents of a submodule
554  */
555 static int grep_submodule_launch(struct grep_opt *opt,
556                                  const struct grep_source *gs)
557 {
558         struct child_process cp = CHILD_PROCESS_INIT;
559         int status, i;
560         const char *end_of_base;
561         const char *name;
562         struct strbuf child_output = STRBUF_INIT;
563
564         end_of_base = strchr(gs->name, ':');
565         if (gs->identifier && end_of_base)
566                 name = end_of_base + 1;
567         else
568                 name = gs->name;
569
570         prepare_submodule_repo_env(&cp.env_array);
571         argv_array_push(&cp.env_array, GIT_DIR_ENVIRONMENT);
572
573         if (opt->relative && opt->prefix_length)
574                 argv_array_pushf(&cp.env_array, "%s=%s",
575                                  GIT_TOPLEVEL_PREFIX_ENVIRONMENT,
576                                  opt->prefix);
577
578         /* Add super prefix */
579         argv_array_pushf(&cp.args, "--super-prefix=%s%s/",
580                          super_prefix ? super_prefix : "",
581                          name);
582         argv_array_push(&cp.args, "grep");
583
584         /*
585          * Add basename of parent project
586          * When performing grep on a tree object the filename is prefixed
587          * with the object's name: 'tree-name:filename'.  In order to
588          * provide uniformity of output we want to pass the name of the
589          * parent project's object name to the submodule so the submodule can
590          * prefix its output with the parent's name and not its own OID.
591          */
592         if (gs->identifier && end_of_base)
593                 argv_array_pushf(&cp.args, "--parent-basename=%.*s",
594                                  (int) (end_of_base - gs->name),
595                                  gs->name);
596
597         /* Add options */
598         for (i = 0; i < submodule_options.argc; i++) {
599                 /*
600                  * If there is a tree identifier for the submodule, add the
601                  * rev after adding the submodule options but before the
602                  * pathspecs.  To do this we listen for the '--' and insert the
603                  * oid before pushing the '--' onto the child process argv
604                  * array.
605                  */
606                 if (gs->identifier &&
607                     !strcmp("--", submodule_options.argv[i])) {
608                         argv_array_push(&cp.args, oid_to_hex(gs->identifier));
609                 }
610
611                 argv_array_push(&cp.args, submodule_options.argv[i]);
612         }
613
614         cp.git_cmd = 1;
615         cp.dir = gs->path;
616
617         /*
618          * Capture output to output buffer and check the return code from the
619          * child process.  A '0' indicates a hit, a '1' indicates no hit and
620          * anything else is an error.
621          */
622         status = capture_command(&cp, &child_output, 0);
623         if (status && (status != 1)) {
624                 /* flush the buffer */
625                 write_or_die(1, child_output.buf, child_output.len);
626                 die("process for submodule '%s' failed with exit code: %d",
627                     gs->name, status);
628         }
629
630         opt->output(opt, child_output.buf, child_output.len);
631         strbuf_release(&child_output);
632         /* invert the return code to make a hit equal to 1 */
633         return !status;
634 }
635
636 /*
637  * Prep grep structures for a submodule grep
638  * oid: the oid of the submodule or NULL if using the working tree
639  * filename: name of the submodule including tree name of parent
640  * path: location of the submodule
641  */
642 static int grep_submodule(struct grep_opt *opt, const struct object_id *oid,
643                           const char *filename, const char *path)
644 {
645         if (!is_submodule_initialized(path))
646                 return 0;
647         if (!is_submodule_populated_gently(path, NULL)) {
648                 /*
649                  * If searching history, check for the presense of the
650                  * submodule's gitdir before skipping the submodule.
651                  */
652                 if (oid) {
653                         const struct submodule *sub =
654                                         submodule_from_path(null_sha1, path);
655                         if (sub)
656                                 path = git_path("modules/%s", sub->name);
657
658                         if (!(is_directory(path) && is_git_directory(path)))
659                                 return 0;
660                 } else {
661                         return 0;
662                 }
663         }
664
665 #ifndef NO_PTHREADS
666         if (num_threads) {
667                 add_work(opt, GREP_SOURCE_SUBMODULE, filename, path, oid);
668                 return 0;
669         } else
670 #endif
671         {
672                 struct grep_source gs;
673                 int hit;
674
675                 grep_source_init(&gs, GREP_SOURCE_SUBMODULE,
676                                  filename, path, oid);
677                 hit = grep_submodule_launch(opt, &gs);
678
679                 grep_source_clear(&gs);
680                 return hit;
681         }
682 }
683
684 static int grep_cache(struct grep_opt *opt, const struct pathspec *pathspec,
685                       int cached)
686 {
687         int hit = 0;
688         int nr;
689         struct strbuf name = STRBUF_INIT;
690         int name_base_len = 0;
691         if (super_prefix) {
692                 name_base_len = strlen(super_prefix);
693                 strbuf_addstr(&name, super_prefix);
694         }
695
696         read_cache();
697
698         for (nr = 0; nr < active_nr; nr++) {
699                 const struct cache_entry *ce = active_cache[nr];
700                 strbuf_setlen(&name, name_base_len);
701                 strbuf_addstr(&name, ce->name);
702
703                 if (S_ISREG(ce->ce_mode) &&
704                     match_pathspec(pathspec, name.buf, name.len, 0, NULL,
705                                    S_ISDIR(ce->ce_mode) ||
706                                    S_ISGITLINK(ce->ce_mode))) {
707                         /*
708                          * If CE_VALID is on, we assume worktree file and its
709                          * cache entry are identical, even if worktree file has
710                          * been modified, so use cache version instead
711                          */
712                         if (cached || (ce->ce_flags & CE_VALID) ||
713                             ce_skip_worktree(ce)) {
714                                 if (ce_stage(ce) || ce_intent_to_add(ce))
715                                         continue;
716                                 hit |= grep_oid(opt, &ce->oid, ce->name,
717                                                  0, ce->name);
718                         } else {
719                                 hit |= grep_file(opt, ce->name);
720                         }
721                 } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
722                            submodule_path_match(pathspec, name.buf, NULL)) {
723                         hit |= grep_submodule(opt, NULL, ce->name, ce->name);
724                 } else {
725                         continue;
726                 }
727
728                 if (ce_stage(ce)) {
729                         do {
730                                 nr++;
731                         } while (nr < active_nr &&
732                                  !strcmp(ce->name, active_cache[nr]->name));
733                         nr--; /* compensate for loop control */
734                 }
735                 if (hit && opt->status_only)
736                         break;
737         }
738
739         strbuf_release(&name);
740         return hit;
741 }
742
743 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
744                      struct tree_desc *tree, struct strbuf *base, int tn_len,
745                      int check_attr)
746 {
747         int hit = 0;
748         enum interesting match = entry_not_interesting;
749         struct name_entry entry;
750         int old_baselen = base->len;
751         struct strbuf name = STRBUF_INIT;
752         int name_base_len = 0;
753         if (super_prefix) {
754                 strbuf_addstr(&name, super_prefix);
755                 name_base_len = name.len;
756         }
757
758         while (tree_entry(tree, &entry)) {
759                 int te_len = tree_entry_len(&entry);
760
761                 if (match != all_entries_interesting) {
762                         strbuf_addstr(&name, base->buf + tn_len);
763                         match = tree_entry_interesting(&entry, &name,
764                                                        0, pathspec);
765                         strbuf_setlen(&name, name_base_len);
766
767                         if (match == all_entries_not_interesting)
768                                 break;
769                         if (match == entry_not_interesting)
770                                 continue;
771                 }
772
773                 strbuf_add(base, entry.path, te_len);
774
775                 if (S_ISREG(entry.mode)) {
776                         hit |= grep_oid(opt, entry.oid, base->buf, tn_len,
777                                          check_attr ? base->buf + tn_len : NULL);
778                 } else if (S_ISDIR(entry.mode)) {
779                         enum object_type type;
780                         struct tree_desc sub;
781                         void *data;
782                         unsigned long size;
783
784                         data = lock_and_read_oid_file(entry.oid, &type, &size);
785                         if (!data)
786                                 die(_("unable to read tree (%s)"),
787                                     oid_to_hex(entry.oid));
788
789                         strbuf_addch(base, '/');
790                         init_tree_desc(&sub, data, size);
791                         hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
792                                          check_attr);
793                         free(data);
794                 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
795                         hit |= grep_submodule(opt, entry.oid, base->buf,
796                                               base->buf + tn_len);
797                 }
798
799                 strbuf_setlen(base, old_baselen);
800
801                 if (hit && opt->status_only)
802                         break;
803         }
804
805         strbuf_release(&name);
806         return hit;
807 }
808
809 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
810                        struct object *obj, const char *name, const char *path)
811 {
812         if (obj->type == OBJ_BLOB)
813                 return grep_oid(opt, &obj->oid, name, 0, path);
814         if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
815                 struct tree_desc tree;
816                 void *data;
817                 unsigned long size;
818                 struct strbuf base;
819                 int hit, len;
820
821                 grep_read_lock();
822                 data = read_object_with_reference(obj->oid.hash, tree_type,
823                                                   &size, NULL);
824                 grep_read_unlock();
825
826                 if (!data)
827                         die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
828
829                 /* Use parent's name as base when recursing submodules */
830                 if (recurse_submodules && parent_basename)
831                         name = parent_basename;
832
833                 len = name ? strlen(name) : 0;
834                 strbuf_init(&base, PATH_MAX + len + 1);
835                 if (len) {
836                         strbuf_add(&base, name, len);
837                         strbuf_addch(&base, ':');
838                 }
839                 init_tree_desc(&tree, data, size);
840                 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
841                                 obj->type == OBJ_COMMIT);
842                 strbuf_release(&base);
843                 free(data);
844                 return hit;
845         }
846         die(_("unable to grep from object of type %s"), typename(obj->type));
847 }
848
849 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
850                         const struct object_array *list)
851 {
852         unsigned int i;
853         int hit = 0;
854         const unsigned int nr = list->nr;
855
856         for (i = 0; i < nr; i++) {
857                 struct object *real_obj;
858                 real_obj = deref_tag(list->objects[i].item, NULL, 0);
859
860                 /* load the gitmodules file for this rev */
861                 if (recurse_submodules) {
862                         submodule_free();
863                         gitmodules_config_sha1(real_obj->oid.hash);
864                 }
865                 if (grep_object(opt, pathspec, real_obj, list->objects[i].name, list->objects[i].path)) {
866                         hit = 1;
867                         if (opt->status_only)
868                                 break;
869                 }
870         }
871         return hit;
872 }
873
874 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
875                           int exc_std, int use_index)
876 {
877         struct dir_struct dir;
878         int i, hit = 0;
879
880         memset(&dir, 0, sizeof(dir));
881         if (!use_index)
882                 dir.flags |= DIR_NO_GITLINKS;
883         if (exc_std)
884                 setup_standard_excludes(&dir);
885
886         fill_directory(&dir, &the_index, pathspec);
887         for (i = 0; i < dir.nr; i++) {
888                 if (!dir_path_match(dir.entries[i], pathspec, 0, NULL))
889                         continue;
890                 hit |= grep_file(opt, dir.entries[i]->name);
891                 if (hit && opt->status_only)
892                         break;
893         }
894         return hit;
895 }
896
897 static int context_callback(const struct option *opt, const char *arg,
898                             int unset)
899 {
900         struct grep_opt *grep_opt = opt->value;
901         int value;
902         const char *endp;
903
904         if (unset) {
905                 grep_opt->pre_context = grep_opt->post_context = 0;
906                 return 0;
907         }
908         value = strtol(arg, (char **)&endp, 10);
909         if (*endp) {
910                 return error(_("switch `%c' expects a numerical value"),
911                              opt->short_name);
912         }
913         grep_opt->pre_context = grep_opt->post_context = value;
914         return 0;
915 }
916
917 static int file_callback(const struct option *opt, const char *arg, int unset)
918 {
919         struct grep_opt *grep_opt = opt->value;
920         int from_stdin = !strcmp(arg, "-");
921         FILE *patterns;
922         int lno = 0;
923         struct strbuf sb = STRBUF_INIT;
924
925         patterns = from_stdin ? stdin : fopen(arg, "r");
926         if (!patterns)
927                 die_errno(_("cannot open '%s'"), arg);
928         while (strbuf_getline(&sb, patterns) == 0) {
929                 /* ignore empty line like grep does */
930                 if (sb.len == 0)
931                         continue;
932
933                 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
934                                 GREP_PATTERN);
935         }
936         if (!from_stdin)
937                 fclose(patterns);
938         strbuf_release(&sb);
939         return 0;
940 }
941
942 static int not_callback(const struct option *opt, const char *arg, int unset)
943 {
944         struct grep_opt *grep_opt = opt->value;
945         append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
946         return 0;
947 }
948
949 static int and_callback(const struct option *opt, const char *arg, int unset)
950 {
951         struct grep_opt *grep_opt = opt->value;
952         append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
953         return 0;
954 }
955
956 static int open_callback(const struct option *opt, const char *arg, int unset)
957 {
958         struct grep_opt *grep_opt = opt->value;
959         append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
960         return 0;
961 }
962
963 static int close_callback(const struct option *opt, const char *arg, int unset)
964 {
965         struct grep_opt *grep_opt = opt->value;
966         append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
967         return 0;
968 }
969
970 static int pattern_callback(const struct option *opt, const char *arg,
971                             int unset)
972 {
973         struct grep_opt *grep_opt = opt->value;
974         append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
975         return 0;
976 }
977
978 int cmd_grep(int argc, const char **argv, const char *prefix)
979 {
980         int hit = 0;
981         int cached = 0, untracked = 0, opt_exclude = -1;
982         int seen_dashdash = 0;
983         int external_grep_allowed__ignored;
984         const char *show_in_pager = NULL, *default_pager = "dummy";
985         struct grep_opt opt;
986         struct object_array list = OBJECT_ARRAY_INIT;
987         struct pathspec pathspec;
988         struct string_list path_list = STRING_LIST_INIT_NODUP;
989         int i;
990         int dummy;
991         int use_index = 1;
992         int pattern_type_arg = GREP_PATTERN_TYPE_UNSPECIFIED;
993         int allow_revs;
994
995         struct option options[] = {
996                 OPT_BOOL(0, "cached", &cached,
997                         N_("search in index instead of in the work tree")),
998                 OPT_NEGBIT(0, "no-index", &use_index,
999                          N_("find in contents not managed by git"), 1),
1000                 OPT_BOOL(0, "untracked", &untracked,
1001                         N_("search in both tracked and untracked files")),
1002                 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
1003                             N_("ignore files specified via '.gitignore'"), 1),
1004                 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
1005                          N_("recursively search in each submodule")),
1006                 OPT_STRING(0, "parent-basename", &parent_basename,
1007                            N_("basename"),
1008                            N_("prepend parent project's basename to output")),
1009                 OPT_GROUP(""),
1010                 OPT_BOOL('v', "invert-match", &opt.invert,
1011                         N_("show non-matching lines")),
1012                 OPT_BOOL('i', "ignore-case", &opt.ignore_case,
1013                         N_("case insensitive matching")),
1014                 OPT_BOOL('w', "word-regexp", &opt.word_regexp,
1015                         N_("match patterns only at word boundaries")),
1016                 OPT_SET_INT('a', "text", &opt.binary,
1017                         N_("process binary files as text"), GREP_BINARY_TEXT),
1018                 OPT_SET_INT('I', NULL, &opt.binary,
1019                         N_("don't match patterns in binary files"),
1020                         GREP_BINARY_NOMATCH),
1021                 OPT_BOOL(0, "textconv", &opt.allow_textconv,
1022                          N_("process binary files with textconv filters")),
1023                 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
1024                         N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
1025                         NULL, 1 },
1026                 OPT_GROUP(""),
1027                 OPT_SET_INT('E', "extended-regexp", &pattern_type_arg,
1028                             N_("use extended POSIX regular expressions"),
1029                             GREP_PATTERN_TYPE_ERE),
1030                 OPT_SET_INT('G', "basic-regexp", &pattern_type_arg,
1031                             N_("use basic POSIX regular expressions (default)"),
1032                             GREP_PATTERN_TYPE_BRE),
1033                 OPT_SET_INT('F', "fixed-strings", &pattern_type_arg,
1034                             N_("interpret patterns as fixed strings"),
1035                             GREP_PATTERN_TYPE_FIXED),
1036                 OPT_SET_INT('P', "perl-regexp", &pattern_type_arg,
1037                             N_("use Perl-compatible regular expressions"),
1038                             GREP_PATTERN_TYPE_PCRE),
1039                 OPT_GROUP(""),
1040                 OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
1041                 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
1042                 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
1043                 OPT_NEGBIT(0, "full-name", &opt.relative,
1044                         N_("show filenames relative to top directory"), 1),
1045                 OPT_BOOL('l', "files-with-matches", &opt.name_only,
1046                         N_("show only filenames instead of matching lines")),
1047                 OPT_BOOL(0, "name-only", &opt.name_only,
1048                         N_("synonym for --files-with-matches")),
1049                 OPT_BOOL('L', "files-without-match",
1050                         &opt.unmatch_name_only,
1051                         N_("show only the names of files without match")),
1052                 OPT_BOOL('z', "null", &opt.null_following_name,
1053                         N_("print NUL after filenames")),
1054                 OPT_BOOL('c', "count", &opt.count,
1055                         N_("show the number of matches instead of matching lines")),
1056                 OPT__COLOR(&opt.color, N_("highlight matches")),
1057                 OPT_BOOL(0, "break", &opt.file_break,
1058                         N_("print empty line between matches from different files")),
1059                 OPT_BOOL(0, "heading", &opt.heading,
1060                         N_("show filename only once above matches from same file")),
1061                 OPT_GROUP(""),
1062                 OPT_CALLBACK('C', "context", &opt, N_("n"),
1063                         N_("show <n> context lines before and after matches"),
1064                         context_callback),
1065                 OPT_INTEGER('B', "before-context", &opt.pre_context,
1066                         N_("show <n> context lines before matches")),
1067                 OPT_INTEGER('A', "after-context", &opt.post_context,
1068                         N_("show <n> context lines after matches")),
1069                 OPT_INTEGER(0, "threads", &num_threads,
1070                         N_("use <n> worker threads")),
1071                 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
1072                         context_callback),
1073                 OPT_BOOL('p', "show-function", &opt.funcname,
1074                         N_("show a line with the function name before matches")),
1075                 OPT_BOOL('W', "function-context", &opt.funcbody,
1076                         N_("show the surrounding function")),
1077                 OPT_GROUP(""),
1078                 OPT_CALLBACK('f', NULL, &opt, N_("file"),
1079                         N_("read patterns from file"), file_callback),
1080                 { OPTION_CALLBACK, 'e', NULL, &opt, N_("pattern"),
1081                         N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback },
1082                 { OPTION_CALLBACK, 0, "and", &opt, NULL,
1083                   N_("combine patterns specified with -e"),
1084                   PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
1085                 OPT_BOOL(0, "or", &dummy, ""),
1086                 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
1087                   PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
1088                 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
1089                   PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
1090                   open_callback },
1091                 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
1092                   PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
1093                   close_callback },
1094                 OPT__QUIET(&opt.status_only,
1095                            N_("indicate hit with exit status without output")),
1096                 OPT_BOOL(0, "all-match", &opt.all_match,
1097                         N_("show only matches from files that match all patterns")),
1098                 { OPTION_SET_INT, 0, "debug", &opt.debug, NULL,
1099                   N_("show parse tree for grep expression"),
1100                   PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 1 },
1101                 OPT_GROUP(""),
1102                 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
1103                         N_("pager"), N_("show matching files in the pager"),
1104                         PARSE_OPT_OPTARG, NULL, (intptr_t)default_pager },
1105                 OPT_BOOL(0, "ext-grep", &external_grep_allowed__ignored,
1106                          N_("allow calling of grep(1) (ignored by this build)")),
1107                 OPT_END()
1108         };
1109
1110         init_grep_defaults();
1111         git_config(grep_cmd_config, NULL);
1112         grep_init(&opt, prefix);
1113         super_prefix = get_super_prefix();
1114
1115         /*
1116          * If there is no -- then the paths must exist in the working
1117          * tree.  If there is no explicit pattern specified with -e or
1118          * -f, we take the first unrecognized non option to be the
1119          * pattern, but then what follows it must be zero or more
1120          * valid refs up to the -- (if exists), and then existing
1121          * paths.  If there is an explicit pattern, then the first
1122          * unrecognized non option is the beginning of the refs list
1123          * that continues up to the -- (if exists), and then paths.
1124          */
1125         argc = parse_options(argc, argv, prefix, options, grep_usage,
1126                              PARSE_OPT_KEEP_DASHDASH |
1127                              PARSE_OPT_STOP_AT_NON_OPTION);
1128         grep_commit_pattern_type(pattern_type_arg, &opt);
1129
1130         if (use_index && !startup_info->have_repository) {
1131                 int fallback = 0;
1132                 git_config_get_bool("grep.fallbacktonoindex", &fallback);
1133                 if (fallback)
1134                         use_index = 0;
1135                 else
1136                         /* die the same way as if we did it at the beginning */
1137                         setup_git_directory();
1138         }
1139
1140         /*
1141          * skip a -- separator; we know it cannot be
1142          * separating revisions from pathnames if
1143          * we haven't even had any patterns yet
1144          */
1145         if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1146                 argv++;
1147                 argc--;
1148         }
1149
1150         /* First unrecognized non-option token */
1151         if (argc > 0 && !opt.pattern_list) {
1152                 append_grep_pattern(&opt, argv[0], "command line", 0,
1153                                     GREP_PATTERN);
1154                 argv++;
1155                 argc--;
1156         }
1157
1158         if (show_in_pager == default_pager)
1159                 show_in_pager = git_pager(1);
1160         if (show_in_pager) {
1161                 opt.color = 0;
1162                 opt.name_only = 1;
1163                 opt.null_following_name = 1;
1164                 opt.output_priv = &path_list;
1165                 opt.output = append_path;
1166                 string_list_append(&path_list, show_in_pager);
1167         }
1168
1169         if (!opt.pattern_list)
1170                 die(_("no pattern given."));
1171         if (!opt.fixed && opt.ignore_case)
1172                 opt.regflags |= REG_ICASE;
1173
1174         /*
1175          * We have to find "--" in a separate pass, because its presence
1176          * influences how we will parse arguments that come before it.
1177          */
1178         for (i = 0; i < argc; i++) {
1179                 if (!strcmp(argv[i], "--")) {
1180                         seen_dashdash = 1;
1181                         break;
1182                 }
1183         }
1184
1185         /*
1186          * Resolve any rev arguments. If we have a dashdash, then everything up
1187          * to it must resolve as a rev. If not, then we stop at the first
1188          * non-rev and assume everything else is a path.
1189          */
1190         allow_revs = use_index && !untracked;
1191         for (i = 0; i < argc; i++) {
1192                 const char *arg = argv[i];
1193                 struct object_id oid;
1194                 struct object_context oc;
1195                 struct object *object;
1196
1197                 if (!strcmp(arg, "--")) {
1198                         i++;
1199                         break;
1200                 }
1201
1202                 if (!allow_revs) {
1203                         if (seen_dashdash)
1204                                 die(_("--no-index or --untracked cannot be used with revs"));
1205                         break;
1206                 }
1207
1208                 if (get_sha1_with_context(arg, GET_SHA1_RECORD_PATH,
1209                                           oid.hash, &oc)) {
1210                         if (seen_dashdash)
1211                                 die(_("unable to resolve revision: %s"), arg);
1212                         break;
1213                 }
1214
1215                 object = parse_object_or_die(&oid, arg);
1216                 if (!seen_dashdash)
1217                         verify_non_filename(prefix, arg);
1218                 add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
1219                 free(oc.path);
1220         }
1221
1222         /*
1223          * Anything left over is presumed to be a path. But in the non-dashdash
1224          * "do what I mean" case, we verify and complain when that isn't true.
1225          */
1226         if (!seen_dashdash) {
1227                 int j;
1228                 for (j = i; j < argc; j++)
1229                         verify_filename(prefix, argv[j], j == i && allow_revs);
1230         }
1231
1232         parse_pathspec(&pathspec, 0,
1233                        PATHSPEC_PREFER_CWD |
1234                        (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
1235                        prefix, argv + i);
1236         pathspec.max_depth = opt.max_depth;
1237         pathspec.recursive = 1;
1238
1239 #ifndef NO_PTHREADS
1240         if (list.nr || cached || show_in_pager)
1241                 num_threads = 0;
1242         else if (num_threads == 0)
1243                 num_threads = GREP_NUM_THREADS_DEFAULT;
1244         else if (num_threads < 0)
1245                 die(_("invalid number of threads specified (%d)"), num_threads);
1246         if (num_threads == 1)
1247                 num_threads = 0;
1248 #else
1249         if (num_threads)
1250                 warning(_("no threads support, ignoring --threads"));
1251         num_threads = 0;
1252 #endif
1253
1254         if (!num_threads)
1255                 /*
1256                  * The compiled patterns on the main path are only
1257                  * used when not using threading. Otherwise
1258                  * start_threads() below calls compile_grep_patterns()
1259                  * for each thread.
1260                  */
1261                 compile_grep_patterns(&opt);
1262
1263 #ifndef NO_PTHREADS
1264         if (num_threads) {
1265                 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
1266                     && (opt.pre_context || opt.post_context ||
1267                         opt.file_break || opt.funcbody))
1268                         skip_first_line = 1;
1269                 start_threads(&opt);
1270         }
1271 #endif
1272
1273         if (recurse_submodules) {
1274                 gitmodules_config();
1275                 compile_submodule_options(&opt, argv + i, cached, untracked,
1276                                           opt_exclude, use_index,
1277                                           pattern_type_arg);
1278         }
1279
1280         if (show_in_pager && (cached || list.nr))
1281                 die(_("--open-files-in-pager only works on the worktree"));
1282
1283         if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1284                 const char *pager = path_list.items[0].string;
1285                 int len = strlen(pager);
1286
1287                 if (len > 4 && is_dir_sep(pager[len - 5]))
1288                         pager += len - 4;
1289
1290                 if (opt.ignore_case && !strcmp("less", pager))
1291                         string_list_append(&path_list, "-I");
1292
1293                 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1294                         struct strbuf buf = STRBUF_INIT;
1295                         strbuf_addf(&buf, "+/%s%s",
1296                                         strcmp("less", pager) ? "" : "*",
1297                                         opt.pattern_list->pattern);
1298                         string_list_append(&path_list, buf.buf);
1299                         strbuf_detach(&buf, NULL);
1300                 }
1301         }
1302
1303         if (recurse_submodules && (!use_index || untracked))
1304                 die(_("option not supported with --recurse-submodules."));
1305
1306         if (!show_in_pager && !opt.status_only)
1307                 setup_pager();
1308
1309         if (!use_index && (untracked || cached))
1310                 die(_("--cached or --untracked cannot be used with --no-index."));
1311
1312         if (!use_index || untracked) {
1313                 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
1314                 hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
1315         } else if (0 <= opt_exclude) {
1316                 die(_("--[no-]exclude-standard cannot be used for tracked contents."));
1317         } else if (!list.nr) {
1318                 if (!cached)
1319                         setup_work_tree();
1320
1321                 hit = grep_cache(&opt, &pathspec, cached);
1322         } else {
1323                 if (cached)
1324                         die(_("both --cached and trees are given."));
1325                 hit = grep_objects(&opt, &pathspec, &list);
1326         }
1327
1328         if (num_threads)
1329                 hit |= wait_all();
1330         if (hit && show_in_pager)
1331                 run_pager(&opt, prefix);
1332         clear_pathspec(&pathspec);
1333         free_grep_patterns(&opt);
1334         return !hit;
1335 }