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