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