Raw
1 /*
2 * Builtin "git grep"
3 *
4 * Copyright (c) 2006 Junio C Hamano
5 */
6
7 #define USE_THE_REPOSITORY_VARIABLE
8 #define DISABLE_SIGN_COMPARE_WARNINGS
9
10 #include "builtin.h"
11 #include "abspath.h"
12 #include "environment.h"
13 #include "gettext.h"
14 #include "hex.h"
15 #include "config.h"
16 #include "tag.h"
17 #include "tree-walk.h"
18 #include "parse-options.h"
19 #include "string-list.h"
20 #include "run-command.h"
21 #include "grep.h"
22 #include "quote.h"
23 #include "dir.h"
24 #include "pathspec.h"
25 #include "setup.h"
26 #include "submodule.h"
27 #include "submodule-config.h"
28 #include "object-file.h"
29 #include "object-name.h"
30 #include "odb.h"
31 #include "oid-array.h"
32 #include "oidset.h"
33 #include "packfile.h"
34 #include "pager.h"
35 #include "path.h"
36 #include "promisor-remote.h"
37 #include "read-cache-ll.h"
38 #include "write-or-die.h"
39
40 static const char *grep_prefix;
41
42 static char const * const grep_usage[] = {
43 N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
44 NULL
45 };
46
47 static int recurse_submodules;
48
49 static int num_threads;
50
51 static pthread_t *threads;
52
53 /* We use one producer thread and THREADS consumer
54 * threads. The producer adds struct work_items to 'todo' and the
55 * consumers pick work items from the same array.
56 */
57 struct work_item {
58 struct grep_source source;
59 char done;
60 struct strbuf out;
61 };
62
63 /* In the range [todo_done, todo_start) in 'todo' we have work_items
64 * that have been or are processed by a consumer thread. We haven't
65 * written the result for these to stdout yet.
66 *
67 * The work_items in [todo_start, todo_end) are waiting to be picked
68 * up by a consumer thread.
69 *
70 * The ranges are modulo TODO_SIZE.
71 */
72 #define TODO_SIZE 128
73 static struct work_item todo[TODO_SIZE];
74 static int todo_start;
75 static int todo_end;
76 static int todo_done;
77
78 /* Has all work items been added? */
79 static int all_work_added;
80
81 static struct repository **repos_to_free;
82 static size_t repos_to_free_nr, repos_to_free_alloc;
83
84 /* This lock protects all the variables above. */
85 static pthread_mutex_t grep_mutex;
86
87 static inline void grep_lock(void)
88 {
89 pthread_mutex_lock(&grep_mutex);
90 }
91
92 static inline void grep_unlock(void)
93 {
94 pthread_mutex_unlock(&grep_mutex);
95 }
96
97 /* Signalled when a new work_item is added to todo. */
98 static pthread_cond_t cond_add;
99
100 /* Signalled when the result from one work_item is written to
101 * stdout.
102 */
103 static pthread_cond_t cond_write;
104
105 /* Signalled when we are finished with everything. */
106 static pthread_cond_t cond_result;
107
108 static int skip_first_line;
109
110 static void add_work(struct grep_opt *opt, struct grep_source *gs)
111 {
112 if (opt->binary != GREP_BINARY_TEXT)
113 grep_source_load_driver(gs, opt->repo->index);
114
115 grep_lock();
116
117 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
118 pthread_cond_wait(&cond_write, &grep_mutex);
119 }
120
121 todo[todo_end].source = *gs;
122 todo[todo_end].done = 0;
123 strbuf_reset(&todo[todo_end].out);
124 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
125
126 pthread_cond_signal(&cond_add);
127 grep_unlock();
128 }
129
130 static struct work_item *get_work(void)
131 {
132 struct work_item *ret;
133
134 grep_lock();
135 while (todo_start == todo_end && !all_work_added) {
136 pthread_cond_wait(&cond_add, &grep_mutex);
137 }
138
139 if (todo_start == todo_end && all_work_added) {
140 ret = NULL;
141 } else {
142 ret = &todo[todo_start];
143 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
144 }
145 grep_unlock();
146 return ret;
147 }
148
149 static void work_done(struct work_item *w)
150 {
151 int old_done;
152
153 grep_lock();
154 w->done = 1;
155 old_done = todo_done;
156 for(; todo[todo_done].done && todo_done != todo_start;
157 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
158 w = &todo[todo_done];
159 if (w->out.len) {
160 const char *p = w->out.buf;
161 size_t len = w->out.len;
162
163 /* Skip the leading hunk mark of the first file. */
164 if (skip_first_line) {
165 while (len) {
166 len--;
167 if (*p++ == '\n')
168 break;
169 }
170 skip_first_line = 0;
171 }
172
173 write_or_die(1, p, len);
174 }
175 grep_source_clear(&w->source);
176 }
177
178 if (old_done != todo_done)
179 pthread_cond_signal(&cond_write);
180
181 if (all_work_added && todo_done == todo_end)
182 pthread_cond_signal(&cond_result);
183
184 grep_unlock();
185 }
186
187 static void free_repos(void)
188 {
189 int i;
190
191 for (i = 0; i < repos_to_free_nr; i++) {
192 repo_clear(repos_to_free[i]);
193 free(repos_to_free[i]);
194 }
195 FREE_AND_NULL(repos_to_free);
196 repos_to_free_nr = 0;
197 repos_to_free_alloc = 0;
198 }
199
200 static void *run(void *arg)
201 {
202 int hit = 0;
203 struct grep_opt *opt = arg;
204
205 while (1) {
206 struct work_item *w = get_work();
207 if (!w)
208 break;
209
210 opt->output_priv = w;
211 hit |= grep_source(opt, &w->source);
212 grep_source_clear_data(&w->source);
213 work_done(w);
214 }
215 free_grep_patterns(opt);
216 free(opt);
217
218 return (void*) (intptr_t) hit;
219 }
220
221 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
222 {
223 struct work_item *w = opt->output_priv;
224 strbuf_add(&w->out, buf, size);
225 }
226
227 static void start_threads(struct grep_opt *opt)
228 {
229 int i;
230
231 pthread_mutex_init(&grep_mutex, NULL);
232 pthread_mutex_init(&grep_attr_mutex, NULL);
233 pthread_cond_init(&cond_add, NULL);
234 pthread_cond_init(&cond_write, NULL);
235 pthread_cond_init(&cond_result, NULL);
236 grep_use_locks = 1;
237 enable_obj_read_lock();
238
239 for (i = 0; i < ARRAY_SIZE(todo); i++) {
240 strbuf_init(&todo[i].out, 0);
241 }
242
243 CALLOC_ARRAY(threads, num_threads);
244 for (i = 0; i < num_threads; i++) {
245 int err;
246 struct grep_opt *o = grep_opt_dup(opt);
247 o->output = strbuf_out;
248 compile_grep_patterns(o);
249 err = pthread_create(&threads[i], NULL, run, o);
250
251 if (err)
252 die(_("grep: failed to create thread: %s"),
253 strerror(err));
254 }
255 }
256
257 static int wait_all(void)
258 {
259 int hit = 0;
260 int i;
261
262 if (!HAVE_THREADS)
263 BUG("Never call this function unless you have started threads");
264
265 grep_lock();
266 all_work_added = 1;
267
268 /* Wait until all work is done. */
269 while (todo_done != todo_end)
270 pthread_cond_wait(&cond_result, &grep_mutex);
271
272 /* Wake up all the consumer threads so they can see that there
273 * is no more work to do.
274 */
275 pthread_cond_broadcast(&cond_add);
276 grep_unlock();
277
278 for (i = 0; i < num_threads; i++) {
279 void *h;
280 pthread_join(threads[i], &h);
281 hit |= (int) (intptr_t) h;
282 }
283
284 free(threads);
285
286 pthread_mutex_destroy(&grep_mutex);
287 pthread_mutex_destroy(&grep_attr_mutex);
288 pthread_cond_destroy(&cond_add);
289 pthread_cond_destroy(&cond_write);
290 pthread_cond_destroy(&cond_result);
291 grep_use_locks = 0;
292 disable_obj_read_lock();
293
294 return hit;
295 }
296
297 static int grep_cmd_config(const char *var, const char *value,
298 const struct config_context *ctx, void *cb)
299 {
300 int st = grep_config(var, value, ctx, cb);
301
302 if (git_color_config(var, value, cb) < 0)
303 st = -1;
304 else if (git_default_config(var, value, ctx, cb) < 0)
305 st = -1;
306
307 if (!strcmp(var, "grep.threads")) {
308 num_threads = git_config_int(var, value, ctx->kvi);
309 if (num_threads < 0)
310 die(_("invalid number of threads specified (%d) for %s"),
311 num_threads, var);
312 else if (!HAVE_THREADS && num_threads > 1) {
313 /*
314 * TRANSLATORS: %s is the configuration
315 * variable for tweaking threads, currently
316 * grep.threads
317 */
318 warning(_("no threads support, ignoring %s"), var);
319 num_threads = 1;
320 }
321 }
322
323 if (!strcmp(var, "submodule.recurse"))
324 recurse_submodules = git_config_bool(var, value);
325
326 return st;
327 }
328
329 static void grep_source_name(struct grep_opt *opt, const char *filename,
330 int tree_name_len, struct strbuf *out)
331 {
332 strbuf_reset(out);
333
334 if (opt->null_following_name) {
335 if (opt->relative && grep_prefix) {
336 struct strbuf rel_buf = STRBUF_INIT;
337 const char *rel_name =
338 relative_path(filename + tree_name_len,
339 grep_prefix, &rel_buf);
340
341 if (tree_name_len)
342 strbuf_add(out, filename, tree_name_len);
343
344 strbuf_addstr(out, rel_name);
345 strbuf_release(&rel_buf);
346 } else {
347 strbuf_addstr(out, filename);
348 }
349 return;
350 }
351
352 if (opt->relative && grep_prefix)
353 quote_path(filename + tree_name_len, grep_prefix, out, 0);
354 else
355 quote_c_style(filename + tree_name_len, out, NULL, 0);
356
357 if (tree_name_len)
358 strbuf_insert(out, 0, filename, tree_name_len);
359 }
360
361 static int grep_oid(struct grep_opt *opt, const struct object_id *oid,
362 const char *filename, int tree_name_len,
363 const char *path)
364 {
365 struct strbuf pathbuf = STRBUF_INIT;
366 struct grep_source gs;
367
368 grep_source_name(opt, filename, tree_name_len, &pathbuf);
369 grep_source_init_oid(&gs, pathbuf.buf, path, oid, opt->repo);
370 strbuf_release(&pathbuf);
371
372 if (num_threads > 1) {
373 /*
374 * add_work() copies gs and thus assumes ownership of
375 * its fields, so do not call grep_source_clear()
376 */
377 add_work(opt, &gs);
378 return 0;
379 } else {
380 int hit;
381
382 hit = grep_source(opt, &gs);
383
384 grep_source_clear(&gs);
385 return hit;
386 }
387 }
388
389 static int grep_file(struct grep_opt *opt, const char *filename)
390 {
391 struct strbuf buf = STRBUF_INIT;
392 struct grep_source gs;
393
394 grep_source_name(opt, filename, 0, &buf);
395 grep_source_init_file(&gs, buf.buf, filename);
396 strbuf_release(&buf);
397
398 if (num_threads > 1) {
399 /*
400 * add_work() copies gs and thus assumes ownership of
401 * its fields, so do not call grep_source_clear()
402 */
403 add_work(opt, &gs);
404 return 0;
405 } else {
406 int hit;
407
408 hit = grep_source(opt, &gs);
409
410 grep_source_clear(&gs);
411 return hit;
412 }
413 }
414
415 static void append_path(struct grep_opt *opt, const void *data, size_t len)
416 {
417 struct string_list *path_list = opt->output_priv;
418
419 if (len == 1 && *(const char *)data == '\0')
420 return;
421 string_list_append_nodup(path_list, xstrndup(data, len));
422 }
423
424 static void run_pager(struct grep_opt *opt, const char *prefix)
425 {
426 struct string_list *path_list = opt->output_priv;
427 struct child_process child = CHILD_PROCESS_INIT;
428 int i, status;
429
430 for (i = 0; i < path_list->nr; i++)
431 strvec_push(&child.args, path_list->items[i].string);
432 child.dir = prefix;
433 child.use_shell = 1;
434
435 status = run_command(&child);
436 if (status)
437 exit(status);
438 }
439
440 static int grep_cache(struct grep_opt *opt,
441 const struct pathspec *pathspec, int cached);
442 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
443 struct tree_desc *tree, struct strbuf *base, int tn_len,
444 int check_attr);
445
446 static int grep_submodule(struct grep_opt *opt,
447 const struct pathspec *pathspec,
448 const struct object_id *oid,
449 const char *filename, const char *path, int cached)
450 {
451 struct repository *subrepo;
452 struct repository *superproject = opt->repo;
453 struct grep_opt subopt;
454 int hit = 0;
455
456 if (!is_submodule_active(superproject, path))
457 return 0;
458
459 subrepo = xmalloc(sizeof(*subrepo));
460 if (repo_submodule_init(subrepo, superproject, path, null_oid(opt->repo->hash_algo))) {
461 free(subrepo);
462 return 0;
463 }
464 ALLOC_GROW(repos_to_free, repos_to_free_nr + 1, repos_to_free_alloc);
465 repos_to_free[repos_to_free_nr++] = subrepo;
466
467 /*
468 * NEEDSWORK: repo_read_gitmodules() might call
469 * odb_add_to_alternates_memory() via config_from_gitmodules(). This
470 * operation causes a race condition with concurrent object readings
471 * performed by the worker threads. That's why we need obj_read_lock()
472 * here. It should be removed once it's no longer necessary to add the
473 * subrepo's odbs to the in-memory alternates list.
474 */
475 obj_read_lock();
476
477 /*
478 * NEEDSWORK: when reading a submodule, the sparsity settings in the
479 * superproject are incorrectly forgotten or misused. For example:
480 *
481 * 1. "command_requires_full_index"
482 * When this setting is turned on for `grep`, only the superproject
483 * knows it. All the submodules are read with their own configs
484 * and get prepare_repo_settings()'d. Therefore, these submodules
485 * "forget" the sparse-index feature switch. As a result, the index
486 * of these submodules are expanded unexpectedly.
487 *
488 * 2. "config_values_private_.apply_sparse_checkout"
489 * When running `grep` in the superproject, this setting is
490 * populated using the superproject's configs. However, once
491 * initialized, this config is globally accessible and is read by
492 * prepare_repo_settings() for the submodules. For instance, if a
493 * submodule is using a sparse-checkout, however, the superproject
494 * is not, the result is that the config from the superproject will
495 * dictate the behavior for the submodule, making it "forget" its
496 * sparse-checkout state.
497 *
498 * 3. "core_sparse_checkout_cone"
499 * ditto.
500 *
501 * Note that this list is not exhaustive.
502 */
503 repo_read_gitmodules(subrepo, 0);
504
505 /*
506 * All code paths tested by test code no longer need submodule ODBs to
507 * be added as alternates, but add it to the list just in case.
508 * Submodule ODBs added through add_submodule_odb_by_path() will be
509 * lazily registered as alternates when needed (and except in an
510 * unexpected code interaction, it won't be needed).
511 */
512 odb_add_submodule_source_by_path(the_repository->objects,
513 subrepo->objects->sources->path);
514 obj_read_unlock();
515
516 memcpy(&subopt, opt, sizeof(subopt));
517 subopt.repo = subrepo;
518
519 if (oid) {
520 enum object_type object_type;
521 struct tree_desc tree;
522 void *data;
523 unsigned long size;
524 struct strbuf base = STRBUF_INIT;
525
526 obj_read_lock();
527 object_type = odb_read_object_info(subrepo->objects, oid, NULL);
528 obj_read_unlock();
529 data = odb_read_object_peeled(subrepo->objects, oid, OBJ_TREE, &size, NULL);
530 if (!data)
531 die(_("unable to read tree (%s)"), oid_to_hex(oid));
532
533 strbuf_addstr(&base, filename);
534 strbuf_addch(&base, '/');
535
536 init_tree_desc(&tree, oid, data, size);
537 hit = grep_tree(&subopt, pathspec, &tree, &base, base.len,
538 object_type == OBJ_COMMIT);
539 strbuf_release(&base);
540 free(data);
541 } else {
542 hit = grep_cache(&subopt, pathspec, cached);
543 }
544
545 return hit;
546 }
547
548 static int grep_cache(struct grep_opt *opt,
549 const struct pathspec *pathspec, int cached)
550 {
551 struct repository *repo = opt->repo;
552 int hit = 0;
553 int nr;
554 struct strbuf name = STRBUF_INIT;
555 int name_base_len = 0;
556 if (repo->submodule_prefix) {
557 name_base_len = strlen(repo->submodule_prefix);
558 strbuf_addstr(&name, repo->submodule_prefix);
559 }
560
561 if (repo_read_index(repo) < 0)
562 die(_("index file corrupt"));
563
564 for (nr = 0; nr < repo->index->cache_nr; nr++) {
565 const struct cache_entry *ce = repo->index->cache[nr];
566
567 if (!cached && ce_skip_worktree(ce))
568 continue;
569
570 strbuf_setlen(&name, name_base_len);
571 strbuf_addstr(&name, ce->name);
572 if (S_ISSPARSEDIR(ce->ce_mode)) {
573 enum object_type type;
574 struct tree_desc tree;
575 void *data;
576 unsigned long size;
577
578 data = odb_read_object(the_repository->objects, &ce->oid,
579 &type, &size);
580 if (!data)
581 die(_("unable to read tree %s"), oid_to_hex(&ce->oid));
582 init_tree_desc(&tree, &ce->oid, data, size);
583
584 hit |= grep_tree(opt, pathspec, &tree, &name, 0, 0);
585 strbuf_setlen(&name, name_base_len);
586 strbuf_addstr(&name, ce->name);
587 free(data);
588 } else if (S_ISREG(ce->ce_mode) &&
589 match_pathspec(repo->index, pathspec, name.buf, name.len, 0, NULL,
590 S_ISDIR(ce->ce_mode) ||
591 S_ISGITLINK(ce->ce_mode))) {
592 /*
593 * If CE_VALID is on, we assume worktree file and its
594 * cache entry are identical, even if worktree file has
595 * been modified, so use cache version instead
596 */
597 if (cached || (ce->ce_flags & CE_VALID)) {
598 if (ce_stage(ce) || ce_intent_to_add(ce))
599 continue;
600 hit |= grep_oid(opt, &ce->oid, name.buf,
601 0, name.buf);
602 } else {
603 hit |= grep_file(opt, name.buf);
604 }
605 } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
606 submodule_path_match(repo->index, pathspec, name.buf, NULL)) {
607 hit |= grep_submodule(opt, pathspec, NULL, ce->name,
608 ce->name, cached);
609 } else {
610 continue;
611 }
612
613 if (ce_stage(ce)) {
614 do {
615 nr++;
616 } while (nr < repo->index->cache_nr &&
617 !strcmp(ce->name, repo->index->cache[nr]->name));
618 nr--; /* compensate for loop control */
619 }
620 if (hit && opt->status_only)
621 break;
622 }
623
624 strbuf_release(&name);
625 return hit;
626 }
627
628 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
629 struct tree_desc *tree, struct strbuf *base, int tn_len,
630 int check_attr)
631 {
632 struct repository *repo = opt->repo;
633 int hit = 0;
634 enum interesting match = entry_not_interesting;
635 struct name_entry entry;
636 int old_baselen = base->len;
637 struct strbuf name = STRBUF_INIT;
638 int name_base_len = 0;
639 if (repo->submodule_prefix) {
640 strbuf_addstr(&name, repo->submodule_prefix);
641 name_base_len = name.len;
642 }
643
644 while (tree_entry(tree, &entry)) {
645 int te_len = tree_entry_len(&entry);
646
647 if (match != all_entries_interesting) {
648 strbuf_addstr(&name, base->buf + tn_len);
649 match = tree_entry_interesting(repo->index,
650 &entry, &name,
651 pathspec);
652 strbuf_setlen(&name, name_base_len);
653
654 if (match == all_entries_not_interesting)
655 break;
656 if (match == entry_not_interesting)
657 continue;
658 }
659
660 strbuf_add(base, entry.path, te_len);
661
662 if (S_ISREG(entry.mode)) {
663 hit |= grep_oid(opt, &entry.oid, base->buf, tn_len,
664 check_attr ? base->buf + tn_len : NULL);
665 } else if (S_ISDIR(entry.mode)) {
666 enum object_type type;
667 struct tree_desc sub;
668 void *data;
669 unsigned long size;
670
671 data = odb_read_object(the_repository->objects,
672 &entry.oid, &type, &size);
673 if (!data)
674 die(_("unable to read tree (%s)"),
675 oid_to_hex(&entry.oid));
676
677 strbuf_addch(base, '/');
678 init_tree_desc(&sub, &entry.oid, data, size);
679 hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
680 check_attr);
681 free(data);
682 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
683 hit |= grep_submodule(opt, pathspec, &entry.oid,
684 base->buf, base->buf + tn_len,
685 1); /* ignored */
686 }
687
688 strbuf_setlen(base, old_baselen);
689
690 if (hit && opt->status_only)
691 break;
692 }
693
694 strbuf_release(&name);
695 return hit;
696 }
697
698 static void collect_blob_oids_for_tree(struct repository *repo,
699 const struct pathspec *pathspec,
700 struct tree_desc *tree,
701 struct strbuf *base,
702 int tn_len,
703 struct oidset *blob_oids)
704 {
705 struct name_entry entry;
706 int old_baselen = base->len;
707 struct strbuf name = STRBUF_INIT;
708 enum interesting match = entry_not_interesting;
709
710 while (tree_entry(tree, &entry)) {
711 if (match != all_entries_interesting) {
712 strbuf_addstr(&name, base->buf + tn_len);
713 match = tree_entry_interesting(repo->index,
714 &entry, &name,
715 pathspec);
716 strbuf_reset(&name);
717
718 if (match == all_entries_not_interesting)
719 break;
720 if (match == entry_not_interesting)
721 continue;
722 }
723
724 strbuf_add(base, entry.path, tree_entry_len(&entry));
725
726 if (S_ISREG(entry.mode)) {
727 if (!odb_has_object(repo->objects, &entry.oid, 0))
728 oidset_insert(blob_oids, &entry.oid);
729 } else if (S_ISDIR(entry.mode)) {
730 enum object_type type;
731 struct tree_desc sub_tree;
732 void *data;
733 unsigned long size;
734
735 data = odb_read_object(repo->objects, &entry.oid,
736 &type, &size);
737 if (!data)
738 die(_("unable to read tree (%s)"),
739 oid_to_hex(&entry.oid));
740
741 strbuf_addch(base, '/');
742 init_tree_desc(&sub_tree, &entry.oid, data, size);
743 collect_blob_oids_for_tree(repo, pathspec, &sub_tree,
744 base, tn_len, blob_oids);
745 free(data);
746 }
747 /*
748 * ...no else clause for S_ISGITLINK: submodules have their
749 * own promisor configuration and would need separate fetches
750 * anyway.
751 */
752
753 strbuf_setlen(base, old_baselen);
754 }
755
756 strbuf_release(&name);
757 }
758
759 static void collect_blob_oids_for_treeish(struct grep_opt *opt,
760 const struct pathspec *pathspec,
761 const struct object_id *tree_ish_oid,
762 const char *name,
763 struct oidset *blob_oids)
764 {
765 struct tree_desc tree;
766 void *data;
767 unsigned long size;
768 struct strbuf base = STRBUF_INIT;
769 int len;
770
771 data = odb_read_object_peeled(opt->repo->objects, tree_ish_oid,
772 OBJ_TREE, &size, NULL);
773
774 if (!data)
775 return;
776
777 len = name ? strlen(name) : 0;
778 if (len) {
779 strbuf_add(&base, name, len);
780 strbuf_addch(&base, ':');
781 }
782 init_tree_desc(&tree, tree_ish_oid, data, size);
783
784 collect_blob_oids_for_tree(opt->repo, pathspec, &tree,
785 &base, base.len, blob_oids);
786
787 strbuf_release(&base);
788 free(data);
789 }
790
791 static void prefetch_grep_blobs(struct grep_opt *opt,
792 const struct pathspec *pathspec,
793 const struct object_array *list)
794 {
795 struct oidset blob_oids = OIDSET_INIT;
796
797 /* Exit if we're not in a partial clone */
798 if (!repo_has_promisor_remote(opt->repo))
799 return;
800
801 /* For each tree, gather the blobs in it */
802 for (int i = 0; i < list->nr; i++) {
803 struct object *real_obj;
804
805 obj_read_lock();
806 real_obj = deref_tag(opt->repo, list->objects[i].item,
807 NULL, 0);
808 obj_read_unlock();
809
810 if (real_obj &&
811 (real_obj->type == OBJ_COMMIT ||
812 real_obj->type == OBJ_TREE))
813 collect_blob_oids_for_treeish(opt, pathspec,
814 &real_obj->oid,
815 list->objects[i].name,
816 &blob_oids);
817 }
818
819 /* Prefetch the blobs we found */
820 if (oidset_size(&blob_oids)) {
821 struct oid_array to_fetch = OID_ARRAY_INIT;
822 struct oidset_iter iter;
823 const struct object_id *oid;
824
825 oidset_iter_init(&blob_oids, &iter);
826 while ((oid = oidset_iter_next(&iter)))
827 oid_array_append(&to_fetch, oid);
828
829 promisor_remote_get_direct(opt->repo, to_fetch.oid, to_fetch.nr);
830
831 oid_array_clear(&to_fetch);
832 }
833 oidset_clear(&blob_oids);
834 }
835
836 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
837 struct object *obj, const char *name, const char *path)
838 {
839 if (obj->type == OBJ_BLOB)
840 return grep_oid(opt, &obj->oid, name, 0, path);
841 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
842 struct tree_desc tree;
843 void *data;
844 unsigned long size;
845 struct strbuf base;
846 int hit, len;
847
848 data = odb_read_object_peeled(opt->repo->objects, &obj->oid,
849 OBJ_TREE, &size, NULL);
850 if (!data)
851 die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
852
853 len = name ? strlen(name) : 0;
854 strbuf_init(&base, PATH_MAX + len + 1);
855 if (len) {
856 strbuf_add(&base, name, len);
857 strbuf_addch(&base, ':');
858 }
859 init_tree_desc(&tree, &obj->oid, data, size);
860 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
861 obj->type == OBJ_COMMIT);
862 strbuf_release(&base);
863 free(data);
864 return hit;
865 }
866 die(_("unable to grep from object of type %s"), type_name(obj->type));
867 }
868
869 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
870 const struct object_array *list)
871 {
872 unsigned int i;
873 int hit = 0;
874 const unsigned int nr = list->nr;
875
876 prefetch_grep_blobs(opt, pathspec, list);
877
878 for (i = 0; i < nr; i++) {
879 struct object *real_obj;
880
881 obj_read_lock();
882 real_obj = deref_tag(opt->repo, list->objects[i].item,
883 NULL, 0);
884 obj_read_unlock();
885
886 if (!real_obj) {
887 char hex[GIT_MAX_HEXSZ + 1];
888 const char *name = list->objects[i].name;
889
890 if (!name) {
891 oid_to_hex_r(hex, &list->objects[i].item->oid);
892 name = hex;
893 }
894 die(_("invalid object '%s' given."), name);
895 }
896
897 /* load the gitmodules file for this rev */
898 if (recurse_submodules) {
899 submodule_free(opt->repo);
900 obj_read_lock();
901 gitmodules_config_oid(&real_obj->oid);
902 obj_read_unlock();
903 }
904 if (grep_object(opt, pathspec, real_obj, list->objects[i].name,
905 list->objects[i].path)) {
906 hit = 1;
907 if (opt->status_only)
908 break;
909 }
910 }
911 return hit;
912 }
913
914 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
915 int exc_std, int use_index)
916 {
917 struct dir_struct dir = DIR_INIT;
918 int i, hit = 0;
919
920 if (!use_index)
921 dir.flags |= DIR_NO_GITLINKS;
922 if (exc_std)
923 setup_standard_excludes(&dir);
924
925 fill_directory(&dir, opt->repo->index, pathspec);
926 for (i = 0; i < dir.nr; i++) {
927 hit |= grep_file(opt, dir.entries[i]->name);
928 if (hit && opt->status_only)
929 break;
930 }
931 dir_clear(&dir);
932 return hit;
933 }
934
935 static int context_callback(const struct option *opt, const char *arg,
936 int unset)
937 {
938 struct grep_opt *grep_opt = opt->value;
939 int value;
940 const char *endp;
941
942 if (unset) {
943 grep_opt->pre_context = grep_opt->post_context = 0;
944 return 0;
945 }
946 value = strtol(arg, (char **)&endp, 10);
947 if (*endp) {
948 return error(_("switch `%c' expects a numerical value"),
949 opt->short_name);
950 }
951 grep_opt->pre_context = grep_opt->post_context = value;
952 return 0;
953 }
954
955 static int file_callback(const struct option *opt, const char *arg, int unset)
956 {
957 struct grep_opt *grep_opt = opt->value;
958 int from_stdin;
959 const char *filename = arg;
960 FILE *patterns;
961 int lno = 0;
962 struct strbuf sb = STRBUF_INIT;
963
964 BUG_ON_OPT_NEG(unset);
965
966 if (!*filename)
967 ; /* leave it as-is */
968 else
969 filename = prefix_filename_except_for_dash(grep_prefix, filename);
970
971 from_stdin = !strcmp(filename, "-");
972 patterns = from_stdin ? stdin : fopen(filename, "r");
973 if (!patterns)
974 die_errno(_("cannot open '%s'"), arg);
975 while (strbuf_getline(&sb, patterns) == 0) {
976 /* ignore empty line like grep does */
977 if (sb.len == 0)
978 continue;
979
980 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
981 GREP_PATTERN);
982 }
983 if (!from_stdin)
984 fclose(patterns);
985 strbuf_release(&sb);
986 if (filename != arg)
987 free((void *)filename);
988 return 0;
989 }
990
991 static int not_callback(const struct option *opt, const char *arg, int unset)
992 {
993 struct grep_opt *grep_opt = opt->value;
994 BUG_ON_OPT_NEG(unset);
995 BUG_ON_OPT_ARG(arg);
996 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
997 return 0;
998 }
999
1000 static int and_callback(const struct option *opt, const char *arg, int unset)
1001 {
1002 struct grep_opt *grep_opt = opt->value;
1003 BUG_ON_OPT_NEG(unset);
1004 BUG_ON_OPT_ARG(arg);
1005 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
1006 return 0;
1007 }
1008
1009 static int open_callback(const struct option *opt, const char *arg, int unset)
1010 {
1011 struct grep_opt *grep_opt = opt->value;
1012 BUG_ON_OPT_NEG(unset);
1013 BUG_ON_OPT_ARG(arg);
1014 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
1015 return 0;
1016 }
1017
1018 static int close_callback(const struct option *opt, const char *arg, int unset)
1019 {
1020 struct grep_opt *grep_opt = opt->value;
1021 BUG_ON_OPT_NEG(unset);
1022 BUG_ON_OPT_ARG(arg);
1023 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
1024 return 0;
1025 }
1026
1027 static int pattern_callback(const struct option *opt, const char *arg,
1028 int unset)
1029 {
1030 struct grep_opt *grep_opt = opt->value;
1031 BUG_ON_OPT_NEG(unset);
1032 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
1033 return 0;
1034 }
1035
1036 int cmd_grep(int argc,
1037 const char **argv,
1038 const char *prefix,
1039 struct repository *repo UNUSED)
1040 {
1041 int hit = 0;
1042 int cached = 0, untracked = 0, opt_exclude = -1;
1043 int seen_dashdash = 0;
1044 int external_grep_allowed__ignored;
1045 const char *show_in_pager = NULL, *default_pager = "dummy";
1046 struct grep_opt opt;
1047 struct object_array list = OBJECT_ARRAY_INIT;
1048 struct pathspec pathspec;
1049 struct string_list path_list = STRING_LIST_INIT_DUP;
1050 int i;
1051 int dummy;
1052 int use_index = 1;
1053 int allow_revs;
1054 int ret;
1055
1056 struct option options[] = {
1057 OPT_BOOL(0, "cached", &cached,
1058 N_("search in index instead of in the work tree")),
1059 OPT_NEGBIT(0, "no-index", &use_index,
1060 N_("find in contents not managed by git"), 1),
1061 OPT_BOOL(0, "untracked", &untracked,
1062 N_("search in both tracked and untracked files")),
1063 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
1064 N_("ignore files specified via '.gitignore'"), 1),
1065 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
1066 N_("recursively search in each submodule")),
1067 OPT_GROUP(""),
1068 OPT_BOOL('v', "invert-match", &opt.invert,
1069 N_("show non-matching lines")),
1070 OPT_BOOL('i', "ignore-case", &opt.ignore_case,
1071 N_("case insensitive matching")),
1072 OPT_BOOL('w', "word-regexp", &opt.word_regexp,
1073 N_("match patterns only at word boundaries")),
1074 OPT_SET_INT('a', "text", &opt.binary,
1075 N_("process binary files as text"), GREP_BINARY_TEXT),
1076 OPT_SET_INT('I', NULL, &opt.binary,
1077 N_("don't match patterns in binary files"),
1078 GREP_BINARY_NOMATCH),
1079 OPT_BOOL(0, "textconv", &opt.allow_textconv,
1080 N_("process binary files with textconv filters")),
1081 OPT_SET_INT('r', "recursive", &opt.max_depth,
1082 N_("search in subdirectories (default)"), -1),
1083 OPT_INTEGER_F(0, "max-depth", &opt.max_depth,
1084 N_("descend at most <n> levels"), PARSE_OPT_NONEG),
1085 OPT_GROUP(""),
1086 OPT_SET_INT('E', "extended-regexp", &opt.pattern_type_option,
1087 N_("use extended POSIX regular expressions"),
1088 GREP_PATTERN_TYPE_ERE),
1089 OPT_SET_INT('G', "basic-regexp", &opt.pattern_type_option,
1090 N_("use basic POSIX regular expressions (default)"),
1091 GREP_PATTERN_TYPE_BRE),
1092 OPT_SET_INT('F', "fixed-strings", &opt.pattern_type_option,
1093 N_("interpret patterns as fixed strings"),
1094 GREP_PATTERN_TYPE_FIXED),
1095 OPT_SET_INT('P', "perl-regexp", &opt.pattern_type_option,
1096 N_("use Perl-compatible regular expressions"),
1097 GREP_PATTERN_TYPE_PCRE),
1098 OPT_GROUP(""),
1099 OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
1100 OPT_BOOL(0, "column", &opt.columnnum, N_("show column number of first match")),
1101 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
1102 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
1103 OPT_NEGBIT(0, "full-name", &opt.relative,
1104 N_("show filenames relative to top directory"), 1),
1105 OPT_BOOL('l', "files-with-matches", &opt.name_only,
1106 N_("show only filenames instead of matching lines")),
1107 OPT_BOOL(0, "name-only", &opt.name_only,
1108 N_("synonym for --files-with-matches")),
1109 OPT_BOOL('L', "files-without-match",
1110 &opt.unmatch_name_only,
1111 N_("show only the names of files without match")),
1112 OPT_BOOL_F('z', "null", &opt.null_following_name,
1113 N_("print NUL after filenames"),
1114 PARSE_OPT_NOCOMPLETE),
1115 OPT_BOOL('o', "only-matching", &opt.only_matching,
1116 N_("show only matching parts of a line")),
1117 OPT_BOOL('c', "count", &opt.count,
1118 N_("show the number of matches instead of matching lines")),
1119 OPT__COLOR(&opt.color, N_("highlight matches")),
1120 OPT_BOOL(0, "break", &opt.file_break,
1121 N_("print empty line between matches from different files")),
1122 OPT_BOOL(0, "heading", &opt.heading,
1123 N_("show filename only once above matches from same file")),
1124 OPT_GROUP(""),
1125 OPT_CALLBACK('C', "context", &opt, N_("n"),
1126 N_("show <n> context lines before and after matches"),
1127 context_callback),
1128 OPT_UNSIGNED('B', "before-context", &opt.pre_context,
1129 N_("show <n> context lines before matches")),
1130 OPT_UNSIGNED('A', "after-context", &opt.post_context,
1131 N_("show <n> context lines after matches")),
1132 OPT_INTEGER(0, "threads", &num_threads,
1133 N_("use <n> worker threads")),
1134 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
1135 context_callback),
1136 OPT_BOOL('p', "show-function", &opt.funcname,
1137 N_("show a line with the function name before matches")),
1138 OPT_BOOL('W', "function-context", &opt.funcbody,
1139 N_("show the surrounding function")),
1140 OPT_GROUP(""),
1141 OPT_CALLBACK('f', NULL, &opt, N_("file"),
1142 N_("read patterns from file"), file_callback),
1143 OPT_CALLBACK_F('e', NULL, &opt, N_("pattern"),
1144 N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback),
1145 OPT_CALLBACK_F(0, "and", &opt, NULL,
1146 N_("combine patterns specified with -e"),
1147 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback),
1148 OPT_BOOL_F(0, "or", &dummy, "", PARSE_OPT_NONEG),
1149 OPT_CALLBACK_F(0, "not", &opt, NULL, "",
1150 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback),
1151 OPT_CALLBACK_F('(', NULL, &opt, NULL, "",
1152 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
1153 open_callback),
1154 OPT_CALLBACK_F(')', NULL, &opt, NULL, "",
1155 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
1156 close_callback),
1157 OPT__QUIET(&opt.status_only,
1158 N_("indicate hit with exit status without output")),
1159 OPT_BOOL(0, "all-match", &opt.all_match,
1160 N_("show only matches from files that match all patterns")),
1161 OPT_GROUP(""),
1162 {
1163 .type = OPTION_STRING,
1164 .short_name = 'O',
1165 .long_name = "open-files-in-pager",
1166 .value = &show_in_pager,
1167 .argh = N_("pager"),
1168 .help = N_("show matching files in the pager"),
1169 .flags = PARSE_OPT_OPTARG | PARSE_OPT_NOCOMPLETE,
1170 .defval = (intptr_t)default_pager,
1171 },
1172 OPT_BOOL_F(0, "ext-grep", &external_grep_allowed__ignored,
1173 N_("allow calling of grep(1) (ignored by this build)"),
1174 PARSE_OPT_NOCOMPLETE),
1175 OPT_INTEGER('m', "max-count", &opt.max_count,
1176 N_("maximum number of results per file")),
1177 OPT_END()
1178 };
1179 grep_prefix = prefix;
1180
1181 grep_init(&opt, the_repository);
1182 repo_config(the_repository, grep_cmd_config, &opt);
1183
1184 /*
1185 * If there is no -- then the paths must exist in the working
1186 * tree. If there is no explicit pattern specified with -e or
1187 * -f, we take the first unrecognized non option to be the
1188 * pattern, but then what follows it must be zero or more
1189 * valid refs up to the -- (if exists), and then existing
1190 * paths. If there is an explicit pattern, then the first
1191 * unrecognized non option is the beginning of the refs list
1192 * that continues up to the -- (if exists), and then paths.
1193 */
1194 argc = parse_options(argc, argv, prefix, options, grep_usage,
1195 PARSE_OPT_KEEP_DASHDASH |
1196 PARSE_OPT_STOP_AT_NON_OPTION);
1197
1198 if (the_repository->gitdir) {
1199 prepare_repo_settings(the_repository);
1200 the_repository->settings.command_requires_full_index = 0;
1201 }
1202
1203 if (use_index && !startup_info->have_repository) {
1204 int fallback = 0;
1205 repo_config_get_bool(the_repository, "grep.fallbacktonoindex", &fallback);
1206 if (fallback)
1207 use_index = 0;
1208 else
1209 /* die the same way as if we did it at the beginning */
1210 setup_git_directory(the_repository);
1211 }
1212 /* Ignore --recurse-submodules if --no-index is given or implied */
1213 if (!use_index)
1214 recurse_submodules = 0;
1215
1216 /*
1217 * skip a -- separator; we know it cannot be
1218 * separating revisions from pathnames if
1219 * we haven't even had any patterns yet
1220 */
1221 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1222 argv++;
1223 argc--;
1224 }
1225
1226 /* First unrecognized non-option token */
1227 if (argc > 0 && !opt.pattern_list) {
1228 append_grep_pattern(&opt, argv[0], "command line", 0,
1229 GREP_PATTERN);
1230 argv++;
1231 argc--;
1232 }
1233
1234 if (show_in_pager == default_pager)
1235 show_in_pager = git_pager(the_repository, 1);
1236 if (show_in_pager) {
1237 opt.color = GIT_COLOR_NEVER;
1238 opt.name_only = 1;
1239 opt.null_following_name = 1;
1240 opt.output_priv = &path_list;
1241 opt.output = append_path;
1242 string_list_append(&path_list, show_in_pager);
1243 }
1244
1245 if (!opt.pattern_list)
1246 die(_("no pattern given"));
1247
1248 /* --only-matching has no effect with --invert. */
1249 if (opt.invert)
1250 opt.only_matching = 0;
1251
1252 /*
1253 * We have to find "--" in a separate pass, because its presence
1254 * influences how we will parse arguments that come before it.
1255 */
1256 for (i = 0; i < argc; i++) {
1257 if (!strcmp(argv[i], "--")) {
1258 seen_dashdash = 1;
1259 break;
1260 }
1261 }
1262
1263 /*
1264 * Resolve any rev arguments. If we have a dashdash, then everything up
1265 * to it must resolve as a rev. If not, then we stop at the first
1266 * non-rev and assume everything else is a path.
1267 */
1268 allow_revs = use_index && !untracked;
1269 for (i = 0; i < argc; i++) {
1270 const char *arg = argv[i];
1271 struct object_id oid;
1272 struct object_context oc = {0};
1273 struct object *object;
1274
1275 if (!strcmp(arg, "--")) {
1276 i++;
1277 break;
1278 }
1279
1280 if (!allow_revs) {
1281 if (seen_dashdash)
1282 die(_("--no-index or --untracked cannot be used with revs"));
1283 break;
1284 }
1285
1286 if (get_oid_with_context(the_repository, arg,
1287 GET_OID_RECORD_PATH,
1288 &oid, &oc)) {
1289 if (seen_dashdash)
1290 die(_("unable to resolve revision: %s"), arg);
1291 object_context_release(&oc);
1292 break;
1293 }
1294
1295 object = parse_object_or_die(the_repository, &oid, arg);
1296 if (!seen_dashdash)
1297 verify_non_filename(the_repository, prefix, arg);
1298 add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
1299 object_context_release(&oc);
1300 }
1301
1302 /*
1303 * Anything left over is presumed to be a path. But in the non-dashdash
1304 * "do what I mean" case, we verify and complain when that isn't true.
1305 */
1306 if (!seen_dashdash) {
1307 int j;
1308 for (j = i; j < argc; j++)
1309 verify_filename(the_repository, prefix, argv[j], j == i && allow_revs);
1310 }
1311
1312 parse_pathspec(&pathspec, 0,
1313 PATHSPEC_PREFER_CWD |
1314 (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
1315 prefix, argv + i);
1316 pathspec.max_depth = opt.max_depth;
1317 pathspec.recursive = 1;
1318 pathspec.recurse_submodules = !!recurse_submodules;
1319
1320 if (recurse_submodules && untracked)
1321 die(_("--untracked not supported with --recurse-submodules"));
1322
1323 /*
1324 * Optimize out the case where the amount of matches is limited to zero.
1325 * We do this to keep results consistent with GNU grep(1).
1326 */
1327 if (opt.max_count == 0) {
1328 ret = 1;
1329 goto out;
1330 }
1331
1332 if (show_in_pager) {
1333 if (num_threads > 1)
1334 warning(_("invalid option combination, ignoring --threads"));
1335 num_threads = 1;
1336 } else if (!HAVE_THREADS && num_threads > 1) {
1337 warning(_("no threads support, ignoring --threads"));
1338 num_threads = 1;
1339 } else if (num_threads < 0)
1340 die(_("invalid number of threads specified (%d)"), num_threads);
1341 else if (num_threads == 0)
1342 num_threads = HAVE_THREADS ? online_cpus() : 1;
1343
1344 if (num_threads > 1) {
1345 if (!HAVE_THREADS)
1346 BUG("Somebody got num_threads calculation wrong!");
1347 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
1348 && (opt.pre_context || opt.post_context ||
1349 opt.file_break || opt.funcbody))
1350 skip_first_line = 1;
1351
1352 /*
1353 * Pre-read gitmodules (if not read already) and force eager
1354 * initialization of packed_git to prevent racy lazy
1355 * reading/initialization once worker threads are started.
1356 */
1357 if (recurse_submodules)
1358 repo_read_gitmodules(the_repository, 1);
1359
1360 if (startup_info->have_repository) {
1361 struct odb_source *source;
1362
1363 odb_prepare_alternates(the_repository->objects);
1364 for (source = the_repository->objects->sources; source; source = source->next) {
1365 struct odb_source_files *files = odb_source_files_downcast(source);
1366 packfile_store_prepare(files->packed);
1367 }
1368 }
1369
1370 start_threads(&opt);
1371 } else {
1372 /*
1373 * The compiled patterns on the main path are only
1374 * used when not using threading. Otherwise
1375 * start_threads() above calls compile_grep_patterns()
1376 * for each thread.
1377 */
1378 compile_grep_patterns(&opt);
1379 }
1380
1381 if (show_in_pager && (cached || list.nr))
1382 die(_("--open-files-in-pager only works on the worktree"));
1383
1384 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1385 const char *pager = path_list.items[0].string;
1386 int len = strlen(pager);
1387
1388 if (len > 4 && is_dir_sep(pager[len - 5]))
1389 pager += len - 4;
1390
1391 if (opt.ignore_case && !strcmp("less", pager))
1392 string_list_append(&path_list, "-I");
1393
1394 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1395 struct strbuf buf = STRBUF_INIT;
1396 strbuf_addf(&buf, "+/%s%s",
1397 strcmp("less", pager) ? "" : "*",
1398 opt.pattern_list->pattern);
1399 string_list_append_nodup(&path_list,
1400 strbuf_detach(&buf, NULL));
1401 }
1402 }
1403
1404 if (!show_in_pager && !opt.status_only)
1405 setup_pager(the_repository);
1406
1407 die_for_incompatible_opt3(!use_index, "--no-index",
1408 untracked, "--untracked",
1409 cached, "--cached");
1410
1411 if (!use_index || untracked) {
1412 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
1413 hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
1414 } else if (0 <= opt_exclude) {
1415 die(_("--[no-]exclude-standard cannot be used for tracked contents"));
1416 } else if (!list.nr) {
1417 if (!cached)
1418 setup_work_tree(the_repository);
1419
1420 hit = grep_cache(&opt, &pathspec, cached);
1421 } else {
1422 if (cached)
1423 die(_("both --cached and trees are given"));
1424
1425 hit = grep_objects(&opt, &pathspec, &list);
1426 }
1427
1428 if (num_threads > 1)
1429 hit |= wait_all();
1430 if (hit && show_in_pager)
1431 run_pager(&opt, prefix);
1432
1433 ret = !hit;
1434
1435 out:
1436 clear_pathspec(&pathspec);
1437 string_list_clear(&path_list, 0);
1438 free_grep_patterns(&opt);
1439 object_array_clear(&list);
1440 free_repos();
1441 return ret;
1442 }