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