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